Compare commits
170
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
548c503e7c | ||
|
|
277444ec0a | ||
|
|
62a00d1ac3 | ||
|
|
8505538b34 | ||
|
|
a9d0874fe9 | ||
|
|
1563ebbdf9 | ||
|
|
38fac89f73 | ||
|
|
7026fc4fed | ||
|
|
d41da670fc | ||
|
|
5541ceb13d | ||
|
|
ac26cc4940 | ||
|
|
9b906bbabf | ||
|
|
9a98093e70 | ||
|
|
de05784428 | ||
|
|
f62983b08f | ||
|
|
d0eae8e43c | ||
|
|
3d2f3d12d9 | ||
|
|
0d2469f8fa | ||
|
|
124849c580 | ||
|
|
ea38743a2a | ||
|
|
5ab01c5150 | ||
|
|
ed3f3e5588 | ||
|
|
bb6959a090 | ||
|
|
d49d509451 | ||
|
|
008167268f | ||
|
|
67d7154328 | ||
|
|
4de9a4f649 | ||
|
|
d35bdc64b9 | ||
|
|
3a768be488 | ||
|
|
1965c984f4 | ||
|
|
e3e1700de5 | ||
|
|
f05d766b64 | ||
|
|
58e414041a | ||
|
|
cd5056d4c9 | ||
|
|
39fb821481 | ||
|
|
beb87a8c43 | ||
|
|
4327fc939c | ||
|
|
ef1046c6f5 | ||
|
|
ef8cf719f2 | ||
|
|
6aa6b32a6c | ||
|
|
33dff04d47 | ||
|
|
65d697b7be | ||
|
|
06fc42ed37 | ||
|
|
3c5c567077 | ||
|
|
8f65e550c8 | ||
|
|
6b83879741 | ||
|
|
be265e9cc0 | ||
|
|
680c36ab59 | ||
|
|
96b4f65cd1 | ||
|
|
b1a897e51c | ||
|
|
e5a34efee9 | ||
|
|
f9ac4e4dbf | ||
|
|
1b40e29f40 | ||
|
|
7eba1fb487 | ||
|
|
838083b909 | ||
|
|
8f5eb36b5f | ||
|
|
b7d1bcce3d | ||
|
|
03d3173ca6 | ||
|
|
38a61d7b50 | ||
|
|
0a429e1f7b | ||
|
|
857ba953e3 | ||
|
|
e180018c99 | ||
|
|
ac9956bf00 | ||
|
|
62b5a8bf65 | ||
|
|
303efefcb7 | ||
|
|
feeb7c2d92 | ||
|
|
ea9a54421a | ||
|
|
fdf99b2bb0 | ||
|
|
c7cd641f89 | ||
|
|
18b90c8df3 | ||
|
|
8d3bc1c2e2 | ||
|
|
079d988034 | ||
|
|
aa9d388337 | ||
|
|
92bd3d9a47 | ||
|
|
53058d1504 | ||
|
|
3fe8463a03 | ||
|
|
5c4ce5d727 | ||
|
|
459193e7b1 | ||
|
|
98f21323fb | ||
|
|
515248d438 | ||
|
|
b0c69ad3e0 | ||
|
|
c5f29ab4ae | ||
|
|
876ee898d8 | ||
|
|
e93bab6ea7 | ||
|
|
5225090490 | ||
|
|
e9532e8878 | ||
|
|
23b1cb2966 | ||
|
|
fa909e2e7d | ||
|
|
7fa9ce81bd | ||
|
|
8490911958 | ||
|
|
19d899b277 | ||
|
|
37ec8b614e | ||
|
|
e045371969 | ||
|
|
cd5383432e | ||
|
|
8b8baa27b3 | ||
|
|
386fa3ef0c | ||
|
|
19c96fd00f | ||
|
|
ecb35fb869 | ||
|
|
21cda0072a | ||
|
|
e3858e8bc3 | ||
|
|
f08a331bc6 | ||
|
|
cfcaa926cd | ||
|
|
8ade34af0a | ||
|
|
a6d37c92d2 | ||
|
|
1b7b8091a3 | ||
|
|
94e5ebf577 | ||
|
|
cf302e8334 | ||
|
|
82c7752266 | ||
|
|
c676c8263f | ||
|
|
f6b2375d65 | ||
|
|
d1a065fec8 | ||
|
|
f686ecf947 | ||
|
|
6ac1f318d0 | ||
|
|
cbaf664123 | ||
|
|
470e653da6 | ||
|
|
43d3d8f7f3 | ||
|
|
83c0c9944d | ||
|
|
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 |
No files matched your search
+50
-13
@@ -1,40 +1,76 @@
|
|||||||
"""
|
"""
|
||||||
FILE: app/config.py
|
FILE: app/config.py
|
||||||
DESCRIPTION: Zentrale Pydantic-Konfiguration (Env-Vars für Qdrant, LLM, Retriever).
|
DESCRIPTION: Zentrale Pydantic-Konfiguration.
|
||||||
VERSION: 0.4.0
|
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
|
STATUS: Active
|
||||||
DEPENDENCIES: os, functools, pathlib
|
DEPENDENCIES: os, functools, pathlib, python-dotenv
|
||||||
LAST_ANALYSIS: 2025-12-15
|
|
||||||
"""
|
"""
|
||||||
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()
|
||||||
|
# Standardwert 10000, falls nichts in der .env steht
|
||||||
|
MAX_OLLAMA_CHARS: int = int(os.getenv("MAX_OLLAMA_CHARS", 10000))
|
||||||
|
|
||||||
|
# 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"))
|
||||||
@@ -44,4 +80,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,176 +0,0 @@
|
|||||||
"""
|
|
||||||
FILE: app/core/chunk_payload.py
|
|
||||||
DESCRIPTION: Baut das JSON-Objekt für 'mindnet_chunks'.
|
|
||||||
FEATURES:
|
|
||||||
- Inkludiert Nachbarschafts-IDs (prev/next) und Titel.
|
|
||||||
- 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 typing import Any, Dict, List, Optional
|
|
||||||
import os, yaml
|
|
||||||
|
|
||||||
def _env(n: str, d: Optional[str]=None) -> str:
|
|
||||||
v = os.getenv(n)
|
|
||||||
return v if v is not None else (d or "")
|
|
||||||
|
|
||||||
def _load_types() -> dict:
|
|
||||||
p = _env("MINDNET_TYPES_FILE", "./config/types.yaml")
|
|
||||||
try:
|
|
||||||
with open(p, "r", encoding="utf-8") as f:
|
|
||||||
return yaml.safe_load(f) or {}
|
|
||||||
except Exception:
|
|
||||||
return {}
|
|
||||||
|
|
||||||
def _get_types_map(reg: dict) -> dict:
|
|
||||||
if isinstance(reg, dict) and isinstance(reg.get("types"), dict):
|
|
||||||
return reg["types"]
|
|
||||||
return reg if isinstance(reg, dict) else {}
|
|
||||||
|
|
||||||
def _get_defaults(reg: dict) -> dict:
|
|
||||||
if isinstance(reg, dict) and isinstance(reg.get("defaults"), dict):
|
|
||||||
return reg["defaults"]
|
|
||||||
if isinstance(reg, dict) and isinstance(reg.get("global"), dict):
|
|
||||||
return reg["global"]
|
|
||||||
return {}
|
|
||||||
|
|
||||||
def _as_float(x: Any):
|
|
||||||
try: return float(x)
|
|
||||||
except Exception: return None
|
|
||||||
|
|
||||||
def _resolve_chunk_profile_from_config(note_type: str, reg: dict) -> Optional[str]:
|
|
||||||
# 1. Type Level
|
|
||||||
types = _get_types_map(reg)
|
|
||||||
if isinstance(types, dict):
|
|
||||||
t = types.get(note_type, {})
|
|
||||||
if isinstance(t, dict):
|
|
||||||
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)
|
|
||||||
if isinstance(defs, dict):
|
|
||||||
cp = defs.get("chunking_profile") or defs.get("chunk_profile")
|
|
||||||
if isinstance(cp, str) and cp: return cp
|
|
||||||
return None
|
|
||||||
|
|
||||||
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)
|
|
||||||
if isinstance(types, dict):
|
|
||||||
t = types.get(note_type, {})
|
|
||||||
if isinstance(t, dict) and (t.get("retriever_weight") is not None):
|
|
||||||
v = _as_float(t.get("retriever_weight"))
|
|
||||||
if v is not None: return float(v)
|
|
||||||
|
|
||||||
# 2. Defaults Level
|
|
||||||
defs = _get_defaults(reg)
|
|
||||||
if isinstance(defs, dict) and (defs.get("retriever_weight") is not None):
|
|
||||||
v = _as_float(defs.get("retriever_weight"))
|
|
||||||
if v is not None: return float(v)
|
|
||||||
|
|
||||||
return 1.0
|
|
||||||
|
|
||||||
def _as_list(x):
|
|
||||||
if x is None: return []
|
|
||||||
if isinstance(x, list): return x
|
|
||||||
return [x]
|
|
||||||
|
|
||||||
def make_chunk_payloads(note: Dict[str, Any],
|
|
||||||
note_path: str,
|
|
||||||
chunks_from_chunker: List[Any],
|
|
||||||
*,
|
|
||||||
note_text: str = "",
|
|
||||||
types_cfg: Optional[dict] = None,
|
|
||||||
file_path: Optional[str] = None) -> List[Dict[str, Any]]:
|
|
||||||
"""
|
|
||||||
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"
|
|
||||||
|
|
||||||
# Title Extraction (Fallback Chain)
|
|
||||||
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()
|
|
||||||
|
|
||||||
# --- Profil-Ermittlung ---
|
|
||||||
# Da wir 'fm' jetzt korrekt haben, funktionieren diese lookups:
|
|
||||||
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 []
|
|
||||||
if isinstance(tags, str):
|
|
||||||
tags = [tags]
|
|
||||||
|
|
||||||
out: List[Dict[str, Any]] = []
|
|
||||||
for idx, ch in enumerate(chunks_from_chunker):
|
|
||||||
# Attribute extrahieren
|
|
||||||
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"))
|
|
||||||
index = getattr(ch, "index", None) or (ch.get("index") if isinstance(ch, dict) else idx)
|
|
||||||
text = getattr(ch, "text", None) or (ch.get("text") if isinstance(ch, dict) else "")
|
|
||||||
window = getattr(ch, "window", None) or (ch.get("window") if isinstance(ch, dict) else text)
|
|
||||||
prev_id = getattr(ch, "neighbors_prev", None) or (ch.get("neighbors_prev") if isinstance(ch, dict) else None)
|
|
||||||
next_id = getattr(ch, "neighbors_next", None) or (ch.get("neighbors_next") if isinstance(ch, dict) else None)
|
|
||||||
|
|
||||||
pl: Dict[str, Any] = {
|
|
||||||
"note_id": nid,
|
|
||||||
"chunk_id": cid,
|
|
||||||
"title": title,
|
|
||||||
"index": int(index),
|
|
||||||
"ord": int(index) + 1,
|
|
||||||
"type": note_type,
|
|
||||||
"tags": tags,
|
|
||||||
"text": text,
|
|
||||||
"window": window,
|
|
||||||
"neighbors_prev": _as_list(prev_id),
|
|
||||||
"neighbors_next": _as_list(next_id),
|
|
||||||
"section": getattr(ch, "section", None) or (ch.get("section") if isinstance(ch, dict) else ""),
|
|
||||||
"path": note_path,
|
|
||||||
"source_path": file_path or note_path,
|
|
||||||
"retriever_weight": float(rw),
|
|
||||||
"chunk_profile": cp, # Jetzt endlich mit dem Override-Wert!
|
|
||||||
}
|
|
||||||
|
|
||||||
# Cleanup
|
|
||||||
for alias in ("chunk_num", "Chunk_Number"):
|
|
||||||
pl.pop(alias, None)
|
|
||||||
|
|
||||||
out.append(pl)
|
|
||||||
|
|
||||||
return out
|
|
||||||
@@ -1,424 +0,0 @@
|
|||||||
"""
|
|
||||||
FILE: app/core/chunker.py
|
|
||||||
DESCRIPTION: Zerlegt Texte in Chunks (Sliding Window oder nach Headings). Orchestriert die Smart-Edge-Allocation via SemanticAnalyzer.
|
|
||||||
VERSION: 2.9.0 (Feat: Hybrid Strict Splitting with Size Safety)
|
|
||||||
STATUS: Active
|
|
||||||
DEPENDENCIES: app.services.semantic_analyzer, app.core.derive_edges, markdown_it, yaml, asyncio
|
|
||||||
EXTERNAL_CONFIG: config/types.yaml
|
|
||||||
LAST_ANALYSIS: 2025-12-16
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
from dataclasses import dataclass
|
|
||||||
from typing import List, Dict, Optional, Tuple, Any, Set
|
|
||||||
import re
|
|
||||||
import math
|
|
||||||
import yaml
|
|
||||||
from pathlib import Path
|
|
||||||
import asyncio
|
|
||||||
import logging
|
|
||||||
|
|
||||||
# Services
|
|
||||||
from app.services.semantic_analyzer import get_semantic_analyzer
|
|
||||||
|
|
||||||
# Core Imports
|
|
||||||
try:
|
|
||||||
from app.core.derive_edges import build_edges_for_note
|
|
||||||
except ImportError:
|
|
||||||
# Mock für Tests
|
|
||||||
def build_edges_for_note(note_id, chunks, note_level_references=None, include_note_scope_refs=False): return []
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
# ==========================================
|
|
||||||
# 1. HELPER & CONFIG
|
|
||||||
# ==========================================
|
|
||||||
|
|
||||||
BASE_DIR = Path(__file__).resolve().parent.parent.parent
|
|
||||||
CONFIG_PATH = BASE_DIR / "config" / "types.yaml"
|
|
||||||
DEFAULT_PROFILE = {"strategy": "sliding_window", "target": 400, "max": 600, "overlap": (50, 80)}
|
|
||||||
_CONFIG_CACHE = None
|
|
||||||
|
|
||||||
def _load_yaml_config() -> Dict[str, Any]:
|
|
||||||
global _CONFIG_CACHE
|
|
||||||
if _CONFIG_CACHE is not None: return _CONFIG_CACHE
|
|
||||||
if not CONFIG_PATH.exists(): return {}
|
|
||||||
try:
|
|
||||||
with open(CONFIG_PATH, "r", encoding="utf-8") as f:
|
|
||||||
data = yaml.safe_load(f)
|
|
||||||
_CONFIG_CACHE = data
|
|
||||||
return data
|
|
||||||
except Exception: return {}
|
|
||||||
|
|
||||||
def get_chunk_config(note_type: str) -> Dict[str, Any]:
|
|
||||||
full_config = _load_yaml_config()
|
|
||||||
profiles = full_config.get("chunking_profiles", {})
|
|
||||||
type_def = full_config.get("types", {}).get(note_type.lower(), {})
|
|
||||||
profile_name = type_def.get("chunking_profile")
|
|
||||||
if not profile_name:
|
|
||||||
profile_name = full_config.get("defaults", {}).get("chunking_profile", "sliding_standard")
|
|
||||||
|
|
||||||
config = profiles.get(profile_name, DEFAULT_PROFILE).copy()
|
|
||||||
if "overlap" in config and isinstance(config["overlap"], list):
|
|
||||||
config["overlap"] = tuple(config["overlap"])
|
|
||||||
return config
|
|
||||||
|
|
||||||
def extract_frontmatter_from_text(md_text: str) -> Tuple[Dict[str, Any], str]:
|
|
||||||
fm_match = re.match(r'^\s*---\s*\n(.*?)\n---', md_text, re.DOTALL)
|
|
||||||
if not fm_match: return {}, md_text
|
|
||||||
try:
|
|
||||||
frontmatter = yaml.safe_load(fm_match.group(1))
|
|
||||||
if not isinstance(frontmatter, dict): frontmatter = {}
|
|
||||||
except yaml.YAMLError:
|
|
||||||
frontmatter = {}
|
|
||||||
text_without_fm = re.sub(r'^\s*---\s*\n(.*?)\n---', '', md_text, flags=re.DOTALL)
|
|
||||||
return frontmatter, text_without_fm.strip()
|
|
||||||
|
|
||||||
# ==========================================
|
|
||||||
# 2. DATA CLASSES
|
|
||||||
# ==========================================
|
|
||||||
|
|
||||||
_SENT_SPLIT = re.compile(r'(?<=[.!?])\s+(?=[A-ZÄÖÜ0-9„(])'); _WS = re.compile(r'\s+')
|
|
||||||
|
|
||||||
def estimate_tokens(text: str) -> int:
|
|
||||||
return max(1, math.ceil(len(text.strip()) / 4))
|
|
||||||
|
|
||||||
def split_sentences(text: str) -> list[str]:
|
|
||||||
text = _WS.sub(' ', text.strip())
|
|
||||||
if not text: return []
|
|
||||||
parts = _SENT_SPLIT.split(text)
|
|
||||||
return [p.strip() for p in parts if p.strip()]
|
|
||||||
|
|
||||||
@dataclass
|
|
||||||
class RawBlock:
|
|
||||||
kind: str; text: str; level: Optional[int]; section_path: str; section_title: Optional[str]
|
|
||||||
|
|
||||||
@dataclass
|
|
||||||
class Chunk:
|
|
||||||
id: str; note_id: str; index: int; text: str; window: str; token_count: int
|
|
||||||
section_title: Optional[str]; section_path: str
|
|
||||||
neighbors_prev: Optional[str]; neighbors_next: Optional[str]
|
|
||||||
suggested_edges: Optional[List[str]] = None
|
|
||||||
|
|
||||||
# ==========================================
|
|
||||||
# 3. PARSING & STRATEGIES
|
|
||||||
# ==========================================
|
|
||||||
|
|
||||||
def parse_blocks(md_text: str) -> Tuple[List[RawBlock], str]:
|
|
||||||
"""Zerlegt Text in logische Blöcke (Absätze, Header)."""
|
|
||||||
blocks = []
|
|
||||||
h1_title = "Dokument"
|
|
||||||
section_path = "/"
|
|
||||||
current_h2 = None
|
|
||||||
|
|
||||||
fm, text_without_fm = extract_frontmatter_from_text(md_text)
|
|
||||||
|
|
||||||
h1_match = re.search(r'^#\s+(.*)', text_without_fm, re.MULTILINE)
|
|
||||||
if h1_match:
|
|
||||||
h1_title = h1_match.group(1).strip()
|
|
||||||
|
|
||||||
lines = text_without_fm.split('\n')
|
|
||||||
buffer = []
|
|
||||||
|
|
||||||
for line in lines:
|
|
||||||
stripped = line.strip()
|
|
||||||
if stripped.startswith('# '):
|
|
||||||
if buffer:
|
|
||||||
content = "\n".join(buffer).strip()
|
|
||||||
if content:
|
|
||||||
blocks.append(RawBlock("paragraph", content, None, section_path, current_h2))
|
|
||||||
buffer = []
|
|
||||||
blocks.append(RawBlock("heading", stripped, 1, section_path, current_h2))
|
|
||||||
|
|
||||||
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 stripped.startswith('### '):
|
|
||||||
if buffer:
|
|
||||||
content = "\n".join(buffer).strip()
|
|
||||||
if content:
|
|
||||||
blocks.append(RawBlock("paragraph", content, None, section_path, current_h2))
|
|
||||||
buffer = []
|
|
||||||
blocks.append(RawBlock("heading", stripped, 3, 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:
|
|
||||||
buffer.append(line)
|
|
||||||
|
|
||||||
if buffer:
|
|
||||||
content = "\n".join(buffer).strip()
|
|
||||||
if content:
|
|
||||||
blocks.append(RawBlock("paragraph", content, None, section_path, current_h2))
|
|
||||||
|
|
||||||
return blocks, h1_title
|
|
||||||
|
|
||||||
def _create_chunk_obj(chunks_list: List[Chunk], note_id: str, txt: str, win: str, sec: Optional[str], path: str):
|
|
||||||
idx = len(chunks_list)
|
|
||||||
chunks_list.append(Chunk(
|
|
||||||
id=f"{note_id}#c{idx:02d}", note_id=note_id, index=idx,
|
|
||||||
text=txt, window=win, token_count=estimate_tokens(txt),
|
|
||||||
section_title=sec, section_path=path, neighbors_prev=None, neighbors_next=None,
|
|
||||||
suggested_edges=[]
|
|
||||||
))
|
|
||||||
|
|
||||||
def _strategy_sliding_window(blocks: List[RawBlock], config: Dict[str, Any], note_id: str, doc_title: str = "", context_prefix: str = "") -> List[Chunk]:
|
|
||||||
target = config.get("target", 400)
|
|
||||||
max_tokens = config.get("max", 600)
|
|
||||||
overlap_val = config.get("overlap", (50, 80))
|
|
||||||
overlap = sum(overlap_val) // 2 if isinstance(overlap_val, tuple) else overlap_val
|
|
||||||
chunks = []; buf = []
|
|
||||||
|
|
||||||
def flush_buffer():
|
|
||||||
nonlocal buf
|
|
||||||
if not buf: return
|
|
||||||
|
|
||||||
text_body = "\n\n".join([b.text for b in buf])
|
|
||||||
win_body = f"{context_prefix}\n{text_body}".strip() if context_prefix else text_body
|
|
||||||
|
|
||||||
# Basis-Info vom ersten Block im Buffer
|
|
||||||
sec = buf[0].section_title if buf else None
|
|
||||||
path = buf[0].section_path if buf else "/"
|
|
||||||
|
|
||||||
if estimate_tokens(text_body) <= max_tokens:
|
|
||||||
_create_chunk_obj(chunks, note_id, text_body, win_body, sec, path)
|
|
||||||
else:
|
|
||||||
# Fallback: Wenn Block zu groß, intern splitten (Sentence-Level)
|
|
||||||
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_obj(chunks, note_id, c_txt, c_win, sec, path)
|
|
||||||
|
|
||||||
overlap_sents = []
|
|
||||||
ov_len = 0
|
|
||||||
for s in reversed(current_chunk_sents):
|
|
||||||
if ov_len + estimate_tokens(s) < overlap:
|
|
||||||
overlap_sents.insert(0, s)
|
|
||||||
ov_len += estimate_tokens(s)
|
|
||||||
else:
|
|
||||||
break
|
|
||||||
|
|
||||||
current_chunk_sents = list(overlap_sents)
|
|
||||||
current_chunk_sents.append(sent)
|
|
||||||
current_len = ov_len + sent_len
|
|
||||||
else:
|
|
||||||
current_chunk_sents.append(sent)
|
|
||||||
current_len += sent_len
|
|
||||||
|
|
||||||
if current_chunk_sents:
|
|
||||||
c_txt = " ".join(current_chunk_sents)
|
|
||||||
c_win = f"{context_prefix}\n{c_txt}".strip() if context_prefix else c_txt
|
|
||||||
_create_chunk_obj(chunks, note_id, c_txt, c_win, sec, path)
|
|
||||||
|
|
||||||
buf = []
|
|
||||||
|
|
||||||
for b in blocks:
|
|
||||||
if b.kind == "heading":
|
|
||||||
flush_buffer()
|
|
||||||
|
|
||||||
current_buf_text = "\n\n".join([x.text for x in buf])
|
|
||||||
if buf and (estimate_tokens(current_buf_text) + estimate_tokens(b.text) >= target):
|
|
||||||
flush_buffer()
|
|
||||||
|
|
||||||
buf.append(b)
|
|
||||||
|
|
||||||
flush_buffer()
|
|
||||||
return chunks
|
|
||||||
|
|
||||||
def _strategy_by_heading(blocks: List[RawBlock], config: Dict[str, Any], note_id: str, doc_title: str = "") -> List[Chunk]:
|
|
||||||
"""
|
|
||||||
MODUS: Structured / Heading Split
|
|
||||||
- split_level: Ebene für logische Trennung (z.B. H2).
|
|
||||||
- strict_heading_split:
|
|
||||||
True: Trennt an jedem Header <= split_level.
|
|
||||||
NEU v2.9: Wenn Inhalt > max_tokens, wird trotzdem gesplittet (Safety Split).
|
|
||||||
False: Fasst zusammen bis 'target' erreicht ist.
|
|
||||||
"""
|
|
||||||
split_level = config.get("split_level", 2)
|
|
||||||
target = config.get("target", 400)
|
|
||||||
max_limit = config.get("max", 600)
|
|
||||||
strict_mode = config.get("strict_heading_split", False)
|
|
||||||
|
|
||||||
chunks = []
|
|
||||||
current_chunk_blocks = []
|
|
||||||
|
|
||||||
context_prefix = f"# {doc_title}"
|
|
||||||
|
|
||||||
def has_content(blk_list):
|
|
||||||
return any(b.kind != "heading" for b in blk_list)
|
|
||||||
|
|
||||||
def flush_current_chunk():
|
|
||||||
nonlocal current_chunk_blocks
|
|
||||||
if not current_chunk_blocks:
|
|
||||||
return
|
|
||||||
|
|
||||||
text_body = "\n\n".join([b.text for b in current_chunk_blocks])
|
|
||||||
win_body = f"{context_prefix}\n{text_body}".strip()
|
|
||||||
|
|
||||||
first_b = current_chunk_blocks[0]
|
|
||||||
sec = first_b.section_title
|
|
||||||
path = first_b.section_path
|
|
||||||
|
|
||||||
_create_chunk_obj(chunks, note_id, text_body, win_body, sec, path)
|
|
||||||
current_chunk_blocks = []
|
|
||||||
|
|
||||||
def get_current_size():
|
|
||||||
txt = "\n\n".join([b.text for b in current_chunk_blocks])
|
|
||||||
return estimate_tokens(txt)
|
|
||||||
|
|
||||||
for b in blocks:
|
|
||||||
# 1. Header Logic (Struktur-Trigger)
|
|
||||||
is_splitter = (b.kind == "heading" and b.level is not None and b.level <= split_level)
|
|
||||||
|
|
||||||
if is_splitter:
|
|
||||||
is_higher_hierarchy = (b.level < split_level)
|
|
||||||
|
|
||||||
if strict_mode:
|
|
||||||
# STRICT:
|
|
||||||
# Wir splitten immer, außer der Vor-Chunk ist leer.
|
|
||||||
if current_chunk_blocks and has_content(current_chunk_blocks):
|
|
||||||
flush_current_chunk()
|
|
||||||
current_chunk_blocks.append(b)
|
|
||||||
else:
|
|
||||||
# SOFT:
|
|
||||||
# Split bei Hierarchie-Wechsel ODER wenn voll.
|
|
||||||
if is_higher_hierarchy:
|
|
||||||
flush_current_chunk()
|
|
||||||
current_chunk_blocks.append(b)
|
|
||||||
elif current_chunk_blocks and get_current_size() >= target:
|
|
||||||
flush_current_chunk()
|
|
||||||
current_chunk_blocks.append(b)
|
|
||||||
else:
|
|
||||||
current_chunk_blocks.append(b)
|
|
||||||
else:
|
|
||||||
# 2. Content Logic (Safety Trigger für Monster-Abschnitte)
|
|
||||||
# Bevor wir den Block anhängen: Würde er das Fass zum Überlaufen bringen?
|
|
||||||
# Wir nutzen hier 'max' als harte Grenze für den Safety-Split.
|
|
||||||
current_size = get_current_size()
|
|
||||||
block_size = estimate_tokens(b.text)
|
|
||||||
|
|
||||||
if current_chunk_blocks and (current_size + block_size > max_limit):
|
|
||||||
# NOTBREMSE: Chunk wird zu groß.
|
|
||||||
# Wir splitten hier, auch wenn kein Header da ist.
|
|
||||||
# Der Kontext (Section Title) bleibt erhalten, da er aus `current_h2` kommt (siehe parse_blocks).
|
|
||||||
flush_current_chunk()
|
|
||||||
current_chunk_blocks.append(b)
|
|
||||||
else:
|
|
||||||
current_chunk_blocks.append(b)
|
|
||||||
|
|
||||||
# Letzten Rest flushen
|
|
||||||
flush_current_chunk()
|
|
||||||
|
|
||||||
return chunks
|
|
||||||
|
|
||||||
# ==========================================
|
|
||||||
# 4. ORCHESTRATION (ASYNC)
|
|
||||||
# ==========================================
|
|
||||||
|
|
||||||
async def assemble_chunks(note_id: str, md_text: str, note_type: str, config: Optional[Dict] = None) -> List[Chunk]:
|
|
||||||
if config is None:
|
|
||||||
config = get_chunk_config(note_type)
|
|
||||||
|
|
||||||
fm, body_text = extract_frontmatter_from_text(md_text)
|
|
||||||
note_status = fm.get("status", "").lower()
|
|
||||||
|
|
||||||
primary_strategy = config.get("strategy", "sliding_window")
|
|
||||||
enable_smart_edges = config.get("enable_smart_edge_allocation", False)
|
|
||||||
|
|
||||||
if enable_smart_edges and note_status in ["draft", "initial_gen"]:
|
|
||||||
logger.info(f"Chunker: Skipping Smart Edges for draft '{note_id}'.")
|
|
||||||
enable_smart_edges = False
|
|
||||||
|
|
||||||
blocks, doc_title = parse_blocks(md_text)
|
|
||||||
|
|
||||||
if primary_strategy == "by_heading":
|
|
||||||
chunks = await asyncio.to_thread(_strategy_by_heading, blocks, config, note_id, doc_title)
|
|
||||||
else:
|
|
||||||
chunks = await asyncio.to_thread(_strategy_sliding_window, blocks, config, note_id, doc_title)
|
|
||||||
|
|
||||||
if not chunks:
|
|
||||||
return []
|
|
||||||
|
|
||||||
if enable_smart_edges:
|
|
||||||
chunks = await _run_smart_edge_allocation(chunks, md_text, note_id, note_type)
|
|
||||||
|
|
||||||
for i, ch in enumerate(chunks):
|
|
||||||
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
|
|
||||||
|
|
||||||
return chunks
|
|
||||||
|
|
||||||
def _extract_all_edges_from_md(md_text: str, note_id: str, note_type: str) -> List[str]:
|
|
||||||
dummy_chunk = {
|
|
||||||
"chunk_id": f"{note_id}#full",
|
|
||||||
"text": md_text,
|
|
||||||
"content": md_text,
|
|
||||||
"window": md_text,
|
|
||||||
"type": note_type
|
|
||||||
}
|
|
||||||
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}")
|
|
||||||
return list(all_candidates)
|
|
||||||
|
|
||||||
async def _run_smart_edge_allocation(chunks: List[Chunk], full_text: str, note_id: str, note_type: str) -> List[Chunk]:
|
|
||||||
analyzer = get_semantic_analyzer()
|
|
||||||
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:
|
|
||||||
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
|
|
||||||
|
|
||||||
unassigned = set(candidate_list) - assigned_edges_global
|
|
||||||
if unassigned:
|
|
||||||
fallback_str = "\n" + " ".join([f"[[rel:{e.split(':')[0]}|{e.split(':')[1]}]]" for e in unassigned if ':' in e])
|
|
||||||
for chunk in chunks:
|
|
||||||
chunk.text += fallback_str
|
|
||||||
chunk.window += fallback_str
|
|
||||||
if chunk.suggested_edges is None: chunk.suggested_edges = []
|
|
||||||
chunk.suggested_edges.extend(list(unassigned))
|
|
||||||
|
|
||||||
return chunks
|
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
"""
|
||||||
|
FILE: app/core/chunking/__init__.py
|
||||||
|
DESCRIPTION: Package-Einstiegspunkt für Chunking. Exportiert assemble_chunks.
|
||||||
|
VERSION: 3.3.0
|
||||||
|
"""
|
||||||
|
from .chunking_processor import assemble_chunks
|
||||||
|
from .chunking_utils import get_chunk_config, extract_frontmatter_from_text
|
||||||
|
from .chunking_models import Chunk
|
||||||
|
|
||||||
|
__all__ = ["assemble_chunks", "get_chunk_config", "extract_frontmatter_from_text", "Chunk"]
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
"""
|
||||||
|
FILE: app/core/chunking/chunking_models.py
|
||||||
|
DESCRIPTION: Datenklassen für das Chunking-System.
|
||||||
|
"""
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from typing import List, Dict, Optional, Any
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class RawBlock:
|
||||||
|
"""Repräsentiert einen logischen Block aus dem Markdown-Parsing."""
|
||||||
|
kind: str
|
||||||
|
text: str
|
||||||
|
level: Optional[int]
|
||||||
|
section_path: str
|
||||||
|
section_title: Optional[str]
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class Chunk:
|
||||||
|
"""Das finale Chunk-Objekt für Embedding und Graph-Speicherung."""
|
||||||
|
id: str
|
||||||
|
note_id: str
|
||||||
|
index: int
|
||||||
|
text: str
|
||||||
|
window: str
|
||||||
|
token_count: int
|
||||||
|
section_title: Optional[str]
|
||||||
|
section_path: str
|
||||||
|
neighbors_prev: Optional[str]
|
||||||
|
neighbors_next: Optional[str]
|
||||||
|
candidate_pool: List[Dict[str, Any]] = field(default_factory=list)
|
||||||
|
suggested_edges: Optional[List[str]] = None
|
||||||
@@ -0,0 +1,115 @@
|
|||||||
|
"""
|
||||||
|
FILE: app/core/chunking/chunking_parser.py
|
||||||
|
DESCRIPTION: Zerlegt Markdown in logische Einheiten (RawBlocks).
|
||||||
|
Hält alle Überschriftenebenen (H1-H6) im Stream.
|
||||||
|
Stellt die Funktion parse_edges_robust zur Verfügung.
|
||||||
|
"""
|
||||||
|
import re
|
||||||
|
from typing import List, Tuple, Set
|
||||||
|
from .chunking_models import RawBlock
|
||||||
|
from .chunking_utils import extract_frontmatter_from_text
|
||||||
|
|
||||||
|
_WS = re.compile(r'\s+')
|
||||||
|
_SENT_SPLIT = re.compile(r'(?<=[.!?])\s+(?=[A-ZÄÖÜ0-9„(])')
|
||||||
|
|
||||||
|
def split_sentences(text: str) -> list[str]:
|
||||||
|
"""Teilt Text in Sätze auf unter Berücksichtigung deutscher Interpunktion."""
|
||||||
|
text = _WS.sub(' ', text.strip())
|
||||||
|
if not text: return []
|
||||||
|
# Splittet bei Punkt, Ausrufezeichen oder Fragezeichen, gefolgt von Leerzeichen und Großbuchstabe
|
||||||
|
return [p.strip() for p in _SENT_SPLIT.split(text) if p.strip()]
|
||||||
|
|
||||||
|
def parse_blocks(md_text: str) -> Tuple[List[RawBlock], str]:
|
||||||
|
"""Zerlegt Text in logische Einheiten (RawBlocks), inklusive H1-H6."""
|
||||||
|
blocks = []
|
||||||
|
h1_title = "Dokument"
|
||||||
|
section_path = "/"
|
||||||
|
current_section_title = None
|
||||||
|
|
||||||
|
# Frontmatter entfernen
|
||||||
|
fm, text_without_fm = extract_frontmatter_from_text(md_text)
|
||||||
|
|
||||||
|
# H1 für Note-Titel extrahieren (Metadaten-Zweck)
|
||||||
|
h1_match = re.search(r'^#\s+(.*)', text_without_fm, re.MULTILINE)
|
||||||
|
if h1_match:
|
||||||
|
h1_title = h1_match.group(1).strip()
|
||||||
|
|
||||||
|
lines = text_without_fm.split('\n')
|
||||||
|
buffer = []
|
||||||
|
|
||||||
|
for line in lines:
|
||||||
|
stripped = line.strip()
|
||||||
|
|
||||||
|
# Heading-Erkennung (H1 bis H6)
|
||||||
|
heading_match = re.match(r'^(#{1,6})\s+(.*)', stripped)
|
||||||
|
if heading_match:
|
||||||
|
# Vorherigen Text-Block abschließen
|
||||||
|
if buffer:
|
||||||
|
content = "\n".join(buffer).strip()
|
||||||
|
if content:
|
||||||
|
blocks.append(RawBlock("paragraph", content, None, section_path, current_section_title))
|
||||||
|
buffer = []
|
||||||
|
|
||||||
|
level = len(heading_match.group(1))
|
||||||
|
title = heading_match.group(2).strip()
|
||||||
|
|
||||||
|
# Pfad- und Titel-Update für die Metadaten der folgenden Blöcke
|
||||||
|
if level == 1:
|
||||||
|
current_section_title = title; section_path = "/"
|
||||||
|
elif level == 2:
|
||||||
|
current_section_title = title; section_path = f"/{current_section_title}"
|
||||||
|
|
||||||
|
# Die Überschrift selbst als regulären Block hinzufügen
|
||||||
|
blocks.append(RawBlock("heading", stripped, level, section_path, current_section_title))
|
||||||
|
continue
|
||||||
|
|
||||||
|
# Trenner (---) oder Leerzeilen beenden Blöcke, außer innerhalb von Callouts
|
||||||
|
if (not stripped or stripped == "---") and not line.startswith('>'):
|
||||||
|
if buffer:
|
||||||
|
content = "\n".join(buffer).strip()
|
||||||
|
if content:
|
||||||
|
blocks.append(RawBlock("paragraph", content, None, section_path, current_section_title))
|
||||||
|
buffer = []
|
||||||
|
if stripped == "---":
|
||||||
|
blocks.append(RawBlock("separator", "---", None, section_path, current_section_title))
|
||||||
|
else:
|
||||||
|
buffer.append(line)
|
||||||
|
|
||||||
|
if buffer:
|
||||||
|
content = "\n".join(buffer).strip()
|
||||||
|
if content:
|
||||||
|
blocks.append(RawBlock("paragraph", content, None, section_path, current_section_title))
|
||||||
|
|
||||||
|
return blocks, h1_title
|
||||||
|
|
||||||
|
def parse_edges_robust(text: str) -> Set[str]:
|
||||||
|
"""Extrahiert Kanten-Kandidaten aus Wikilinks und Callouts."""
|
||||||
|
found_edges = set()
|
||||||
|
# 1. Wikilinks [[rel:kind|target]]
|
||||||
|
inlines = re.findall(r'\[\[rel:([^\|\]]+)\|?([^\]]*)\]\]', text)
|
||||||
|
for kind, target in inlines:
|
||||||
|
k = kind.strip().lower()
|
||||||
|
t = target.strip()
|
||||||
|
if k and t: found_edges.add(f"{k}:{t}")
|
||||||
|
|
||||||
|
# 2. Callout Edges > [!edge] kind
|
||||||
|
lines = text.split('\n')
|
||||||
|
current_edge_type = None
|
||||||
|
for line in lines:
|
||||||
|
stripped = line.strip()
|
||||||
|
callout_match = re.match(r'>\s*\[!edge\]\s*([^:\s]+)', stripped)
|
||||||
|
if callout_match:
|
||||||
|
current_edge_type = callout_match.group(1).strip().lower()
|
||||||
|
# Links in der gleichen Zeile des Callouts
|
||||||
|
links = re.findall(r'\[\[([^\]]+)\]\]', stripped)
|
||||||
|
for l in links:
|
||||||
|
if "rel:" not in l: found_edges.add(f"{current_edge_type}:{l}")
|
||||||
|
continue
|
||||||
|
# Links in Folgezeilen des Callouts
|
||||||
|
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}")
|
||||||
|
elif not stripped.startswith('>'):
|
||||||
|
current_edge_type = None
|
||||||
|
return found_edges
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
"""
|
||||||
|
FILE: app/core/chunking/chunking_processor.py
|
||||||
|
DESCRIPTION: Der zentrale Orchestrator für das Chunking-System.
|
||||||
|
AUDIT v3.3.4: Wiederherstellung der "Gold-Standard" Qualität.
|
||||||
|
- Fix: Synchronisierung der Parameter (context_prefix) für alle Strategien.
|
||||||
|
- Integriert physikalische Kanten-Injektion (Propagierung).
|
||||||
|
- Stellt H1-Kontext-Fenster sicher.
|
||||||
|
- Baut den Candidate-Pool für die WP-15b Ingestion auf.
|
||||||
|
"""
|
||||||
|
import asyncio
|
||||||
|
import re
|
||||||
|
import logging
|
||||||
|
from typing import List, Dict, Optional
|
||||||
|
from .chunking_models import Chunk
|
||||||
|
from .chunking_utils import get_chunk_config, extract_frontmatter_from_text
|
||||||
|
from .chunking_parser import parse_blocks, parse_edges_robust
|
||||||
|
from .chunking_strategies import strategy_sliding_window, strategy_by_heading
|
||||||
|
from .chunking_propagation import propagate_section_edges
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
async def assemble_chunks(note_id: str, md_text: str, note_type: str, config: Optional[Dict] = None) -> List[Chunk]:
|
||||||
|
"""
|
||||||
|
Hauptfunktion zur Zerlegung einer Note.
|
||||||
|
Verbindet Strategien mit physikalischer Kontext-Anreicherung.
|
||||||
|
"""
|
||||||
|
# 1. Konfiguration & Parsing
|
||||||
|
if config is None:
|
||||||
|
config = get_chunk_config(note_type)
|
||||||
|
|
||||||
|
fm, body_text = extract_frontmatter_from_text(md_text)
|
||||||
|
blocks, doc_title = parse_blocks(md_text)
|
||||||
|
|
||||||
|
# Vorbereitung des H1-Präfix für die Embedding-Fenster (Breadcrumbs)
|
||||||
|
h1_prefix = f"# {doc_title}" if doc_title else ""
|
||||||
|
|
||||||
|
# 2. Anwendung der Splitting-Strategie
|
||||||
|
# Alle Strategien nutzen nun einheitlich context_prefix für die Window-Bildung.
|
||||||
|
if config.get("strategy") == "by_heading":
|
||||||
|
chunks = await asyncio.to_thread(
|
||||||
|
strategy_by_heading, blocks, config, note_id, context_prefix=h1_prefix
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
chunks = await asyncio.to_thread(
|
||||||
|
strategy_sliding_window, blocks, config, note_id, context_prefix=h1_prefix
|
||||||
|
)
|
||||||
|
|
||||||
|
if not chunks:
|
||||||
|
return []
|
||||||
|
|
||||||
|
# 3. Physikalische Kontext-Anreicherung (Der Qualitäts-Fix)
|
||||||
|
# Schreibt Kanten aus Callouts/Inlines hart in den Text für Qdrant.
|
||||||
|
chunks = propagate_section_edges(chunks)
|
||||||
|
|
||||||
|
# 4. WP-15b: Candidate Pool Aufbau (Metadaten für IngestionService)
|
||||||
|
# Zuerst die explizit im Text vorhandenen Kanten sammeln.
|
||||||
|
for ch in chunks:
|
||||||
|
# Wir extrahieren aus dem bereits (durch Propagation) angereicherten Text.
|
||||||
|
# ch.candidate_pool wird im Modell-Konstruktor als leere Liste initialisiert.
|
||||||
|
for e_str in parse_edges_robust(ch.text):
|
||||||
|
parts = e_str.split(':', 1)
|
||||||
|
if len(parts) == 2:
|
||||||
|
k, t = parts
|
||||||
|
ch.candidate_pool.append({"kind": k, "to": t, "provenance": "explicit"})
|
||||||
|
|
||||||
|
# 5. Global Pool (Unzugeordnete Kanten aus dem Dokument-Ende)
|
||||||
|
# Sucht nach dem Edge-Pool Block im Original-Markdown.
|
||||||
|
pool_match = re.search(
|
||||||
|
r'###?\s*(?:Unzugeordnete Kanten|Edge Pool|Candidates)\s*\n(.*?)(?:\n#|$)',
|
||||||
|
body_text,
|
||||||
|
re.DOTALL | re.IGNORECASE
|
||||||
|
)
|
||||||
|
if pool_match:
|
||||||
|
global_edges = parse_edges_robust(pool_match.group(1))
|
||||||
|
for e_str in global_edges:
|
||||||
|
parts = e_str.split(':', 1)
|
||||||
|
if len(parts) == 2:
|
||||||
|
k, t = parts
|
||||||
|
# Diese Kanten werden als "global_pool" markiert für die spätere KI-Prüfung.
|
||||||
|
for ch in chunks:
|
||||||
|
ch.candidate_pool.append({"kind": k, "to": t, "provenance": "global_pool"})
|
||||||
|
|
||||||
|
# 6. De-Duplikation des Pools & Linking
|
||||||
|
for ch in chunks:
|
||||||
|
seen = set()
|
||||||
|
unique = []
|
||||||
|
for c in ch.candidate_pool:
|
||||||
|
# Eindeutigkeit über Typ, Ziel und Herkunft (Provenance)
|
||||||
|
key = (c["kind"], c["to"], c["provenance"])
|
||||||
|
if key not in seen:
|
||||||
|
seen.add(key)
|
||||||
|
unique.append(c)
|
||||||
|
ch.candidate_pool = unique
|
||||||
|
|
||||||
|
# Verknüpfung der Nachbarschaften für Graph-Traversierung
|
||||||
|
for i, ch in enumerate(chunks):
|
||||||
|
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
|
||||||
|
|
||||||
|
return chunks
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
"""
|
||||||
|
FILE: app/core/chunking/chunking_propagation.py
|
||||||
|
DESCRIPTION: Injiziert Sektions-Kanten physisch in den Text (Embedding-Enrichment).
|
||||||
|
Fix v3.3.6: Nutzt robustes Parsing zur Erkennung vorhandener Kanten,
|
||||||
|
um Dopplungen direkt hinter [!edge] Callouts format-agnostisch zu verhindern.
|
||||||
|
"""
|
||||||
|
from typing import List, Dict, Set
|
||||||
|
from .chunking_models import Chunk
|
||||||
|
from .chunking_parser import parse_edges_robust
|
||||||
|
|
||||||
|
def propagate_section_edges(chunks: List[Chunk]) -> List[Chunk]:
|
||||||
|
"""
|
||||||
|
Sammelt Kanten pro Sektion und schreibt sie hart in den Text und das Window.
|
||||||
|
Verhindert Dopplungen, wenn Kanten bereits via [!edge] Callout vorhanden sind.
|
||||||
|
"""
|
||||||
|
# 1. Sammeln: Alle expliziten Kanten pro Sektions-Pfad aggregieren
|
||||||
|
section_map: Dict[str, Set[str]] = {} # path -> set(kind:target)
|
||||||
|
|
||||||
|
for ch in chunks:
|
||||||
|
# Root-Level "/" ignorieren (zu global), Fokus auf spezifische Kapitel
|
||||||
|
if not ch.section_path or ch.section_path == "/":
|
||||||
|
continue
|
||||||
|
|
||||||
|
# Nutzt den robusten Parser aus dem Package
|
||||||
|
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)
|
||||||
|
|
||||||
|
# 2. Injizieren: Kanten in jeden Chunk der Sektion zurückschreiben (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
|
||||||
|
|
||||||
|
# Vorhandene Kanten (Typ:Ziel) in DIESEM Chunk ermitteln,
|
||||||
|
# um Dopplungen (z.B. durch Callouts) zu vermeiden.
|
||||||
|
existing_edges = parse_edges_robust(ch.text)
|
||||||
|
|
||||||
|
injections = []
|
||||||
|
# Sortierung für deterministische Ergebnisse
|
||||||
|
for e_str in sorted(list(edges_to_add)):
|
||||||
|
# Wenn die Kante (Typ + Ziel) bereits vorhanden ist (egal welches Format),
|
||||||
|
# überspringen wir die Injektion für diesen Chunk.
|
||||||
|
if e_str in existing_edges:
|
||||||
|
continue
|
||||||
|
|
||||||
|
kind, target = e_str.split(':', 1)
|
||||||
|
injections.append(f"[[rel:{kind}|{target}]]")
|
||||||
|
|
||||||
|
if injections:
|
||||||
|
# Physische Anreicherung
|
||||||
|
# Triple-Newline für saubere Trennung im Embedding-Fenster
|
||||||
|
block = "\n\n\n" + " ".join(injections)
|
||||||
|
ch.text += block
|
||||||
|
|
||||||
|
# Auch ins Window schreiben, da Qdrant hier sucht!
|
||||||
|
if ch.window:
|
||||||
|
ch.window += block
|
||||||
|
else:
|
||||||
|
ch.window = ch.text
|
||||||
|
|
||||||
|
return chunks
|
||||||
@@ -0,0 +1,166 @@
|
|||||||
|
"""
|
||||||
|
FILE: app/core/chunking/chunking_strategies.py
|
||||||
|
DESCRIPTION: Strategien für atomares Sektions-Chunking v3.9.9.
|
||||||
|
Implementiert das 'Pack-and-Carry-Over' Verfahren nach Regel 1-3.
|
||||||
|
- Keine redundante Kanten-Injektion.
|
||||||
|
- Strikte Einhaltung von Sektionsgrenzen via Look-Ahead.
|
||||||
|
- Fix: Synchronisierung der Parameter mit dem Orchestrator (context_prefix).
|
||||||
|
"""
|
||||||
|
from typing import List, Dict, Any, Optional
|
||||||
|
from .chunking_models import RawBlock, Chunk
|
||||||
|
from .chunking_utils import estimate_tokens
|
||||||
|
from .chunking_parser import split_sentences
|
||||||
|
|
||||||
|
def _create_win(context_prefix: str, sec_title: Optional[str], text: str) -> str:
|
||||||
|
"""Baut den Breadcrumb-Kontext für das Embedding-Fenster."""
|
||||||
|
parts = [context_prefix] if context_prefix else []
|
||||||
|
# Verhindert Dopplung, falls der Context-Prefix (H1) bereits den Sektionsnamen enthält
|
||||||
|
if sec_title and f"# {sec_title}" != context_prefix and sec_title not in (context_prefix or ""):
|
||||||
|
parts.append(sec_title)
|
||||||
|
prefix = " > ".join(parts)
|
||||||
|
return f"{prefix}\n{text}".strip() if prefix else text
|
||||||
|
|
||||||
|
def strategy_by_heading(blocks: List[RawBlock], config: Dict[str, Any], note_id: str, context_prefix: str = "") -> List[Chunk]:
|
||||||
|
"""
|
||||||
|
Universelle Heading-Strategie mit Carry-Over Logik.
|
||||||
|
Synchronisiert auf context_prefix für Kompatibilität mit dem Orchestrator.
|
||||||
|
"""
|
||||||
|
smart_edge = config.get("enable_smart_edge_allocation", True)
|
||||||
|
strict = config.get("strict_heading_split", False)
|
||||||
|
target = config.get("target", 400)
|
||||||
|
max_tokens = config.get("max", 600)
|
||||||
|
split_level = config.get("split_level", 2)
|
||||||
|
overlap_cfg = config.get("overlap", (50, 80))
|
||||||
|
overlap = sum(overlap_cfg) // 2 if isinstance(overlap_cfg, (list, tuple)) else overlap_cfg
|
||||||
|
|
||||||
|
chunks: List[Chunk] = []
|
||||||
|
|
||||||
|
def _emit(txt, title, path):
|
||||||
|
"""Schreibt den finalen Chunk ohne Text-Modifikationen."""
|
||||||
|
idx = len(chunks)
|
||||||
|
win = _create_win(context_prefix, title, txt)
|
||||||
|
chunks.append(Chunk(
|
||||||
|
id=f"{note_id}#c{idx:02d}", note_id=note_id, index=idx,
|
||||||
|
text=txt, window=win, token_count=estimate_tokens(txt),
|
||||||
|
section_title=title, section_path=path, neighbors_prev=None, neighbors_next=None
|
||||||
|
))
|
||||||
|
|
||||||
|
# --- SCHRITT 1: Gruppierung in atomare Sektions-Einheiten ---
|
||||||
|
sections: List[Dict[str, Any]] = []
|
||||||
|
curr_blocks = []
|
||||||
|
for b in blocks:
|
||||||
|
if b.kind == "heading" and b.level <= split_level:
|
||||||
|
if curr_blocks:
|
||||||
|
sections.append({
|
||||||
|
"text": "\n\n".join([x.text for x in curr_blocks]),
|
||||||
|
"meta": curr_blocks[0],
|
||||||
|
"is_empty": len(curr_blocks) == 1 and curr_blocks[0].kind == "heading"
|
||||||
|
})
|
||||||
|
curr_blocks = [b]
|
||||||
|
else:
|
||||||
|
curr_blocks.append(b)
|
||||||
|
if curr_blocks:
|
||||||
|
sections.append({
|
||||||
|
"text": "\n\n".join([x.text for x in curr_blocks]),
|
||||||
|
"meta": curr_blocks[0],
|
||||||
|
"is_empty": len(curr_blocks) == 1 and curr_blocks[0].kind == "heading"
|
||||||
|
})
|
||||||
|
|
||||||
|
# --- SCHRITT 2: Verarbeitung der Queue ---
|
||||||
|
queue = list(sections)
|
||||||
|
current_chunk_text = ""
|
||||||
|
current_meta = {"title": None, "path": "/"}
|
||||||
|
|
||||||
|
# Bestimmung des Modus: Hard-Split wenn smart_edge=False ODER strict=True
|
||||||
|
is_hard_split_mode = (not smart_edge) or (strict)
|
||||||
|
|
||||||
|
while queue:
|
||||||
|
item = queue.pop(0)
|
||||||
|
item_text = item["text"]
|
||||||
|
|
||||||
|
# Initialisierung für neuen Chunk
|
||||||
|
if not current_chunk_text:
|
||||||
|
current_meta["title"] = item["meta"].section_title
|
||||||
|
current_meta["path"] = item["meta"].section_path
|
||||||
|
|
||||||
|
# FALL A: HARD SPLIT MODUS
|
||||||
|
if is_hard_split_mode:
|
||||||
|
# Leere Überschriften (z.B. H1 direkt vor H2) verbleiben am nächsten Chunk
|
||||||
|
if item.get("is_empty", False) and queue:
|
||||||
|
current_chunk_text = (current_chunk_text + "\n\n" + item_text).strip()
|
||||||
|
continue
|
||||||
|
|
||||||
|
combined = (current_chunk_text + "\n\n" + item_text).strip()
|
||||||
|
# Wenn durch Verschmelzung das Limit gesprengt würde, vorher flashen
|
||||||
|
if estimate_tokens(combined) > max_tokens and current_chunk_text:
|
||||||
|
_emit(current_chunk_text, current_meta["title"], current_meta["path"])
|
||||||
|
current_chunk_text = item_text
|
||||||
|
else:
|
||||||
|
current_chunk_text = combined
|
||||||
|
|
||||||
|
# Im Hard-Split wird nach jeder Sektion geflasht
|
||||||
|
_emit(current_chunk_text, current_meta["title"], current_meta["path"])
|
||||||
|
current_chunk_text = ""
|
||||||
|
continue
|
||||||
|
|
||||||
|
# FALL B: SMART MODE (Regel 1-3)
|
||||||
|
combined_text = (current_chunk_text + "\n\n" + item_text).strip() if current_chunk_text else item_text
|
||||||
|
combined_est = estimate_tokens(combined_text)
|
||||||
|
|
||||||
|
if combined_est <= max_tokens:
|
||||||
|
# Regel 1 & 2: Passt rein laut Schätzung -> Aufnehmen
|
||||||
|
current_chunk_text = combined_text
|
||||||
|
else:
|
||||||
|
if current_chunk_text:
|
||||||
|
# Regel 2: Flashen an Sektionsgrenze, Item zurücklegen
|
||||||
|
_emit(current_chunk_text, current_meta["title"], current_meta["path"])
|
||||||
|
current_chunk_text = ""
|
||||||
|
queue.insert(0, item)
|
||||||
|
else:
|
||||||
|
# Regel 3: Einzelne Sektion zu groß -> Smart Zerlegung
|
||||||
|
sents = split_sentences(item_text)
|
||||||
|
header_prefix = item["meta"].text if item["meta"].kind == "heading" else ""
|
||||||
|
|
||||||
|
take_sents = []; take_len = 0
|
||||||
|
while sents:
|
||||||
|
s = sents.pop(0); slen = estimate_tokens(s)
|
||||||
|
if take_len + slen > target and take_sents:
|
||||||
|
sents.insert(0, s); break
|
||||||
|
take_sents.append(s); take_len += slen
|
||||||
|
|
||||||
|
_emit(" ".join(take_sents), current_meta["title"], current_meta["path"])
|
||||||
|
|
||||||
|
if sents:
|
||||||
|
remainder = " ".join(sents)
|
||||||
|
# Kontext-Erhalt: Überschrift für den Rest wiederholen
|
||||||
|
if header_prefix and not remainder.startswith(header_prefix):
|
||||||
|
remainder = header_prefix + "\n\n" + remainder
|
||||||
|
# Carry-Over: Rest wird vorne in die Queue geschoben
|
||||||
|
queue.insert(0, {"text": remainder, "meta": item["meta"], "is_split": True})
|
||||||
|
|
||||||
|
if current_chunk_text:
|
||||||
|
_emit(current_chunk_text, current_meta["title"], current_meta["path"])
|
||||||
|
|
||||||
|
return chunks
|
||||||
|
|
||||||
|
def strategy_sliding_window(blocks: List[RawBlock], config: Dict[str, Any], note_id: str, context_prefix: str = "") -> List[Chunk]:
|
||||||
|
"""Standard-Sliding-Window für flache Texte ohne Sektionsfokus."""
|
||||||
|
target = config.get("target", 400); max_tokens = config.get("max", 600)
|
||||||
|
chunks: List[Chunk] = []; buf: List[RawBlock] = []
|
||||||
|
|
||||||
|
for b in blocks:
|
||||||
|
b_tokens = estimate_tokens(b.text)
|
||||||
|
curr_tokens = sum(estimate_tokens(x.text) for x in buf) if buf else 0
|
||||||
|
if curr_tokens + b_tokens > max_tokens and buf:
|
||||||
|
txt = "\n\n".join([x.text for x in buf]); idx = len(chunks)
|
||||||
|
win = _create_win(context_prefix, buf[0].section_title, txt)
|
||||||
|
chunks.append(Chunk(id=f"{note_id}#c{idx:02d}", note_id=note_id, index=idx, text=txt, window=win, token_count=curr_tokens, section_title=buf[0].section_title, section_path=buf[0].section_path, neighbors_prev=None, neighbors_next=None))
|
||||||
|
buf = []
|
||||||
|
buf.append(b)
|
||||||
|
|
||||||
|
if buf:
|
||||||
|
txt = "\n\n".join([x.text for x in buf]); idx = len(chunks)
|
||||||
|
win = _create_win(context_prefix, buf[0].section_title, txt)
|
||||||
|
chunks.append(Chunk(id=f"{note_id}#c{idx:02d}", note_id=note_id, index=idx, text=txt, window=win, token_count=estimate_tokens(txt), section_title=buf[0].section_title, section_path=buf[0].section_path, neighbors_prev=None, neighbors_next=None))
|
||||||
|
|
||||||
|
return chunks
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
"""
|
||||||
|
FILE: app/core/chunking/chunking_utils.py
|
||||||
|
DESCRIPTION: Hilfswerkzeuge für Token-Schätzung und YAML-Konfiguration.
|
||||||
|
"""
|
||||||
|
import math
|
||||||
|
import yaml
|
||||||
|
import logging
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Dict, Any, Tuple
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
BASE_DIR = Path(__file__).resolve().parent.parent.parent.parent
|
||||||
|
CONFIG_PATH = BASE_DIR / "config" / "types.yaml"
|
||||||
|
DEFAULT_PROFILE = {"strategy": "sliding_window", "target": 400, "max": 600, "overlap": (50, 80)}
|
||||||
|
|
||||||
|
_CONFIG_CACHE = None
|
||||||
|
|
||||||
|
def load_yaml_config() -> Dict[str, Any]:
|
||||||
|
global _CONFIG_CACHE
|
||||||
|
if _CONFIG_CACHE is not None: return _CONFIG_CACHE
|
||||||
|
if not CONFIG_PATH.exists(): return {}
|
||||||
|
try:
|
||||||
|
with open(CONFIG_PATH, "r", encoding="utf-8") as f:
|
||||||
|
data = yaml.safe_load(f)
|
||||||
|
_CONFIG_CACHE = data
|
||||||
|
return data
|
||||||
|
except Exception: return {}
|
||||||
|
|
||||||
|
def get_chunk_config(note_type: str) -> Dict[str, Any]:
|
||||||
|
"""Lädt die Chunking-Strategie basierend auf dem Note-Type."""
|
||||||
|
full_config = load_yaml_config()
|
||||||
|
profiles = full_config.get("chunking_profiles", {})
|
||||||
|
type_def = full_config.get("types", {}).get(note_type.lower(), {})
|
||||||
|
profile_name = type_def.get("chunking_profile") or full_config.get("defaults", {}).get("chunking_profile", "sliding_standard")
|
||||||
|
config = profiles.get(profile_name, DEFAULT_PROFILE).copy()
|
||||||
|
if "overlap" in config and isinstance(config["overlap"], list):
|
||||||
|
config["overlap"] = tuple(config["overlap"])
|
||||||
|
return config
|
||||||
|
|
||||||
|
def estimate_tokens(text: str) -> int:
|
||||||
|
"""Grobe Schätzung der Token-Anzahl."""
|
||||||
|
return max(1, math.ceil(len(text.strip()) / 4))
|
||||||
|
|
||||||
|
def extract_frontmatter_from_text(md_text: str) -> Tuple[Dict[str, Any], str]:
|
||||||
|
"""Trennt YAML-Frontmatter vom Text."""
|
||||||
|
import re
|
||||||
|
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 Exception: frontmatter = {}
|
||||||
|
text_without_fm = re.sub(r'^\s*---\s*\n(.*?)\n---', '', md_text, flags=re.DOTALL)
|
||||||
|
return frontmatter, text_without_fm.strip()
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
"""
|
||||||
|
PACKAGE: app.core.database
|
||||||
|
DESCRIPTION: Zentrale Schnittstelle für alle Datenbank-Operationen (Qdrant).
|
||||||
|
Bündelt Client-Initialisierung und Point-Konvertierung.
|
||||||
|
"""
|
||||||
|
from .qdrant import (
|
||||||
|
QdrantConfig,
|
||||||
|
get_client,
|
||||||
|
ensure_collections,
|
||||||
|
ensure_payload_indexes,
|
||||||
|
collection_names
|
||||||
|
)
|
||||||
|
from .qdrant_points import (
|
||||||
|
points_for_note,
|
||||||
|
points_for_chunks,
|
||||||
|
points_for_edges,
|
||||||
|
upsert_batch,
|
||||||
|
get_edges_for_sources,
|
||||||
|
search_chunks_by_vector
|
||||||
|
)
|
||||||
|
|
||||||
|
# Öffentlicher Export für das Gesamtsystem
|
||||||
|
__all__ = [
|
||||||
|
"QdrantConfig",
|
||||||
|
"get_client",
|
||||||
|
"ensure_collections",
|
||||||
|
"ensure_payload_indexes",
|
||||||
|
"collection_names",
|
||||||
|
"points_for_note",
|
||||||
|
"points_for_chunks",
|
||||||
|
"points_for_edges",
|
||||||
|
"upsert_batch",
|
||||||
|
"get_edges_for_sources",
|
||||||
|
"search_chunks_by_vector"
|
||||||
|
]
|
||||||
@@ -1,20 +1,23 @@
|
|||||||
"""
|
"""
|
||||||
FILE: app/core/qdrant.py
|
FILE: app/core/database/qdrant.py
|
||||||
DESCRIPTION: Qdrant-Client Factory und Schema-Management. Erstellt Collections und Payload-Indizes.
|
DESCRIPTION: Qdrant-Client Factory und Schema-Management.
|
||||||
VERSION: 2.2.0
|
Erstellt Collections und Payload-Indizes.
|
||||||
|
MODULARISIERUNG: Verschoben in das database-Paket für WP-14.
|
||||||
|
VERSION: 2.2.2 (WP-Fix: Index für target_section)
|
||||||
STATUS: Active
|
STATUS: Active
|
||||||
DEPENDENCIES: qdrant_client, dataclasses, os
|
DEPENDENCIES: qdrant_client, dataclasses, os
|
||||||
LAST_ANALYSIS: 2025-12-15
|
|
||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import os
|
import os
|
||||||
|
import logging
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from typing import Optional, Tuple, Dict, List
|
from typing import Optional, Tuple, Dict, List
|
||||||
|
|
||||||
from qdrant_client import QdrantClient
|
from qdrant_client import QdrantClient
|
||||||
from qdrant_client.http import models as rest
|
from qdrant_client.http import models as rest
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
# Konfiguration
|
# Konfiguration
|
||||||
@@ -22,6 +25,7 @@ from qdrant_client.http import models as rest
|
|||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
class QdrantConfig:
|
class QdrantConfig:
|
||||||
|
"""Konfigurationsobjekt für den Qdrant-Verbindungsaufbau."""
|
||||||
host: Optional[str] = None
|
host: Optional[str] = None
|
||||||
port: Optional[int] = None
|
port: Optional[int] = None
|
||||||
url: Optional[str] = None
|
url: Optional[str] = None
|
||||||
@@ -33,6 +37,7 @@ class QdrantConfig:
|
|||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def from_env(cls) -> "QdrantConfig":
|
def from_env(cls) -> "QdrantConfig":
|
||||||
|
"""Erstellt die Konfiguration aus Umgebungsvariablen."""
|
||||||
# Entweder URL ODER Host/Port, API-Key optional
|
# Entweder URL ODER Host/Port, API-Key optional
|
||||||
url = os.getenv("QDRANT_URL") or None
|
url = os.getenv("QDRANT_URL") or None
|
||||||
host = os.getenv("QDRANT_HOST") or None
|
host = os.getenv("QDRANT_HOST") or None
|
||||||
@@ -43,6 +48,7 @@ class QdrantConfig:
|
|||||||
dim = int(os.getenv("VECTOR_DIM") or 384)
|
dim = int(os.getenv("VECTOR_DIM") or 384)
|
||||||
distance = os.getenv("DISTANCE", "Cosine")
|
distance = os.getenv("DISTANCE", "Cosine")
|
||||||
on_disk_payload = (os.getenv("ON_DISK_PAYLOAD", "true").lower() == "true")
|
on_disk_payload = (os.getenv("ON_DISK_PAYLOAD", "true").lower() == "true")
|
||||||
|
|
||||||
return cls(
|
return cls(
|
||||||
host=host, port=port, url=url, api_key=api_key,
|
host=host, port=port, url=url, api_key=api_key,
|
||||||
prefix=prefix, dim=dim, distance=distance, on_disk_payload=on_disk_payload
|
prefix=prefix, dim=dim, distance=distance, on_disk_payload=on_disk_payload
|
||||||
@@ -50,6 +56,7 @@ class QdrantConfig:
|
|||||||
|
|
||||||
|
|
||||||
def get_client(cfg: QdrantConfig) -> QdrantClient:
|
def get_client(cfg: QdrantConfig) -> QdrantClient:
|
||||||
|
"""Initialisiert den Qdrant-Client basierend auf der Konfiguration."""
|
||||||
# QdrantClient akzeptiert entweder url=... oder host/port
|
# QdrantClient akzeptiert entweder url=... oder host/port
|
||||||
if cfg.url:
|
if cfg.url:
|
||||||
return QdrantClient(url=cfg.url, api_key=cfg.api_key, timeout=60.0)
|
return QdrantClient(url=cfg.url, api_key=cfg.api_key, timeout=60.0)
|
||||||
@@ -61,17 +68,19 @@ def get_client(cfg: QdrantConfig) -> QdrantClient:
|
|||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
def collection_names(prefix: str) -> Tuple[str, str, str]:
|
def collection_names(prefix: str) -> Tuple[str, str, str]:
|
||||||
|
"""Gibt die standardisierten Collection-Namen zurück."""
|
||||||
return f"{prefix}_notes", f"{prefix}_chunks", f"{prefix}_edges"
|
return f"{prefix}_notes", f"{prefix}_chunks", f"{prefix}_edges"
|
||||||
|
|
||||||
|
|
||||||
def _vector_params(dim: int, distance: str) -> rest.VectorParams:
|
def _vector_params(dim: int, distance: str) -> rest.VectorParams:
|
||||||
|
"""Erstellt Vektor-Parameter für das Collection-Schema."""
|
||||||
# Distance: "Cosine" | "Dot" | "Euclid"
|
# Distance: "Cosine" | "Dot" | "Euclid"
|
||||||
dist = getattr(rest.Distance, distance.capitalize(), rest.Distance.COSINE)
|
dist = getattr(rest.Distance, distance.capitalize(), rest.Distance.COSINE)
|
||||||
return rest.VectorParams(size=dim, distance=dist)
|
return rest.VectorParams(size=dim, distance=dist)
|
||||||
|
|
||||||
|
|
||||||
def ensure_collections(client: QdrantClient, prefix: str, dim: int) -> None:
|
def ensure_collections(client: QdrantClient, prefix: str, dim: int) -> None:
|
||||||
"""Legt mindnet_notes, mindnet_chunks, mindnet_edges an (falls nicht vorhanden)."""
|
"""Legt notes, chunks und edges Collections an, falls nicht vorhanden."""
|
||||||
notes, chunks, edges = collection_names(prefix)
|
notes, chunks, edges = collection_names(prefix)
|
||||||
|
|
||||||
# notes
|
# notes
|
||||||
@@ -88,7 +97,7 @@ def ensure_collections(client: QdrantClient, prefix: str, dim: int) -> None:
|
|||||||
vectors_config=_vector_params(dim, os.getenv("DISTANCE", "Cosine")),
|
vectors_config=_vector_params(dim, os.getenv("DISTANCE", "Cosine")),
|
||||||
on_disk_payload=True,
|
on_disk_payload=True,
|
||||||
)
|
)
|
||||||
# edges (Dummy-Vektor, Filter via Payload)
|
# edges (Dummy-Vektor, da primär via Payload gefiltert wird)
|
||||||
if not client.collection_exists(edges):
|
if not client.collection_exists(edges):
|
||||||
client.create_collection(
|
client.create_collection(
|
||||||
collection_name=edges,
|
collection_name=edges,
|
||||||
@@ -102,21 +111,20 @@ def ensure_collections(client: QdrantClient, prefix: str, dim: int) -> None:
|
|||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
def _ensure_index(client: QdrantClient, collection: str, field: str, schema: rest.PayloadSchemaType) -> None:
|
def _ensure_index(client: QdrantClient, collection: str, field: str, schema: rest.PayloadSchemaType) -> None:
|
||||||
"""Idempotentes Anlegen eines Payload-Indexes für ein Feld."""
|
"""Idempotentes Anlegen eines Payload-Indexes für ein spezifisches Feld."""
|
||||||
try:
|
try:
|
||||||
client.create_payload_index(collection_name=collection, field_name=field, field_schema=schema, wait=True)
|
client.create_payload_index(collection_name=collection, field_name=field, field_schema=schema, wait=True)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
# Fehler ignorieren, falls Index bereits existiert oder Server "already indexed" meldet.
|
# Fehler ignorieren, falls Index bereits existiert
|
||||||
# Für Debugging ggf. Logging ergänzen.
|
logger.debug(f"Index check for {field} in {collection}: {e}")
|
||||||
_ = e
|
|
||||||
|
|
||||||
|
|
||||||
def ensure_payload_indexes(client: QdrantClient, prefix: str) -> None:
|
def ensure_payload_indexes(client: QdrantClient, prefix: str) -> None:
|
||||||
"""
|
"""
|
||||||
Stellt sicher, dass alle benötigten Payload-Indizes existieren.
|
Stellt sicher, dass alle benötigten Payload-Indizes für die Suche existieren.
|
||||||
- notes: note_id(KEYWORD), type(KEYWORD), title(TEXT), updated(INTEGER), tags(KEYWORD)
|
- notes: note_id, type, title, updated, tags
|
||||||
- chunks: note_id(KEYWORD), chunk_id(KEYWORD), index(INTEGER), type(KEYWORD), tags(KEYWORD)
|
- chunks: note_id, chunk_id, index, type, tags
|
||||||
- edges: note_id(KEYWORD), kind(KEYWORD), scope(KEYWORD), source_id(KEYWORD), target_id(KEYWORD), chunk_id(KEYWORD)
|
- edges: note_id, kind, scope, source_id, target_id, chunk_id, target_section
|
||||||
"""
|
"""
|
||||||
notes, chunks, edges = collection_names(prefix)
|
notes, chunks, edges = collection_names(prefix)
|
||||||
|
|
||||||
@@ -148,6 +156,8 @@ def ensure_payload_indexes(client: QdrantClient, prefix: str) -> None:
|
|||||||
("source_id", rest.PayloadSchemaType.KEYWORD),
|
("source_id", rest.PayloadSchemaType.KEYWORD),
|
||||||
("target_id", rest.PayloadSchemaType.KEYWORD),
|
("target_id", rest.PayloadSchemaType.KEYWORD),
|
||||||
("chunk_id", rest.PayloadSchemaType.KEYWORD),
|
("chunk_id", rest.PayloadSchemaType.KEYWORD),
|
||||||
|
# NEU: Index für Section-Links (WP-15b)
|
||||||
|
("target_section", rest.PayloadSchemaType.KEYWORD),
|
||||||
]:
|
]:
|
||||||
_ensure_index(client, edges, field, schema)
|
_ensure_index(client, edges, field, schema)
|
||||||
|
|
||||||
@@ -1,10 +1,10 @@
|
|||||||
"""
|
"""
|
||||||
FILE: app/core/qdrant_points.py
|
FILE: app/core/database/qdrant_points.py
|
||||||
DESCRIPTION: Object-Mapper für Qdrant. Konvertiert JSON-Payloads (Notes, Chunks, Edges) in PointStructs und generiert deterministische UUIDs.
|
DESCRIPTION: Object-Mapper für Qdrant. Konvertiert JSON-Payloads (Notes, Chunks, Edges) in PointStructs und generiert deterministische UUIDs.
|
||||||
VERSION: 1.5.0
|
VERSION: 1.5.1 (WP-Fix: Explicit Target Section Support)
|
||||||
STATUS: Active
|
STATUS: Active
|
||||||
DEPENDENCIES: qdrant_client, uuid, os
|
DEPENDENCIES: qdrant_client, uuid, os
|
||||||
LAST_ANALYSIS: 2025-12-15
|
LAST_ANALYSIS: 2025-12-29
|
||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
import os
|
import os
|
||||||
@@ -46,16 +46,25 @@ def points_for_chunks(prefix: str, chunk_payloads: List[dict], vectors: List[Lis
|
|||||||
return chunks_col, points
|
return chunks_col, points
|
||||||
|
|
||||||
def _normalize_edge_payload(pl: dict) -> dict:
|
def _normalize_edge_payload(pl: dict) -> dict:
|
||||||
|
"""Normalisiert Edge-Felder und sichert Schema-Konformität."""
|
||||||
kind = pl.get("kind") or pl.get("edge_type") or "edge"
|
kind = pl.get("kind") or pl.get("edge_type") or "edge"
|
||||||
source_id = pl.get("source_id") or pl.get("src_id") or "unknown-src"
|
source_id = pl.get("source_id") or pl.get("src_id") or "unknown-src"
|
||||||
target_id = pl.get("target_id") or pl.get("dst_id") or "unknown-tgt"
|
target_id = pl.get("target_id") or pl.get("dst_id") or "unknown-tgt"
|
||||||
seq = pl.get("seq") or pl.get("order") or pl.get("index")
|
seq = pl.get("seq") or pl.get("order") or pl.get("index")
|
||||||
|
|
||||||
|
# WP-Fix: target_section explizit durchreichen
|
||||||
|
target_section = pl.get("target_section")
|
||||||
|
|
||||||
pl.setdefault("kind", kind)
|
pl.setdefault("kind", kind)
|
||||||
pl.setdefault("source_id", source_id)
|
pl.setdefault("source_id", source_id)
|
||||||
pl.setdefault("target_id", target_id)
|
pl.setdefault("target_id", target_id)
|
||||||
|
|
||||||
if seq is not None and "seq" not in pl:
|
if seq is not None and "seq" not in pl:
|
||||||
pl["seq"] = seq
|
pl["seq"] = seq
|
||||||
|
|
||||||
|
if target_section is not None:
|
||||||
|
pl["target_section"] = target_section
|
||||||
|
|
||||||
return pl
|
return pl
|
||||||
|
|
||||||
def points_for_edges(prefix: str, edge_payloads: List[dict]) -> Tuple[str, List[rest.PointStruct]]:
|
def points_for_edges(prefix: str, edge_payloads: List[dict]) -> Tuple[str, List[rest.PointStruct]]:
|
||||||
@@ -277,6 +286,10 @@ def get_edges_for_sources(
|
|||||||
offset=next_page,
|
offset=next_page,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# Recovery: In der originalen Codebasis v1.5.0 fehlt hier der Abschluss des Loops.
|
||||||
|
# Um 100% Konformität zu wahren, habe ich ihn genau so gelassen.
|
||||||
|
# ACHTUNG: Der Code unten stellt die logische Fortsetzung aus deiner Datei dar.
|
||||||
|
|
||||||
if not res:
|
if not res:
|
||||||
break
|
break
|
||||||
|
|
||||||
@@ -1,420 +0,0 @@
|
|||||||
"""
|
|
||||||
FILE: app/core/derive_edges.py
|
|
||||||
DESCRIPTION: Extrahiert Graph-Kanten aus Text. Unterstützt Wikilinks, Inline-Relations ([[rel:type|target]]) und Obsidian Callouts.
|
|
||||||
VERSION: 2.0.0
|
|
||||||
STATUS: Active
|
|
||||||
DEPENDENCIES: re, os, yaml, typing
|
|
||||||
EXTERNAL_CONFIG: config/types.yaml
|
|
||||||
LAST_ANALYSIS: 2025-12-15
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import os
|
|
||||||
import re
|
|
||||||
from typing import Iterable, List, Optional, Tuple, Set, Dict
|
|
||||||
|
|
||||||
try:
|
|
||||||
import yaml # optional, nur für types.yaml
|
|
||||||
except Exception: # pragma: no cover
|
|
||||||
yaml = None
|
|
||||||
|
|
||||||
# --------------------------------------------------------------------------- #
|
|
||||||
# Utilities
|
|
||||||
# --------------------------------------------------------------------------- #
|
|
||||||
|
|
||||||
def _get(d: dict, *keys, default=None):
|
|
||||||
for k in keys:
|
|
||||||
if isinstance(d, dict) and k in d and d[k] is not None:
|
|
||||||
return d[k]
|
|
||||||
return default
|
|
||||||
|
|
||||||
def _chunk_text_for_refs(chunk: dict) -> str:
|
|
||||||
# bevorzugt 'window' → dann 'text' → 'content' → 'raw'
|
|
||||||
return (
|
|
||||||
_get(chunk, "window")
|
|
||||||
or _get(chunk, "text")
|
|
||||||
or _get(chunk, "content")
|
|
||||||
or _get(chunk, "raw")
|
|
||||||
or ""
|
|
||||||
)
|
|
||||||
|
|
||||||
def _dedupe_seq(seq: Iterable[str]) -> List[str]:
|
|
||||||
seen: Set[str] = set()
|
|
||||||
out: List[str] = []
|
|
||||||
for s in seq:
|
|
||||||
if s not in seen:
|
|
||||||
seen.add(s)
|
|
||||||
out.append(s)
|
|
||||||
return out
|
|
||||||
|
|
||||||
def _edge(kind: str, scope: str, source_id: str, target_id: str, note_id: str, extra: Optional[dict] = None) -> dict:
|
|
||||||
pl = {
|
|
||||||
"kind": kind,
|
|
||||||
"relation": kind, # Alias (v2)
|
|
||||||
"scope": scope, # "chunk" | "note"
|
|
||||||
"source_id": source_id,
|
|
||||||
"target_id": target_id,
|
|
||||||
"note_id": note_id, # Träger-Note der Kante
|
|
||||||
}
|
|
||||||
if extra:
|
|
||||||
pl.update(extra)
|
|
||||||
return pl
|
|
||||||
|
|
||||||
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
|
|
||||||
|
|
||||||
# --------------------------------------------------------------------------- #
|
|
||||||
# Typen-Registry (types.yaml)
|
|
||||||
# --------------------------------------------------------------------------- #
|
|
||||||
|
|
||||||
def _env(n: str, default: Optional[str] = None) -> str:
|
|
||||||
v = os.getenv(n)
|
|
||||||
return v if v is not None else (default or "")
|
|
||||||
|
|
||||||
def _load_types_registry() -> dict:
|
|
||||||
"""Lädt die YAML-Registry aus MINDNET_TYPES_FILE oder ./config/types.yaml"""
|
|
||||||
p = _env("MINDNET_TYPES_FILE", "./config/types.yaml")
|
|
||||||
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 {}
|
|
||||||
return data
|
|
||||||
except Exception:
|
|
||||||
return {}
|
|
||||||
|
|
||||||
def _get_types_map(reg: dict) -> dict:
|
|
||||||
if isinstance(reg, dict) and isinstance(reg.get("types"), dict):
|
|
||||||
return reg["types"]
|
|
||||||
return reg if isinstance(reg, dict) else {}
|
|
||||||
|
|
||||||
def _edge_defaults_for(note_type: Optional[str], reg: dict) -> List[str]:
|
|
||||||
"""
|
|
||||||
Liefert die edge_defaults-Liste für den gegebenen Notiztyp.
|
|
||||||
Fallback-Reihenfolge:
|
|
||||||
1) reg['types'][note_type]['edge_defaults']
|
|
||||||
2) reg['defaults']['edge_defaults'] (oder 'default'/'global')
|
|
||||||
3) []
|
|
||||||
"""
|
|
||||||
types_map = _get_types_map(reg)
|
|
||||||
if note_type and isinstance(types_map, dict):
|
|
||||||
t = types_map.get(note_type)
|
|
||||||
if isinstance(t, dict) and isinstance(t.get("edge_defaults"), list):
|
|
||||||
return [str(x) for x in t["edge_defaults"] if isinstance(x, str)]
|
|
||||||
for key in ("defaults", "default", "global"):
|
|
||||||
v = reg.get(key)
|
|
||||||
if isinstance(v, dict) and isinstance(v.get("edge_defaults"), list):
|
|
||||||
return [str(x) for x in v["edge_defaults"] if isinstance(x, str)]
|
|
||||||
return []
|
|
||||||
|
|
||||||
# --------------------------------------------------------------------------- #
|
|
||||||
# Parser für Links / Relationen
|
|
||||||
# --------------------------------------------------------------------------- #
|
|
||||||
|
|
||||||
# Normale Wikilinks (Fallback)
|
|
||||||
_WIKILINK_RE = re.compile(r"\[\[(?:[^\|\]]+\|)?([a-zA-Z0-9_\-#:. ]+)\]\]")
|
|
||||||
|
|
||||||
# Getypte Inline-Relationen:
|
|
||||||
# [[rel:KIND | Target]]
|
|
||||||
# [[rel:KIND Target]]
|
|
||||||
_REL_PIPE = re.compile(r"\[\[\s*rel:(?P<kind>[a-z_]+)\s*\|\s*(?P<target>[^\]]+?)\s*\]\]", re.IGNORECASE)
|
|
||||||
_REL_SPACE = re.compile(r"\[\[\s*rel:(?P<kind>[a-z_]+)\s+(?P<target>[^\]]+?)\s*\]\]", re.IGNORECASE)
|
|
||||||
# rel: KIND [[Target]] (reines Textmuster)
|
|
||||||
_REL_TEXT = re.compile(r"rel\s*:\s*(?P<kind>[a-z_]+)\s*\[\[\s*(?P<target>[^\]]+?)\s*\]\]", re.IGNORECASE)
|
|
||||||
|
|
||||||
def _extract_typed_relations(text: str) -> Tuple[List[Tuple[str,str]], str]:
|
|
||||||
"""
|
|
||||||
Gibt Liste (kind, target) zurück und den Text mit entfernten getypten Relation-Links,
|
|
||||||
damit die generische Wikilink-Erkennung sie nicht doppelt zählt.
|
|
||||||
Unterstützt drei Varianten:
|
|
||||||
- [[rel:KIND | Target]]
|
|
||||||
- [[rel:KIND Target]]
|
|
||||||
- rel: KIND [[Target]]
|
|
||||||
"""
|
|
||||||
pairs: List[Tuple[str,str]] = []
|
|
||||||
def _collect(m):
|
|
||||||
k = (m.group("kind") or "").strip().lower()
|
|
||||||
t = (m.group("target") or "").strip()
|
|
||||||
if k and t:
|
|
||||||
pairs.append((k, t))
|
|
||||||
return "" # Link entfernen
|
|
||||||
|
|
||||||
text = _REL_PIPE.sub(_collect, text)
|
|
||||||
text = _REL_SPACE.sub(_collect, text)
|
|
||||||
text = _REL_TEXT.sub(_collect, text)
|
|
||||||
return pairs, text
|
|
||||||
|
|
||||||
# Obsidian Callout Parser
|
|
||||||
_CALLOUT_START = re.compile(r"^\s*>\s*\[!edge\]\s*(.*)$", re.IGNORECASE)
|
|
||||||
_REL_LINE = re.compile(r"^(?P<kind>[a-z_]+)\s*:\s*(?P<targets>.+?)\s*$", re.IGNORECASE)
|
|
||||||
_WIKILINKS_IN_LINE = re.compile(r"\[\[([^\]]+)\]\]")
|
|
||||||
|
|
||||||
def _extract_callout_relations(text: str) -> Tuple[List[Tuple[str,str]], str]:
|
|
||||||
"""
|
|
||||||
Findet [!edge]-Callouts und extrahiert (kind, target). Entfernt den gesamten
|
|
||||||
Callout-Block aus dem Text (damit Wikilinks daraus nicht zusätzlich als
|
|
||||||
"references" gezählt werden).
|
|
||||||
"""
|
|
||||||
if not text:
|
|
||||||
return [], text
|
|
||||||
|
|
||||||
lines = text.splitlines()
|
|
||||||
out_pairs: List[Tuple[str,str]] = []
|
|
||||||
keep_lines: List[str] = []
|
|
||||||
i = 0
|
|
||||||
|
|
||||||
while i < len(lines):
|
|
||||||
m = _CALLOUT_START.match(lines[i])
|
|
||||||
if not m:
|
|
||||||
keep_lines.append(lines[i])
|
|
||||||
i += 1
|
|
||||||
continue
|
|
||||||
|
|
||||||
block_lines: List[str] = []
|
|
||||||
first_rest = m.group(1) or ""
|
|
||||||
if first_rest.strip():
|
|
||||||
block_lines.append(first_rest)
|
|
||||||
|
|
||||||
i += 1
|
|
||||||
while i < len(lines) and lines[i].lstrip().startswith('>'):
|
|
||||||
block_lines.append(lines[i].lstrip()[1:].lstrip())
|
|
||||||
i += 1
|
|
||||||
|
|
||||||
for bl in block_lines:
|
|
||||||
mrel = _REL_LINE.match(bl)
|
|
||||||
if not mrel:
|
|
||||||
continue
|
|
||||||
kind = (mrel.group("kind") or "").strip().lower()
|
|
||||||
targets = mrel.group("targets") or ""
|
|
||||||
found = _WIKILINKS_IN_LINE.findall(targets)
|
|
||||||
if found:
|
|
||||||
for t in found:
|
|
||||||
t = t.strip()
|
|
||||||
if t:
|
|
||||||
out_pairs.append((kind, t))
|
|
||||||
else:
|
|
||||||
for raw in re.split(r"[,;]", targets):
|
|
||||||
t = raw.strip()
|
|
||||||
if t:
|
|
||||||
out_pairs.append((kind, t))
|
|
||||||
|
|
||||||
# Callout wird NICHT in keep_lines übernommen
|
|
||||||
continue
|
|
||||||
|
|
||||||
remainder = "\n".join(keep_lines)
|
|
||||||
return out_pairs, remainder
|
|
||||||
|
|
||||||
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
|
|
||||||
|
|
||||||
# --------------------------------------------------------------------------- #
|
|
||||||
# Hauptfunktion
|
|
||||||
# --------------------------------------------------------------------------- #
|
|
||||||
|
|
||||||
def build_edges_for_note(
|
|
||||||
note_id: str,
|
|
||||||
chunks: List[dict],
|
|
||||||
note_level_references: Optional[List[str]] = None,
|
|
||||||
include_note_scope_refs: bool = False,
|
|
||||||
) -> List[dict]:
|
|
||||||
"""
|
|
||||||
Erzeugt Kanten für eine Note.
|
|
||||||
|
|
||||||
- belongs_to: für jeden Chunk (chunk -> note)
|
|
||||||
- next / prev: zwischen aufeinanderfolgenden Chunks
|
|
||||||
- references: pro Chunk aus window/text (via Wikilinks)
|
|
||||||
- typed inline relations: [[rel:KIND | Target]] / [[rel:KIND Target]] / rel: KIND [[Target]]
|
|
||||||
- Obsidian Callouts: > [!edge] KIND: [[Target]] [[Target2]]
|
|
||||||
- optional note-scope references/backlinks: dedupliziert über alle Chunk-Funde + note_level_references
|
|
||||||
- typenbasierte Default-Kanten (edge_defaults) je gefundener Referenz
|
|
||||||
"""
|
|
||||||
edges: List[dict] = []
|
|
||||||
|
|
||||||
# Note-Typ (aus erstem Chunk erwartet)
|
|
||||||
note_type = None
|
|
||||||
if chunks:
|
|
||||||
note_type = _get(chunks[0], "type")
|
|
||||||
|
|
||||||
# 1) belongs_to
|
|
||||||
for ch in chunks:
|
|
||||||
cid = _get(ch, "chunk_id", "id")
|
|
||||||
if not cid:
|
|
||||||
continue
|
|
||||||
edges.append(_edge("belongs_to", "chunk", cid, note_id, note_id, {
|
|
||||||
"chunk_id": cid,
|
|
||||||
"edge_id": _mk_edge_id("belongs_to", cid, note_id, "chunk", "structure:belongs_to"),
|
|
||||||
"provenance": "rule",
|
|
||||||
"rule_id": "structure:belongs_to",
|
|
||||||
"confidence": 1.0,
|
|
||||||
}))
|
|
||||||
|
|
||||||
# 2) next / prev
|
|
||||||
for i in range(len(chunks) - 1):
|
|
||||||
a, b = chunks[i], chunks[i + 1]
|
|
||||||
a_id = _get(a, "chunk_id", "id")
|
|
||||||
b_id = _get(b, "chunk_id", "id")
|
|
||||||
if not a_id or not b_id:
|
|
||||||
continue
|
|
||||||
edges.append(_edge("next", "chunk", a_id, b_id, note_id, {
|
|
||||||
"chunk_id": a_id,
|
|
||||||
"edge_id": _mk_edge_id("next", a_id, b_id, "chunk", "structure:order"),
|
|
||||||
"provenance": "rule",
|
|
||||||
"rule_id": "structure:order",
|
|
||||||
"confidence": 0.95,
|
|
||||||
}))
|
|
||||||
edges.append(_edge("prev", "chunk", b_id, a_id, note_id, {
|
|
||||||
"chunk_id": b_id,
|
|
||||||
"edge_id": _mk_edge_id("prev", b_id, a_id, "chunk", "structure:order"),
|
|
||||||
"provenance": "rule",
|
|
||||||
"rule_id": "structure:order",
|
|
||||||
"confidence": 0.95,
|
|
||||||
}))
|
|
||||||
|
|
||||||
# 3) references + typed inline + callouts + defaults (chunk-scope)
|
|
||||||
reg = _load_types_registry()
|
|
||||||
defaults = _edge_defaults_for(note_type, reg)
|
|
||||||
refs_all: List[str] = []
|
|
||||||
|
|
||||||
for ch in chunks:
|
|
||||||
cid = _get(ch, "chunk_id", "id")
|
|
||||||
if not cid:
|
|
||||||
continue
|
|
||||||
raw = _chunk_text_for_refs(ch)
|
|
||||||
|
|
||||||
# 3a) typed inline relations
|
|
||||||
typed, remainder = _extract_typed_relations(raw)
|
|
||||||
for kind, target in typed:
|
|
||||||
kind = kind.strip().lower()
|
|
||||||
if not kind or not target:
|
|
||||||
continue
|
|
||||||
edges.append(_edge(kind, "chunk", cid, target, note_id, {
|
|
||||||
"chunk_id": cid,
|
|
||||||
"edge_id": _mk_edge_id(kind, cid, target, "chunk", "inline:rel"),
|
|
||||||
"provenance": "explicit",
|
|
||||||
"rule_id": "inline:rel",
|
|
||||||
"confidence": 0.95,
|
|
||||||
}))
|
|
||||||
if kind in {"related_to", "similar_to"}:
|
|
||||||
edges.append(_edge(kind, "chunk", target, cid, note_id, {
|
|
||||||
"chunk_id": cid,
|
|
||||||
"edge_id": _mk_edge_id(kind, target, cid, "chunk", "inline:rel"),
|
|
||||||
"provenance": "explicit",
|
|
||||||
"rule_id": "inline:rel",
|
|
||||||
"confidence": 0.95,
|
|
||||||
}))
|
|
||||||
|
|
||||||
# 3b) callouts
|
|
||||||
call_pairs, remainder2 = _extract_callout_relations(remainder)
|
|
||||||
for kind, target in call_pairs:
|
|
||||||
k = (kind or "").strip().lower()
|
|
||||||
if not k or not target:
|
|
||||||
continue
|
|
||||||
edges.append(_edge(k, "chunk", cid, target, note_id, {
|
|
||||||
"chunk_id": cid,
|
|
||||||
"edge_id": _mk_edge_id(k, cid, target, "chunk", "callout:edge"),
|
|
||||||
"provenance": "explicit",
|
|
||||||
"rule_id": "callout:edge",
|
|
||||||
"confidence": 0.95,
|
|
||||||
}))
|
|
||||||
if k in {"related_to", "similar_to"}:
|
|
||||||
edges.append(_edge(k, "chunk", target, cid, note_id, {
|
|
||||||
"chunk_id": cid,
|
|
||||||
"edge_id": _mk_edge_id(k, target, cid, "chunk", "callout:edge"),
|
|
||||||
"provenance": "explicit",
|
|
||||||
"rule_id": "callout:edge",
|
|
||||||
"confidence": 0.95,
|
|
||||||
}))
|
|
||||||
|
|
||||||
# 3c) generische Wikilinks → references (+ defaults je Ref)
|
|
||||||
refs = _extract_wikilinks(remainder2)
|
|
||||||
for r in refs:
|
|
||||||
edges.append(_edge("references", "chunk", cid, r, note_id, {
|
|
||||||
"chunk_id": cid,
|
|
||||||
"ref_text": r,
|
|
||||||
"edge_id": _mk_edge_id("references", cid, r, "chunk", "explicit:wikilink"),
|
|
||||||
"provenance": "explicit",
|
|
||||||
"rule_id": "explicit:wikilink",
|
|
||||||
"confidence": 1.0,
|
|
||||||
}))
|
|
||||||
for rel in defaults:
|
|
||||||
if rel == "references":
|
|
||||||
continue
|
|
||||||
edges.append(_edge(rel, "chunk", cid, r, note_id, {
|
|
||||||
"chunk_id": cid,
|
|
||||||
"edge_id": _mk_edge_id(rel, cid, r, "chunk", f"edge_defaults:{note_type}:{rel}"),
|
|
||||||
"provenance": "rule",
|
|
||||||
"rule_id": f"edge_defaults:{note_type}:{rel}",
|
|
||||||
"confidence": 0.7,
|
|
||||||
}))
|
|
||||||
if rel in {"related_to", "similar_to"}:
|
|
||||||
edges.append(_edge(rel, "chunk", r, cid, note_id, {
|
|
||||||
"chunk_id": cid,
|
|
||||||
"edge_id": _mk_edge_id(rel, r, cid, "chunk", f"edge_defaults:{note_type}:{rel}"),
|
|
||||||
"provenance": "rule",
|
|
||||||
"rule_id": f"edge_defaults:{note_type}:{rel}",
|
|
||||||
"confidence": 0.7,
|
|
||||||
}))
|
|
||||||
|
|
||||||
refs_all.extend(refs)
|
|
||||||
|
|
||||||
# 4) optional note-scope refs/backlinks (+ defaults)
|
|
||||||
if include_note_scope_refs:
|
|
||||||
refs_note = list(refs_all or [])
|
|
||||||
if note_level_references:
|
|
||||||
refs_note.extend([r for r in note_level_references if isinstance(r, str) and r])
|
|
||||||
refs_note = _dedupe_seq(refs_note)
|
|
||||||
for r in refs_note:
|
|
||||||
edges.append(_edge("references", "note", note_id, r, note_id, {
|
|
||||||
"edge_id": _mk_edge_id("references", note_id, r, "note", "explicit:note_scope"),
|
|
||||||
"provenance": "explicit",
|
|
||||||
"rule_id": "explicit:note_scope",
|
|
||||||
"confidence": 1.0,
|
|
||||||
}))
|
|
||||||
edges.append(_edge("backlink", "note", r, note_id, note_id, {
|
|
||||||
"edge_id": _mk_edge_id("backlink", r, note_id, "note", "derived:backlink"),
|
|
||||||
"provenance": "rule",
|
|
||||||
"rule_id": "derived:backlink",
|
|
||||||
"confidence": 0.9,
|
|
||||||
}))
|
|
||||||
for rel in defaults:
|
|
||||||
if rel == "references":
|
|
||||||
continue
|
|
||||||
edges.append(_edge(rel, "note", note_id, r, note_id, {
|
|
||||||
"edge_id": _mk_edge_id(rel, note_id, r, "note", f"edge_defaults:{note_type}:{rel}"),
|
|
||||||
"provenance": "rule",
|
|
||||||
"rule_id": f"edge_defaults:{note_type}:{rel}",
|
|
||||||
"confidence": 0.7,
|
|
||||||
}))
|
|
||||||
if rel in {"related_to", "similar_to"}:
|
|
||||||
edges.append(_edge(rel, "note", r, note_id, note_id, {
|
|
||||||
"edge_id": _mk_edge_id(rel, r, note_id, "note", f"edge_defaults:{note_type}:{rel}"),
|
|
||||||
"provenance": "rule",
|
|
||||||
"rule_id": f"edge_defaults:{note_type}:{rel}",
|
|
||||||
"confidence": 0.7,
|
|
||||||
}))
|
|
||||||
|
|
||||||
# 5) De-Dupe (source_id, target_id, relation, rule_id)
|
|
||||||
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
|
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
"""
|
||||||
|
FILE: app/core/graph/__init__.py
|
||||||
|
DESCRIPTION: Unified Graph Package. Exportiert Kanten-Ableitung und Graph-Adapter.
|
||||||
|
"""
|
||||||
|
from .graph_derive_edges import build_edges_for_note
|
||||||
|
from .graph_utils import PROVENANCE_PRIORITY
|
||||||
|
from .graph_subgraph import Subgraph, expand
|
||||||
|
from .graph_weights import EDGE_BASE_WEIGHTS
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"build_edges_for_note",
|
||||||
|
"PROVENANCE_PRIORITY",
|
||||||
|
"Subgraph",
|
||||||
|
"expand",
|
||||||
|
"EDGE_BASE_WEIGHTS"
|
||||||
|
]
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
"""
|
||||||
|
FILE: app/core/graph/graph_db_adapter.py
|
||||||
|
DESCRIPTION: Datenbeschaffung aus Qdrant für den Graphen.
|
||||||
|
AUDIT v1.1.1: Volle Unterstützung für WP-15c Metadaten.
|
||||||
|
Stellt sicher, dass 'target_section' und 'provenance' für die
|
||||||
|
Super-Edge-Aggregation im Retriever geladen werden.
|
||||||
|
"""
|
||||||
|
from typing import List, Dict, Optional
|
||||||
|
from qdrant_client import QdrantClient
|
||||||
|
from qdrant_client.http import models as rest
|
||||||
|
|
||||||
|
# Nutzt die zentrale Infrastruktur für konsistente Collection-Namen (WP-14)
|
||||||
|
from app.core.database import collection_names
|
||||||
|
|
||||||
|
def fetch_edges_from_qdrant(
|
||||||
|
client: QdrantClient,
|
||||||
|
prefix: str,
|
||||||
|
seeds: List[str],
|
||||||
|
edge_types: Optional[List[str]] = None,
|
||||||
|
limit: int = 2048,
|
||||||
|
) -> List[Dict]:
|
||||||
|
"""
|
||||||
|
Holt Edges aus der Datenbank basierend auf Seed-IDs.
|
||||||
|
WP-15c: Erhält alle Metadaten für das Note-Level Diversity Pooling.
|
||||||
|
"""
|
||||||
|
if not seeds or limit <= 0:
|
||||||
|
return []
|
||||||
|
|
||||||
|
# Konsistente Namensauflösung via database-Paket
|
||||||
|
# Rückgabe: (notes_col, chunks_col, edges_col)
|
||||||
|
_, _, edges_col = collection_names(prefix)
|
||||||
|
|
||||||
|
# Wir suchen Kanten, bei denen die Seed-IDs entweder Quelle, Ziel oder Kontext-Note sind.
|
||||||
|
seed_conditions = []
|
||||||
|
for field in ("source_id", "target_id", "note_id"):
|
||||||
|
for s in seeds:
|
||||||
|
seed_conditions.append(
|
||||||
|
rest.FieldCondition(key=field, match=rest.MatchValue(value=str(s)))
|
||||||
|
)
|
||||||
|
seeds_filter = rest.Filter(should=seed_conditions) if seed_conditions else None
|
||||||
|
|
||||||
|
# Optionaler Filter auf spezifische Kanten-Typen (z.B. für Intent-Routing)
|
||||||
|
type_filter = None
|
||||||
|
if edge_types:
|
||||||
|
type_conds = [
|
||||||
|
rest.FieldCondition(key="kind", match=rest.MatchValue(value=str(k)))
|
||||||
|
for k in edge_types
|
||||||
|
]
|
||||||
|
type_filter = rest.Filter(should=type_conds)
|
||||||
|
|
||||||
|
must = []
|
||||||
|
if seeds_filter:
|
||||||
|
must.append(seeds_filter)
|
||||||
|
if type_filter:
|
||||||
|
must.append(type_filter)
|
||||||
|
|
||||||
|
flt = rest.Filter(must=must) if must else None
|
||||||
|
|
||||||
|
# Abfrage via Qdrant Scroll API
|
||||||
|
# WICHTIG: with_payload=True lädt alle Metadaten (target_section, provenance etc.)
|
||||||
|
pts, _ = client.scroll(
|
||||||
|
collection_name=edges_col,
|
||||||
|
scroll_filter=flt,
|
||||||
|
limit=limit,
|
||||||
|
with_payload=True,
|
||||||
|
with_vectors=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Wir geben das vollständige Payload zurück, damit der Retriever
|
||||||
|
# alle Signale für die Super-Edge-Aggregation und das Scoring hat.
|
||||||
|
return [dict(p.payload) for p in pts if p.payload]
|
||||||
@@ -0,0 +1,169 @@
|
|||||||
|
"""
|
||||||
|
FILE: app/core/graph/graph_derive_edges.py
|
||||||
|
DESCRIPTION: Hauptlogik zur Kanten-Aggregation und De-Duplizierung.
|
||||||
|
WP-15b/c Audit:
|
||||||
|
- Präzises Sektions-Splitting via parse_link_target.
|
||||||
|
- Eindeutige ID-Generierung pro Sektions-Variante (Multigraph).
|
||||||
|
- Ermöglicht dem Retriever die Super-Edge-Aggregation.
|
||||||
|
"""
|
||||||
|
from typing import List, Optional, Dict, Tuple
|
||||||
|
from .graph_utils import (
|
||||||
|
_get, _edge, _mk_edge_id, _dedupe_seq, parse_link_target,
|
||||||
|
PROVENANCE_PRIORITY, load_types_registry, get_edge_defaults_for
|
||||||
|
)
|
||||||
|
from .graph_extractors import (
|
||||||
|
extract_typed_relations, extract_callout_relations, extract_wikilinks
|
||||||
|
)
|
||||||
|
|
||||||
|
def build_edges_for_note(
|
||||||
|
note_id: str,
|
||||||
|
chunks: List[dict],
|
||||||
|
note_level_references: Optional[List[str]] = None,
|
||||||
|
include_note_scope_refs: bool = False,
|
||||||
|
) -> List[dict]:
|
||||||
|
"""
|
||||||
|
Erzeugt und aggregiert alle Kanten für eine Note.
|
||||||
|
Sorgt für die physische Trennung von Sektions-Links via Edge-ID.
|
||||||
|
"""
|
||||||
|
edges: List[dict] = []
|
||||||
|
# note_type für die Ermittlung der edge_defaults (types.yaml)
|
||||||
|
note_type = _get(chunks[0], "type") if chunks else "concept"
|
||||||
|
|
||||||
|
# 1) Struktur-Kanten (Internal: belongs_to, next/prev)
|
||||||
|
# Diese erhalten die Provenienz 'structure' und sind in der Registry geschützt.
|
||||||
|
for idx, ch in enumerate(chunks):
|
||||||
|
cid = _get(ch, "chunk_id", "id")
|
||||||
|
if not cid: continue
|
||||||
|
|
||||||
|
# Verbindung Chunk -> Note
|
||||||
|
edges.append(_edge("belongs_to", "chunk", cid, note_id, note_id, {
|
||||||
|
"chunk_id": cid,
|
||||||
|
"edge_id": _mk_edge_id("belongs_to", cid, note_id, "chunk", "structure:belongs_to"),
|
||||||
|
"provenance": "structure",
|
||||||
|
"rule_id": "structure:belongs_to",
|
||||||
|
"confidence": PROVENANCE_PRIORITY["structure:belongs_to"]
|
||||||
|
}))
|
||||||
|
|
||||||
|
# Horizontale Verkettung (Ordnung)
|
||||||
|
if idx < len(chunks) - 1:
|
||||||
|
next_id = _get(chunks[idx+1], "chunk_id", "id")
|
||||||
|
if next_id:
|
||||||
|
edges.append(_edge("next", "chunk", cid, next_id, note_id, {
|
||||||
|
"chunk_id": cid,
|
||||||
|
"edge_id": _mk_edge_id("next", cid, next_id, "chunk", "structure:order"),
|
||||||
|
"provenance": "structure", "rule_id": "structure:order", "confidence": PROVENANCE_PRIORITY["structure:order"]
|
||||||
|
}))
|
||||||
|
edges.append(_edge("prev", "chunk", next_id, cid, note_id, {
|
||||||
|
"chunk_id": next_id,
|
||||||
|
"edge_id": _mk_edge_id("prev", next_id, cid, "chunk", "structure:order"),
|
||||||
|
"provenance": "structure", "rule_id": "structure:order", "confidence": PROVENANCE_PRIORITY["structure:order"]
|
||||||
|
}))
|
||||||
|
|
||||||
|
# 2) Inhaltliche Kanten (Explicit & Candidate Pool)
|
||||||
|
reg = load_types_registry()
|
||||||
|
defaults = get_edge_defaults_for(note_type, reg)
|
||||||
|
refs_all: List[str] = []
|
||||||
|
|
||||||
|
for ch in chunks:
|
||||||
|
cid = _get(ch, "chunk_id", "id")
|
||||||
|
if not cid: continue
|
||||||
|
raw = _get(ch, "window") or _get(ch, "text") or ""
|
||||||
|
|
||||||
|
# A. Typed Relations (Inline [[rel:kind|target]])
|
||||||
|
typed, rem = extract_typed_relations(raw)
|
||||||
|
for k, raw_t in typed:
|
||||||
|
t, sec = parse_link_target(raw_t, note_id)
|
||||||
|
if not t: continue
|
||||||
|
|
||||||
|
payload = {
|
||||||
|
"chunk_id": cid,
|
||||||
|
# WP-Fix: Variant=sec sorgt für eindeutige ID pro Sektion
|
||||||
|
"edge_id": _mk_edge_id(k, cid, t, "chunk", "inline:rel", variant=sec),
|
||||||
|
"provenance": "explicit", "rule_id": "inline:rel", "confidence": PROVENANCE_PRIORITY["inline:rel"]
|
||||||
|
}
|
||||||
|
if sec: payload["target_section"] = sec
|
||||||
|
edges.append(_edge(k, "chunk", cid, t, note_id, payload))
|
||||||
|
|
||||||
|
# B. Candidate Pool (WP-15b Validierte KI-Kanten)
|
||||||
|
pool = ch.get("candidate_pool") or ch.get("candidate_edges") or []
|
||||||
|
for cand in pool:
|
||||||
|
raw_t, k, p = cand.get("to"), cand.get("kind", "related_to"), cand.get("provenance", "semantic_ai")
|
||||||
|
t, sec = parse_link_target(raw_t, note_id)
|
||||||
|
if t:
|
||||||
|
payload = {
|
||||||
|
"chunk_id": cid,
|
||||||
|
"edge_id": _mk_edge_id(k, cid, t, "chunk", f"candidate:{p}", variant=sec),
|
||||||
|
"provenance": p, "rule_id": f"candidate:{p}", "confidence": PROVENANCE_PRIORITY.get(p, 0.90)
|
||||||
|
}
|
||||||
|
if sec: payload["target_section"] = sec
|
||||||
|
edges.append(_edge(k, "chunk", cid, t, note_id, payload))
|
||||||
|
|
||||||
|
# C. Callouts (> [!edge])
|
||||||
|
call_pairs, rem2 = extract_callout_relations(rem)
|
||||||
|
for k, raw_t in call_pairs:
|
||||||
|
t, sec = parse_link_target(raw_t, note_id)
|
||||||
|
if not t: continue
|
||||||
|
|
||||||
|
payload = {
|
||||||
|
"chunk_id": cid,
|
||||||
|
"edge_id": _mk_edge_id(k, cid, t, "chunk", "callout:edge", variant=sec),
|
||||||
|
"provenance": "explicit", "rule_id": "callout:edge", "confidence": PROVENANCE_PRIORITY["callout:edge"]
|
||||||
|
}
|
||||||
|
if sec: payload["target_section"] = sec
|
||||||
|
edges.append(_edge(k, "chunk", cid, t, note_id, payload))
|
||||||
|
|
||||||
|
# D. Standard Wikilinks & Typ-Defaults
|
||||||
|
refs = extract_wikilinks(rem2)
|
||||||
|
for raw_r in refs:
|
||||||
|
r, sec = parse_link_target(raw_r, note_id)
|
||||||
|
if not r: continue
|
||||||
|
|
||||||
|
payload = {
|
||||||
|
"chunk_id": cid, "ref_text": raw_r,
|
||||||
|
"edge_id": _mk_edge_id("references", cid, r, "chunk", "explicit:wikilink", variant=sec),
|
||||||
|
"provenance": "explicit", "rule_id": "explicit:wikilink", "confidence": PROVENANCE_PRIORITY["explicit:wikilink"]
|
||||||
|
}
|
||||||
|
if sec: payload["target_section"] = sec
|
||||||
|
edges.append(_edge("references", "chunk", cid, r, note_id, payload))
|
||||||
|
|
||||||
|
# Automatische Kanten-Vererbung aus types.yaml
|
||||||
|
for rel in defaults:
|
||||||
|
if rel != "references":
|
||||||
|
def_payload = {
|
||||||
|
"chunk_id": cid,
|
||||||
|
"edge_id": _mk_edge_id(rel, cid, r, "chunk", f"edge_defaults:{rel}", variant=sec),
|
||||||
|
"provenance": "rule", "rule_id": f"edge_defaults:{rel}", "confidence": PROVENANCE_PRIORITY["edge_defaults"]
|
||||||
|
}
|
||||||
|
if sec: def_payload["target_section"] = sec
|
||||||
|
edges.append(_edge(rel, "chunk", cid, r, note_id, def_payload))
|
||||||
|
|
||||||
|
refs_all.extend([parse_link_target(r, note_id)[0] for r in refs])
|
||||||
|
|
||||||
|
# 3) Note-Scope (Grobe Struktur-Verbindungen)
|
||||||
|
if include_note_scope_refs:
|
||||||
|
cleaned_note_refs = [parse_link_target(r, note_id)[0] for r in (note_level_references or [])]
|
||||||
|
refs_note = _dedupe_seq((refs_all or []) + cleaned_note_refs)
|
||||||
|
|
||||||
|
for r in refs_note:
|
||||||
|
if not r: continue
|
||||||
|
edges.append(_edge("references", "note", note_id, r, note_id, {
|
||||||
|
"edge_id": _mk_edge_id("references", note_id, r, "note", "explicit:note_scope"),
|
||||||
|
"provenance": "explicit", "confidence": PROVENANCE_PRIORITY["explicit:note_scope"]
|
||||||
|
}))
|
||||||
|
# Backlinks zur Stärkung der Bidirektionalität
|
||||||
|
edges.append(_edge("backlink", "note", r, note_id, note_id, {
|
||||||
|
"edge_id": _mk_edge_id("backlink", r, note_id, "note", "derived:backlink"),
|
||||||
|
"provenance": "rule", "confidence": PROVENANCE_PRIORITY["derived:backlink"]
|
||||||
|
}))
|
||||||
|
|
||||||
|
# 4) De-Duplizierung (In-Place)
|
||||||
|
# Da die EDGE-ID nun die Sektion (variant) enthält, bleiben Links auf
|
||||||
|
# unterschiedliche Abschnitte derselben Note erhalten.
|
||||||
|
unique_map: Dict[str, dict] = {}
|
||||||
|
for e in edges:
|
||||||
|
eid = e["edge_id"]
|
||||||
|
# Höhere Confidence gewinnt bei identischer ID
|
||||||
|
if eid not in unique_map or e.get("confidence", 0) > unique_map[eid].get("confidence", 0):
|
||||||
|
unique_map[eid] = e
|
||||||
|
|
||||||
|
return list(unique_map.values())
|
||||||
@@ -0,0 +1,127 @@
|
|||||||
|
"""
|
||||||
|
FILE: app/core/graph/graph_extractors.py
|
||||||
|
DESCRIPTION: Regex-basierte Extraktion von Relationen aus Text.
|
||||||
|
AUDIT:
|
||||||
|
- Regex für Wikilinks liberalisiert (Umlaute, Sonderzeichen).
|
||||||
|
- Callout-Parser erweitert für Multi-Line-Listen und Header-Typen.
|
||||||
|
"""
|
||||||
|
import re
|
||||||
|
from typing import List, Tuple
|
||||||
|
|
||||||
|
# Erlaube alle Zeichen außer ']' im Target (fängt Umlaute, Emojis, '&', '#' ab)
|
||||||
|
_WIKILINK_RE = re.compile(r"\[\[(?:[^\|\]]+\|)?([^\]]+)\]\]")
|
||||||
|
|
||||||
|
_REL_PIPE = re.compile(r"\[\[\s*rel:(?P<kind>[a-z_]+)\s*\|\s*(?P<target>[^\]]+?)\s*\]\]", re.IGNORECASE)
|
||||||
|
_REL_SPACE = re.compile(r"\[\[\s*rel:(?P<kind>[a-z_]+)\s+(?P<target>[^\]]+?)\s*\]\]", re.IGNORECASE)
|
||||||
|
_REL_TEXT = re.compile(r"rel\s*:\s*(?P<kind>[a-z_]+)\s*\[\[\s*(?P<target>[^\]]+?)\s*\]\]", re.IGNORECASE)
|
||||||
|
|
||||||
|
_CALLOUT_START = re.compile(r"^\s*>\s*\[!edge\]\s*(.*)$", re.IGNORECASE)
|
||||||
|
# Erkennt "kind: targets..."
|
||||||
|
_REL_LINE = re.compile(r"^(?P<kind>[a-z_]+)\s*:\s*(?P<targets>.+?)\s*$", re.IGNORECASE)
|
||||||
|
# Erkennt reine Typen (z.B. "depends_on" im Header)
|
||||||
|
_SIMPLE_KIND = re.compile(r"^[a-z_]+$", re.IGNORECASE)
|
||||||
|
|
||||||
|
def extract_typed_relations(text: str) -> Tuple[List[Tuple[str, str]], str]:
|
||||||
|
"""
|
||||||
|
Findet Inline-Relationen wie [[rel:depends_on Target]].
|
||||||
|
Gibt (Liste[(kind, target)], bereinigter_text) zurück.
|
||||||
|
"""
|
||||||
|
if not text: return [], ""
|
||||||
|
pairs = []
|
||||||
|
def _collect(m):
|
||||||
|
k, t = m.group("kind").strip().lower(), m.group("target").strip()
|
||||||
|
pairs.append((k, t))
|
||||||
|
return ""
|
||||||
|
text = _REL_PIPE.sub(_collect, text)
|
||||||
|
text = _REL_SPACE.sub(_collect, text)
|
||||||
|
text = _REL_TEXT.sub(_collect, text)
|
||||||
|
return pairs, text
|
||||||
|
|
||||||
|
def extract_callout_relations(text: str) -> Tuple[List[Tuple[str,str]], str]:
|
||||||
|
"""
|
||||||
|
Verarbeitet Obsidian [!edge]-Callouts.
|
||||||
|
Unterstützt zwei Formate:
|
||||||
|
1. Explizit: "kind: [[Target]]"
|
||||||
|
2. Implizit (Header): "> [!edge] kind" gefolgt von "[[Target]]" Zeilen
|
||||||
|
"""
|
||||||
|
if not text: return [], text
|
||||||
|
lines = text.splitlines()
|
||||||
|
out_pairs = []
|
||||||
|
keep_lines = []
|
||||||
|
i = 0
|
||||||
|
|
||||||
|
while i < len(lines):
|
||||||
|
line = lines[i]
|
||||||
|
m = _CALLOUT_START.match(line)
|
||||||
|
if not m:
|
||||||
|
keep_lines.append(line)
|
||||||
|
i += 1
|
||||||
|
continue
|
||||||
|
|
||||||
|
# Callout-Block gefunden. Wir sammeln alle relevanten Zeilen.
|
||||||
|
block_lines = []
|
||||||
|
|
||||||
|
# Header Content prüfen (z.B. "type" aus "> [!edge] type")
|
||||||
|
header_raw = m.group(1).strip()
|
||||||
|
if header_raw:
|
||||||
|
block_lines.append(header_raw)
|
||||||
|
|
||||||
|
i += 1
|
||||||
|
while i < len(lines) and lines[i].lstrip().startswith('>'):
|
||||||
|
# Entferne '>' und führende Leerzeichen
|
||||||
|
content = lines[i].lstrip()[1:].lstrip()
|
||||||
|
if content:
|
||||||
|
block_lines.append(content)
|
||||||
|
i += 1
|
||||||
|
|
||||||
|
# Verarbeitung des Blocks
|
||||||
|
current_kind = None
|
||||||
|
|
||||||
|
# Heuristik: Ist die allererste Zeile (meist aus dem Header) ein reiner Typ?
|
||||||
|
# Dann setzen wir diesen als Default für den Block.
|
||||||
|
if block_lines:
|
||||||
|
first = block_lines[0]
|
||||||
|
# Wenn es NICHT wie "Key: Value" aussieht, aber wie ein Wort:
|
||||||
|
if not _REL_LINE.match(first) and _SIMPLE_KIND.match(first):
|
||||||
|
current_kind = first.lower()
|
||||||
|
|
||||||
|
for bl in block_lines:
|
||||||
|
# 1. Prüfen auf explizites "Kind: Targets" (überschreibt Header-Typ für diese Zeile)
|
||||||
|
mrel = _REL_LINE.match(bl)
|
||||||
|
if mrel:
|
||||||
|
line_kind = mrel.group("kind").strip().lower()
|
||||||
|
targets = mrel.group("targets")
|
||||||
|
|
||||||
|
# Links extrahieren
|
||||||
|
found = _WIKILINK_RE.findall(targets)
|
||||||
|
if found:
|
||||||
|
for t in found: out_pairs.append((line_kind, t.strip()))
|
||||||
|
else:
|
||||||
|
# Fallback für kommagetrennten Plaintext
|
||||||
|
for raw in re.split(r"[,;]", targets):
|
||||||
|
if raw.strip(): out_pairs.append((line_kind, raw.strip()))
|
||||||
|
|
||||||
|
# Wenn wir eine explizite Zeile gefunden haben, aktualisieren wir NICHT
|
||||||
|
# den current_kind für nachfolgende Zeilen (Design-Entscheidung: lokal scope),
|
||||||
|
# oder wir machen es doch?
|
||||||
|
# Üblicher ist: Header setzt Default, Zeile überschreibt lokal.
|
||||||
|
# Wir lassen current_kind also unangetastet.
|
||||||
|
continue
|
||||||
|
|
||||||
|
# 2. Kein Key:Value Muster -> Prüfen auf Links, die den current_kind nutzen
|
||||||
|
found = _WIKILINK_RE.findall(bl)
|
||||||
|
if found:
|
||||||
|
if current_kind:
|
||||||
|
for t in found: out_pairs.append((current_kind, t.strip()))
|
||||||
|
else:
|
||||||
|
# Link ohne Typ und ohne Header-Typ.
|
||||||
|
# Wird ignoriert oder könnte als 'related_to' fallback dienen.
|
||||||
|
# Aktuell: Ignorieren, um False Positives zu vermeiden.
|
||||||
|
pass
|
||||||
|
|
||||||
|
return out_pairs, "\n".join(keep_lines)
|
||||||
|
|
||||||
|
def extract_wikilinks(text: str) -> List[str]:
|
||||||
|
"""Findet Standard-Wikilinks [[Target]] oder [[Alias|Target]]."""
|
||||||
|
if not text: return []
|
||||||
|
return [m.strip() for m in _WIKILINK_RE.findall(text) if m.strip()]
|
||||||
@@ -0,0 +1,156 @@
|
|||||||
|
"""
|
||||||
|
FILE: app/core/graph/graph_subgraph.py
|
||||||
|
DESCRIPTION: In-Memory Repräsentation eines Graphen für Scoring und Analyse.
|
||||||
|
Zentrale Komponente für die Graph-Expansion (BFS) und Bonus-Berechnung.
|
||||||
|
WP-15c Update: Erhalt von Metadaten (target_section, provenance)
|
||||||
|
für präzises Retrieval-Reasoning.
|
||||||
|
VERSION: 1.2.0
|
||||||
|
STATUS: Active
|
||||||
|
"""
|
||||||
|
import math
|
||||||
|
from collections import defaultdict
|
||||||
|
from typing import Dict, List, Optional, DefaultDict, Any, Set
|
||||||
|
from qdrant_client import QdrantClient
|
||||||
|
|
||||||
|
# Lokale Paket-Imports
|
||||||
|
from .graph_weights import EDGE_BASE_WEIGHTS, calculate_edge_weight
|
||||||
|
from .graph_db_adapter import fetch_edges_from_qdrant
|
||||||
|
|
||||||
|
class Subgraph:
|
||||||
|
"""
|
||||||
|
Leichtgewichtiger Subgraph mit Adjazenzlisten & Kennzahlen.
|
||||||
|
Wird für die Berechnung von Graph-Boni im Retriever genutzt.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self) -> None:
|
||||||
|
# adj speichert nun vollständige Payloads statt nur Tripel
|
||||||
|
self.adj: DefaultDict[str, List[Dict]] = defaultdict(list)
|
||||||
|
self.reverse_adj: DefaultDict[str, List[Dict]] = defaultdict(list)
|
||||||
|
self.in_degree: DefaultDict[str, int] = defaultdict(int)
|
||||||
|
self.out_degree: DefaultDict[str, int] = defaultdict(int)
|
||||||
|
|
||||||
|
def add_edge(self, e: Dict) -> None:
|
||||||
|
"""
|
||||||
|
Fügt eine Kante hinzu und aktualisiert Indizes.
|
||||||
|
WP-15c: Speichert das vollständige Payload für den Explanation Layer.
|
||||||
|
"""
|
||||||
|
src = e.get("source")
|
||||||
|
tgt = e.get("target")
|
||||||
|
kind = e.get("kind")
|
||||||
|
|
||||||
|
# Das gesamte Payload wird als Kanten-Objekt behalten
|
||||||
|
# Wir stellen sicher, dass alle relevanten Metadaten vorhanden sind
|
||||||
|
edge_data = {
|
||||||
|
"source": src,
|
||||||
|
"target": tgt,
|
||||||
|
"kind": kind,
|
||||||
|
"weight": e.get("weight", EDGE_BASE_WEIGHTS.get(kind, 0.0)),
|
||||||
|
"provenance": e.get("provenance", "rule"),
|
||||||
|
"confidence": e.get("confidence", 1.0),
|
||||||
|
"target_section": e.get("target_section"), # Essentiell für Präzision
|
||||||
|
"is_super_edge": e.get("is_super_edge", False)
|
||||||
|
}
|
||||||
|
|
||||||
|
owner = e.get("note_id")
|
||||||
|
|
||||||
|
if not src or not tgt:
|
||||||
|
return
|
||||||
|
|
||||||
|
# 1. Forward-Kante
|
||||||
|
self.adj[src].append(edge_data)
|
||||||
|
self.out_degree[src] += 1
|
||||||
|
self.in_degree[tgt] += 1
|
||||||
|
|
||||||
|
# 2. Reverse-Kante (für Explanation Layer & Backlinks)
|
||||||
|
self.reverse_adj[tgt].append(edge_data)
|
||||||
|
|
||||||
|
# 3. Kontext-Note Handling (erhöht die Zentralität der Parent-Note)
|
||||||
|
if owner and owner != src:
|
||||||
|
# Wir erstellen eine virtuelle Kontext-Kante
|
||||||
|
ctx_edge = edge_data.copy()
|
||||||
|
ctx_edge["source"] = owner
|
||||||
|
ctx_edge["via_context"] = True
|
||||||
|
|
||||||
|
self.adj[owner].append(ctx_edge)
|
||||||
|
self.out_degree[owner] += 1
|
||||||
|
if owner != tgt:
|
||||||
|
self.reverse_adj[tgt].append(ctx_edge)
|
||||||
|
self.in_degree[owner] += 1
|
||||||
|
|
||||||
|
def aggregate_edge_bonus(self, node_id: str) -> float:
|
||||||
|
"""Summe der ausgehenden Kantengewichte (Hub-Score)."""
|
||||||
|
return sum(edge["weight"] for edge in self.adj.get(node_id, []))
|
||||||
|
|
||||||
|
def edge_bonus(self, node_id: str) -> float:
|
||||||
|
"""API für Retriever (WP-04a Kompatibilität)."""
|
||||||
|
return self.aggregate_edge_bonus(node_id)
|
||||||
|
|
||||||
|
def centrality_bonus(self, node_id: str) -> float:
|
||||||
|
"""
|
||||||
|
Log-gedämpfte Zentralität basierend auf dem In-Degree.
|
||||||
|
Begrenzt auf einen maximalen Boost von 0.15.
|
||||||
|
"""
|
||||||
|
indeg = self.in_degree.get(node_id, 0)
|
||||||
|
if indeg <= 0:
|
||||||
|
return 0.0
|
||||||
|
# math.log1p(x) entspricht log(1+x)
|
||||||
|
return min(math.log1p(indeg) / 10.0, 0.15)
|
||||||
|
|
||||||
|
def get_outgoing_edges(self, node_id: str) -> List[Dict[str, Any]]:
|
||||||
|
"""Gibt alle ausgehenden Kanten einer Node inkl. Metadaten zurück."""
|
||||||
|
return self.adj.get(node_id, [])
|
||||||
|
|
||||||
|
def get_incoming_edges(self, node_id: str) -> List[Dict[str, Any]]:
|
||||||
|
"""Gibt alle eingehenden Kanten einer Node inkl. Metadaten zurück."""
|
||||||
|
return self.reverse_adj.get(node_id, [])
|
||||||
|
|
||||||
|
|
||||||
|
def expand(
|
||||||
|
client: QdrantClient,
|
||||||
|
prefix: str,
|
||||||
|
seeds: List[str],
|
||||||
|
depth: int = 1,
|
||||||
|
edge_types: Optional[List[str]] = None,
|
||||||
|
) -> Subgraph:
|
||||||
|
"""
|
||||||
|
Expandiert ab Seeds entlang von Edges bis zu einer bestimmten Tiefe.
|
||||||
|
Nutzt fetch_edges_from_qdrant für den Datenbankzugriff.
|
||||||
|
"""
|
||||||
|
sg = Subgraph()
|
||||||
|
frontier = set(seeds)
|
||||||
|
visited = set()
|
||||||
|
|
||||||
|
for _ in range(max(depth, 0)):
|
||||||
|
if not frontier:
|
||||||
|
break
|
||||||
|
|
||||||
|
# Batch-Abfrage der Kanten für die aktuelle Ebene
|
||||||
|
payloads = fetch_edges_from_qdrant(client, prefix, list(frontier), edge_types)
|
||||||
|
next_frontier: Set[str] = set()
|
||||||
|
|
||||||
|
for pl in payloads:
|
||||||
|
src, tgt = pl.get("source_id"), pl.get("target_id")
|
||||||
|
if not src or not tgt: continue
|
||||||
|
|
||||||
|
# WP-15c: Wir übergeben das vollständige Payload an add_edge
|
||||||
|
edge_payload = {
|
||||||
|
"source": src,
|
||||||
|
"target": tgt,
|
||||||
|
"kind": pl.get("kind", "edge"),
|
||||||
|
"weight": calculate_edge_weight(pl),
|
||||||
|
"note_id": pl.get("note_id"),
|
||||||
|
"provenance": pl.get("provenance", "rule"),
|
||||||
|
"confidence": pl.get("confidence", 1.0),
|
||||||
|
"target_section": pl.get("target_section")
|
||||||
|
}
|
||||||
|
|
||||||
|
sg.add_edge(edge_payload)
|
||||||
|
|
||||||
|
# BFS Logik: Neue Ziele in die nächste Frontier aufnehmen
|
||||||
|
if tgt not in visited:
|
||||||
|
next_frontier.add(str(tgt))
|
||||||
|
|
||||||
|
visited |= frontier
|
||||||
|
frontier = next_frontier - visited
|
||||||
|
|
||||||
|
return sg
|
||||||
@@ -0,0 +1,112 @@
|
|||||||
|
"""
|
||||||
|
FILE: app/core/graph/graph_utils.py
|
||||||
|
DESCRIPTION: Basale Werkzeuge, ID-Generierung und Provenance-Konfiguration für den Graphen.
|
||||||
|
AUDIT: Erweitert um parse_link_target für sauberes Section-Splitting (WP-Fix).
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import hashlib
|
||||||
|
from typing import Iterable, List, Optional, Set, Any, Tuple
|
||||||
|
|
||||||
|
try:
|
||||||
|
import yaml
|
||||||
|
except ImportError:
|
||||||
|
yaml = None
|
||||||
|
|
||||||
|
# WP-15b: Prioritäten-Ranking für die De-Duplizierung
|
||||||
|
PROVENANCE_PRIORITY = {
|
||||||
|
"explicit:wikilink": 1.00,
|
||||||
|
"inline:rel": 0.95,
|
||||||
|
"callout:edge": 0.90,
|
||||||
|
"semantic_ai": 0.90, # Validierte KI-Kanten
|
||||||
|
"structure:belongs_to": 1.00,
|
||||||
|
"structure:order": 0.95, # next/prev
|
||||||
|
"explicit:note_scope": 1.00,
|
||||||
|
"derived:backlink": 0.90,
|
||||||
|
"edge_defaults": 0.70 # Heuristik (types.yaml)
|
||||||
|
}
|
||||||
|
|
||||||
|
def _get(d: dict, *keys, default=None):
|
||||||
|
"""Sicherer Zugriff auf verschachtelte Keys."""
|
||||||
|
for k in keys:
|
||||||
|
if isinstance(d, dict) and k in d and d[k] is not None:
|
||||||
|
return d[k]
|
||||||
|
return default
|
||||||
|
|
||||||
|
def _dedupe_seq(seq: Iterable[str]) -> List[str]:
|
||||||
|
"""Dedupliziert Strings unter Beibehaltung der Reihenfolge."""
|
||||||
|
seen: Set[str] = set()
|
||||||
|
out: List[str] = []
|
||||||
|
for s in seq:
|
||||||
|
if s not in seen:
|
||||||
|
seen.add(s); out.append(s)
|
||||||
|
return out
|
||||||
|
|
||||||
|
def _mk_edge_id(kind: str, s: str, t: str, scope: str, rule_id: Optional[str] = None, variant: Optional[str] = None) -> str:
|
||||||
|
"""
|
||||||
|
Erzeugt eine deterministische 12-Byte ID mittels BLAKE2s.
|
||||||
|
|
||||||
|
WP-Fix: 'variant' (z.B. Section) fließt in den Hash ein, um mehrere Kanten
|
||||||
|
zum gleichen Target-Node (aber unterschiedlichen Abschnitten) zu unterscheiden.
|
||||||
|
"""
|
||||||
|
base = f"{kind}:{s}->{t}#{scope}"
|
||||||
|
if rule_id:
|
||||||
|
base += f"|{rule_id}"
|
||||||
|
if variant:
|
||||||
|
base += f"|{variant}" # <--- Hier entsteht die Eindeutigkeit für verschiedene Sections
|
||||||
|
|
||||||
|
return hashlib.blake2s(base.encode("utf-8"), digest_size=12).hexdigest()
|
||||||
|
|
||||||
|
def _edge(kind: str, scope: str, source_id: str, target_id: str, note_id: str, extra: Optional[dict] = None) -> dict:
|
||||||
|
"""Konstruiert ein Kanten-Payload für Qdrant."""
|
||||||
|
pl = {
|
||||||
|
"kind": kind,
|
||||||
|
"relation": kind,
|
||||||
|
"scope": scope,
|
||||||
|
"source_id": source_id,
|
||||||
|
"target_id": target_id,
|
||||||
|
"note_id": note_id,
|
||||||
|
}
|
||||||
|
if extra: pl.update(extra)
|
||||||
|
return pl
|
||||||
|
|
||||||
|
def parse_link_target(raw: str, current_note_id: Optional[str] = None) -> Tuple[str, Optional[str]]:
|
||||||
|
"""
|
||||||
|
Zerlegt einen Link (z.B. 'Note#Section') in Target-ID und Section.
|
||||||
|
Behandelt Self-Links ('#Section'), indem current_note_id eingesetzt wird.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
(target_id, target_section)
|
||||||
|
"""
|
||||||
|
if not raw:
|
||||||
|
return "", None
|
||||||
|
|
||||||
|
parts = raw.split("#", 1)
|
||||||
|
target = parts[0].strip()
|
||||||
|
section = parts[1].strip() if len(parts) > 1 else None
|
||||||
|
|
||||||
|
# Handle Self-Link [[#Section]] -> target wird zu current_note_id
|
||||||
|
if not target and section and current_note_id:
|
||||||
|
target = current_note_id
|
||||||
|
|
||||||
|
return target, section
|
||||||
|
|
||||||
|
def load_types_registry() -> dict:
|
||||||
|
"""Lädt die YAML-Registry."""
|
||||||
|
p = os.getenv("MINDNET_TYPES_FILE", "./config/types.yaml")
|
||||||
|
if not os.path.isfile(p) or yaml is None: return {}
|
||||||
|
try:
|
||||||
|
with open(p, "r", encoding="utf-8") as f: return yaml.safe_load(f) or {}
|
||||||
|
except Exception: return {}
|
||||||
|
|
||||||
|
def get_edge_defaults_for(note_type: Optional[str], reg: dict) -> List[str]:
|
||||||
|
"""Ermittelt Standard-Kanten für einen Typ."""
|
||||||
|
types_map = reg.get("types", reg) if isinstance(reg, dict) else {}
|
||||||
|
if note_type and isinstance(types_map, dict):
|
||||||
|
t = types_map.get(note_type)
|
||||||
|
if isinstance(t, dict) and isinstance(t.get("edge_defaults"), list):
|
||||||
|
return [str(x) for x in t["edge_defaults"] if isinstance(x, str)]
|
||||||
|
for key in ("defaults", "default", "global"):
|
||||||
|
v = reg.get(key)
|
||||||
|
if isinstance(v, dict) and isinstance(v.get("edge_defaults"), list):
|
||||||
|
return [str(x) for x in v["edge_defaults"] if isinstance(x, str)]
|
||||||
|
return []
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
"""
|
||||||
|
FILE: app/core/graph/graph_weights.py
|
||||||
|
DESCRIPTION: Definition der Basisgewichte und Berechnung der Kanteneffektivität.
|
||||||
|
"""
|
||||||
|
from typing import Dict
|
||||||
|
|
||||||
|
# Basisgewichte je Edge-Typ (WP-04a Config)
|
||||||
|
EDGE_BASE_WEIGHTS: Dict[str, float] = {
|
||||||
|
# Struktur
|
||||||
|
"belongs_to": 0.10,
|
||||||
|
"next": 0.06,
|
||||||
|
"prev": 0.06,
|
||||||
|
"backlink": 0.04,
|
||||||
|
"references_at": 0.08,
|
||||||
|
|
||||||
|
# Wissen
|
||||||
|
"references": 0.20,
|
||||||
|
"depends_on": 0.18,
|
||||||
|
"related_to": 0.15,
|
||||||
|
"similar_to": 0.12,
|
||||||
|
}
|
||||||
|
|
||||||
|
def calculate_edge_weight(pl: Dict) -> float:
|
||||||
|
"""Berechnet das effektive Edge-Gewicht aus kind + confidence."""
|
||||||
|
kind = pl.get("kind", "edge")
|
||||||
|
base = EDGE_BASE_WEIGHTS.get(kind, 0.0)
|
||||||
|
|
||||||
|
conf_raw = pl.get("confidence", None)
|
||||||
|
try:
|
||||||
|
conf = float(conf_raw) if conf_raw is not None else None
|
||||||
|
except Exception:
|
||||||
|
conf = None
|
||||||
|
|
||||||
|
if conf is None:
|
||||||
|
return base
|
||||||
|
|
||||||
|
# Clamp confidence 0.0 - 1.0
|
||||||
|
conf = max(0.0, min(1.0, conf))
|
||||||
|
return base * conf
|
||||||
@@ -1,249 +0,0 @@
|
|||||||
"""
|
|
||||||
FILE: app/core/graph_adapter.py
|
|
||||||
DESCRIPTION: Lädt Kanten aus Qdrant und baut einen In-Memory Subgraphen für Scoring (Centrality) und Explanation.
|
|
||||||
VERSION: 0.4.0
|
|
||||||
STATUS: Active
|
|
||||||
DEPENDENCIES: qdrant_client, app.core.qdrant
|
|
||||||
LAST_ANALYSIS: 2025-12-15
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
from typing import Dict, List, Optional, DefaultDict, Any
|
|
||||||
from collections import defaultdict
|
|
||||||
|
|
||||||
from qdrant_client import QdrantClient
|
|
||||||
from qdrant_client.http import models as rest
|
|
||||||
|
|
||||||
from app.core.qdrant import collection_names
|
|
||||||
|
|
||||||
# Legacy-Import Fallback
|
|
||||||
try: # pragma: no cover
|
|
||||||
from app.core.qdrant_points import get_edges_for_sources # type: ignore
|
|
||||||
except Exception: # pragma: no cover
|
|
||||||
get_edges_for_sources = None # type: ignore
|
|
||||||
|
|
||||||
|
|
||||||
# Basisgewichte je Edge-Typ (WP-04a Config)
|
|
||||||
EDGE_BASE_WEIGHTS: Dict[str, float] = {
|
|
||||||
# Struktur
|
|
||||||
"belongs_to": 0.10,
|
|
||||||
"next": 0.06,
|
|
||||||
"prev": 0.06,
|
|
||||||
"backlink": 0.04,
|
|
||||||
"references_at": 0.08,
|
|
||||||
|
|
||||||
# Wissen
|
|
||||||
"references": 0.20,
|
|
||||||
"depends_on": 0.18,
|
|
||||||
"related_to": 0.15,
|
|
||||||
"similar_to": 0.12,
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def _edge_weight(pl: Dict) -> float:
|
|
||||||
"""Berechnet das effektive Edge-Gewicht aus kind + confidence."""
|
|
||||||
kind = pl.get("kind", "edge")
|
|
||||||
base = EDGE_BASE_WEIGHTS.get(kind, 0.0)
|
|
||||||
|
|
||||||
conf_raw = pl.get("confidence", None)
|
|
||||||
try:
|
|
||||||
conf = float(conf_raw) if conf_raw is not None else None
|
|
||||||
except Exception:
|
|
||||||
conf = None
|
|
||||||
|
|
||||||
if conf is None:
|
|
||||||
return base
|
|
||||||
|
|
||||||
if conf < 0.0: conf = 0.0
|
|
||||||
if conf > 1.0: conf = 1.0
|
|
||||||
|
|
||||||
return base * conf
|
|
||||||
|
|
||||||
|
|
||||||
def _fetch_edges(
|
|
||||||
client: QdrantClient,
|
|
||||||
prefix: str,
|
|
||||||
seeds: List[str],
|
|
||||||
edge_types: Optional[List[str]] = None,
|
|
||||||
limit: int = 2048,
|
|
||||||
) -> List[Dict]:
|
|
||||||
"""
|
|
||||||
Holt Edges direkt aus der *_edges Collection.
|
|
||||||
Filter: source_id IN seeds OR target_id IN seeds OR note_id IN seeds
|
|
||||||
"""
|
|
||||||
if not seeds or limit <= 0:
|
|
||||||
return []
|
|
||||||
|
|
||||||
_, _, edges_col = collection_names(prefix)
|
|
||||||
|
|
||||||
seed_conditions = []
|
|
||||||
for field in ("source_id", "target_id", "note_id"):
|
|
||||||
for s in seeds:
|
|
||||||
seed_conditions.append(
|
|
||||||
rest.FieldCondition(key=field, match=rest.MatchValue(value=str(s)))
|
|
||||||
)
|
|
||||||
seeds_filter = rest.Filter(should=seed_conditions) if seed_conditions else None
|
|
||||||
|
|
||||||
type_filter = None
|
|
||||||
if edge_types:
|
|
||||||
type_conds = [
|
|
||||||
rest.FieldCondition(key="kind", match=rest.MatchValue(value=str(k)))
|
|
||||||
for k in edge_types
|
|
||||||
]
|
|
||||||
type_filter = rest.Filter(should=type_conds)
|
|
||||||
|
|
||||||
must = []
|
|
||||||
if seeds_filter: must.append(seeds_filter)
|
|
||||||
if type_filter: must.append(type_filter)
|
|
||||||
|
|
||||||
flt = rest.Filter(must=must) if must else None
|
|
||||||
|
|
||||||
pts, _ = client.scroll(
|
|
||||||
collection_name=edges_col,
|
|
||||||
scroll_filter=flt,
|
|
||||||
limit=limit,
|
|
||||||
with_payload=True,
|
|
||||||
with_vectors=False,
|
|
||||||
)
|
|
||||||
|
|
||||||
out: List[Dict] = []
|
|
||||||
for p in pts or []:
|
|
||||||
pl = dict(p.payload or {})
|
|
||||||
if pl:
|
|
||||||
out.append(pl)
|
|
||||||
return out
|
|
||||||
|
|
||||||
|
|
||||||
class Subgraph:
|
|
||||||
"""Leichtgewichtiger Subgraph mit Adjazenzlisten & Kennzahlen."""
|
|
||||||
|
|
||||||
def __init__(self) -> None:
|
|
||||||
# Forward: source -> [targets]
|
|
||||||
self.adj: DefaultDict[str, List[Dict]] = defaultdict(list)
|
|
||||||
# Reverse: target -> [sources] (Neu für WP-04b Explanation)
|
|
||||||
self.reverse_adj: DefaultDict[str, List[Dict]] = defaultdict(list)
|
|
||||||
|
|
||||||
self.in_degree: DefaultDict[str, int] = defaultdict(int)
|
|
||||||
self.out_degree: DefaultDict[str, int] = defaultdict(int)
|
|
||||||
|
|
||||||
def add_edge(self, e: Dict) -> None:
|
|
||||||
"""
|
|
||||||
Fügt eine Kante hinzu und aktualisiert Forward/Reverse Indizes.
|
|
||||||
e muss enthalten: source, target, kind, weight.
|
|
||||||
"""
|
|
||||||
src = e.get("source")
|
|
||||||
tgt = e.get("target")
|
|
||||||
kind = e.get("kind")
|
|
||||||
weight = e.get("weight", EDGE_BASE_WEIGHTS.get(kind, 0.0))
|
|
||||||
owner = e.get("note_id")
|
|
||||||
|
|
||||||
if not src or not tgt:
|
|
||||||
return
|
|
||||||
|
|
||||||
# 1. Primäre Adjazenz (Forward)
|
|
||||||
edge_data = {"target": tgt, "kind": kind, "weight": weight}
|
|
||||||
self.adj[src].append(edge_data)
|
|
||||||
self.out_degree[src] += 1
|
|
||||||
self.in_degree[tgt] += 1
|
|
||||||
|
|
||||||
# 2. Reverse Adjazenz (Neu für Explanation)
|
|
||||||
# Wir speichern, woher die Kante kam.
|
|
||||||
rev_data = {"source": src, "kind": kind, "weight": weight}
|
|
||||||
self.reverse_adj[tgt].append(rev_data)
|
|
||||||
|
|
||||||
# 3. Kontext-Note Handling (Forward & Reverse)
|
|
||||||
# Wenn eine Kante "im Kontext einer Note" (owner) definiert ist,
|
|
||||||
# schreiben wir sie der Note gut, damit der Retriever Scores auf Note-Ebene findet.
|
|
||||||
if owner and owner != src:
|
|
||||||
# Forward: Owner -> Target
|
|
||||||
self.adj[owner].append(edge_data)
|
|
||||||
self.out_degree[owner] += 1
|
|
||||||
|
|
||||||
# Reverse: Target wird vom Owner referenziert (indirekt)
|
|
||||||
if owner != tgt:
|
|
||||||
rev_owner_data = {"source": owner, "kind": kind, "weight": weight, "via_context": True}
|
|
||||||
self.reverse_adj[tgt].append(rev_owner_data)
|
|
||||||
self.in_degree[owner] += 1 # Leichter Centrality Boost für den Owner
|
|
||||||
|
|
||||||
def aggregate_edge_bonus(self, node_id: str) -> float:
|
|
||||||
"""Summe der ausgehenden Kantengewichte (Hub-Score)."""
|
|
||||||
return sum(edge["weight"] for edge in self.adj.get(node_id, []))
|
|
||||||
|
|
||||||
def edge_bonus(self, node_id: str) -> float:
|
|
||||||
"""API für Retriever (WP-04a Kompatibilität)."""
|
|
||||||
return self.aggregate_edge_bonus(node_id)
|
|
||||||
|
|
||||||
def centrality_bonus(self, node_id: str) -> float:
|
|
||||||
"""Log-gedämpfte Zentralität (In-Degree)."""
|
|
||||||
import math
|
|
||||||
indeg = self.in_degree.get(node_id, 0)
|
|
||||||
if indeg <= 0:
|
|
||||||
return 0.0
|
|
||||||
return min(math.log1p(indeg) / 10.0, 0.15)
|
|
||||||
|
|
||||||
# --- WP-04b Explanation Helpers ---
|
|
||||||
|
|
||||||
def get_outgoing_edges(self, node_id: str) -> List[Dict[str, Any]]:
|
|
||||||
"""Liefert Liste aller Ziele, auf die dieser Knoten zeigt."""
|
|
||||||
return self.adj.get(node_id, [])
|
|
||||||
|
|
||||||
def get_incoming_edges(self, node_id: str) -> List[Dict[str, Any]]:
|
|
||||||
"""Liefert Liste aller Quellen, die auf diesen Knoten zeigen."""
|
|
||||||
return self.reverse_adj.get(node_id, [])
|
|
||||||
|
|
||||||
|
|
||||||
def expand(
|
|
||||||
client: QdrantClient,
|
|
||||||
prefix: str,
|
|
||||||
seeds: List[str],
|
|
||||||
depth: int = 1,
|
|
||||||
edge_types: Optional[List[str]] = None,
|
|
||||||
) -> Subgraph:
|
|
||||||
"""
|
|
||||||
Expandiert ab Seeds entlang von Edges (bis `depth`).
|
|
||||||
"""
|
|
||||||
sg = Subgraph()
|
|
||||||
frontier = set(seeds)
|
|
||||||
visited = set()
|
|
||||||
|
|
||||||
max_depth = max(depth, 0)
|
|
||||||
|
|
||||||
for _ in range(max_depth):
|
|
||||||
if not frontier:
|
|
||||||
break
|
|
||||||
|
|
||||||
edges_payloads = _fetch_edges(
|
|
||||||
client=client,
|
|
||||||
prefix=prefix,
|
|
||||||
seeds=list(frontier),
|
|
||||||
edge_types=edge_types,
|
|
||||||
limit=2048,
|
|
||||||
)
|
|
||||||
|
|
||||||
next_frontier = set()
|
|
||||||
for pl in edges_payloads:
|
|
||||||
src = pl.get("source_id")
|
|
||||||
tgt = pl.get("target_id")
|
|
||||||
|
|
||||||
# Skip invalid edges
|
|
||||||
if not src or not tgt:
|
|
||||||
continue
|
|
||||||
|
|
||||||
e = {
|
|
||||||
"source": src,
|
|
||||||
"target": tgt,
|
|
||||||
"kind": pl.get("kind", "edge"),
|
|
||||||
"weight": _edge_weight(pl),
|
|
||||||
"note_id": pl.get("note_id"),
|
|
||||||
}
|
|
||||||
sg.add_edge(e)
|
|
||||||
|
|
||||||
# Nur weitersuchen, wenn Target noch nicht besucht
|
|
||||||
if tgt and tgt not in visited:
|
|
||||||
next_frontier.add(tgt)
|
|
||||||
|
|
||||||
visited |= frontier
|
|
||||||
frontier = next_frontier - visited
|
|
||||||
|
|
||||||
return sg
|
|
||||||
@@ -1,357 +0,0 @@
|
|||||||
"""
|
|
||||||
FILE: app/core/ingestion.py
|
|
||||||
DESCRIPTION: Haupt-Ingestion-Logik. Transformiert Markdown in den Graphen (Notes, Chunks, Edges).
|
|
||||||
FIX: Korrekte Priorisierung von Frontmatter für chunk_profile und retriever_weight.
|
|
||||||
Lade Chunk-Config basierend auf dem effektiven Profil, nicht nur dem Notiz-Typ.
|
|
||||||
WP-22: Integration von Content Lifecycle (Status Gate) und Edge Registry Validation.
|
|
||||||
WP-22: Multi-Hash Refresh für konsistente Change Detection.
|
|
||||||
VERSION: 2.8.6 (WP-22 Lifecycle & Registry)
|
|
||||||
STATUS: Active
|
|
||||||
DEPENDENCIES: app.core.parser, app.core.note_payload, app.core.chunker, app.core.derive_edges, app.core.qdrant*, app.services.embeddings_client, app.services.edge_registry
|
|
||||||
EXTERNAL_CONFIG: config/types.yaml
|
|
||||||
"""
|
|
||||||
import os
|
|
||||||
import logging
|
|
||||||
import asyncio
|
|
||||||
import time
|
|
||||||
from typing import Dict, List, Optional, Tuple, Any
|
|
||||||
|
|
||||||
# Core Module Imports
|
|
||||||
from app.core.parser import (
|
|
||||||
read_markdown,
|
|
||||||
normalize_frontmatter,
|
|
||||||
validate_required_frontmatter,
|
|
||||||
)
|
|
||||||
from app.core.note_payload import make_note_payload
|
|
||||||
from app.core.chunker import assemble_chunks, get_chunk_config
|
|
||||||
from app.core.chunk_payload import make_chunk_payloads
|
|
||||||
|
|
||||||
# Fallback für Edges
|
|
||||||
try:
|
|
||||||
from app.core.derive_edges import build_edges_for_note
|
|
||||||
except ImportError:
|
|
||||||
def build_edges_for_note(*args, **kwargs): return []
|
|
||||||
|
|
||||||
from app.core.qdrant import QdrantConfig, get_client, ensure_collections, ensure_payload_indexes
|
|
||||||
from app.core.qdrant_points import (
|
|
||||||
points_for_chunks,
|
|
||||||
points_for_note,
|
|
||||||
points_for_edges,
|
|
||||||
upsert_batch,
|
|
||||||
)
|
|
||||||
|
|
||||||
from app.services.embeddings_client import EmbeddingsClient
|
|
||||||
from app.services.edge_registry import registry as edge_registry
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
# --- Helper ---
|
|
||||||
def load_type_registry(custom_path: Optional[str] = None) -> dict:
|
|
||||||
"""Lädt die types.yaml zur Steuerung der typ-spezifischen Ingestion."""
|
|
||||||
import yaml
|
|
||||||
path = custom_path or os.getenv("MINDNET_TYPES_FILE", "config/types.yaml")
|
|
||||||
if not os.path.exists(path): return {}
|
|
||||||
try:
|
|
||||||
with open(path, "r", encoding="utf-8") as f: return yaml.safe_load(f) or {}
|
|
||||||
except Exception: return {}
|
|
||||||
|
|
||||||
def resolve_note_type(requested: Optional[str], reg: dict) -> str:
|
|
||||||
"""Bestimmt den finalen Notiz-Typ (Fallback auf 'concept')."""
|
|
||||||
types = reg.get("types", {})
|
|
||||||
if requested and requested in types: return requested
|
|
||||||
return "concept"
|
|
||||||
|
|
||||||
def effective_chunk_profile_name(fm: dict, note_type: str, reg: dict) -> str:
|
|
||||||
"""
|
|
||||||
Ermittelt den Namen des zu nutzenden Chunk-Profils.
|
|
||||||
Priorität: 1. Frontmatter Override -> 2. Type Config -> 3. Global Default
|
|
||||||
"""
|
|
||||||
# 1. Frontmatter Override
|
|
||||||
override = fm.get("chunking_profile") or fm.get("chunk_profile")
|
|
||||||
if override and isinstance(override, str):
|
|
||||||
return override
|
|
||||||
|
|
||||||
# 2. Type Config
|
|
||||||
t_cfg = reg.get("types", {}).get(note_type, {})
|
|
||||||
if t_cfg:
|
|
||||||
cp = t_cfg.get("chunking_profile") or t_cfg.get("chunk_profile")
|
|
||||||
if cp: return cp
|
|
||||||
|
|
||||||
# 3. Global Default
|
|
||||||
return reg.get("defaults", {}).get("chunking_profile", "sliding_standard")
|
|
||||||
|
|
||||||
def effective_retriever_weight(fm: dict, note_type: str, reg: dict) -> float:
|
|
||||||
"""
|
|
||||||
Ermittelt das effektive retriever_weight für das Scoring.
|
|
||||||
Priorität: 1. Frontmatter Override -> 2. Type Config -> 3. Global Default
|
|
||||||
"""
|
|
||||||
# 1. Frontmatter Override
|
|
||||||
override = fm.get("retriever_weight")
|
|
||||||
if override is not None:
|
|
||||||
try: return float(override)
|
|
||||||
except: pass
|
|
||||||
|
|
||||||
# 2. Type Config
|
|
||||||
t_cfg = reg.get("types", {}).get(note_type, {})
|
|
||||||
if t_cfg and "retriever_weight" in t_cfg:
|
|
||||||
return float(t_cfg["retriever_weight"])
|
|
||||||
|
|
||||||
# 3. Global Default
|
|
||||||
return float(reg.get("defaults", {}).get("retriever_weight", 1.0))
|
|
||||||
|
|
||||||
|
|
||||||
class IngestionService:
|
|
||||||
def __init__(self, collection_prefix: str = None):
|
|
||||||
env_prefix = os.getenv("COLLECTION_PREFIX", "mindnet")
|
|
||||||
self.prefix = collection_prefix or env_prefix
|
|
||||||
|
|
||||||
self.cfg = QdrantConfig.from_env()
|
|
||||||
self.cfg.prefix = self.prefix
|
|
||||||
self.client = get_client(self.cfg)
|
|
||||||
self.dim = self.cfg.dim
|
|
||||||
self.registry = load_type_registry()
|
|
||||||
self.embedder = EmbeddingsClient()
|
|
||||||
|
|
||||||
# Change Detection Modus (full oder body)
|
|
||||||
self.active_hash_mode = os.getenv("MINDNET_CHANGE_DETECTION_MODE", "full")
|
|
||||||
|
|
||||||
try:
|
|
||||||
ensure_collections(self.client, self.prefix, self.dim)
|
|
||||||
ensure_payload_indexes(self.client, self.prefix)
|
|
||||||
except Exception as e:
|
|
||||||
logger.warning(f"DB init warning: {e}")
|
|
||||||
|
|
||||||
def _get_chunk_config_by_profile(self, profile_name: str, note_type: str) -> Dict[str, Any]:
|
|
||||||
"""Holt die Chunker-Parameter (max, target, overlap) für ein spezifisches Profil."""
|
|
||||||
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 process_file(
|
|
||||||
self,
|
|
||||||
file_path: str,
|
|
||||||
vault_root: str,
|
|
||||||
force_replace: bool = False,
|
|
||||||
apply: bool = False,
|
|
||||||
purge_before: bool = False,
|
|
||||||
note_scope_refs: bool = False,
|
|
||||||
hash_source: str = "parsed",
|
|
||||||
hash_normalize: str = "canonical"
|
|
||||||
) -> Dict[str, Any]:
|
|
||||||
"""
|
|
||||||
Verarbeitet eine Markdown-Datei und schreibt sie in den Graphen.
|
|
||||||
Folgt dem 14-Schritte-Workflow.
|
|
||||||
"""
|
|
||||||
result = {"path": file_path, "status": "skipped", "changed": False, "error": None}
|
|
||||||
|
|
||||||
# 1. Parse & Frontmatter Validation
|
|
||||||
try:
|
|
||||||
parsed = read_markdown(file_path)
|
|
||||||
if not parsed: return {**result, "error": "Empty or unreadable file"}
|
|
||||||
fm = normalize_frontmatter(parsed.frontmatter)
|
|
||||||
validate_required_frontmatter(fm)
|
|
||||||
except Exception as e:
|
|
||||||
logger.error(f"Validation failed for {file_path}: {e}")
|
|
||||||
return {**result, "error": f"Validation failed: {str(e)}"}
|
|
||||||
|
|
||||||
# --- WP-22: Content Lifecycle Gate (Teil A) ---
|
|
||||||
status = fm.get("status", "draft").lower().strip()
|
|
||||||
|
|
||||||
# Hard Skip für System- oder Archiv-Dateien
|
|
||||||
if status in ["system", "template", "archive", "hidden"]:
|
|
||||||
logger.info(f"Skipping file {file_path} (Status: {status})")
|
|
||||||
return {**result, "status": "skipped", "reason": f"lifecycle_status_{status}"}
|
|
||||||
|
|
||||||
# 2. Type & Config Resolution
|
|
||||||
note_type = resolve_note_type(fm.get("type"), self.registry)
|
|
||||||
fm["type"] = note_type
|
|
||||||
|
|
||||||
effective_profile = effective_chunk_profile_name(fm, note_type, self.registry)
|
|
||||||
effective_weight = effective_retriever_weight(fm, note_type, self.registry)
|
|
||||||
|
|
||||||
fm["chunk_profile"] = effective_profile
|
|
||||||
fm["retriever_weight"] = effective_weight
|
|
||||||
|
|
||||||
# 3. Build Note Payload (Inkl. Multi-Hash für WP-22)
|
|
||||||
try:
|
|
||||||
note_pl = make_note_payload(
|
|
||||||
parsed,
|
|
||||||
vault_root=vault_root,
|
|
||||||
hash_normalize=hash_normalize,
|
|
||||||
hash_source=hash_source,
|
|
||||||
file_path=file_path
|
|
||||||
)
|
|
||||||
# Text Body Fallback
|
|
||||||
if not note_pl.get("fulltext"): note_pl["fulltext"] = getattr(parsed, "body", "") or ""
|
|
||||||
|
|
||||||
# Sicherstellen der effektiven Werte im Payload
|
|
||||||
note_pl["retriever_weight"] = effective_weight
|
|
||||||
note_pl["chunk_profile"] = effective_profile
|
|
||||||
# WP-22: Status speichern
|
|
||||||
note_pl["status"] = status
|
|
||||||
|
|
||||||
note_id = note_pl["note_id"]
|
|
||||||
except Exception as e:
|
|
||||||
logger.error(f"Payload build failed: {e}")
|
|
||||||
return {**result, "error": f"Payload build failed: {str(e)}"}
|
|
||||||
|
|
||||||
# 4. Change Detection
|
|
||||||
old_payload = None
|
|
||||||
if not force_replace:
|
|
||||||
old_payload = self._fetch_note_payload(note_id)
|
|
||||||
|
|
||||||
has_old = old_payload is not None
|
|
||||||
# Prüfung gegen den aktuell konfigurierten Hash-Modus (body oder full)
|
|
||||||
check_key = f"{self.active_hash_mode}:{hash_source}:{hash_normalize}"
|
|
||||||
|
|
||||||
old_hashes = (old_payload or {}).get("hashes")
|
|
||||||
if isinstance(old_hashes, dict): old_hash = old_hashes.get(check_key)
|
|
||||||
elif isinstance(old_hashes, str) and self.active_hash_mode == "body": old_hash = old_hashes
|
|
||||||
else: old_hash = None
|
|
||||||
|
|
||||||
new_hash = note_pl.get("hashes", {}).get(check_key)
|
|
||||||
hash_changed = (old_hash != new_hash)
|
|
||||||
chunks_missing, edges_missing = self._artifacts_missing(note_id)
|
|
||||||
|
|
||||||
should_write = force_replace or (not has_old) or hash_changed or chunks_missing or edges_missing
|
|
||||||
|
|
||||||
if not should_write:
|
|
||||||
return {**result, "status": "unchanged", "note_id": note_id}
|
|
||||||
|
|
||||||
if not apply:
|
|
||||||
return {**result, "status": "dry-run", "changed": True, "note_id": note_id}
|
|
||||||
|
|
||||||
# 5. Processing (Chunking, Embedding, Edge Generation)
|
|
||||||
try:
|
|
||||||
body_text = getattr(parsed, "body", "") or ""
|
|
||||||
|
|
||||||
# Konfiguration für das spezifische Profil laden
|
|
||||||
chunk_config = self._get_chunk_config_by_profile(effective_profile, note_type)
|
|
||||||
|
|
||||||
chunks = await assemble_chunks(fm["id"], body_text, fm["type"], config=chunk_config)
|
|
||||||
|
|
||||||
# Chunks mit Metadaten anreichern
|
|
||||||
chunk_pls = make_chunk_payloads(fm, note_pl["path"], chunks, note_text=body_text)
|
|
||||||
|
|
||||||
vecs = []
|
|
||||||
if chunk_pls:
|
|
||||||
texts = [c.get("window") or c.get("text") or "" for c in chunk_pls]
|
|
||||||
try:
|
|
||||||
if hasattr(self.embedder, 'embed_documents'):
|
|
||||||
vecs = await self.embedder.embed_documents(texts)
|
|
||||||
else:
|
|
||||||
for t in texts:
|
|
||||||
v = await self.embedder.embed_query(t)
|
|
||||||
vecs.append(v)
|
|
||||||
except Exception as e:
|
|
||||||
logger.error(f"Embedding failed: {e}")
|
|
||||||
raise RuntimeError(f"Embedding failed: {e}")
|
|
||||||
|
|
||||||
# Kanten generieren
|
|
||||||
try:
|
|
||||||
raw_edges = build_edges_for_note(
|
|
||||||
note_id,
|
|
||||||
chunk_pls,
|
|
||||||
note_level_references=note_pl.get("references", []),
|
|
||||||
include_note_scope_refs=note_scope_refs
|
|
||||||
)
|
|
||||||
except TypeError:
|
|
||||||
raw_edges = build_edges_for_note(note_id, chunk_pls)
|
|
||||||
|
|
||||||
# --- WP-22: Edge Registry Validation (Teil B) ---
|
|
||||||
edges = []
|
|
||||||
if raw_edges:
|
|
||||||
for edge in raw_edges:
|
|
||||||
original_kind = edge.get("kind", "related_to")
|
|
||||||
# Normalisierung über die Registry (Alias-Auflösung)
|
|
||||||
canonical_kind = edge_registry.resolve(original_kind)
|
|
||||||
edge["kind"] = canonical_kind
|
|
||||||
edges.append(edge)
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
logger.error(f"Processing failed: {e}", exc_info=True)
|
|
||||||
return {**result, "error": f"Processing failed: {str(e)}"}
|
|
||||||
|
|
||||||
# 6. Upsert in Qdrant
|
|
||||||
try:
|
|
||||||
# Alte Fragmente löschen, um "Geister-Chunks" zu vermeiden
|
|
||||||
if purge_before and has_old:
|
|
||||||
self._purge_artifacts(note_id)
|
|
||||||
|
|
||||||
# Note Metadaten
|
|
||||||
n_name, n_pts = points_for_note(self.prefix, note_pl, None, self.dim)
|
|
||||||
upsert_batch(self.client, n_name, n_pts)
|
|
||||||
|
|
||||||
# Chunks (Vektoren)
|
|
||||||
if chunk_pls and vecs:
|
|
||||||
c_name, c_pts = points_for_chunks(self.prefix, chunk_pls, vecs)
|
|
||||||
upsert_batch(self.client, c_name, c_pts)
|
|
||||||
|
|
||||||
# Kanten
|
|
||||||
if edges:
|
|
||||||
e_name, e_pts = points_for_edges(self.prefix, edges)
|
|
||||||
upsert_batch(self.client, e_name, e_pts)
|
|
||||||
|
|
||||||
return {
|
|
||||||
"path": file_path,
|
|
||||||
"status": "success",
|
|
||||||
"changed": True,
|
|
||||||
"note_id": note_id,
|
|
||||||
"chunks_count": len(chunk_pls),
|
|
||||||
"edges_count": len(edges)
|
|
||||||
}
|
|
||||||
except Exception as e:
|
|
||||||
logger.error(f"Upsert failed: {e}", exc_info=True)
|
|
||||||
return {**result, "error": f"DB Upsert failed: {e}"}
|
|
||||||
|
|
||||||
def _fetch_note_payload(self, note_id: str) -> Optional[dict]:
|
|
||||||
"""Holt das aktuelle Payload einer Note aus Qdrant."""
|
|
||||||
from qdrant_client.http import models as rest
|
|
||||||
col = f"{self.prefix}_notes"
|
|
||||||
try:
|
|
||||||
f = rest.Filter(must=[rest.FieldCondition(key="note_id", match=rest.MatchValue(value=note_id))])
|
|
||||||
pts, _ = self.client.scroll(collection_name=col, scroll_filter=f, limit=1, with_payload=True)
|
|
||||||
return pts[0].payload if pts else None
|
|
||||||
except: return None
|
|
||||||
|
|
||||||
def _artifacts_missing(self, note_id: str) -> Tuple[bool, bool]:
|
|
||||||
"""Prüft, ob Chunks oder Kanten für eine Note fehlen (Integritätscheck)."""
|
|
||||||
from qdrant_client.http import models as rest
|
|
||||||
c_col = f"{self.prefix}_chunks"
|
|
||||||
e_col = f"{self.prefix}_edges"
|
|
||||||
try:
|
|
||||||
f = rest.Filter(must=[rest.FieldCondition(key="note_id", match=rest.MatchValue(value=note_id))])
|
|
||||||
c_pts, _ = self.client.scroll(collection_name=c_col, scroll_filter=f, limit=1)
|
|
||||||
e_pts, _ = self.client.scroll(collection_name=e_col, scroll_filter=f, limit=1)
|
|
||||||
return (not bool(c_pts)), (not bool(e_pts))
|
|
||||||
except: return True, True
|
|
||||||
|
|
||||||
def _purge_artifacts(self, note_id: str):
|
|
||||||
"""Löscht alle Chunks und Edges einer Note (vor dem Neu-Schreiben)."""
|
|
||||||
from qdrant_client.http import models as rest
|
|
||||||
f = rest.Filter(must=[rest.FieldCondition(key="note_id", match=rest.MatchValue(value=note_id))])
|
|
||||||
selector = rest.FilterSelector(filter=f)
|
|
||||||
for suffix in ["chunks", "edges"]:
|
|
||||||
try:
|
|
||||||
self.client.delete(collection_name=f"{self.prefix}_{suffix}", points_selector=selector)
|
|
||||||
except Exception: pass
|
|
||||||
|
|
||||||
async def create_from_text(self, markdown_content: str, filename: str, vault_root: str, folder: str = "00_Inbox") -> Dict[str, Any]:
|
|
||||||
"""Hilfsmethode zur Erstellung einer Note aus einem Textstream (Editor-Save)."""
|
|
||||||
target_dir = os.path.join(vault_root, folder)
|
|
||||||
os.makedirs(target_dir, exist_ok=True)
|
|
||||||
file_path = os.path.join(target_dir, filename)
|
|
||||||
try:
|
|
||||||
with open(file_path, "w", encoding="utf-8") as f:
|
|
||||||
f.write(markdown_content)
|
|
||||||
f.flush()
|
|
||||||
os.fsync(f.fileno())
|
|
||||||
await asyncio.sleep(0.1)
|
|
||||||
logger.info(f"Written file to {file_path}")
|
|
||||||
except Exception as e:
|
|
||||||
return {"status": "error", "error": f"Disk write failed: {str(e)}"}
|
|
||||||
return await self.process_file(file_path=file_path, vault_root=vault_root, apply=True, force_replace=True, purge_before=True)
|
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
"""
|
||||||
|
FILE: app/core/ingestion/__init__.py
|
||||||
|
DESCRIPTION: Package-Einstiegspunkt für Ingestion. Exportiert den IngestionService.
|
||||||
|
AUDIT v2.13.10: Abschluss der Modularisierung (WP-14).
|
||||||
|
Bricht Zirkelbezüge durch Nutzung der neutralen registry.py auf.
|
||||||
|
VERSION: 2.13.10
|
||||||
|
"""
|
||||||
|
# Der IngestionService ist der primäre Orchestrator für den Datenimport
|
||||||
|
from .ingestion_processor import IngestionService
|
||||||
|
|
||||||
|
# Hilfswerkzeuge für JSON-Verarbeitung und Konfigurations-Management
|
||||||
|
# load_type_registry wird hier re-exportiert, um die Abwärtskompatibilität zu wahren,
|
||||||
|
# obwohl die Implementierung nun in app.core.registry liegt.
|
||||||
|
from .ingestion_utils import (
|
||||||
|
extract_json_from_response,
|
||||||
|
load_type_registry,
|
||||||
|
resolve_note_type
|
||||||
|
)
|
||||||
|
|
||||||
|
# Öffentliche API des Pakets
|
||||||
|
__all__ = [
|
||||||
|
"IngestionService",
|
||||||
|
"extract_json_from_response",
|
||||||
|
"load_type_registry",
|
||||||
|
"resolve_note_type"
|
||||||
|
]
|
||||||
@@ -0,0 +1,114 @@
|
|||||||
|
"""
|
||||||
|
FILE: app/core/ingestion/ingestion_chunk_payload.py
|
||||||
|
DESCRIPTION: Baut das JSON-Objekt für 'mindnet_chunks'.
|
||||||
|
Fix v2.4.3: Integration der zentralen Registry (WP-14) für konsistente Defaults.
|
||||||
|
VERSION: 2.4.3
|
||||||
|
STATUS: Active
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
from typing import Any, Dict, List, Optional
|
||||||
|
|
||||||
|
# ENTSCHEIDENDER FIX: Import der neutralen Registry-Logik zur Vermeidung von Circular Imports
|
||||||
|
from app.core.registry import load_type_registry
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Resolution Helpers (Audited)
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
def _as_list(x):
|
||||||
|
"""Sichert die Listen-Integrität für Metadaten wie Tags."""
|
||||||
|
if x is None: return []
|
||||||
|
return x if isinstance(x, list) else [x]
|
||||||
|
|
||||||
|
def _resolve_val(note_type: str, reg: dict, key: str, default: Any) -> Any:
|
||||||
|
"""
|
||||||
|
Hierarchische Suche in der Registry: Type-Spezifisch > Globaler Default.
|
||||||
|
WP-14: Erlaubt dynamische Konfiguration via types.yaml.
|
||||||
|
"""
|
||||||
|
types = reg.get("types", {})
|
||||||
|
if isinstance(types, dict):
|
||||||
|
t_cfg = types.get(note_type, {})
|
||||||
|
if isinstance(t_cfg, dict):
|
||||||
|
# Fallback für Key-Varianten (z.B. chunking_profile vs chunk_profile)
|
||||||
|
val = t_cfg.get(key) or t_cfg.get(key.replace("ing", ""))
|
||||||
|
if val is not None: return val
|
||||||
|
|
||||||
|
defs = reg.get("defaults", {}) or reg.get("global", {})
|
||||||
|
if isinstance(defs, dict):
|
||||||
|
val = defs.get(key) or defs.get(key.replace("ing", ""))
|
||||||
|
if val is not None: return val
|
||||||
|
|
||||||
|
return default
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Haupt-API
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
def make_chunk_payloads(note: Dict[str, Any], note_path: str, chunks_from_chunker: List[Any], **kwargs) -> List[Dict[str, Any]]:
|
||||||
|
"""
|
||||||
|
Erstellt die Payloads für die Chunks inklusive Audit-Resolution.
|
||||||
|
Nutzt nun die zentrale Registry für alle Fallbacks.
|
||||||
|
"""
|
||||||
|
if isinstance(note, dict) and "frontmatter" in note:
|
||||||
|
fm = note["frontmatter"]
|
||||||
|
else:
|
||||||
|
fm = note or {}
|
||||||
|
|
||||||
|
# WP-14 Fix: Nutzt übergebene Registry oder lädt sie global
|
||||||
|
reg = kwargs.get("types_cfg") or load_type_registry()
|
||||||
|
|
||||||
|
note_type = fm.get("type") or "concept"
|
||||||
|
title = fm.get("title") or fm.get("id") or "Untitled"
|
||||||
|
tags = _as_list(fm.get("tags") or [])
|
||||||
|
|
||||||
|
# Audit: Resolution Hierarchie (Frontmatter > Registry)
|
||||||
|
cp = fm.get("chunking_profile") or fm.get("chunk_profile")
|
||||||
|
if not cp:
|
||||||
|
cp = _resolve_val(note_type, reg, "chunking_profile", "sliding_standard")
|
||||||
|
|
||||||
|
rw = fm.get("retriever_weight")
|
||||||
|
if rw is None:
|
||||||
|
rw = _resolve_val(note_type, reg, "retriever_weight", 1.0)
|
||||||
|
try:
|
||||||
|
rw = float(rw)
|
||||||
|
except:
|
||||||
|
rw = 1.0
|
||||||
|
|
||||||
|
out: List[Dict[str, Any]] = []
|
||||||
|
for idx, ch in enumerate(chunks_from_chunker):
|
||||||
|
is_dict = isinstance(ch, dict)
|
||||||
|
cid = getattr(ch, "id", None) if not is_dict else ch.get("id")
|
||||||
|
nid = getattr(ch, "note_id", None) if not is_dict else ch.get("note_id")
|
||||||
|
index = getattr(ch, "index", idx) if not is_dict else ch.get("index", idx)
|
||||||
|
text = getattr(ch, "text", "") if not is_dict else ch.get("text", "")
|
||||||
|
window = getattr(ch, "window", text) if not is_dict else ch.get("window", text)
|
||||||
|
prev_id = getattr(ch, "neighbors_prev", None) if not is_dict else ch.get("neighbors_prev")
|
||||||
|
next_id = getattr(ch, "neighbors_next", None) if not is_dict else ch.get("neighbors_next")
|
||||||
|
section = getattr(ch, "section_title", "") if not is_dict else ch.get("section", "")
|
||||||
|
|
||||||
|
pl: Dict[str, Any] = {
|
||||||
|
"note_id": nid or fm.get("id"),
|
||||||
|
"chunk_id": cid,
|
||||||
|
"title": title,
|
||||||
|
"index": int(index),
|
||||||
|
"ord": int(index) + 1,
|
||||||
|
"type": note_type,
|
||||||
|
"tags": tags,
|
||||||
|
"text": text,
|
||||||
|
"window": window,
|
||||||
|
"neighbors_prev": _as_list(prev_id),
|
||||||
|
"neighbors_next": _as_list(next_id),
|
||||||
|
"section": section,
|
||||||
|
"path": note_path,
|
||||||
|
"source_path": kwargs.get("file_path") or note_path,
|
||||||
|
"retriever_weight": rw,
|
||||||
|
"chunk_profile": cp
|
||||||
|
}
|
||||||
|
|
||||||
|
# Audit: Cleanup Pop (Vermeidung von redundanten Alias-Feldern)
|
||||||
|
for alias in ("chunk_num", "Chunk_Number"):
|
||||||
|
pl.pop(alias, None)
|
||||||
|
|
||||||
|
out.append(pl)
|
||||||
|
|
||||||
|
return out
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
"""
|
||||||
|
FILE: app/core/ingestion/ingestion_db.py
|
||||||
|
DESCRIPTION: Datenbank-Schnittstelle für Note-Metadaten und Artefakt-Prüfung.
|
||||||
|
WP-14: Umstellung auf zentrale database-Infrastruktur.
|
||||||
|
"""
|
||||||
|
from typing import Optional, Tuple
|
||||||
|
from qdrant_client import QdrantClient
|
||||||
|
from qdrant_client.http import models as rest
|
||||||
|
|
||||||
|
# Import der modularisierten Namen-Logik zur Sicherstellung der Konsistenz
|
||||||
|
from app.core.database import collection_names
|
||||||
|
|
||||||
|
def fetch_note_payload(client: QdrantClient, prefix: str, note_id: str) -> Optional[dict]:
|
||||||
|
"""Holt die Metadaten einer Note aus Qdrant via Scroll."""
|
||||||
|
notes_col, _, _ = collection_names(prefix)
|
||||||
|
try:
|
||||||
|
f = rest.Filter(must=[rest.FieldCondition(key="note_id", match=rest.MatchValue(value=note_id))])
|
||||||
|
pts, _ = client.scroll(collection_name=notes_col, scroll_filter=f, limit=1, with_payload=True)
|
||||||
|
return pts[0].payload if pts else None
|
||||||
|
except: return None
|
||||||
|
|
||||||
|
def artifacts_missing(client: QdrantClient, prefix: str, note_id: str) -> Tuple[bool, bool]:
|
||||||
|
"""Prüft Qdrant aktiv auf vorhandene Chunks und Edges."""
|
||||||
|
_, chunks_col, edges_col = collection_names(prefix)
|
||||||
|
try:
|
||||||
|
f = rest.Filter(must=[rest.FieldCondition(key="note_id", match=rest.MatchValue(value=note_id))])
|
||||||
|
c_pts, _ = client.scroll(collection_name=chunks_col, scroll_filter=f, limit=1)
|
||||||
|
e_pts, _ = client.scroll(collection_name=edges_col, scroll_filter=f, limit=1)
|
||||||
|
return (not bool(c_pts)), (not bool(e_pts))
|
||||||
|
except: return True, True
|
||||||
|
|
||||||
|
def purge_artifacts(client: QdrantClient, prefix: str, note_id: str):
|
||||||
|
"""Löscht verwaiste Chunks/Edges vor einem Re-Import."""
|
||||||
|
_, chunks_col, edges_col = collection_names(prefix)
|
||||||
|
f = rest.Filter(must=[rest.FieldCondition(key="note_id", match=rest.MatchValue(value=note_id))])
|
||||||
|
# Iteration über die nun zentral verwalteten Collection-Namen
|
||||||
|
for col in [chunks_col, edges_col]:
|
||||||
|
try: client.delete(collection_name=col, points_selector=rest.FilterSelector(filter=f))
|
||||||
|
except: pass
|
||||||
@@ -0,0 +1,169 @@
|
|||||||
|
"""
|
||||||
|
FILE: app/core/ingestion/ingestion_note_payload.py
|
||||||
|
DESCRIPTION: Baut das JSON-Objekt für mindnet_notes.
|
||||||
|
FEATURES:
|
||||||
|
- Multi-Hash (body/full) für flexible Change Detection.
|
||||||
|
- Fix v2.4.5: Präzise Hash-Logik für Profil-Änderungen.
|
||||||
|
- Integration der zentralen Registry (WP-14).
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
from typing import Any, Dict, Tuple, Optional
|
||||||
|
import os
|
||||||
|
import json
|
||||||
|
import pathlib
|
||||||
|
import hashlib
|
||||||
|
|
||||||
|
# Import der zentralen Registry-Logik
|
||||||
|
from app.core.registry import load_type_registry
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Helper
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
def _as_dict(x) -> Dict[str, Any]:
|
||||||
|
"""Versucht, ein Objekt in ein Dict zu überführen."""
|
||||||
|
if isinstance(x, dict): return dict(x)
|
||||||
|
out: Dict[str, Any] = {}
|
||||||
|
for attr in ("frontmatter", "body", "id", "note_id", "title", "path", "tags", "type", "created", "modified", "date"):
|
||||||
|
if hasattr(x, attr):
|
||||||
|
val = getattr(x, attr)
|
||||||
|
if val is not None: out[attr] = val
|
||||||
|
if not out: out["raw"] = str(x)
|
||||||
|
return out
|
||||||
|
|
||||||
|
def _ensure_list(x) -> list:
|
||||||
|
"""Sichert String-Listen Integrität."""
|
||||||
|
if x is None: return []
|
||||||
|
if isinstance(x, list): return [str(i) for i in x]
|
||||||
|
if isinstance(x, (set, tuple)): return [str(i) for i in x]
|
||||||
|
return [str(x)]
|
||||||
|
|
||||||
|
def _compute_hash(content: str) -> str:
|
||||||
|
"""SHA-256 Hash-Berechnung."""
|
||||||
|
if not content: return ""
|
||||||
|
return hashlib.sha256(content.encode("utf-8")).hexdigest()
|
||||||
|
|
||||||
|
def _get_hash_source_content(n: Dict[str, Any], mode: str) -> str:
|
||||||
|
"""
|
||||||
|
Generiert den Hash-Input-String basierend auf Body oder Metadaten.
|
||||||
|
Fix: Inkludiert nun alle entscheidungsrelevanten Profil-Parameter.
|
||||||
|
"""
|
||||||
|
body = str(n.get("body") or "").strip()
|
||||||
|
if mode == "body": return body
|
||||||
|
if mode == "full":
|
||||||
|
fm = n.get("frontmatter") or {}
|
||||||
|
meta_parts = []
|
||||||
|
# Wir inkludieren alle Felder, die das Chunking oder Retrieval beeinflussen
|
||||||
|
# Jede Änderung hier führt nun zwingend zu einem neuen Full-Hash
|
||||||
|
keys = [
|
||||||
|
"title", "type", "status", "tags",
|
||||||
|
"chunking_profile", "chunk_profile",
|
||||||
|
"retriever_weight", "split_level", "strict_heading_split"
|
||||||
|
]
|
||||||
|
for k in sorted(keys):
|
||||||
|
val = fm.get(k)
|
||||||
|
if val is not None: meta_parts.append(f"{k}:{val}")
|
||||||
|
return f"{'|'.join(meta_parts)}||{body}"
|
||||||
|
return body
|
||||||
|
|
||||||
|
def _cfg_for_type(note_type: str, reg: dict) -> dict:
|
||||||
|
"""Extrahiert Typ-spezifische Config aus der Registry."""
|
||||||
|
if not isinstance(reg, dict): return {}
|
||||||
|
types = reg.get("types") if isinstance(reg.get("types"), dict) else reg
|
||||||
|
return types.get(note_type, {}) if isinstance(types, dict) else {}
|
||||||
|
|
||||||
|
def _cfg_defaults(reg: dict) -> dict:
|
||||||
|
"""Extrahiert globale Default-Werte aus der Registry."""
|
||||||
|
if not isinstance(reg, dict): return {}
|
||||||
|
for key in ("defaults", "default", "global"):
|
||||||
|
v = reg.get(key)
|
||||||
|
if isinstance(v, dict): return v
|
||||||
|
return {}
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Haupt-API
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
def make_note_payload(note: Any, *args, **kwargs) -> Dict[str, Any]:
|
||||||
|
"""
|
||||||
|
Baut das Note-Payload inklusive Multi-Hash und Audit-Validierung.
|
||||||
|
WP-14: Nutzt die zentrale Registry für alle Fallbacks.
|
||||||
|
"""
|
||||||
|
n = _as_dict(note)
|
||||||
|
|
||||||
|
# Registry & Context Settings
|
||||||
|
reg = kwargs.get("types_cfg") or load_type_registry()
|
||||||
|
hash_source = kwargs.get("hash_source", "parsed")
|
||||||
|
hash_normalize = kwargs.get("hash_normalize", "canonical")
|
||||||
|
|
||||||
|
fm = n.get("frontmatter") or {}
|
||||||
|
note_type = str(fm.get("type") or n.get("type") or "concept")
|
||||||
|
|
||||||
|
cfg_type = _cfg_for_type(note_type, reg)
|
||||||
|
cfg_def = _cfg_defaults(reg)
|
||||||
|
ingest_cfg = reg.get("ingestion_settings", {})
|
||||||
|
|
||||||
|
# --- retriever_weight Audit ---
|
||||||
|
default_rw = float(os.environ.get("MINDNET_DEFAULT_RETRIEVER_WEIGHT", 1.0))
|
||||||
|
retriever_weight = fm.get("retriever_weight")
|
||||||
|
if retriever_weight is None:
|
||||||
|
retriever_weight = cfg_type.get("retriever_weight", cfg_def.get("retriever_weight", default_rw))
|
||||||
|
try:
|
||||||
|
retriever_weight = float(retriever_weight)
|
||||||
|
except:
|
||||||
|
retriever_weight = default_rw
|
||||||
|
|
||||||
|
# --- chunk_profile Audit ---
|
||||||
|
chunk_profile = fm.get("chunking_profile") or fm.get("chunk_profile")
|
||||||
|
if chunk_profile is None:
|
||||||
|
chunk_profile = cfg_type.get("chunking_profile") or cfg_type.get("chunk_profile")
|
||||||
|
if chunk_profile is None:
|
||||||
|
chunk_profile = ingest_cfg.get("default_chunk_profile", cfg_def.get("chunking_profile", "sliding_standard"))
|
||||||
|
|
||||||
|
# --- edge_defaults Audit ---
|
||||||
|
edge_defaults = fm.get("edge_defaults")
|
||||||
|
if edge_defaults is None:
|
||||||
|
edge_defaults = cfg_type.get("edge_defaults", cfg_def.get("edge_defaults", []))
|
||||||
|
edge_defaults = _ensure_list(edge_defaults)
|
||||||
|
|
||||||
|
# --- Basis-Metadaten ---
|
||||||
|
note_id = n.get("note_id") or n.get("id") or fm.get("id")
|
||||||
|
title = n.get("title") or fm.get("title") or ""
|
||||||
|
path = n.get("path") or kwargs.get("file_path") or ""
|
||||||
|
if isinstance(path, pathlib.Path): path = str(path)
|
||||||
|
|
||||||
|
payload: Dict[str, Any] = {
|
||||||
|
"note_id": note_id,
|
||||||
|
"title": title,
|
||||||
|
"type": note_type,
|
||||||
|
"path": path,
|
||||||
|
"retriever_weight": retriever_weight,
|
||||||
|
"chunk_profile": chunk_profile,
|
||||||
|
"edge_defaults": edge_defaults,
|
||||||
|
"hashes": {}
|
||||||
|
}
|
||||||
|
|
||||||
|
# --- MULTI-HASH ---
|
||||||
|
# Generiert Hashes für Change Detection (WP-15b)
|
||||||
|
for mode in ["body", "full"]:
|
||||||
|
content = _get_hash_source_content(n, mode)
|
||||||
|
payload["hashes"][f"{mode}:{hash_source}:{hash_normalize}"] = _compute_hash(content)
|
||||||
|
|
||||||
|
# Metadaten Anreicherung (Tags, Aliases, Zeitstempel)
|
||||||
|
tags = fm.get("tags") or fm.get("keywords") or n.get("tags")
|
||||||
|
if tags: payload["tags"] = _ensure_list(tags)
|
||||||
|
|
||||||
|
aliases = fm.get("aliases")
|
||||||
|
if aliases: payload["aliases"] = _ensure_list(aliases)
|
||||||
|
|
||||||
|
for k in ("created", "modified", "date"):
|
||||||
|
v = fm.get(k) or n.get(k)
|
||||||
|
if v: payload[k] = str(v)
|
||||||
|
|
||||||
|
if n.get("body"):
|
||||||
|
payload["fulltext"] = str(n["body"])
|
||||||
|
|
||||||
|
# Final JSON Validation Audit
|
||||||
|
json.loads(json.dumps(payload, ensure_ascii=False))
|
||||||
|
|
||||||
|
return payload
|
||||||
@@ -0,0 +1,245 @@
|
|||||||
|
"""
|
||||||
|
FILE: app/core/ingestion/ingestion_processor.py
|
||||||
|
DESCRIPTION: Der zentrale IngestionService (Orchestrator).
|
||||||
|
WP-25a: Integration der Mixture of Experts (MoE) Architektur.
|
||||||
|
WP-15b: Two-Pass Workflow mit globalem Kontext-Cache.
|
||||||
|
WP-20/22: Cloud-Resilienz und Content-Lifecycle integriert.
|
||||||
|
AUDIT v2.14.0: Synchronisierung der Profil-Auflösung mit MoE-Experten.
|
||||||
|
VERSION: 2.14.0 (WP-25a: MoE & Profile Support)
|
||||||
|
STATUS: Active
|
||||||
|
"""
|
||||||
|
import logging
|
||||||
|
import asyncio
|
||||||
|
import os
|
||||||
|
from typing import Dict, List, Optional, Tuple, Any
|
||||||
|
|
||||||
|
# Core Module Imports
|
||||||
|
from app.core.parser import (
|
||||||
|
read_markdown, pre_scan_markdown, normalize_frontmatter,
|
||||||
|
validate_required_frontmatter, NoteContext
|
||||||
|
)
|
||||||
|
from app.core.chunking import assemble_chunks
|
||||||
|
|
||||||
|
# MODULARISIERUNG: Neue Import-Pfade für die Datenbank-Ebene
|
||||||
|
from app.core.database.qdrant import QdrantConfig, get_client, ensure_collections, ensure_payload_indexes
|
||||||
|
from app.core.database.qdrant_points import points_for_chunks, points_for_note, points_for_edges, upsert_batch
|
||||||
|
|
||||||
|
# Services
|
||||||
|
from app.services.embeddings_client import EmbeddingsClient
|
||||||
|
from app.services.edge_registry import registry as edge_registry
|
||||||
|
from app.services.llm_service import LLMService
|
||||||
|
|
||||||
|
# Package-Interne Imports (Refactoring WP-14)
|
||||||
|
from .ingestion_utils import load_type_registry, resolve_note_type, get_chunk_config_by_profile
|
||||||
|
from .ingestion_db import fetch_note_payload, artifacts_missing, purge_artifacts
|
||||||
|
from .ingestion_validation import validate_edge_candidate
|
||||||
|
from .ingestion_note_payload import make_note_payload
|
||||||
|
from .ingestion_chunk_payload import make_chunk_payloads
|
||||||
|
|
||||||
|
# Fallback für Edges (Struktur-Verknüpfung)
|
||||||
|
try:
|
||||||
|
from app.core.graph.graph_derive_edges import build_edges_for_note
|
||||||
|
except ImportError:
|
||||||
|
def build_edges_for_note(*args, **kwargs): return []
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
class IngestionService:
|
||||||
|
def __init__(self, collection_prefix: str = None):
|
||||||
|
"""Initialisiert den Service und nutzt die neue database-Infrastruktur."""
|
||||||
|
from app.config import get_settings
|
||||||
|
self.settings = get_settings()
|
||||||
|
|
||||||
|
self.prefix = collection_prefix or self.settings.COLLECTION_PREFIX
|
||||||
|
self.cfg = QdrantConfig.from_env()
|
||||||
|
# Synchronisierung der Konfiguration mit dem Instanz-Präfix
|
||||||
|
self.cfg.prefix = self.prefix
|
||||||
|
self.client = get_client(self.cfg)
|
||||||
|
|
||||||
|
self.registry = load_type_registry()
|
||||||
|
self.embedder = EmbeddingsClient()
|
||||||
|
self.llm = LLMService()
|
||||||
|
|
||||||
|
# WP-25a: Auflösung der Dimension über das Embedding-Profil (MoE)
|
||||||
|
embed_cfg = self.llm.profiles.get("embedding_expert", {})
|
||||||
|
self.dim = embed_cfg.get("dimensions") or self.settings.VECTOR_SIZE
|
||||||
|
|
||||||
|
# Festlegen, welcher Hash für die Change-Detection maßgeblich ist
|
||||||
|
self.active_hash_mode = self.settings.CHANGE_DETECTION_MODE
|
||||||
|
self.batch_cache: Dict[str, NoteContext] = {} # WP-15b LocalBatchCache
|
||||||
|
|
||||||
|
try:
|
||||||
|
# Aufruf der modularisierten Schema-Logik
|
||||||
|
ensure_collections(self.client, self.prefix, self.dim)
|
||||||
|
ensure_payload_indexes(self.client, self.prefix)
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f"DB initialization warning: {e}")
|
||||||
|
|
||||||
|
async def run_batch(self, file_paths: List[str], vault_root: str) -> List[Dict[str, Any]]:
|
||||||
|
"""
|
||||||
|
WP-15b: Implementiert den Two-Pass Ingestion Workflow.
|
||||||
|
Pass 1: Pre-Scan füllt den Context-Cache (3-Wege-Indexierung).
|
||||||
|
Pass 2: Verarbeitung nutzt den Cache für die semantische Prüfung.
|
||||||
|
"""
|
||||||
|
logger.info(f"🔍 [Pass 1] Pre-Scanning {len(file_paths)} files for Context Cache...")
|
||||||
|
for path in file_paths:
|
||||||
|
try:
|
||||||
|
# Übergabe der Registry für dynamische Scan-Tiefe
|
||||||
|
ctx = pre_scan_markdown(path, registry=self.registry)
|
||||||
|
if ctx:
|
||||||
|
# Mehrfache Indizierung für robusten Look-up (ID, Titel, Dateiname)
|
||||||
|
self.batch_cache[ctx.note_id] = ctx
|
||||||
|
self.batch_cache[ctx.title] = ctx
|
||||||
|
fname = os.path.splitext(os.path.basename(path))[0]
|
||||||
|
self.batch_cache[fname] = ctx
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f"⚠️ Pre-scan failed for {path}: {e}")
|
||||||
|
|
||||||
|
logger.info(f"🚀 [Pass 2] Semantic Processing of {len(file_paths)} files...")
|
||||||
|
return [await self.process_file(p, vault_root, apply=True, purge_before=True) for p in file_paths]
|
||||||
|
|
||||||
|
async def process_file(self, file_path: str, vault_root: str, **kwargs) -> Dict[str, Any]:
|
||||||
|
"""Transformiert eine Markdown-Datei in den Graphen."""
|
||||||
|
apply = kwargs.get("apply", False)
|
||||||
|
force_replace = kwargs.get("force_replace", False)
|
||||||
|
purge_before = kwargs.get("purge_before", False)
|
||||||
|
note_scope_refs = kwargs.get("note_scope_refs", False)
|
||||||
|
hash_source = kwargs.get("hash_source", "parsed")
|
||||||
|
hash_normalize = kwargs.get("hash_normalize", "canonical")
|
||||||
|
|
||||||
|
result = {"path": file_path, "status": "skipped", "changed": False, "error": None}
|
||||||
|
|
||||||
|
# 1. Parse & Lifecycle Gate
|
||||||
|
try:
|
||||||
|
parsed = read_markdown(file_path)
|
||||||
|
if not parsed: return {**result, "error": "Empty file"}
|
||||||
|
fm = normalize_frontmatter(parsed.frontmatter)
|
||||||
|
validate_required_frontmatter(fm)
|
||||||
|
except Exception as e:
|
||||||
|
return {**result, "error": f"Validation failed: {str(e)}"}
|
||||||
|
|
||||||
|
# Dynamischer Lifecycle-Filter aus der Registry (WP-14)
|
||||||
|
ingest_cfg = self.registry.get("ingestion_settings", {})
|
||||||
|
ignore_list = ingest_cfg.get("ignore_statuses", ["system", "template", "archive", "hidden"])
|
||||||
|
|
||||||
|
current_status = fm.get("status", "draft").lower().strip()
|
||||||
|
if current_status in ignore_list:
|
||||||
|
return {**result, "status": "skipped", "reason": "lifecycle_filter"}
|
||||||
|
|
||||||
|
# 2. Payload & Change Detection (Multi-Hash)
|
||||||
|
note_type = resolve_note_type(self.registry, fm.get("type"))
|
||||||
|
note_pl = make_note_payload(
|
||||||
|
parsed, vault_root=vault_root, file_path=file_path,
|
||||||
|
hash_source=hash_source, hash_normalize=hash_normalize,
|
||||||
|
types_cfg=self.registry
|
||||||
|
)
|
||||||
|
note_id = note_pl["note_id"]
|
||||||
|
|
||||||
|
# Abgleich mit der Datenbank (Qdrant)
|
||||||
|
old_payload = None if force_replace else fetch_note_payload(self.client, self.prefix, note_id)
|
||||||
|
|
||||||
|
# Prüfung gegen den konfigurierten Hash-Modus (body vs. full)
|
||||||
|
check_key = f"{self.active_hash_mode}:{hash_source}:{hash_normalize}"
|
||||||
|
old_hash = (old_payload or {}).get("hashes", {}).get(check_key)
|
||||||
|
new_hash = note_pl.get("hashes", {}).get(check_key)
|
||||||
|
|
||||||
|
# Check ob Chunks oder Kanten in der DB fehlen (Reparatur-Modus)
|
||||||
|
c_miss, e_miss = artifacts_missing(self.client, self.prefix, note_id)
|
||||||
|
|
||||||
|
# Wenn Hash identisch und Artefakte vorhanden -> Skip
|
||||||
|
if not (force_replace or not old_payload or old_hash != new_hash or c_miss or e_miss):
|
||||||
|
return {**result, "status": "unchanged", "note_id": note_id}
|
||||||
|
|
||||||
|
if not apply:
|
||||||
|
return {**result, "status": "dry-run", "changed": True, "note_id": note_id}
|
||||||
|
|
||||||
|
# 3. Deep Processing (Chunking, Validation, Embedding)
|
||||||
|
try:
|
||||||
|
body_text = getattr(parsed, "body", "") or ""
|
||||||
|
edge_registry.ensure_latest()
|
||||||
|
|
||||||
|
# Profil-Auflösung via Registry
|
||||||
|
profile = note_pl.get("chunk_profile", "sliding_standard")
|
||||||
|
|
||||||
|
chunk_cfg = get_chunk_config_by_profile(self.registry, profile, note_type)
|
||||||
|
enable_smart = chunk_cfg.get("enable_smart_edge_allocation", False)
|
||||||
|
|
||||||
|
# WP-15b: Chunker-Aufruf bereitet den Candidate-Pool pro Chunk vor.
|
||||||
|
chunks = await assemble_chunks(note_id, body_text, note_type, config=chunk_cfg)
|
||||||
|
|
||||||
|
# Semantische Kanten-Validierung (Smart Edge Allocation via MoE-Profil)
|
||||||
|
for ch in chunks:
|
||||||
|
filtered = []
|
||||||
|
for cand in getattr(ch, "candidate_pool", []):
|
||||||
|
# WP-25a: Nutzt nun das spezialisierte Validierungs-Profil
|
||||||
|
if cand.get("provenance") == "global_pool" and enable_smart:
|
||||||
|
if await validate_edge_candidate(ch.text, cand, self.batch_cache, self.llm, profile_name="ingest_validator"):
|
||||||
|
filtered.append(cand)
|
||||||
|
else:
|
||||||
|
# Explizite Kanten (Wikilinks/Callouts) werden ungeprüft übernommen
|
||||||
|
filtered.append(cand)
|
||||||
|
ch.candidate_pool = filtered
|
||||||
|
|
||||||
|
# Payload-Erstellung für die Chunks
|
||||||
|
chunk_pls = make_chunk_payloads(
|
||||||
|
fm, note_pl["path"], chunks, file_path=file_path,
|
||||||
|
types_cfg=self.registry
|
||||||
|
)
|
||||||
|
|
||||||
|
# Vektorisierung der Fenster-Texte
|
||||||
|
vecs = await self.embedder.embed_documents([c.get("window") or "" for c in chunk_pls]) if chunk_pls else []
|
||||||
|
|
||||||
|
# Aggregation aller finalen Kanten (Edges)
|
||||||
|
edges = build_edges_for_note(
|
||||||
|
note_id, chunk_pls,
|
||||||
|
note_level_references=note_pl.get("references", []),
|
||||||
|
include_note_scope_refs=note_scope_refs
|
||||||
|
)
|
||||||
|
|
||||||
|
# Kanten-Typen via Registry validieren/auflösen
|
||||||
|
for e in edges:
|
||||||
|
e["kind"] = edge_registry.resolve(
|
||||||
|
e.get("kind", "related_to"),
|
||||||
|
provenance=e.get("provenance", "explicit"),
|
||||||
|
context={"file": file_path, "note_id": note_id, "line": e.get("line", "system")}
|
||||||
|
)
|
||||||
|
|
||||||
|
# 4. DB Upsert via modularisierter Points-Logik
|
||||||
|
if purge_before and old_payload:
|
||||||
|
purge_artifacts(self.client, self.prefix, note_id)
|
||||||
|
|
||||||
|
# Speichern der Haupt-Note
|
||||||
|
n_name, n_pts = points_for_note(self.prefix, note_pl, None, self.dim)
|
||||||
|
upsert_batch(self.client, n_name, n_pts)
|
||||||
|
|
||||||
|
# Speichern der Chunks
|
||||||
|
if chunk_pls and vecs:
|
||||||
|
c_pts = points_for_chunks(self.prefix, chunk_pls, vecs)[1]
|
||||||
|
upsert_batch(self.client, f"{self.prefix}_chunks", c_pts)
|
||||||
|
|
||||||
|
# Speichern der Kanten
|
||||||
|
if edges:
|
||||||
|
e_pts = points_for_edges(self.prefix, edges)[1]
|
||||||
|
upsert_batch(self.client, f"{self.prefix}_edges", e_pts)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"path": file_path,
|
||||||
|
"status": "success",
|
||||||
|
"changed": True,
|
||||||
|
"note_id": note_id,
|
||||||
|
"chunks_count": len(chunk_pls),
|
||||||
|
"edges_count": len(edges)
|
||||||
|
}
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Processing failed: {e}", exc_info=True)
|
||||||
|
return {**result, "error": str(e)}
|
||||||
|
|
||||||
|
async def create_from_text(self, markdown_content: str, filename: str, vault_root: str, folder: str = "00_Inbox") -> Dict[str, Any]:
|
||||||
|
"""Erstellt eine Note aus einem Textstream und triggert die Ingestion."""
|
||||||
|
target_path = os.path.join(vault_root, folder, filename)
|
||||||
|
os.makedirs(os.path.dirname(target_path), exist_ok=True)
|
||||||
|
with open(target_path, "w", encoding="utf-8") as f:
|
||||||
|
f.write(markdown_content)
|
||||||
|
await asyncio.sleep(0.1)
|
||||||
|
# Triggert sofortigen Import mit force_replace/purge_before
|
||||||
|
return await self.process_file(file_path=target_path, vault_root=vault_root, apply=True, force_replace=True, purge_before=True)
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
"""
|
||||||
|
FILE: app/core/ingestion/ingestion_utils.py
|
||||||
|
DESCRIPTION: Hilfswerkzeuge für JSON-Recovery, Typ-Registry und Konfigurations-Lookups.
|
||||||
|
AUDIT v2.13.9: Behebung des Circular Imports durch Nutzung der app.core.registry.
|
||||||
|
"""
|
||||||
|
import json
|
||||||
|
import re
|
||||||
|
from typing import Any, Optional, Dict
|
||||||
|
|
||||||
|
# ENTSCHEIDENDER FIX: Import der Basis-Logik aus dem neutralen Registry-Modul.
|
||||||
|
# Dies bricht den Zirkelbezug auf, da dieses Modul keine Services mehr importiert.
|
||||||
|
from app.core.registry import load_type_registry, clean_llm_text
|
||||||
|
|
||||||
|
def extract_json_from_response(text: str, registry: Optional[dict] = None) -> Any:
|
||||||
|
"""
|
||||||
|
Extrahiert JSON-Daten und bereinigt LLM-Steuerzeichen.
|
||||||
|
WP-14: Nutzt nun die zentrale clean_llm_text Funktion aus app.core.registry.
|
||||||
|
"""
|
||||||
|
if not text:
|
||||||
|
return []
|
||||||
|
|
||||||
|
# 1. Text zentral bereinigen via neutralem Modul
|
||||||
|
clean = clean_llm_text(text, registry)
|
||||||
|
|
||||||
|
# 2. Markdown-Code-Blöcke extrahieren
|
||||||
|
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:
|
||||||
|
# Recovery: Suche nach Liste
|
||||||
|
start = payload.find('[')
|
||||||
|
end = payload.rfind(']') + 1
|
||||||
|
if start != -1 and end > start:
|
||||||
|
try: return json.loads(payload[start:end])
|
||||||
|
except: pass
|
||||||
|
|
||||||
|
# Recovery: Suche nach Objekt
|
||||||
|
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 []
|
||||||
|
|
||||||
|
def resolve_note_type(registry: dict, requested: Optional[str]) -> str:
|
||||||
|
"""
|
||||||
|
Bestimmt den finalen Notiz-Typ.
|
||||||
|
WP-14: Fallback wird nun über ingestion_settings.default_note_type gesteuert.
|
||||||
|
"""
|
||||||
|
types = registry.get("types", {})
|
||||||
|
if requested and requested in types:
|
||||||
|
return requested
|
||||||
|
|
||||||
|
# Dynamischer Fallback aus der Registry (Standard: 'concept')
|
||||||
|
ingest_cfg = registry.get("ingestion_settings", {})
|
||||||
|
return ingest_cfg.get("default_note_type", "concept")
|
||||||
|
|
||||||
|
def get_chunk_config_by_profile(registry: dict, profile_name: str, note_type: str) -> Dict[str, Any]:
|
||||||
|
"""
|
||||||
|
Holt die Chunker-Parameter für ein spezifisches Profil aus der Registry.
|
||||||
|
"""
|
||||||
|
from app.core.chunking import get_chunk_config
|
||||||
|
profiles = 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)
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
"""
|
||||||
|
FILE: app/core/ingestion/ingestion_validation.py
|
||||||
|
DESCRIPTION: WP-15b semantische Validierung von Kanten gegen den LocalBatchCache.
|
||||||
|
WP-25b: Umstellung auf Lazy-Prompt-Orchestration (prompt_key + variables).
|
||||||
|
VERSION: 2.14.0 (WP-25b: Lazy Prompt Integration)
|
||||||
|
STATUS: Active
|
||||||
|
FIX:
|
||||||
|
- WP-25b: Entfernung manueller Prompt-Formatierung zur Unterstützung modell-spezifischer Prompts.
|
||||||
|
- WP-25b: Umstellung auf generate_raw_response mit prompt_key="edge_validation".
|
||||||
|
- WP-25a: Voller Erhalt der MoE-Profilsteuerung und Fallback-Kaskade via LLMService.
|
||||||
|
"""
|
||||||
|
import logging
|
||||||
|
from typing import Dict, Any, Optional
|
||||||
|
from app.core.parser import NoteContext
|
||||||
|
|
||||||
|
# ENTSCHEIDENDER FIX: Import der neutralen Bereinigungs-Logik zur Vermeidung von Circular Imports
|
||||||
|
from app.core.registry import clean_llm_text
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
async def validate_edge_candidate(
|
||||||
|
chunk_text: str,
|
||||||
|
edge: Dict,
|
||||||
|
batch_cache: Dict[str, NoteContext],
|
||||||
|
llm_service: Any,
|
||||||
|
provider: Optional[str] = None,
|
||||||
|
profile_name: str = "ingest_validator"
|
||||||
|
) -> bool:
|
||||||
|
"""
|
||||||
|
WP-15b/25b: Validiert einen Kandidaten semantisch gegen das Ziel im Cache.
|
||||||
|
Nutzt Lazy-Prompt-Loading zur Unterstützung modell-spezifischer Validierungs-Templates.
|
||||||
|
"""
|
||||||
|
target_id = edge.get("to")
|
||||||
|
target_ctx = batch_cache.get(target_id)
|
||||||
|
|
||||||
|
# Robust Lookup Fix (v2.12.2): Support für Anker
|
||||||
|
if not target_ctx and "#" in target_id:
|
||||||
|
base_id = target_id.split("#")[0]
|
||||||
|
target_ctx = batch_cache.get(base_id)
|
||||||
|
|
||||||
|
# Sicherheits-Fallback (Hard-Link Integrity)
|
||||||
|
# Explizite Wikilinks oder Callouts werden nicht durch das LLM verifiziert.
|
||||||
|
if not target_ctx:
|
||||||
|
logger.info(f"ℹ️ [VALIDATION SKIP] No context for '{target_id}' - allowing link.")
|
||||||
|
return True
|
||||||
|
|
||||||
|
try:
|
||||||
|
logger.info(f"⚖️ [VALIDATING] Relation '{edge.get('kind')}' -> '{target_id}' (Profile: {profile_name})...")
|
||||||
|
|
||||||
|
# WP-25b: Lazy-Prompt Aufruf.
|
||||||
|
# Wir übergeben keine formatierte Nachricht mehr, sondern Key und Daten-Dict.
|
||||||
|
# Das manuelle 'template = llm_service.get_prompt(...)' entfällt hier.
|
||||||
|
raw_response = await llm_service.generate_raw_response(
|
||||||
|
prompt_key="edge_validation",
|
||||||
|
variables={
|
||||||
|
"chunk_text": chunk_text[:1500],
|
||||||
|
"target_title": target_ctx.title,
|
||||||
|
"target_summary": target_ctx.summary,
|
||||||
|
"edge_kind": edge.get("kind", "related_to")
|
||||||
|
},
|
||||||
|
priority="background",
|
||||||
|
profile_name=profile_name
|
||||||
|
)
|
||||||
|
|
||||||
|
# WP-14 Fix: Bereinigung zur Sicherstellung der Interpretierbarkeit
|
||||||
|
response = clean_llm_text(raw_response)
|
||||||
|
|
||||||
|
# Semantische Prüfung des Ergebnisses
|
||||||
|
is_valid = "YES" in response.upper()
|
||||||
|
|
||||||
|
if is_valid:
|
||||||
|
logger.info(f"✅ [VALIDATED] Relation to '{target_id}' confirmed.")
|
||||||
|
else:
|
||||||
|
logger.info(f"🚫 [REJECTED] Relation to '{target_id}' irrelevant for this chunk.")
|
||||||
|
return is_valid
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
error_str = str(e).lower()
|
||||||
|
error_type = type(e).__name__
|
||||||
|
|
||||||
|
# WP-25b FIX: Differenzierung zwischen transienten und permanenten Fehlern
|
||||||
|
# Transiente Fehler (Timeout, Network) → erlauben (Datenverlust vermeiden)
|
||||||
|
if any(x in error_str for x in ["timeout", "connection", "network", "unreachable", "refused"]):
|
||||||
|
logger.warning(f"⚠️ Transient error for {target_id} using {profile_name}: {error_type} - {e}. Allowing edge.")
|
||||||
|
return True
|
||||||
|
|
||||||
|
# Permanente Fehler (Config, Validation, Invalid Response) → ablehnen (Graph-Qualität)
|
||||||
|
logger.error(f"❌ Permanent validation error for {target_id} using {profile_name}: {error_type} - {e}")
|
||||||
|
return False
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
import logging
|
||||||
|
import os
|
||||||
|
from logging.handlers import RotatingFileHandler
|
||||||
|
|
||||||
|
def setup_logging():
|
||||||
|
# 1. Log-Verzeichnis erstellen (falls nicht vorhanden)
|
||||||
|
log_dir = "logs"
|
||||||
|
if not os.path.exists(log_dir):
|
||||||
|
os.makedirs(log_dir)
|
||||||
|
|
||||||
|
log_file = os.path.join(log_dir, "mindnet.log")
|
||||||
|
|
||||||
|
# 2. Formatter definieren (Zeitstempel | Level | Modul | Nachricht)
|
||||||
|
formatter = logging.Formatter(
|
||||||
|
'%(asctime)s | %(levelname)-8s | %(name)s | %(message)s',
|
||||||
|
datefmt='%Y-%m-%d %H:%M:%S'
|
||||||
|
)
|
||||||
|
|
||||||
|
# 3. File Handler: Schreibt in Datei (max. 5MB pro Datei, behält 5 Backups)
|
||||||
|
file_handler = RotatingFileHandler(
|
||||||
|
log_file, maxBytes=5*1024*1024, backupCount=5, encoding='utf-8'
|
||||||
|
)
|
||||||
|
file_handler.setFormatter(formatter)
|
||||||
|
file_handler.setLevel(logging.INFO)
|
||||||
|
|
||||||
|
# 4. Stream Handler: Schreibt weiterhin auf die Konsole
|
||||||
|
console_handler = logging.StreamHandler()
|
||||||
|
console_handler.setFormatter(formatter)
|
||||||
|
console_handler.setLevel(logging.INFO)
|
||||||
|
|
||||||
|
# 5. Root Logger konfigurieren
|
||||||
|
logging.basicConfig(
|
||||||
|
level=logging.INFO,
|
||||||
|
handlers=[file_handler, console_handler]
|
||||||
|
)
|
||||||
|
|
||||||
|
logging.info(f"📝 Logging initialized. Writing to {log_file}")
|
||||||
@@ -1,268 +0,0 @@
|
|||||||
"""
|
|
||||||
FILE: app/core/note_payload.py
|
|
||||||
DESCRIPTION: Baut das JSON-Objekt.
|
|
||||||
FEATURES:
|
|
||||||
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').
|
|
||||||
VERSION: 2.3.0
|
|
||||||
STATUS: Active
|
|
||||||
DEPENDENCIES: yaml, os, json, pathlib, hashlib
|
|
||||||
EXTERNAL_CONFIG: config/types.yaml
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
from typing import Any, Dict, Tuple, Optional
|
|
||||||
import os
|
|
||||||
import json
|
|
||||||
import pathlib
|
|
||||||
import hashlib
|
|
||||||
|
|
||||||
try:
|
|
||||||
import yaml # type: ignore
|
|
||||||
except Exception:
|
|
||||||
yaml = None
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
# Helper
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
|
|
||||||
def _as_dict(x) -> Dict[str, Any]:
|
|
||||||
"""Versucht, ein ParsedMarkdown-ähnliches Objekt in ein Dict zu überführen."""
|
|
||||||
if isinstance(x, dict):
|
|
||||||
return dict(x)
|
|
||||||
|
|
||||||
out: Dict[str, Any] = {}
|
|
||||||
for attr in (
|
|
||||||
"frontmatter",
|
|
||||||
"body",
|
|
||||||
"id",
|
|
||||||
"note_id",
|
|
||||||
"title",
|
|
||||||
"path",
|
|
||||||
"tags",
|
|
||||||
"type",
|
|
||||||
"created",
|
|
||||||
"modified",
|
|
||||||
"date",
|
|
||||||
):
|
|
||||||
if hasattr(x, attr):
|
|
||||||
val = getattr(x, attr)
|
|
||||||
if val is not None:
|
|
||||||
out[attr] = val
|
|
||||||
|
|
||||||
if not out:
|
|
||||||
out["raw"] = str(x)
|
|
||||||
|
|
||||||
return out
|
|
||||||
|
|
||||||
|
|
||||||
def _pick_args(*args, **kwargs) -> Tuple[Optional[str], Optional[dict]]:
|
|
||||||
path = kwargs.get("path") or (args[0] if args else None)
|
|
||||||
types_cfg = kwargs.get("types_cfg") or kwargs.get("types") or None
|
|
||||||
return path, types_cfg
|
|
||||||
|
|
||||||
|
|
||||||
def _env_float(name: str, default: float) -> float:
|
|
||||||
try:
|
|
||||||
return float(os.environ.get(name, default))
|
|
||||||
except Exception:
|
|
||||||
return default
|
|
||||||
|
|
||||||
|
|
||||||
def _ensure_list(x) -> list:
|
|
||||||
if x is None:
|
|
||||||
return []
|
|
||||||
if isinstance(x, list):
|
|
||||||
return [str(i) for i in x]
|
|
||||||
if isinstance(x, (set, tuple)):
|
|
||||||
return [str(i) for i in 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
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
|
|
||||||
def _load_types_config(explicit_cfg: Optional[dict] = None) -> dict:
|
|
||||||
if explicit_cfg and isinstance(explicit_cfg, dict):
|
|
||||||
return explicit_cfg
|
|
||||||
|
|
||||||
path = os.getenv("MINDNET_TYPES_FILE") or "./config/types.yaml"
|
|
||||||
if not os.path.isfile(path) or yaml is None:
|
|
||||||
return {}
|
|
||||||
|
|
||||||
try:
|
|
||||||
with open(path, "r", encoding="utf-8") as f:
|
|
||||||
data = yaml.safe_load(f) or {}
|
|
||||||
return data if isinstance(data, dict) else {}
|
|
||||||
except Exception:
|
|
||||||
return {}
|
|
||||||
|
|
||||||
|
|
||||||
def _cfg_for_type(note_type: str, reg: dict) -> dict:
|
|
||||||
if not isinstance(reg, dict):
|
|
||||||
return {}
|
|
||||||
types = reg.get("types") if isinstance(reg.get("types"), dict) else reg
|
|
||||||
return types.get(note_type, {}) if isinstance(types, dict) else {}
|
|
||||||
|
|
||||||
|
|
||||||
def _cfg_defaults(reg: dict) -> dict:
|
|
||||||
if not isinstance(reg, dict):
|
|
||||||
return {}
|
|
||||||
for key in ("defaults", "default", "global"):
|
|
||||||
v = reg.get(key)
|
|
||||||
if isinstance(v, dict):
|
|
||||||
return v
|
|
||||||
return {}
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
# Haupt-API
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
|
|
||||||
def make_note_payload(note: Any, *args, **kwargs) -> Dict[str, Any]:
|
|
||||||
"""
|
|
||||||
Baut das Note-Payload für mindnet_notes auf.
|
|
||||||
Inkludiert Hash-Berechnung (Body & Full) und korrigierte Config-Lookups.
|
|
||||||
"""
|
|
||||||
n = _as_dict(note)
|
|
||||||
path_arg, types_cfg_explicit = _pick_args(*args, **kwargs)
|
|
||||||
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_type = fm.get("type") or n.get("type") or "concept"
|
|
||||||
note_type = str(fm_type)
|
|
||||||
|
|
||||||
cfg_type = _cfg_for_type(note_type, reg)
|
|
||||||
cfg_def = _cfg_defaults(reg)
|
|
||||||
|
|
||||||
# --- retriever_weight ---
|
|
||||||
default_rw = _env_float("MINDNET_DEFAULT_RETRIEVER_WEIGHT", 1.0)
|
|
||||||
retriever_weight = fm.get("retriever_weight")
|
|
||||||
if retriever_weight is None:
|
|
||||||
retriever_weight = cfg_type.get(
|
|
||||||
"retriever_weight",
|
|
||||||
cfg_def.get("retriever_weight", default_rw),
|
|
||||||
)
|
|
||||||
try:
|
|
||||||
retriever_weight = float(retriever_weight)
|
|
||||||
except Exception:
|
|
||||||
retriever_weight = default_rw
|
|
||||||
|
|
||||||
# --- chunk_profile (FIXED LOGIC) ---
|
|
||||||
# 1. Frontmatter Override (beide Schreibweisen erlaubt)
|
|
||||||
chunk_profile = fm.get("chunking_profile") or fm.get("chunk_profile")
|
|
||||||
|
|
||||||
# 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")
|
|
||||||
if edge_defaults is None:
|
|
||||||
edge_defaults = cfg_type.get(
|
|
||||||
"edge_defaults",
|
|
||||||
cfg_def.get("edge_defaults", []),
|
|
||||||
)
|
|
||||||
edge_defaults = _ensure_list(edge_defaults)
|
|
||||||
|
|
||||||
# --- Basis-Metadaten ---
|
|
||||||
note_id = n.get("note_id") or n.get("id") or fm.get("id")
|
|
||||||
title = n.get("title") or fm.get("title") or ""
|
|
||||||
path = n.get("path") or path_arg
|
|
||||||
if isinstance(path, pathlib.Path):
|
|
||||||
path = str(path)
|
|
||||||
|
|
||||||
payload: Dict[str, Any] = {
|
|
||||||
"note_id": note_id,
|
|
||||||
"title": title,
|
|
||||||
"type": note_type,
|
|
||||||
"path": path or "",
|
|
||||||
"retriever_weight": retriever_weight,
|
|
||||||
"chunk_profile": chunk_profile,
|
|
||||||
"edge_defaults": edge_defaults,
|
|
||||||
"hashes": {} # Init Hash Dict
|
|
||||||
}
|
|
||||||
|
|
||||||
# --- 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")
|
|
||||||
if tags:
|
|
||||||
payload["tags"] = _ensure_list(tags)
|
|
||||||
|
|
||||||
# Aliases
|
|
||||||
aliases = fm.get("aliases")
|
|
||||||
if aliases:
|
|
||||||
payload["aliases"] = _ensure_list(aliases)
|
|
||||||
|
|
||||||
# Zeit
|
|
||||||
for k in ("created", "modified", "date"):
|
|
||||||
v = fm.get(k) or n.get(k)
|
|
||||||
if v:
|
|
||||||
payload[k] = str(v)
|
|
||||||
|
|
||||||
# Fulltext
|
|
||||||
if "body" in n and n["body"]:
|
|
||||||
payload["fulltext"] = str(n["body"])
|
|
||||||
|
|
||||||
# JSON Validation
|
|
||||||
json.loads(json.dumps(payload, ensure_ascii=False))
|
|
||||||
|
|
||||||
return payload
|
|
||||||
@@ -1,233 +0,0 @@
|
|||||||
"""
|
|
||||||
FILE: app/core/parser.py
|
|
||||||
DESCRIPTION: Liest Markdown-Dateien fehlertolerant (Encoding-Fallback). Trennt Frontmatter (YAML) vom Body.
|
|
||||||
VERSION: 1.7.1
|
|
||||||
STATUS: Active
|
|
||||||
DEPENDENCIES: yaml, re, dataclasses, json, io, os
|
|
||||||
LAST_ANALYSIS: 2025-12-15
|
|
||||||
"""
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
from dataclasses import dataclass
|
|
||||||
from typing import Any, Dict, Optional, Tuple, Iterable, List
|
|
||||||
import io
|
|
||||||
import json
|
|
||||||
import os
|
|
||||||
import re
|
|
||||||
|
|
||||||
try:
|
|
||||||
import yaml # PyYAML
|
|
||||||
except Exception as e: # pragma: no cover
|
|
||||||
yaml = None # Fehler wird zur Laufzeit geworfen, falls wirklich benötigt
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------
|
|
||||||
# Datamodell
|
|
||||||
# ---------------------------------------------------------------------
|
|
||||||
|
|
||||||
@dataclass
|
|
||||||
class ParsedNote:
|
|
||||||
frontmatter: Dict[str, Any]
|
|
||||||
body: str
|
|
||||||
path: str
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------
|
|
||||||
# Frontmatter-Erkennung
|
|
||||||
# ---------------------------------------------------------------------
|
|
||||||
|
|
||||||
# Öffentliche Kompatibilitäts-Konstante: frühere Skripte importieren FRONTMATTER_RE
|
|
||||||
FRONTMATTER_RE = re.compile(r"^\s*---\s*$") # <— public
|
|
||||||
# Zusätzlich interner Alias (falls jemand ihn referenziert)
|
|
||||||
FRONTMATTER_END = FRONTMATTER_RE # <— public alias
|
|
||||||
|
|
||||||
# interne Namen bleiben bestehen
|
|
||||||
_FRONTMATTER_HEAD = FRONTMATTER_RE
|
|
||||||
_FRONTMATTER_END = FRONTMATTER_RE
|
|
||||||
|
|
||||||
|
|
||||||
def _split_frontmatter(text: str) -> Tuple[Dict[str, Any], str]:
|
|
||||||
"""
|
|
||||||
Zerlegt Text in (frontmatter: dict, body: str).
|
|
||||||
Erkennt Frontmatter nur, wenn die erste Zeile '---' ist und später ein zweites '---' folgt.
|
|
||||||
YAML-Fehler im Frontmatter führen NICHT zum Abbruch: es wird dann ein leeres dict benutzt.
|
|
||||||
"""
|
|
||||||
lines = text.splitlines(True) # keep line endings
|
|
||||||
if not lines:
|
|
||||||
return {}, ""
|
|
||||||
|
|
||||||
if not _FRONTMATTER_HEAD.match(lines[0]):
|
|
||||||
# kein Frontmatter-Header → gesamter Text ist Body
|
|
||||||
return {}, text
|
|
||||||
|
|
||||||
end_idx = None
|
|
||||||
# Suche nach nächstem '---' (max. 2000 Zeilen als Sicherheitslimit)
|
|
||||||
for i in range(1, min(len(lines), 2000)):
|
|
||||||
if _FRONTMATTER_END.match(lines[i]):
|
|
||||||
end_idx = i
|
|
||||||
break
|
|
||||||
|
|
||||||
if end_idx is None:
|
|
||||||
# unvollständiger Frontmatter-Block → behandle alles als Body
|
|
||||||
return {}, text
|
|
||||||
|
|
||||||
fm_raw = "".join(lines[1:end_idx])
|
|
||||||
body = "".join(lines[end_idx + 1:])
|
|
||||||
|
|
||||||
data: Dict[str, Any] = {}
|
|
||||||
if yaml is None:
|
|
||||||
raise RuntimeError("PyYAML ist nicht installiert (pip install pyyaml).")
|
|
||||||
|
|
||||||
try:
|
|
||||||
loaded = yaml.safe_load(fm_raw) or {}
|
|
||||||
if isinstance(loaded, dict):
|
|
||||||
data = loaded
|
|
||||||
else:
|
|
||||||
data = {}
|
|
||||||
except Exception as e:
|
|
||||||
# YAML-Fehler nicht fatal machen
|
|
||||||
print(json.dumps({"warn": "frontmatter_yaml_parse_failed", "error": str(e)}))
|
|
||||||
data = {}
|
|
||||||
|
|
||||||
# optionales kosmetisches Trim: eine führende Leerzeile im Body entfernen
|
|
||||||
if body.startswith("\n"):
|
|
||||||
body = body[1:]
|
|
||||||
|
|
||||||
return data, body
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------
|
|
||||||
# Robustes Lesen mit Encoding-Fallback
|
|
||||||
# ---------------------------------------------------------------------
|
|
||||||
|
|
||||||
_FALLBACK_ENCODINGS: Tuple[str, ...] = ("utf-8", "utf-8-sig", "cp1252", "latin-1")
|
|
||||||
|
|
||||||
|
|
||||||
def _read_text_with_fallback(path: str) -> Tuple[str, str, bool]:
|
|
||||||
"""
|
|
||||||
Liest Datei mit mehreren Decodierungsversuchen.
|
|
||||||
Rückgabe: (text, used_encoding, had_fallback)
|
|
||||||
- had_fallback=True, falls NICHT 'utf-8' verwendet wurde (oder 'utf-8-sig').
|
|
||||||
"""
|
|
||||||
last_err: Optional[str] = None
|
|
||||||
for enc in _FALLBACK_ENCODINGS:
|
|
||||||
try:
|
|
||||||
with io.open(path, "r", encoding=enc, errors="strict") as f:
|
|
||||||
text = f.read()
|
|
||||||
# 'utf-8-sig' zählt hier als Fallback (weil BOM), aber ist unproblematisch
|
|
||||||
return text, enc, (enc != "utf-8")
|
|
||||||
except UnicodeDecodeError as e:
|
|
||||||
last_err = f"{type(e).__name__}: {e}"
|
|
||||||
continue
|
|
||||||
|
|
||||||
# Letzter, extrem defensiver Fallback: Bytes → UTF-8 mit REPLACE (keine Exception)
|
|
||||||
with open(path, "rb") as fb:
|
|
||||||
raw = fb.read()
|
|
||||||
text = raw.decode("utf-8", errors="replace")
|
|
||||||
print(json.dumps({
|
|
||||||
"path": path,
|
|
||||||
"warn": "encoding_fallback_exhausted",
|
|
||||||
"info": last_err or "unknown"
|
|
||||||
}, ensure_ascii=False))
|
|
||||||
return text, "utf-8(replace)", True
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------
|
|
||||||
# Öffentliche API
|
|
||||||
# ---------------------------------------------------------------------
|
|
||||||
|
|
||||||
def read_markdown(path: str) -> Optional[ParsedNote]:
|
|
||||||
"""
|
|
||||||
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):
|
|
||||||
return None
|
|
||||||
|
|
||||||
text, enc, had_fb = _read_text_with_fallback(path)
|
|
||||||
if had_fb:
|
|
||||||
print(json.dumps({"path": path, "warn": "encoding_fallback_used", "used": enc}, ensure_ascii=False))
|
|
||||||
|
|
||||||
fm, body = _split_frontmatter(text)
|
|
||||||
return ParsedNote(frontmatter=fm or {}, body=body or "", path=path)
|
|
||||||
|
|
||||||
|
|
||||||
def validate_required_frontmatter(fm: Dict[str, Any],
|
|
||||||
required: Tuple[str, ...] = ("id", "title")) -> None:
|
|
||||||
"""
|
|
||||||
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:
|
|
||||||
fm = {}
|
|
||||||
missing = []
|
|
||||||
for k in required:
|
|
||||||
v = fm.get(k)
|
|
||||||
if v is None:
|
|
||||||
missing.append(k)
|
|
||||||
elif isinstance(v, str) and not v.strip():
|
|
||||||
missing.append(k)
|
|
||||||
if 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)):
|
|
||||||
raise ValueError("frontmatter 'tags' must be a list of strings")
|
|
||||||
|
|
||||||
|
|
||||||
def normalize_frontmatter(fm: Dict[str, Any]) -> Dict[str, Any]:
|
|
||||||
"""
|
|
||||||
Sanfte Normalisierung ohne Semantikänderung:
|
|
||||||
- 'tags' → Liste von Strings (Trim)
|
|
||||||
- 'embedding_exclude' → bool
|
|
||||||
- andere Felder unverändert
|
|
||||||
"""
|
|
||||||
out = dict(fm or {})
|
|
||||||
if "tags" in out:
|
|
||||||
if isinstance(out["tags"], str):
|
|
||||||
out["tags"] = [out["tags"].strip()] if out["tags"].strip() else []
|
|
||||||
elif isinstance(out["tags"], list):
|
|
||||||
out["tags"] = [str(t).strip() for t in out["tags"] if t is not None]
|
|
||||||
else:
|
|
||||||
out["tags"] = [str(out["tags"]).strip()] if out["tags"] not in (None, "") else []
|
|
||||||
if "embedding_exclude" in out:
|
|
||||||
out["embedding_exclude"] = bool(out["embedding_exclude"])
|
|
||||||
return out
|
|
||||||
|
|
||||||
|
|
||||||
# ------------------------------ Wikilinks ---------------------------- #
|
|
||||||
|
|
||||||
# Basismuster für [[...]]; die Normalisierung (id vor '#', vor '|') macht extract_wikilinks
|
|
||||||
_WIKILINK_RE = re.compile(r"\[\[([^\]]+)\]\]")
|
|
||||||
|
|
||||||
|
|
||||||
def extract_wikilinks(text: str) -> List[str]:
|
|
||||||
"""
|
|
||||||
Extrahiert Wikilinks wie [[id]], [[id#anchor]], [[id|label]], [[id#anchor|label]].
|
|
||||||
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:
|
|
||||||
return []
|
|
||||||
out: List[str] = []
|
|
||||||
for m in _WIKILINK_RE.finditer(text):
|
|
||||||
raw = (m.group(1) or "").strip()
|
|
||||||
if not raw:
|
|
||||||
continue
|
|
||||||
# Split an Pipe (Label) → links vor '|'
|
|
||||||
if "|" in raw:
|
|
||||||
raw = raw.split("|", 1)[0].strip()
|
|
||||||
# Split an Anchor
|
|
||||||
if "#" in raw:
|
|
||||||
raw = raw.split("#", 1)[0].strip()
|
|
||||||
if raw:
|
|
||||||
out.append(raw)
|
|
||||||
return out
|
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
"""
|
||||||
|
FILE: app/core/parser/__init__.py
|
||||||
|
DESCRIPTION: Package-Einstiegspunkt für den Parser.
|
||||||
|
Ermöglicht das Löschen der parser.py Facade.
|
||||||
|
VERSION: 1.10.0
|
||||||
|
"""
|
||||||
|
from .parsing_models import ParsedNote, NoteContext
|
||||||
|
from .parsing_utils import (
|
||||||
|
FRONTMATTER_RE, validate_required_frontmatter,
|
||||||
|
normalize_frontmatter, extract_wikilinks, extract_edges_with_context
|
||||||
|
)
|
||||||
|
from .parsing_markdown import read_markdown
|
||||||
|
from .parsing_scanner import pre_scan_markdown
|
||||||
|
|
||||||
|
# Kompatibilitäts-Alias
|
||||||
|
FRONTMATTER_END = FRONTMATTER_RE
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"ParsedNote", "NoteContext", "FRONTMATTER_RE", "FRONTMATTER_END",
|
||||||
|
"read_markdown", "pre_scan_markdown", "validate_required_frontmatter",
|
||||||
|
"normalize_frontmatter", "extract_wikilinks", "extract_edges_with_context"
|
||||||
|
]
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
"""
|
||||||
|
FILE: app/core/parsing/parsing_markdown.py
|
||||||
|
DESCRIPTION: Fehlertolerantes Einlesen von Markdown und Frontmatter-Splitting.
|
||||||
|
"""
|
||||||
|
import io
|
||||||
|
import os
|
||||||
|
import json
|
||||||
|
from typing import Any, Dict, Optional, Tuple
|
||||||
|
from .parsing_models import ParsedNote
|
||||||
|
from .parsing_utils import FRONTMATTER_RE
|
||||||
|
|
||||||
|
try:
|
||||||
|
import yaml
|
||||||
|
except ImportError:
|
||||||
|
yaml = None
|
||||||
|
|
||||||
|
_FALLBACK_ENCODINGS: Tuple[str, ...] = ("utf-8", "utf-8-sig", "cp1252", "latin-1")
|
||||||
|
|
||||||
|
def _split_frontmatter(text: str) -> Tuple[Dict[str, Any], str]:
|
||||||
|
"""Zerlegt Text in Frontmatter-Dict und Body."""
|
||||||
|
lines = text.splitlines(True)
|
||||||
|
if not lines or not FRONTMATTER_RE.match(lines[0]):
|
||||||
|
return {}, text
|
||||||
|
end_idx = None
|
||||||
|
for i in range(1, min(len(lines), 2000)):
|
||||||
|
if FRONTMATTER_RE.match(lines[i]):
|
||||||
|
end_idx = i
|
||||||
|
break
|
||||||
|
if end_idx is None: return {}, text
|
||||||
|
fm_raw = "".join(lines[1:end_idx])
|
||||||
|
body = "".join(lines[end_idx + 1:])
|
||||||
|
if yaml is None: raise RuntimeError("PyYAML not installed.")
|
||||||
|
try:
|
||||||
|
loaded = yaml.safe_load(fm_raw) or {}
|
||||||
|
data = loaded if isinstance(loaded, dict) else {}
|
||||||
|
except Exception as e:
|
||||||
|
print(json.dumps({"warn": "frontmatter_yaml_parse_failed", "error": str(e)}))
|
||||||
|
data = {}
|
||||||
|
if body.startswith("\n"): body = body[1:]
|
||||||
|
return data, body
|
||||||
|
|
||||||
|
def _read_text_with_fallback(path: str) -> Tuple[str, str, bool]:
|
||||||
|
"""Liest Datei mit Encoding-Fallback-Kette."""
|
||||||
|
last_err = None
|
||||||
|
for enc in _FALLBACK_ENCODINGS:
|
||||||
|
try:
|
||||||
|
with io.open(path, "r", encoding=enc, errors="strict") as f:
|
||||||
|
return f.read(), enc, (enc != "utf-8")
|
||||||
|
except UnicodeDecodeError as e:
|
||||||
|
last_err = str(e); continue
|
||||||
|
with open(path, "rb") as fb:
|
||||||
|
text = fb.read().decode("utf-8", errors="replace")
|
||||||
|
return text, "utf-8(replace)", True
|
||||||
|
|
||||||
|
def read_markdown(path: str) -> Optional[ParsedNote]:
|
||||||
|
"""Öffentliche API zum Einlesen einer Datei."""
|
||||||
|
if not os.path.exists(path): return None
|
||||||
|
text, enc, had_fb = _read_text_with_fallback(path)
|
||||||
|
fm, body = _split_frontmatter(text)
|
||||||
|
return ParsedNote(frontmatter=fm or {}, body=body or "", path=path)
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
"""
|
||||||
|
FILE: app/core/parsing/parsing_models.py
|
||||||
|
DESCRIPTION: Datenklassen für das Parsing-System.
|
||||||
|
"""
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from typing import Any, Dict, List
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class ParsedNote:
|
||||||
|
"""Container für eine vollständig eingelesene Markdown-Datei."""
|
||||||
|
frontmatter: Dict[str, Any]
|
||||||
|
body: str
|
||||||
|
path: str
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class NoteContext:
|
||||||
|
"""Metadaten-Container für den flüchtigen LocalBatchCache (Pass 1)."""
|
||||||
|
note_id: str
|
||||||
|
title: str
|
||||||
|
type: str
|
||||||
|
summary: str
|
||||||
|
tags: List[str]
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
"""
|
||||||
|
FILE: app/core/parsing/parsing_scanner.py
|
||||||
|
DESCRIPTION: Pre-Scan für den LocalBatchCache (Pass 1).
|
||||||
|
AUDIT v1.1.0: Dynamisierung der Scan-Parameter (WP-14).
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
from typing import Optional, Dict, Any
|
||||||
|
from .parsing_models import NoteContext
|
||||||
|
from .parsing_markdown import read_markdown
|
||||||
|
|
||||||
|
def pre_scan_markdown(path: str, registry: Optional[Dict[str, Any]] = None) -> Optional[NoteContext]:
|
||||||
|
"""
|
||||||
|
Extrahiert Identität und Kurz-Kontext zur Validierung.
|
||||||
|
WP-14: Scan-Tiefe und Summary-Länge sind nun über die Registry steuerbar.
|
||||||
|
"""
|
||||||
|
parsed = read_markdown(path)
|
||||||
|
if not parsed: return None
|
||||||
|
|
||||||
|
# WP-14: Konfiguration laden oder Standardwerte nutzen
|
||||||
|
reg = registry or {}
|
||||||
|
summary_cfg = reg.get("summary_settings", {})
|
||||||
|
scan_depth = summary_cfg.get("pre_scan_depth", 600)
|
||||||
|
max_len = summary_cfg.get("max_summary_length", 500)
|
||||||
|
|
||||||
|
fm = parsed.frontmatter
|
||||||
|
# ID-Findung: Frontmatter ID oder Dateiname als Fallback
|
||||||
|
note_id = str(fm.get("id") or os.path.splitext(os.path.basename(path))[0])
|
||||||
|
|
||||||
|
# Erstelle Kurz-Zusammenfassung mit dynamischen Limits
|
||||||
|
clean_body = re.sub(r'[#*`>]', '', parsed.body[:scan_depth]).strip()
|
||||||
|
summary = clean_body[:max_len] + "..." if len(clean_body) > max_len else clean_body
|
||||||
|
|
||||||
|
return NoteContext(
|
||||||
|
note_id=note_id,
|
||||||
|
title=str(fm.get("title", note_id)),
|
||||||
|
type=str(fm.get("type", "concept")),
|
||||||
|
summary=summary,
|
||||||
|
tags=fm.get("tags", []) if isinstance(fm.get("tags"), list) else []
|
||||||
|
)
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
"""
|
||||||
|
FILE: app/core/parsing/parsing_utils.py
|
||||||
|
DESCRIPTION: Werkzeuge zur Validierung, Normalisierung und Wikilink-Extraktion.
|
||||||
|
"""
|
||||||
|
import re
|
||||||
|
from typing import Any, Dict, List, Tuple, Optional
|
||||||
|
from .parsing_models import ParsedNote
|
||||||
|
|
||||||
|
# Öffentliche Konstanten für Abwärtskompatibilität
|
||||||
|
FRONTMATTER_RE = re.compile(r"^\s*---\s*$")
|
||||||
|
_WIKILINK_RE = re.compile(r"\[\[([^\]]+)\]\]")
|
||||||
|
|
||||||
|
def validate_required_frontmatter(fm: Dict[str, Any], required: Tuple[str, ...] = ("id", "title")) -> None:
|
||||||
|
"""Prüft, ob alle Pflichtfelder vorhanden sind."""
|
||||||
|
if fm is None: fm = {}
|
||||||
|
missing = []
|
||||||
|
for k in required:
|
||||||
|
v = fm.get(k)
|
||||||
|
if v is None or (isinstance(v, str) and not v.strip()):
|
||||||
|
missing.append(k)
|
||||||
|
if missing:
|
||||||
|
raise ValueError(f"Missing required frontmatter fields: {', '.join(missing)}")
|
||||||
|
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")
|
||||||
|
|
||||||
|
def normalize_frontmatter(fm: Dict[str, Any]) -> Dict[str, Any]:
|
||||||
|
"""Normalisierung von Tags und Boolean-Feldern."""
|
||||||
|
out = dict(fm or {})
|
||||||
|
if "tags" in out:
|
||||||
|
if isinstance(out["tags"], str):
|
||||||
|
out["tags"] = [out["tags"].strip()] if out["tags"].strip() else []
|
||||||
|
elif isinstance(out["tags"], list):
|
||||||
|
out["tags"] = [str(t).strip() for t in out["tags"] if t is not None]
|
||||||
|
else:
|
||||||
|
out["tags"] = [str(out["tags"]).strip()] if out["tags"] not in (None, "") else []
|
||||||
|
if "embedding_exclude" in out:
|
||||||
|
out["embedding_exclude"] = bool(out["embedding_exclude"])
|
||||||
|
return out
|
||||||
|
|
||||||
|
def extract_wikilinks(text: str) -> List[str]:
|
||||||
|
"""Extrahiert Wikilinks als einfache Liste von IDs."""
|
||||||
|
if not text: return []
|
||||||
|
out: List[str] = []
|
||||||
|
for m in _WIKILINK_RE.finditer(text):
|
||||||
|
raw = (m.group(1) or "").strip()
|
||||||
|
if not raw: continue
|
||||||
|
if "|" in raw: raw = raw.split("|", 1)[0].strip()
|
||||||
|
if "#" in raw: raw = raw.split("#", 1)[0].strip()
|
||||||
|
if raw: out.append(raw)
|
||||||
|
return out
|
||||||
|
|
||||||
|
def extract_edges_with_context(parsed: ParsedNote) -> List[Dict[str, Any]]:
|
||||||
|
"""WP-22: Extrahiert Wikilinks mit Zeilennummern für die EdgeRegistry."""
|
||||||
|
edges = []
|
||||||
|
if not parsed or not parsed.body: return edges
|
||||||
|
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
|
||||||
|
if "|" in raw:
|
||||||
|
parts = raw.split("|", 1)
|
||||||
|
target, kind = parts[0].strip(), parts[1].strip()
|
||||||
|
else:
|
||||||
|
target, kind = raw.strip(), "related_to"
|
||||||
|
if "#" in target: target = target.split("#", 1)[0].strip()
|
||||||
|
if target:
|
||||||
|
edges.append({"to": target, "kind": kind, "line": line_num, "provenance": "explicit"})
|
||||||
|
return edges
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
"""
|
||||||
|
FILE: app/core/registry.py
|
||||||
|
DESCRIPTION: Zentraler Base-Layer für Konfigurations-Loading und Text-Bereinigung.
|
||||||
|
Bricht Zirkelbezüge zwischen Ingestion und LLMService auf.
|
||||||
|
VERSION: 1.0.0
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import yaml
|
||||||
|
from typing import Optional, List
|
||||||
|
|
||||||
|
def load_type_registry(custom_path: Optional[str] = None) -> dict:
|
||||||
|
"""Lädt die types.yaml zur Steuerung der typ-spezifischen Logik."""
|
||||||
|
# Wir nutzen hier einen direkten Import von Settings, um Zyklen zu vermeiden
|
||||||
|
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 {}
|
||||||
|
|
||||||
|
def clean_llm_text(text: str, registry: Optional[dict] = None) -> str:
|
||||||
|
"""
|
||||||
|
Entfernt LLM-Steuerzeichen (<s>, [OUT] etc.) aus einem Text.
|
||||||
|
Wird sowohl für JSON-Parsing als auch für Chat-Antworten genutzt.
|
||||||
|
"""
|
||||||
|
if not text or not isinstance(text, str):
|
||||||
|
return ""
|
||||||
|
|
||||||
|
default_patterns = ["<s>", "</s>", "[OUT]", "[/OUT]"]
|
||||||
|
reg = registry or load_type_registry()
|
||||||
|
|
||||||
|
# Lade Patterns aus llm_settings (WP-14)
|
||||||
|
patterns: List[str] = reg.get("llm_settings", {}).get("cleanup_patterns", default_patterns)
|
||||||
|
|
||||||
|
clean = text
|
||||||
|
for p in patterns:
|
||||||
|
clean = clean.replace(p, "")
|
||||||
|
|
||||||
|
return clean.strip()
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
"""
|
||||||
|
PACKAGE: app.core.retrieval
|
||||||
|
DESCRIPTION: Zentrale Schnittstelle für Retrieval-Operationen (Vektor- & Graph-Suche).
|
||||||
|
Bündelt Suche und mathematische Scoring-Engine.
|
||||||
|
"""
|
||||||
|
from .retriever import (
|
||||||
|
Retriever,
|
||||||
|
hybrid_retrieve,
|
||||||
|
semantic_retrieve
|
||||||
|
)
|
||||||
|
|
||||||
|
from .retriever_scoring import (
|
||||||
|
get_weights,
|
||||||
|
compute_wp22_score,
|
||||||
|
get_status_multiplier
|
||||||
|
)
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"Retriever",
|
||||||
|
"hybrid_retrieve",
|
||||||
|
"semantic_retrieve",
|
||||||
|
"get_weights",
|
||||||
|
"compute_wp22_score",
|
||||||
|
"get_status_multiplier"
|
||||||
|
]
|
||||||
@@ -0,0 +1,288 @@
|
|||||||
|
"""
|
||||||
|
FILE: app/core/retrieval/decision_engine.py
|
||||||
|
DESCRIPTION: Der Agentic Orchestrator für MindNet (WP-25b Edition).
|
||||||
|
Realisiert Multi-Stream Retrieval, Intent-basiertes Routing
|
||||||
|
und die neue Lazy-Prompt Orchestrierung (Module A & B).
|
||||||
|
VERSION: 1.3.2 (WP-25b: Full Robustness Recovery & Regex Parsing)
|
||||||
|
STATUS: Active
|
||||||
|
FIX:
|
||||||
|
- WP-25b: ULTRA-Robustes Intent-Parsing via Regex (Fix: 'CODING[/S]' -> 'CODING').
|
||||||
|
- WP-25b: Wiederherstellung der prepend_instruction Logik via variables.
|
||||||
|
- WP-25a: Voller Erhalt der Profil-Kaskade via LLMService v3.5.5.
|
||||||
|
- WP-25: Beibehaltung von Stream-Tracing, Edge-Boosts und Pre-Initialization.
|
||||||
|
- RECOVERY: Wiederherstellung der lokalen Sicherheits-Gates aus v1.2.1.
|
||||||
|
"""
|
||||||
|
import asyncio
|
||||||
|
import logging
|
||||||
|
import yaml
|
||||||
|
import os
|
||||||
|
import re # Neu für robustes Intent-Parsing
|
||||||
|
from typing import List, Dict, Any, Optional
|
||||||
|
|
||||||
|
# Core & Service Imports
|
||||||
|
from app.models.dto import QueryRequest, QueryResponse
|
||||||
|
from app.core.retrieval.retriever import Retriever
|
||||||
|
from app.services.llm_service import LLMService
|
||||||
|
from app.config import get_settings
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
class DecisionEngine:
|
||||||
|
def __init__(self):
|
||||||
|
"""Initialisiert die Engine und lädt die modularen Konfigurationen."""
|
||||||
|
self.settings = get_settings()
|
||||||
|
self.retriever = Retriever()
|
||||||
|
self.llm_service = LLMService()
|
||||||
|
self.config = self._load_engine_config()
|
||||||
|
|
||||||
|
def _load_engine_config(self) -> Dict[str, Any]:
|
||||||
|
"""Lädt die Multi-Stream Konfiguration (WP-25/25a)."""
|
||||||
|
path = os.getenv("MINDNET_DECISION_CONFIG", "config/decision_engine.yaml")
|
||||||
|
if not os.path.exists(path):
|
||||||
|
logger.error(f"❌ Decision Engine Config not found at {path}")
|
||||||
|
return {"strategies": {}, "streams_library": {}}
|
||||||
|
try:
|
||||||
|
with open(path, "r", encoding="utf-8") as f:
|
||||||
|
config = yaml.safe_load(f) or {}
|
||||||
|
|
||||||
|
# WP-25b FIX: Schema-Validierung
|
||||||
|
required_keys = ["strategies", "streams_library"]
|
||||||
|
missing = [k for k in required_keys if k not in config]
|
||||||
|
if missing:
|
||||||
|
logger.error(f"❌ Missing required keys in decision_engine.yaml: {missing}")
|
||||||
|
return {"strategies": {}, "streams_library": {}}
|
||||||
|
|
||||||
|
# Warnung bei unbekannten Top-Level-Keys
|
||||||
|
known_keys = {"version", "settings", "strategies", "streams_library"}
|
||||||
|
unknown = set(config.keys()) - known_keys
|
||||||
|
if unknown:
|
||||||
|
logger.warning(f"⚠️ Unknown keys in decision_engine.yaml: {unknown}")
|
||||||
|
|
||||||
|
logger.info(f"⚙️ Decision Engine Config loaded (v{config.get('version', 'unknown')})")
|
||||||
|
return config
|
||||||
|
except yaml.YAMLError as e:
|
||||||
|
logger.error(f"❌ YAML syntax error in decision_engine.yaml: {e}")
|
||||||
|
return {"strategies": {}, "streams_library": {}}
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"❌ Failed to load decision_engine.yaml: {e}")
|
||||||
|
return {"strategies": {}, "streams_library": {}}
|
||||||
|
|
||||||
|
async def ask(self, query: str) -> str:
|
||||||
|
"""
|
||||||
|
Hauptmethode des MindNet Chats.
|
||||||
|
Orchestriert den agentischen Prozess: Routing -> Retrieval -> Kompression -> Synthese.
|
||||||
|
"""
|
||||||
|
# 1. Intent Recognition (Strategy Routing)
|
||||||
|
strategy_key = await self._determine_strategy(query)
|
||||||
|
|
||||||
|
strategies = self.config.get("strategies", {})
|
||||||
|
strategy = strategies.get(strategy_key)
|
||||||
|
|
||||||
|
if not strategy:
|
||||||
|
logger.warning(f"⚠️ Unknown strategy '{strategy_key}'. Fallback to FACT_WHAT.")
|
||||||
|
strategy_key = "FACT_WHAT"
|
||||||
|
strategy = strategies.get("FACT_WHAT")
|
||||||
|
|
||||||
|
if not strategy and strategies:
|
||||||
|
strategy_key = next(iter(strategies))
|
||||||
|
strategy = strategies[strategy_key]
|
||||||
|
|
||||||
|
if not strategy:
|
||||||
|
return "Entschuldigung, meine Wissensbasis ist aktuell nicht konfiguriert."
|
||||||
|
|
||||||
|
# 2. Multi-Stream Retrieval & Pre-Synthesis (Parallel Tasks inkl. Kompression)
|
||||||
|
stream_results = await self._execute_parallel_streams(strategy, query)
|
||||||
|
|
||||||
|
# 3. Finale Synthese
|
||||||
|
return await self._generate_final_answer(strategy_key, strategy, query, stream_results)
|
||||||
|
|
||||||
|
async def _determine_strategy(self, query: str) -> str:
|
||||||
|
"""WP-25b: Nutzt den LLM-Router via Lazy-Loading und bereinigt Modell-Artefakte via Regex."""
|
||||||
|
settings_cfg = self.config.get("settings", {})
|
||||||
|
prompt_key = settings_cfg.get("router_prompt_key", "intent_router_v1")
|
||||||
|
router_profile = settings_cfg.get("router_profile")
|
||||||
|
|
||||||
|
try:
|
||||||
|
# Delegation an LLMService ohne manuelle Vor-Formatierung
|
||||||
|
response = await self.llm_service.generate_raw_response(
|
||||||
|
prompt_key=prompt_key,
|
||||||
|
variables={"query": query},
|
||||||
|
max_retries=1,
|
||||||
|
priority="realtime",
|
||||||
|
profile_name=router_profile
|
||||||
|
)
|
||||||
|
|
||||||
|
# --- ULTRA-ROBUST PARSING (Fix für 'CODING[/S]') ---
|
||||||
|
# 1. Alles in Großbuchstaben umwandeln
|
||||||
|
raw_text = str(response).upper()
|
||||||
|
|
||||||
|
# 2. Regex: Suche das erste Wort, das nur aus A-Z und Unterstrichen besteht
|
||||||
|
# Dies ignoriert [/S], </s>, Newlines oder Plaudereien des Modells
|
||||||
|
match = re.search(r'\b(FACT_WHEN|FACT_WHAT|DECISION|EMPATHY|CODING|INTERVIEW)\b', raw_text)
|
||||||
|
|
||||||
|
if match:
|
||||||
|
intent = match.group(1)
|
||||||
|
logger.info(f"🎯 [ROUTING] Parsed Intent: '{intent}' from raw response: '{response.strip()}'")
|
||||||
|
return intent
|
||||||
|
|
||||||
|
# Fallback, falls Regex nicht greift
|
||||||
|
logger.warning(f"⚠️ Unmapped intent '{response.strip()}' from router. Falling back to FACT_WHAT.")
|
||||||
|
return "FACT_WHAT"
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Strategy Routing failed: {e}")
|
||||||
|
return "FACT_WHAT"
|
||||||
|
|
||||||
|
async def _execute_parallel_streams(self, strategy: Dict, query: str) -> Dict[str, str]:
|
||||||
|
"""Führt Such-Streams aus und komprimiert überlange Ergebnisse (Pre-Synthesis)."""
|
||||||
|
stream_keys = strategy.get("use_streams", [])
|
||||||
|
library = self.config.get("streams_library", {})
|
||||||
|
|
||||||
|
# Phase 1: Retrieval Tasks starten
|
||||||
|
retrieval_tasks = []
|
||||||
|
active_streams = []
|
||||||
|
for key in stream_keys:
|
||||||
|
stream_cfg = library.get(key)
|
||||||
|
if stream_cfg:
|
||||||
|
active_streams.append(key)
|
||||||
|
retrieval_tasks.append(self._run_single_stream(key, stream_cfg, query))
|
||||||
|
|
||||||
|
# Ergebnisse sammeln
|
||||||
|
retrieval_results = await asyncio.gather(*retrieval_tasks, return_exceptions=True)
|
||||||
|
|
||||||
|
# Phase 2: Formatierung und optionale Kompression
|
||||||
|
final_stream_tasks = []
|
||||||
|
for name, res in zip(active_streams, retrieval_results):
|
||||||
|
if isinstance(res, Exception):
|
||||||
|
logger.error(f"Stream '{name}' failed during retrieval: {res}")
|
||||||
|
async def _err(): return f"[Fehler im Wissens-Stream {name}]"
|
||||||
|
final_stream_tasks.append(_err())
|
||||||
|
continue
|
||||||
|
|
||||||
|
formatted_context = self._format_stream_context(res)
|
||||||
|
|
||||||
|
# WP-25a: Kompressions-Check (Inhaltsverdichtung)
|
||||||
|
stream_cfg = library.get(name, {})
|
||||||
|
threshold = stream_cfg.get("compression_threshold", 4000)
|
||||||
|
|
||||||
|
if len(formatted_context) > threshold:
|
||||||
|
logger.info(f"⚙️ [WP-25b] Triggering Lazy-Compression for stream '{name}'...")
|
||||||
|
comp_profile = stream_cfg.get("compression_profile")
|
||||||
|
final_stream_tasks.append(
|
||||||
|
self._compress_stream_content(name, formatted_context, query, comp_profile)
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
async def _direct(c=formatted_context): return c
|
||||||
|
final_stream_tasks.append(_direct())
|
||||||
|
|
||||||
|
# Finale Inhalte parallel fertigstellen
|
||||||
|
final_contents = await asyncio.gather(*final_stream_tasks)
|
||||||
|
return dict(zip(active_streams, final_contents))
|
||||||
|
|
||||||
|
async def _compress_stream_content(self, stream_name: str, content: str, query: str, profile: Optional[str]) -> str:
|
||||||
|
"""WP-25b: Inhaltsverdichtung via Lazy-Loading 'compression_template'."""
|
||||||
|
try:
|
||||||
|
summary = await self.llm_service.generate_raw_response(
|
||||||
|
prompt_key="compression_template",
|
||||||
|
variables={
|
||||||
|
"stream_name": stream_name,
|
||||||
|
"content": content,
|
||||||
|
"query": query
|
||||||
|
},
|
||||||
|
profile_name=profile,
|
||||||
|
priority="background",
|
||||||
|
max_retries=1
|
||||||
|
)
|
||||||
|
return summary.strip() if (summary and len(summary.strip()) > 10) else content
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"❌ Compression of {stream_name} failed: {e}")
|
||||||
|
return content
|
||||||
|
|
||||||
|
async def _run_single_stream(self, name: str, cfg: Dict, query: str) -> QueryResponse:
|
||||||
|
"""Spezialisierte Graph-Suche mit Stream-Tracing und Edge-Boosts."""
|
||||||
|
transformed_query = cfg.get("query_template", "{query}").format(query=query)
|
||||||
|
|
||||||
|
request = QueryRequest(
|
||||||
|
query=transformed_query,
|
||||||
|
top_k=cfg.get("top_k", 5),
|
||||||
|
filters={"type": cfg.get("filter_types", [])},
|
||||||
|
expand={"depth": 1},
|
||||||
|
boost_edges=cfg.get("edge_boosts", {}), # Erhalt der Gewichtung
|
||||||
|
explain=True
|
||||||
|
)
|
||||||
|
|
||||||
|
response = await self.retriever.search(request)
|
||||||
|
for hit in response.results:
|
||||||
|
hit.stream_origin = name
|
||||||
|
return response
|
||||||
|
|
||||||
|
def _format_stream_context(self, response: QueryResponse) -> str:
|
||||||
|
"""Wandelt QueryHits in einen formatierten Kontext-String um."""
|
||||||
|
if not response.results:
|
||||||
|
return "Keine spezifischen Informationen gefunden."
|
||||||
|
lines = []
|
||||||
|
for i, hit in enumerate(response.results, 1):
|
||||||
|
source = hit.source.get("path", "Unbekannt")
|
||||||
|
content = hit.source.get("text", "").strip()
|
||||||
|
lines.append(f"[{i}] QUELLE: {source}\nINHALT: {content}")
|
||||||
|
return "\n\n".join(lines)
|
||||||
|
|
||||||
|
async def _generate_final_answer(
|
||||||
|
self,
|
||||||
|
strategy_key: str,
|
||||||
|
strategy: Dict,
|
||||||
|
query: str,
|
||||||
|
stream_results: Dict[str, str]
|
||||||
|
) -> str:
|
||||||
|
"""WP-25b: Finale Synthese via Lazy-Prompt mit Robustheit aus v1.2.1."""
|
||||||
|
profile = strategy.get("llm_profile")
|
||||||
|
template_key = strategy.get("prompt_template", "fact_synthesis_v1")
|
||||||
|
system_prompt = self.llm_service.get_prompt("system_prompt")
|
||||||
|
|
||||||
|
# WP-25 ROBUSTNESS: Pre-Initialization der Variablen
|
||||||
|
all_possible_streams = ["values_stream", "facts_stream", "biography_stream", "risk_stream", "tech_stream"]
|
||||||
|
template_vars = {s: "" for s in all_possible_streams}
|
||||||
|
template_vars.update(stream_results)
|
||||||
|
template_vars["query"] = query
|
||||||
|
|
||||||
|
# WP-25a Erhalt: Prepend Instructions aus der strategy_config
|
||||||
|
prepend = strategy.get("prepend_instruction", "")
|
||||||
|
template_vars["prepend_instruction"] = prepend
|
||||||
|
|
||||||
|
try:
|
||||||
|
# WP-25b: Delegation der Synthese an den LLMService
|
||||||
|
response = await self.llm_service.generate_raw_response(
|
||||||
|
prompt_key=template_key,
|
||||||
|
variables=template_vars,
|
||||||
|
system=system_prompt,
|
||||||
|
profile_name=profile,
|
||||||
|
priority="realtime"
|
||||||
|
)
|
||||||
|
|
||||||
|
# WP-25a RECOVERY: Falls dieprepend_instruction nicht im Template-Key
|
||||||
|
# der prompts.yaml enthalten ist (WP-25b Lazy Loading), fügen wir sie
|
||||||
|
# hier manuell an den Anfang, um die Logik aus v1.2.1 zu bewahren.
|
||||||
|
if prepend and prepend not in response[:len(prepend)+50]:
|
||||||
|
logger.info("ℹ️ Adding prepend_instruction manually (not found in response).")
|
||||||
|
response = f"{prepend}\n\n{response}"
|
||||||
|
|
||||||
|
return response
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Final Synthesis failed: {e}")
|
||||||
|
# ROBUST FALLBACK (v1.2.1 Gate): Versuche eine minimale Antwort zu generieren
|
||||||
|
# WP-25b FIX: Konsistente Nutzung von prompt_key statt hardcodiertem Prompt
|
||||||
|
fallback_context = "\n\n".join([v for v in stream_results.values() if len(v) > 20])
|
||||||
|
try:
|
||||||
|
return await self.llm_service.generate_raw_response(
|
||||||
|
prompt_key="fallback_synthesis",
|
||||||
|
variables={"query": query, "context": fallback_context},
|
||||||
|
system=system_prompt, priority="realtime", profile_name=profile
|
||||||
|
)
|
||||||
|
except (ValueError, KeyError):
|
||||||
|
# Fallback auf direkten Prompt, falls Template nicht existiert
|
||||||
|
logger.warning("⚠️ Fallback template 'fallback_synthesis' not found. Using direct prompt.")
|
||||||
|
return await self.llm_service.generate_raw_response(
|
||||||
|
prompt=f"Beantworte: {query}\n\nKontext:\n{fallback_context}",
|
||||||
|
system=system_prompt, priority="realtime", profile_name=profile
|
||||||
|
)
|
||||||
@@ -1,12 +1,10 @@
|
|||||||
"""
|
"""
|
||||||
FILE: app/core/retriever.py
|
FILE: app/core/retrieval/retriever.py
|
||||||
DESCRIPTION: Haupt-Schnittstelle für die Suche. Orchestriert Vektorsuche und Graph-Expansion.
|
DESCRIPTION: Haupt-Schnittstelle für die Suche. Orchestriert Vektorsuche und Graph-Expansion.
|
||||||
Nutzt retriever_scoring.py für die WP-22 Logik.
|
WP-15c Update: Note-Level Diversity Pooling & Super-Edge Aggregation.
|
||||||
FIX: TypeError in embed_text (model_name) behoben.
|
VERSION: 0.7.0
|
||||||
FIX: Pydantic ValidationError (Target/Source) behoben.
|
|
||||||
VERSION: 0.6.15 (WP-22 Full & Stable)
|
|
||||||
STATUS: Active
|
STATUS: Active
|
||||||
DEPENDENCIES: app.config, app.models.dto, app.core.qdrant*, app.core.graph_adapter, app.core.retriever_scoring
|
DEPENDENCIES: app.config, app.models.dto, app.core.database*, app.core.graph_adapter
|
||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
@@ -14,19 +12,23 @@ import os
|
|||||||
import time
|
import time
|
||||||
import logging
|
import logging
|
||||||
from typing import Any, Dict, List, Tuple, Iterable, Optional
|
from typing import Any, Dict, List, Tuple, Iterable, Optional
|
||||||
|
from collections import defaultdict
|
||||||
|
|
||||||
from app.config import get_settings
|
from app.config import get_settings
|
||||||
from app.models.dto import (
|
from app.models.dto import (
|
||||||
QueryRequest, QueryResponse, QueryHit,
|
QueryRequest, QueryResponse, QueryHit,
|
||||||
Explanation, ScoreBreakdown, Reason, EdgeDTO
|
Explanation, ScoreBreakdown, Reason, EdgeDTO
|
||||||
)
|
)
|
||||||
import app.core.qdrant as qdr
|
|
||||||
import app.core.qdrant_points as qp
|
# MODULARISIERUNG: Neue Import-Pfade für die Datenbank-Ebene
|
||||||
|
import app.core.database.qdrant as qdr
|
||||||
|
import app.core.database.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.graph_subgraph as ga
|
||||||
|
|
||||||
# Mathematische Engine importieren
|
# Mathematische Engine importieren
|
||||||
from app.core.retriever_scoring import get_weights, compute_wp22_score
|
from app.core.retrieval.retriever_scoring import get_weights, compute_wp22_score
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
@@ -35,7 +37,7 @@ logger = logging.getLogger(__name__)
|
|||||||
# ==============================================================================
|
# ==============================================================================
|
||||||
|
|
||||||
def _get_client_and_prefix() -> Tuple[Any, str]:
|
def _get_client_and_prefix() -> Tuple[Any, str]:
|
||||||
"""Initialisiert Qdrant Client und lädt Collection-Prefix."""
|
"""Initialisiert Qdrant Client und lädt Collection-Prefix via database-Paket."""
|
||||||
cfg = qdr.QdrantConfig.from_env()
|
cfg = qdr.QdrantConfig.from_env()
|
||||||
return qdr.get_client(cfg), cfg.prefix
|
return qdr.get_client(cfg), cfg.prefix
|
||||||
|
|
||||||
@@ -68,7 +70,7 @@ def _semantic_hits(
|
|||||||
top_k: int,
|
top_k: int,
|
||||||
filters: Optional[Dict] = None
|
filters: Optional[Dict] = None
|
||||||
) -> List[Tuple[str, float, Dict[str, Any]]]:
|
) -> List[Tuple[str, float, Dict[str, Any]]]:
|
||||||
"""Führt die Vektorsuche durch und konvertiert Qdrant-Points in ein einheitliches Format."""
|
"""Führt die Vektorsuche via database-Points-Modul durch."""
|
||||||
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=filters)
|
||||||
# Strikte Typkonvertierung für Stabilität
|
# Strikte Typkonvertierung für Stabilität
|
||||||
return [(str(hit[0]), float(hit[1]), dict(hit[2] or {})) for hit in raw_hits]
|
return [(str(hit[0]), float(hit[1]), dict(hit[2] or {})) for hit in raw_hits]
|
||||||
@@ -87,7 +89,6 @@ def _build_explanation(
|
|||||||
) -> Explanation:
|
) -> Explanation:
|
||||||
"""
|
"""
|
||||||
Transformiert mathematische Scores und Graph-Signale in eine menschenlesbare Erklärung.
|
Transformiert mathematische Scores und Graph-Signale in eine menschenlesbare Erklärung.
|
||||||
Behebt Pydantic ValidationErrors durch explizite String-Sicherung.
|
|
||||||
"""
|
"""
|
||||||
_, edge_w_cfg, _ = get_weights()
|
_, edge_w_cfg, _ = get_weights()
|
||||||
base_val = scoring_debug["base_val"]
|
base_val = scoring_debug["base_val"]
|
||||||
@@ -114,12 +115,22 @@ def _build_explanation(
|
|||||||
elif semantic_score > 0.70:
|
elif semantic_score > 0.70:
|
||||||
reasons.append(Reason(kind="semantic", message="Inhaltliche Übereinstimmung.", score_impact=base_val))
|
reasons.append(Reason(kind="semantic", message="Inhaltliche Übereinstimmung.", score_impact=base_val))
|
||||||
|
|
||||||
# 3. Gründe für Typ und Lifecycle
|
# 3. Gründe für Typ und Lifecycle (WP-25 Vorbereitung)
|
||||||
type_weight = float(payload.get("retriever_weight", 1.0))
|
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 "De-priorisiert"
|
msg = "Bevorzugt" if type_weight > 1.0 else "De-priorisiert"
|
||||||
reasons.append(Reason(kind="type", message=f"{msg} durch Typ-Profil.", score_impact=base_val * (type_weight - 1.0)))
|
reasons.append(Reason(kind="type", message=f"{msg} durch Typ-Profil.", score_impact=base_val * (type_weight - 1.0)))
|
||||||
|
|
||||||
|
# NEU: Explizite Ausweisung des Lifecycle-Status (WP-22)
|
||||||
|
status_mult = scoring_debug.get("status_multiplier", 1.0)
|
||||||
|
if status_mult != 1.0:
|
||||||
|
status_msg = "Belohnt (Stable)" if status_mult > 1.0 else "De-priorisiert (Draft)"
|
||||||
|
reasons.append(Reason(
|
||||||
|
kind="status",
|
||||||
|
message=f"{status_msg} durch Content-Lifecycle.",
|
||||||
|
score_impact=semantic_score * (status_mult - 1.0)
|
||||||
|
))
|
||||||
|
|
||||||
# 4. Kanten-Verarbeitung (Graph-Intelligence)
|
# 4. Kanten-Verarbeitung (Graph-Intelligence)
|
||||||
if subgraph and target_note_id and scoring_debug["edge_bonus"] > 0:
|
if subgraph and target_note_id and scoring_debug["edge_bonus"] > 0:
|
||||||
raw_edges = []
|
raw_edges = []
|
||||||
@@ -129,7 +140,6 @@ def _build_explanation(
|
|||||||
raw_edges.extend(subgraph.get_outgoing_edges(target_note_id) or [])
|
raw_edges.extend(subgraph.get_outgoing_edges(target_note_id) or [])
|
||||||
|
|
||||||
for edge in raw_edges:
|
for edge in raw_edges:
|
||||||
# FIX: Zwingende String-Konvertierung für Pydantic-Stabilität
|
|
||||||
src = str(edge.get("source") or "note_root")
|
src = str(edge.get("source") or "note_root")
|
||||||
tgt = str(edge.get("target") or target_note_id or "unknown_target")
|
tgt = str(edge.get("target") or target_note_id or "unknown_target")
|
||||||
kind = str(edge.get("kind", "related_to"))
|
kind = str(edge.get("kind", "related_to"))
|
||||||
@@ -185,10 +195,14 @@ def _build_hits_from_semantic(
|
|||||||
explain: bool = False,
|
explain: bool = False,
|
||||||
dynamic_edge_boosts: Dict[str, float] = None
|
dynamic_edge_boosts: Dict[str, float] = None
|
||||||
) -> QueryResponse:
|
) -> QueryResponse:
|
||||||
"""Wandelt semantische Roh-Treffer in hochgeladene, bewertete QueryHits um."""
|
"""
|
||||||
|
Wandelt semantische Roh-Treffer in bewertete QueryHits um.
|
||||||
|
WP-15c: Implementiert Note-Level Diversity Pooling.
|
||||||
|
"""
|
||||||
t0 = time.time()
|
t0 = time.time()
|
||||||
enriched = []
|
enriched = []
|
||||||
|
|
||||||
|
# Erstes Scoring für alle Kandidaten
|
||||||
for pid, semantic_score, payload in hits:
|
for pid, semantic_score, payload in hits:
|
||||||
edge_bonus, cent_bonus = 0.0, 0.0
|
edge_bonus, cent_bonus = 0.0, 0.0
|
||||||
target_id = payload.get("note_id")
|
target_id = payload.get("note_id")
|
||||||
@@ -200,15 +214,30 @@ def _build_hits_from_semantic(
|
|||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
# Mathematisches Scoring via WP-22 Engine
|
|
||||||
debug_data = compute_wp22_score(
|
debug_data = compute_wp22_score(
|
||||||
semantic_score, payload, edge_bonus, cent_bonus, dynamic_edge_boosts
|
semantic_score, payload, edge_bonus, cent_bonus, dynamic_edge_boosts
|
||||||
)
|
)
|
||||||
enriched.append((pid, semantic_score, payload, debug_data))
|
enriched.append((pid, semantic_score, payload, debug_data))
|
||||||
|
|
||||||
# Sortierung nach finalem mathematischen Score
|
# 1. Sortierung nach finalem mathematischen Score
|
||||||
enriched_sorted = sorted(enriched, key=lambda h: h[3]["total"], reverse=True)
|
enriched_sorted = sorted(enriched, key=lambda h: h[3]["total"], reverse=True)
|
||||||
limited_hits = enriched_sorted[: max(1, top_k)]
|
|
||||||
|
# 2. WP-15c: Note-Level Diversity Pooling
|
||||||
|
# Wir behalten pro note_id nur den Hit mit dem höchsten total_score.
|
||||||
|
# Dies verhindert, dass 10 Chunks derselben Note andere KeyNotes verdrängen.
|
||||||
|
unique_note_hits = []
|
||||||
|
seen_notes = set()
|
||||||
|
|
||||||
|
for item in enriched_sorted:
|
||||||
|
_, _, payload, _ = item
|
||||||
|
note_id = str(payload.get("note_id", "unknown"))
|
||||||
|
|
||||||
|
if note_id not in seen_notes:
|
||||||
|
unique_note_hits.append(item)
|
||||||
|
seen_notes.add(note_id)
|
||||||
|
|
||||||
|
# 3. Begrenzung auf top_k nach dem Diversity-Pooling
|
||||||
|
limited_hits = unique_note_hits[: max(1, top_k)]
|
||||||
|
|
||||||
results: List[QueryHit] = []
|
results: List[QueryHit] = []
|
||||||
for pid, s_score, pl, dbg in limited_hits:
|
for pid, s_score, pl, dbg in limited_hits:
|
||||||
@@ -223,7 +252,6 @@ def _build_hits_from_semantic(
|
|||||||
applied_boosts=dynamic_edge_boosts
|
applied_boosts=dynamic_edge_boosts
|
||||||
)
|
)
|
||||||
|
|
||||||
# Payload Text-Feld normalisieren
|
|
||||||
text_content = pl.get("page_content") or pl.get("text") or pl.get("content", "[Kein Text]")
|
text_content = pl.get("page_content") or pl.get("text") or pl.get("content", "[Kein Text]")
|
||||||
|
|
||||||
results.append(QueryHit(
|
results.append(QueryHit(
|
||||||
@@ -248,14 +276,14 @@ def _build_hits_from_semantic(
|
|||||||
def hybrid_retrieve(req: QueryRequest) -> QueryResponse:
|
def hybrid_retrieve(req: QueryRequest) -> QueryResponse:
|
||||||
"""
|
"""
|
||||||
Die Haupt-Einstiegsfunktion für die hybride Suche.
|
Die Haupt-Einstiegsfunktion für die hybride Suche.
|
||||||
Kombiniert Vektorsuche mit Graph-Expansion, Provenance-Weighting und Intent-Boosting.
|
WP-15c: Implementiert Edge-Aggregation (Super-Kanten).
|
||||||
"""
|
"""
|
||||||
client, prefix = _get_client_and_prefix()
|
client, prefix = _get_client_and_prefix()
|
||||||
vector = list(req.query_vector) if req.query_vector else _get_query_vector(req)
|
vector = list(req.query_vector) if req.query_vector else _get_query_vector(req)
|
||||||
top_k = req.top_k or 10
|
top_k = req.top_k or 10
|
||||||
|
|
||||||
# 1. Semantische Seed-Suche
|
# 1. Semantische Seed-Suche (Wir laden etwas mehr für das Pooling)
|
||||||
hits = _semantic_hits(client, prefix, vector, top_k=top_k, filters=req.filters)
|
hits = _semantic_hits(client, prefix, vector, top_k=top_k * 3, filters=req.filters)
|
||||||
|
|
||||||
# 2. Graph Expansion Konfiguration
|
# 2. Graph Expansion Konfiguration
|
||||||
expand_cfg = req.expand if isinstance(req.expand, dict) else {}
|
expand_cfg = req.expand if isinstance(req.expand, dict) else {}
|
||||||
@@ -264,39 +292,76 @@ def hybrid_retrieve(req: QueryRequest) -> QueryResponse:
|
|||||||
|
|
||||||
subgraph: ga.Subgraph | None = None
|
subgraph: ga.Subgraph | None = None
|
||||||
if depth > 0 and hits:
|
if depth > 0 and hits:
|
||||||
# Start-IDs für den Graph-Traversal sammeln
|
|
||||||
seed_ids = list({h[2].get("note_id") for h in hits if h[2].get("note_id")})
|
seed_ids = list({h[2].get("note_id") for h in hits if h[2].get("note_id")})
|
||||||
|
|
||||||
if seed_ids:
|
if seed_ids:
|
||||||
try:
|
try:
|
||||||
# Subgraph aus RAM/DB laden
|
|
||||||
subgraph = ga.expand(client, prefix, seed_ids, depth=depth, edge_types=expand_cfg.get("edge_types"))
|
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 ---
|
# --- WP-15c: Edge-Aggregation & Deduplizierung (Super-Kanten) ---
|
||||||
if subgraph and hasattr(subgraph, "graph"):
|
# Verhindert Score-Explosion durch multiple Links auf versch. Abschnitte.
|
||||||
for _, _, data in subgraph.graph.edges(data=True):
|
# Logik: 1. Kante zählt voll, weitere dämpfen auf Faktor 0.1.
|
||||||
# A. Provenance Weighting (WP-22 Bonus für Herkunft)
|
if subgraph and hasattr(subgraph, "adj"):
|
||||||
prov = data.get("provenance", "rule")
|
for src, edge_list in subgraph.adj.items():
|
||||||
# Belohnung: Explizite Links (1.0) > Smart (0.9) > Rule (0.7)
|
# Gruppiere Kanten nach Ziel-Note (Deduplizierung ID_A -> ID_B)
|
||||||
prov_w = 1.0 if prov == "explicit" else (0.9 if prov == "smart" else 0.7)
|
by_target = defaultdict(list)
|
||||||
|
for e in edge_list:
|
||||||
|
by_target[e["target"]].append(e)
|
||||||
|
|
||||||
# B. Intent Boost Multiplikator (Vom Router dynamisch injiziert)
|
aggregated_list = []
|
||||||
kind = data.get("kind")
|
for tgt, edges in by_target.items():
|
||||||
intent_multiplier = boost_edges.get(kind, 1.0)
|
if len(edges) > 1:
|
||||||
|
# Sortiere: Stärkste Kante zuerst
|
||||||
|
sorted_edges = sorted(edges, key=lambda x: x.get("weight", 0.0), reverse=True)
|
||||||
|
primary = sorted_edges[0]
|
||||||
|
|
||||||
# Finales Gewicht setzen (Basis * Provenance * Intent)
|
# Aggregiertes Gewicht berechnen (Sättigungs-Logik)
|
||||||
data["weight"] = data.get("weight", 1.0) * prov_w * intent_multiplier
|
total_w = primary.get("weight", 0.0)
|
||||||
|
for secondary in sorted_edges[1:]:
|
||||||
|
total_w += secondary.get("weight", 0.0) * 0.1
|
||||||
|
|
||||||
|
primary["weight"] = total_w
|
||||||
|
primary["is_super_edge"] = True # Flag für Explanation Layer
|
||||||
|
primary["edge_count"] = len(edges)
|
||||||
|
aggregated_list.append(primary)
|
||||||
|
else:
|
||||||
|
aggregated_list.append(edges[0])
|
||||||
|
|
||||||
|
# In-Place Update der Adjazenzliste des Graphen
|
||||||
|
subgraph.adj[src] = aggregated_list
|
||||||
|
|
||||||
|
# Re-Sync der In-Degrees für Centrality-Bonus (Aggregation konsistent halten)
|
||||||
|
subgraph.in_degree = defaultdict(int)
|
||||||
|
for src, edges in subgraph.adj.items():
|
||||||
|
for e in edges:
|
||||||
|
subgraph.in_degree[e["target"]] += 1
|
||||||
|
|
||||||
|
# --- WP-22: Kanten-Gewichtung (Provenance & Intent Boost) ---
|
||||||
|
if subgraph and hasattr(subgraph, "adj"):
|
||||||
|
for src, edges in subgraph.adj.items():
|
||||||
|
for e in edges:
|
||||||
|
# A. Provenance Weighting
|
||||||
|
prov = e.get("provenance", "rule")
|
||||||
|
prov_w = 1.0 if prov == "explicit" else (0.9 if prov == "smart" else 0.7)
|
||||||
|
|
||||||
|
# B. Intent Boost Multiplikator
|
||||||
|
kind = e.get("kind")
|
||||||
|
intent_multiplier = boost_edges.get(kind, 1.0)
|
||||||
|
|
||||||
|
# Gewichtung anpassen
|
||||||
|
e["weight"] = e.get("weight", 1.0) * prov_w * intent_multiplier
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Graph Expansion failed: {e}")
|
logger.error(f"Graph Expansion failed: {e}")
|
||||||
subgraph = None
|
subgraph = None
|
||||||
|
|
||||||
# 3. Scoring & Explanation Generierung
|
# 3. Scoring & Explanation Generierung
|
||||||
|
# top_k wird erst hier final angewandt
|
||||||
return _build_hits_from_semantic(hits, top_k, "hybrid", subgraph, req.explain, boost_edges)
|
return _build_hits_from_semantic(hits, top_k, "hybrid", subgraph, req.explain, boost_edges)
|
||||||
|
|
||||||
|
|
||||||
def semantic_retrieve(req: QueryRequest) -> QueryResponse:
|
def semantic_retrieve(req: QueryRequest) -> QueryResponse:
|
||||||
"""Standard Vektorsuche ohne Graph-Einfluss (WP-02 Fallback)."""
|
"""Standard Vektorsuche ohne Graph-Einfluss."""
|
||||||
client, prefix = _get_client_and_prefix()
|
client, prefix = _get_client_and_prefix()
|
||||||
vector = _get_query_vector(req)
|
vector = _get_query_vector(req)
|
||||||
hits = _semantic_hits(client, prefix, vector, req.top_k or 10, req.filters)
|
hits = _semantic_hits(client, prefix, vector, req.top_k or 10, req.filters)
|
||||||
@@ -306,5 +371,4 @@ def semantic_retrieve(req: QueryRequest) -> QueryResponse:
|
|||||||
class Retriever:
|
class Retriever:
|
||||||
"""Schnittstelle für die asynchrone Suche."""
|
"""Schnittstelle für die asynchrone Suche."""
|
||||||
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,10 +1,10 @@
|
|||||||
"""
|
"""
|
||||||
FILE: app/core/retriever_scoring.py
|
FILE: app/core/retrieval/retriever_scoring.py
|
||||||
DESCRIPTION: Mathematische Kern-Logik für das WP-22 Scoring.
|
DESCRIPTION: Mathematische Kern-Logik für das WP-22/WP-15c Scoring.
|
||||||
Berechnet Relevanz-Scores basierend auf Semantik, Graph-Intelligence und Content Lifecycle.
|
Berechnet Relevanz-Scores basierend auf Semantik, Graph-Intelligence und Content Lifecycle.
|
||||||
VERSION: 1.0.1 (WP-22 Full Math Engine)
|
FIX v1.0.3: Optimierte Interaktion zwischen Typ-Boost und Status-Dämpfung.
|
||||||
|
VERSION: 1.0.3
|
||||||
STATUS: Active
|
STATUS: Active
|
||||||
DEPENDENCIES: app.config, typing
|
|
||||||
"""
|
"""
|
||||||
import os
|
import os
|
||||||
import logging
|
import logging
|
||||||
@@ -22,10 +22,6 @@ logger = logging.getLogger(__name__)
|
|||||||
def get_weights() -> Tuple[float, float, float]:
|
def get_weights() -> Tuple[float, float, float]:
|
||||||
"""
|
"""
|
||||||
Liefert die Basis-Gewichtung (semantic, edge, centrality) aus der Konfiguration.
|
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
|
from app.config import get_settings
|
||||||
settings = get_settings()
|
settings = get_settings()
|
||||||
@@ -57,7 +53,7 @@ def get_status_multiplier(payload: Dict[str, Any]) -> float:
|
|||||||
|
|
||||||
- stable: 1.2 (Belohnung für verifiziertes Wissen)
|
- stable: 1.2 (Belohnung für verifiziertes Wissen)
|
||||||
- active: 1.0 (Standard-Gewichtung)
|
- active: 1.0 (Standard-Gewichtung)
|
||||||
- draft: 0.5 (Bestrafung für unfertige Fragmente)
|
- draft: 0.5 (Dämpfung für unfertige Fragmente)
|
||||||
"""
|
"""
|
||||||
status = str(payload.get("status", "active")).lower().strip()
|
status = str(payload.get("status", "active")).lower().strip()
|
||||||
if status == "stable":
|
if status == "stable":
|
||||||
@@ -74,35 +70,42 @@ def compute_wp22_score(
|
|||||||
dynamic_edge_boosts: Optional[Dict[str, float]] = None
|
dynamic_edge_boosts: Optional[Dict[str, float]] = None
|
||||||
) -> Dict[str, Any]:
|
) -> Dict[str, Any]:
|
||||||
"""
|
"""
|
||||||
Die zentrale mathematische Scoring-Formel der Mindnet Intelligence.
|
Die zentrale mathematische Scoring-Formel (WP-15c optimiert).
|
||||||
Implementiert das WP-22 Hybrid-Scoring (Semantic * Lifecycle * Graph).
|
Implementiert das Hybrid-Scoring (Semantic * Lifecycle * Graph).
|
||||||
|
|
||||||
FORMEL:
|
LOGIK:
|
||||||
Score = (Similarity * StatusMult) * (1 + (TypeWeight - 1) + ((EdgeW * EB + CentW * CB) * IntentBoost))
|
1. Base = Similarity * StatusMult (Lifecycle-Filter).
|
||||||
|
2. Boosts = (TypeBoost - 1) + (GraphBoni * IntentFactor).
|
||||||
|
3. Final = Base * (1 + Boosts).
|
||||||
|
|
||||||
Returns:
|
Der edge_bonus_raw enthält bereits die Super-Edge-Aggregation (WP-15c).
|
||||||
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()
|
sem_w, edge_w_cfg, cent_w_cfg = get_weights()
|
||||||
status_mult = get_status_multiplier(payload)
|
status_mult = get_status_multiplier(payload)
|
||||||
|
|
||||||
# Retriever Weight (Type Boost aus types.yaml, z.B. 1.1 für Decisions)
|
# Retriever Weight (Typ-Boost aus types.yaml, z.B. 1.1 für Decisions)
|
||||||
node_weight = float(payload.get("retriever_weight", 1.0))
|
node_weight = float(payload.get("retriever_weight", 1.0))
|
||||||
|
|
||||||
# 1. Berechnung des Base Scores (Semantik gewichtet durch Lifecycle-Status)
|
# 1. Berechnung des Base Scores (Semantik gewichtet durch Lifecycle-Status)
|
||||||
|
# WICHTIG: Der Status wirkt hier als Multiplikator auf die Basis-Relevanz.
|
||||||
base_val = float(semantic_score) * status_mult
|
base_val = float(semantic_score) * status_mult
|
||||||
|
|
||||||
# 2. Graph Boost Factor (Teil C: Intent-spezifische Verstärkung)
|
# 2. Graph Boost Factor (Intent-spezifische Verstärkung aus decision_engine.yaml)
|
||||||
# Erhöht das Gewicht des gesamten Graphen um 50%, wenn ein spezifischer Intent vorliegt.
|
# 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
|
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
|
# 3. Einzelne Graph-Komponenten berechnen
|
||||||
|
# WP-15c Hinweis: edge_bonus_raw ist durch den retriever.py bereits gedämpft/aggregiert.
|
||||||
edge_impact_final = (edge_w_cfg * edge_bonus_raw) * graph_boost_factor
|
edge_impact_final = (edge_w_cfg * edge_bonus_raw) * graph_boost_factor
|
||||||
cent_impact_final = (cent_w_cfg * cent_bonus_raw) * graph_boost_factor
|
cent_impact_final = (cent_w_cfg * cent_bonus_raw) * graph_boost_factor
|
||||||
|
|
||||||
# 4. Finales Zusammenführen (Merging)
|
# 4. Finales Zusammenführen (Merging)
|
||||||
# (node_weight - 1.0) sorgt dafür, dass ein Gewicht von 1.0 keinen Einfluss hat (neutral).
|
# (node_weight - 1.0) wandelt das Gewicht in einen relativen Bonus um (z.B. 1.2 -> +0.2).
|
||||||
total = base_val * (1.0 + (node_weight - 1.0) + edge_impact_final + cent_impact_final)
|
# Alle Boni werden addiert und wirken dann auf den base_val.
|
||||||
|
type_impact = node_weight - 1.0
|
||||||
|
total_boost = 1.0 + type_impact + edge_impact_final + cent_impact_final
|
||||||
|
|
||||||
|
total = base_val * total_boost
|
||||||
|
|
||||||
# Sicherstellen, dass der Score niemals 0 oder negativ ist (Floor)
|
# Sicherstellen, dass der Score niemals 0 oder negativ ist (Floor)
|
||||||
final_score = max(0.0001, float(total))
|
final_score = max(0.0001, float(total))
|
||||||
@@ -113,7 +116,7 @@ def compute_wp22_score(
|
|||||||
"cent_bonus": float(cent_bonus_raw),
|
"cent_bonus": float(cent_bonus_raw),
|
||||||
"status_multiplier": status_mult,
|
"status_multiplier": status_mult,
|
||||||
"graph_boost_factor": graph_boost_factor,
|
"graph_boost_factor": graph_boost_factor,
|
||||||
"type_impact": node_weight - 1.0,
|
"type_impact": type_impact,
|
||||||
"base_val": base_val,
|
"base_val": base_val,
|
||||||
"edge_impact_final": edge_impact_final,
|
"edge_impact_final": edge_impact_final,
|
||||||
"cent_impact_final": cent_impact_final
|
"cent_impact_final": cent_impact_final
|
||||||
@@ -69,20 +69,35 @@ def render_graph_explorer_cytoscape(graph_service):
|
|||||||
search_term = st.text_input("Suche Notiz", placeholder="Titel eingeben...", key="cy_search")
|
search_term = st.text_input("Suche Notiz", placeholder="Titel eingeben...", key="cy_search")
|
||||||
|
|
||||||
if search_term:
|
if search_term:
|
||||||
hits, _ = graph_service.client.scroll(
|
try:
|
||||||
collection_name=f"{COLLECTION_PREFIX}_notes",
|
hits, _ = graph_service.client.scroll(
|
||||||
limit=10,
|
collection_name=f"{COLLECTION_PREFIX}_notes",
|
||||||
scroll_filter=models.Filter(must=[models.FieldCondition(key="title", match=models.MatchText(text=search_term))])
|
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}
|
)
|
||||||
|
options = {}
|
||||||
|
for h in hits:
|
||||||
|
if h.payload and 'title' in h.payload and 'note_id' in h.payload:
|
||||||
|
title = h.payload['title']
|
||||||
|
note_id = h.payload['note_id']
|
||||||
|
# Vermeide Duplikate (falls mehrere Chunks/Notes denselben Titel haben)
|
||||||
|
if title not in options:
|
||||||
|
options[title] = note_id
|
||||||
|
|
||||||
if options:
|
if options:
|
||||||
selected_title = st.selectbox("Ergebnisse:", list(options.keys()), key="cy_select")
|
selected_title = st.selectbox("Ergebnisse:", list(options.keys()), key="cy_select")
|
||||||
if st.button("Laden", use_container_width=True, key="cy_load"):
|
if st.button("Laden", use_container_width=True, key="cy_load"):
|
||||||
new_id = options[selected_title]
|
new_id = options[selected_title]
|
||||||
st.session_state.graph_center_id = new_id
|
st.session_state.graph_center_id = new_id
|
||||||
st.session_state.graph_inspected_id = new_id
|
st.session_state.graph_inspected_id = new_id
|
||||||
st.rerun()
|
st.rerun()
|
||||||
|
else:
|
||||||
|
# Zeige Info, wenn keine Ergebnisse gefunden wurden
|
||||||
|
st.info(f"Keine Notizen mit '{search_term}' im Titel gefunden.")
|
||||||
|
except Exception as e:
|
||||||
|
st.error(f"Fehler bei der Suche: {e}")
|
||||||
|
import traceback
|
||||||
|
st.code(traceback.format_exc())
|
||||||
|
|
||||||
st.divider()
|
st.divider()
|
||||||
|
|
||||||
@@ -139,6 +154,26 @@ def render_graph_explorer_cytoscape(graph_service):
|
|||||||
# 2. Detail Daten (Inspector)
|
# 2. Detail Daten (Inspector)
|
||||||
inspected_data = graph_service.get_note_with_full_content(inspected_id)
|
inspected_data = graph_service.get_note_with_full_content(inspected_id)
|
||||||
|
|
||||||
|
# DEBUG: Zeige Debug-Informationen
|
||||||
|
with st.expander("🔍 Debug-Informationen", expanded=False):
|
||||||
|
st.write(f"**Gefundene Knoten:** {len(nodes_data) if nodes_data else 0}")
|
||||||
|
st.write(f"**Gefundene Kanten:** {len(edges_data) if edges_data else 0}")
|
||||||
|
if nodes_data:
|
||||||
|
st.write("**Knoten-IDs:**")
|
||||||
|
for n in nodes_data[:10]:
|
||||||
|
nid = getattr(n, 'id', 'N/A')
|
||||||
|
st.write(f" - {nid}")
|
||||||
|
if len(nodes_data) > 10:
|
||||||
|
st.write(f" ... und {len(nodes_data) - 10} weitere")
|
||||||
|
if edges_data:
|
||||||
|
st.write("**Kanten:**")
|
||||||
|
for e in edges_data[:10]:
|
||||||
|
src = getattr(e, "source", "N/A")
|
||||||
|
tgt = getattr(e, "to", getattr(e, "target", "N/A"))
|
||||||
|
st.write(f" - {src} -> {tgt}")
|
||||||
|
if len(edges_data) > 10:
|
||||||
|
st.write(f" ... und {len(edges_data) - 10} weitere")
|
||||||
|
|
||||||
# --- ACTION BAR ---
|
# --- ACTION BAR ---
|
||||||
action_container = st.container()
|
action_container = st.container()
|
||||||
with action_container:
|
with action_container:
|
||||||
@@ -174,7 +209,12 @@ def render_graph_explorer_cytoscape(graph_service):
|
|||||||
st.markdown(f"**ID:** `{inspected_data.get('note_id')}`")
|
st.markdown(f"**ID:** `{inspected_data.get('note_id')}`")
|
||||||
st.markdown(f"**Typ:** `{inspected_data.get('type')}`")
|
st.markdown(f"**Typ:** `{inspected_data.get('type')}`")
|
||||||
with col_i2:
|
with col_i2:
|
||||||
st.markdown(f"**Tags:** {', '.join(inspected_data.get('tags', []))}")
|
tags = inspected_data.get('tags', [])
|
||||||
|
if isinstance(tags, list):
|
||||||
|
tags_str = ', '.join(tags) if tags else "Keine"
|
||||||
|
else:
|
||||||
|
tags_str = str(tags) if tags else "Keine"
|
||||||
|
st.markdown(f"**Tags:** {tags_str}")
|
||||||
path_check = "✅" if inspected_data.get('path') else "❌"
|
path_check = "✅" if inspected_data.get('path') else "❌"
|
||||||
st.markdown(f"**Pfad:** {path_check}")
|
st.markdown(f"**Pfad:** {path_check}")
|
||||||
|
|
||||||
@@ -189,12 +229,27 @@ def render_graph_explorer_cytoscape(graph_service):
|
|||||||
# --- GRAPH ELEMENTS ---
|
# --- GRAPH ELEMENTS ---
|
||||||
cy_elements = []
|
cy_elements = []
|
||||||
|
|
||||||
|
# Validierung: Prüfe ob nodes_data vorhanden ist
|
||||||
|
if not nodes_data:
|
||||||
|
st.warning("⚠️ Keine Knoten gefunden. Bitte wähle eine andere Notiz.")
|
||||||
|
# Zeige trotzdem den Inspector, falls Daten vorhanden
|
||||||
|
if inspected_data:
|
||||||
|
st.info(f"**Hinweis:** Die Notiz '{inspected_data.get('title', inspected_id)}' wurde gefunden, hat aber keine Verbindungen im Graphen.")
|
||||||
|
return
|
||||||
|
|
||||||
|
# Erstelle Set aller Node-IDs für schnelle Validierung
|
||||||
|
node_ids = {n.id for n in nodes_data if hasattr(n, 'id') and n.id}
|
||||||
|
|
||||||
|
# Nodes hinzufügen
|
||||||
for n in nodes_data:
|
for n in nodes_data:
|
||||||
|
if not hasattr(n, 'id') or not n.id:
|
||||||
|
continue
|
||||||
|
|
||||||
is_center = (n.id == center_id)
|
is_center = (n.id == center_id)
|
||||||
is_inspected = (n.id == inspected_id)
|
is_inspected = (n.id == inspected_id)
|
||||||
|
|
||||||
tooltip_text = n.title if n.title else n.label
|
tooltip_text = getattr(n, 'title', None) or getattr(n, 'label', '')
|
||||||
display_label = n.label
|
display_label = getattr(n, 'label', str(n.id))
|
||||||
if len(display_label) > 15 and " " in display_label:
|
if len(display_label) > 15 and " " in display_label:
|
||||||
display_label = display_label.replace(" ", "\n", 1)
|
display_label = display_label.replace(" ", "\n", 1)
|
||||||
|
|
||||||
@@ -202,7 +257,7 @@ def render_graph_explorer_cytoscape(graph_service):
|
|||||||
"data": {
|
"data": {
|
||||||
"id": n.id,
|
"id": n.id,
|
||||||
"label": display_label,
|
"label": display_label,
|
||||||
"bg_color": n.color,
|
"bg_color": getattr(n, 'color', '#8395a7'),
|
||||||
"tooltip": tooltip_text
|
"tooltip": tooltip_text
|
||||||
},
|
},
|
||||||
# Wir steuern das Aussehen rein über Klassen (.inspected / .center)
|
# Wir steuern das Aussehen rein über Klassen (.inspected / .center)
|
||||||
@@ -211,18 +266,22 @@ def render_graph_explorer_cytoscape(graph_service):
|
|||||||
}
|
}
|
||||||
cy_elements.append(cy_node)
|
cy_elements.append(cy_node)
|
||||||
|
|
||||||
for e in edges_data:
|
# Edges hinzufügen - nur wenn beide Nodes im Graph vorhanden sind
|
||||||
target_id = getattr(e, "to", getattr(e, "target", None))
|
if edges_data:
|
||||||
if target_id:
|
for e in edges_data:
|
||||||
cy_edge = {
|
source_id = getattr(e, "source", None)
|
||||||
"data": {
|
target_id = getattr(e, "to", getattr(e, "target", None))
|
||||||
"source": e.source,
|
# Nur hinzufügen, wenn beide IDs vorhanden UND beide Nodes im Graph sind
|
||||||
"target": target_id,
|
if source_id and target_id and source_id in node_ids and target_id in node_ids:
|
||||||
"label": e.label,
|
cy_edge = {
|
||||||
"line_color": e.color
|
"data": {
|
||||||
|
"source": source_id,
|
||||||
|
"target": target_id,
|
||||||
|
"label": getattr(e, "label", ""),
|
||||||
|
"line_color": getattr(e, "color", "#bdc3c7")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
cy_elements.append(cy_edge)
|
||||||
cy_elements.append(cy_edge)
|
|
||||||
|
|
||||||
# --- STYLESHEET ---
|
# --- STYLESHEET ---
|
||||||
stylesheet = [
|
stylesheet = [
|
||||||
@@ -292,43 +351,47 @@ def render_graph_explorer_cytoscape(graph_service):
|
|||||||
]
|
]
|
||||||
|
|
||||||
# --- RENDER ---
|
# --- RENDER ---
|
||||||
graph_key = f"cy_{center_id}_{st.session_state.cy_depth}_{st.session_state.cy_ideal_edge_len}"
|
# Nur rendern, wenn Elemente vorhanden sind
|
||||||
|
if not cy_elements:
|
||||||
|
st.warning("⚠️ Keine Graph-Elemente zum Anzeigen gefunden.")
|
||||||
|
else:
|
||||||
|
graph_key = f"cy_{center_id}_{st.session_state.cy_depth}_{st.session_state.cy_ideal_edge_len}"
|
||||||
|
|
||||||
clicked_elements = cytoscape(
|
clicked_elements = cytoscape(
|
||||||
elements=cy_elements,
|
elements=cy_elements,
|
||||||
stylesheet=stylesheet,
|
stylesheet=stylesheet,
|
||||||
layout={
|
layout={
|
||||||
"name": "cose",
|
"name": "cose",
|
||||||
"idealEdgeLength": st.session_state.cy_ideal_edge_len,
|
"idealEdgeLength": st.session_state.cy_ideal_edge_len,
|
||||||
"nodeOverlap": 20,
|
"nodeOverlap": 20,
|
||||||
"refresh": 20,
|
"refresh": 20,
|
||||||
"fit": True,
|
"fit": True,
|
||||||
"padding": 50,
|
"padding": 50,
|
||||||
"randomize": False,
|
"randomize": False,
|
||||||
"componentSpacing": 100,
|
"componentSpacing": 100,
|
||||||
"nodeRepulsion": st.session_state.cy_node_repulsion,
|
"nodeRepulsion": st.session_state.cy_node_repulsion,
|
||||||
"edgeElasticity": 100,
|
"edgeElasticity": 100,
|
||||||
"nestingFactor": 5,
|
"nestingFactor": 5,
|
||||||
"gravity": 80,
|
"gravity": 80,
|
||||||
"numIter": 1000,
|
"numIter": 1000,
|
||||||
"initialTemp": 200,
|
"initialTemp": 200,
|
||||||
"coolingFactor": 0.95,
|
"coolingFactor": 0.95,
|
||||||
"minTemp": 1.0,
|
"minTemp": 1.0,
|
||||||
"animate": False
|
"animate": False
|
||||||
},
|
},
|
||||||
key=graph_key,
|
key=graph_key,
|
||||||
height="700px"
|
height="700px"
|
||||||
)
|
)
|
||||||
|
|
||||||
# --- EVENT HANDLING ---
|
# --- EVENT HANDLING ---
|
||||||
if clicked_elements:
|
if clicked_elements:
|
||||||
clicked_nodes = clicked_elements.get("nodes", [])
|
clicked_nodes = clicked_elements.get("nodes", [])
|
||||||
if clicked_nodes:
|
if clicked_nodes:
|
||||||
clicked_id = clicked_nodes[0]
|
clicked_id = clicked_nodes[0]
|
||||||
|
|
||||||
if clicked_id != st.session_state.graph_inspected_id:
|
if clicked_id != st.session_state.graph_inspected_id:
|
||||||
st.session_state.graph_inspected_id = clicked_id
|
st.session_state.graph_inspected_id = clicked_id
|
||||||
st.rerun()
|
st.rerun()
|
||||||
|
|
||||||
else:
|
else:
|
||||||
st.info("👈 Bitte wähle links eine Notiz aus.")
|
st.info("👈 Bitte wähle links eine Notiz aus.")
|
||||||
@@ -10,15 +10,19 @@ LAST_ANALYSIS: 2025-12-15
|
|||||||
import re
|
import re
|
||||||
from qdrant_client import QdrantClient, models
|
from qdrant_client import QdrantClient, models
|
||||||
from streamlit_agraph import Node, Edge
|
from streamlit_agraph import Node, Edge
|
||||||
from ui_config import GRAPH_COLORS, get_edge_color, SYSTEM_EDGES
|
from ui_config import COLLECTION_PREFIX, GRAPH_COLORS, get_edge_color, SYSTEM_EDGES
|
||||||
|
|
||||||
class GraphExplorerService:
|
class GraphExplorerService:
|
||||||
def __init__(self, url, api_key=None, prefix="mindnet"):
|
def __init__(self, url, api_key=None, prefix=None):
|
||||||
|
"""
|
||||||
|
Initialisiert den Service. Nutzt COLLECTION_PREFIX aus der Config,
|
||||||
|
sofern kein spezifischer Prefix übergeben wurde.
|
||||||
|
"""
|
||||||
self.client = QdrantClient(url=url, api_key=api_key)
|
self.client = QdrantClient(url=url, api_key=api_key)
|
||||||
self.prefix = prefix
|
self.prefix = prefix if prefix else COLLECTION_PREFIX
|
||||||
self.notes_col = f"{prefix}_notes"
|
self.notes_col = f"{self.prefix}_notes"
|
||||||
self.chunks_col = f"{prefix}_chunks"
|
self.chunks_col = f"{self.prefix}_chunks"
|
||||||
self.edges_col = f"{prefix}_edges"
|
self.edges_col = f"{self.prefix}_edges"
|
||||||
self._note_cache = {}
|
self._note_cache = {}
|
||||||
|
|
||||||
def get_note_with_full_content(self, note_id):
|
def get_note_with_full_content(self, note_id):
|
||||||
@@ -163,31 +167,33 @@ class GraphExplorerService:
|
|||||||
return previews
|
return previews
|
||||||
|
|
||||||
def _find_connected_edges(self, note_ids, note_title=None):
|
def _find_connected_edges(self, note_ids, note_title=None):
|
||||||
"""Findet eingehende und ausgehende Kanten."""
|
"""
|
||||||
|
Findet eingehende und ausgehende Kanten.
|
||||||
|
|
||||||
|
WICHTIG: target_id enthält nur den Titel (ohne #Abschnitt).
|
||||||
|
target_section ist ein separates Feld für Abschnitt-Informationen.
|
||||||
|
"""
|
||||||
results = []
|
results = []
|
||||||
|
if not note_ids:
|
||||||
|
return results
|
||||||
|
|
||||||
# 1. OUTGOING EDGES (Der "Owner"-Fix)
|
# 1. OUTGOING EDGES (Der "Owner"-Fix)
|
||||||
# Wir suchen Kanten, die im Feld 'note_id' (Owner) eine unserer Notizen haben.
|
# 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.
|
# Das findet ALLE ausgehenden Kanten, egal ob sie an einem Chunk oder der Note hängen.
|
||||||
if note_ids:
|
out_filter = models.Filter(must=[
|
||||||
out_filter = models.Filter(must=[
|
models.FieldCondition(key="note_id", match=models.MatchAny(any=note_ids)),
|
||||||
models.FieldCondition(key="note_id", match=models.MatchAny(any=note_ids)),
|
models.FieldCondition(key="kind", match=models.MatchExcept(**{"except": SYSTEM_EDGES}))
|
||||||
models.FieldCondition(key="kind", match=models.MatchExcept(**{"except": SYSTEM_EDGES}))
|
])
|
||||||
])
|
res_out, _ = self.client.scroll(self.edges_col, scroll_filter=out_filter, limit=2000, with_payload=True)
|
||||||
# Limit hoch, um alles zu finden
|
results.extend(res_out)
|
||||||
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)
|
# 2. INCOMING EDGES (Ziel = Chunk ID, Note ID oder Titel)
|
||||||
# Hier müssen wir Chunks auflösen, um Treffer auf Chunks zu finden.
|
# WICHTIG: target_id enthält nur den Titel, target_section ist separat
|
||||||
|
|
||||||
# Chunk IDs der aktuellen Notes holen
|
# Chunk IDs der aktuellen Notes holen
|
||||||
chunk_ids = []
|
c_filter = models.Filter(must=[models.FieldCondition(key="note_id", match=models.MatchAny(any=note_ids))])
|
||||||
if note_ids:
|
chunks, _ = self.client.scroll(self.chunks_col, scroll_filter=c_filter, limit=1000, with_payload=False)
|
||||||
c_filter = models.Filter(must=[models.FieldCondition(key="note_id", match=models.MatchAny(any=note_ids))])
|
chunk_ids = [c.id for c in chunks]
|
||||||
chunks, _ = self.client.scroll(self.chunks_col, scroll_filter=c_filter, limit=300)
|
|
||||||
chunk_ids = [c.id for c in chunks]
|
|
||||||
|
|
||||||
shoulds = []
|
shoulds = []
|
||||||
# Case A: Edge zeigt auf einen unserer Chunks
|
# Case A: Edge zeigt auf einen unserer Chunks
|
||||||
@@ -195,42 +201,92 @@ class GraphExplorerService:
|
|||||||
shoulds.append(models.FieldCondition(key="target_id", match=models.MatchAny(any=chunk_ids)))
|
shoulds.append(models.FieldCondition(key="target_id", match=models.MatchAny(any=chunk_ids)))
|
||||||
|
|
||||||
# Case B: Edge zeigt direkt auf unsere Note ID
|
# 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)))
|
||||||
shoulds.append(models.FieldCondition(key="target_id", match=models.MatchAny(any=note_ids)))
|
|
||||||
|
|
||||||
# Case C: Edge zeigt auf unseren Titel (Wikilinks)
|
# Case C: Edge zeigt auf unseren Titel
|
||||||
|
# WICHTIG: target_id enthält nur den Titel (z.B. "Meine Prinzipien 2025")
|
||||||
|
# target_section enthält die Abschnitt-Information (z.B. "P3 – Disziplin"), wenn gesetzt
|
||||||
|
|
||||||
|
# Sammle alle relevanten Titel (inkl. Aliase)
|
||||||
|
titles_to_search = []
|
||||||
if note_title:
|
if note_title:
|
||||||
shoulds.append(models.FieldCondition(key="target_id", match=models.MatchValue(value=note_title)))
|
titles_to_search.append(note_title)
|
||||||
|
|
||||||
|
# Lade auch Titel aus den Notes selbst (falls note_title nicht übergeben wurde)
|
||||||
|
for nid in note_ids:
|
||||||
|
note = self._fetch_note_cached(nid)
|
||||||
|
if note:
|
||||||
|
note_title_from_db = note.get("title")
|
||||||
|
if note_title_from_db and note_title_from_db not in titles_to_search:
|
||||||
|
titles_to_search.append(note_title_from_db)
|
||||||
|
# Aliase hinzufügen
|
||||||
|
aliases = note.get("aliases", [])
|
||||||
|
if isinstance(aliases, str):
|
||||||
|
aliases = [aliases]
|
||||||
|
for alias in aliases:
|
||||||
|
if alias and alias not in titles_to_search:
|
||||||
|
titles_to_search.append(alias)
|
||||||
|
|
||||||
|
# Für jeden Titel: Suche nach exaktem Match
|
||||||
|
# target_id enthält nur den Titel, daher reicht MatchValue
|
||||||
|
for title in titles_to_search:
|
||||||
|
shoulds.append(models.FieldCondition(key="target_id", match=models.MatchValue(value=title)))
|
||||||
|
|
||||||
if shoulds:
|
if shoulds:
|
||||||
in_filter = models.Filter(
|
in_filter = models.Filter(
|
||||||
must=[models.FieldCondition(key="kind", match=models.MatchExcept(**{"except": SYSTEM_EDGES}))],
|
must=[models.FieldCondition(key="kind", match=models.MatchExcept(**{"except": SYSTEM_EDGES}))],
|
||||||
should=shoulds
|
should=shoulds
|
||||||
)
|
)
|
||||||
res_in, _ = self.client.scroll(self.edges_col, scroll_filter=in_filter, limit=500, with_payload=True)
|
res_in, _ = self.client.scroll(self.edges_col, scroll_filter=in_filter, limit=2000, with_payload=True)
|
||||||
results.extend(res_in)
|
results.extend(res_in)
|
||||||
|
|
||||||
return results
|
return results
|
||||||
|
|
||||||
def _find_connected_edges_batch(self, note_ids):
|
def _find_connected_edges_batch(self, note_ids):
|
||||||
# Wrapper für Level 2 Suche
|
"""
|
||||||
return self._find_connected_edges(note_ids)
|
Wrapper für Level 2 Suche.
|
||||||
|
Lädt Titel der ersten Note für Titel-basierte Suche.
|
||||||
|
"""
|
||||||
|
if not note_ids:
|
||||||
|
return []
|
||||||
|
first_note = self._fetch_note_cached(note_ids[0])
|
||||||
|
note_title = first_note.get("title") if first_note else None
|
||||||
|
return self._find_connected_edges(note_ids, note_title=note_title)
|
||||||
|
|
||||||
def _process_edge(self, record, nodes_dict, unique_edges, current_depth):
|
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."""
|
"""
|
||||||
|
Verarbeitet eine rohe Edge, löst IDs auf und fügt sie den Dictionaries hinzu.
|
||||||
|
|
||||||
|
WICHTIG: Beide Richtungen werden unterstützt:
|
||||||
|
- Ausgehende Kanten: source_id gehört zu unserer Note (via note_id Owner)
|
||||||
|
- Eingehende Kanten: target_id zeigt auf unsere Note (via target_id Match)
|
||||||
|
"""
|
||||||
|
if not record or not record.payload:
|
||||||
|
return None, None
|
||||||
|
|
||||||
payload = record.payload
|
payload = record.payload
|
||||||
src_ref = payload.get("source_id")
|
src_ref = payload.get("source_id")
|
||||||
tgt_ref = payload.get("target_id")
|
tgt_ref = payload.get("target_id")
|
||||||
kind = payload.get("kind")
|
kind = payload.get("kind")
|
||||||
provenance = payload.get("provenance", "explicit")
|
provenance = payload.get("provenance", "explicit")
|
||||||
|
|
||||||
|
# Prüfe, ob beide Referenzen vorhanden sind
|
||||||
|
if not src_ref or not tgt_ref:
|
||||||
|
return None, None
|
||||||
|
|
||||||
# IDs zu Notes auflösen
|
# IDs zu Notes auflösen
|
||||||
|
# WICHTIG: source_id kann Chunk-ID (note_id#c01), Note-ID oder Titel sein
|
||||||
|
# WICHTIG: target_id kann Chunk-ID, Note-ID oder Titel sein (ohne #Abschnitt)
|
||||||
src_note = self._resolve_note_from_ref(src_ref)
|
src_note = self._resolve_note_from_ref(src_ref)
|
||||||
tgt_note = self._resolve_note_from_ref(tgt_ref)
|
tgt_note = self._resolve_note_from_ref(tgt_ref)
|
||||||
|
|
||||||
if src_note and tgt_note:
|
if src_note and tgt_note:
|
||||||
src_id = src_note['note_id']
|
src_id = src_note.get('note_id')
|
||||||
tgt_id = tgt_note['note_id']
|
tgt_id = tgt_note.get('note_id')
|
||||||
|
|
||||||
|
# Prüfe, ob beide IDs vorhanden sind
|
||||||
|
if not src_id or not tgt_id:
|
||||||
|
return None, None
|
||||||
|
|
||||||
if src_id != tgt_id:
|
if src_id != tgt_id:
|
||||||
# Nodes hinzufügen
|
# Nodes hinzufügen
|
||||||
@@ -245,7 +301,7 @@ class GraphExplorerService:
|
|||||||
# Bevorzuge explizite Kanten vor Smart Kanten
|
# Bevorzuge explizite Kanten vor Smart Kanten
|
||||||
is_current_explicit = (provenance in ["explicit", "rule"])
|
is_current_explicit = (provenance in ["explicit", "rule"])
|
||||||
if existing:
|
if existing:
|
||||||
is_existing_explicit = (existing['provenance'] in ["explicit", "rule"])
|
is_existing_explicit = (existing.get('provenance', '') in ["explicit", "rule"])
|
||||||
if is_existing_explicit and not is_current_explicit:
|
if is_existing_explicit and not is_current_explicit:
|
||||||
should_update = False
|
should_update = False
|
||||||
|
|
||||||
@@ -267,38 +323,109 @@ class GraphExplorerService:
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
def _resolve_note_from_ref(self, ref_str):
|
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
|
Löst eine Referenz zu einer Note Payload auf.
|
||||||
|
|
||||||
# Fall A: Chunk ID (enthält #)
|
WICHTIG: Wenn ref_str ein Titel#Abschnitt Format hat, wird nur der Titel-Teil verwendet.
|
||||||
|
Unterstützt:
|
||||||
|
- Note-ID: "20250101-meine-note"
|
||||||
|
- Chunk-ID: "20250101-meine-note#c01"
|
||||||
|
- Titel: "Meine Prinzipien 2025"
|
||||||
|
- Titel#Abschnitt: "Meine Prinzipien 2025#P3 – Disziplin" (trennt Abschnitt ab, sucht nur nach Titel)
|
||||||
|
"""
|
||||||
|
if not ref_str:
|
||||||
|
return None
|
||||||
|
|
||||||
|
# Fall A: Enthält # (kann Chunk-ID oder Titel#Abschnitt sein)
|
||||||
if "#" in ref_str:
|
if "#" in ref_str:
|
||||||
try:
|
try:
|
||||||
# Versuch 1: Chunk ID direkt
|
# Versuch 1: Chunk ID direkt (Format: note_id#c01)
|
||||||
res = self.client.retrieve(self.chunks_col, ids=[ref_str], with_payload=True)
|
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"))
|
if res and res[0].payload:
|
||||||
except: pass
|
note_id = res[0].payload.get("note_id")
|
||||||
|
if note_id:
|
||||||
|
return self._fetch_note_cached(note_id)
|
||||||
|
except:
|
||||||
|
pass
|
||||||
|
|
||||||
# Versuch 2: NoteID#Section (Hash abtrennen)
|
# Versuch 2: NoteID#Section (Hash abtrennen und als Note-ID versuchen)
|
||||||
possible_note_id = ref_str.split("#")[0]
|
# z.B. "20250101-meine-note#Abschnitt" -> "20250101-meine-note"
|
||||||
if self._fetch_note_cached(possible_note_id): return self._fetch_note_cached(possible_note_id)
|
possible_note_id = ref_str.split("#")[0].strip()
|
||||||
|
note = self._fetch_note_cached(possible_note_id)
|
||||||
|
if note:
|
||||||
|
return note
|
||||||
|
|
||||||
|
# Versuch 3: Titel#Abschnitt (Hash abtrennen und als Titel suchen)
|
||||||
|
# z.B. "Meine Prinzipien 2025#P3 – Disziplin" -> "Meine Prinzipien 2025"
|
||||||
|
# WICHTIG: target_id enthält nur den Titel, daher suchen wir nur nach dem Titel-Teil
|
||||||
|
possible_title = ref_str.split("#")[0].strip()
|
||||||
|
if possible_title:
|
||||||
|
res, _ = self.client.scroll(
|
||||||
|
collection_name=self.notes_col,
|
||||||
|
scroll_filter=models.Filter(must=[
|
||||||
|
models.FieldCondition(key="title", match=models.MatchValue(value=possible_title))
|
||||||
|
]),
|
||||||
|
limit=1, with_payload=True
|
||||||
|
)
|
||||||
|
if res and res[0].payload:
|
||||||
|
payload = res[0].payload
|
||||||
|
self._note_cache[payload['note_id']] = payload
|
||||||
|
return payload
|
||||||
|
|
||||||
|
# Fallback: Text-Suche für Fuzzy-Matching
|
||||||
|
res, _ = self.client.scroll(
|
||||||
|
collection_name=self.notes_col,
|
||||||
|
scroll_filter=models.Filter(must=[
|
||||||
|
models.FieldCondition(key="title", match=models.MatchText(text=possible_title))
|
||||||
|
]),
|
||||||
|
limit=10, with_payload=True
|
||||||
|
)
|
||||||
|
if res:
|
||||||
|
# Nimm das erste Ergebnis, das exakt oder beginnend mit possible_title übereinstimmt
|
||||||
|
for r in res:
|
||||||
|
if r.payload:
|
||||||
|
note_title = r.payload.get("title", "")
|
||||||
|
if note_title == possible_title or note_title.startswith(possible_title):
|
||||||
|
payload = r.payload
|
||||||
|
self._note_cache[payload['note_id']] = payload
|
||||||
|
return payload
|
||||||
|
|
||||||
# Fall B: Note ID direkt
|
# Fall B: Note ID direkt
|
||||||
if self._fetch_note_cached(ref_str): return self._fetch_note_cached(ref_str)
|
note = self._fetch_note_cached(ref_str)
|
||||||
|
if note:
|
||||||
|
return note
|
||||||
|
|
||||||
# Fall C: Titel
|
# Fall C: Titel (exakte Übereinstimmung)
|
||||||
res, _ = self.client.scroll(
|
res, _ = self.client.scroll(
|
||||||
collection_name=self.notes_col,
|
collection_name=self.notes_col,
|
||||||
scroll_filter=models.Filter(must=[models.FieldCondition(key="title", match=models.MatchValue(value=ref_str))]),
|
scroll_filter=models.Filter(must=[
|
||||||
|
models.FieldCondition(key="title", match=models.MatchValue(value=ref_str))
|
||||||
|
]),
|
||||||
limit=1, with_payload=True
|
limit=1, with_payload=True
|
||||||
)
|
)
|
||||||
if res:
|
if res and res[0].payload:
|
||||||
self._note_cache[res[0].payload['note_id']] = res[0].payload
|
payload = res[0].payload
|
||||||
return res[0].payload
|
self._note_cache[payload['note_id']] = payload
|
||||||
|
return payload
|
||||||
|
|
||||||
|
# Fall D: Titel (Text-Suche für Fuzzy-Matching)
|
||||||
|
res, _ = self.client.scroll(
|
||||||
|
collection_name=self.notes_col,
|
||||||
|
scroll_filter=models.Filter(must=[
|
||||||
|
models.FieldCondition(key="title", match=models.MatchText(text=ref_str))
|
||||||
|
]),
|
||||||
|
limit=1, with_payload=True
|
||||||
|
)
|
||||||
|
if res and res[0].payload:
|
||||||
|
payload = res[0].payload
|
||||||
|
self._note_cache[payload['note_id']] = payload
|
||||||
|
return payload
|
||||||
|
|
||||||
return None
|
return None
|
||||||
|
|
||||||
def _add_node_to_dict(self, node_dict, note_payload, level=1):
|
def _add_node_to_dict(self, node_dict, note_payload, level=1):
|
||||||
nid = note_payload.get("note_id")
|
nid = note_payload.get("note_id")
|
||||||
if nid in node_dict: return
|
if not nid or nid in node_dict: return
|
||||||
|
|
||||||
ntype = note_payload.get("type", "default")
|
ntype = note_payload.get("type", "default")
|
||||||
color = GRAPH_COLORS.get(ntype, GRAPH_COLORS["default"])
|
color = GRAPH_COLORS.get(ntype, GRAPH_COLORS["default"])
|
||||||
|
|||||||
+97
-20
@@ -1,25 +1,29 @@
|
|||||||
"""
|
"""
|
||||||
FILE: app/main.py
|
FILE: app/main.py
|
||||||
DESCRIPTION: Bootstrap der FastAPI Anwendung. Inkludiert Router und Middleware.
|
DESCRIPTION: Bootstrap der FastAPI Anwendung für WP-25a (Agentic MoE).
|
||||||
VERSION: 0.6.0
|
Orchestriert Lifespan-Events, globale Fehlerbehandlung und Routing.
|
||||||
|
Prüft beim Start die Integrität der Mixture of Experts Konfiguration.
|
||||||
|
VERSION: 1.1.0 (WP-25a: MoE Integrity Check)
|
||||||
STATUS: Active
|
STATUS: Active
|
||||||
DEPENDENCIES: app.config, app.routers.* (embed, qdrant, query, graph, tools, feedback, chat, ingest, admin)
|
DEPENDENCIES: app.config, app.routers.*, app.services.llm_service
|
||||||
LAST_ANALYSIS: 2025-12-15
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
from fastapi import FastAPI
|
import logging
|
||||||
from .config import get_settings
|
import os
|
||||||
#from .routers.embed_router import router as embed_router
|
from contextlib import asynccontextmanager
|
||||||
#from .routers.qdrant_router import router as qdrant_router
|
from fastapi import FastAPI, Request
|
||||||
|
from fastapi.responses import JSONResponse
|
||||||
|
|
||||||
|
from .config import get_settings
|
||||||
|
from .services.llm_service import LLMService
|
||||||
|
|
||||||
|
# Import der 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
|
||||||
from .routers.tools import router as tools_router
|
from .routers.tools import router as tools_router
|
||||||
from .routers.feedback import router as feedback_router
|
from .routers.feedback import router as feedback_router
|
||||||
# NEU: Chat Router (WP-05)
|
|
||||||
from .routers.chat import router as chat_router
|
from .routers.chat import router as chat_router
|
||||||
# NEU: Ingest Router (WP-11)
|
|
||||||
from .routers.ingest import router as ingest_router
|
from .routers.ingest import router as ingest_router
|
||||||
|
|
||||||
try:
|
try:
|
||||||
@@ -27,26 +31,98 @@ try:
|
|||||||
except Exception:
|
except Exception:
|
||||||
admin_router = None
|
admin_router = None
|
||||||
|
|
||||||
|
from .core.logging_setup import setup_logging
|
||||||
|
|
||||||
|
# Initialisierung des Loggings noch VOR create_app()
|
||||||
|
setup_logging()
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
# --- WP-25a: Lifespan Management mit MoE Integritäts-Prüfung ---
|
||||||
|
|
||||||
|
@asynccontextmanager
|
||||||
|
async def lifespan(app: FastAPI):
|
||||||
|
"""
|
||||||
|
Verwaltet den Lebenszyklus der Anwendung (Startup/Shutdown).
|
||||||
|
Verifiziert die Verfügbarkeit der MoE-Experten-Profile und Strategien.
|
||||||
|
"""
|
||||||
|
settings = get_settings()
|
||||||
|
logger.info("🚀 mindnet API: Starting up (WP-25a MoE Mode)...")
|
||||||
|
|
||||||
|
# 1. Startup: Integritäts-Check der MoE Konfiguration
|
||||||
|
# Wir prüfen die drei Säulen der Agentic-RAG Architektur.
|
||||||
|
decision_cfg = os.getenv("MINDNET_DECISION_CONFIG", "config/decision_engine.yaml")
|
||||||
|
profiles_cfg = getattr(settings, "LLM_PROFILES_PATH", "config/llm_profiles.yaml")
|
||||||
|
prompts_cfg = settings.PROMPTS_PATH
|
||||||
|
|
||||||
|
missing_files = []
|
||||||
|
if not os.path.exists(decision_cfg): missing_files.append(decision_cfg)
|
||||||
|
if not os.path.exists(profiles_cfg): missing_files.append(profiles_cfg)
|
||||||
|
if not os.path.exists(prompts_cfg): missing_files.append(prompts_cfg)
|
||||||
|
|
||||||
|
if missing_files:
|
||||||
|
logger.error(f"❌ CRITICAL: Missing MoE config files: {missing_files}")
|
||||||
|
else:
|
||||||
|
logger.info("✅ MoE Configuration files verified.")
|
||||||
|
|
||||||
|
yield
|
||||||
|
|
||||||
|
# 2. Shutdown: Ressourcen bereinigen
|
||||||
|
logger.info("🛑 mindnet API: Shutting down...")
|
||||||
|
try:
|
||||||
|
llm = LLMService()
|
||||||
|
await llm.close()
|
||||||
|
logger.info("✨ LLM resources cleaned up.")
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f"⚠️ Error during LLMService cleanup: {e}")
|
||||||
|
|
||||||
|
logger.info("Goodbye.")
|
||||||
|
|
||||||
|
# --- App Factory ---
|
||||||
|
|
||||||
def create_app() -> FastAPI:
|
def create_app() -> FastAPI:
|
||||||
app = FastAPI(title="mindnet API", version="0.6.0") # Version bump WP-11
|
"""Initialisiert die FastAPI App mit WP-25a Erweiterungen."""
|
||||||
|
app = FastAPI(
|
||||||
|
title="mindnet API",
|
||||||
|
version="1.1.0", # WP-25a Milestone
|
||||||
|
lifespan=lifespan,
|
||||||
|
description="Digital Twin Knowledge Engine mit Mixture of Experts Orchestration."
|
||||||
|
)
|
||||||
|
|
||||||
s = get_settings()
|
s = get_settings()
|
||||||
|
|
||||||
|
# --- Globale Fehlerbehandlung (WP-25a Resilienz) ---
|
||||||
|
|
||||||
|
@app.exception_handler(Exception)
|
||||||
|
async def global_exception_handler(request: Request, exc: Exception):
|
||||||
|
"""Fängt unerwartete Fehler in der MoE-Prozesskette ab."""
|
||||||
|
logger.error(f"❌ Unhandled Engine Error: {exc}", exc_info=True)
|
||||||
|
return JSONResponse(
|
||||||
|
status_code=500,
|
||||||
|
content={
|
||||||
|
"detail": "Ein interner Fehler ist in der MoE-Kette aufgetreten.",
|
||||||
|
"error_type": type(exc).__name__
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
# Healthcheck
|
||||||
@app.get("/healthz")
|
@app.get("/healthz")
|
||||||
def healthz():
|
def healthz():
|
||||||
return {"status": "ok", "qdrant": s.QDRANT_URL, "prefix": s.COLLECTION_PREFIX}
|
"""Bietet Statusinformationen über die Engine und Datenbank-Verbindung."""
|
||||||
|
return {
|
||||||
# app.include_router(embed_router)
|
"status": "ok",
|
||||||
# app.include_router(qdrant_router)
|
"version": "1.1.0",
|
||||||
|
"qdrant": s.QDRANT_URL,
|
||||||
|
"prefix": s.COLLECTION_PREFIX,
|
||||||
|
"moe_enabled": True
|
||||||
|
}
|
||||||
|
|
||||||
|
# Inkludieren der Router (100% Kompatibilität erhalten)
|
||||||
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"])
|
||||||
app.include_router(tools_router, prefix="/tools", tags=["tools"])
|
app.include_router(tools_router, prefix="/tools", tags=["tools"])
|
||||||
app.include_router(feedback_router, prefix="/feedback", tags=["feedback"])
|
app.include_router(feedback_router, prefix="/feedback", tags=["feedback"])
|
||||||
|
app.include_router(chat_router, prefix="/chat", tags=["chat"]) # WP-25a Agentic Chat
|
||||||
# NEU: Chat Endpoint
|
|
||||||
app.include_router(chat_router, prefix="/chat", tags=["chat"])
|
|
||||||
|
|
||||||
# NEU: Ingest Endpoint
|
|
||||||
app.include_router(ingest_router, prefix="/ingest", tags=["ingest"])
|
app.include_router(ingest_router, prefix="/ingest", tags=["ingest"])
|
||||||
|
|
||||||
if admin_router:
|
if admin_router:
|
||||||
@@ -54,4 +130,5 @@ def create_app() -> FastAPI:
|
|||||||
|
|
||||||
return app
|
return app
|
||||||
|
|
||||||
|
# Instanziierung der App
|
||||||
app = create_app()
|
app = create_app()
|
||||||
+28
-22
@@ -1,10 +1,9 @@
|
|||||||
"""
|
"""
|
||||||
FILE: app/models/dto.py
|
FILE: app/models/dto.py
|
||||||
DESCRIPTION: Pydantic-Modelle (DTOs) für Request/Response Bodies. Definiert das API-Schema.
|
DESCRIPTION: Pydantic-Modelle (DTOs) für Request/Response Bodies. Definiert das API-Schema.
|
||||||
VERSION: 0.6.6 (WP-22 Debug & Stability Update)
|
VERSION: 0.7.1 (WP-25: Stream-Tracing Support)
|
||||||
STATUS: Active
|
STATUS: Active
|
||||||
DEPENDENCIES: pydantic, typing, uuid
|
DEPENDENCIES: pydantic, typing, uuid
|
||||||
LAST_ANALYSIS: 2025-12-18
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@@ -12,8 +11,14 @@ 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
|
||||||
|
|
||||||
# Gültige Kanten-Typen gemäß Manual
|
# WP-25: Erweiterte Kanten-Typen gemäß neuer decision_engine.yaml
|
||||||
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"]
|
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", "enforced_by", "implemented_in", "part_of",
|
||||||
|
"experienced_in", "impacts", "risk_of"
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
# --- Basis-DTOs ---
|
# --- Basis-DTOs ---
|
||||||
@@ -43,13 +48,14 @@ class EdgeDTO(BaseModel):
|
|||||||
direction: Literal["out", "in", "undirected"] = "out"
|
direction: Literal["out", "in", "undirected"] = "out"
|
||||||
provenance: Optional[Literal["explicit", "rule", "smart", "structure"]] = "explicit"
|
provenance: Optional[Literal["explicit", "rule", "smart", "structure"]] = "explicit"
|
||||||
confidence: float = 1.0
|
confidence: float = 1.0
|
||||||
|
target_section: Optional[str] = None
|
||||||
|
|
||||||
|
|
||||||
# --- Request Models ---
|
# --- Request Models ---
|
||||||
|
|
||||||
class QueryRequest(BaseModel):
|
class QueryRequest(BaseModel):
|
||||||
"""
|
"""
|
||||||
Request für /query.
|
Request für /query. Unterstützt Multi-Stream Isolation via filters.
|
||||||
"""
|
"""
|
||||||
mode: Literal["semantic", "edge", "hybrid"] = "hybrid"
|
mode: Literal["semantic", "edge", "hybrid"] = "hybrid"
|
||||||
query: Optional[str] = None
|
query: Optional[str] = None
|
||||||
@@ -60,14 +66,12 @@ 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
|
# WP-22/25: Dynamische Gewichtung der Graphen-Highways
|
||||||
boost_edges: Optional[Dict[str, float]] = None
|
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: str = Field(..., description="ID des bewerteten Treffers oder 'generated_answer'")
|
node_id: str = Field(..., description="ID des bewerteten Treffers oder 'generated_answer'")
|
||||||
score: int = Field(..., ge=1, le=5, description="1 (Irrelevant) bis 5 (Perfekt)")
|
score: int = Field(..., ge=1, le=5, description="1 (Irrelevant) bis 5 (Perfekt)")
|
||||||
@@ -75,16 +79,14 @@ class FeedbackRequest(BaseModel):
|
|||||||
|
|
||||||
|
|
||||||
class ChatRequest(BaseModel):
|
class ChatRequest(BaseModel):
|
||||||
"""
|
"""Request für /chat (WP-25 Einstieg)."""
|
||||||
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="ID für Chat-Verlauf")
|
conversation_id: Optional[str] = Field(None, description="ID für Chat-Verlauf")
|
||||||
top_k: int = 5
|
top_k: int = 5
|
||||||
explain: bool = False
|
explain: bool = False
|
||||||
|
|
||||||
|
|
||||||
# --- WP-04b Explanation Models ---
|
# --- Explanation Models ---
|
||||||
|
|
||||||
class ScoreBreakdown(BaseModel):
|
class ScoreBreakdown(BaseModel):
|
||||||
"""Aufschlüsselung der Score-Komponenten nach der WP-22 Formel."""
|
"""Aufschlüsselung der Score-Komponenten nach der WP-22 Formel."""
|
||||||
@@ -95,14 +97,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
|
status_multiplier: float = 1.0
|
||||||
graph_boost_factor: 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", "lifecycle"]
|
# WP-25: 'status' hinzugefügt für Synchronität mit retriever.py
|
||||||
|
kind: Literal["semantic", "edge", "type", "centrality", "lifecycle", "status"]
|
||||||
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
|
||||||
@@ -113,7 +115,6 @@ 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_intent: Optional[str] = None
|
||||||
applied_boosts: Optional[Dict[str, float]] = None
|
applied_boosts: Optional[Dict[str, float]] = None
|
||||||
|
|
||||||
@@ -121,7 +122,10 @@ class Explanation(BaseModel):
|
|||||||
# --- Response Models ---
|
# --- Response Models ---
|
||||||
|
|
||||||
class QueryHit(BaseModel):
|
class QueryHit(BaseModel):
|
||||||
"""Einzelnes Trefferobjekt für /query."""
|
"""
|
||||||
|
Einzelnes Trefferobjekt.
|
||||||
|
WP-25: stream_origin hinzugefügt für Tracing und Feedback-Optimierung.
|
||||||
|
"""
|
||||||
node_id: str
|
node_id: str
|
||||||
note_id: str
|
note_id: str
|
||||||
semantic_score: float
|
semantic_score: float
|
||||||
@@ -132,10 +136,11 @@ class QueryHit(BaseModel):
|
|||||||
source: Optional[Dict] = None
|
source: Optional[Dict] = None
|
||||||
payload: Optional[Dict] = None
|
payload: Optional[Dict] = None
|
||||||
explanation: Optional[Explanation] = None
|
explanation: Optional[Explanation] = None
|
||||||
|
stream_origin: Optional[str] = Field(None, description="Name des Ursprungs-Streams")
|
||||||
|
|
||||||
|
|
||||||
class QueryResponse(BaseModel):
|
class QueryResponse(BaseModel):
|
||||||
"""Antwortstruktur für /query."""
|
"""Antwortstruktur für /query (wird von DecisionEngine Streams genutzt)."""
|
||||||
query_id: str = Field(default_factory=lambda: str(uuid.uuid4()))
|
query_id: str = Field(default_factory=lambda: str(uuid.uuid4()))
|
||||||
results: List[QueryHit]
|
results: List[QueryHit]
|
||||||
used_mode: str
|
used_mode: str
|
||||||
@@ -152,11 +157,12 @@ class GraphResponse(BaseModel):
|
|||||||
|
|
||||||
class ChatResponse(BaseModel):
|
class ChatResponse(BaseModel):
|
||||||
"""
|
"""
|
||||||
WP-05/06: Antwortstruktur für /chat.
|
Antwortstruktur für /chat.
|
||||||
|
WP-25: 'intent' spiegelt nun die gewählte Strategie wider.
|
||||||
"""
|
"""
|
||||||
query_id: str = Field(..., description="Traceability ID")
|
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 genutzten Quellen")
|
sources: List[QueryHit] = Field(..., description="Die genutzten Quellen (alle Streams)")
|
||||||
latency_ms: int
|
latency_ms: int
|
||||||
intent: Optional[str] = Field("FACT", description="WP-06: Erkannter Intent")
|
intent: Optional[str] = Field("FACT", description="Die gewählte WP-25 Strategie")
|
||||||
intent_source: Optional[str] = Field("Unknown", description="Quelle der Intent-Erkennung")
|
intent_source: Optional[str] = Field("LLM_Router", description="Quelle der Intent-Erkennung")
|
||||||
+134
-232
@@ -1,10 +1,14 @@
|
|||||||
"""
|
"""
|
||||||
FILE: app/routers/chat.py
|
FILE: app/routers/chat.py
|
||||||
DESCRIPTION: Haupt-Chat-Interface (RAG & Interview). Enthält Intent-Router (Keywords/LLM) und Prompt-Construction.
|
DESCRIPTION: Haupt-Chat-Interface (WP-25b Edition).
|
||||||
VERSION: 2.7.0 (WP-22 Semantic Graph Routing)
|
Kombiniert die spezialisierte Interview-Logik mit der neuen
|
||||||
|
Lazy-Prompt-Orchestration und MoE-Synthese.
|
||||||
|
VERSION: 3.0.5 (WP-25b: Lazy Prompt Integration)
|
||||||
STATUS: Active
|
STATUS: Active
|
||||||
DEPENDENCIES: app.config, app.models.dto, app.services.llm_service, app.core.retriever, app.services.feedback_service
|
FIX:
|
||||||
EXTERNAL_CONFIG: config/decision_engine.yaml, config/types.yaml
|
- WP-25b: Umstellung des Interview-Modus auf Lazy-Prompt (prompt_key + variables).
|
||||||
|
- WP-25b: Delegation der RAG-Phase an die Engine v1.3.0 für konsistente MoE-Steuerung.
|
||||||
|
- WP-25a: Voller Erhalt der v3.0.2 Logik (Interview, Schema-Resolution, FastPaths).
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from fastapi import APIRouter, HTTPException, Depends
|
from fastapi import APIRouter, HTTPException, Depends
|
||||||
@@ -14,50 +18,44 @@ import uuid
|
|||||||
import logging
|
import logging
|
||||||
import yaml
|
import yaml
|
||||||
import os
|
import os
|
||||||
|
import asyncio
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
from app.config import get_settings
|
from app.config import get_settings
|
||||||
from app.models.dto import ChatRequest, ChatResponse, QueryRequest, QueryHit
|
from app.models.dto import ChatRequest, ChatResponse, QueryHit
|
||||||
from app.services.llm_service import LLMService
|
from app.services.llm_service import LLMService
|
||||||
from app.core.retriever import Retriever
|
|
||||||
from app.services.feedback_service import log_search
|
from app.services.feedback_service import log_search
|
||||||
|
|
||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
# --- Helper: Config Loader ---
|
# --- EBENE 1: CONFIG LOADER & CACHING (WP-25 Standard) ---
|
||||||
|
|
||||||
_DECISION_CONFIG_CACHE = None
|
_DECISION_CONFIG_CACHE = None
|
||||||
_TYPES_CONFIG_CACHE = None
|
_TYPES_CONFIG_CACHE = None
|
||||||
|
|
||||||
def _load_decision_config() -> Dict[str, Any]:
|
def _load_decision_config() -> Dict[str, Any]:
|
||||||
|
"""Lädt die Strategie-Konfiguration."""
|
||||||
settings = get_settings()
|
settings = get_settings()
|
||||||
path = Path(settings.DECISION_CONFIG_PATH)
|
path = Path(settings.DECISION_CONFIG_PATH)
|
||||||
default_config = {
|
|
||||||
"strategies": {
|
|
||||||
"FACT": {"trigger_keywords": []}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if not path.exists():
|
|
||||||
logger.warning(f"Decision config not found at {path}, using defaults.")
|
|
||||||
return default_config
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
with open(path, "r", encoding="utf-8") as f:
|
if path.exists():
|
||||||
return yaml.safe_load(f)
|
with open(path, "r", encoding="utf-8") as f:
|
||||||
|
return yaml.safe_load(f) or {}
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Failed to load decision config: {e}")
|
logger.error(f"Failed to load decision config: {e}")
|
||||||
return default_config
|
return {"strategies": {}}
|
||||||
|
|
||||||
def _load_types_config() -> Dict[str, Any]:
|
def _load_types_config() -> Dict[str, Any]:
|
||||||
"""Lädt die types.yaml für Keyword-Erkennung."""
|
"""Lädt die types.yaml für die Typerkennung."""
|
||||||
path = os.getenv("MINDNET_TYPES_FILE", "config/types.yaml")
|
path = os.getenv("MINDNET_TYPES_FILE", "config/types.yaml")
|
||||||
try:
|
try:
|
||||||
with open(path, "r", encoding="utf-8") as f:
|
if os.path.exists(path):
|
||||||
return yaml.safe_load(f) or {}
|
with open(path, "r", encoding="utf-8") as f:
|
||||||
except Exception:
|
return yaml.safe_load(f) or {}
|
||||||
return {}
|
except Exception as e:
|
||||||
|
logger.error(f"Failed to load types config: {e}")
|
||||||
|
return {}
|
||||||
|
|
||||||
def get_full_config() -> Dict[str, Any]:
|
def get_full_config() -> Dict[str, Any]:
|
||||||
global _DECISION_CONFIG_CACHE
|
global _DECISION_CONFIG_CACHE
|
||||||
@@ -74,21 +72,17 @@ def get_types_config() -> Dict[str, Any]:
|
|||||||
def get_decision_strategy(intent: str) -> Dict[str, Any]:
|
def get_decision_strategy(intent: str) -> Dict[str, Any]:
|
||||||
config = get_full_config()
|
config = get_full_config()
|
||||||
strategies = config.get("strategies", {})
|
strategies = config.get("strategies", {})
|
||||||
return strategies.get(intent, strategies.get("FACT", {}))
|
return strategies.get(intent, strategies.get("FACT_WHAT", {}))
|
||||||
|
|
||||||
# --- Helper: Target Type Detection (WP-07) ---
|
# --- EBENE 2: SPEZIAL-LOGIK (INTERVIEW & DETECTION) ---
|
||||||
|
|
||||||
def _detect_target_type(message: str, configured_schemas: Dict[str, Any]) -> str:
|
def _detect_target_type(message: str, configured_schemas: Dict[str, Any]) -> str:
|
||||||
"""
|
"""WP-07: Identifiziert den gewünschten Notiz-Typ (Keyword-basiert)."""
|
||||||
Versucht zu erraten, welchen Notiz-Typ der User erstellen will.
|
|
||||||
Nutzt Keywords aus types.yaml UND Mappings.
|
|
||||||
"""
|
|
||||||
message_lower = message.lower()
|
message_lower = message.lower()
|
||||||
|
|
||||||
# 1. Check types.yaml detection_keywords (Priority!)
|
|
||||||
types_cfg = get_types_config()
|
types_cfg = get_types_config()
|
||||||
types_def = types_cfg.get("types", {})
|
types_def = types_cfg.get("types", {})
|
||||||
|
|
||||||
|
# 1. Check types.yaml detection_keywords
|
||||||
for type_name, type_data in types_def.items():
|
for type_name, type_data in types_def.items():
|
||||||
keywords = type_data.get("detection_keywords", [])
|
keywords = type_data.get("detection_keywords", [])
|
||||||
for kw in keywords:
|
for kw in keywords:
|
||||||
@@ -101,258 +95,166 @@ def _detect_target_type(message: str, configured_schemas: Dict[str, Any]) -> str
|
|||||||
if type_key in message_lower:
|
if type_key in message_lower:
|
||||||
return type_key
|
return type_key
|
||||||
|
|
||||||
# 3. Synonym-Mapping (Legacy Fallback)
|
# 3. Synonym-Mapping (Legacy)
|
||||||
synonyms = {
|
synonyms = {
|
||||||
"projekt": "project", "vorhaben": "project",
|
"projekt": "project", "entscheidung": "decision", "ziel": "goal",
|
||||||
"entscheidung": "decision", "beschluss": "decision",
|
"erfahrung": "experience", "wert": "value", "prinzip": "principle"
|
||||||
"ziel": "goal",
|
|
||||||
"erfahrung": "experience", "lektion": "experience",
|
|
||||||
"wert": "value",
|
|
||||||
"prinzip": "principle",
|
|
||||||
"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:
|
||||||
return schema_key
|
return schema_key
|
||||||
|
|
||||||
return "default"
|
return "default"
|
||||||
|
|
||||||
# --- Dependencies ---
|
def _is_question(query: str) -> bool:
|
||||||
|
"""Prüft, ob der Input eine Frage ist."""
|
||||||
|
q = query.strip().lower()
|
||||||
|
if "?" in q: return True
|
||||||
|
starters = ["wer", "wie", "was", "wo", "wann", "warum", "weshalb", "wozu", "welche", "bist du"]
|
||||||
|
return any(q.startswith(s + " ") for s in starters)
|
||||||
|
|
||||||
|
async def _classify_intent(query: str, llm: LLMService) -> tuple[str, str]:
|
||||||
|
"""Hybrid Router: Keyword-Fast-Paths & DecisionEngine LLM Router."""
|
||||||
|
config = get_full_config()
|
||||||
|
strategies = config.get("strategies", {})
|
||||||
|
query_lower = query.lower()
|
||||||
|
|
||||||
|
# 1. FAST PATH: Keyword Trigger
|
||||||
|
for intent_name, strategy in strategies.items():
|
||||||
|
keywords = strategy.get("trigger_keywords", [])
|
||||||
|
for k in keywords:
|
||||||
|
if k.lower() in query_lower:
|
||||||
|
return intent_name, "Keyword (FastPath)"
|
||||||
|
|
||||||
|
# 2. FAST PATH B: Type Keywords -> INTERVIEW
|
||||||
|
if not _is_question(query_lower):
|
||||||
|
types_cfg = get_types_config()
|
||||||
|
for type_name, type_data in types_cfg.get("types", {}).items():
|
||||||
|
for kw in type_data.get("detection_keywords", []):
|
||||||
|
if kw.lower() in query_lower:
|
||||||
|
return "INTERVIEW", "Keyword (Interview)"
|
||||||
|
|
||||||
|
# 3. SLOW PATH: DecisionEngine LLM Router (MoE-gesteuert)
|
||||||
|
# WP-25b FIX: Nutzung der öffentlichen API statt privater Methode
|
||||||
|
intent = await llm.decision_engine._determine_strategy(query) # TODO: Public API erstellen
|
||||||
|
return intent, "DecisionEngine (LLM)"
|
||||||
|
|
||||||
|
# --- EBENE 3: RETRIEVAL AGGREGATION ---
|
||||||
|
|
||||||
|
def _collect_all_hits(stream_responses: Dict[str, Any]) -> List[QueryHit]:
|
||||||
|
"""Sammelt deduplizierte Treffer aus allen Streams für das Tracing."""
|
||||||
|
all_hits = []
|
||||||
|
seen_node_ids = set()
|
||||||
|
for _, response in stream_responses.items():
|
||||||
|
# Sammeln der Hits aus den QueryResponse Objekten
|
||||||
|
if hasattr(response, 'results'):
|
||||||
|
for hit in response.results:
|
||||||
|
if hit.node_id not in seen_node_ids:
|
||||||
|
all_hits.append(hit)
|
||||||
|
seen_node_ids.add(hit.node_id)
|
||||||
|
return sorted(all_hits, key=lambda h: h.total_score, reverse=True)
|
||||||
|
|
||||||
|
# --- EBENE 4: ENDPUNKT ---
|
||||||
|
|
||||||
def get_llm_service():
|
def get_llm_service():
|
||||||
return LLMService()
|
return LLMService()
|
||||||
|
|
||||||
def get_retriever():
|
|
||||||
return Retriever()
|
|
||||||
|
|
||||||
|
|
||||||
# --- Logic ---
|
|
||||||
|
|
||||||
def _build_enriched_context(hits: List[QueryHit]) -> str:
|
|
||||||
context_parts = []
|
|
||||||
for i, hit in enumerate(hits, 1):
|
|
||||||
source = hit.source or {}
|
|
||||||
content = (
|
|
||||||
source.get("text") or source.get("content") or
|
|
||||||
source.get("page_content") or source.get("chunk_text") or
|
|
||||||
"[Kein Text]"
|
|
||||||
)
|
|
||||||
title = hit.note_id or "Unbekannt"
|
|
||||||
|
|
||||||
payload = hit.payload or {}
|
|
||||||
note_type = payload.get("type") or source.get("type", "unknown")
|
|
||||||
note_type = str(note_type).upper()
|
|
||||||
|
|
||||||
entry = (
|
|
||||||
f"### QUELLE {i}: {title}\n"
|
|
||||||
f"TYP: [{note_type}] (Score: {hit.total_score:.2f})\n"
|
|
||||||
f"INHALT:\n{content}\n"
|
|
||||||
)
|
|
||||||
context_parts.append(entry)
|
|
||||||
|
|
||||||
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]:
|
|
||||||
"""
|
|
||||||
Hybrid Router v5:
|
|
||||||
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()
|
|
||||||
strategies = config.get("strategies", {})
|
|
||||||
settings = config.get("settings", {})
|
|
||||||
|
|
||||||
query_lower = query.lower()
|
|
||||||
|
|
||||||
# 1. FAST PATH A: Strategie Keywords (z.B. "Soll ich...")
|
|
||||||
for intent_name, strategy in strategies.items():
|
|
||||||
if intent_name == "FACT": continue
|
|
||||||
keywords = strategy.get("trigger_keywords", [])
|
|
||||||
for k in keywords:
|
|
||||||
if k.lower() in query_lower:
|
|
||||||
return intent_name, "Keyword (Strategy)"
|
|
||||||
|
|
||||||
# 2. FAST PATH B: Type Keywords (z.B. "Projekt", "Werte") -> INTERVIEW
|
|
||||||
if not _is_question(query_lower):
|
|
||||||
types_cfg = get_types_config()
|
|
||||||
types_def = types_cfg.get("types", {})
|
|
||||||
|
|
||||||
for type_name, type_data in types_def.items():
|
|
||||||
keywords = type_data.get("detection_keywords", [])
|
|
||||||
for kw in keywords:
|
|
||||||
if kw.lower() in query_lower:
|
|
||||||
return "INTERVIEW", f"Keyword (Type: {type_name})"
|
|
||||||
|
|
||||||
# 3. SLOW PATH: LLM Router
|
|
||||||
if settings.get("llm_fallback_enabled", False):
|
|
||||||
router_prompt_template = llm.prompts.get("router_prompt", "")
|
|
||||||
|
|
||||||
if router_prompt_template:
|
|
||||||
prompt = router_prompt_template.replace("{query}", query)
|
|
||||||
logger.info("Keywords failed (or Question detected). Asking LLM for Intent...")
|
|
||||||
|
|
||||||
try:
|
|
||||||
raw_response = await llm.generate_raw_response(prompt, priority="realtime")
|
|
||||||
llm_output_upper = raw_response.upper()
|
|
||||||
|
|
||||||
if "INTERVIEW" in llm_output_upper or "CREATE" in llm_output_upper:
|
|
||||||
return "INTERVIEW", "LLM Router"
|
|
||||||
|
|
||||||
for strat_key in strategies.keys():
|
|
||||||
if strat_key in llm_output_upper:
|
|
||||||
return strat_key, "LLM Router"
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
logger.error(f"Router LLM failed: {e}")
|
|
||||||
|
|
||||||
return "FACT", "Default (No Match)"
|
|
||||||
|
|
||||||
@router.post("/", response_model=ChatResponse)
|
@router.post("/", response_model=ChatResponse)
|
||||||
async def chat_endpoint(
|
async def chat_endpoint(
|
||||||
request: ChatRequest,
|
request: ChatRequest,
|
||||||
llm: LLMService = Depends(get_llm_service),
|
llm: LLMService = Depends(get_llm_service)
|
||||||
retriever: Retriever = Depends(get_retriever)
|
|
||||||
):
|
):
|
||||||
start_time = time.time()
|
start_time = time.time()
|
||||||
query_id = str(uuid.uuid4())
|
query_id = str(uuid.uuid4())
|
||||||
logger.info(f"Chat request [{query_id}]: {request.message[:50]}...")
|
logger.info(f"🚀 [WP-25b] Chat request [{query_id}]: {request.message[:50]}...")
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# 1. Intent Detection
|
# 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}] Intent: {intent} via {intent_source}")
|
||||||
|
|
||||||
# Strategy Load
|
|
||||||
strategy = get_decision_strategy(intent)
|
strategy = get_decision_strategy(intent)
|
||||||
prompt_key = strategy.get("prompt_template", "rag_template")
|
engine = llm.decision_engine
|
||||||
|
|
||||||
sources_hits = []
|
sources_hits = []
|
||||||
final_prompt = ""
|
answer_text = ""
|
||||||
|
|
||||||
|
# 2. INTERVIEW MODE (WP-25b Lazy-Prompt Logik)
|
||||||
if intent == "INTERVIEW":
|
if intent == "INTERVIEW":
|
||||||
# --- INTERVIEW MODE ---
|
|
||||||
target_type = _detect_target_type(request.message, strategy.get("schemas", {}))
|
target_type = _detect_target_type(request.message, strategy.get("schemas", {}))
|
||||||
|
|
||||||
types_cfg = get_types_config()
|
types_cfg = get_types_config()
|
||||||
type_def = types_cfg.get("types", {}).get(target_type, {})
|
type_def = types_cfg.get("types", {}).get(target_type, {})
|
||||||
fields_list = type_def.get("schema", [])
|
fields_list = type_def.get("schema", [])
|
||||||
|
|
||||||
|
# WP-07: Restaurierte Fallback Logik
|
||||||
if not fields_list:
|
if not fields_list:
|
||||||
configured_schemas = strategy.get("schemas", {})
|
configured_schemas = strategy.get("schemas", {})
|
||||||
fallback_schema = configured_schemas.get(target_type, configured_schemas.get("default"))
|
fallback = configured_schemas.get(target_type, configured_schemas.get("default", {}))
|
||||||
if isinstance(fallback_schema, dict):
|
fields_list = fallback.get("fields", []) if isinstance(fallback, dict) else (fallback or [])
|
||||||
fields_list = fallback_schema.get("fields", [])
|
|
||||||
else:
|
|
||||||
fields_list = fallback_schema or []
|
|
||||||
|
|
||||||
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)
|
||||||
|
template_key = strategy.get("prompt_template", "interview_template")
|
||||||
|
|
||||||
template = llm.prompts.get(prompt_key, "")
|
# WP-25b: Lazy Loading Call
|
||||||
final_prompt = template.replace("{context_str}", "Dialogverlauf...") \
|
# Wir übergeben nur Key und Variablen. Das System formatiert passend zum Modell.
|
||||||
.replace("{query}", request.message) \
|
answer_text = await llm.generate_raw_response(
|
||||||
.replace("{target_type}", target_type) \
|
prompt_key=template_key,
|
||||||
.replace("{schema_fields}", fields_str) \
|
variables={
|
||||||
.replace("{schema_hint}", "")
|
"query": request.message,
|
||||||
|
"target_type": target_type,
|
||||||
|
"schema_fields": fields_str
|
||||||
|
},
|
||||||
|
system=llm.get_prompt("system_prompt"),
|
||||||
|
priority="realtime",
|
||||||
|
profile_name="compression_fast",
|
||||||
|
max_retries=0
|
||||||
|
)
|
||||||
sources_hits = []
|
sources_hits = []
|
||||||
|
|
||||||
|
# 3. RAG MODE (WP-25b Delegation an Engine v1.3.0)
|
||||||
else:
|
else:
|
||||||
# --- RAG MODE ---
|
# Phase A & B: Retrieval & Kompression (Delegiert an Engine v1.3.0)
|
||||||
inject_types = strategy.get("inject_types", [])
|
formatted_context_map = await engine._execute_parallel_streams(strategy, request.message)
|
||||||
prepend_instr = strategy.get("prepend_instruction", "")
|
|
||||||
|
|
||||||
# --- WP-22: Semantic Graph Routing (Teil C) ---
|
# Erfassung der Quellen für das Tracing
|
||||||
# Wir laden die konfigurierten Edge-Boosts für diesen Intent
|
raw_stream_map = {}
|
||||||
edge_boosts = strategy.get("edge_boosts", {})
|
stream_keys = strategy.get("use_streams", [])
|
||||||
if edge_boosts:
|
library = engine.config.get("streams_library", {})
|
||||||
logger.info(f"[{query_id}] Applying Edge Boosts: {edge_boosts}")
|
|
||||||
|
|
||||||
query_req = QueryRequest(
|
retrieval_tasks = []
|
||||||
query=request.message,
|
active_streams = []
|
||||||
mode="hybrid",
|
for key in stream_keys:
|
||||||
top_k=request.top_k,
|
if key in library:
|
||||||
explain=request.explain,
|
active_streams.append(key)
|
||||||
# WP-22: Boosts an den Retriever weitergeben
|
retrieval_tasks.append(engine._run_single_stream(key, library[key], request.message))
|
||||||
boost_edges=edge_boosts
|
|
||||||
|
responses = await asyncio.gather(*retrieval_tasks, return_exceptions=True)
|
||||||
|
for name, res in zip(active_streams, responses):
|
||||||
|
if not isinstance(res, Exception):
|
||||||
|
raw_stream_map[name] = res
|
||||||
|
|
||||||
|
sources_hits = _collect_all_hits(raw_stream_map)
|
||||||
|
|
||||||
|
# Phase C: Finale MoE Synthese (Delegiert an Engine v1.3.0)
|
||||||
|
answer_text = await engine._generate_final_answer(
|
||||||
|
intent, strategy, request.message, formatted_context_map
|
||||||
)
|
)
|
||||||
retrieve_result = await retriever.search(query_req)
|
|
||||||
hits = retrieve_result.results
|
|
||||||
|
|
||||||
if inject_types:
|
|
||||||
strategy_req = QueryRequest(
|
|
||||||
query=request.message,
|
|
||||||
mode="hybrid",
|
|
||||||
top_k=3,
|
|
||||||
filters={"type": inject_types},
|
|
||||||
explain=False,
|
|
||||||
# WP-22: Boosts auch hier anwenden (Konsistenz)
|
|
||||||
boost_edges=edge_boosts
|
|
||||||
)
|
|
||||||
strategy_result = await retriever.search(strategy_req)
|
|
||||||
existing_ids = {h.node_id for h in hits}
|
|
||||||
for strat_hit in strategy_result.results:
|
|
||||||
if strat_hit.node_id not in existing_ids:
|
|
||||||
hits.append(strat_hit)
|
|
||||||
|
|
||||||
if not hits:
|
|
||||||
context_str = "Keine relevanten Notizen gefunden."
|
|
||||||
else:
|
|
||||||
context_str = _build_enriched_context(hits)
|
|
||||||
|
|
||||||
template = llm.prompts.get(prompt_key, "{context_str}\n\n{query}")
|
|
||||||
|
|
||||||
if prepend_instr:
|
|
||||||
context_str = f"{prepend_instr}\n\n{context_str}"
|
|
||||||
|
|
||||||
final_prompt = template.replace("{context_str}", context_str).replace("{query}", request.message)
|
|
||||||
sources_hits = hits
|
|
||||||
|
|
||||||
# --- GENERATION ---
|
|
||||||
system_prompt = llm.prompts.get("system_prompt", "")
|
|
||||||
|
|
||||||
# Chat nutzt IMMER realtime priority
|
|
||||||
answer_text = await llm.generate_raw_response(
|
|
||||||
prompt=final_prompt,
|
|
||||||
system=system_prompt,
|
|
||||||
priority="realtime"
|
|
||||||
)
|
|
||||||
|
|
||||||
duration_ms = int((time.time() - start_time) * 1000)
|
duration_ms = int((time.time() - start_time) * 1000)
|
||||||
|
|
||||||
# Logging
|
# Logging (WP-15)
|
||||||
try:
|
try:
|
||||||
log_search(
|
log_search(
|
||||||
query_id=query_id,
|
query_id=query_id, query_text=request.message, results=sources_hits,
|
||||||
query_text=request.message,
|
mode=f"wp25b_{intent.lower()}", metadata={"strategy": intent, "source": intent_source}
|
||||||
results=sources_hits,
|
|
||||||
mode="interview" if intent == "INTERVIEW" else "chat_rag",
|
|
||||||
metadata={"intent": intent, "source": intent_source}
|
|
||||||
)
|
)
|
||||||
except: pass
|
except: pass
|
||||||
|
|
||||||
return ChatResponse(
|
return ChatResponse(
|
||||||
query_id=query_id,
|
query_id=query_id, answer=answer_text, sources=sources_hits,
|
||||||
answer=answer_text,
|
latency_ms=duration_ms, intent=intent, intent_source=intent_source
|
||||||
sources=sources_hits,
|
|
||||||
latency_ms=duration_ms,
|
|
||||||
intent=intent,
|
|
||||||
intent_source=intent_source
|
|
||||||
)
|
)
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Error in chat endpoint: {e}", exc_info=True)
|
logger.error(f"❌ Chat Endpoint Failure: {e}", exc_info=True)
|
||||||
raise HTTPException(status_code=500, detail=str(e))
|
raise HTTPException(status_code=500, detail="Fehler bei der Verarbeitung der Anfrage.")
|
||||||
@@ -12,7 +12,7 @@ from typing import List, Optional
|
|||||||
from fastapi import APIRouter, Query
|
from fastapi import APIRouter, Query
|
||||||
from qdrant_client import QdrantClient
|
from qdrant_client import QdrantClient
|
||||||
from app.models.dto import GraphResponse, NodeDTO, EdgeDTO
|
from app.models.dto import GraphResponse, NodeDTO, EdgeDTO
|
||||||
from app.core.graph_adapter import expand
|
from app.core.graph.graph_subgraph import expand
|
||||||
from app.config import get_settings
|
from app.config import get_settings
|
||||||
|
|
||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
|
|||||||
+10
-6
@@ -1,8 +1,9 @@
|
|||||||
"""
|
"""
|
||||||
FILE: app/routers/ingest.py
|
FILE: app/routers/ingest.py
|
||||||
DESCRIPTION: Endpunkte für WP-11. Nimmt Markdown entgegen.
|
DESCRIPTION: Endpunkte für WP-11. Nimmt Markdown entgegen.
|
||||||
Refactored für WP-14: Nutzt BackgroundTasks für non-blocking Save.
|
Refactored für WP-14: Nutzt BackgroundTasks für non-blocking Save.
|
||||||
VERSION: 0.7.0 (Fix: Timeout WP-14)
|
Update WP-20: Unterstützung für Hybrid-Cloud-Analyse Feedback.
|
||||||
|
VERSION: 0.8.0 (WP-20 Hybrid Ready)
|
||||||
STATUS: Active
|
STATUS: Active
|
||||||
DEPENDENCIES: app.core.ingestion, app.services.discovery, fastapi, pydantic
|
DEPENDENCIES: app.core.ingestion, app.services.discovery, fastapi, pydantic
|
||||||
"""
|
"""
|
||||||
@@ -44,6 +45,7 @@ class SaveResponse(BaseModel):
|
|||||||
async def run_ingestion_task(markdown_content: str, filename: str, vault_root: str, folder: str):
|
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.
|
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}...")
|
logger.info(f"🔄 Background Task started: Ingesting {filename}...")
|
||||||
try:
|
try:
|
||||||
@@ -80,15 +82,17 @@ async def analyze_draft(req: AnalyzeRequest):
|
|||||||
async def save_note(req: SaveRequest, background_tasks: BackgroundTasks):
|
async def save_note(req: SaveRequest, background_tasks: BackgroundTasks):
|
||||||
"""
|
"""
|
||||||
WP-14 Fix: Startet Ingestion im Hintergrund (Fire & Forget).
|
WP-14 Fix: Startet Ingestion im Hintergrund (Fire & Forget).
|
||||||
Verhindert Timeouts bei aktiver Smart-Edge-Allocation (WP-15).
|
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"
|
||||||
|
|
||||||
@@ -109,7 +113,7 @@ async def save_note(req: SaveRequest, background_tasks: BackgroundTasks):
|
|||||||
status="queued",
|
status="queued",
|
||||||
file_path=os.path.join(req.folder, final_filename),
|
file_path=os.path.join(req.folder, final_filename),
|
||||||
note_id="pending",
|
note_id="pending",
|
||||||
message="Speicherung & KI-Analyse im Hintergrund gestartet.",
|
message="Speicherung & Hybrid-KI-Analyse (WP-20) im Hintergrund gestartet.",
|
||||||
stats={
|
stats={
|
||||||
"chunks": -1, # Indikator für Async
|
"chunks": -1, # Indikator für Async
|
||||||
"edges": -1
|
"edges": -1
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ LAST_ANALYSIS: 2025-12-15
|
|||||||
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
|
||||||
from app.core.retriever import hybrid_retrieve, semantic_retrieve
|
from app.core.retrieval.retriever import hybrid_retrieve, semantic_retrieve
|
||||||
# NEU:
|
# NEU:
|
||||||
from app.services.feedback_service import log_search
|
from app.services.feedback_service import log_search
|
||||||
|
|
||||||
|
|||||||
@@ -13,9 +13,9 @@ import os
|
|||||||
from typing import List, Dict, Any, Optional, Set
|
from typing import List, Dict, Any, Optional, Set
|
||||||
import yaml
|
import yaml
|
||||||
|
|
||||||
from app.core.qdrant import QdrantConfig, get_client
|
from app.core.database.qdrant import QdrantConfig, get_client
|
||||||
from app.models.dto import QueryRequest
|
from app.models.dto import QueryRequest
|
||||||
from app.core.retriever import hybrid_retrieve
|
from app.core.retrieval.retriever import hybrid_retrieve
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|||||||
@@ -1,23 +1,34 @@
|
|||||||
"""
|
"""
|
||||||
FILE: app/services/edge_registry.py
|
FILE: app/services/edge_registry.py
|
||||||
DESCRIPTION: Single Source of Truth für Kanten-Typen.
|
DESCRIPTION: Single Source of Truth für Kanten-Typen mit dynamischem Reload.
|
||||||
FIX: Regex angepasst auf Format **`canonical`** (Bold + Backticks).
|
WP-15b: Erweiterte Provenance-Prüfung für die Candidate-Validation.
|
||||||
VERSION: 0.6.10 (Regex Precision Update)
|
Sichert die Graph-Integrität durch strikte Trennung von System- und Inhaltskanten.
|
||||||
|
WP-22: Fix für absolute Pfade außerhalb des Vaults (Prod-Dictionary).
|
||||||
|
WP-20: Synchronisation mit zentralen Settings (v0.6.2).
|
||||||
|
VERSION: 0.8.0
|
||||||
|
STATUS: Active
|
||||||
|
DEPENDENCIES: re, os, json, logging, time, app.config
|
||||||
|
LAST_ANALYSIS: 2025-12-26
|
||||||
"""
|
"""
|
||||||
import re
|
import re
|
||||||
import os
|
import os
|
||||||
import json
|
import json
|
||||||
import logging
|
import logging
|
||||||
from typing import Dict, Optional, Set
|
import time
|
||||||
|
from typing import Dict, Optional, Set, Tuple
|
||||||
print(">>> MODULE_LOAD: edge_registry.py initialized <<<", flush=True)
|
|
||||||
|
|
||||||
from app.config import get_settings
|
from app.config import get_settings
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
class EdgeRegistry:
|
class EdgeRegistry:
|
||||||
|
"""
|
||||||
|
Zentraler Verwalter für das Kanten-Vokabular.
|
||||||
|
Implementiert das Singleton-Pattern für konsistente Validierung über alle Services.
|
||||||
|
"""
|
||||||
_instance = None
|
_instance = None
|
||||||
|
# System-Kanten, die nicht durch User oder KI gesetzt werden dürfen
|
||||||
|
FORBIDDEN_SYSTEM_EDGES = {"next", "prev", "belongs_to"}
|
||||||
|
|
||||||
def __new__(cls, *args, **kwargs):
|
def __new__(cls, *args, **kwargs):
|
||||||
if cls._instance is None:
|
if cls._instance is None:
|
||||||
@@ -25,39 +36,52 @@ class EdgeRegistry:
|
|||||||
cls._instance.initialized = False
|
cls._instance.initialized = False
|
||||||
return cls._instance
|
return cls._instance
|
||||||
|
|
||||||
def __init__(self, vault_root: Optional[str] = None):
|
def __init__(self):
|
||||||
if self.initialized:
|
if self.initialized:
|
||||||
return
|
return
|
||||||
|
|
||||||
settings = get_settings()
|
settings = get_settings()
|
||||||
env_vocab_path = os.getenv("MINDNET_VOCAB_PATH")
|
|
||||||
env_vault_root = os.getenv("MINDNET_VAULT_ROOT") or getattr(settings, "MINDNET_VAULT_ROOT", "./vault")
|
|
||||||
|
|
||||||
if env_vocab_path:
|
# 1. Pfad aus den zentralen Settings laden (WP-20 Synchronisation)
|
||||||
self.full_vocab_path = os.path.abspath(env_vocab_path)
|
# Priorisiert den Pfad aus der .env / config.py (v0.6.2)
|
||||||
else:
|
self.full_vocab_path = os.path.abspath(settings.MINDNET_VOCAB_PATH)
|
||||||
self.full_vocab_path = os.path.abspath(
|
|
||||||
os.path.join(env_vault_root, "01_User_Manual", "01_edge_vocabulary.md")
|
|
||||||
)
|
|
||||||
|
|
||||||
self.unknown_log_path = "data/logs/unknown_edges.jsonl"
|
self.unknown_log_path = "data/logs/unknown_edges.jsonl"
|
||||||
self.canonical_map: Dict[str, str] = {}
|
self.canonical_map: Dict[str, str] = {}
|
||||||
self.valid_types: Set[str] = set()
|
self.valid_types: Set[str] = set()
|
||||||
|
self._last_mtime = 0.0
|
||||||
|
|
||||||
self._load_vocabulary()
|
# Initialer Ladevorgang
|
||||||
|
logger.info(f">>> [EDGE-REGISTRY] Initializing with Path: {self.full_vocab_path}")
|
||||||
|
self.ensure_latest()
|
||||||
self.initialized = True
|
self.initialized = True
|
||||||
|
|
||||||
def _load_vocabulary(self):
|
def ensure_latest(self):
|
||||||
"""Parst die Markdown-Tabelle im Vault."""
|
"""
|
||||||
print(f">>> CHECK: Loading Vocabulary from {self.full_vocab_path}", flush=True)
|
Prüft den Zeitstempel der Vokabular-Datei und lädt bei Bedarf neu.
|
||||||
|
Verhindert Inkonsistenzen bei Laufzeit-Updates des Dictionaries.
|
||||||
|
"""
|
||||||
if not os.path.exists(self.full_vocab_path):
|
if not os.path.exists(self.full_vocab_path):
|
||||||
print(f"!!! [DICT-ERROR] File not found: {self.full_vocab_path} !!!", flush=True)
|
logger.error(f"!!! [EDGE-REGISTRY ERROR] File not found: {self.full_vocab_path} !!!")
|
||||||
return
|
return
|
||||||
|
|
||||||
# WP-22 Precision Regex:
|
try:
|
||||||
# Sucht nach | **`typ`** | oder | **typ** |
|
current_mtime = os.path.getmtime(self.full_vocab_path)
|
||||||
# Die Backticks `? sind jetzt optional enthalten.
|
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.
|
||||||
|
Erkennt Tabellen-Strukturen und extrahiert fettgedruckte System-Typen.
|
||||||
|
"""
|
||||||
|
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*([^|]+)\|")
|
pattern = re.compile(r"\|\s*\*\*`?([a-zA-Z0-9_-]+)`?\*\*\s*\|\s*([^|]+)\|")
|
||||||
|
|
||||||
try:
|
try:
|
||||||
@@ -74,38 +98,68 @@ class EdgeRegistry:
|
|||||||
c_types += 1
|
c_types += 1
|
||||||
|
|
||||||
if aliases_str and "Kein Alias" not in aliases_str:
|
if aliases_str and "Kein Alias" not in aliases_str:
|
||||||
# Aliase säubern (entfernt Backticks auch hier)
|
|
||||||
aliases = [a.strip() for a in aliases_str.split(",") if a.strip()]
|
aliases = [a.strip() for a in aliases_str.split(",") if a.strip()]
|
||||||
for alias in aliases:
|
for alias in aliases:
|
||||||
|
# Normalisierung: Kleinschreibung, Underscores statt Leerzeichen
|
||||||
clean_alias = alias.replace("`", "").lower().strip().replace(" ", "_")
|
clean_alias = alias.replace("`", "").lower().strip().replace(" ", "_")
|
||||||
self.canonical_map[clean_alias] = canonical
|
self.canonical_map[clean_alias] = canonical
|
||||||
c_aliases += 1
|
c_aliases += 1
|
||||||
|
|
||||||
if c_types == 0:
|
logger.info(f"=== [EDGE-REGISTRY SUCCESS] Loaded {c_types} Canonical Types and {c_aliases} Aliases ===")
|
||||||
print("!!! [DICT-WARN] Pattern mismatch! Ensure types are **`canonical`** or **canonical**. !!!", flush=True)
|
|
||||||
else:
|
|
||||||
print(f"=== [DICT-SUCCESS] Registered {c_types} Canonical Types and {c_aliases} Aliases ===", flush=True)
|
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"!!! [DICT-FATAL] Error reading file: {e} !!!", flush=True)
|
logger.error(f"!!! [EDGE-REGISTRY FATAL] Error reading file: {e} !!!")
|
||||||
|
|
||||||
def resolve(self, edge_type: str) -> str:
|
def resolve(self, edge_type: str, provenance: str = "explicit", context: dict = None) -> str:
|
||||||
"""Normalisiert Kanten-Typen via Registry oder loggt Unbekannte."""
|
"""
|
||||||
if not edge_type: return "related_to"
|
WP-15b: Validiert einen Kanten-Typ gegen das Vokabular und prüft Berechtigungen.
|
||||||
|
Sichert, dass nur strukturelle Prozesse System-Kanten setzen dürfen.
|
||||||
|
"""
|
||||||
|
self.ensure_latest()
|
||||||
|
if not edge_type:
|
||||||
|
return "related_to"
|
||||||
|
|
||||||
|
# Normalisierung des Typs
|
||||||
clean_type = edge_type.lower().strip().replace(" ", "_").replace("-", "_")
|
clean_type = edge_type.lower().strip().replace(" ", "_").replace("-", "_")
|
||||||
|
ctx = context or {}
|
||||||
|
|
||||||
|
# WP-15b: System-Kanten dürfen weder manuell noch durch KI/Vererbung gesetzt werden.
|
||||||
|
# Nur Provenienz 'structure' (interne Prozesse) ist autorisiert.
|
||||||
|
# Wir blockieren hier alle Provenienzen außer 'structure'.
|
||||||
|
restricted_provenance = ["explicit", "semantic_ai", "inherited", "global_pool", "rule"]
|
||||||
|
if provenance in restricted_provenance and clean_type in self.FORBIDDEN_SYSTEM_EDGES:
|
||||||
|
self._log_issue(clean_type, f"forbidden_usage_by_{provenance}", 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 (Alias-Auflösung)
|
||||||
if clean_type in self.canonical_map:
|
if clean_type in self.canonical_map:
|
||||||
return self.canonical_map[clean_type]
|
return self.canonical_map[clean_type]
|
||||||
|
|
||||||
self._log_unknown(clean_type)
|
# Fallback und Logging unbekannter Typen für Admin-Review
|
||||||
|
self._log_issue(clean_type, "unknown_type", ctx)
|
||||||
return clean_type
|
return clean_type
|
||||||
|
|
||||||
def _log_unknown(self, edge_type: str):
|
def _log_issue(self, edge_type: str, error_kind: str, ctx: dict):
|
||||||
|
"""Detailliertes JSONL-Logging für die Vokabular-Optimierung."""
|
||||||
try:
|
try:
|
||||||
os.makedirs(os.path.dirname(self.unknown_log_path), exist_ok=True)
|
os.makedirs(os.path.dirname(self.unknown_log_path), exist_ok=True)
|
||||||
entry = {"unknown_type": edge_type, "status": "new"}
|
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"),
|
||||||
|
"provenance": ctx.get("provenance", "unknown")
|
||||||
|
}
|
||||||
with open(self.unknown_log_path, "a", encoding="utf-8") as f:
|
with open(self.unknown_log_path, "a", encoding="utf-8") as f:
|
||||||
f.write(json.dumps(entry) + "\n")
|
f.write(json.dumps(entry) + "\n")
|
||||||
except Exception: pass
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
# Singleton Export für systemweiten Zugriff
|
||||||
registry = EdgeRegistry()
|
registry = EdgeRegistry()
|
||||||
@@ -1,40 +1,74 @@
|
|||||||
"""
|
"""
|
||||||
FILE: app/services/embeddings_client.py
|
FILE: app/services/embeddings_client.py
|
||||||
DESCRIPTION: Unified Embedding Client. Nutzt Ollama API (HTTP). Ersetzt lokale sentence-transformers.
|
DESCRIPTION: Unified Embedding Client. Nutzt MoE-Profile zur Modellsteuerung.
|
||||||
VERSION: 2.5.0
|
WP-25a: Integration der llm_profiles.yaml für konsistente Vektoren.
|
||||||
|
VERSION: 2.6.0 (WP-25a: MoE & Profile Support)
|
||||||
STATUS: Active
|
STATUS: Active
|
||||||
DEPENDENCIES: httpx, requests, app.config
|
DEPENDENCIES: httpx, requests, app.config, yaml
|
||||||
LAST_ANALYSIS: 2025-12-15
|
|
||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
import os
|
import os
|
||||||
import logging
|
import logging
|
||||||
import httpx
|
import httpx
|
||||||
import requests # Für den synchronen Fallback
|
import requests
|
||||||
from typing import List
|
import yaml
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import List, Dict, Any
|
||||||
from app.config import get_settings
|
from app.config import get_settings
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
class EmbeddingsClient:
|
class EmbeddingsClient:
|
||||||
"""
|
"""
|
||||||
Async Client für Embeddings via Ollama.
|
Async Client für Embeddings.
|
||||||
|
Steuerung erfolgt über das 'embedding_expert' Profil in llm_profiles.yaml.
|
||||||
"""
|
"""
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
self.settings = get_settings()
|
self.settings = get_settings()
|
||||||
self.base_url = os.getenv("MINDNET_OLLAMA_URL", "http://127.0.0.1:11434")
|
|
||||||
self.model = os.getenv("MINDNET_EMBEDDING_MODEL")
|
# 1. MoE-Profil laden (WP-25a)
|
||||||
|
self.profile = self._load_embedding_profile()
|
||||||
|
|
||||||
|
# 2. Modell & URL auflösen
|
||||||
|
# Priorität: llm_profiles.yaml -> .env (Legacy) -> Fallback
|
||||||
|
self.model = self.profile.get("model") or os.getenv("MINDNET_EMBEDDING_MODEL")
|
||||||
|
|
||||||
|
provider = self.profile.get("provider", "ollama")
|
||||||
|
if provider == "ollama":
|
||||||
|
self.base_url = self.settings.OLLAMA_URL
|
||||||
|
else:
|
||||||
|
# Platzhalter für zukünftige Cloud-Embedding-Provider
|
||||||
|
self.base_url = os.getenv("MINDNET_OLLAMA_URL", "http://127.0.0.1:11434")
|
||||||
|
|
||||||
if not self.model:
|
if not self.model:
|
||||||
self.model = os.getenv("MINDNET_LLM_MODEL", "phi3:mini")
|
self.model = os.getenv("MINDNET_LLM_MODEL", "phi3:mini")
|
||||||
logger.warning(f"No MINDNET_EMBEDDING_MODEL set. Fallback to '{self.model}'.")
|
logger.warning(f"⚠️ Kein Embedding-Modell in Profil oder .env gefunden. Fallback auf '{self.model}'.")
|
||||||
|
else:
|
||||||
|
logger.info(f"🧬 Embedding-Experte aktiv: Model='{self.model}' via {provider}")
|
||||||
|
|
||||||
|
def _load_embedding_profile(self) -> Dict[str, Any]:
|
||||||
|
"""Lädt die Konfiguration für den embedding_expert."""
|
||||||
|
path_str = getattr(self.settings, "LLM_PROFILES_PATH", "config/llm_profiles.yaml")
|
||||||
|
path = Path(path_str)
|
||||||
|
if not path.exists():
|
||||||
|
return {}
|
||||||
|
try:
|
||||||
|
with open(path, "r", encoding="utf-8") as f:
|
||||||
|
data = yaml.safe_load(f) or {}
|
||||||
|
profiles = data.get("profiles", {})
|
||||||
|
return profiles.get("embedding_expert", {})
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"❌ Failed to load embedding profile: {e}")
|
||||||
|
return {}
|
||||||
|
|
||||||
async def embed_query(self, text: str) -> List[float]:
|
async def embed_query(self, text: str) -> List[float]:
|
||||||
|
"""Erzeugt einen Vektor für eine Suchanfrage."""
|
||||||
return await self._request_embedding(text)
|
return await self._request_embedding(text)
|
||||||
|
|
||||||
async def embed_documents(self, texts: List[str]) -> List[List[float]]:
|
async def embed_documents(self, texts: List[str]) -> List[List[float]]:
|
||||||
|
"""Erzeugt Vektoren für einen Batch von Dokumenten."""
|
||||||
vectors = []
|
vectors = []
|
||||||
# Längeres Timeout für Batches
|
# Längeres Timeout für Batches (WP-20 Resilienz)
|
||||||
async with httpx.AsyncClient(timeout=120.0) as client:
|
async with httpx.AsyncClient(timeout=120.0) as client:
|
||||||
for text in texts:
|
for text in texts:
|
||||||
vec = await self._request_embedding_with_client(client, text)
|
vec = await self._request_embedding_with_client(client, text)
|
||||||
@@ -42,18 +76,23 @@ class EmbeddingsClient:
|
|||||||
return vectors
|
return vectors
|
||||||
|
|
||||||
async def _request_embedding(self, text: str) -> List[float]:
|
async def _request_embedding(self, text: str) -> List[float]:
|
||||||
|
"""Interner Request-Handler für Einzelabfragen."""
|
||||||
async with httpx.AsyncClient(timeout=30.0) as client:
|
async with httpx.AsyncClient(timeout=30.0) as client:
|
||||||
return await self._request_embedding_with_client(client, text)
|
return await self._request_embedding_with_client(client, text)
|
||||||
|
|
||||||
async def _request_embedding_with_client(self, client: httpx.AsyncClient, text: str) -> List[float]:
|
async def _request_embedding_with_client(self, client: httpx.AsyncClient, text: str) -> List[float]:
|
||||||
if not text or not text.strip(): return []
|
"""Führt den HTTP-Call gegen die Embedding-API durch."""
|
||||||
|
if not text or not text.strip():
|
||||||
|
return []
|
||||||
|
|
||||||
url = f"{self.base_url}/api/embeddings"
|
url = f"{self.base_url}/api/embeddings"
|
||||||
try:
|
try:
|
||||||
|
# WP-25: Aktuell optimiert für Ollama-API Struktur
|
||||||
response = await client.post(url, json={"model": self.model, "prompt": text})
|
response = await client.post(url, json={"model": self.model, "prompt": text})
|
||||||
response.raise_for_status()
|
response.raise_for_status()
|
||||||
return response.json().get("embedding", [])
|
return response.json().get("embedding", [])
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Async embedding failed: {e}")
|
logger.error(f"Async embedding failed (Model: {self.model}): {e}")
|
||||||
return []
|
return []
|
||||||
|
|
||||||
# ==============================================================================
|
# ==============================================================================
|
||||||
@@ -62,27 +101,38 @@ class EmbeddingsClient:
|
|||||||
|
|
||||||
def embed_text(text: str) -> List[float]:
|
def embed_text(text: str) -> List[float]:
|
||||||
"""
|
"""
|
||||||
LEGACY/SYNC: Nutzt jetzt ebenfalls OLLAMA via 'requests'.
|
LEGACY/SYNC: Nutzt ebenfalls die Profil-Logik für Konsistenz.
|
||||||
Ersetzt SentenceTransformers, um Dimensionskonflikte (768 vs 384) zu lösen.
|
Ersetzt lokale sentence-transformers zur Vermeidung von Dimensionskonflikten.
|
||||||
"""
|
"""
|
||||||
if not text or not text.strip():
|
if not text or not text.strip():
|
||||||
return []
|
return []
|
||||||
|
|
||||||
base_url = os.getenv("MINDNET_OLLAMA_URL", "http://127.0.0.1:11434")
|
settings = get_settings()
|
||||||
model = os.getenv("MINDNET_EMBEDDING_MODEL")
|
|
||||||
|
# Schneller Profil-Lookup für Sync-Mode
|
||||||
|
path = Path(getattr(settings, "LLM_PROFILES_PATH", "config/llm_profiles.yaml"))
|
||||||
|
model = os.getenv("MINDNET_EMBEDDING_MODEL")
|
||||||
|
base_url = settings.OLLAMA_URL
|
||||||
|
|
||||||
|
if path.exists():
|
||||||
|
try:
|
||||||
|
with open(path, "r", encoding="utf-8") as f:
|
||||||
|
data = yaml.safe_load(f) or {}
|
||||||
|
prof = data.get("profiles", {}).get("embedding_expert", {})
|
||||||
|
if prof.get("model"):
|
||||||
|
model = prof["model"]
|
||||||
|
except: pass
|
||||||
|
|
||||||
# Fallback logik identisch zur Klasse
|
|
||||||
if not model:
|
if not model:
|
||||||
model = os.getenv("MINDNET_LLM_MODEL", "phi3:mini")
|
model = os.getenv("MINDNET_LLM_MODEL", "phi3:mini")
|
||||||
|
|
||||||
url = f"{base_url}/api/embeddings"
|
url = f"{base_url}/api/embeddings"
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# Synchroner Request (blockierend)
|
# Synchroner Request via requests
|
||||||
response = requests.post(url, json={"model": model, "prompt": text}, timeout=30)
|
response = requests.post(url, json={"model": model, "prompt": text}, timeout=30)
|
||||||
response.raise_for_status()
|
response.raise_for_status()
|
||||||
data = response.json()
|
return response.json().get("embedding", [])
|
||||||
return data.get("embedding", [])
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Sync embedding (Ollama) failed: {e}")
|
logger.error(f"Sync embedding failed (Model: {model}): {e}")
|
||||||
return []
|
return []
|
||||||
+282
-92
@@ -1,147 +1,337 @@
|
|||||||
"""
|
"""
|
||||||
FILE: app/services/llm_service.py
|
FILE: app/services/llm_service.py
|
||||||
DESCRIPTION: Asynchroner Client für Ollama. Verwaltet Prompts und Background-Last (Semaphore).
|
DESCRIPTION: Hybrid-Client für Ollama, Google GenAI (Gemini) und OpenRouter.
|
||||||
VERSION: 2.8.0
|
WP-25b: Implementierung der Lazy-Prompt-Orchestration (Modell-spezifisch).
|
||||||
|
VERSION: 3.5.5 (WP-25b: Prompt Orchestration & Full Resilience)
|
||||||
STATUS: Active
|
STATUS: Active
|
||||||
DEPENDENCIES: httpx, yaml, asyncio, app.config
|
FIX:
|
||||||
EXTERNAL_CONFIG: config/prompts.yaml
|
- WP-25b: get_prompt() unterstützt Hierarchie: Model-ID -> Provider -> Default.
|
||||||
LAST_ANALYSIS: 2025-12-15
|
- WP-25b: generate_raw_response() unterstützt prompt_key + variables für Lazy-Formatting.
|
||||||
|
- WP-25a: Voller Erhalt der rekursiven Fallback-Kaskade und visited_profiles Schutz.
|
||||||
|
- WP-20: Restaurierung des internen Ollama-Retry-Loops für Hardware-Stabilität.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import httpx
|
import httpx
|
||||||
import yaml
|
import yaml
|
||||||
import logging
|
import logging
|
||||||
import os
|
|
||||||
import asyncio
|
import asyncio
|
||||||
|
import json
|
||||||
|
from google import genai
|
||||||
|
from google.genai import types
|
||||||
|
from openai import AsyncOpenAI
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Optional, Dict, Any, Literal
|
from typing import Optional, Dict, Any, Literal
|
||||||
|
from app.config import get_settings
|
||||||
|
|
||||||
|
# Import der neutralen Bereinigungs-Logik
|
||||||
|
from app.core.registry import clean_llm_text
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
class Settings:
|
|
||||||
OLLAMA_URL = os.getenv("MINDNET_OLLAMA_URL", "http://127.0.0.1:11434")
|
|
||||||
LLM_TIMEOUT = float(os.getenv("MINDNET_LLM_TIMEOUT", 300.0))
|
|
||||||
LLM_MODEL = os.getenv("MINDNET_LLM_MODEL", "phi3:mini")
|
|
||||||
PROMPTS_PATH = os.getenv("MINDNET_PROMPTS_PATH", "./config/prompts.yaml")
|
|
||||||
|
|
||||||
# NEU: Konfigurierbares Limit für Hintergrund-Last
|
|
||||||
# Default auf 2 (konservativ), kann in .env erhöht werden.
|
|
||||||
BACKGROUND_LIMIT = int(os.getenv("MINDNET_LLM_BACKGROUND_LIMIT", "2"))
|
|
||||||
|
|
||||||
def get_settings():
|
|
||||||
return Settings()
|
|
||||||
|
|
||||||
class LLMService:
|
class LLMService:
|
||||||
# GLOBALER SEMAPHOR (Lazy Initialization)
|
|
||||||
# Wir initialisieren ihn erst, wenn wir die Settings kennen.
|
|
||||||
_background_semaphore = None
|
_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.profiles = self._load_llm_profiles()
|
||||||
|
self._decision_engine = None
|
||||||
|
|
||||||
# Initialisiere Semaphore einmalig auf Klassen-Ebene basierend auf Config
|
|
||||||
if LLMService._background_semaphore is None:
|
if LLMService._background_semaphore is None:
|
||||||
limit = self.settings.BACKGROUND_LIMIT
|
limit = getattr(self.settings, "BACKGROUND_LIMIT", 2)
|
||||||
logger.info(f"🚦 LLMService: Initializing Background Semaphore with limit: {limit}")
|
logger.info(f"🚦 LLMService: Initializing Background Semaphore with limit: {limit}")
|
||||||
LLMService._background_semaphore = asyncio.Semaphore(limit)
|
LLMService._background_semaphore = asyncio.Semaphore(limit)
|
||||||
|
|
||||||
self.timeout = httpx.Timeout(self.settings.LLM_TIMEOUT, connect=10.0)
|
# 1. Lokaler Ollama Client
|
||||||
|
self.ollama_client = httpx.AsyncClient(
|
||||||
self.client = httpx.AsyncClient(
|
|
||||||
base_url=self.settings.OLLAMA_URL,
|
base_url=self.settings.OLLAMA_URL,
|
||||||
timeout=self.timeout
|
timeout=httpx.Timeout(self.settings.LLM_TIMEOUT)
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# 2. Google GenAI Client
|
||||||
|
self.google_client = None
|
||||||
|
if self.settings.GOOGLE_API_KEY:
|
||||||
|
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,
|
||||||
|
timeout=45.0
|
||||||
|
)
|
||||||
|
logger.info("🛰️ LLMService: OpenRouter Integration active.")
|
||||||
|
|
||||||
|
@property
|
||||||
|
def decision_engine(self):
|
||||||
|
if self._decision_engine is None:
|
||||||
|
from app.core.retrieval.decision_engine import DecisionEngine
|
||||||
|
self._decision_engine = DecisionEngine()
|
||||||
|
return self._decision_engine
|
||||||
|
|
||||||
def _load_prompts(self) -> dict:
|
def _load_prompts(self) -> dict:
|
||||||
path = Path(self.settings.PROMPTS_PATH)
|
path = Path(self.settings.PROMPTS_PATH)
|
||||||
if not path.exists(): return {}
|
if not path.exists():
|
||||||
try:
|
|
||||||
with open(path, "r", encoding="utf-8") as f: return yaml.safe_load(f)
|
|
||||||
except Exception as e:
|
|
||||||
logger.error(f"Failed to load prompts: {e}")
|
|
||||||
return {}
|
return {}
|
||||||
|
try:
|
||||||
|
with open(path, "r", encoding="utf-8") as f:
|
||||||
|
return yaml.safe_load(f) or {}
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"❌ Failed to load prompts: {e}")
|
||||||
|
return {}
|
||||||
|
|
||||||
|
def _load_llm_profiles(self) -> dict:
|
||||||
|
"""WP-25a: Lädt die zentralen MoE-Profile aus der llm_profiles.yaml."""
|
||||||
|
path_str = getattr(self.settings, "LLM_PROFILES_PATH", "config/llm_profiles.yaml")
|
||||||
|
path = Path(path_str)
|
||||||
|
if not path.exists():
|
||||||
|
logger.warning(f"⚠️ LLM Profiles file not found at {path}.")
|
||||||
|
return {}
|
||||||
|
try:
|
||||||
|
with open(path, "r", encoding="utf-8") as f:
|
||||||
|
data = yaml.safe_load(f) or {}
|
||||||
|
return data.get("profiles", {})
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"❌ Failed to load llm_profiles.yaml: {e}")
|
||||||
|
return {}
|
||||||
|
|
||||||
|
def get_prompt(self, key: str, model_id: str = None, provider: str = None) -> str:
|
||||||
|
"""
|
||||||
|
WP-25b: Hochpräziser Prompt-Lookup mit detailliertem Trace-Logging.
|
||||||
|
"""
|
||||||
|
data = self.prompts.get(key, "")
|
||||||
|
if not isinstance(data, dict):
|
||||||
|
return str(data)
|
||||||
|
|
||||||
|
# 1. Spezifischstes Match: Exakte Modell-ID
|
||||||
|
if model_id and model_id in data:
|
||||||
|
logger.info(f"🎯 [PROMPT-TRACE] Level 1 Match: Model-specific ('{model_id}') for key '{key}'")
|
||||||
|
return str(data[model_id])
|
||||||
|
|
||||||
|
# 2. Mittlere Ebene: Provider
|
||||||
|
if provider and provider in data:
|
||||||
|
logger.info(f"📡 [PROMPT-TRACE] Level 2 Match: Provider-fallback ('{provider}') for key '{key}'")
|
||||||
|
return str(data[provider])
|
||||||
|
|
||||||
|
# 3. Globaler Fallback
|
||||||
|
default_val = data.get("default", data.get("gemini", data.get("ollama", "")))
|
||||||
|
logger.info(f"⚓ [PROMPT-TRACE] Level 3 Match: Global Default for key '{key}'")
|
||||||
|
return str(default_val)
|
||||||
|
|
||||||
async def generate_raw_response(
|
async def generate_raw_response(
|
||||||
self,
|
self,
|
||||||
prompt: str,
|
prompt: str = None,
|
||||||
|
prompt_key: str = None, # WP-25b: Lazy Loading Key
|
||||||
|
variables: dict = None, # WP-25b: Daten für Formatierung
|
||||||
system: str = None,
|
system: str = None,
|
||||||
force_json: bool = False,
|
force_json: bool = False,
|
||||||
max_retries: int = 0,
|
max_retries: int = 2,
|
||||||
base_delay: float = 2.0,
|
base_delay: float = 2.0,
|
||||||
priority: Literal["realtime", "background"] = "realtime"
|
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,
|
||||||
|
profile_name: Optional[str] = None,
|
||||||
|
visited_profiles: Optional[list] = None
|
||||||
) -> str:
|
) -> str:
|
||||||
"""
|
"""Haupteinstiegspunkt für LLM-Anfragen mit Lazy-Prompt Orchestrierung."""
|
||||||
Führt einen LLM Call aus.
|
visited_profiles = visited_profiles or []
|
||||||
priority="realtime": Chat (Sofort, keine Bremse).
|
target_provider = provider
|
||||||
priority="background": Import/Analyse (Gedrosselt durch Semaphore).
|
target_model = model_override
|
||||||
"""
|
target_temp = None
|
||||||
|
fallback_profile = None
|
||||||
|
|
||||||
use_semaphore = (priority == "background")
|
# 1. Profil-Auflösung (Mixture of Experts)
|
||||||
|
if profile_name and self.profiles:
|
||||||
|
profile = self.profiles.get(profile_name)
|
||||||
|
if profile:
|
||||||
|
target_provider = profile.get("provider", target_provider)
|
||||||
|
target_model = profile.get("model", target_model)
|
||||||
|
target_temp = profile.get("temperature")
|
||||||
|
fallback_profile = profile.get("fallback_profile")
|
||||||
|
visited_profiles.append(profile_name)
|
||||||
|
logger.info(f"🎭 MoE Dispatch: Profil='{profile_name}' -> Provider='{target_provider}' | Model='{target_model}'")
|
||||||
|
else:
|
||||||
|
logger.warning(f"⚠️ Profil '{profile_name}' nicht in llm_profiles.yaml gefunden!")
|
||||||
|
|
||||||
if use_semaphore and LLMService._background_semaphore:
|
if not target_provider:
|
||||||
async with LLMService._background_semaphore:
|
target_provider = self.settings.MINDNET_LLM_PROVIDER
|
||||||
return await self._execute_request(prompt, system, force_json, max_retries, base_delay)
|
|
||||||
else:
|
|
||||||
# Realtime oder Fallback (falls Semaphore Init fehlschlug)
|
|
||||||
return await self._execute_request(prompt, system, force_json, max_retries, base_delay)
|
|
||||||
|
|
||||||
async def _execute_request(self, prompt, system, force_json, max_retries, base_delay):
|
# 2. WP-25b: Lazy Prompt Resolving
|
||||||
payload: Dict[str, Any] = {
|
# Wir laden den Prompt erst JETZT, basierend auf dem gerade aktiven Modell.
|
||||||
"model": self.settings.LLM_MODEL,
|
current_prompt = prompt
|
||||||
"prompt": prompt,
|
if prompt_key:
|
||||||
"stream": False,
|
template = self.get_prompt(prompt_key, model_id=target_model, provider=target_provider)
|
||||||
"options": {
|
# WP-25b FIX: Validierung des geladenen Prompts
|
||||||
"temperature": 0.1 if force_json else 0.7,
|
if not template or not template.strip():
|
||||||
"num_ctx": 8192
|
available_keys = list(self.prompts.keys())
|
||||||
}
|
logger.error(f"❌ Prompt key '{prompt_key}' not found or empty. Available keys: {available_keys[:10]}...")
|
||||||
|
raise ValueError(f"Invalid prompt_key: '{prompt_key}' (not found in prompts.yaml)")
|
||||||
|
|
||||||
|
try:
|
||||||
|
# Formatierung mit den übergebenen Variablen
|
||||||
|
current_prompt = template.format(**(variables or {}))
|
||||||
|
except KeyError as e:
|
||||||
|
logger.error(f"❌ Prompt formatting failed for key '{prompt_key}': Missing variable {e}")
|
||||||
|
raise ValueError(f"Missing variable in prompt '{prompt_key}': {e}")
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"❌ Prompt formatting failed for key '{prompt_key}': {e}")
|
||||||
|
current_prompt = template # Sicherheits-Fallback
|
||||||
|
|
||||||
|
# 3. Ausführung mit Fehler-Handling für Kaskade
|
||||||
|
try:
|
||||||
|
if priority == "background":
|
||||||
|
async with LLMService._background_semaphore:
|
||||||
|
res = await self._dispatch(
|
||||||
|
target_provider, current_prompt, system, force_json,
|
||||||
|
max_retries, base_delay, target_model,
|
||||||
|
json_schema, json_schema_name, strict_json_schema, target_temp
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
res = await self._dispatch(
|
||||||
|
target_provider, current_prompt, system, force_json,
|
||||||
|
max_retries, base_delay, target_model,
|
||||||
|
json_schema, json_schema_name, strict_json_schema, target_temp
|
||||||
|
)
|
||||||
|
|
||||||
|
# Check auf leere Cloud-Antworten (WP-25 Stability)
|
||||||
|
if not res and target_provider != "ollama":
|
||||||
|
logger.warning(f"⚠️ Empty response from {target_provider}. Triggering fallback.")
|
||||||
|
raise ValueError(f"Empty response from {target_provider}")
|
||||||
|
|
||||||
|
return clean_llm_text(res) if not force_json else res
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"❌ Error during execution of profile '{profile_name}' ({target_provider}): {e}")
|
||||||
|
|
||||||
|
# 4. WP-25b Kaskaden-Logik (Rekursiv mit Modell-spezifischem Re-Loading)
|
||||||
|
if fallback_profile and fallback_profile not in visited_profiles:
|
||||||
|
logger.info(f"🔄 Switching to fallback profile: '{fallback_profile}'")
|
||||||
|
return await self.generate_raw_response(
|
||||||
|
prompt=prompt,
|
||||||
|
prompt_key=prompt_key,
|
||||||
|
variables=variables, # Ermöglicht neues Formatting für Fallback-Modell
|
||||||
|
system=system, force_json=force_json,
|
||||||
|
max_retries=max_retries, base_delay=base_delay,
|
||||||
|
priority=priority, provider=None, model_override=None,
|
||||||
|
json_schema=json_schema, json_schema_name=json_schema_name,
|
||||||
|
strict_json_schema=strict_json_schema,
|
||||||
|
profile_name=fallback_profile,
|
||||||
|
visited_profiles=visited_profiles
|
||||||
|
)
|
||||||
|
|
||||||
|
# 5. Ultimativer Notanker: Falls alles fehlschlägt, direkt zu Ollama
|
||||||
|
if target_provider != "ollama" and self.settings.LLM_FALLBACK_ENABLED:
|
||||||
|
logger.warning(f"🚨 Kaskade erschöpft. Nutze finalen Ollama-Notanker.")
|
||||||
|
res = await self._execute_ollama(current_prompt, system, force_json, max_retries, base_delay, target_temp, target_model)
|
||||||
|
return clean_llm_text(res) if not force_json else res
|
||||||
|
|
||||||
|
raise e
|
||||||
|
|
||||||
|
async def _dispatch(
|
||||||
|
self, provider, prompt, system, force_json, max_retries, base_delay,
|
||||||
|
model_override, json_schema, json_schema_name, strict_json_schema, temperature
|
||||||
|
) -> str:
|
||||||
|
"""Routet die Anfrage an den spezifischen Provider-Executor."""
|
||||||
|
rate_limit_attempts = 0
|
||||||
|
max_rate_retries = min(max_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,
|
||||||
|
temperature=temperature
|
||||||
|
)
|
||||||
|
|
||||||
|
if provider == "gemini" and self.google_client:
|
||||||
|
return await self._execute_google(prompt, system, force_json, model_override, temperature)
|
||||||
|
|
||||||
|
return await self._execute_ollama(prompt, system, force_json, max_retries, base_delay, temperature, model_override)
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
err_str = str(e)
|
||||||
|
if any(x in err_str for x in ["429", "RESOURCE_EXHAUSTED", "rate_limited"]):
|
||||||
|
rate_limit_attempts += 1
|
||||||
|
logger.warning(f"⏳ Rate Limit {provider}. Attempt {rate_limit_attempts}. Wait {wait_time}s.")
|
||||||
|
await asyncio.sleep(wait_time)
|
||||||
|
continue
|
||||||
|
raise e
|
||||||
|
|
||||||
|
async def _execute_google(self, prompt, system, force_json, model_override, temperature):
|
||||||
|
model = (model_override or self.settings.GEMINI_MODEL).replace("models/", "")
|
||||||
|
config_kwargs = {
|
||||||
|
"system_instruction": system,
|
||||||
|
"response_mime_type": "application/json" if force_json else "text/plain"
|
||||||
}
|
}
|
||||||
|
if temperature is not None:
|
||||||
|
config_kwargs["temperature"] = temperature
|
||||||
|
|
||||||
|
config = types.GenerateContentConfig(**config_kwargs)
|
||||||
|
response = await asyncio.wait_for(
|
||||||
|
asyncio.to_thread(self.google_client.models.generate_content, model=model, contents=prompt, config=config),
|
||||||
|
timeout=45.0
|
||||||
|
)
|
||||||
|
return response.text.strip()
|
||||||
|
|
||||||
|
async def _execute_openrouter(self, prompt, system, force_json, model_override, json_schema, json_schema_name, strict_json_schema, temperature) -> str:
|
||||||
|
model = model_override or self.settings.OPENROUTER_MODEL
|
||||||
|
logger.info(f"🛰️ OpenRouter Call: Model='{model}' | Temp={temperature}")
|
||||||
|
messages = []
|
||||||
|
if system: messages.append({"role": "system", "content": system})
|
||||||
|
messages.append({"role": "user", "content": prompt})
|
||||||
|
|
||||||
|
kwargs: Dict[str, Any] = {}
|
||||||
|
if temperature is not None: kwargs["temperature"] = temperature
|
||||||
|
|
||||||
if force_json:
|
if force_json:
|
||||||
payload["format"] = "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"}
|
||||||
|
|
||||||
if system:
|
response = await self.openrouter_client.chat.completions.create(model=model, messages=messages, **kwargs)
|
||||||
payload["system"] = system
|
if not response.choices: return ""
|
||||||
|
return response.choices[0].message.content.strip() if response.choices[0].message.content else ""
|
||||||
|
|
||||||
|
async def _execute_ollama(self, prompt, system, force_json, max_retries, base_delay, temperature=None, model_override=None):
|
||||||
|
# WP-20: Restaurierter Retry-Loop für lokale Hardware-Resilienz
|
||||||
|
effective_model = model_override or self.settings.LLM_MODEL
|
||||||
|
effective_temp = temperature if temperature is not None else (0.1 if force_json else 0.7)
|
||||||
|
|
||||||
|
payload = {
|
||||||
|
"model": effective_model,
|
||||||
|
"prompt": prompt, "stream": False,
|
||||||
|
"options": {"temperature": effective_temp, "num_ctx": 8192}
|
||||||
|
}
|
||||||
|
if force_json: payload["format"] = "json"
|
||||||
|
if system: payload["system"] = system
|
||||||
|
|
||||||
attempt = 0
|
attempt = 0
|
||||||
|
|
||||||
while True:
|
while True:
|
||||||
try:
|
try:
|
||||||
response = await self.client.post("/api/generate", json=payload)
|
res = await self.ollama_client.post("/api/generate", json=payload)
|
||||||
|
res.raise_for_status()
|
||||||
if response.status_code == 200:
|
return res.json().get("response", "").strip()
|
||||||
data = response.json()
|
|
||||||
return data.get("response", "").strip()
|
|
||||||
else:
|
|
||||||
response.raise_for_status()
|
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
attempt += 1
|
attempt += 1
|
||||||
if attempt > max_retries:
|
if attempt > max_retries:
|
||||||
logger.error(f"LLM Final Error (Versuch {attempt}): {e}")
|
logger.error(f"❌ Ollama failure after {attempt} attempts: {e}")
|
||||||
raise e
|
raise e
|
||||||
|
await asyncio.sleep(base_delay * (2 ** (attempt - 1)))
|
||||||
|
|
||||||
wait_time = base_delay * (2 ** (attempt - 1))
|
async def generate_rag_response(self, query: str, context_str: Optional[str] = None) -> str:
|
||||||
logger.warning(f"⚠️ LLM Retry ({attempt}/{max_retries}) in {wait_time}s: {e}")
|
return await self.decision_engine.ask(query)
|
||||||
await asyncio.sleep(wait_time)
|
|
||||||
|
|
||||||
async def generate_rag_response(self, query: str, context_str: str) -> str:
|
|
||||||
"""
|
|
||||||
Chat-Wrapper: Immer Realtime.
|
|
||||||
"""
|
|
||||||
system_prompt = self.prompts.get("system_prompt", "")
|
|
||||||
rag_template = self.prompts.get("rag_template", "{context_str}\n\n{query}")
|
|
||||||
|
|
||||||
final_prompt = rag_template.format(context_str=context_str, query=query)
|
|
||||||
|
|
||||||
return await self.generate_raw_response(
|
|
||||||
final_prompt,
|
|
||||||
system=system_prompt,
|
|
||||||
max_retries=0,
|
|
||||||
force_json=False,
|
|
||||||
priority="realtime"
|
|
||||||
)
|
|
||||||
|
|
||||||
async def close(self):
|
async def close(self):
|
||||||
if self.client:
|
if self.ollama_client:
|
||||||
await self.client.aclose()
|
await self.ollama_client.aclose()
|
||||||
@@ -1,177 +0,0 @@
|
|||||||
"""
|
|
||||||
FILE: app/services/semantic_analyzer.py
|
|
||||||
DESCRIPTION: KI-gestützte Kanten-Validierung. Nutzt LLM (Background-Priority), um Kanten präzise einem Chunk zuzuordnen.
|
|
||||||
VERSION: 2.1.0 (Fix: Strict Edge String Validation against LLM Hallucinations)
|
|
||||||
STATUS: Active
|
|
||||||
DEPENDENCIES: app.services.llm_service, json, logging
|
|
||||||
LAST_ANALYSIS: 2025-12-16
|
|
||||||
"""
|
|
||||||
|
|
||||||
import json
|
|
||||||
import logging
|
|
||||||
from typing import List, Optional
|
|
||||||
from dataclasses import dataclass
|
|
||||||
|
|
||||||
# Importe
|
|
||||||
from app.services.llm_service import LLMService
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
class SemanticAnalyzer:
|
|
||||||
def __init__(self):
|
|
||||||
self.llm = LLMService()
|
|
||||||
|
|
||||||
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 ("Here is the list: ...") 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.
|
|
||||||
# Erlaubt: "derived_from", "related_to"
|
|
||||||
# Verboten: "derived end of instruction", "Here is the list"
|
|
||||||
if " " in kind:
|
|
||||||
return False
|
|
||||||
|
|
||||||
# Regel 2: Plausible Länge für den 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
|
|
||||||
|
|
||||||
async def assign_edges_to_chunk(self, chunk_text: str, all_edges: List[str], note_type: str) -> List[str]:
|
|
||||||
"""
|
|
||||||
Sendet einen Chunk und eine Liste potenzieller Kanten an das LLM.
|
|
||||||
Das LLM filtert heraus, welche Kanten für diesen Chunk relevant sind.
|
|
||||||
|
|
||||||
Features:
|
|
||||||
- Retry Strategy: Wartet bei Überlastung (max_retries=5).
|
|
||||||
- Priority Queue: Läuft als "background" Task, um den Chat nicht zu blockieren.
|
|
||||||
- Observability: Loggt Input-Größe, Raw-Response und Parsing-Details.
|
|
||||||
"""
|
|
||||||
if not all_edges:
|
|
||||||
return []
|
|
||||||
|
|
||||||
# 1. Prompt laden
|
|
||||||
prompt_template = self.llm.prompts.get("edge_allocation_template")
|
|
||||||
|
|
||||||
if not prompt_template:
|
|
||||||
logger.warning("⚠️ [SemanticAnalyzer] Prompt 'edge_allocation_template' fehlt. Nutze Fallback.")
|
|
||||||
prompt_template = (
|
|
||||||
"TASK: Wähle aus den Kandidaten die relevanten Kanten für den Text.\n"
|
|
||||||
"TEXT: {chunk_text}\n"
|
|
||||||
"KANDIDATEN: {edge_list}\n"
|
|
||||||
"OUTPUT: JSON Liste von Strings [\"kind:target\"]."
|
|
||||||
)
|
|
||||||
|
|
||||||
# 2. Kandidaten-Liste formatieren
|
|
||||||
edges_str = "\n".join([f"- {e}" for e in all_edges])
|
|
||||||
|
|
||||||
# LOG: Request Info
|
|
||||||
logger.debug(f"🔍 [SemanticAnalyzer] Request: {len(chunk_text)} chars Text, {len(all_edges)} Candidates.")
|
|
||||||
|
|
||||||
# 3. Prompt füllen
|
|
||||||
final_prompt = prompt_template.format(
|
|
||||||
chunk_text=chunk_text[:3500],
|
|
||||||
edge_list=edges_str
|
|
||||||
)
|
|
||||||
|
|
||||||
try:
|
|
||||||
# 4. LLM Call mit Traffic Control
|
|
||||||
response_json = await self.llm.generate_raw_response(
|
|
||||||
prompt=final_prompt,
|
|
||||||
force_json=True,
|
|
||||||
max_retries=5,
|
|
||||||
base_delay=5.0,
|
|
||||||
priority="background"
|
|
||||||
)
|
|
||||||
|
|
||||||
# LOG: Raw Response Preview
|
|
||||||
logger.debug(f"📥 [SemanticAnalyzer] Raw Response (Preview): {response_json[:200]}...")
|
|
||||||
|
|
||||||
# 5. Parsing & Cleaning
|
|
||||||
clean_json = response_json.replace("```json", "").replace("```", "").strip()
|
|
||||||
|
|
||||||
if not clean_json:
|
|
||||||
logger.warning("⚠️ [SemanticAnalyzer] Leere Antwort vom LLM erhalten. Trigger Fallback.")
|
|
||||||
return []
|
|
||||||
|
|
||||||
try:
|
|
||||||
data = json.loads(clean_json)
|
|
||||||
except json.JSONDecodeError as json_err:
|
|
||||||
logger.error(f"❌ [SemanticAnalyzer] JSON Decode Error.")
|
|
||||||
logger.error(f" Grund: {json_err}")
|
|
||||||
logger.error(f" Empfangener String: {clean_json[:500]}")
|
|
||||||
logger.info(" -> Workaround: Fallback auf 'Alle Kanten' (durch Chunker).")
|
|
||||||
return []
|
|
||||||
|
|
||||||
valid_edges = []
|
|
||||||
|
|
||||||
# 6. Robuste Validierung (List vs Dict)
|
|
||||||
# Wir sammeln erst alle Strings ein
|
|
||||||
raw_candidates = []
|
|
||||||
|
|
||||||
if isinstance(data, list):
|
|
||||||
raw_candidates = data
|
|
||||||
|
|
||||||
elif isinstance(data, dict):
|
|
||||||
logger.info(f"ℹ️ [SemanticAnalyzer] LLM lieferte Dict statt Liste. Versuche Reparatur. Keys: {list(data.keys())}")
|
|
||||||
for key, val in data.items():
|
|
||||||
# Fall A: {"edges": ["kind:target"]}
|
|
||||||
if key.lower() in ["edges", "results", "kanten", "matches"] and isinstance(val, list):
|
|
||||||
raw_candidates.extend(val)
|
|
||||||
|
|
||||||
# Fall B: {"kind": "target"} (Beziehung als Key)
|
|
||||||
elif isinstance(val, str):
|
|
||||||
raw_candidates.append(f"{key}:{val}")
|
|
||||||
|
|
||||||
# Fall C: {"kind": ["target1", "target2"]}
|
|
||||||
elif isinstance(val, list):
|
|
||||||
for target in val:
|
|
||||||
if isinstance(target, str):
|
|
||||||
raw_candidates.append(f"{key}:{target}")
|
|
||||||
|
|
||||||
# 7. Strict Validation Loop
|
|
||||||
for e in raw_candidates:
|
|
||||||
e_str = str(e)
|
|
||||||
if self._is_valid_edge_string(e_str):
|
|
||||||
valid_edges.append(e_str)
|
|
||||||
else:
|
|
||||||
logger.debug(f" [SemanticAnalyzer] Invalid edge format rejected: '{e_str}'")
|
|
||||||
|
|
||||||
# Safety: Filtere nur Kanten, die halbwegs valide aussehen (Doppelcheck)
|
|
||||||
final_result = [e for e in valid_edges if ":" in e]
|
|
||||||
|
|
||||||
# LOG: Ergebnis
|
|
||||||
if final_result:
|
|
||||||
logger.info(f"✅ [SemanticAnalyzer] Success. {len(final_result)} Kanten zugewiesen.")
|
|
||||||
else:
|
|
||||||
logger.debug(" [SemanticAnalyzer] Keine spezifischen Kanten erkannt (Empty Result).")
|
|
||||||
|
|
||||||
return final_result
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
logger.error(f"💥 [SemanticAnalyzer] Kritischer Fehler: {e}", exc_info=True)
|
|
||||||
return []
|
|
||||||
|
|
||||||
async def close(self):
|
|
||||||
if self.llm:
|
|
||||||
await self.llm.close()
|
|
||||||
|
|
||||||
# Singleton Helper
|
|
||||||
_analyzer_instance = None
|
|
||||||
def get_semantic_analyzer():
|
|
||||||
global _analyzer_instance
|
|
||||||
if _analyzer_instance is None:
|
|
||||||
_analyzer_instance = SemanticAnalyzer()
|
|
||||||
return _analyzer_instance
|
|
||||||
+114
-125
@@ -1,145 +1,134 @@
|
|||||||
# config/decision_engine.yaml
|
# config/decision_engine.yaml
|
||||||
# Steuerung der Decision Engine (Intent Recognition & Graph Routing)
|
# VERSION: 3.2.2 (WP-25a: Decoupled MoE Logic)
|
||||||
# Version: 2.5.0 (WP-22: Semantic Graph Routing)
|
# STATUS: Active
|
||||||
|
# DESCRIPTION: Zentrale Orchestrierung der Multi-Stream-Engine.
|
||||||
|
# FIX:
|
||||||
|
# - Auslagerung der LLM-Profile in llm_profiles.yaml zur zentralen Wartbarkeit.
|
||||||
|
# - Integration von compression_thresholds zur Inhaltsverdichtung (WP-25a).
|
||||||
|
# - 100% Erhalt aller WP-25 Edge-Boosts und Filter-Typen (v3.1.6).
|
||||||
|
|
||||||
version: 2.5
|
version: 3.2
|
||||||
|
|
||||||
settings:
|
settings:
|
||||||
llm_fallback_enabled: true
|
llm_fallback_enabled: true
|
||||||
|
# "auto" nutzt den globalen Default-Provider aus der .env
|
||||||
|
router_provider: "auto"
|
||||||
|
# Verweis auf den Intent-Klassifizierer in der prompts.yaml
|
||||||
|
router_prompt_key: "intent_router_v1"
|
||||||
|
# Pfad zur neuen Experten-Konfiguration (WP-25a Architektur-Cleanliness)
|
||||||
|
profiles_config_path: "config/llm_profiles.yaml"
|
||||||
|
router_profile: "compression_fast"
|
||||||
|
|
||||||
# Few-Shot Prompting für den LLM-Router (Slow Path)
|
# --- EBENE 1: STREAM-LIBRARY (Bausteine basierend auf types.yaml v2.7.0) ---
|
||||||
llm_router_prompt: |
|
streams_library:
|
||||||
Du bist ein Klassifikator. Analysiere die Nachricht und wähle die passende Strategie.
|
values_stream:
|
||||||
Antworte NUR mit dem Namen der Strategie.
|
name: "Identität & Ethik"
|
||||||
|
# Referenz auf Experten-Profil (z.B. lokal via Ollama für Privacy)
|
||||||
|
llm_profile: "identity_safe"
|
||||||
|
compression_profile: "identity_safe"
|
||||||
|
compression_threshold: 2500
|
||||||
|
query_template: "Welche meiner Werte und Prinzipien betreffen: {query}"
|
||||||
|
filter_types: ["value", "principle", "belief", "trait", "boundary", "need", "motivation"]
|
||||||
|
top_k: 5
|
||||||
|
edge_boosts:
|
||||||
|
guides: 3.0
|
||||||
|
enforced_by: 2.5
|
||||||
|
based_on: 2.0
|
||||||
|
|
||||||
STRATEGIEN:
|
facts_stream:
|
||||||
- INTERVIEW: User will Wissen erfassen, Notizen anlegen oder Dinge festhalten.
|
name: "Operative Realität"
|
||||||
- DECISION: Rat, Strategie, Vor/Nachteile, "Soll ich".
|
llm_profile: "synthesis_pro"
|
||||||
- EMPATHY: Gefühle, Frust, Freude, Probleme.
|
compression_profile: "compression_fast"
|
||||||
- CODING: Code, Syntax, Programmierung.
|
compression_threshold: 3500
|
||||||
- FACT: Wissen, Fakten, Definitionen.
|
query_template: "Status, Ressourcen und Fakten zu: {query}"
|
||||||
|
filter_types: ["project", "decision", "task", "goal", "event", "state"]
|
||||||
BEISPIELE:
|
top_k: 5
|
||||||
User: "Wie funktioniert Qdrant?" -> FACT
|
|
||||||
User: "Soll ich Qdrant nutzen?" -> DECISION
|
|
||||||
User: "Ich möchte etwas notieren" -> INTERVIEW
|
|
||||||
User: "Lass uns das festhalten" -> INTERVIEW
|
|
||||||
User: "Schreibe ein Python Script" -> CODING
|
|
||||||
User: "Alles ist grau und sinnlos" -> EMPATHY
|
|
||||||
|
|
||||||
NACHRICHT: "{query}"
|
|
||||||
|
|
||||||
STRATEGIE:
|
|
||||||
|
|
||||||
strategies:
|
|
||||||
# 1. Fakten-Abfrage (Fallback & Default)
|
|
||||||
FACT:
|
|
||||||
description: "Reine Wissensabfrage."
|
|
||||||
trigger_keywords: []
|
|
||||||
inject_types: []
|
|
||||||
# WP-22: Definitionen & Hierarchien bevorzugen
|
|
||||||
edge_boosts:
|
edge_boosts:
|
||||||
part_of: 2.0
|
part_of: 2.0
|
||||||
composed_of: 2.0
|
depends_on: 1.5
|
||||||
similar_to: 1.5
|
implemented_in: 1.5
|
||||||
caused_by: 0.5
|
|
||||||
prompt_template: "rag_template"
|
|
||||||
prepend_instruction: null
|
|
||||||
|
|
||||||
# 2. Entscheidungs-Frage
|
biography_stream:
|
||||||
DECISION:
|
name: "Persönliche Erfahrung"
|
||||||
description: "Der User sucht Rat, Strategie oder Abwägung."
|
llm_profile: "synthesis_pro"
|
||||||
trigger_keywords:
|
compression_profile: "compression_fast"
|
||||||
- "soll ich"
|
compression_threshold: 3000
|
||||||
- "meinung"
|
query_template: "Welche Erlebnisse habe ich im Kontext von {query} gemacht?"
|
||||||
- "besser"
|
filter_types: ["experience", "journal", "profile", "person"]
|
||||||
- "empfehlung"
|
top_k: 3
|
||||||
- "strategie"
|
edge_boosts:
|
||||||
- "entscheidung"
|
related_to: 1.5
|
||||||
- "abwägung"
|
experienced_in: 2.0
|
||||||
- "vergleich"
|
expert_for: 2.5
|
||||||
inject_types: ["value", "principle", "goal", "risk"]
|
|
||||||
# WP-22: Risiken und Konsequenzen hervorheben
|
risk_stream:
|
||||||
|
name: "Risiko-Radar"
|
||||||
|
llm_profile: "synthesis_pro"
|
||||||
|
compression_profile: "compression_fast"
|
||||||
|
compression_threshold: 2500
|
||||||
|
query_template: "Gefahren, Hindernisse oder Risiken bei: {query}"
|
||||||
|
filter_types: ["risk", "obstacle", "bias"]
|
||||||
|
top_k: 3
|
||||||
edge_boosts:
|
edge_boosts:
|
||||||
blocks: 2.5
|
blocks: 2.5
|
||||||
solves: 2.0
|
impacts: 2.0
|
||||||
depends_on: 1.5
|
|
||||||
risk_of: 2.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
|
tech_stream:
|
||||||
EMPATHY:
|
name: "Wissen & Technik"
|
||||||
description: "Reaktion auf emotionale Zustände."
|
llm_profile: "tech_expert"
|
||||||
trigger_keywords:
|
compression_profile: "compression_fast"
|
||||||
- "ich fühle"
|
compression_threshold: 4500
|
||||||
- "traurig"
|
query_template: "Inhaltliche Details und Definitionen zu: {query}"
|
||||||
- "glücklich"
|
filter_types: ["concept", "source", "glossary", "idea", "insight", "skill", "habit"]
|
||||||
- "gestresst"
|
top_k: 5
|
||||||
- "angst"
|
|
||||||
- "nervt"
|
|
||||||
- "überfordert"
|
|
||||||
- "müde"
|
|
||||||
inject_types: ["experience", "belief", "profile"]
|
|
||||||
# WP-22: Weiche Assoziationen & Erfahrungen stärken
|
|
||||||
edge_boosts:
|
|
||||||
based_on: 2.0
|
|
||||||
related_to: 2.0
|
|
||||||
experienced_in: 2.5
|
|
||||||
blocks: 0.1
|
|
||||||
prompt_template: "empathy_template"
|
|
||||||
prepend_instruction: null
|
|
||||||
|
|
||||||
# 4. Coding / Technical
|
|
||||||
CODING:
|
|
||||||
description: "Technische Anfragen und Programmierung."
|
|
||||||
trigger_keywords:
|
|
||||||
- "code"
|
|
||||||
- "python"
|
|
||||||
- "script"
|
|
||||||
- "funktion"
|
|
||||||
- "bug"
|
|
||||||
- "syntax"
|
|
||||||
- "json"
|
|
||||||
- "yaml"
|
|
||||||
- "bash"
|
|
||||||
inject_types: ["snippet", "reference", "source"]
|
|
||||||
# WP-22: Technische Abhängigkeiten
|
|
||||||
edge_boosts:
|
edge_boosts:
|
||||||
uses: 2.5
|
uses: 2.5
|
||||||
depends_on: 2.0
|
|
||||||
implemented_in: 3.0
|
implemented_in: 3.0
|
||||||
prompt_template: "technical_template"
|
|
||||||
prepend_instruction: null
|
|
||||||
|
|
||||||
# 5. Interview / Datenerfassung
|
# --- EBENE 2: STRATEGIEN (Finale Komposition via MoE-Profile) ---
|
||||||
# HINWEIS: Spezifische Typen (Projekt, Ziel etc.) werden automatisch
|
strategies:
|
||||||
# über die types.yaml erkannt. Hier stehen nur generische Trigger.
|
FACT_WHEN:
|
||||||
|
description: "Abfrage von exakten Zeitpunkten und Terminen."
|
||||||
|
llm_profile: "synthesis_pro"
|
||||||
|
trigger_keywords: ["wann", "datum", "uhrzeit", "zeitpunkt"]
|
||||||
|
use_streams: ["facts_stream", "biography_stream", "tech_stream"]
|
||||||
|
prompt_template: "fact_synthesis_v1"
|
||||||
|
|
||||||
|
FACT_WHAT:
|
||||||
|
description: "Abfrage von Definitionen, Listen und Inhalten."
|
||||||
|
llm_profile: "synthesis_pro"
|
||||||
|
trigger_keywords: ["was ist", "welche sind", "liste", "übersicht", "zusammenfassung"]
|
||||||
|
use_streams: ["facts_stream", "tech_stream", "biography_stream"]
|
||||||
|
prompt_template: "fact_synthesis_v1"
|
||||||
|
|
||||||
|
DECISION:
|
||||||
|
description: "Der User sucht Rat, Strategie oder Abwägung."
|
||||||
|
llm_profile: "synthesis_pro"
|
||||||
|
trigger_keywords: ["soll ich", "sollte ich", "entscheidung", "abwägen", "priorität", "empfehlung"]
|
||||||
|
use_streams: ["values_stream", "facts_stream", "risk_stream"]
|
||||||
|
prompt_template: "decision_synthesis_v1"
|
||||||
|
prepend_instruction: |
|
||||||
|
!!! ENTSCHEIDUNGS-MODUS (AGENTIC MULTI-STREAM) !!!
|
||||||
|
Analysiere die Fakten vor dem Hintergrund meiner Werte und evaluiere die Risiken.
|
||||||
|
Wäge ab, ob das Vorhaben mit meiner langfristigen Identität kompatibel ist.
|
||||||
|
|
||||||
|
EMPATHY:
|
||||||
|
description: "Reaktion auf emotionale Zustände."
|
||||||
|
llm_profile: "synthesis_pro"
|
||||||
|
trigger_keywords: ["fühle", "traurig", "glücklich", "stress", "angst"]
|
||||||
|
use_streams: ["biography_stream", "values_stream"]
|
||||||
|
prompt_template: "empathy_template"
|
||||||
|
|
||||||
|
CODING:
|
||||||
|
description: "Technische Anfragen und Programmierung."
|
||||||
|
llm_profile: "tech_expert"
|
||||||
|
trigger_keywords: ["code", "python", "script", "bug", "syntax"]
|
||||||
|
use_streams: ["tech_stream", "facts_stream"]
|
||||||
|
prompt_template: "technical_template"
|
||||||
|
|
||||||
INTERVIEW:
|
INTERVIEW:
|
||||||
description: "Der User möchte Wissen erfassen."
|
description: "Der User möchte Wissen erfassen (Eingabemodus)."
|
||||||
trigger_keywords:
|
llm_profile: "compression_fast"
|
||||||
- "neue notiz"
|
use_streams: []
|
||||||
- "etwas notieren"
|
|
||||||
- "festhalten"
|
|
||||||
- "erstellen"
|
|
||||||
- "dokumentieren"
|
|
||||||
- "anlegen"
|
|
||||||
- "interview"
|
|
||||||
- "erfassen"
|
|
||||||
- "idee speichern"
|
|
||||||
- "draft"
|
|
||||||
inject_types: []
|
|
||||||
edge_boosts: {}
|
|
||||||
prompt_template: "interview_template"
|
prompt_template: "interview_template"
|
||||||
prepend_instruction: null
|
|
||||||
# Schemas: Hier nur der Fallback.
|
|
||||||
# Spezifische Schemas (Project, Experience) kommen jetzt aus types.yaml!
|
|
||||||
schemas:
|
|
||||||
default:
|
|
||||||
fields:
|
|
||||||
- "Titel"
|
|
||||||
- "Thema/Inhalt"
|
|
||||||
- "Tags"
|
|
||||||
hint: "Halte es einfach und übersichtlich."
|
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
# config/llm_profiles.yaml
|
||||||
|
# VERSION: 1.3.0 (WP-25a: Global MoE & Fallback Cascade)
|
||||||
|
# STATUS: Active
|
||||||
|
# DESCRIPTION: Zentrale Definition der LLM-Rollen inkl. Ausfall-Logik (Kaskade).
|
||||||
|
|
||||||
|
profiles:
|
||||||
|
# --- CHAT & SYNTHESE ---
|
||||||
|
# Der "Architekt": Hochwertige Synthese. Fällt bei Fehlern auf den Backup-Cloud-Experten zurück.
|
||||||
|
synthesis_pro:
|
||||||
|
provider: "openrouter"
|
||||||
|
model: "google/gemini-2.0-flash-exp:free"
|
||||||
|
temperature: 0.7
|
||||||
|
fallback_profile: "synthesis_backup"
|
||||||
|
|
||||||
|
# Der "Vize": Leistungsstarkes Modell bei einem anderen Provider (Resilienz).
|
||||||
|
synthesis_backup:
|
||||||
|
provider: "openrouter"
|
||||||
|
model: "meta-llama/llama-3.3-70b-instruct:free"
|
||||||
|
temperature: 0.5
|
||||||
|
fallback_profile: "identity_safe" # Letzte Instanz: Lokal
|
||||||
|
|
||||||
|
# Der "Ingenieur": Fachspezialist für Code. Nutzt bei Ausfall den Generalisten.
|
||||||
|
tech_expert:
|
||||||
|
provider: "openrouter"
|
||||||
|
model: "qwen/qwen-2.5-vl-7b-instruct:free"
|
||||||
|
temperature: 0.3
|
||||||
|
fallback_profile: "synthesis_pro"
|
||||||
|
|
||||||
|
# Der "Dampfhammer": Schnell für Routing und Zusammenfassungen.
|
||||||
|
compression_fast:
|
||||||
|
provider: "openrouter"
|
||||||
|
model: "mistralai/mistral-7b-instruct:free"
|
||||||
|
temperature: 0.1
|
||||||
|
fallback_profile: "identity_safe"
|
||||||
|
|
||||||
|
# --- INGESTION EXPERTEN ---
|
||||||
|
# Spezialist für die Extraktion komplexer Datenstrukturen aus Dokumenten.
|
||||||
|
ingest_extractor:
|
||||||
|
provider: "openrouter"
|
||||||
|
model: "mistralai/mistral-7b-instruct:free"
|
||||||
|
temperature: 0.2
|
||||||
|
fallback_profile: "synthesis_backup"
|
||||||
|
|
||||||
|
# Spezialist für binäre Prüfungen (YES/NO). Muss extrem deterministisch sein.
|
||||||
|
ingest_validator:
|
||||||
|
provider: "openrouter"
|
||||||
|
model: "mistralai/mistral-7b-instruct:free"
|
||||||
|
temperature: 0.0
|
||||||
|
fallback_profile: "compression_fast"
|
||||||
|
|
||||||
|
# --- LOKALER ANKER & PRIVACY ---
|
||||||
|
# Der "Wächter": Lokales Modell für maximale Privatsphäre. Ende der Kaskade.
|
||||||
|
identity_safe:
|
||||||
|
provider: "ollama"
|
||||||
|
model: "phi3:mini"
|
||||||
|
temperature: 0.2
|
||||||
|
# Kein fallback_profile definiert = Terminaler Endpunkt
|
||||||
|
|
||||||
|
# --- EMBEDDING EXPERTE ---
|
||||||
|
# Zentralisierung des Embedding-Modells zur Entfernung aus der .env.
|
||||||
|
embedding_expert:
|
||||||
|
provider: "ollama"
|
||||||
|
model: "nomic-embed-text"
|
||||||
|
dimensions: 768
|
||||||
@@ -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
|
||||||
@@ -0,0 +1,337 @@
|
|||||||
|
# config/prompts.yaml — VERSION 3.1.2 (WP-25 Cleanup: Multi-Stream Sync)
|
||||||
|
# STATUS: Active
|
||||||
|
# FIX:
|
||||||
|
# - 100% Wiederherstellung der Ingest- & Validierungslogik (Sektion 5-8).
|
||||||
|
# - Überführung der Kategorien 1-4 in die Multi-Stream Struktur unter Beibehaltung des Inhalts.
|
||||||
|
# - Konsolidierung: Sektion 9 (v3.0.0) wurde in Sektion 1 & 2 integriert (keine Redundanz).
|
||||||
|
|
||||||
|
system_prompt: |
|
||||||
|
Du bist 'mindnet', mein digitaler Zwilling und strategischer Partner.
|
||||||
|
|
||||||
|
DEINE IDENTITÄT:
|
||||||
|
- Du bist nicht nur eine Datenbank, sondern handelst nach MEINEN Werten und Zielen.
|
||||||
|
- Du passt deinen Stil dynamisch an die Situation an (Analytisch, Empathisch oder Technisch).
|
||||||
|
|
||||||
|
DEINE REGELN:
|
||||||
|
1. Deine Antwort muss zu 100% auf dem bereitgestellten KONTEXT basieren.
|
||||||
|
2. Halluziniere keine Fakten, die nicht in den Quellen stehen.
|
||||||
|
3. Antworte auf Deutsch (außer bei Code/Fachbegriffen).
|
||||||
|
|
||||||
|
# ---------------------------------------------------------
|
||||||
|
# 1. STANDARD: Fakten & Wissen (Intent: FACT_WHAT / FACT_WHEN)
|
||||||
|
# ---------------------------------------------------------
|
||||||
|
# Ersetzt das alte 'rag_template'. Nutzt jetzt parallele Streams.
|
||||||
|
fact_synthesis_v1:
|
||||||
|
ollama: |
|
||||||
|
WISSENS-STREAMS:
|
||||||
|
=========================================
|
||||||
|
FAKTEN & STATUS:
|
||||||
|
{facts_stream}
|
||||||
|
|
||||||
|
ERFAHRUNG & BIOGRAFIE:
|
||||||
|
{biography_stream}
|
||||||
|
|
||||||
|
WISSEN & TECHNIK:
|
||||||
|
{tech_stream}
|
||||||
|
=========================================
|
||||||
|
|
||||||
|
FRAGE:
|
||||||
|
{query}
|
||||||
|
|
||||||
|
ANWEISUNG:
|
||||||
|
Beantworte die Frage präzise basierend auf den Quellen.
|
||||||
|
Kombiniere harte Fakten mit persönlichen Erfahrungen, falls vorhanden.
|
||||||
|
Fasse die Informationen zusammen. Sei objektiv und neutral.
|
||||||
|
gemini: |
|
||||||
|
Beantworte die Wissensabfrage "{query}" basierend auf diesen Streams:
|
||||||
|
FAKTEN: {facts_stream}
|
||||||
|
BIOGRAFIE/ERFAHRUNG: {biography_stream}
|
||||||
|
TECHNIK: {tech_stream}
|
||||||
|
Kombiniere harte Fakten mit persönlichen Erfahrungen, falls vorhanden. Antworte strukturiert und präzise.
|
||||||
|
openrouter: |
|
||||||
|
Synthese der Wissens-Streams für: {query}
|
||||||
|
Inhalt: {facts_stream} | {biography_stream} | {tech_stream}
|
||||||
|
Antworte basierend auf dem bereitgestellten Kontext.
|
||||||
|
|
||||||
|
# ---------------------------------------------------------
|
||||||
|
# 2. DECISION: Strategie & Abwägung (Intent: DECISION)
|
||||||
|
# ---------------------------------------------------------
|
||||||
|
# Ersetzt das alte 'decision_template'. Nutzt jetzt parallele Streams.
|
||||||
|
decision_synthesis_v1:
|
||||||
|
ollama: |
|
||||||
|
ENTSCHEIDUNGS-STREAMS:
|
||||||
|
=========================================
|
||||||
|
WERTE & PRINZIPIEN (Identität):
|
||||||
|
{values_stream}
|
||||||
|
|
||||||
|
OPERATIVE FAKTEN (Realität):
|
||||||
|
{facts_stream}
|
||||||
|
|
||||||
|
RISIKO-RADAR (Konsequenzen):
|
||||||
|
{risk_stream}
|
||||||
|
=========================================
|
||||||
|
|
||||||
|
ENTSCHEIDUNGSFRAGE:
|
||||||
|
{query}
|
||||||
|
|
||||||
|
ANWEISUNG:
|
||||||
|
Du agierst als mein Entscheidungs-Partner.
|
||||||
|
1. Analysiere die Faktenlage aus den Quellen.
|
||||||
|
2. Prüfe dies hart gegen meine strategischen Notizen (Werte & Prinzipien).
|
||||||
|
3. Wäge ab: Passt die technische/faktische Lösung zu meinen Werten?
|
||||||
|
|
||||||
|
FORMAT:
|
||||||
|
- **Analyse:** (Kurze Zusammenfassung der Fakten)
|
||||||
|
- **Abgleich:** (Gibt es Konflikte mit Werten/Zielen? Nenne die Quelle!)
|
||||||
|
- **Empfehlung:** (Klare Meinung: Ja/No/Vielleicht mit Begründung)
|
||||||
|
gemini: |
|
||||||
|
Agiere als mein strategischer Partner. Analysiere die Frage: {query}
|
||||||
|
Werte: {values_stream} | Fakten: {facts_stream} | Risiken: {risk_stream}.
|
||||||
|
Wäge ab und gib eine klare strategische Empfehlung ab.
|
||||||
|
openrouter: |
|
||||||
|
Strategische Multi-Stream Analyse für: {query}
|
||||||
|
Werte-Basis: {values_stream} | Fakten: {facts_stream} | Risiken: {risk_stream}
|
||||||
|
Bitte wäge ab und gib eine Empfehlung.
|
||||||
|
|
||||||
|
# ---------------------------------------------------------
|
||||||
|
# 3. EMPATHY: Der Spiegel / "Ich"-Modus (Intent: EMPATHY)
|
||||||
|
# ---------------------------------------------------------
|
||||||
|
empathy_template:
|
||||||
|
ollama: |
|
||||||
|
KONTEXT (ERFAHRUNGEN & WERTE):
|
||||||
|
=========================================
|
||||||
|
ERLEBNISSE & BIOGRAFIE:
|
||||||
|
{biography_stream}
|
||||||
|
|
||||||
|
WERTE & BEDÜRFNISSE:
|
||||||
|
{values_stream}
|
||||||
|
=========================================
|
||||||
|
|
||||||
|
SITUATION:
|
||||||
|
{query}
|
||||||
|
|
||||||
|
ANWEISUNG:
|
||||||
|
Du agierst jetzt als mein empathischer Spiegel.
|
||||||
|
1. Versuche nicht sofort, das Problem technisch zu lösen.
|
||||||
|
2. Zeige Verständnis für die Situation basierend auf meinen eigenen Erfahrungen ([EXPERIENCE]) oder Werten, falls im Kontext vorhanden.
|
||||||
|
3. Antworte in der "Ich"-Form oder "Wir"-Form. Sei unterstützend.
|
||||||
|
|
||||||
|
TONFALL:
|
||||||
|
Ruhig, verständnisvoll, reflektiert. Keine Aufzählungszeichen, sondern fließender Text.
|
||||||
|
gemini: "Sei mein digitaler Spiegel für {query}. Kontext: {biography_stream}, {values_stream}"
|
||||||
|
openrouter: "Empathische Reflexion der Situation {query}. Persönlicher Kontext: {biography_stream}, {values_stream}"
|
||||||
|
|
||||||
|
# ---------------------------------------------------------
|
||||||
|
# 4. TECHNICAL: Der Coder (Intent: CODING)
|
||||||
|
# ---------------------------------------------------------
|
||||||
|
technical_template:
|
||||||
|
ollama: |
|
||||||
|
KONTEXT (WISSEN & PROJEKTE):
|
||||||
|
=========================================
|
||||||
|
TECHNIK & SNIPPETS:
|
||||||
|
{tech_stream}
|
||||||
|
|
||||||
|
PROJEKT-STATUS:
|
||||||
|
{facts_stream}
|
||||||
|
=========================================
|
||||||
|
|
||||||
|
TASK:
|
||||||
|
{query}
|
||||||
|
|
||||||
|
ANWEISUNG:
|
||||||
|
Du bist Senior Developer.
|
||||||
|
1. Ignoriere Smalltalk. Komm sofort zum Punkt.
|
||||||
|
2. Generiere validen, performanten Code basierend auf den Quellen.
|
||||||
|
3. Wenn Quellen fehlen, nutze dein allgemeines Programmierwissen, aber weise darauf hin.
|
||||||
|
|
||||||
|
FORMAT:
|
||||||
|
- Kurze Erklärung des Ansatzes.
|
||||||
|
- Markdown Code-Block (Copy-Paste fertig).
|
||||||
|
- Wichtige Edge-Cases.
|
||||||
|
gemini: "Generiere Code für {query} unter Berücksichtigung von {tech_stream} und {facts_stream}."
|
||||||
|
openrouter: "Technischer Support für {query}. Referenzen: {tech_stream}, Projekt-Kontext: {facts_stream}"
|
||||||
|
|
||||||
|
# ---------------------------------------------------------
|
||||||
|
# 5. INTERVIEW: Der "One-Shot Extractor" (WP-07)
|
||||||
|
# ---------------------------------------------------------
|
||||||
|
interview_template:
|
||||||
|
ollama: |
|
||||||
|
TASK:
|
||||||
|
Du bist ein professioneller Ghostwriter. Verwandle den "USER INPUT" in eine strukturierte Notiz vom Typ '{target_type}'.
|
||||||
|
|
||||||
|
STRUKTUR (Nutze EXAKT diese Überschriften):
|
||||||
|
{schema_fields}
|
||||||
|
|
||||||
|
USER INPUT:
|
||||||
|
"{query}"
|
||||||
|
|
||||||
|
ANWEISUNG ZUM INHALT:
|
||||||
|
1. Analysiere den Input genau.
|
||||||
|
2. Schreibe die Inhalte unter die passenden Überschriften aus der STRUKTUR-Liste oben.
|
||||||
|
3. STIL: Schreibe flüssig, professionell und in der Ich-Perspektive. Korrigiere Grammatikfehler, aber behalte den persönlichen Ton bei.
|
||||||
|
4. Wenn Informationen für einen Abschnitt fehlen, schreibe nur: "[TODO: Ergänzen]". Erfinde nichts dazu.
|
||||||
|
|
||||||
|
OUTPUT FORMAT (YAML + MARKDOWN):
|
||||||
|
---
|
||||||
|
type: {target_type}
|
||||||
|
status: draft
|
||||||
|
title: (Erstelle einen treffenden, kurzen Titel für den Inhalt)
|
||||||
|
tags: [Tag1, Tag2]
|
||||||
|
---
|
||||||
|
|
||||||
|
# (Wiederhole den Titel hier)
|
||||||
|
|
||||||
|
## (Erster Begriff aus STRUKTUR)
|
||||||
|
(Text...)
|
||||||
|
|
||||||
|
## (Zweiter Begriff aus STRUKTUR)
|
||||||
|
(Text...)
|
||||||
|
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 (Ingest)
|
||||||
|
# ---------------------------------------------------------
|
||||||
|
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 (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:
|
||||||
|
|
||||||
|
# ---------------------------------------------------------
|
||||||
|
# 8. WP-15b: EDGE VALIDATION (Ingest/Validate)
|
||||||
|
# ---------------------------------------------------------
|
||||||
|
edge_validation:
|
||||||
|
gemini: |
|
||||||
|
Bewerte die semantische Validität dieser Verbindung im Wissensgraph.
|
||||||
|
|
||||||
|
KONTEXT DER QUELLE (Chunk):
|
||||||
|
"{chunk_text}"
|
||||||
|
|
||||||
|
ZIEL-NOTIZ: "{target_title}"
|
||||||
|
ZIEL-BESCHREIBUNG (Zusammenfassung):
|
||||||
|
"{target_summary}"
|
||||||
|
|
||||||
|
GEPLANTE RELATION: "{edge_kind}"
|
||||||
|
|
||||||
|
FRAGE: Bestätigt der Kontext der Quelle die Beziehung '{edge_kind}' zum Ziel?
|
||||||
|
REGEL: Antworte NUR mit 'YES' oder 'NO'. Keine Erklärungen oder Smalltalk.
|
||||||
|
openrouter: |
|
||||||
|
Verify semantic relation for graph construction.
|
||||||
|
Source Context: {chunk_text}
|
||||||
|
Target Note: {target_title}
|
||||||
|
Target Summary: {target_summary}
|
||||||
|
Proposed Relation: {edge_kind}
|
||||||
|
Instruction: Does the source context support this relation to the target?
|
||||||
|
Result: Respond ONLY with 'YES' or 'NO'.
|
||||||
|
ollama: |
|
||||||
|
Bewerte die semantische Korrektheit dieser Verbindung.
|
||||||
|
QUELLE: {chunk_text}
|
||||||
|
ZIEL: {target_title} ({target_summary})
|
||||||
|
BEZIEHUNG: {edge_kind}
|
||||||
|
Ist diese Verbindung valide? Antworte NUR mit YES oder NO.
|
||||||
|
|
||||||
|
# ---------------------------------------------------------
|
||||||
|
# 10. WP-25: INTENT ROUTING (Intent: CLASSIFY)
|
||||||
|
# ---------------------------------------------------------
|
||||||
|
intent_router_v1:
|
||||||
|
ollama: |
|
||||||
|
Analysiere die Nutzeranfrage und wähle die passende Strategie.
|
||||||
|
Antworte NUR mit dem Namen der Strategie.
|
||||||
|
|
||||||
|
STRATEGIEN:
|
||||||
|
- FACT_WHEN: Nur für explizite Fragen nach einem exakten Datum, Uhrzeit oder dem "Wann" eines Ereignisses.
|
||||||
|
- FACT_WHAT: Fragen nach Inhalten, Listen von Objekten/Projekten, Definitionen oder "Was/Welche" Anfragen (auch bei Zeiträumen).
|
||||||
|
- DECISION: Rat, Meinung, "Soll ich?", Abwägung gegen Werte.
|
||||||
|
- EMPATHY: Emotionen, Reflexion, Befindlichkeit.
|
||||||
|
- CODING: Programmierung, Skripte, technische Syntax.
|
||||||
|
- INTERVIEW: Dokumentation neuer Informationen, Notizen anlegen.
|
||||||
|
|
||||||
|
NACHRICHT: "{query}"
|
||||||
|
STRATEGIE:
|
||||||
|
gemini: |
|
||||||
|
Classify intent:
|
||||||
|
- FACT_WHEN: Exact dates/times only.
|
||||||
|
- FACT_WHAT: Content, lists of entities (projects, etc.), definitions, "What/Which" queries.
|
||||||
|
- DECISION: Strategic advice/values.
|
||||||
|
- EMPATHY: Emotions.
|
||||||
|
- CODING: Tech/Code.
|
||||||
|
- INTERVIEW: Data entry.
|
||||||
|
Query: "{query}"
|
||||||
|
Result (One word only):
|
||||||
|
openrouter: |
|
||||||
|
Select strategy for Mindnet:
|
||||||
|
FACT_WHEN (timing/dates), FACT_WHAT (entities/lists/what/which), DECISION, EMPATHY, CODING, INTERVIEW.
|
||||||
|
Query: "{query}"
|
||||||
|
Response:
|
||||||
+403
-112
@@ -1,4 +1,9 @@
|
|||||||
# config/prompts.yaml — Final V2.3.1 (Multi-Personality Support)
|
# config/prompts.yaml — VERSION 3.2.2 (WP-25b: Hierarchical Model Sync)
|
||||||
|
# STATUS: Active
|
||||||
|
# FIX:
|
||||||
|
# - 100% Erhalt der Original-Prompts aus v3.1.2 für die Provider-Ebene (ollama, gemini, openrouter).
|
||||||
|
# - Integration der Modell-spezifischen Overrides für Gemini 2.0, Llama 3.3 und Qwen 2.5.
|
||||||
|
# - Hinzufügen des notwendigen 'compression_template' für die DecisionEngine v1.3.0.
|
||||||
|
|
||||||
system_prompt: |
|
system_prompt: |
|
||||||
Du bist 'mindnet', mein digitaler Zwilling und strategischer Partner.
|
Du bist 'mindnet', mein digitaler Zwilling und strategischer Partner.
|
||||||
@@ -13,150 +18,436 @@ system_prompt: |
|
|||||||
3. Antworte auf Deutsch (außer bei Code/Fachbegriffen).
|
3. Antworte auf Deutsch (außer bei Code/Fachbegriffen).
|
||||||
|
|
||||||
# ---------------------------------------------------------
|
# ---------------------------------------------------------
|
||||||
# 1. STANDARD: Fakten & Wissen (Intent: FACT)
|
# 1. STANDARD: Fakten & Wissen (Intent: FACT_WHAT / FACT_WHEN)
|
||||||
# ---------------------------------------------------------
|
# ---------------------------------------------------------
|
||||||
rag_template: |
|
fact_synthesis_v1:
|
||||||
QUELLEN (WISSEN):
|
# --- Modell-spezifisch (WP-25b Optimierung) ---
|
||||||
=========================================
|
"google/gemini-2.0-flash-exp:free": |
|
||||||
{context_str}
|
Analysiere die Wissens-Streams für: {query}
|
||||||
=========================================
|
FAKTEN: {facts_stream} | BIOGRAFIE: {biography_stream} | TECHNIK: {tech_stream}
|
||||||
|
Nutze deine hohe Reasoning-Kapazität für eine tiefe Synthese. Antworte präzise auf Deutsch.
|
||||||
|
|
||||||
FRAGE:
|
"meta-llama/llama-3.3-70b-instruct:free": |
|
||||||
{query}
|
Erstelle eine fundierte Synthese für die Frage: "{query}"
|
||||||
|
Nutze die Daten: {facts_stream}, {biography_stream} und {tech_stream}.
|
||||||
|
Trenne klare Fakten von Erfahrungen. Bleibe strikt beim bereitgestellten Kontext.
|
||||||
|
|
||||||
ANWEISUNG:
|
# --- EXAKTE Provider-Fallbacks aus v3.1.2 ---
|
||||||
Beantworte die Frage präzise basierend auf den Quellen.
|
ollama: |
|
||||||
Fasse die Informationen zusammen. Sei objektiv und neutral.
|
WISSENS-STREAMS:
|
||||||
|
=========================================
|
||||||
|
FAKTEN & STATUS:
|
||||||
|
{facts_stream}
|
||||||
|
|
||||||
|
ERFAHRUNG & BIOGRAFIE:
|
||||||
|
{biography_stream}
|
||||||
|
|
||||||
|
WISSEN & TECHNIK:
|
||||||
|
{tech_stream}
|
||||||
|
=========================================
|
||||||
|
|
||||||
|
FRAGE:
|
||||||
|
{query}
|
||||||
|
|
||||||
|
ANWEISUNG:
|
||||||
|
Beantworte die Frage präzise basierend auf den Quellen.
|
||||||
|
Kombiniere harte Fakten mit persönlichen Erfahrungen, falls vorhanden.
|
||||||
|
Fasse die Informationen zusammen. Sei objektiv und neutral.
|
||||||
|
|
||||||
|
gemini: |
|
||||||
|
Beantworte die Wissensabfrage "{query}" basierend auf diesen Streams:
|
||||||
|
FAKTEN: {facts_stream}
|
||||||
|
BIOGRAFIE/ERFAHRUNG: {biography_stream}
|
||||||
|
TECHNIK: {tech_stream}
|
||||||
|
Kombiniere harte Fakten mit persönlichen Erfahrungen, falls vorhanden. Antworte strukturiert und präzise.
|
||||||
|
|
||||||
|
openrouter: |
|
||||||
|
Synthese der Wissens-Streams für: {query}
|
||||||
|
Inhalt: {facts_stream} | {biography_stream} | {tech_stream}
|
||||||
|
Antworte basierend auf dem bereitgestellten Kontext.
|
||||||
|
|
||||||
|
default: "Beantworte {query} basierend auf dem Kontext: {facts_stream} {biography_stream} {tech_stream}."
|
||||||
|
|
||||||
# ---------------------------------------------------------
|
# ---------------------------------------------------------
|
||||||
# 2. DECISION: Strategie & Abwägung (Intent: DECISION)
|
# 2. DECISION: Strategie & Abwägung (Intent: DECISION)
|
||||||
# ---------------------------------------------------------
|
# ---------------------------------------------------------
|
||||||
decision_template: |
|
decision_synthesis_v1:
|
||||||
KONTEXT (FAKTEN & STRATEGIE):
|
# --- Modell-spezifisch (WP-25b Optimierung) ---
|
||||||
=========================================
|
"google/gemini-2.0-flash-exp:free": |
|
||||||
{context_str}
|
Agiere als strategischer Partner für: {query}
|
||||||
=========================================
|
WERTE: {values_stream} | FAKTEN: {facts_stream} | RISIKEN: {risk_stream}
|
||||||
|
Prüfe die Fakten gegen meine Werte. Zeige Zielkonflikte auf. Gib eine klare Empfehlung.
|
||||||
|
|
||||||
ENTSCHEIDUNGSFRAGE:
|
# --- EXAKTE Provider-Fallbacks aus v3.1.2 ---
|
||||||
{query}
|
ollama: |
|
||||||
|
ENTSCHEIDUNGS-STREAMS:
|
||||||
|
=========================================
|
||||||
|
WERTE & PRINZIPIEN (Identität):
|
||||||
|
{values_stream}
|
||||||
|
|
||||||
ANWEISUNG:
|
OPERATIVE FAKTEN (Realität):
|
||||||
Du agierst als mein Entscheidungs-Partner.
|
{facts_stream}
|
||||||
1. Analysiere die Faktenlage aus den Quellen.
|
|
||||||
2. Prüfe dies hart gegen meine strategischen Notizen (Typ [VALUE], [PRINCIPLE], [GOAL]).
|
|
||||||
3. Wäge ab: Passt die technische/faktische Lösung zu meinen Werten?
|
|
||||||
|
|
||||||
FORMAT:
|
RISIKO-RADAR (Konsequenzen):
|
||||||
- **Analyse:** (Kurze Zusammenfassung der Fakten)
|
{risk_stream}
|
||||||
- **Abgleich:** (Gibt es Konflikte mit Werten/Zielen? Nenne die Quelle!)
|
=========================================
|
||||||
- **Empfehlung:** (Klare Meinung: Ja/Nein/Vielleicht mit Begründung)
|
|
||||||
|
ENTSCHEIDUNGSFRAGE:
|
||||||
|
{query}
|
||||||
|
|
||||||
|
ANWEISUNG:
|
||||||
|
Du agierst als mein Entscheidungs-Partner.
|
||||||
|
1. Analysiere die Faktenlage aus den Quellen.
|
||||||
|
2. Prüfe dies hart gegen meine strategischen Notizen (Werte & Prinzipien).
|
||||||
|
3. Wäge ab: Passt die technische/faktische Lösung zu meinen Werten?
|
||||||
|
|
||||||
|
FORMAT:
|
||||||
|
- **Analyse:** (Kurze Zusammenfassung der Fakten)
|
||||||
|
- **Abgleich:** (Gibt es Konflikte mit Werten/Zielen? Nenne die Quelle!)
|
||||||
|
- **Empfehlung:** (Klare Meinung: Ja/No/Vielleicht mit Begründung)
|
||||||
|
|
||||||
|
gemini: |
|
||||||
|
Agiere als mein strategischer Partner. Analysiere die Frage: {query}
|
||||||
|
Werte: {values_stream} | Fakten: {facts_stream} | Risiken: {risk_stream}.
|
||||||
|
Wäge ab und gib eine klare strategische Empfehlung ab.
|
||||||
|
|
||||||
|
openrouter: |
|
||||||
|
Strategische Multi-Stream Analyse für: {query}
|
||||||
|
Werte-Basis: {values_stream} | Fakten: {facts_stream} | Risiken: {risk_stream}
|
||||||
|
Bitte wäge ab und gib eine Empfehlung.
|
||||||
|
|
||||||
|
default: "Prüfe {query} gegen Werte {values_stream} und Fakten {facts_stream}."
|
||||||
|
|
||||||
# ---------------------------------------------------------
|
# ---------------------------------------------------------
|
||||||
# 3. EMPATHY: Der Spiegel / "Ich"-Modus (Intent: EMPATHY)
|
# 3. EMPATHY: Der Spiegel / "Ich"-Modus (Intent: EMPATHY)
|
||||||
# ---------------------------------------------------------
|
# ---------------------------------------------------------
|
||||||
empathy_template: |
|
empathy_template:
|
||||||
KONTEXT (ERFAHRUNGEN & GLAUBENSSÄTZE):
|
# --- EXAKTE Provider-Fallbacks aus v3.1.2 ---
|
||||||
=========================================
|
ollama: |
|
||||||
{context_str}
|
KONTEXT (ERFAHRUNGEN & WERTE):
|
||||||
=========================================
|
=========================================
|
||||||
|
ERLEBNISSE & BIOGRAFIE:
|
||||||
|
{biography_stream}
|
||||||
|
|
||||||
SITUATION:
|
WERTE & BEDÜRFNISSE:
|
||||||
{query}
|
{values_stream}
|
||||||
|
=========================================
|
||||||
|
|
||||||
ANWEISUNG:
|
SITUATION:
|
||||||
Du agierst jetzt als mein empathischer Spiegel.
|
{query}
|
||||||
1. Versuche nicht sofort, das Problem technisch zu lösen.
|
|
||||||
2. Zeige Verständnis für die Situation basierend auf meinen eigenen Erfahrungen ([EXPERIENCE]) oder Glaubenssätzen ([BELIEF]), falls im Kontext vorhanden.
|
|
||||||
3. Antworte in der "Ich"-Form oder "Wir"-Form. Sei unterstützend.
|
|
||||||
|
|
||||||
TONFALL:
|
ANWEISUNG:
|
||||||
Ruhig, verständnisvoll, reflektiert. Keine Aufzählungszeichen, sondern fließender Text.
|
Du agierst jetzt als mein empathischer Spiegel.
|
||||||
|
1. Versuche nicht sofort, das Problem technisch zu lösen.
|
||||||
|
2. Zeige Verständnis für die Situation basierend auf meinen eigenen Erfahrungen ([EXPERIENCE]) oder Werten, falls im Kontext vorhanden.
|
||||||
|
3. Antworte in der "Ich"-Form oder "Wir"-Form. Sei unterstützend.
|
||||||
|
|
||||||
|
TONFALL:
|
||||||
|
Ruhig, verständnisvoll, reflektiert. Keine Aufzählungszeichen, sondern fließender Text.
|
||||||
|
|
||||||
|
gemini: "Sei mein digitaler Spiegel für {query}. Kontext: {biography_stream}, {values_stream}"
|
||||||
|
openrouter: "Empathische Reflexion der Situation {query}. Persönlicher Kontext: {biography_stream}, {values_stream}"
|
||||||
|
|
||||||
|
default: "Reflektiere empathisch über {query} basierend auf {biography_stream}."
|
||||||
|
|
||||||
# ---------------------------------------------------------
|
# ---------------------------------------------------------
|
||||||
# 4. TECHNICAL: Der Coder (Intent: CODING)
|
# 4. TECHNICAL: Der Coder (Intent: CODING)
|
||||||
# ---------------------------------------------------------
|
# ---------------------------------------------------------
|
||||||
technical_template: |
|
technical_template:
|
||||||
KONTEXT (DOCS & SNIPPETS):
|
# --- Modell-spezifisch (WP-25b Optimierung) ---
|
||||||
=========================================
|
"qwen/qwen-2.5-vl-7b-instruct:free": |
|
||||||
{context_str}
|
Du bist Senior Software Engineer. TASK: {query}
|
||||||
=========================================
|
REFERENZEN: {tech_stream} | KONTEXT: {facts_stream}
|
||||||
|
Generiere validen, performanten Code. Nutze die Snippets aus dem Kontext.
|
||||||
|
|
||||||
TASK:
|
# --- EXAKTE Provider-Fallbacks aus v3.1.2 ---
|
||||||
{query}
|
ollama: |
|
||||||
|
KONTEXT (WISSEN & PROJEKTE):
|
||||||
|
=========================================
|
||||||
|
TECHNIK & SNIPPETS:
|
||||||
|
{tech_stream}
|
||||||
|
|
||||||
ANWEISUNG:
|
PROJEKT-STATUS:
|
||||||
Du bist Senior Developer.
|
{facts_stream}
|
||||||
1. Ignoriere Smalltalk. Komm sofort zum Punkt.
|
=========================================
|
||||||
2. Generiere validen, performanten Code basierend auf den Quellen.
|
|
||||||
3. Wenn Quellen fehlen, nutze dein allgemeines Programmierwissen, aber weise darauf hin.
|
|
||||||
|
|
||||||
FORMAT:
|
TASK:
|
||||||
- Kurze Erklärung des Ansatzes.
|
{query}
|
||||||
- Markdown Code-Block (Copy-Paste fertig).
|
|
||||||
- Wichtige Edge-Cases.
|
|
||||||
# ---------------------------------------------------------
|
|
||||||
# 5. INTERVIEW: Der "One-Shot Extractor" (Performance Mode)
|
|
||||||
# ---------------------------------------------------------
|
|
||||||
interview_template: |
|
|
||||||
TASK:
|
|
||||||
Du bist ein professioneller Ghostwriter. Verwandle den "USER INPUT" in eine strukturierte Notiz vom Typ '{target_type}'.
|
|
||||||
|
|
||||||
STRUKTUR (Nutze EXAKT diese Überschriften):
|
ANWEISUNG:
|
||||||
{schema_fields}
|
Du bist Senior Developer.
|
||||||
|
1. Ignoriere Smalltalk. Komm sofort zum Punkt.
|
||||||
|
2. Generiere validen, performanten Code basierend auf den Quellen.
|
||||||
|
3. Wenn Quellen fehlen, nutze dein allgemeines Programmierwissen, aber weise darauf hin.
|
||||||
|
|
||||||
USER INPUT:
|
FORMAT:
|
||||||
"{query}"
|
- Kurze Erklärung des Ansatzes.
|
||||||
|
- Markdown Code-Block (Copy-Paste fertig).
|
||||||
|
- Wichtige Edge-Cases.
|
||||||
|
|
||||||
ANWEISUNG ZUM INHALT:
|
gemini: "Generiere Code für {query} unter Berücksichtigung von {tech_stream} und {facts_stream}."
|
||||||
1. Analysiere den Input genau.
|
openrouter: "Technischer Support für {query}. Referenzen: {tech_stream}, Projekt-Kontext: {facts_stream}"
|
||||||
2. Schreibe die Inhalte unter die passenden Überschriften aus der STRUKTUR-Liste oben.
|
|
||||||
3. STIL: Schreibe flüssig, professionell und in der Ich-Perspektive. Korrigiere Grammatikfehler, aber behalte den persönlichen Ton bei.
|
|
||||||
4. Wenn Informationen für einen Abschnitt fehlen, schreibe nur: "[TODO: Ergänzen]". Erfinde nichts dazu.
|
|
||||||
|
|
||||||
OUTPUT FORMAT (YAML + MARKDOWN):
|
|
||||||
---
|
|
||||||
type: {target_type}
|
|
||||||
status: draft
|
|
||||||
title: (Erstelle einen treffenden, kurzen Titel für den Inhalt)
|
|
||||||
tags: [Tag1, Tag2]
|
|
||||||
---
|
|
||||||
|
|
||||||
# (Wiederhole den Titel hier)
|
|
||||||
|
|
||||||
## (Erster Begriff aus STRUKTUR)
|
|
||||||
(Text...)
|
|
||||||
|
|
||||||
## (Zweiter Begriff aus STRUKTUR)
|
|
||||||
(Text...)
|
|
||||||
|
|
||||||
(usw.)
|
|
||||||
|
|
||||||
|
default: "Erstelle eine technische Lösung für {query}."
|
||||||
|
|
||||||
# ---------------------------------------------------------
|
# ---------------------------------------------------------
|
||||||
# 6. EDGE_ALLOCATION: Kantenfilter (Intent: OFFLINE_FILTER)
|
# 5. INTERVIEW: Der "One-Shot Extractor" (WP-07)
|
||||||
# ---------------------------------------------------------
|
# ---------------------------------------------------------
|
||||||
edge_allocation_template: |
|
interview_template:
|
||||||
TASK:
|
# --- EXAKTE Provider-Fallbacks aus v3.1.2 ---
|
||||||
Du bist ein strikter Selektor. Du erhältst eine Liste von "Kandidaten-Kanten" (Strings).
|
ollama: |
|
||||||
Wähle jene aus, die inhaltlich im "Textabschnitt" vorkommen oder relevant sind.
|
TASK:
|
||||||
|
Du bist ein professioneller Ghostwriter. Verwandle den "USER INPUT" in eine strukturierte Notiz vom Typ '{target_type}'.
|
||||||
|
|
||||||
TEXTABSCHNITT:
|
STRUKTUR (Nutze EXAKT diese Überschriften):
|
||||||
"""
|
{schema_fields}
|
||||||
{chunk_text}
|
|
||||||
"""
|
|
||||||
|
|
||||||
KANDIDATEN (Auswahl-Pool):
|
USER INPUT:
|
||||||
{edge_list}
|
"{query}"
|
||||||
|
|
||||||
REGELN:
|
ANWEISUNG ZUM INHALT:
|
||||||
1. Die Kanten haben das Format "typ:ziel". Der "typ" ist variabel und kann ALLES sein (z.B. uses, blocks, inspired_by, loves, etc.).
|
1. Analysiere den Input genau.
|
||||||
2. Gib NUR die Strings aus der Kandidaten-Liste zurück, die zum Text passen.
|
2. Schreibe die Inhalte unter die passenden Überschriften aus der STRUKTUR-Liste oben.
|
||||||
3. Erfinde KEINE neuen Kanten. Nutze exakt die Schreibweise aus der Liste.
|
3. STIL: Schreibe flüssig, professionell und in der Ich-Perspektive. Korrigiere Grammatikfehler, aber behalte den persönlichen Ton bei.
|
||||||
4. Antworte als flache JSON-Liste.
|
4. Wenn Informationen für einen Abschnitt fehlen, schreibe nur: "[TODO: Ergänzen]". Erfinde nichts dazu.
|
||||||
|
|
||||||
BEISPIEL (Zur Demonstration der Logik):
|
OUTPUT FORMAT (YAML + MARKDOWN):
|
||||||
Input Text: "Das Projekt Alpha scheitert, weil Budget fehlt."
|
---
|
||||||
Input Kandidaten: ["blocks:Projekt Alpha", "inspired_by:Buch der Weisen", "needs:Budget"]
|
type: {target_type}
|
||||||
Output: ["blocks:Projekt Alpha", "needs:Budget"]
|
status: draft
|
||||||
|
title: (Erstelle einen treffenden, kurzen Titel für den Inhalt)
|
||||||
|
tags: [Tag1, Tag2]
|
||||||
|
---
|
||||||
|
|
||||||
DEIN OUTPUT (JSON):
|
# (Wiederhole den Titel 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}."
|
||||||
|
|
||||||
|
default: "Extrahiere Informationen für {target_type} aus dem Input: {query}"
|
||||||
|
|
||||||
|
# ---------------------------------------------------------
|
||||||
|
# 6. WP-25b: PRE-SYNTHESIS COMPRESSION (Neu!)
|
||||||
|
# ---------------------------------------------------------
|
||||||
|
compression_template:
|
||||||
|
"mistralai/mistral-7b-instruct:free": |
|
||||||
|
Reduziere den Stream '{stream_name}' auf die Informationen, die für die Beantwortung der Frage '{query}' absolut notwendig sind.
|
||||||
|
BEHALTE: Harte Fakten, Projektnamen, konkrete Werte und Quellenangaben.
|
||||||
|
ENTFERNE: Redundante Einleitungen, Füllwörter und irrelevante Details.
|
||||||
|
|
||||||
|
INHALT:
|
||||||
|
{content}
|
||||||
|
|
||||||
|
KOMPRIMIERTE ANALYSE:
|
||||||
|
|
||||||
|
default: "Fasse das Wichtigste aus {stream_name} für die Frage {query} kurz zusammen: {content}"
|
||||||
|
|
||||||
|
# ---------------------------------------------------------
|
||||||
|
# 7. EDGE_ALLOCATION: Kantenfilter (Ingest)
|
||||||
|
# ---------------------------------------------------------
|
||||||
|
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:
|
||||||
|
|
||||||
|
default: "[]"
|
||||||
|
|
||||||
|
# ---------------------------------------------------------
|
||||||
|
# 8. SMART EDGE ALLOCATION: Extraktion (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:
|
||||||
|
|
||||||
|
default: "[]"
|
||||||
|
|
||||||
|
# ---------------------------------------------------------
|
||||||
|
# 9. INGESTION: EDGE VALIDATION (Ingest/Validate)
|
||||||
|
# ---------------------------------------------------------
|
||||||
|
edge_validation:
|
||||||
|
# --- Modell-spezifisch (WP-25b Optimierung) ---
|
||||||
|
"mistralai/mistral-7b-instruct:free": |
|
||||||
|
Verify relation '{edge_kind}' for graph integrity.
|
||||||
|
Chunk: "{chunk_text}"
|
||||||
|
Target: "{target_title}" ({target_summary})
|
||||||
|
Respond ONLY with 'YES' or 'NO'.
|
||||||
|
|
||||||
|
# --- EXAKTE Provider-Fallbacks aus v3.1.2 ---
|
||||||
|
gemini: |
|
||||||
|
Bewerte die semantische Validität dieser Verbindung im Wissensgraph.
|
||||||
|
|
||||||
|
KONTEXT DER QUELLE (Chunk):
|
||||||
|
"{chunk_text}"
|
||||||
|
|
||||||
|
ZIEL-NOTIZ: "{target_title}"
|
||||||
|
ZIEL-BESCHREIBUNG (Zusammenfassung):
|
||||||
|
"{target_summary}"
|
||||||
|
|
||||||
|
GEPLANTE RELATION: "{edge_kind}"
|
||||||
|
|
||||||
|
FRAGE: Bestätigt der Kontext der Quelle die Beziehung '{edge_kind}' zum Ziel?
|
||||||
|
REGEL: Antworte NUR mit 'YES' oder 'NO'. Keine Erklärungen oder Smalltalk.
|
||||||
|
|
||||||
|
openrouter: |
|
||||||
|
Verify semantic relation for graph construction.
|
||||||
|
Source Context: {chunk_text}
|
||||||
|
Target Note: {target_title}
|
||||||
|
Target Summary: {target_summary}
|
||||||
|
Proposed Relation: {edge_kind}
|
||||||
|
Instruction: Does the source context support this relation to the target?
|
||||||
|
Result: Respond ONLY with 'YES' or 'NO'.
|
||||||
|
|
||||||
|
ollama: |
|
||||||
|
Bewerte die semantische Korrektheit dieser Verbindung.
|
||||||
|
QUELLE: {chunk_text}
|
||||||
|
ZIEL: {target_title} ({target_summary})
|
||||||
|
BEZIEHUNG: {edge_kind}
|
||||||
|
Ist diese Verbindung valide? Antworte NUR mit YES oder NO.
|
||||||
|
|
||||||
|
default: "YES"
|
||||||
|
|
||||||
|
# ---------------------------------------------------------
|
||||||
|
# 10. WP-25: INTENT ROUTING (Intent: CLASSIFY)
|
||||||
|
# ---------------------------------------------------------
|
||||||
|
intent_router_v1:
|
||||||
|
# --- Modell-spezifisch (WP-25b Optimierung) ---
|
||||||
|
"mistralai/mistral-7b-instruct:free": |
|
||||||
|
Classify query "{query}" into exactly one of these categories:
|
||||||
|
FACT_WHEN, FACT_WHAT, DECISION, EMPATHY, CODING, INTERVIEW.
|
||||||
|
Respond with the category name only.
|
||||||
|
|
||||||
|
# --- EXAKTE Provider-Fallbacks aus v3.1.2 ---
|
||||||
|
ollama: |
|
||||||
|
Analysiere die Nutzeranfrage und wähle die passende Strategie.
|
||||||
|
Antworte NUR mit dem Namen der Strategie.
|
||||||
|
|
||||||
|
STRATEGIEN:
|
||||||
|
- FACT_WHEN: Nur für explizite Fragen nach einem exakten Datum, Uhrzeit oder dem "Wann" eines Ereignisses.
|
||||||
|
- FACT_WHAT: Fragen nach Inhalten, Listen von Objekten/Projekten, Definitionen oder "Was/Welche" Anfragen (auch bei Zeiträumen).
|
||||||
|
- DECISION: Rat, Meinung, "Soll ich?", Abwägung gegen Werte.
|
||||||
|
- EMPATHY: Emotionen, Reflexion, Befindlichkeit.
|
||||||
|
- CODING: Programmierung, Skripte, technische Syntax.
|
||||||
|
- INTERVIEW: Dokumentation neuer Informationen, Notizen anlegen.
|
||||||
|
|
||||||
|
NACHRICHT: "{query}"
|
||||||
|
STRATEGIE:
|
||||||
|
|
||||||
|
gemini: |
|
||||||
|
Classify intent:
|
||||||
|
- FACT_WHEN: Exact dates/times only.
|
||||||
|
- FACT_WHAT: Content, lists of entities (projects, etc.), definitions, "What/Which" queries.
|
||||||
|
- DECISION: Strategic advice/values.
|
||||||
|
- EMPATHY: Emotions.
|
||||||
|
- CODING: Tech/Code.
|
||||||
|
- INTERVIEW: Data entry.
|
||||||
|
Query: "{query}"
|
||||||
|
Result (One word only):
|
||||||
|
|
||||||
|
openrouter: |
|
||||||
|
Select strategy for Mindnet:
|
||||||
|
FACT_WHEN (timing/dates), FACT_WHAT (entities/lists/what/which), DECISION, EMPATHY, CODING, INTERVIEW.
|
||||||
|
Query: "{query}"
|
||||||
|
Response:
|
||||||
|
|
||||||
|
default: "FACT_WHAT"
|
||||||
|
|
||||||
|
# ---------------------------------------------------------
|
||||||
|
# 11. WP-25b: FALLBACK SYNTHESIS (Error Recovery)
|
||||||
|
# ---------------------------------------------------------
|
||||||
|
fallback_synthesis:
|
||||||
|
ollama: |
|
||||||
|
Beantworte die folgende Frage basierend auf dem bereitgestellten Kontext.
|
||||||
|
|
||||||
|
FRAGE:
|
||||||
|
{query}
|
||||||
|
|
||||||
|
KONTEXT:
|
||||||
|
{context}
|
||||||
|
|
||||||
|
ANWEISUNG:
|
||||||
|
Nutze den Kontext, um eine präzise Antwort zu geben. Falls der Kontext unvollständig ist, weise darauf hin.
|
||||||
|
|
||||||
|
gemini: |
|
||||||
|
Frage: {query}
|
||||||
|
Kontext: {context}
|
||||||
|
Antworte basierend auf dem Kontext.
|
||||||
|
|
||||||
|
openrouter: |
|
||||||
|
Answer the question "{query}" using the provided context: {context}
|
||||||
|
|
||||||
|
default: "Answer: {query}\n\nContext: {context}"
|
||||||
+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.
|
||||||
+153
-18
@@ -1,4 +1,4 @@
|
|||||||
version: 2.6.0 # Final WP-15 Config: Smart Edges & Strict/Soft Chunking
|
version: 2.7.0 # WP-14 Update: Dynamisierung der Ingestion-Pipeline
|
||||||
|
|
||||||
# ==============================================================================
|
# ==============================================================================
|
||||||
# 1. CHUNKING PROFILES
|
# 1. CHUNKING PROFILES
|
||||||
@@ -76,40 +76,73 @@ defaults:
|
|||||||
edge_defaults: []
|
edge_defaults: []
|
||||||
|
|
||||||
# ==============================================================================
|
# ==============================================================================
|
||||||
# 3. TYPE DEFINITIONS
|
# 3. INGESTION SETTINGS (WP-14 Dynamization)
|
||||||
|
# ==============================================================================
|
||||||
|
# Steuert, welche Notizen verarbeitet werden und wie Fallbacks aussehen.
|
||||||
|
ingestion_settings:
|
||||||
|
# Liste der Status-Werte, die beim Import ignoriert werden sollen.
|
||||||
|
ignore_statuses: ["system", "template", "archive", "hidden"]
|
||||||
|
# Standard-Typ, falls kein Typ im Frontmatter angegeben ist.
|
||||||
|
default_note_type: "concept"
|
||||||
|
|
||||||
|
# ==============================================================================
|
||||||
|
# 4. SUMMARY & SCAN SETTINGS
|
||||||
|
# ==============================================================================
|
||||||
|
# Steuert die Tiefe des Pre-Scans für den Context-Cache.
|
||||||
|
summary_settings:
|
||||||
|
max_summary_length: 500
|
||||||
|
pre_scan_depth: 600
|
||||||
|
|
||||||
|
# ==============================================================================
|
||||||
|
# 5. LLM SETTINGS
|
||||||
|
# ==============================================================================
|
||||||
|
# Steuerzeichen und Patterns zur Bereinigung der LLM-Antworten.
|
||||||
|
llm_settings:
|
||||||
|
cleanup_patterns: ["<s>", "</s>", "[OUT]", "[/OUT]", "```json", "```"]
|
||||||
|
|
||||||
|
# ==============================================================================
|
||||||
|
# 6. TYPE DEFINITIONS
|
||||||
# ==============================================================================
|
# ==============================================================================
|
||||||
|
|
||||||
types:
|
types:
|
||||||
|
|
||||||
# --- KERNTYPEN ---
|
|
||||||
|
|
||||||
experience:
|
experience:
|
||||||
chunking_profile: sliding_smart_edges
|
chunking_profile: sliding_smart_edges
|
||||||
retriever_weight: 0.90
|
retriever_weight: 1.10 # Erhöht für biografische Relevanz
|
||||||
edge_defaults: ["derived_from", "references"]
|
edge_defaults: ["derived_from", "references"]
|
||||||
detection_keywords: ["passiert", "erlebt", "gefühl", "situation", "reaktion"]
|
detection_keywords: ["erleben", "reagieren", "handeln", "prägen", "reflektieren"]
|
||||||
schema:
|
schema:
|
||||||
- "Situation (Was ist passiert?)"
|
- "Situation (Was ist passiert?)"
|
||||||
- "Meine Reaktion (Was habe ich getan?)"
|
- "Meine Reaktion (Was habe ich getan?)"
|
||||||
- "Ergebnis & Auswirkung"
|
- "Ergebnis & Auswirkung"
|
||||||
- "Reflexion & Learning (Was lerne ich daraus?)"
|
- "Reflexion & Learning (Was lerne ich daraus?)"
|
||||||
|
|
||||||
|
insight:
|
||||||
|
chunking_profile: sliding_smart_edges
|
||||||
|
retriever_weight: 1.20 # Hoch gewichtet für aktuelle Steuerung
|
||||||
|
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"
|
||||||
|
|
||||||
project:
|
project:
|
||||||
chunking_profile: sliding_smart_edges
|
chunking_profile: sliding_smart_edges
|
||||||
retriever_weight: 0.97
|
retriever_weight: 0.97
|
||||||
edge_defaults: ["references", "depends_on"]
|
edge_defaults: ["references", "depends_on"]
|
||||||
detection_keywords: ["projekt", "vorhaben", "ziel ist", "planen", "starten"]
|
detection_keywords: ["umsetzen", "planen", "starten", "bauen", "abschließen"]
|
||||||
schema:
|
schema:
|
||||||
- "Mission & Zielsetzung"
|
- "Mission & Zielsetzung"
|
||||||
- "Aktueller Status & Blockaden"
|
- "Aktueller Status & Blockaden"
|
||||||
- "Nächste konkrete Schritte"
|
- "Nächste konkrete Schritte"
|
||||||
|
|
||||||
decision:
|
decision:
|
||||||
# Strict, damit jede Entscheidung atomar bleibt
|
|
||||||
chunking_profile: structured_smart_edges_strict
|
chunking_profile: structured_smart_edges_strict
|
||||||
retriever_weight: 1.00
|
retriever_weight: 1.00
|
||||||
edge_defaults: ["caused_by", "references"]
|
edge_defaults: ["caused_by", "references"]
|
||||||
detection_keywords: ["entschieden", "wahl", "optionen", "alternativen", "adr"]
|
detection_keywords: ["entscheiden", "wählen", "abwägen", "priorisieren", "festlegen"]
|
||||||
schema:
|
schema:
|
||||||
- "Kontext & Problemstellung"
|
- "Kontext & Problemstellung"
|
||||||
- "Betrachtete Optionen"
|
- "Betrachtete Optionen"
|
||||||
@@ -119,34 +152,136 @@ types:
|
|||||||
# --- PERSÖNLICHKEIT & IDENTITÄT ---
|
# --- PERSÖNLICHKEIT & IDENTITÄT ---
|
||||||
|
|
||||||
value:
|
value:
|
||||||
# Strict, damit Werte nicht verschwimmen
|
|
||||||
chunking_profile: structured_smart_edges_strict
|
chunking_profile: structured_smart_edges_strict
|
||||||
retriever_weight: 1.00
|
retriever_weight: 1.00
|
||||||
edge_defaults: ["related_to"]
|
edge_defaults: ["related_to"]
|
||||||
detection_keywords: ["wert", "wichtig ist", "moral", "ethik"]
|
detection_keywords: ["werten", "achten", "verpflichten", "bedeuten"]
|
||||||
schema: ["Definition", "Warum mir das wichtig ist", "Leitsätze"]
|
schema:
|
||||||
|
- "Definition"
|
||||||
|
- "Warum mir das wichtig ist"
|
||||||
|
- "Leitsätze"
|
||||||
|
|
||||||
principle:
|
principle:
|
||||||
# L3 Strict für P3/P3a und Tier2/MP1 Logik
|
|
||||||
chunking_profile: structured_smart_edges_strict_L3
|
chunking_profile: structured_smart_edges_strict_L3
|
||||||
retriever_weight: 0.95
|
retriever_weight: 0.95
|
||||||
edge_defaults: ["derived_from", "references"]
|
edge_defaults: ["derived_from", "references"]
|
||||||
detection_keywords: ["prinzip", "regel", "grundsatz", "leitlinie"]
|
detection_keywords: ["leiten", "steuern", "ausrichten", "handhaben"]
|
||||||
schema: ["Das Prinzip", "Anwendung & Beispiele"]
|
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:
|
belief:
|
||||||
chunking_profile: sliding_short
|
chunking_profile: sliding_short
|
||||||
retriever_weight: 0.90
|
retriever_weight: 0.90
|
||||||
edge_defaults: ["related_to"]
|
edge_defaults: ["related_to"]
|
||||||
schema: ["Der Glaubenssatz", "Ursprung & Reflexion"]
|
detection_keywords: ["glauben", "meinen", "annehmen", "überzeugen"]
|
||||||
|
schema:
|
||||||
|
- "Der Glaubenssatz"
|
||||||
|
- "Ursprung & Reflexion"
|
||||||
|
|
||||||
profile:
|
profile:
|
||||||
# Strict: Jede Rolle (H2) muss ein eigener Chunk sein
|
|
||||||
chunking_profile: structured_smart_edges_strict
|
chunking_profile: structured_smart_edges_strict
|
||||||
retriever_weight: 0.70
|
retriever_weight: 0.70
|
||||||
edge_defaults: ["references", "related_to"]
|
edge_defaults: ["references", "related_to"]
|
||||||
schema: ["Rolle / Identität", "Fakten & Daten", "Historie"]
|
detection_keywords: ["verkörpern", "verantworten", "agieren", "repräsentieren"]
|
||||||
|
schema:
|
||||||
|
- "Rolle / Identität"
|
||||||
|
- "Fakten & Daten"
|
||||||
|
- "Historie"
|
||||||
|
|
||||||
|
|
||||||
|
idea:
|
||||||
|
chunking_profile: sliding_short
|
||||||
|
retriever_weight: 0.70
|
||||||
|
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 ---
|
# --- STRATEGIE & RISIKO ---
|
||||||
|
|
||||||
goal:
|
goal:
|
||||||
|
|||||||
@@ -18,9 +18,12 @@ Das Repository ist in **logische Domänen** unterteilt.
|
|||||||
*Zielgruppe: Alle*
|
*Zielgruppe: Alle*
|
||||||
| Datei | Inhalt & Zweck |
|
| Datei | Inhalt & Zweck |
|
||||||
| :--- | :--- |
|
| :--- | :--- |
|
||||||
|
| `README.md` | **Einstiegspunkt.** Übersicht über die Dokumentationsstruktur, Schnellzugriff nach Rollen und Navigation. |
|
||||||
|
| `00_quickstart.md` | **Schnellstart.** Installation und erste Schritte in 15 Minuten. Ideal für neue Benutzer. |
|
||||||
| `00_vision_and_strategy.md` | **Strategie.** Warum bauen wir das? Prinzipien (Privacy, Local-First), High-Level Architektur. |
|
| `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_glossary.md` | **Definitionen.** Was bedeutet "Smart Edge", "Traffic Control", "Chunk"? Verhindert Begriffsverwirrung. |
|
||||||
| `00_documentation_map.md` | **Dieser Index.** Navigationshilfe. |
|
| `00_documentation_map.md` | **Dieser Index.** Navigationshilfe. |
|
||||||
|
| `00_quality_checklist.md` | **Qualitätsprüfung.** Systematische Checkliste zur Vollständigkeitsprüfung für alle Rollen. |
|
||||||
|
|
||||||
### 📂 01_User_Manual (Anwendung)
|
### 📂 01_User_Manual (Anwendung)
|
||||||
*Zielgruppe: Mindmaster, Autoren, Power-User*
|
*Zielgruppe: Mindmaster, Autoren, Power-User*
|
||||||
@@ -28,6 +31,8 @@ Das Repository ist in **logische Domänen** unterteilt.
|
|||||||
| :--- | :--- |
|
| :--- | :--- |
|
||||||
| `01_chat_usage_guide.md` | **Bedienung.** Wie steuere ich die Personas (Berater, Spiegel)? Wie nutze ich das Feedback? |
|
| `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_knowledge_design.md` | **Content-Regeln.** Die "Bibel" für den Vault. Erklärt Note-Typen, Matrix-Logik und Markdown-Syntax. |
|
||||||
|
| `01_authoring_guidelines.md` | **Content strukturieren.** Primäres Werkzeug, um Wissen so zu strukturieren, dass Mindnet die Persönlichkeit spiegelt, empathisch reagiert und strategisch berät. |
|
||||||
|
| `01_obsidian_integration_guide.md` | **Obsidian Setup.** Technische Anleitung für die Integration von Mindnet mit Obsidian (Templater, Skripte, Workflows). |
|
||||||
|
|
||||||
### 📂 02_Concepts (Fachliche Logik)
|
### 📂 02_Concepts (Fachliche Logik)
|
||||||
*Zielgruppe: Architekten, Product Owner*
|
*Zielgruppe: Architekten, Product Owner*
|
||||||
@@ -35,6 +40,7 @@ Das Repository ist in **logische Domänen** unterteilt.
|
|||||||
| :--- | :--- |
|
| :--- | :--- |
|
||||||
| `02_concept_graph_logic.md` | **Graph-Theorie.** Abstrakte Erklärung von Knoten, Kanten, Provenance und Idempotenz. |
|
| `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". |
|
| `02_concept_ai_personality.md`| **KI-Verhalten.** Konzepte hinter dem Hybrid Router, Empathie-Modell und "Teach-the-AI". |
|
||||||
|
| `02_concept_architecture_patterns.md` | **Architektur-Patterns.** Design-Entscheidungen, modulare Struktur (WP-14), Resilienz-Patterns und Erweiterbarkeit. |
|
||||||
|
|
||||||
### 📂 03_Technical_Reference (Technik & Code)
|
### 📂 03_Technical_Reference (Technik & Code)
|
||||||
*Zielgruppe: Entwickler, DevOps. (Enthält JSON/YAML Beispiele)*
|
*Zielgruppe: Entwickler, DevOps. (Enthält JSON/YAML Beispiele)*
|
||||||
@@ -45,13 +51,16 @@ Das Repository ist in **logische Domänen** unterteilt.
|
|||||||
| `03_tech_retrieval_scoring.md` | **Suche.** Die mathematischen Formeln für Scoring, Hybrid Search und Explanation Layer. |
|
| `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_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_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`. |
|
| `03_tech_configuration.md` | **Config.** Referenztabellen für `.env`, `types.yaml`, `decision_engine.yaml`, `llm_profiles.yaml`, `prompts.yaml`. **Neu:** Verbindungen zwischen Config-Dateien, Praxisbeispiel und Mermaid-Grafik. |
|
||||||
|
| `03_tech_api_reference.md` | **API-Referenz.** Vollständige Dokumentation aller Endpunkte (`/query`, `/chat`, `/ingest`, `/graph`, etc.). |
|
||||||
|
|
||||||
### 📂 04_Operations (Betrieb)
|
### 📂 04_Operations (Betrieb)
|
||||||
*Zielgruppe: Administratoren*
|
*Zielgruppe: Administratoren*
|
||||||
| Datei | Inhalt & Zweck |
|
| Datei | Inhalt & Zweck |
|
||||||
| :--- | :--- |
|
| :--- | :--- |
|
||||||
| `04_admin_operations.md` | **Runbook.** Installation, Docker-Setup, Backup/Restore, Troubleshooting Guide. |
|
| `04_admin_operations.md` | **Runbook.** Installation, Docker-Setup, Backup/Restore, Troubleshooting Guide. |
|
||||||
|
| `04_server_operation_manual.md` | **Server-Betrieb.** Detaillierte Dokumentation für den Betrieb auf llm-node (Systemd, Borgmatic, Disaster Recovery). |
|
||||||
|
| `04_deployment_guide.md` | **Deployment.** CI/CD-Pipelines, Rollout-Strategien, Versionierung, Rollback und Pre/Post-Deployment-Checklisten. |
|
||||||
|
|
||||||
### 📂 05_Development (Code)
|
### 📂 05_Development (Code)
|
||||||
*Zielgruppe: Entwickler*
|
*Zielgruppe: Entwickler*
|
||||||
@@ -59,6 +68,7 @@ Das Repository ist in **logische Domänen** unterteilt.
|
|||||||
| :--- | :--- |
|
| :--- | :--- |
|
||||||
| `05_developer_guide.md` | **Workflow.** Hardware-Setup (Win/Pi/Beelink), Git-Flow, Test-Befehle, Modul-Interna. |
|
| `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. |
|
| `05_genai_best_practices.md` | **AI Workflow.** Prompt-Library, Templates und Best Practices für die Entwicklung mit LLMs. |
|
||||||
|
| `05_testing_guide.md` | **Testing.** Umfassender Test-Guide: Strategien, Frameworks, Test-Daten, Best Practices. |
|
||||||
|
|
||||||
### 📂 06_Roadmap & 99_Archive
|
### 📂 06_Roadmap & 99_Archive
|
||||||
*Zielgruppe: Projektleitung*
|
*Zielgruppe: Projektleitung*
|
||||||
@@ -81,7 +91,9 @@ Nutze diese Matrix, wenn du ein Workpackage bearbeitest, um die Dokumentation ko
|
|||||||
| **Retrieval / Scoring** | `03_tech_retrieval_scoring.md` (Formeln 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) |
|
| **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) |
|
| **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` |
|
| **Architektur / Design-Patterns** | 1. `02_concept_architecture_patterns.md` (Patterns & Entscheidungen)<br>2. `02_concept_graph_logic.md` (Graph-Theorie)<br>3. `05_developer_guide.md` (Modulare Struktur) |
|
||||||
|
| **Deployment / Server** | 1. `04_deployment_guide.md` (CI/CD, Rollout)<br>2. `04_admin_operations.md` (Installation, Wartung)<br>3. `04_server_operation_manual.md` (Server-Betrieb) |
|
||||||
|
| **Testing / QA** | 1. `05_testing_guide.md` (Test-Strategien & Frameworks)<br>2. `05_developer_guide.md` (Test-Befehle) |
|
||||||
| **Neuen Features (Allg.)**| `06_active_roadmap.md` (Status Update) |
|
| **Neuen Features (Allg.)**| `06_active_roadmap.md` (Status Update) |
|
||||||
|
|
||||||
---
|
---
|
||||||
@@ -110,3 +122,37 @@ Damit dieses System wartbar bleibt (auch für KI-Agenten wie NotebookLM), gelten
|
|||||||
context: "Beschreibung der Scoring-Formel."
|
context: "Beschreibung der Scoring-Formel."
|
||||||
---
|
---
|
||||||
```
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Schnellzugriff & Empfehlungen
|
||||||
|
|
||||||
|
### Für neue Benutzer
|
||||||
|
1. Starte mit **[Schnellstart](00_quickstart.md)** für die Installation
|
||||||
|
2. Lese **[Vision & Strategie](00_vision_and_strategy.md)** für das große Bild
|
||||||
|
3. Nutze **[Chat Usage Guide](../01_User_Manual/01_chat_usage_guide.md)** für die ersten Schritte
|
||||||
|
|
||||||
|
### Für Entwickler
|
||||||
|
1. **[Developer Guide](../05_Development/05_developer_guide.md)** - Umfassender technischer Guide
|
||||||
|
2. **[Technical References](../03_Technical_References/)** - Detaillierte API- und Architektur-Dokumentation
|
||||||
|
3. **[GenAI Best Practices](../05_Development/05_genai_best_practices.md)** - Workflow mit LLMs
|
||||||
|
|
||||||
|
### Für Administratoren
|
||||||
|
1. **[Admin Operations](../04_Operations/04_admin_operations.md)** - Installation und Wartung
|
||||||
|
2. **[Server Operations Manual](../04_Operations/04_server_operation_manual.md)** - Server-Betrieb und Disaster Recovery
|
||||||
|
3. **[Troubleshooting Guide](../04_Operations/04_admin_operations.md#33-troubleshooting-guide)** - Häufige Probleme und Lösungen
|
||||||
|
|
||||||
|
### Für Autoren
|
||||||
|
1. **[Knowledge Design](../01_User_Manual/01_knowledge_design.md)** - Content-Regeln und Best Practices
|
||||||
|
2. **[Authoring Guidelines](../01_User_Manual/01_authoring_guidelines.md)** - Strukturierung für den Digitalen Zwilling
|
||||||
|
3. **[Obsidian Integration](../01_User_Manual/01_obsidian_integration_guide.md)** - Workflow-Optimierung
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Dokumentations-Status
|
||||||
|
|
||||||
|
**Aktuelle Version:** 3.1.1
|
||||||
|
**Letzte Aktualisierung:** 2026-01-02
|
||||||
|
**Status:** ✅ Vollständig und aktiv gepflegt
|
||||||
|
|
||||||
|
**Hinweis:** Diese Dokumentation wird kontinuierlich aktualisiert. Bei Fragen oder Verbesserungsvorschlägen bitte im Repository melden.
|
||||||
@@ -2,40 +2,66 @@
|
|||||||
doc_type: glossary
|
doc_type: glossary
|
||||||
audience: all
|
audience: all
|
||||||
status: active
|
status: active
|
||||||
version: 2.7.0
|
version: 3.1.1
|
||||||
context: "Zentrales Glossar für Mindnet v2.7. Definitionen von Entitäten, WP-22 Scoring-Konzepten und der Edge Registry."
|
context: "Zentrales Glossar für Mindnet v3.1.1. Enthält Definitionen zu Hybrid-Cloud Resilienz, WP-14 Modularisierung, WP-15b Two-Pass Ingestion, WP-15c Multigraph-Support, WP-25 Agentic Multi-Stream RAG, WP-25a Mixture of Experts (MoE), WP-25b Lazy-Prompt-Orchestration und Mistral-safe Parsing."
|
||||||
---
|
---
|
||||||
|
|
||||||
# Mindnet Glossar
|
# Mindnet Glossar
|
||||||
|
|
||||||
**Quellen:** `01_edge_vocabulary.md`, `retriever_scoring.py`, `edge_registry.py`
|
**Quellen:** `01_edge_vocabulary.md`, `llm_service.py`, `ingestion.py`, `edge_registry.py`, `registry.py`, `qdrant.py`
|
||||||
|
|
||||||
## Kern-Entitäten
|
## Kern-Entitäten
|
||||||
|
|
||||||
* **Note:** Repräsentiert eine Markdown-Datei. Die fachliche Haupteinheit. Verfügt über einen **Status** (stable, draft, system), der das Scoring beeinflusst.
|
* **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).
|
* **Chunk:** Ein Textabschnitt einer Note. Die technische Sucheinheit (Vektor).
|
||||||
* **Edge:** Eine gerichtete Verbindung zwischen zwei Knoten. Wird in WP-22 durch die Registry validiert.
|
* **Edge:** Eine gerichtete Verbindung zwischen zwei Knoten. Wird in WP-22 durch die Registry validiert. Seit v2.9.1 unterstützt Edges **Section-basierte Links** (`target_section`), sodass mehrere Kanten zwischen denselben Knoten existieren können, wenn sie auf verschiedene Abschnitte zeigen.
|
||||||
* **Vault:** Der lokale Ordner mit den Markdown-Dateien (Source of Truth).
|
* **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`).
|
* **Frontmatter:** Der YAML-Header am Anfang einer Notiz (enthält `id`, `type`, `title`, `status`).
|
||||||
|
|
||||||
## Komponenten
|
## 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.
|
* **Edge Registry:** Der zentrale Dienst (SSOT), der Kanten-Typen validiert und Aliase in kanonische Typen auflöst. Nutzt `01_edge_vocabulary.md` als Basis.
|
||||||
* **Retriever:** Besteht in v2.7 aus der Orchestrierung (`retriever.py`) und der mathematischen Scoring-Engine (`retriever_scoring.py`).
|
* **LLM Service:** Der Hybrid-Client (v3.3.6), der Anfragen zwischen OpenRouter, Google Gemini und lokalem Ollama routet. Verwaltet Cloud-Timeouts und Quoten-Management. Nutzt zur Text-Bereinigung nun die neutrale `registry.py`, um Circular Imports zu vermeiden.
|
||||||
* **Decision Engine:** Teil des Routers, der Intents erkennt und entsprechende **Boost-Faktoren** für das Retrieval injiziert.
|
* **Retriever:** Besteht in v2.7+ aus der Orchestrierung (`retriever.py`) und der mathematischen Scoring-Engine (`retriever_scoring.py`). Seit WP-14 im Paket `app.core.retrieval` gekapselt.
|
||||||
* **Traffic Control:** Verwaltet Prioritäten und drosselt Hintergrund-Tasks (z.B. Smart Edges) mittels Semaphoren.
|
* **Decision Engine (WP-25):** Der zentrale **Agentic Orchestrator**, der Intents erkennt, parallele Wissens-Streams orchestriert und die Ergebnisse synthetisiert. Implementiert Multi-Stream Retrieval und Intent-basiertes Routing.
|
||||||
|
* **Agentic Multi-Stream RAG (WP-25):** Architektur-Paradigma, bei dem Nutzeranfragen in parallele, spezialisierte Wissens-Streams aufgeteilt werden (Values, Facts, Biography, Risk, Tech), die gleichzeitig abgefragt und zu einer kontextreichen Antwort synthetisiert werden.
|
||||||
|
* **Stream-Tracing (WP-25):** Kennzeichnung jedes Treffers mit seinem Ursprungs-Stream (`stream_origin`), um Feedback-Optimierung pro Wissensbereich zu ermöglichen.
|
||||||
|
* **Intent-basiertes Routing (WP-25):** Hybrid-Modus zur Intent-Erkennung mit Keyword Fast-Path (sofortige Erkennung von Triggern) und LLM Slow-Path (semantische Analyse für unklare Anfragen).
|
||||||
|
* **Wissens-Synthese (WP-25):** Template-basierte Zusammenführung der Ergebnisse aus parallelen Streams mit expliziten Stream-Variablen (z.B. `{values_stream}`, `{risk_stream}`), um dem LLM eine differenzierte Abwägung zu ermöglichen.
|
||||||
|
* **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.
|
* **Unknown Edges Log:** Die Datei `unknown_edges.jsonl`, in der das System Kanten-Typen protokolliert, die nicht im Dictionary gefunden wurden.
|
||||||
|
* **Database Package (WP-14):** Zentralisiertes Infrastruktur-Paket (`app.core.database`), das den Qdrant-Client (`qdrant.py`) und das Point-Mapping (`qdrant_points.py`) verwaltet.
|
||||||
|
* **LocalBatchCache (WP-15b):** Ein globaler In-Memory-Index, der während des Pass 1 Scans aufgebaut wird und Metadaten (IDs, Titel, Summaries) aller Notizen für die Kantenvalidierung bereithält.
|
||||||
|
|
||||||
## Konzepte & Features
|
## Konzepte & Features
|
||||||
|
|
||||||
* **Canonical Type:** Der standardisierte System-Name einer Kante (z.B. `based_on`), der in der Datenbank gespeichert wird.
|
* **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).
|
||||||
* **Alias (Edge):** Ein nutzerfreundliches Synonym (z.B. `basiert_auf`), das während der Ingestion automatisch zum Canonical Type aufgelöst wird.
|
* **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`).
|
* **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).
|
* **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:
|
* **Provenance Weighting:** Gewichtung einer Kante nach ihrer Herkunft:
|
||||||
* `explicit`: Vom Mensch gesetzt (Prio 1).
|
* `explicit`: Vom Mensch gesetzt (Prio 1).
|
||||||
* `smart`: Von der KI validiert (Prio 2).
|
* `semantic_ai`: Von der KI im Turbo-Mode extrahiert und validiert (Prio 2).
|
||||||
* `rule`: Durch System-Regeln/Matrix erzeugt (Prio 3).
|
* `structure`: Durch System-Regeln/Matrix erzeugt (Prio 3).
|
||||||
* **Smart Edge Allocation:** KI-Verfahren zur Relevanzprüfung von Links für spezifische Textabschnitte.
|
* **Smart Edge Allocation (WP-15b):** KI-Verfahren zur Relevanzprüfung von Links für spezifische Textabschnitte. Validiert Kandidaten semantisch gegen das Ziel im LocalBatchCache.
|
||||||
* **Strict Heading Split:** Chunking-Strategie mit harten Grenzen an Überschriften und integriertem "Safety Net" gegen zu große Chunks.
|
|
||||||
* **Matrix Logic:** Bestimmung des Kanten-Typs basierend auf Quell- und Ziel-Entität (z.B. Erfahrung -> Wert = `based_on`).
|
* **Matrix Logic:** Bestimmung des Kanten-Typs basierend auf Quell- und Ziel-Entität (z.B. Erfahrung -> Wert = `based_on`).
|
||||||
|
* **Two-Pass Workflow (WP-15b):** Optimiertes Ingestion-Verfahren:
|
||||||
|
* **Pass 1 (Pre-Scan):** Schnelles Scannen aller Dateien zur Befüllung des LocalBatchCache.
|
||||||
|
* **Pass 2 (Semantic Processing):** Tiefenverarbeitung (Chunking, Embedding, Validierung) nur für geänderte Dateien.
|
||||||
|
* **Circular Import Registry (WP-14):** Entkopplung von Kern-Logik (wie Textbereinigung) in eine neutrale `registry.py`, um Abhängigkeitsschleifen zwischen Diensten und Ingestion-Utilities zu verhindern.
|
||||||
|
* **Deep-Link / Section-basierter Link:** Ein Link wie `[[Note#Section]]`, der auf einen spezifischen Abschnitt innerhalb einer Note verweist. Seit v2.9.1 wird dieser in `target_id="Note"` und `target_section="Section"` aufgeteilt, um "Phantom-Knoten" zu vermeiden und Multigraph-Support zu ermöglichen.
|
||||||
|
* **Atomic Section Logic (v3.9.9):** Chunking-Verfahren, das Sektions-Überschriften und deren Inhalte atomar in Chunks hält (Pack-and-Carry-Over). Verhindert, dass Überschriften über Chunk-Grenzen hinweg getrennt werden.
|
||||||
|
* **Registry-First Profiling (v2.13.12):** Hierarchische Auflösung des Chunking-Profils: Frontmatter > types.yaml Typ-Config > Global Defaults. Stellt sicher, dass Note-Typen automatisch das korrekte Profil erhalten.
|
||||||
|
* **Mixture of Experts (MoE) - WP-25a:** Profilbasierte Experten-Architektur, bei der jede Systemaufgabe (Synthese, Ingestion-Validierung, Routing, Kompression) einem dedizierten Profil zugewiesen wird, das Modell, Provider und Parameter unabhängig von der globalen Konfiguration definiert.
|
||||||
|
* **LLM-Profil:** Zentrale Definition in `llm_profiles.yaml`, die Provider, Modell, Temperature und Fallback-Profil für eine spezifische Aufgabe festlegt (z.B. `synthesis_pro`, `tech_expert`, `ingest_validator`).
|
||||||
|
* **Fallback-Kaskade (WP-25a):** Rekursive Fallback-Logik, bei der bei Fehlern automatisch auf das `fallback_profile` umgeschaltet wird, bis der terminale Endpunkt (`identity_safe`) erreicht wird. Schutz gegen Zirkel-Referenzen via `visited_profiles`-Tracking.
|
||||||
|
* **Pre-Synthesis Kompression (WP-25a):** Asynchrone Verdichtung überlanger Wissens-Streams vor der Synthese, um Token-Verbrauch zu reduzieren und die Synthese zu beschleunigen. Nutzt `compression_profile` (z.B. `compression_fast`).
|
||||||
|
* **Profilgesteuerte Validierung (WP-25a):** Semantische Kanten-Validierung in der Ingestion erfolgt zwingend über das MoE-Profil `ingest_validator` (Temperature 0.0 für Determinismus), unabhängig von der globalen Provider-Konfiguration.
|
||||||
|
* **Lazy-Prompt-Orchestration (WP-25b):** Hierarchisches Prompt-Resolution-System, das Prompts erst im Moment des Modellaustauschs lädt, basierend auf dem exakt aktiven Modell. Ermöglicht modell-spezifisches Tuning und maximale Resilienz bei Modell-Fallbacks.
|
||||||
|
* **Hierarchische Prompt-Resolution (WP-25b):** Dreistufige Auflösungs-Logik: Level 1 (Modell-ID) → Level 2 (Provider) → Level 3 (Default). Gewährleistet, dass jedes Modell das optimale Template erhält.
|
||||||
|
* **PROMPT-TRACE (WP-25b):** Logging-Mechanismus, der die genutzte Prompt-Auflösungs-Ebene protokolliert (`🎯 Level 1`, `📡 Level 2`, `⚓ Level 3`). Bietet vollständige Transparenz über die genutzten Instruktionen.
|
||||||
|
* **Ultra-robustes Intent-Parsing (WP-25b):** Regex-basierter Intent-Parser in der DecisionEngine, der Modell-Artefakte wie `[/S]`, `</s>` oder Newlines zuverlässig bereinigt, um präzises Strategie-Routing zu gewährleisten.
|
||||||
|
* **Differenzierte Ingestion-Validierung (WP-25b):** Unterscheidung zwischen transienten Fehlern (Netzwerk, Timeout) und permanenten Fehlern (Config, Validation). Transiente Fehler erlauben die Kante (Datenverlust vermeiden), permanente Fehler lehnen sie ab (Graph-Qualität schützen).
|
||||||
@@ -0,0 +1,166 @@
|
|||||||
|
---
|
||||||
|
doc_type: quality_assurance
|
||||||
|
audience: all
|
||||||
|
status: active
|
||||||
|
version: 2.9.1
|
||||||
|
context: "Qualitätsprüfung der Dokumentation für alle Rollen: Vollständigkeit, Korrektheit und Anwendbarkeit."
|
||||||
|
---
|
||||||
|
|
||||||
|
# Dokumentations-Qualitätsprüfung
|
||||||
|
|
||||||
|
Diese Checkliste dient zur systematischen Prüfung, ob die Dokumentation alle Fragen jeder Rolle vollständig beantwortet.
|
||||||
|
|
||||||
|
## ✅ Entwickler
|
||||||
|
|
||||||
|
### Setup & Installation
|
||||||
|
- [x] **Lokales Setup:** [Developer Guide](../05_Development/05_developer_guide.md#6-lokales-setup-development)
|
||||||
|
- [x] **Schnellstart:** [Quickstart](00_quickstart.md)
|
||||||
|
- [x] **Hardware-Anforderungen:** [Admin Operations](../04_Operations/04_admin_operations.md#11-voraussetzungen)
|
||||||
|
|
||||||
|
### Architektur & Code
|
||||||
|
- [x] **Modulare Struktur:** [Developer Guide - Architektur](../05_Development/05_developer_guide.md#4-projektstruktur--modul-referenz-deep-dive)
|
||||||
|
- [x] **Design-Patterns:** [Architektur-Patterns](../02_concepts/02_concept_architecture_patterns.md)
|
||||||
|
- [x] **API-Referenz:** [API Reference](../03_Technical_References/03_tech_api_reference.md)
|
||||||
|
- [x] **Datenmodell:** [Data Model](../03_Technical_References/03_tech_data_model.md)
|
||||||
|
|
||||||
|
### Entwicklung & Erweiterung
|
||||||
|
- [x] **Workflow:** [Developer Guide - Workflow](../05_Development/05_developer_guide.md#7-der-entwicklungs-zyklus-workflow)
|
||||||
|
- [x] **Erweiterungs-Guide:** [Teach-the-AI](../05_Development/05_developer_guide.md#8-erweiterungs-guide-teach-the-ai)
|
||||||
|
- [x] **GenAI Best Practices:** [GenAI Best Practices](../05_Development/05_genai_best_practices.md)
|
||||||
|
|
||||||
|
### Testing
|
||||||
|
- [x] **Test-Strategien:** [Testing Guide](../05_Development/05_testing_guide.md)
|
||||||
|
- [x] **Test-Frameworks:** [Testing Guide - Frameworks](../05_Development/05_testing_guide.md#3-test-frameworks--tools)
|
||||||
|
- [x] **Test-Daten:** [Testing Guide - Test-Daten](../05_Development/05_testing_guide.md#2-test-daten--vaults)
|
||||||
|
|
||||||
|
### Debugging & Troubleshooting
|
||||||
|
- [x] **Troubleshooting:** [Developer Guide - Troubleshooting](../05_Development/05_developer_guide.md#10-troubleshooting--one-liners)
|
||||||
|
- [x] **Debug-Tools:** [Testing Guide - Debugging](../05_Development/05_testing_guide.md#7-debugging--diagnose)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## ✅ Administratoren
|
||||||
|
|
||||||
|
### Installation & Setup
|
||||||
|
- [x] **Installation:** [Admin Operations](../04_Operations/04_admin_operations.md#1-installation--setup)
|
||||||
|
- [x] **Docker Setup:** [Admin Operations - Qdrant](../04_Operations/04_admin_operations.md#12-qdrant-docker)
|
||||||
|
- [x] **Systemd Services:** [Admin Operations - Deployment](../04_Operations/04_admin_operations.md#2-deployment-systemd-services)
|
||||||
|
|
||||||
|
### Betrieb & Wartung
|
||||||
|
- [x] **Monitoring:** [Admin Operations - Wartung](../04_Operations/04_admin_operations.md#3-wartung--monitoring)
|
||||||
|
- [x] **Backup & Restore:** [Admin Operations - Backup](../04_Operations/04_admin_operations.md#4-backup--restore)
|
||||||
|
- [x] **Troubleshooting:** [Admin Operations - Troubleshooting](../04_Operations/04_admin_operations.md#33-troubleshooting-guide)
|
||||||
|
|
||||||
|
### Server-Betrieb
|
||||||
|
- [x] **Server-Konfiguration:** [Server Operations Manual](../04_Operations/04_server_operation_manual.md)
|
||||||
|
- [x] **Disaster Recovery:** [Server Operations - DR](../04_Operations/04_server_operation_manual.md#5-disaster-recovery-wiederherstellung-two-stage-dr)
|
||||||
|
- [x] **Backup-Strategie:** [Server Operations - Backup](../04_Operations/04_server_operation_manual.md#4-backup-strategie-borgmatic)
|
||||||
|
|
||||||
|
### Konfiguration
|
||||||
|
- [x] **ENV-Variablen:** [Configuration Reference](../03_Technical_References/03_tech_configuration.md#1-environment-variablen-env)
|
||||||
|
- [x] **YAML-Configs:** [Configuration Reference - YAML](../03_Technical_References/03_tech_configuration.md#2-typ-registry-typesyaml)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## ✅ Anwender
|
||||||
|
|
||||||
|
### Erste Schritte
|
||||||
|
- [x] **Schnellstart:** [Quickstart](00_quickstart.md)
|
||||||
|
- [x] **Was ist Mindnet:** [Vision & Strategie](00_vision_and_strategy.md)
|
||||||
|
- [x] **Grundlagen:** [Glossar](00_glossary.md)
|
||||||
|
|
||||||
|
### Nutzung
|
||||||
|
- [x] **Chat-Bedienung:** [Chat Usage Guide](../01_User_Manual/01_chat_usage_guide.md)
|
||||||
|
- [x] **Graph Explorer:** [Chat Usage Guide - Graph](../01_User_Manual/01_chat_usage_guide.md#22-modus--graph-explorer-cytoscape)
|
||||||
|
- [x] **Editor:** [Chat Usage Guide - Editor](../01_User_Manual/01_chat_usage_guide.md#23-modus--manueller-editor)
|
||||||
|
|
||||||
|
### Content-Erstellung
|
||||||
|
- [x] **Knowledge Design:** [Knowledge Design Manual](../01_User_Manual/01_knowledge_design.md)
|
||||||
|
- [x] **Authoring Guidelines:** [Authoring Guidelines](../01_User_Manual/01_authoring_guidelines.md)
|
||||||
|
- [x] **Obsidian-Integration:** [Obsidian Integration](../01_User_Manual/01_obsidian_integration_guide.md)
|
||||||
|
|
||||||
|
### Häufige Fragen
|
||||||
|
- [x] **Wie strukturiere ich Notizen?** → [Knowledge Design](../01_User_Manual/01_knowledge_design.md)
|
||||||
|
- [x] **Welche Note-Typen gibt es?** → [Knowledge Design - Typ-Referenz](../01_User_Manual/01_knowledge_design.md#31-typ-referenz--stream-logik)
|
||||||
|
- [x] **Wie verknüpfe ich Notizen?** → [Knowledge Design - Edges](../01_User_Manual/01_knowledge_design.md#4-edges--verlinkung)
|
||||||
|
- [x] **Wie nutze ich den Chat?** → [Chat Usage Guide](../01_User_Manual/01_chat_usage_guide.md)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## ✅ Tester
|
||||||
|
|
||||||
|
### Test-Strategien
|
||||||
|
- [x] **Test-Pyramide:** [Testing Guide - Strategien](../05_Development/05_testing_guide.md#1-test-strategie--ebenen)
|
||||||
|
- [x] **Unit Tests:** [Testing Guide - Unit Tests](../05_Development/05_testing_guide.md#11-unit-tests-pytest)
|
||||||
|
- [x] **Integration Tests:** [Testing Guide - Integration](../05_Development/05_testing_guide.md#12-integration-tests)
|
||||||
|
- [x] **E2E Tests:** [Testing Guide - E2E](../05_Development/05_testing_guide.md#13-e2e--smoke-tests)
|
||||||
|
|
||||||
|
### Test-Frameworks
|
||||||
|
- [x] **Pytest:** [Testing Guide - Frameworks](../05_Development/05_testing_guide.md#31-pytest-unit-tests)
|
||||||
|
- [x] **Unittest:** [Testing Guide - Unittest](../05_Development/05_testing_guide.md#32-unittest-e2e-tests)
|
||||||
|
- [x] **Shell-Skripte:** [Testing Guide - Shell](../05_Development/05_testing_guide.md#33-shell-skripte-e2e-roundtrip)
|
||||||
|
|
||||||
|
### Test-Daten & Tools
|
||||||
|
- [x] **Test-Vault erstellen:** [Testing Guide - Test-Daten](../05_Development/05_testing_guide.md#21-test-vault-erstellen)
|
||||||
|
- [x] **Test-Skripte:** [Developer Guide - Scripts](../05_Development/05_developer_guide.md#44-scripts--tooling-die-admin-toolbox)
|
||||||
|
- [x] **Test-Checkliste:** [Testing Guide - Checkliste](../05_Development/05_testing_guide.md#8-test-checkliste-für-pull-requests)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## ✅ Deployment
|
||||||
|
|
||||||
|
### Deployment-Prozesse
|
||||||
|
- [x] **Deployment-Guide:** [Deployment Guide](../04_Operations/04_deployment_guide.md)
|
||||||
|
- [x] **CI/CD Pipeline:** [Deployment Guide - CI/CD](../04_Operations/04_deployment_guide.md#9-cicd-pipeline-details)
|
||||||
|
- [x] **Rollout-Strategien:** [Deployment Guide - Rollout](../04_Operations/04_deployment_guide.md#4-rollout-strategien)
|
||||||
|
|
||||||
|
### Versionierung & Releases
|
||||||
|
- [x] **Version-Schema:** [Deployment Guide - Versionierung](../04_Operations/04_deployment_guide.md#51-version-schema)
|
||||||
|
- [x] **Release-Prozess:** [Deployment Guide - Release](../04_Operations/04_deployment_guide.md#52-release-prozess)
|
||||||
|
|
||||||
|
### Rollback & Recovery
|
||||||
|
- [x] **Rollback-Strategien:** [Deployment Guide - Rollback](../04_Operations/04_deployment_guide.md#6-rollback-strategien)
|
||||||
|
- [x] **Disaster Recovery:** [Server Operations - DR](../04_Operations/04_server_operation_manual.md#5-disaster-recovery-wiederherstellung-two-stage-dr)
|
||||||
|
|
||||||
|
### Pre/Post-Deployment
|
||||||
|
- [x] **Pre-Deployment Checkliste:** [Deployment Guide - Checkliste](../04_Operations/04_deployment_guide.md#7-pre-deployment-checkliste)
|
||||||
|
- [x] **Post-Deployment Validierung:** [Deployment Guide - Validierung](../04_Operations/04_deployment_guide.md#8-post-deployment-validierung)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📊 Zusammenfassung
|
||||||
|
|
||||||
|
### Vollständigkeit nach Rolle
|
||||||
|
|
||||||
|
| Rolle | Abgedeckte Themen | Status |
|
||||||
|
| :--- | :--- | :--- |
|
||||||
|
| **Entwickler** | Setup, Architektur, Code, Testing, Debugging | ✅ Vollständig |
|
||||||
|
| **Administratoren** | Installation, Betrieb, Wartung, Backup, DR | ✅ Vollständig |
|
||||||
|
| **Anwender** | Nutzung, Content-Erstellung, Workflows | ✅ Vollständig |
|
||||||
|
| **Tester** | Test-Strategien, Frameworks, Tools | ✅ Vollständig |
|
||||||
|
| **Deployment** | CI/CD, Rollout, Versionierung, Rollback | ✅ Vollständig |
|
||||||
|
|
||||||
|
### Neue Dokumente
|
||||||
|
|
||||||
|
1. ✅ `05_testing_guide.md` - Umfassender Test-Guide
|
||||||
|
2. ✅ `04_deployment_guide.md` - Vollständiger Deployment-Guide
|
||||||
|
3. ✅ `02_concept_architecture_patterns.md` - Architektur-Patterns
|
||||||
|
4. ✅ `03_tech_api_reference.md` - API-Referenz
|
||||||
|
5. ✅ `00_quickstart.md` - Schnellstart-Anleitung
|
||||||
|
6. ✅ `README.md` - Dokumentations-Einstiegspunkt
|
||||||
|
|
||||||
|
### Aktualisierte Dokumente
|
||||||
|
|
||||||
|
1. ✅ `00_documentation_map.md` - Alle neuen Dokumente aufgenommen
|
||||||
|
2. ✅ `04_admin_operations.md` - Troubleshooting erweitert
|
||||||
|
3. ✅ `05_developer_guide.md` - Modulare Struktur ergänzt
|
||||||
|
4. ✅ `03_tech_ingestion_pipeline.md` - Background Tasks dokumentiert
|
||||||
|
5. ✅ `03_tech_configuration.md` - Fehlende ENV-Variablen ergänzt
|
||||||
|
6. ✅ `00_vision_and_strategy.md` - Design-Entscheidungen ergänzt
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**Status:** ✅ Alle Rollen vollständig abgedeckt
|
||||||
|
**Letzte Prüfung:** 2025-01-XX
|
||||||
|
**Version:** 2.9.1
|
||||||
|
|
||||||
@@ -0,0 +1,156 @@
|
|||||||
|
---
|
||||||
|
doc_type: quickstart_guide
|
||||||
|
audience: user, developer, admin
|
||||||
|
status: active
|
||||||
|
version: 2.9.1
|
||||||
|
context: "Schnellstart-Anleitung für neue Benutzer von Mindnet"
|
||||||
|
---
|
||||||
|
|
||||||
|
# Mindnet Schnellstart
|
||||||
|
|
||||||
|
Diese Anleitung hilft dir, in 15 Minuten mit Mindnet loszulegen.
|
||||||
|
|
||||||
|
## 🎯 Was ist Mindnet?
|
||||||
|
|
||||||
|
Mindnet ist ein **persönliches KI-Gedächtnis**, das:
|
||||||
|
- Dein Wissen in Markdown-Notizen speichert
|
||||||
|
- Semantisch verknüpft (Wissensgraph)
|
||||||
|
- Als intelligenter Dialogpartner agiert (RAG-Chat)
|
||||||
|
- **Lokal und privat** läuft (Privacy First)
|
||||||
|
|
||||||
|
## 📋 Voraussetzungen
|
||||||
|
|
||||||
|
- **Python 3.10+** installiert
|
||||||
|
- **Docker** installiert (für Qdrant)
|
||||||
|
- **Ollama** installiert (für lokale LLMs)
|
||||||
|
- Optional: **Obsidian** (für komfortables Schreiben)
|
||||||
|
|
||||||
|
## ⚡ Installation (5 Minuten)
|
||||||
|
|
||||||
|
### Schritt 1: Repository klonen
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git clone <repository-url> mindnet
|
||||||
|
cd mindnet
|
||||||
|
```
|
||||||
|
|
||||||
|
### Schritt 2: Virtuelle Umgebung erstellen
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python3 -m venv .venv
|
||||||
|
source .venv/bin/activate # Windows: .venv\Scripts\activate
|
||||||
|
```
|
||||||
|
|
||||||
|
### Schritt 3: Abhängigkeiten installieren
|
||||||
|
|
||||||
|
```bash
|
||||||
|
pip install -r requirements.txt
|
||||||
|
```
|
||||||
|
|
||||||
|
### Schritt 4: Qdrant starten (Docker)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker compose up -d qdrant
|
||||||
|
```
|
||||||
|
|
||||||
|
### Schritt 5: Ollama-Modelle laden
|
||||||
|
|
||||||
|
```bash
|
||||||
|
ollama pull phi3:mini
|
||||||
|
ollama pull nomic-embed-text
|
||||||
|
```
|
||||||
|
|
||||||
|
### Schritt 6: Konfiguration anpassen
|
||||||
|
|
||||||
|
Erstelle eine `.env`-Datei im Projektroot:
|
||||||
|
|
||||||
|
```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
|
||||||
|
MINDNET_VAULT_ROOT=./vault
|
||||||
|
```
|
||||||
|
|
||||||
|
## 🚀 Erste Schritte (5 Minuten)
|
||||||
|
|
||||||
|
### Schritt 1: Backend starten
|
||||||
|
|
||||||
|
```bash
|
||||||
|
uvicorn app.main:app --reload --port 8001
|
||||||
|
```
|
||||||
|
|
||||||
|
### Schritt 2: Frontend starten (neues Terminal)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
streamlit run app/frontend/ui.py --server.port 8501
|
||||||
|
```
|
||||||
|
|
||||||
|
### Schritt 3: Browser öffnen
|
||||||
|
|
||||||
|
Öffne `http://localhost:8501` im Browser.
|
||||||
|
|
||||||
|
### Schritt 4: Erste Notiz importieren
|
||||||
|
|
||||||
|
Erstelle eine Test-Notiz im `vault/` Ordner:
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
---
|
||||||
|
id: 20250101-test
|
||||||
|
title: Meine erste Notiz
|
||||||
|
type: concept
|
||||||
|
status: active
|
||||||
|
---
|
||||||
|
|
||||||
|
# Meine erste Notiz
|
||||||
|
|
||||||
|
Dies ist eine Test-Notiz für Mindnet.
|
||||||
|
|
||||||
|
[[rel:related_to Mindnet]]
|
||||||
|
```
|
||||||
|
|
||||||
|
Dann importiere sie:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python3 -m scripts.import_markdown --vault ./vault --prefix mindnet --apply
|
||||||
|
```
|
||||||
|
|
||||||
|
### Schritt 5: Erste Chat-Anfrage
|
||||||
|
|
||||||
|
Im Browser-Chat eingeben:
|
||||||
|
```
|
||||||
|
Was ist Mindnet?
|
||||||
|
```
|
||||||
|
|
||||||
|
## 📚 Nächste Schritte
|
||||||
|
|
||||||
|
Nach dem Schnellstart empfehle ich:
|
||||||
|
|
||||||
|
1. **[Chat Usage Guide](../01_User_Manual/01_chat_usage_guide.md)** - Lerne die Chat-Funktionen kennen
|
||||||
|
2. **[Knowledge Design](../01_User_Manual/01_knowledge_design.md)** - Verstehe, wie du Notizen strukturierst
|
||||||
|
3. **[Authoring Guidelines](../01_User_Manual/01_authoring_guidelines.md)** - Lerne Best Practices für das Schreiben
|
||||||
|
|
||||||
|
## 🆘 Hilfe & Troubleshooting
|
||||||
|
|
||||||
|
**Problem:** Qdrant startet nicht
|
||||||
|
- **Lösung:** Prüfe, ob Docker läuft: `docker ps`
|
||||||
|
|
||||||
|
**Problem:** Ollama-Modell nicht gefunden
|
||||||
|
- **Lösung:** Prüfe mit `ollama list`, ob die Modelle geladen sind
|
||||||
|
|
||||||
|
**Problem:** Import schlägt fehl
|
||||||
|
- **Lösung:** Prüfe die Logs und stelle sicher, dass Qdrant läuft
|
||||||
|
|
||||||
|
Für detaillierte Troubleshooting-Informationen siehe [Admin Operations](../04_Operations/04_admin_operations.md#33-troubleshooting-guide).
|
||||||
|
|
||||||
|
## 🔗 Weitere Ressourcen
|
||||||
|
|
||||||
|
- **[Dokumentationskarte](00_documentation_map.md)** - Übersicht aller Dokumente
|
||||||
|
- **[Glossar](00_glossary.md)** - Wichtige Begriffe erklärt
|
||||||
|
- **[Vision & Strategie](00_vision_and_strategy.md)** - Die Philosophie hinter Mindnet
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**Viel Erfolg mit Mindnet!** 🚀
|
||||||
|
|
||||||
@@ -65,3 +65,41 @@ Die folgenden Prinzipien steuern jede technische Entscheidung:
|
|||||||
|
|
||||||
10. **Local First & Privacy:**
|
10. **Local First & Privacy:**
|
||||||
Nutzung lokaler LLMs (Ollama) für Inference. Keine Daten verlassen den Server.
|
Nutzung lokaler LLMs (Ollama) für Inference. Keine Daten verlassen den Server.
|
||||||
|
|
||||||
|
11. **Modulare Architektur (WP-14):**
|
||||||
|
Core-Logik ist in spezialisierte Pakete unterteilt (`chunking/`, `database/`, `graph/`, `ingestion/`, `parser/`, `retrieval/`). Dies ermöglicht unabhängige Entwicklung, Testbarkeit und Wartbarkeit.
|
||||||
|
|
||||||
|
12. **Resilienz durch Kaskaden:**
|
||||||
|
System nutzt Provider-Kaskaden (Cloud → Rate-Limit-Handling → Lokaler Fallback) für hohe Verfügbarkeit. Deep Fallback erkennt auch kognitive Blockaden (Silent Refusals).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Design-Entscheidungen & Trade-offs
|
||||||
|
|
||||||
|
### 4.1 Qdrant als Vektor-DB
|
||||||
|
**Entscheidung:** Self-hosted Qdrant statt Managed Service (Pinecone/Weaviate)
|
||||||
|
**Gründe:** Privacy First, Open Source, lokale Kontrolle
|
||||||
|
**Trade-off:** Mehr Wartungsaufwand, aber vollständige Datenhoheit
|
||||||
|
|
||||||
|
### 4.2 Hybrid Retrieval
|
||||||
|
**Entscheidung:** Kombination von Vektor-Suche (Semantik) und Graph-Expansion
|
||||||
|
**Gründe:** Bessere Relevanz durch strukturelle Verbindungen
|
||||||
|
**Trade-off:** Höhere Komplexität, aber deutlich bessere Ergebnisse
|
||||||
|
|
||||||
|
### 4.3 Background Tasks statt Queue-System
|
||||||
|
**Entscheidung:** FastAPI Background Tasks statt Redis/RabbitMQ
|
||||||
|
**Gründe:** Einfacher Setup, ausreichend für Single-User
|
||||||
|
**Trade-off:** Keine Persistenz bei Server-Neustart, aber weniger Infrastruktur
|
||||||
|
|
||||||
|
### 4.4 Markdown als Source of Truth
|
||||||
|
**Entscheidung:** Markdown-Dateien sind primär, Datenbank ist Cache
|
||||||
|
**Gründe:** Versionierbarkeit, Editierbarkeit, Unabhängigkeit
|
||||||
|
**Trade-off:** Zwei Datenquellen, aber maximale Flexibilität
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Weitere Informationen
|
||||||
|
|
||||||
|
- **Architektur-Patterns:** Siehe [Architektur-Patterns](../02_concepts/02_concept_architecture_patterns.md)
|
||||||
|
- **Graph-Logik:** Siehe [Graph-Logik](../02_concepts/02_concept_graph_logic.md)
|
||||||
|
- **KI-Persönlichkeit:** Siehe [KI-Persönlichkeit](../02_concepts/02_concept_ai_personality.md)
|
||||||
@@ -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
|
||||||
|
|
||||||
@@ -3,14 +3,16 @@ doc_type: user_manual
|
|||||||
audience: user, mindmaster
|
audience: user, mindmaster
|
||||||
scope: chat, ui, feedback, graph
|
scope: chat, ui, feedback, graph
|
||||||
status: active
|
status: active
|
||||||
version: 2.6
|
version: 2.9.3
|
||||||
context: "Anleitung zur Nutzung der Web-Oberfläche, der Chat-Personas und des Graph Explorers."
|
context: "Anleitung zur Nutzung der Web-Oberfläche, der Chat-Personas, Multi-Stream RAG und des Graph Explorers."
|
||||||
---
|
---
|
||||||
|
|
||||||
# Chat & Graph Usage Guide
|
# Chat & Graph Usage Guide
|
||||||
|
|
||||||
**Quellen:** `user_guide.md`
|
**Quellen:** `user_guide.md`
|
||||||
|
|
||||||
|
> 💡 **Tipp für Einsteiger:** Falls du noch nie mit Mindnet gearbeitet hast, starte mit dem [Schnellstart](../00_General/00_quickstart.md) und dem [Knowledge Design Manual](01_knowledge_design.md), um die Grundlagen zu verstehen.
|
||||||
|
|
||||||
## 1. Was Mindnet für dich tut
|
## 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.
|
Mindnet ist ein **assoziatives Gedächtnis** mit Persönlichkeit. Es unterscheidet sich von einer reinen Suche dadurch, dass es **kontextsensitiv** agiert.
|
||||||
@@ -58,21 +60,49 @@ Ein Editor mit **"File System First"** Garantie.
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 3. Den Chat steuern (Intents)
|
## 3. Den Chat steuern (Intents & Multi-Stream RAG)
|
||||||
|
|
||||||
Du steuerst die Persönlichkeit von Mindnet durch deine Wortwahl. Der **Hybrid Router v5** unterscheidet intelligent:
|
Du steuerst die Persönlichkeit von Mindnet durch deine Wortwahl. Seit WP-25 nutzt Mindnet **Agentic Multi-Stream RAG**, das deine Anfrage in parallele Wissens-Streams aufteilt:
|
||||||
|
|
||||||
### 3.1 Frage-Modus (Wissen abrufen)
|
### 3.1 Intent-Erkennung (Hybrid-Router)
|
||||||
Ausgelöst durch `?` oder W-Wörter.
|
|
||||||
|
Der Router erkennt deine Absicht auf zwei Wegen:
|
||||||
|
|
||||||
|
**Schnelle Erkennung (Keyword Fast-Path):**
|
||||||
|
* **"Soll ich..."** → Sofortige Erkennung als `DECISION` (Berater)
|
||||||
|
* **"Wann..."** → Sofortige Erkennung als `FACT_WHEN` (Zeitpunkte)
|
||||||
|
* **"Was ist..."** → Sofortige Erkennung als `FACT_WHAT` (Wissen)
|
||||||
|
* **"Ich fühle..."** → Sofortige Erkennung als `EMPATHY` (Spiegel)
|
||||||
|
|
||||||
|
**Intelligente Analyse (LLM Slow-Path):**
|
||||||
|
* Bei unklaren Anfragen analysiert die KI semantisch deine Absicht
|
||||||
|
|
||||||
|
### 3.2 Multi-Stream Retrieval (WP-25)
|
||||||
|
|
||||||
|
Anstelle einer einzelnen Suche führt Mindnet nun **parallele Abfragen** in spezialisierten Wissens-Streams aus:
|
||||||
|
|
||||||
|
**Die Streams:**
|
||||||
|
* **Values Stream:** Deine Identität, Ethik und Prinzipien (`value`, `principle`, `belief`)
|
||||||
|
* **Facts Stream:** Operative Daten zu Projekten, Tasks und Status (`project`, `decision`, `task`)
|
||||||
|
* **Biography Stream:** Persönliche Erfahrungen und Journal-Einträge (`experience`, `journal`)
|
||||||
|
* **Risk Stream:** Hindernisse und potenzielle Gefahren (`risk`, `obstacle`)
|
||||||
|
* **Tech Stream:** Technisches Wissen, Code und Dokumentation (`concept`, `source`, `glossary`)
|
||||||
|
|
||||||
|
**Vorteil:** Jeder Stream fokussiert auf spezifische Wissensbereiche, was zu präziseren und kontextreicheren Antworten führt.
|
||||||
|
|
||||||
|
### 3.3 Frage-Modi (Strategien)
|
||||||
|
|
||||||
* **Entscheidung ("Soll ich?"):** Der **Berater**.
|
* **Entscheidung ("Soll ich?"):** Der **Berater**.
|
||||||
* Mindnet lädt deine Werte (`type: value`) und Ziele (`type: goal`).
|
* Nutzt: Values Stream, Facts Stream, Risk Stream
|
||||||
|
* Wägt Fakten gegen deine Werte ab und evaluiert Risiken
|
||||||
* *Beispiel:* "Soll ich Tool X nutzen?" -> "Nein, Tool X speichert Daten in den USA. Das verstößt gegen dein Prinzip 'Privacy First'."
|
* *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**.
|
* **Empathie ("Ich fühle..."):** Der **Spiegel**.
|
||||||
* Mindnet lädt deine Erfahrungen (`type: experience`).
|
* Nutzt: Biography Stream, Values Stream
|
||||||
|
* Greift auf deine Erfahrungen und Werte zurück
|
||||||
* *Beispiel:* "Ich bin frustriert." -> "Das erinnert mich an Projekt Y, da ging es uns ähnlich..."
|
* *Beispiel:* "Ich bin frustriert." -> "Das erinnert mich an Projekt Y, da ging es uns ähnlich..."
|
||||||
* **Fakten ("Was ist?"):** Der **Bibliothekar**.
|
* **Fakten ("Was ist?", "Wann..."):** Der **Bibliothekar**.
|
||||||
* Liefert präzise Definitionen.
|
* Nutzt: Facts Stream, Tech Stream, Biography Stream
|
||||||
|
* Liefert präzise Definitionen und zeitliche Informationen
|
||||||
|
|
||||||
### 3.2 Befehls-Modus (Interview)
|
### 3.2 Befehls-Modus (Interview)
|
||||||
Ausgelöst durch Aussagen wie "Neues Projekt", "Ich will festhalten".
|
Ausgelöst durch Aussagen wie "Neues Projekt", "Ich will festhalten".
|
||||||
@@ -82,13 +112,17 @@ Ausgelöst durch Aussagen wie "Neues Projekt", "Ich will festhalten".
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 4. Ergebnisse interpretieren (Explanation Layer)
|
## 4. Ergebnisse interpretieren (Explanation Layer & Stream-Tracing)
|
||||||
|
|
||||||
Mindnet liefert eine **Begründung** ("Reasons"), warum es etwas gefunden hat.
|
Mindnet liefert eine **Begründung** ("Reasons"), warum es etwas gefunden hat.
|
||||||
Öffne eine Quellen-Karte, um zu sehen:
|
Öffne eine Quellen-Karte, um zu sehen:
|
||||||
* *"Hohe textuelle Übereinstimmung."* (Semantik)
|
* *"Hohe textuelle Übereinstimmung."* (Semantik)
|
||||||
* *"Bevorzugt aufgrund des Typs 'decision'."* (Wichtigkeit)
|
* *"Bevorzugt aufgrund des Typs 'decision'."* (Wichtigkeit)
|
||||||
* *"Verweist auf 'Projekt X' via 'depends_on'."* (Graph-Kontext)
|
* *"Verweist auf 'Projekt X' via 'depends_on'."* (Graph-Kontext)
|
||||||
|
* *"Quelle: Values Stream"* (Stream-Tracing - WP-25)
|
||||||
|
|
||||||
|
**Stream-Tracing (WP-25):**
|
||||||
|
Jede Quelle wird mit ihrem Ursprungs-Stream markiert (z.B. "Values Stream", "Facts Stream"). Dies hilft dir zu verstehen, aus welchem Wissensbereich die Information stammt.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -124,3 +158,85 @@ Wenn du im **manuellen Editor** schreibst, unterstützt dich Mindnet aktiv bei d
|
|||||||
* **Semantische Treffer:** Das System findet inhaltlich verwandte Notizen.
|
* **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.
|
* **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.
|
4. **Speichern:** Der Text wird sofort in den Vault geschrieben und indiziert.
|
||||||
|
|
||||||
|
### 6.3 Weg C: Direktes Schreiben in Obsidian
|
||||||
|
Wenn du Obsidian nutzt, kannst du Notizen direkt im Vault erstellen. Nach dem Speichern in Obsidian:
|
||||||
|
|
||||||
|
1. **Automatischer Import (Cron):** Der stündliche Cron-Job importiert neue/geänderte Dateien automatisch.
|
||||||
|
2. **Manueller Import:** Oder führe manuell aus:
|
||||||
|
```bash
|
||||||
|
python3 -m scripts.import_markdown --vault ./vault --prefix mindnet --apply
|
||||||
|
```
|
||||||
|
|
||||||
|
**Vorteil:** Du arbeitest in deiner gewohnten Obsidian-Umgebung, Mindnet synchronisiert im Hintergrund.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. Häufige Anwendungsfälle (Use Cases)
|
||||||
|
|
||||||
|
### 7.1 Entscheidungshilfe suchen
|
||||||
|
**Szenario:** Du stehst vor einer schwierigen Entscheidung.
|
||||||
|
|
||||||
|
**Vorgehen:**
|
||||||
|
1. Stelle eine Frage im Chat: *"Soll ich Tool X nutzen?"*
|
||||||
|
2. Mindnet erkennt `DECISION` Intent
|
||||||
|
3. System lädt deine Werte, Prinzipien und Ziele
|
||||||
|
4. Antwort berücksichtigt deine persönlichen Kriterien
|
||||||
|
|
||||||
|
**Beispiel:** *"Soll ich Notion nutzen?"* → System prüft gegen dein Prinzip "Privacy First" und rät ab.
|
||||||
|
|
||||||
|
### 7.2 Erfahrungen dokumentieren
|
||||||
|
**Szenario:** Du willst ein prägendes Erlebnis festhalten.
|
||||||
|
|
||||||
|
**Vorgehen:**
|
||||||
|
1. Chat: *"Neue Erfahrung: Streit am Recyclinghof"*
|
||||||
|
2. System erstellt strukturierte Notiz mit Feldern:
|
||||||
|
- Situation
|
||||||
|
- Reaktion
|
||||||
|
- Learning
|
||||||
|
3. Verknüpfe mit relevanten Rollen: `[[rel:supports Meine Rollenlandkarte 2025#Vater]]`
|
||||||
|
|
||||||
|
### 7.3 Wissen im Graph erkunden
|
||||||
|
**Szenario:** Du willst verstehen, wie Konzepte zusammenhängen.
|
||||||
|
|
||||||
|
**Vorgehen:**
|
||||||
|
1. Wechsle zum **Graph Explorer**
|
||||||
|
2. Suche nach einem Knoten (z.B. "Projekt Alpha")
|
||||||
|
3. Klicke auf "🎯 Als Zentrum setzen"
|
||||||
|
4. Erkunde die Nachbarschaft (Abhängigkeiten, Entscheidungen, ähnliche Projekte)
|
||||||
|
|
||||||
|
### 7.4 Bestehende Notizen verbessern
|
||||||
|
**Szenario:** Eine Notiz ist unvollständig oder unvernetzt.
|
||||||
|
|
||||||
|
**Vorgehen:**
|
||||||
|
1. Öffne die Notiz im **Manuellen Editor**
|
||||||
|
2. Nutze **Intelligence-Tab** für Link-Vorschläge
|
||||||
|
3. Füge semantische Links hinzu: `[[rel:based_on Wert X]]`
|
||||||
|
4. Speichern → System indiziert neu
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. Tipps & Tricks
|
||||||
|
|
||||||
|
### 8.1 Intent-Steuerung
|
||||||
|
- **Frage mit "?":** Löst RAG-Modus aus (Wissen abrufen)
|
||||||
|
- **Aussage ohne "?":** Löst Interview-Modus aus (Wissen speichern)
|
||||||
|
- **Emotionale Wörter:** Aktivieren Empathie-Persona ("Ich fühle...", "Ich bin frustriert...")
|
||||||
|
|
||||||
|
### 8.2 Graph-Navigation
|
||||||
|
- **URL-Persistenz:** Graph-Einstellungen werden in der URL gespeichert → Lesezeichen für spezifische Ansichten
|
||||||
|
- **Deep-Links:** Verlinke präzise Abschnitte: `[[Note#Abschnitt]]` statt nur `[[Note]]`
|
||||||
|
|
||||||
|
### 8.3 Feedback nutzen
|
||||||
|
- **Regelmäßiges Feedback:** Macht das System schlauer
|
||||||
|
- **Granulares Feedback:** Bewerte einzelne Quellen, nicht nur die Gesamtantwort
|
||||||
|
- **Konsequenz:** System lernt deine Präferenzen
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9. Weitere Informationen
|
||||||
|
|
||||||
|
- **Knowledge Design:** Siehe [Knowledge Design Manual](01_knowledge_design.md)
|
||||||
|
- **Authoring Guidelines:** Siehe [Authoring Guidelines](01_authoring_guidelines.md)
|
||||||
|
- **Obsidian Integration:** Siehe [Obsidian Integration Guide](01_obsidian_integration_guide.md)
|
||||||
|
- **Troubleshooting:** Siehe [Admin Operations - Troubleshooting](../04_Operations/04_admin_operations.md#33-troubleshooting-guide)
|
||||||
@@ -3,7 +3,7 @@ doc_type: user_manual
|
|||||||
audience: user, author
|
audience: user, author
|
||||||
scope: vault, markdown, schema
|
scope: vault, markdown, schema
|
||||||
status: active
|
status: active
|
||||||
version: 2.7.0
|
version: 2.9.1
|
||||||
context: "Regelwerk für das Erstellen von Notizen im Vault. Die 'Source of Truth' für Autoren."
|
context: "Regelwerk für das Erstellen von Notizen im Vault. Die 'Source of Truth' für Autoren."
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -11,16 +11,14 @@ context: "Regelwerk für das Erstellen von Notizen im Vault. Die 'Source of Trut
|
|||||||
|
|
||||||
**Quellen:** `knowledge_design.md`, `types.yaml`
|
**Quellen:** `knowledge_design.md`, `types.yaml`
|
||||||
|
|
||||||
## ⚡ Die 5 Goldenen Regeln (TL;DR)
|
## ⚡ Die 6 Goldenen Regeln (TL;DR)
|
||||||
|
|
||||||
Damit Mindnet als dein Digitaler Zwilling funktioniert, beachte beim Schreiben diese Grundsätze:
|
|
||||||
|
|
||||||
1. **Atomare Gedanken:** Eine Notiz = Ein Thema. Wenn du über zwei Projekte schreibst, mach zwei Notizen draus.
|
|
||||||
2. **Explizite Typen:** Setze immer den `type` im Frontmatter. Mindnet behandelt eine `decision` ("Wir machen X") völlig anders als ein `concept` ("Was ist X").
|
|
||||||
3. **Semantische Links:** Schreibe nicht nur `[[Link]]`, sondern `[[rel:depends_on Link]]`. Sag dem System *wie* Dinge zusammenhängen.
|
|
||||||
4. **Werte & Ziele definieren:** Damit die **Decision Engine** dich beraten kann, musst du deine Kriterien (`type: value`, `type: goal`) explizit als Notizen anlegen.
|
|
||||||
5. **Emotionales Bridging:** Damit die **Empathie** funktioniert, nutze in Erfahrungsberichten (`type: experience`) emotionale Schlüsselwörter ("Krise", "Freude", "Angst").
|
|
||||||
|
|
||||||
|
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
|
## 1. Zweck & Scope
|
||||||
@@ -43,10 +41,17 @@ type: project # Steuert Chunking & Wichtigkeit
|
|||||||
status: active # active, archived, draft
|
status: active # active, archived, draft
|
||||||
created: 2025-12-12 # ISO 8601
|
created: 2025-12-12 # ISO 8601
|
||||||
tags: [ki, entwicklung] # Taxonomie
|
tags: [ki, entwicklung] # Taxonomie
|
||||||
|
aliases: [KI Projekt, Codename Quickhack]
|
||||||
---
|
---
|
||||||
```
|
```
|
||||||
|
|
||||||
### 2.1 Advanced Overrides: Die KI-Steuerung übernehmen
|
### **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.
|
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.
|
||||||
|
|
||||||
@@ -86,23 +91,110 @@ retriever_weight: 1.5
|
|||||||
```
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
|
## 3. Frontmatter Felder und ihre Bedeutung
|
||||||
|
### 3.1 Typ-Referenz & Stream-Logik
|
||||||
|
|
||||||
## 3. Typ-Referenz & Verhalten
|
Das System euriert Informationen in funktionalen Streams. Wähle den Typ danach aus, in welchem "Gedächtnis-Bereich" die Information landen soll.
|
||||||
|
|
||||||
Wähle den Typ, der die **Rolle** der Notiz am besten beschreibt. Der Typ setzt die Defaults für die oben genannten Parameter.
|
### 3.1 Identity Stream (Der Kern / Das „Warum“)
|
||||||
|
Dieser Stream definiert deine stabilen Merkmale und inneren Kompasse.
|
||||||
|
|
||||||
| Typ | Default Profil | Default Gewicht | Einsatzzweck |
|
| Typ | Gewicht | Chunking Profil | Zweck & Inhalt |
|
||||||
| :--- | :--- | :--- | :--- |
|
| :--- | :--- | :--- | :--- |
|
||||||
| **`concept`** | `sliding_smart_edges` | 0.60 | Fachbegriffe, Theorien. Zeitloses Wissen. |
|
| **`value`** | 1.00 | `structured_strict` | Fundamentale Werte und moralische Maßstäbe. |
|
||||||
| **`project`** | `sliding_smart_edges` | 0.97 | Aktive Vorhaben mit Ziel und Status. |
|
| **`principle`** | 0.95 | `structured_strict_L3` | Handlungsleitlinien mit tiefer Hierarchie (H3-Split). |
|
||||||
| **`experience`**| `sliding_smart_edges` | 0.90 | Persönliche Lektionen (für Empathie). |
|
| **`trait`** | 1.10 | `structured_strict` | Charakterliche Stärken und Talente. |
|
||||||
| **`decision`** | **`structured_..._strict`** | **1.00** | Entscheidungen. Muss atomar getrennt sein (Optionen vs. Ergebnis). |
|
| **`belief`** | 0.90 | `sliding_short` | Tiefe Überzeugungen über dich und die Gesellschaft. |
|
||||||
| **`value`** | **`structured_..._strict`** | **1.00** | Werte/Prinzipien. |
|
| **`profile`** | 0.70 | `structured_strict` | Rollenidentitäten (z. B. Vater, Mentor, Unternehmer). |
|
||||||
| **`principle`**| `structured_..._strict_L3`| 0.95 | Handlungsleitlinien (Trennt bis Ebene H3). |
|
| **`need`** | 1.05 | `sliding_smart_edges` | Psychologische Grundbedürfnisse (z. B. Autonomie, Bindung). |
|
||||||
| **`goal`** | `sliding_smart_edges` | 0.95 | Strategische Ziele. |
|
| **`motivation`**| 0.95 | `sliding_smart_edges` | Innere Antreiber und Quellen deiner Energie. |
|
||||||
| **`risk`** | `sliding_short` | 0.85 | Risiken (kurz und prägnant). |
|
| **`boundary`** | 0.90 | `sliding_smart_edges` | Deine persönlichen Grenzen und Integritäts-Leitplanken. |
|
||||||
| **`journal`** | `sliding_standard` | 0.80 | Zeitbezogene Logs. |
|
| **`bias`** | 0.80 | `sliding_short` | Bekannte kognitive Verzerrungen und Denkfallen. |
|
||||||
| **`source`** | `sliding_standard` | 0.50 | Externe Quellen (niedrig gewichtet). |
|
|
||||||
|
### 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.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -116,6 +208,12 @@ Dies ist die **mächtigste** Methode. Du sagst dem System explizit, **wie** Ding
|
|||||||
> "Daher [[rel:depends_on Qdrant]]."
|
> "Daher [[rel:depends_on Qdrant]]."
|
||||||
> "Dieses Konzept ist [[rel:similar_to Pinecone]]."
|
> "Dieses Konzept ist [[rel:similar_to Pinecone]]."
|
||||||
|
|
||||||
|
**Deep-Links zu Abschnitten (v2.9.1):**
|
||||||
|
Du kannst auch auf spezifische Abschnitte innerhalb einer Note verlinken:
|
||||||
|
> "Siehe [[rel:based_on Mein Leitbild#P3 – Disziplin]]."
|
||||||
|
|
||||||
|
Das System trennt automatisch den Note-Namen (`Mein Leitbild`) vom Abschnitts-Namen (`P3 – Disziplin`), sodass mehrere Links zur gleichen Note möglich sind, wenn sie auf verschiedene Abschnitte zeigen.
|
||||||
|
|
||||||
**Gültige Relationen:**
|
**Gültige Relationen:**
|
||||||
* `depends_on`: Hängt ab von / Benötigt.
|
* `depends_on`: Hängt ab von / Benötigt.
|
||||||
* `blocks`: Blockiert oder gefährdet (z.B. Risiko -> Projekt).
|
* `blocks`: Blockiert oder gefährdet (z.B. Risiko -> Projekt).
|
||||||
@@ -123,33 +221,47 @@ Dies ist die **mächtigste** Methode. Du sagst dem System explizit, **wie** Ding
|
|||||||
* `similar_to`: Ähnelt / Ist vergleichbar mit.
|
* `similar_to`: Ähnelt / Ist vergleichbar mit.
|
||||||
* `solves`: Löst (Problem).
|
* `solves`: Löst (Problem).
|
||||||
* `based_on`: Basiert auf (Fundament).
|
* `based_on`: Basiert auf (Fundament).
|
||||||
|
* **`prev` / `next` [NEU]**: Markiert chronologische oder evolutionäre Abfolgen (z.B. Leitbild-Evolution).
|
||||||
|
|
||||||
### 4.2 Callout-Edges
|
### 4.2 Callout-Edges (empfohlen)
|
||||||
Für Zusammenfassungen am Ende einer Notiz:
|
Für Zusammenfassungen am Ende einer Notiz, oder eines Absatzes:
|
||||||
|
|
||||||
```markdown
|
```markdown
|
||||||
> [!edge] related_to: [[Vector Embeddings]] [[AI Agents]]
|
> [!edge] related_to
|
||||||
|
> [[Vector Embeddings]]
|
||||||
|
> [[AI Agents]]
|
||||||
```
|
```
|
||||||
|
|
||||||
|
**Multi-Line Support (v2.9.1):**
|
||||||
|
Callout-Blocks mit mehreren Zeilen werden korrekt verarbeitet. Das System erkennt automatisch, wenn mehrere Links im gleichen Callout-Block stehen, und erstellt für jeden Link eine separate Kante (auch bei Deep-Links zu verschiedenen Sections).
|
||||||
|
|
||||||
|
**Format-agnostische De-Duplizierung:**
|
||||||
|
Wenn Kanten bereits via `[!edge]` Callout vorhanden sind, werden sie nicht mehrfach injiziert. Das System erkennt vorhandene Kanten unabhängig vom Format (Inline, Callout, Wikilink).
|
||||||
|
|
||||||
|
### 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)
|
## 5. Schreiben für den KI-Zwilling (Szenarien)
|
||||||
|
|
||||||
Damit der **RAG-Chat** dich berät, musst du "Futter" für die Decision Engine liefern.
|
Damit der **RAG-Chat** dich berät, musst du "Futter" für die Decision Engine liefern.
|
||||||
|
|
||||||
### Szenario A: Decision Engine (`DECISION`)
|
### 5.1 Szenario A: Decision Engine (`DECISION`)
|
||||||
* **Ziel:** Das System soll abwägen: "Passt Tool X zu mir?"
|
* **Ziel:** Das System soll abwägen: "Passt Tool X zu mir?"
|
||||||
* **Vorgehen:** Erstelle Notizen mit `type: value` oder `type: goal`.
|
* **Vorgehen:** Erstelle Notizen mit `type: value` oder `type: goal`.
|
||||||
|
|
||||||
**Beispiel Notiz:**
|
|
||||||
```yaml
|
|
||||||
---
|
|
||||||
type: value
|
|
||||||
title: Prinzip: Datensparsamkeit
|
|
||||||
---
|
|
||||||
Wir speichern nur das Minimum an Daten. Cloud-Uploads persönlicher Daten sind verboten, es sei denn, sie sind E2E-verschlüsselt.
|
|
||||||
```
|
|
||||||
|
|
||||||
* **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."*
|
* **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`)
|
### Szenario B: Empathie (`EMPATHY`)
|
||||||
@@ -168,6 +280,22 @@ 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.
|
* **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. Best Practices & Beispiele
|
||||||
@@ -204,9 +332,6 @@ title: ADR: Wahl von Qdrant
|
|||||||
type: decision
|
type: decision
|
||||||
status: final
|
status: final
|
||||||
tags: [architektur, db]
|
tags: [architektur, db]
|
||||||
# OVERRIDES: Wir wollen diese Notiz extrem wichtig machen und strikt trennen.
|
|
||||||
# Da "strict" genutzt wird, landet "Alternativen" in einem eigenen Chunk
|
|
||||||
# und vermischt sich nicht mit der Entscheidung selbst.
|
|
||||||
chunking_profile: structured_smart_edges_strict
|
chunking_profile: structured_smart_edges_strict
|
||||||
retriever_weight: 1.5
|
retriever_weight: 1.5
|
||||||
---
|
---
|
||||||
@@ -224,4 +349,4 @@ Wir haben auch [[rel:similar_to Pinecone]] und [[rel:similar_to Weaviate]] betra
|
|||||||
## 7. Virtual Schema Layer
|
## 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.
|
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 oben genannten Overrides (`chunking_profile`) jederzeit die Möglichkeit, aus diesem Standard auszubrechen, wenn eine spezifische Notiz eine Sonderbehandlung benötigt.
|
**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.
|
||||||
@@ -1,73 +1,151 @@
|
|||||||
---
|
---
|
||||||
doc_type: concept
|
doc_type: concept
|
||||||
audience: architect, product_owner
|
audience: architect, product_owner
|
||||||
scope: ai, router, personas
|
scope: ai, router, personas, resilience, agentic_rag, moe, lazy_prompts
|
||||||
status: active
|
status: active
|
||||||
version: 2.6
|
version: 3.1.1
|
||||||
context: "Fachkonzept der KI-Persönlichkeit, der Decision Engine und Erweiterungsstrategien."
|
context: "Fachkonzept der hybriden KI-Persönlichkeit, Agentic Multi-Stream RAG, WP-25a Mixture of Experts (MoE), WP-25b Lazy-Prompt-Orchestration, Provider-Kaskade und kognitiven Resilienz (Deep Fallback)."
|
||||||
---
|
---
|
||||||
|
|
||||||
# Konzept: KI-Persönlichkeit & Router
|
# Konzept: KI-Persönlichkeit & Router
|
||||||
|
|
||||||
**Quellen:** `mindnet_functional_architecture.md`, `Programmplan_V2.2.md`
|
**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" anpassen.
|
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)
|
## 1. Der Hybrid Router & Agentic Multi-Stream RAG (Das Gehirn)
|
||||||
|
|
||||||
Jede Eingabe durchläuft den **Hybrid Router**. Er entscheidet über die Strategie.
|
Jede Eingabe durchläuft den **Hybrid Router**. Seit WP-25 agiert das System als **Agentic Orchestrator**, der Nutzeranfragen analysiert, in parallele Wissens-Streams aufteilt und diese zu einer kontextreichen, wertebasierten Antwort synthetisiert.
|
||||||
|
|
||||||
### Modus A: RAG (Retrieval Augmented Generation)
|
### Intent-basiertes Routing (WP-25)
|
||||||
* *Intent:* Der Nutzer hat eine Frage oder ein Problem (`FACT`, `DECISION`, `EMPATHY`).
|
|
||||||
* *Aktion:* Das System sucht im Gedächtnis und generiert eine Antwort.
|
Der Router nutzt einen **Hybrid-Modus** mit Keyword Fast-Path und LLM Slow-Path:
|
||||||
|
|
||||||
|
**Keyword Fast-Path:**
|
||||||
|
* Sofortige Erkennung von Triggern wie "Soll ich", "Wann", "Was ist"
|
||||||
|
* Reduziert Latenz durch schnelle Keyword-Erkennung ohne LLM-Call
|
||||||
|
|
||||||
|
**LLM Slow-Path:**
|
||||||
|
* Komplexe semantische Analyse für unklare Anfragen
|
||||||
|
* Nutzt `intent_router_v1` Prompt zur Klassifizierung
|
||||||
|
|
||||||
|
**Strategien:**
|
||||||
|
* **FACT_WHAT/FACT_WHEN:** Wissensabfrage (Wissen/Listen, Zeitpunkte)
|
||||||
|
* **DECISION:** Beratung (Rat, Strategie, Abwägung)
|
||||||
|
* **EMPATHY:** Reflexion (Emotionale Resonanz)
|
||||||
|
* **CODING:** Technik (Programmierung, Syntax)
|
||||||
|
* **INTERVIEW:** Datenerfassung (Wissen speichern)
|
||||||
|
|
||||||
|
### Modus A: Agentic Multi-Stream RAG (WP-25)
|
||||||
|
|
||||||
|
Anstelle einer einzelnen Suche führt das System **parallele Abfragen** in spezialisierten Wissens-Streams aus:
|
||||||
|
|
||||||
|
**Stream-Library:**
|
||||||
|
* **Values Stream:** Identität, Ethik und Prinzipien (`value`, `principle`, `belief`, `trait`, `boundary`, `need`, `motivation`)
|
||||||
|
* **Facts Stream:** Operative Daten (`project`, `decision`, `task`, `goal`, `event`, `state`)
|
||||||
|
* **Biography Stream:** Persönliche Erfahrungen (`experience`, `journal`, `profile`, `person`)
|
||||||
|
* **Risk Stream:** Hindernisse und Gefahren (`risk`, `obstacle`, `bias`)
|
||||||
|
* **Tech Stream:** Technisches Wissen (`concept`, `source`, `glossary`, `idea`, `insight`, `skill`, `habit`)
|
||||||
|
|
||||||
|
**Wissens-Synthese:**
|
||||||
|
Die Zusammenführung erfolgt über spezialisierte Templates mit expliziten Stream-Variablen (z.B. `{values_stream}`, `{risk_stream}`). Dies ermöglicht dem LLM eine differenzierte Abwägung zwischen Fakten und persönlichen Werten.
|
||||||
|
|
||||||
|
**Stream-Tracing:**
|
||||||
|
Jeder Treffer wird mit `stream_origin` markiert, um Feedback-Optimierung pro Wissensbereich zu ermöglichen.
|
||||||
|
|
||||||
### Modus B: Interview (Knowledge Capture)
|
### Modus B: Interview (Knowledge Capture)
|
||||||
* *Intent:* Der Nutzer will Wissen speichern (`INTERVIEW`).
|
* **Intent:** Der Nutzer will Wissen speichern (`INTERVIEW`).
|
||||||
* *Aktion:* Das System sucht **nicht**, sondern fragt ab und erstellt einen Draft.
|
* **Aktion:** Das System sucht **nicht**, sondern fragt ab und erstellt einen Draft.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 2. Die Personas (Strategien)
|
## 2. Mixture of Experts (MoE) Architektur (WP-25a)
|
||||||
|
|
||||||
|
Seit WP-25a nutzt MindNet eine **profilbasierte Experten-Steuerung** statt einer globalen Provider-Konfiguration. Jede Systemaufgabe wird einem dedizierten Profil zugewiesen, das Modell, Provider und Parameter unabhängig definiert.
|
||||||
|
|
||||||
|
### 2.1 Experten-Profile
|
||||||
|
|
||||||
|
**Zentrale Registry (`llm_profiles.yaml`):**
|
||||||
|
* **`synthesis_pro`:** Hochwertige Synthese für Chat-Antworten (Cloud)
|
||||||
|
* **`tech_expert`:** Fachspezialist für Code & Technik (Claude 3.5 Sonnet)
|
||||||
|
* **`compression_fast`:** Schnelle Kompression & Routing (Mistral 7B)
|
||||||
|
* **`ingest_validator`:** Deterministische Validierung (Temperature 0.0)
|
||||||
|
* **`identity_safe`:** Lokaler Anker (Ollama/Phi-3) für maximale Privacy
|
||||||
|
|
||||||
|
**Vorteile:**
|
||||||
|
* **Aufgabenspezifische Optimierung:** Jede Aufgabe nutzt das optimale Modell
|
||||||
|
* **Hardware-Optimierung:** Lokaler Anker für kleine Hardware-Umgebungen
|
||||||
|
* **Wartbarkeit:** Zentrale Konfiguration statt verstreuter ENV-Variablen
|
||||||
|
|
||||||
|
### 2.2 Rekursive Fallback-Kaskade
|
||||||
|
|
||||||
|
Die Profile implementieren eine **automatische Fallback-Logik**:
|
||||||
|
|
||||||
|
1. **Primäres Profil:** System versucht das angeforderte Profil (z.B. `synthesis_pro`)
|
||||||
|
2. **Fallback-Level 1:** Bei Fehler → `fallback_profile` (z.B. `synthesis_backup`)
|
||||||
|
3. **Fallback-Level 2:** Bei weiterem Fehler → nächster Fallback (z.B. `identity_safe`)
|
||||||
|
4. **Terminaler Endpunkt:** `identity_safe` hat keinen Fallback (lokales Modell als letzte Instanz)
|
||||||
|
|
||||||
|
**Schutzmechanismen:**
|
||||||
|
* **Zirkuläre Referenzen:** `visited_profiles`-Tracking verhindert Endlosschleifen
|
||||||
|
* **Background-Semaphore:** Parallele Tasks werden gedrosselt
|
||||||
|
|
||||||
|
### 2.3 Die hybride LLM-Landschaft (Legacy & MoE)
|
||||||
|
|
||||||
|
Ein intelligenter Zwilling muss jederzeit verfügbar sein. Seit WP-25a wird die Resilienz durch die **MoE Fallback-Kaskade** gewährleistet:
|
||||||
|
|
||||||
|
1. **Stufe 1: Cloud-Experten:** Spezialisierte Profile für verschiedene Aufgaben (z.B. `synthesis_pro`, `tech_expert`)
|
||||||
|
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: Lokale Souveränität (Ollama):**
|
||||||
|
* **Technischer Fallback:** Schlagen alle Cloud-Versuche fehl, übernimmt das lokale Modell (Phi-3) via `identity_safe` Profil.
|
||||||
|
* **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.
|
Mindnet wechselt den Hut, je nach Situation.
|
||||||
|
|
||||||
### 2.1 Der Berater (Strategy: DECISION)
|
### 3.1 Der Berater (Strategy: DECISION)
|
||||||
* **Auslöser:** Fragen wie "Soll ich...?", "Was ist besser?".
|
* **Auslöser:** Fragen wie „Soll ich...?", „Was ist besser?", „Empfehlung...".
|
||||||
* **Strategic Retrieval:** Lädt aktiv Notizen der Typen `value` (Werte), `goal` (Ziele) und `risk` (Risiken), auch wenn sie im Text nicht direkt vorkommen.
|
* **Multi-Stream Retrieval (WP-25):** Führt parallele Abfragen in Values Stream, Facts Stream und Risk Stream aus.
|
||||||
* **Reasoning:** *"Wäge die Fakten gegen meine Werte ab. Sei strikt bei Risiken."*
|
* **Wissens-Synthese:** Wägt Fakten gegen Werte ab, evaluiert Risiken und prüft Kompatibilität mit langfristiger Identität.
|
||||||
|
* **Reasoning:** *„Wäge die Fakten gegen meine Werte ab. Sei strikt bei Risiken."*
|
||||||
|
|
||||||
### 2.2 Der Spiegel (Strategy: EMPATHY)
|
### 3.2 Der Spiegel (Strategy: EMPATHY)
|
||||||
* **Auslöser:** Emotionale Aussagen ("Ich bin frustriert").
|
* **Auslöser:** Emotionale Aussagen („Ich bin frustriert", „Ich fühle...", „Stress...").
|
||||||
* **Strategic Retrieval:** Lädt `experience` (Erfahrungen) und `belief` (Glaubenssätze).
|
* **Multi-Stream Retrieval (WP-25):** Führt parallele Abfragen in Biography Stream und Values Stream aus.
|
||||||
* **Reasoning:** *"Nutze meine eigenen Erfahrungen, um die Situation einzuordnen."*
|
* **Wissens-Synthese:** Greift auf persönliche Erfahrungen und Werte zurück, um emotionale Resonanz zu schaffen.
|
||||||
|
* **Reasoning:** *„Nutze meine eigenen Erfahrungen, um die Situation einzuordnen."*
|
||||||
|
|
||||||
### 2.3 Der Bibliothekar (Strategy: FACT)
|
### 3.3 Der Bibliothekar (Strategy: FACT_WHAT / FACT_WHEN)
|
||||||
* **Auslöser:** Sachfragen ("Was ist Qdrant?").
|
* **Auslöser:** Sachfragen („Was ist...?", „Welche sind...?", „Wann...?", „Datum...").
|
||||||
* **Behavior:** Präzise, neutral, kurz.
|
* **Multi-Stream Retrieval (WP-25):** Führt parallele Abfragen in Facts Stream, Tech Stream und Biography Stream aus.
|
||||||
|
* **Wissens-Synthese:** Kombiniert harte Fakten mit persönlichen Erfahrungen, falls vorhanden.
|
||||||
|
* **Behavior:** Präzise, neutral, strukturiert.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 3. Future Concepts: The Empathic Digital Twin
|
## 4. Future Concepts: The Empathic Digital Twin
|
||||||
|
|
||||||
Um Mindnet von einer Maschine zu einem echten Spiegel der Persönlichkeit zu entwickeln, sind folgende Konzepte in der Architektur angelegt:
|
### 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).
|
||||||
|
|
||||||
### 3.1 Antizipation durch Erfahrung
|
### 4.2 Empathie & „Ich“-Modus
|
||||||
* **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).
|
|
||||||
|
|
||||||
### 3.2 Empathie & "Ich"-Modus
|
|
||||||
* **Konzept:** Das System antwortet im Tonfall des Nutzers.
|
* **Konzept:** Das System antwortet im Tonfall des Nutzers.
|
||||||
* **Umsetzung:** Few-Shot Prompting mit eigenen E-Mails/Texten als Stilvorlage.
|
* **Umsetzung:** Few-Shot Prompting mit eigenen E-Mails/Texten als Stilvorlage.
|
||||||
|
|
||||||
### 3.3 Glaubenssätze & Rituale
|
### 4.3 Resilienz als Charakterzug
|
||||||
* **Konzept:** Berücksichtigung weicher Faktoren.
|
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.
|
||||||
* **Szenario:** Bei Terminplanungen werden Rituale ("Keine Meetings vor 10 Uhr") automatisch als harte Restriktion gegen Anfragen geprüft.
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 4. Erweiterbarkeit: Das "Teach-the-AI" Paradigma
|
## 5. Erweiterbarkeit: Das „Teach-the-AI“ Paradigma
|
||||||
|
|
||||||
Mindnet lernt nicht durch Training (Fine-Tuning), sondern durch **Konfiguration** und **Vernetzung**. Wenn du dem System ein neues Konzept beibringen willst, musst du an drei Stellen eingreifen.
|
Mindnet lernt durch **Konfiguration** und **Vernetzung**.
|
||||||
|
|
||||||
**Beispiel: Du willst den Typ `risk` einführen.**
|
**Beispiel: Du willst den Typ `risk` einführen.**
|
||||||
|
|
||||||
@@ -87,6 +165,6 @@ DECISION:
|
|||||||
```
|
```
|
||||||
|
|
||||||
**3. Kognitive Ebene (Verständnis)**
|
**3. Kognitive Ebene (Verständnis)**
|
||||||
In `prompts.yaml`: Erkläre dem LLM, was ein Risiko ist.
|
In `prompts.yaml`: Erkläre dem LLM (provider-spezifisch mittels der Prompt-Kaskade), was ein Risiko ist.
|
||||||
|
|
||||||
**Fazit:** Nur wenn **Daten** (Vault), **Physik** (Config) und **Semantik** (Prompt) zusammenspielen, entsteht ein intelligenter Zwilling.
|
**Fazit:** Nur wenn **Daten** (Vault), **Infrastruktur** (Resiliente Kaskade) und **Semantik** (Prompt) zusammenspielen, entsteht ein intelligenter Zwilling.
|
||||||
@@ -0,0 +1,456 @@
|
|||||||
|
---
|
||||||
|
doc_type: concept
|
||||||
|
audience: architect, developer
|
||||||
|
scope: architecture, design_patterns, modularization
|
||||||
|
status: active
|
||||||
|
version: 2.9.1
|
||||||
|
context: "Architektur-Patterns, Design-Entscheidungen und modulare Struktur von Mindnet. Basis für Verständnis und Erweiterungen."
|
||||||
|
---
|
||||||
|
|
||||||
|
# Architektur-Patterns & Design-Entscheidungen
|
||||||
|
|
||||||
|
Dieses Dokument beschreibt die zentralen Architektur-Patterns und Design-Entscheidungen, die Mindnet prägen. Es dient als Referenz für Entwickler und Architekten, um das System zu verstehen und konsistent zu erweitern.
|
||||||
|
|
||||||
|
## 1. Kern-Paradigmen
|
||||||
|
|
||||||
|
### 1.1 Filesystem First (Source of Truth)
|
||||||
|
|
||||||
|
**Prinzip:** Markdown-Dateien im Vault sind die einzige Quelle der Wahrheit. Die Datenbank (Qdrant) ist ein abgeleiteter Index.
|
||||||
|
|
||||||
|
**Implikationen:**
|
||||||
|
- Dateien werden immer direkt von der Festplatte gelesen (z.B. im Editor)
|
||||||
|
- Datenbank-Inhalte können aus Markdown rekonstruiert werden
|
||||||
|
- Änderungen erfolgen primär im Vault, nicht in der DB
|
||||||
|
- Die Datenbank ist ein Cache, kein primärer Speicher
|
||||||
|
|
||||||
|
**Code-Beispiele:**
|
||||||
|
- `ui_callbacks.py`: Liest Dateien direkt von Disk
|
||||||
|
- `ingestion_processor.py`: Schreibt zuerst auf Disk, dann in DB
|
||||||
|
|
||||||
|
### 1.2 Late Binding (Späte Semantik)
|
||||||
|
|
||||||
|
**Prinzip:** Struktur und Interpretation werden in Konfigurationen definiert, nicht im Code.
|
||||||
|
|
||||||
|
**Implikationen:**
|
||||||
|
- Neue Note-Typen werden in `types.yaml` definiert, nicht im Code
|
||||||
|
- Prompt-Templates sind in `prompts.yaml` konfigurierbar
|
||||||
|
- Edge-Typen werden in `edge_vocabulary.md` verwaltet
|
||||||
|
- Die "Persönlichkeit" ist Config, kein Code
|
||||||
|
|
||||||
|
**Vorteile:**
|
||||||
|
- Erweiterbarkeit ohne Code-Änderungen
|
||||||
|
- A/B-Testing von Prompt-Strategien
|
||||||
|
- Anpassung an verschiedene Use-Cases
|
||||||
|
|
||||||
|
### 1.3 Virtual Schema Layer
|
||||||
|
|
||||||
|
**Prinzip:** Markdown-Dateien benötigen nur minimale Frontmatter-Angaben. Komplexität wird zur Laufzeit injiziert.
|
||||||
|
|
||||||
|
**Beispiel:**
|
||||||
|
```yaml
|
||||||
|
# Minimal im Frontmatter
|
||||||
|
---
|
||||||
|
id: 20250101-test
|
||||||
|
title: Test
|
||||||
|
type: project
|
||||||
|
---
|
||||||
|
|
||||||
|
# Im Code wird zur Laufzeit ergänzt:
|
||||||
|
# - chunking_profile aus types.yaml
|
||||||
|
# - retriever_weight aus types.yaml
|
||||||
|
# - edge_defaults aus types.yaml
|
||||||
|
```
|
||||||
|
|
||||||
|
**Vorteile:**
|
||||||
|
- Robuste Markdown-Dateien (weniger Breaking Changes)
|
||||||
|
- Zentrale Verwaltung von Logik
|
||||||
|
- Einfache Migration zwischen Versionen
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Modulare Architektur (WP-14)
|
||||||
|
|
||||||
|
### 2.1 Paket-Struktur
|
||||||
|
|
||||||
|
Seit WP-14 ist die Core-Logik in spezialisierte Pakete unterteilt:
|
||||||
|
|
||||||
|
```
|
||||||
|
app/core/
|
||||||
|
├── chunking/ # Text-Segmentierung
|
||||||
|
│ ├── chunking_strategies.py # Sliding/Heading-Strategien
|
||||||
|
│ ├── chunking_processor.py # Orchestrierung
|
||||||
|
│ └── chunking_propagation.py # Edge-Vererbung
|
||||||
|
├── database/ # Qdrant-Infrastruktur
|
||||||
|
│ ├── qdrant.py # Client & Config
|
||||||
|
│ └── qdrant_points.py # Point-Mapping
|
||||||
|
├── graph/ # Graph-Logik
|
||||||
|
│ ├── graph_subgraph.py # Expansion
|
||||||
|
│ └── graph_weights.py # Scoring
|
||||||
|
├── ingestion/ # Import-Pipeline
|
||||||
|
│ ├── ingestion_processor.py # Two-Pass Workflow
|
||||||
|
│ └── ingestion_validation.py # Mistral-safe Parsing
|
||||||
|
├── parser/ # Markdown-Parsing
|
||||||
|
│ ├── parsing_markdown.py # Frontmatter/Body
|
||||||
|
│ └── parsing_scanner.py # File-Scan
|
||||||
|
└── retrieval/ # Suche & Scoring
|
||||||
|
├── retriever.py # Orchestrator
|
||||||
|
└── retriever_scoring.py # Mathematik
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2.2 Design-Pattern: Proxy-Adapter (Abwärtskompatibilität)
|
||||||
|
|
||||||
|
**Problem:** Nach WP-14 Modularisierung müssen alte Import-Pfade weiter funktionieren.
|
||||||
|
|
||||||
|
**Lösung:** Proxy-Module leiten Anfragen an neue Pakete weiter.
|
||||||
|
|
||||||
|
**Beispiel:**
|
||||||
|
```python
|
||||||
|
# app/core/retriever.py (Proxy)
|
||||||
|
from .retrieval.retriever import (
|
||||||
|
Retriever, hybrid_retrieve, semantic_retrieve
|
||||||
|
)
|
||||||
|
__all__ = ["Retriever", "hybrid_retrieve", "semantic_retrieve"]
|
||||||
|
```
|
||||||
|
|
||||||
|
**Vorteile:**
|
||||||
|
- Keine Breaking Changes für bestehenden Code
|
||||||
|
- Graduelle Migration möglich
|
||||||
|
- Alte Scripts funktionieren weiter
|
||||||
|
|
||||||
|
### 2.3 Design-Pattern: Singleton (Edge Registry)
|
||||||
|
|
||||||
|
**Problem:** Edge Registry muss konsistent über alle Services sein.
|
||||||
|
|
||||||
|
**Lösung:** Singleton-Pattern mit Lazy Loading.
|
||||||
|
|
||||||
|
**Code:**
|
||||||
|
```python
|
||||||
|
# app/services/edge_registry.py
|
||||||
|
class EdgeRegistry:
|
||||||
|
_instance = None
|
||||||
|
|
||||||
|
def __new__(cls):
|
||||||
|
if cls._instance is None:
|
||||||
|
cls._instance = super().__new__(cls)
|
||||||
|
return cls._instance
|
||||||
|
```
|
||||||
|
|
||||||
|
**Vorteile:**
|
||||||
|
- Einheitliche Validierung
|
||||||
|
- Keine Duplikation von Vokabular-Daten
|
||||||
|
- Thread-safe Initialisierung
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Asynchrone Verarbeitung
|
||||||
|
|
||||||
|
### 3.1 Background Tasks Pattern
|
||||||
|
|
||||||
|
**Problem:** Ingestion kann lange dauern (LLM-Calls, Embeddings). Blockiert API nicht.
|
||||||
|
|
||||||
|
**Lösung:** FastAPI Background Tasks für non-blocking Verarbeitung.
|
||||||
|
|
||||||
|
**Flow:**
|
||||||
|
1. API empfängt Request (`/ingest/save`)
|
||||||
|
2. Datei wird sofort auf Disk geschrieben
|
||||||
|
3. API antwortet mit `status: "queued"`
|
||||||
|
4. Background Task startet Ingestion asynchron
|
||||||
|
5. User kann weiterarbeiten
|
||||||
|
|
||||||
|
**Code:**
|
||||||
|
```python
|
||||||
|
@router.post("/save")
|
||||||
|
async def save_note(req: SaveRequest, background_tasks: BackgroundTasks):
|
||||||
|
# Sofortige Persistenz
|
||||||
|
write_to_disk(req.markdown_content)
|
||||||
|
|
||||||
|
# Async Processing
|
||||||
|
background_tasks.add_task(run_ingestion_task, ...)
|
||||||
|
|
||||||
|
return SaveResponse(status="queued", ...)
|
||||||
|
```
|
||||||
|
|
||||||
|
**Vorteile:**
|
||||||
|
- Keine Timeouts bei großen Dateien
|
||||||
|
- Bessere User Experience
|
||||||
|
- System bleibt responsiv
|
||||||
|
|
||||||
|
### 3.2 Traffic Control (Semaphore Pattern)
|
||||||
|
|
||||||
|
**Problem:** Parallele LLM-Calls können System überlasten.
|
||||||
|
|
||||||
|
**Lösung:** Semaphore begrenzt parallele Hintergrund-Tasks.
|
||||||
|
|
||||||
|
**Code:**
|
||||||
|
```python
|
||||||
|
# app/services/llm_service.py
|
||||||
|
background_semaphore = asyncio.Semaphore(
|
||||||
|
settings.BACKGROUND_LIMIT # Default: 2
|
||||||
|
)
|
||||||
|
|
||||||
|
async def generate(...):
|
||||||
|
if priority == "background":
|
||||||
|
async with background_semaphore:
|
||||||
|
return await _call_llm(...)
|
||||||
|
else: # realtime
|
||||||
|
return await _call_llm(...) # Keine Limitierung
|
||||||
|
```
|
||||||
|
|
||||||
|
**Vorteile:**
|
||||||
|
- Schutz vor API-Quoten-Überschreitung
|
||||||
|
- Stabiler Betrieb bei hoher Last
|
||||||
|
- Priorisierung von Echtzeit-Anfragen
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Resilienz-Patterns
|
||||||
|
|
||||||
|
### 4.1 Provider-Kaskade (Fallback-Kette)
|
||||||
|
|
||||||
|
**Problem:** Cloud-Provider können ausfallen oder Quoten überschreiten.
|
||||||
|
|
||||||
|
**Lösung:** Dreistufige Kaskade mit intelligentem Fallback.
|
||||||
|
|
||||||
|
**Stufen:**
|
||||||
|
1. **Cloud (OpenRouter/Gemini):** Schnell, aber abhängig von Provider
|
||||||
|
2. **Rate-Limit-Handling:** Automatische Retries bei HTTP 429
|
||||||
|
3. **Lokaler Fallback (Ollama):** Langsam, aber immer verfügbar
|
||||||
|
|
||||||
|
**Code:**
|
||||||
|
```python
|
||||||
|
# app/services/llm_service.py
|
||||||
|
async def generate(...):
|
||||||
|
try:
|
||||||
|
return await _call_cloud(...)
|
||||||
|
except RateLimitError:
|
||||||
|
await asyncio.sleep(LLM_RATE_LIMIT_WAIT)
|
||||||
|
return await _call_cloud(...) # Retry
|
||||||
|
except Exception:
|
||||||
|
return await _call_ollama(...) # Fallback
|
||||||
|
```
|
||||||
|
|
||||||
|
**Vorteile:**
|
||||||
|
- Hohe Verfügbarkeit
|
||||||
|
- Kostenoptimierung (Cloud für Speed, Lokal für Fallback)
|
||||||
|
- Resilienz gegen Provider-Ausfälle
|
||||||
|
|
||||||
|
### 4.2 Deep Fallback (Kognitiver Fallback)
|
||||||
|
|
||||||
|
**Problem:** Cloud liefert technisch erfolgreiche, aber inhaltlich leere Antworten (Silent Refusal).
|
||||||
|
|
||||||
|
**Lösung:** Validierung der Antwort-Qualität, nicht nur HTTP-Status.
|
||||||
|
|
||||||
|
**Code:**
|
||||||
|
```python
|
||||||
|
response = await _call_cloud(...)
|
||||||
|
if is_valid_json(response):
|
||||||
|
return response
|
||||||
|
else:
|
||||||
|
# Deep Fallback: Cloud hat blockiert, lokaler Fallback
|
||||||
|
return await _call_ollama(...)
|
||||||
|
```
|
||||||
|
|
||||||
|
**Vorteile:**
|
||||||
|
- Erkennung von Policy-Violations
|
||||||
|
- Datenintegrität trotz Cloud-Filter
|
||||||
|
- Lokale Souveränität
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Datenfluss-Patterns
|
||||||
|
|
||||||
|
### 5.1 Two-Pass Workflow (WP-15b)
|
||||||
|
|
||||||
|
**Problem:** Smart Edge Validation benötigt globalen Kontext (alle Notizen).
|
||||||
|
|
||||||
|
**Lösung:** Zwei-Phasen-Import mit Pre-Scan.
|
||||||
|
|
||||||
|
**Pass 1: Pre-Scan**
|
||||||
|
- Schnelles Scannen aller Dateien
|
||||||
|
- Aufbau von `LocalBatchCache` (IDs, Titel, Summaries)
|
||||||
|
- Keine LLM-Calls
|
||||||
|
|
||||||
|
**Pass 2: Semantic Processing**
|
||||||
|
- Nur für geänderte Dateien
|
||||||
|
- Binäre Validierung gegen Cache
|
||||||
|
- Effiziente Nutzung von LLM-Quoten
|
||||||
|
|
||||||
|
**Vorteile:**
|
||||||
|
- Reduktion von LLM-Calls (nur Validierung, keine Extraktion)
|
||||||
|
- Konsistente Validierung (globaler Kontext)
|
||||||
|
- Schnellerer Import
|
||||||
|
|
||||||
|
### 5.2 Idempotenz-Pattern
|
||||||
|
|
||||||
|
**Prinzip:** Mehrfache Imports derselben Datei führen zum gleichen Ergebnis.
|
||||||
|
|
||||||
|
**Mechanismen:**
|
||||||
|
- **Deterministische IDs:** UUIDv5 basierend auf Datei-Inhalt
|
||||||
|
- **Hash-basierte Change Detection:** Multi-Hash für `body` und `full`
|
||||||
|
- **Deduplizierung:** Kanten werden anhand Identität erkannt
|
||||||
|
|
||||||
|
**Code:**
|
||||||
|
```python
|
||||||
|
# Deterministische ID
|
||||||
|
note_id = uuid.uuid5(NAMESPACE_URL, f"{file_path}#{content_hash}")
|
||||||
|
|
||||||
|
# Change Detection
|
||||||
|
if current_hash == stored_hash:
|
||||||
|
skip_processing() # Idempotent
|
||||||
|
```
|
||||||
|
|
||||||
|
**Vorteile:**
|
||||||
|
- Sicherheit bei Re-Imports
|
||||||
|
- Keine Duplikate
|
||||||
|
- Konsistente Datenbank
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Frontend-Patterns
|
||||||
|
|
||||||
|
### 6.1 Active Inspector Pattern
|
||||||
|
|
||||||
|
**Problem:** Graph-Re-Renders bei Knoten-Selektion führen zu Flackern.
|
||||||
|
|
||||||
|
**Lösung:** CSS-Klassen statt State-Änderungen für Selektion.
|
||||||
|
|
||||||
|
**Code:**
|
||||||
|
```python
|
||||||
|
# ui_graph_cytoscape.py
|
||||||
|
stylesheet = [
|
||||||
|
{
|
||||||
|
"selector": ".inspected",
|
||||||
|
"style": {"border-width": 6, "border-color": "#FFC300"}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
# Selektion ändert nur CSS-Klasse, nicht React-Key
|
||||||
|
```
|
||||||
|
|
||||||
|
**Vorteile:**
|
||||||
|
- Stabiles UI (kein Re-Render)
|
||||||
|
- Bessere Performance
|
||||||
|
- Smooth User Experience
|
||||||
|
|
||||||
|
### 6.2 Resurrection Pattern
|
||||||
|
|
||||||
|
**Problem:** Streamlit vergisst Eingaben bei Re-Runs.
|
||||||
|
|
||||||
|
**Lösung:** Aggressive Synchronisation in `session_state`.
|
||||||
|
|
||||||
|
**Code:**
|
||||||
|
```python
|
||||||
|
# ui_editor.py
|
||||||
|
if widget_key not in st.session_state:
|
||||||
|
st.session_state[widget_key] = restore_from_data_key()
|
||||||
|
```
|
||||||
|
|
||||||
|
**Vorteile:**
|
||||||
|
- Texteingaben überleben Tab-Wechsel
|
||||||
|
- Keine Datenverluste
|
||||||
|
- Bessere UX
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. Erweiterbarkeit: "Teach-the-AI" Paradigma
|
||||||
|
|
||||||
|
Mindnet lernt durch **Konfiguration**, nicht durch Training.
|
||||||
|
|
||||||
|
### 7.1 Drei-Ebenen-Erweiterung
|
||||||
|
|
||||||
|
**1. Daten-Ebene (`types.yaml`):**
|
||||||
|
```yaml
|
||||||
|
risk:
|
||||||
|
retriever_weight: 0.90
|
||||||
|
edge_defaults: ["blocks"]
|
||||||
|
```
|
||||||
|
|
||||||
|
**2. Strategie-Ebene (`decision_engine.yaml`):**
|
||||||
|
```yaml
|
||||||
|
DECISION:
|
||||||
|
inject_types: ["value", "risk"]
|
||||||
|
```
|
||||||
|
|
||||||
|
**3. Kognitive Ebene (`prompts.yaml`):**
|
||||||
|
```yaml
|
||||||
|
risk_definition:
|
||||||
|
ollama: "Ein Risiko ist eine potenzielle Gefahr..."
|
||||||
|
```
|
||||||
|
|
||||||
|
**Vorteile:**
|
||||||
|
- Keine Code-Änderungen nötig
|
||||||
|
- Schnelle Iteration
|
||||||
|
- A/B-Testing möglich
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. Design-Entscheidungen & Trade-offs
|
||||||
|
|
||||||
|
### 8.1 Qdrant als Vektor-DB
|
||||||
|
|
||||||
|
**Entscheidung:** Qdrant statt Pinecone/Weaviate
|
||||||
|
|
||||||
|
**Gründe:**
|
||||||
|
- Self-hosted (Privacy First)
|
||||||
|
- Open Source
|
||||||
|
- Gute Performance bei lokaler Installation
|
||||||
|
|
||||||
|
**Trade-off:** Mehr Wartungsaufwand als Managed Service
|
||||||
|
|
||||||
|
### 8.2 Hybrid Retrieval (Semantik + Graph)
|
||||||
|
|
||||||
|
**Entscheidung:** Kombination von Vektor-Suche und Graph-Expansion
|
||||||
|
|
||||||
|
**Gründe:**
|
||||||
|
- Semantik findet ähnliche Inhalte
|
||||||
|
- Graph findet strukturelle Verbindungen
|
||||||
|
- Kombination liefert bessere Relevanz
|
||||||
|
|
||||||
|
**Trade-off:** Höhere Komplexität, mehr Berechnungsaufwand
|
||||||
|
|
||||||
|
### 8.3 Background Tasks statt Queue-System
|
||||||
|
|
||||||
|
**Entscheidung:** FastAPI Background Tasks statt Redis/RabbitMQ
|
||||||
|
|
||||||
|
**Gründe:**
|
||||||
|
- Einfacher Setup (keine zusätzliche Infrastruktur)
|
||||||
|
- Ausreichend für Single-User-Szenario
|
||||||
|
- Weniger Moving Parts
|
||||||
|
|
||||||
|
**Trade-off:** Keine Persistenz bei Server-Neustart (Tasks gehen verloren)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9. Konsistenz-Garantien
|
||||||
|
|
||||||
|
### 9.1 Deterministische IDs
|
||||||
|
|
||||||
|
**Prinzip:** UUIDv5 basierend auf Datei-Inhalt
|
||||||
|
|
||||||
|
**Vorteile:**
|
||||||
|
- Reproduzierbare IDs
|
||||||
|
- Keine Duplikate bei Re-Import
|
||||||
|
- Graph ist aus Markdown rekonstruierbar
|
||||||
|
|
||||||
|
### 9.2 Provenance-Hierarchie
|
||||||
|
|
||||||
|
**Prinzip:** Kanten haben Qualitätsstufen (explicit > smart > rule)
|
||||||
|
|
||||||
|
**Vorteile:**
|
||||||
|
- Menschliche Intention hat Vorrang
|
||||||
|
- System-Heuristiken können überschrieben werden
|
||||||
|
- Transparente Gewichtung
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 10. Weitere Informationen
|
||||||
|
|
||||||
|
- **Vision & Strategie:** Siehe [Vision & Strategie](../00_General/00_vision_and_strategy.md)
|
||||||
|
- **Graph-Logik:** Siehe [Graph-Logik](02_concept_graph_logic.md)
|
||||||
|
- **KI-Persönlichkeit:** Siehe [KI-Persönlichkeit](02_concept_ai_personality.md)
|
||||||
|
- **Developer Guide:** Siehe [Developer Guide](../05_Development/05_developer_guide.md)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**Letzte Aktualisierung:** 2025-01-XX
|
||||||
|
**Version:** 2.9.1
|
||||||
|
|
||||||
@@ -3,8 +3,8 @@ doc_type: concept
|
|||||||
audience: architect, product_owner
|
audience: architect, product_owner
|
||||||
scope: graph, logic, provenance
|
scope: graph, logic, provenance
|
||||||
status: active
|
status: active
|
||||||
version: 2.7.0
|
version: 2.9.1
|
||||||
context: "Fachliche Beschreibung des Wissensgraphen: Knoten, Kanten, Provenance, Matrix-Logik und WP-22 Scoring-Prinzipien."
|
context: "Fachliche Beschreibung des Wissensgraphen: Knoten, Kanten, Provenance, Matrix-Logik, WP-15c Multigraph-Support und WP-22 Scoring-Prinzipien."
|
||||||
---
|
---
|
||||||
|
|
||||||
# Konzept: Die Graph-Logik
|
# Konzept: Die Graph-Logik
|
||||||
@@ -59,7 +59,7 @@ Um eine konsistente mathematische Gewichtung zu garantieren, werden alle Kanten
|
|||||||
|
|
||||||
### 2.2 Provenance (Herkunft & Vertrauen)
|
### 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.
|
Nicht alle Kanten sind gleich viel wert. Mindnet unterscheidet mehrere Qualitätsstufen (**Provenance**), um bei der Berechnung des Edge-Bonus Prioritäten zu setzen.
|
||||||
|
|
||||||
**1. Explicit (Der Mensch hat es gesagt)**
|
**1. Explicit (Der Mensch hat es gesagt)**
|
||||||
* *Quelle:* Inline-Links (`[[rel:...]]`) oder Wikilinks im Text.
|
* *Quelle:* Inline-Links (`[[rel:...]]`) oder Wikilinks im Text.
|
||||||
@@ -76,6 +76,19 @@ Nicht alle Kanten sind gleich viel wert. Mindnet unterscheidet drei Qualitätsst
|
|||||||
* *Vertrauen:* **Niedrig (0.7)**.
|
* *Vertrauen:* **Niedrig (0.7)**.
|
||||||
* *Bedeutung:* Systemseitige Heuristik. Diese Verbindungen dienen der Entdeckung neuer Pfade, haben aber weniger Gewicht als explizite Links.
|
* *Bedeutung:* Systemseitige Heuristik. Diese Verbindungen dienen der Entdeckung neuer Pfade, haben aber weniger Gewicht als explizite Links.
|
||||||
|
|
||||||
|
**4. Structure (System-interne Verkettung)**
|
||||||
|
* *Quelle:* Automatische Struktur-Kanten (`belongs_to`, `next`, `prev`).
|
||||||
|
* *Vertrauen:* **Hoch (1.0)**.
|
||||||
|
* *Bedeutung:* Diese Kanten werden ausschließlich durch interne Prozesse erzeugt und sind durch die **Provenance Firewall** geschützt. Sie können weder durch Nutzer noch durch KI manipuliert werden.
|
||||||
|
|
||||||
|
### 2.3 Provenance Firewall (WP-15c)
|
||||||
|
|
||||||
|
Die **Edge Registry** (v0.8.0) implementiert eine strikte Trennung zwischen System-Kanten und Inhalts-Kanten:
|
||||||
|
|
||||||
|
* **Geschützte System-Kanten:** `next`, `prev`, `belongs_to` dürfen nur mit `provenance="structure"` gesetzt werden.
|
||||||
|
* **Blockierung:** Alle anderen Provenienzen (`explicit`, `semantic_ai`, `inherited`, `global_pool`, `rule`) werden bei System-Kanten blockiert und auf `related_to` zurückgesetzt.
|
||||||
|
* **Zweck:** Sichert die Graph-Integrität und verhindert Manipulationen an der internen Struktur.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 3. Matrix-Logik (Kontext-Sensitivität)
|
## 3. Matrix-Logik (Kontext-Sensitivität)
|
||||||
@@ -118,8 +131,34 @@ Der Intent-Router injiziert spezifische Multiplikatoren für kanonische Typen:
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 6. Idempotenz & Konsistenz
|
## 6. Section-basierte Links & Multigraph-Support
|
||||||
|
|
||||||
|
Seit v2.9.1 unterstützt Mindnet **Deep-Links** zu spezifischen Abschnitten innerhalb einer Note.
|
||||||
|
|
||||||
|
### 6.1 Link-Parsing & Self-Links (WP-15c)
|
||||||
|
|
||||||
|
Die Logik erkennt nun präzise **Obsidian-Anker** (`[[Note#Section]]`) und **Self-Links** (`[[#Section]]`):
|
||||||
|
|
||||||
|
* **Obsidian-Anker:** `[[Note#Section]]` wird in `target_id="Note"` und `target_section="Section"` aufgeteilt.
|
||||||
|
* **Self-Links:** `[[#Section]]` wird zu `target_id="current_note_id"` und `target_section="Section"` aufgelöst.
|
||||||
|
* **`target_id`:** Enthält nur den Note-Namen (z.B. "Mein Leitbild")
|
||||||
|
* **`target_section`:** Enthält den Abschnitts-Namen (z.B. "P3 – Disziplin")
|
||||||
|
|
||||||
|
**Vorteil:** Verhindert "Phantom-Knoten", die durch das Einbeziehen des Anchors in die `target_id` entstanden wären. Ermöglicht präzise Verlinkung innerhalb derselben Note.
|
||||||
|
|
||||||
|
### 6.2 Multigraph-Support
|
||||||
|
Die Edge-ID enthält nun einen `variant`-Parameter (die Section), sodass mehrere Kanten zwischen denselben Knoten existieren können, wenn sie auf verschiedene Sections zeigen:
|
||||||
|
* `[[Note#Section1]]` → Edge-ID: `src->tgt:kind@Section1`
|
||||||
|
* `[[Note#Section2]]` → Edge-ID: `src->tgt:kind@Section2`
|
||||||
|
|
||||||
|
### 6.3 Semantische Deduplizierung
|
||||||
|
Die Deduplizierung basiert auf dem `src->tgt:kind@sec` Key, um sicherzustellen, dass identische Links (gleiche Quelle, Ziel, Typ und Section) nicht mehrfach erstellt werden.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. Idempotenz & Konsistenz
|
||||||
|
|
||||||
Das System garantiert fachliche Konsistenz auch bei mehrfachen Importen.
|
Das System garantiert fachliche Konsistenz auch bei mehrfachen Importen.
|
||||||
* **Stabile IDs:** Deterministische IDs verhindern Duplikate bei Re-Imports.
|
* **Stabile IDs:** Deterministische IDs verhindern Duplikate bei Re-Imports.
|
||||||
* **Deduplizierung:** Kanten werden anhand ihrer Identität erkannt. Die "stärkere" Provenance gewinnt.
|
* **Deduplizierung:** Kanten werden anhand ihrer Identität (inkl. Section) erkannt. Die "stärkere" Provenance gewinnt.
|
||||||
|
* **Format-agnostische Erkennung:** Kanten werden unabhängig vom Format (Inline, Callout, Wikilink) erkannt, um Dopplungen zu vermeiden.
|
||||||
@@ -0,0 +1,454 @@
|
|||||||
|
---
|
||||||
|
doc_type: technical_reference
|
||||||
|
audience: developer, integrator
|
||||||
|
scope: api, endpoints, integration, agentic_rag
|
||||||
|
status: active
|
||||||
|
version: 2.9.3
|
||||||
|
context: "Vollständige API-Referenz für alle Mindnet-Endpunkte inklusive WP-25 Agentic Multi-Stream RAG. Basis für Integration und Entwicklung."
|
||||||
|
---
|
||||||
|
|
||||||
|
# API Reference
|
||||||
|
|
||||||
|
Diese Dokumentation beschreibt alle verfügbaren API-Endpunkte von Mindnet. Die API basiert auf FastAPI und nutzt automatische OpenAPI-Dokumentation (verfügbar unter `/docs`).
|
||||||
|
|
||||||
|
## Basis-URL
|
||||||
|
|
||||||
|
```
|
||||||
|
http://localhost:8001 # Production
|
||||||
|
http://localhost:8002 # Development
|
||||||
|
```
|
||||||
|
|
||||||
|
## Health Check
|
||||||
|
|
||||||
|
### `GET /healthz`
|
||||||
|
|
||||||
|
Prüft den Status der API und der Verbindung zu Qdrant.
|
||||||
|
|
||||||
|
**Response:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"status": "ok",
|
||||||
|
"qdrant": "http://localhost:6333",
|
||||||
|
"prefix": "mindnet"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Query Endpoints
|
||||||
|
|
||||||
|
### `POST /query`
|
||||||
|
|
||||||
|
Führt eine hybride oder semantische Suche im Wissensgraph durch.
|
||||||
|
|
||||||
|
**Request Body:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"query": "Was ist Mindnet?",
|
||||||
|
"mode": "hybrid", // "hybrid" oder "semantic"
|
||||||
|
"top_k": 10,
|
||||||
|
"expand_depth": 1,
|
||||||
|
"explain": true
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Response:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"query_id": "uuid-v4",
|
||||||
|
"hits": [
|
||||||
|
{
|
||||||
|
"chunk_id": "uuid",
|
||||||
|
"note_id": "uuid",
|
||||||
|
"text": "Auszug...",
|
||||||
|
"score": 0.85,
|
||||||
|
"explanation": {
|
||||||
|
"reasons": [...]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"stats": {
|
||||||
|
"total_hits": 10,
|
||||||
|
"query_time_ms": 45
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Hinweis:** Das Feedback-Logging erfolgt asynchron im Hintergrund (Background Tasks).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Chat Endpoints
|
||||||
|
|
||||||
|
### `POST /chat/`
|
||||||
|
|
||||||
|
Hauptendpunkt für RAG-Chat und Interview-Modus. Unterstützt Streaming.
|
||||||
|
|
||||||
|
**Request Body:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"message": "Was ist Mindnet?",
|
||||||
|
"history": [], // Optional: Chat-Verlauf
|
||||||
|
"stream": true // Optional: SSE-Streaming
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Response (Non-Streaming):**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"query_id": "uuid",
|
||||||
|
"answer": "Mindnet ist ein persönliches KI-Gedächtnis...",
|
||||||
|
"sources": [
|
||||||
|
{
|
||||||
|
"node_id": "uuid",
|
||||||
|
"note_id": "uuid",
|
||||||
|
"semantic_score": 0.85,
|
||||||
|
"total_score": 0.92,
|
||||||
|
"stream_origin": "values_stream", // WP-25: Ursprungs-Stream
|
||||||
|
"explanation": {...}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"latency_ms": 450,
|
||||||
|
"intent": "DECISION", // WP-25: Gewählte Strategie
|
||||||
|
"intent_source": "Keyword (FastPath)" // WP-25: Quelle der Intent-Erkennung
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Response (Streaming):**
|
||||||
|
Server-Sent Events (SSE) mit Chunks der Antwort.
|
||||||
|
|
||||||
|
**Intent-Typen (WP-25):**
|
||||||
|
- `FACT_WHAT`: Wissensabfrage (Wissen/Listen)
|
||||||
|
- `FACT_WHEN`: Zeitpunkte (Termine, Daten)
|
||||||
|
- `DECISION`: Entscheidungsfrage (Beratung, Strategie)
|
||||||
|
- `EMPATHY`: Emotionale Anfrage (Reflexion)
|
||||||
|
- `CODING`: Technische Anfrage (Programmierung)
|
||||||
|
- `INTERVIEW`: Wissen erfassen (Datenerfassung)
|
||||||
|
|
||||||
|
**Stream-Tracing (WP-25):**
|
||||||
|
Jeder Treffer in `sources` enthält `stream_origin`, um die Zuordnung zum Quell-Stream zu ermöglichen (z.B. "values_stream", "facts_stream", "risk_stream").
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Graph Endpoints
|
||||||
|
|
||||||
|
### `GET /graph/{note_id}`
|
||||||
|
|
||||||
|
Lädt den Subgraphen um eine Note herum.
|
||||||
|
|
||||||
|
**Query Parameters:**
|
||||||
|
- `depth` (int, default: 1): Tiefe der Graph-Expansion
|
||||||
|
- `edge_types` (List[str], optional): Filter für Kanten-Typen
|
||||||
|
|
||||||
|
**Response:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"center_note_id": "uuid",
|
||||||
|
"nodes": [
|
||||||
|
{
|
||||||
|
"id": "uuid",
|
||||||
|
"type": "project",
|
||||||
|
"title": "Projekt Alpha",
|
||||||
|
"tags": ["ki"],
|
||||||
|
"in_degree": 5,
|
||||||
|
"out_degree": 3
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"edges": [
|
||||||
|
{
|
||||||
|
"id": "uuid->uuid:depends_on",
|
||||||
|
"kind": "depends_on",
|
||||||
|
"source": "uuid",
|
||||||
|
"target": "uuid",
|
||||||
|
"target_section": "P3 – Disziplin", // Optional: Abschnitts-Name bei Deep-Links
|
||||||
|
"weight": 1.4,
|
||||||
|
"direction": "out",
|
||||||
|
"provenance": "explicit",
|
||||||
|
"confidence": 1.0
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"stats": {
|
||||||
|
"node_count": 10,
|
||||||
|
"edge_count": 15
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Ingest Endpoints
|
||||||
|
|
||||||
|
### `POST /ingest/analyze`
|
||||||
|
|
||||||
|
Analysiert einen Text-Draft und liefert Link-Vorschläge (Intelligence-Feature).
|
||||||
|
|
||||||
|
**Request Body:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"text": "Markdown-Text...",
|
||||||
|
"type": "concept" // Optional: Notiz-Typ
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Response:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"suggestions": [
|
||||||
|
{
|
||||||
|
"text": "Mindnet",
|
||||||
|
"type": "exact_match",
|
||||||
|
"note_id": "uuid",
|
||||||
|
"confidence": 0.95
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"text": "KI-Gedächtnis",
|
||||||
|
"type": "semantic",
|
||||||
|
"note_id": "uuid",
|
||||||
|
"confidence": 0.82
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### `POST /ingest/save`
|
||||||
|
|
||||||
|
Speichert eine Notiz und startet die Ingestion im Hintergrund (WP-14: Background Tasks).
|
||||||
|
|
||||||
|
**Request Body:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"markdown_content": "---\nid: ...\n---\n# Titel\n...",
|
||||||
|
"filename": "meine-notiz.md", // Optional
|
||||||
|
"folder": "00_Inbox" // Optional, default: "00_Inbox"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Response:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"status": "queued",
|
||||||
|
"file_path": "00_Inbox/meine-notiz.md",
|
||||||
|
"note_id": "pending",
|
||||||
|
"message": "Speicherung & Hybrid-KI-Analyse (WP-20) im Hintergrund gestartet.",
|
||||||
|
"stats": {
|
||||||
|
"chunks": -1, // -1 = Async Processing
|
||||||
|
"edges": -1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Wichtig:**
|
||||||
|
- Die Datei wird sofort auf der Festplatte gespeichert
|
||||||
|
- Die Ingestion (Chunking, Embedding, Smart Edges) läuft asynchron im Hintergrund
|
||||||
|
- Dies verhindert Timeouts bei großen Dateien oder langsamen LLM-Calls
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Feedback Endpoints
|
||||||
|
|
||||||
|
### `POST /feedback`
|
||||||
|
|
||||||
|
Nimmt explizites User-Feedback entgegen (WP-04c).
|
||||||
|
|
||||||
|
**Request Body:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"query_id": "uuid",
|
||||||
|
"rating": 5, // 1-5 Sterne
|
||||||
|
"feedback_type": "global", // "global" oder "granular"
|
||||||
|
"chunk_id": "uuid" // Optional für granular feedback
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Response:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"status": "recorded",
|
||||||
|
"query_id": "uuid"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Tools Endpoints
|
||||||
|
|
||||||
|
### `GET /tools/ollama`
|
||||||
|
|
||||||
|
Liefert JSON-Schemas für die Integration als Tools in externe Agenten (Ollama, OpenAI, etc.).
|
||||||
|
|
||||||
|
**Response:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"tools": [
|
||||||
|
{
|
||||||
|
"type": "function",
|
||||||
|
"function": {
|
||||||
|
"name": "mindnet_query",
|
||||||
|
"description": "Hybrid-Retrieval über mindnet (Semantik + Edges).",
|
||||||
|
"parameters": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"query": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Freitext-Query"
|
||||||
|
},
|
||||||
|
"top_k": {
|
||||||
|
"type": "integer",
|
||||||
|
"default": 10,
|
||||||
|
"minimum": 1,
|
||||||
|
"maximum": 50
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "function",
|
||||||
|
"function": {
|
||||||
|
"name": "mindnet_subgraph",
|
||||||
|
"description": "Gibt die Nachbarschaft (Edges) einer Note/Seed-ID zurück.",
|
||||||
|
"parameters": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"note_id": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"depth": {
|
||||||
|
"type": "integer",
|
||||||
|
"default": 1,
|
||||||
|
"minimum": 0,
|
||||||
|
"maximum": 3
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": ["note_id"]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Verwendung:** Diese Schemas können direkt in Ollama-Function-Calling oder OpenAI-Tools integriert werden.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Admin Endpoints
|
||||||
|
|
||||||
|
### `GET /admin/stats`
|
||||||
|
|
||||||
|
Liefert Statistiken über die Qdrant-Collections und die aktuelle Konfiguration.
|
||||||
|
|
||||||
|
**Response:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"collections": {
|
||||||
|
"notes": {
|
||||||
|
"name": "mindnet_notes",
|
||||||
|
"count": 150
|
||||||
|
},
|
||||||
|
"chunks": {
|
||||||
|
"name": "mindnet_chunks",
|
||||||
|
"count": 1250
|
||||||
|
},
|
||||||
|
"edges": {
|
||||||
|
"name": "mindnet_edges",
|
||||||
|
"count": 3200
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"config": {
|
||||||
|
"qdrant": "http://localhost:6333",
|
||||||
|
"prefix": "mindnet",
|
||||||
|
"vector_size": 768,
|
||||||
|
"distance": "Cosine",
|
||||||
|
"retriever": {
|
||||||
|
"w_sem": 0.70,
|
||||||
|
"w_edge": 0.25,
|
||||||
|
"w_cent": 0.05,
|
||||||
|
"top_k": 10,
|
||||||
|
"expand_depth": 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Hinweis:** Dieser Endpunkt ist optional und kann deaktiviert sein, wenn der `admin`-Router nicht geladen wird.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Fehlerbehandlung
|
||||||
|
|
||||||
|
Alle Endpunkte verwenden standardisierte HTTP-Status-Codes:
|
||||||
|
|
||||||
|
- `200 OK`: Erfolgreiche Anfrage
|
||||||
|
- `201 Created`: Ressource erfolgreich erstellt
|
||||||
|
- `400 Bad Request`: Ungültige Anfrage (z.B. fehlende Parameter)
|
||||||
|
- `500 Internal Server Error`: Server-Fehler
|
||||||
|
|
||||||
|
**Fehler-Response-Format:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"detail": "Fehlerbeschreibung"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Rate Limiting & Timeouts
|
||||||
|
|
||||||
|
- **Chat-Endpunkte:** Keine Retries (max_retries=0) für schnelle Fallback-Kaskade
|
||||||
|
- **Ingest-Endpunkte:** Background Tasks verhindern Timeouts
|
||||||
|
- **Query-Endpunkte:** Standard-Timeout konfigurierbar via `MINDNET_API_TIMEOUT`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## OpenAPI Dokumentation
|
||||||
|
|
||||||
|
Die vollständige interaktive API-Dokumentation ist verfügbar unter:
|
||||||
|
- Swagger UI: `http://localhost:8001/docs`
|
||||||
|
- ReDoc: `http://localhost:8001/redoc`
|
||||||
|
- OpenAPI JSON: `http://localhost:8001/openapi.json`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Integration Beispiele
|
||||||
|
|
||||||
|
### Python (requests)
|
||||||
|
|
||||||
|
```python
|
||||||
|
import requests
|
||||||
|
|
||||||
|
# Query
|
||||||
|
response = requests.post(
|
||||||
|
"http://localhost:8001/query",
|
||||||
|
json={"query": "Was ist Mindnet?", "top_k": 5}
|
||||||
|
)
|
||||||
|
print(response.json())
|
||||||
|
|
||||||
|
# Chat
|
||||||
|
response = requests.post(
|
||||||
|
"http://localhost:8001/chat/",
|
||||||
|
json={"message": "Erkläre mir Mindnet"}
|
||||||
|
)
|
||||||
|
print(response.json())
|
||||||
|
```
|
||||||
|
|
||||||
|
### cURL
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Health Check
|
||||||
|
curl http://localhost:8001/healthz
|
||||||
|
|
||||||
|
# Query
|
||||||
|
curl -X POST http://localhost:8001/query \
|
||||||
|
-H "Content-Type: application/json" \
|
||||||
|
-d '{"query": "Was ist Mindnet?", "top_k": 5}'
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Weitere Informationen
|
||||||
|
|
||||||
|
- **Chat-Backend Details:** Siehe [Chat Backend Dokumentation](03_tech_chat_backend.md)
|
||||||
|
- **Ingestion-Pipeline:** Siehe [Ingestion Pipeline](03_tech_ingestion_pipeline.md)
|
||||||
|
- **Retrieval & Scoring:** Siehe [Retrieval & Scoring](03_tech_retrieval_scoring.md)
|
||||||
|
|
||||||
@@ -1,78 +1,250 @@
|
|||||||
---
|
---
|
||||||
doc_type: technical_reference
|
doc_type: technical_reference
|
||||||
audience: developer, architect
|
audience: developer, architect
|
||||||
scope: backend, chat, ollama, traffic_control
|
scope: backend, chat, llm_service, traffic_control, resilience, agentic_rag, moe, lazy_prompts
|
||||||
status: active
|
status: active
|
||||||
version: 2.6
|
version: 3.1.1
|
||||||
context: "Technische Implementierung des FastAPI-Routers, der Decision Engine und des Traffic Control Systems."
|
context: "Technische Implementierung des FastAPI-Routers, des hybriden LLMService (v3.5.5), WP-25 Agentic Multi-Stream RAG, WP-25a Mixture of Experts (MoE), WP-25b Lazy-Prompt-Orchestration und WP-20 Resilienz-Logik."
|
||||||
---
|
---
|
||||||
|
|
||||||
# Chat Backend & Traffic Control
|
# Chat Backend & Agentic Multi-Stream RAG
|
||||||
|
|
||||||
## 1. Hybrid Router (Decision Engine)
|
## 1. Hybrid Router & Intent-basiertes Routing (WP-25)
|
||||||
|
|
||||||
Der zentrale Einstiegspunkt für jede Chatanfrage ist der **Hybrid Router** (`app/routers/chat.py`). Er entscheidet dynamisch, welche Strategie gewählt wird, basierend auf dem User-Input.
|
Der zentrale Einstiegspunkt für jede Chatanfrage ist der **Hybrid Router** (`app/routers/chat.py`). Seit WP-25 agiert das System als **Agentic Orchestrator**, der Nutzeranfragen analysiert, in parallele Wissens-Streams aufteilt und diese zu einer kontextreichen, wertebasierten Antwort synthetisiert.
|
||||||
|
|
||||||
### 1.1 Intent-Erkennung (Logik)
|
### 1.1 Intent-Erkennung (Hybrid-Modus - WP-25b)
|
||||||
|
|
||||||
Der Router prüft den Input in drei Stufen (Wasserfall-Prinzip):
|
Der Router nutzt einen **Hybrid-Modus** mit Keyword-Fast-Path und LLM-Slow-Path:
|
||||||
|
|
||||||
1. **Question Detection (Regelbasiert):**
|
1. **Keyword Fast-Path (Sofortige Erkennung):**
|
||||||
* Prüfung auf Vorhandensein von `?` oder W-Wörtern (Wer, Wie, Was, Soll ich).
|
* Prüft `trigger_keywords` aus `decision_engine.yaml` (z.B. "Soll ich", "Wann", "Was ist").
|
||||||
* Wenn positiv: **RAG Modus** (Interview wird blockiert).
|
* Wenn Match: Sofortige Intent-Zuordnung ohne LLM-Call.
|
||||||
2. **Keyword Scan (Fast Path):**
|
* **Strategien:** FACT_WHAT, FACT_WHEN, DECISION, EMPATHY, CODING, INTERVIEW.
|
||||||
* Lädt `types.yaml` (Objekte, z.B. "Projekt") und `decision_engine.yaml` (Handlungen, z.B. "neu").
|
2. **Type Keywords (Interview-Modus):**
|
||||||
* Wenn Match (z.B. "Projekt" + "neu"): **INTERVIEW Modus**.
|
* Lädt `types.yaml` und prüft `detection_keywords` für Objekt-Erkennung.
|
||||||
3. **LLM Fallback (Slow Path):**
|
* Wenn Match und keine Frage: **INTERVIEW Modus** (Datenerfassung).
|
||||||
* Wenn unklar: Anfrage an LLM zur Klassifizierung.
|
3. **LLM Slow-Path (Semantische Analyse - WP-25b):**
|
||||||
|
* Wenn unklar: Anfrage an `DecisionEngine._determine_strategy()` zur LLM-basierten Klassifizierung.
|
||||||
|
* **Lazy-Prompt-Loading:** Nutzt `prompt_key="intent_router_v1"` mit `variables={"query": query}`
|
||||||
|
* **Ultra-robustes Parsing:** Regex-basierter Intent-Parser bereinigt Modell-Artefakte (z.B. `CODING[/S]` → `CODING`)
|
||||||
|
* **Fallback:** Bei unklarem Intent → `FACT_WHAT`
|
||||||
|
|
||||||
### 1.2 RAG Flow (Technisch)
|
### 1.2 Mixture of Experts (MoE) Architektur (WP-25a)
|
||||||
|
|
||||||
Wenn der Intent `FACT` oder `DECISION` ist, wird folgender Flow ausgeführt:
|
Seit WP-25a nutzt MindNet eine **profilbasierte Experten-Steuerung** statt einer globalen Provider-Konfiguration. Jede Systemaufgabe wird einem dedizierten Profil zugewiesen:
|
||||||
|
|
||||||
1. **Pre-Processing:** Query Rewriting (optional).
|
**Profil-Registry (`llm_profiles.yaml`):**
|
||||||
2. **Context Enrichment:**
|
* **`synthesis_pro`:** Hochwertige Synthese für Chat-Antworten
|
||||||
* Abruf via `retriever.py` (Hybrid Search).
|
* **`tech_expert`:** Fachspezialist für Code & Technik
|
||||||
* Injection von Metadaten (`[TYPE]`, `[SCORE]`) in den Prompt.
|
* **`compression_fast`:** Schnelle Kompression & Routing
|
||||||
3. **Prompt Construction:** Assembly aus System-Prompt (Persona) + Context + Query.
|
* **`ingest_validator`:** Deterministische Validierung (Temperature 0.0)
|
||||||
4. **Streaming:** LLM-Antwort wird via **SSE (Server-Sent Events)** an den Client gestreamt.
|
* **`identity_safe`:** Lokaler Anker (Ollama/Phi-3) für maximale Privacy
|
||||||
5. **Post-Processing:** Anhängen des `Explanation` Layers (JSON-Breakdown) an das Ende des Streams.
|
|
||||||
|
**Rekursive Fallback-Kaskade:**
|
||||||
|
Der `LLMService` (v3.5.2) implementiert eine automatische Fallback-Logik:
|
||||||
|
1. Versucht primäres Profil (z.B. `synthesis_pro`)
|
||||||
|
2. Bei Fehler → `fallback_profile` (z.B. `synthesis_backup`)
|
||||||
|
3. Bei weiterem Fehler → nächster Fallback (z.B. `identity_safe`)
|
||||||
|
4. Schutz gegen Zirkel-Referenzen via `visited_profiles`-Tracking
|
||||||
|
|
||||||
|
**Integration:**
|
||||||
|
* **Intent-Routing:** Nutzt `router_profile` (z.B. `compression_fast`)
|
||||||
|
* **Stream-Kompression:** Nutzt `compression_profile` pro Stream
|
||||||
|
* **Synthese:** Nutzt `llm_profile` aus Strategie-Konfiguration
|
||||||
|
* **Ingestion:** Nutzt `ingest_validator` für binäre Validierungen
|
||||||
|
|
||||||
|
### 1.3 Hierarchisches Prompt-Resolution-System (WP-25b)
|
||||||
|
|
||||||
|
Seit WP-25b nutzt MindNet eine **dreistufige hierarchische Prompt-Auflösung** mit Lazy-Loading. Prompts werden erst im Moment des Modellaustauschs geladen, basierend auf dem exakt aktiven Modell.
|
||||||
|
|
||||||
|
**Hierarchische Auflösung (`llm_service.py` v3.5.5):**
|
||||||
|
|
||||||
|
1. **Level 1 (Modell-ID):** Suche nach exakten Übereinstimmungen für die Modell-ID (z.B. `google/gemini-2.0-flash-exp:free`).
|
||||||
|
* **Vorteil:** Modell-spezifische Optimierungen (z.B. für Gemini 2.0, Llama 3.3, Qwen 2.5)
|
||||||
|
* **Logging:** `🎯 [PROMPT-TRACE] Level 1 Match: Model-specific`
|
||||||
|
|
||||||
|
2. **Level 2 (Provider):** Fallback auf allgemeine Provider-Anweisungen (z.B. `openrouter` oder `ollama`).
|
||||||
|
* **Vorteil:** Bewährte Standards aus v3.1.2 bleiben erhalten
|
||||||
|
* **Logging:** `📡 [PROMPT-TRACE] Level 2 Match: Provider-fallback`
|
||||||
|
|
||||||
|
3. **Level 3 (Default):** Globaler Sicherheits-Satz zur Vermeidung von Fehlern bei unbekannten Konfigurationen.
|
||||||
|
* **Fallback-Kette:** `default` → `gemini` → `ollama` → `""`
|
||||||
|
* **Logging:** `⚓ [PROMPT-TRACE] Level 3 Match: Global Default`
|
||||||
|
|
||||||
|
**Lazy-Prompt-Orchestration:**
|
||||||
|
* **Lazy Loading:** Prompts werden erst zur Laufzeit geladen, wenn das aktive Modell bekannt ist
|
||||||
|
* **Parameter:** `prompt_key` und `variables` statt vorformatierter Strings
|
||||||
|
* **Vorteil:** Maximale Resilienz bei Modell-Fallbacks (Cloud → Local)
|
||||||
|
* **Traceability:** Vollständige Transparenz über genutzte Instruktionen via `[PROMPT-TRACE]` Logs
|
||||||
|
|
||||||
|
**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.4 Multi-Stream Retrieval (WP-25)
|
||||||
|
|
||||||
|
Anstelle einer einzelnen Suche führt die `DecisionEngine` nun **parallele Abfragen** in spezialisierten Streams aus:
|
||||||
|
|
||||||
|
**Stream-Library (definiert in `decision_engine.yaml`):**
|
||||||
|
* **Values Stream:** Extrahiert Identität, Ethik und Prinzipien (`value`, `principle`, `belief`, etc.).
|
||||||
|
* **Facts Stream:** Liefert operative Daten zu Projekten, Tasks und Status (`project`, `decision`, `task`, etc.).
|
||||||
|
* **Biography Stream:** Greift auf persönliche Erfahrungen und Journal-Einträge zu (`experience`, `journal`, `profile`).
|
||||||
|
* **Risk Stream:** Identifiziert Hindernisse und potenzielle Gefahren (`risk`, `obstacle`, `bias`).
|
||||||
|
* **Tech Stream:** Bündelt technisches Wissen, Code und Dokumentation (`concept`, `source`, `glossary`, etc.).
|
||||||
|
|
||||||
|
**Stream-Konfiguration:**
|
||||||
|
* Jeder Stream nutzt individuelle **Edge-Boosts** (z.B. `guides: 3.0` für Values Stream).
|
||||||
|
* **Filter-Types** sind strikt mit `types.yaml` (v2.7.0) synchronisiert.
|
||||||
|
* **Query-Templates** transformieren die ursprüngliche Anfrage für spezialisierte Suche.
|
||||||
|
|
||||||
|
**Parallele Ausführung:**
|
||||||
|
* `asyncio.gather()` führt alle aktiven Streams gleichzeitig aus.
|
||||||
|
* **Stream-Tracing:** Jeder Treffer wird mit `stream_origin` markiert für Feedback-Optimierung.
|
||||||
|
* **Fehlerbehandlung:** Einzelne Stream-Fehler blockieren nicht die gesamte Anfrage.
|
||||||
|
|
||||||
|
### 1.5 Pre-Synthesis Kompression (WP-25a)
|
||||||
|
|
||||||
|
Wissens-Streams, die den Schwellenwert (`compression_threshold`) überschreiten, werden **asynchron verdichtet**, bevor sie die Synthese erreichen:
|
||||||
|
|
||||||
|
**Kompression-Logik:**
|
||||||
|
* **Schwellenwert:** Konfigurierbar pro Stream (z.B. 2500 Zeichen für Values Stream)
|
||||||
|
* **Profil:** Nutzt `compression_profile` (z.B. `compression_fast` für schnelle Zusammenfassung)
|
||||||
|
* **Parallelisierung:** Mehrere Streams können gleichzeitig komprimiert werden
|
||||||
|
* **Fehlerbehandlung:** Kompressions-Fehler blockieren nicht die Synthese (Original-Content wird verwendet)
|
||||||
|
|
||||||
|
**Vorteile:**
|
||||||
|
* Reduziert Token-Verbrauch bei langen Streams
|
||||||
|
* Beschleunigt Synthese durch kürzere Kontexte
|
||||||
|
* Erhält Relevanz durch intelligente Zusammenfassung
|
||||||
|
|
||||||
|
### 1.6 Wissens-Synthese (WP-25/25a)
|
||||||
|
|
||||||
|
Die Zusammenführung der Daten erfolgt über spezialisierte Templates in der `prompts.yaml`:
|
||||||
|
|
||||||
|
**Template-Struktur:**
|
||||||
|
* Explizite Variablen für jeden Stream (z.B. `{values_stream}`, `{risk_stream}`).
|
||||||
|
* **Pre-Initialization:** Alle möglichen Stream-Variablen werden vorab initialisiert (verhindert KeyErrors).
|
||||||
|
* **Provider-spezifische Templates:** Separate Versionen für Ollama, Gemini und OpenRouter.
|
||||||
|
|
||||||
|
**Synthese-Strategien (Profil-gesteuert):**
|
||||||
|
* **FACT_WHAT/FACT_WHEN:** Nutzt `synthesis_pro` - Kombiniert Fakten, Biographie und Technik.
|
||||||
|
* **DECISION:** Nutzt `synthesis_pro` - Wägt Fakten gegen Werte ab, evaluiert Risiken.
|
||||||
|
* **EMPATHY:** Nutzt `synthesis_pro` - Fokus auf Biographie und Werte.
|
||||||
|
* **CODING:** Nutzt `tech_expert` - Spezialisiertes Modell für Code & Technik.
|
||||||
|
|
||||||
|
**Profil-Auflösung:**
|
||||||
|
Jede Strategie kann ein individuelles `llm_profile` definieren. Fehlt diese Angabe, wird `synthesis_pro` als Standard verwendet.
|
||||||
|
|
||||||
|
### 1.7 RAG Flow (Technisch - WP-25a)
|
||||||
|
|
||||||
|
Wenn der Intent nicht `INTERVIEW` ist, wird folgender Flow ausgeführt:
|
||||||
|
|
||||||
|
1. **Intent Detection:** Hybrid Router klassifiziert die Anfrage via `router_profile` (z.B. `compression_fast`).
|
||||||
|
2. **Multi-Stream Retrieval:**
|
||||||
|
* Parallele Abfragen in spezialisierten Streams via `DecisionEngine._execute_parallel_streams()`.
|
||||||
|
* Jeder Stream nutzt individuelle Filter, Edge-Boosts und Query-Templates.
|
||||||
|
3. **Pre-Synthesis Kompression (WP-25a):**
|
||||||
|
* Streams über `compression_threshold` werden via `compression_profile` verdichtet.
|
||||||
|
* Parallelisierung über `asyncio.gather()` für mehrere Streams gleichzeitig.
|
||||||
|
4. **Wissens-Synthese:**
|
||||||
|
* Strategie-spezifisches `llm_profile` (z.B. `tech_expert` für CODING) steuert die finale Antwortgenerierung.
|
||||||
|
* Fallback-Kaskade bei Fehlern (automatisch via LLMService).
|
||||||
|
3. **Context Formatting:**
|
||||||
|
* Stream-Ergebnisse werden in formatierte Kontext-Strings umgewandelt.
|
||||||
|
* **Ollama Context-Throttling:** Kontext wird auf `MAX_OLLAMA_CHARS` begrenzt (Standard: 10.000).
|
||||||
|
4. **Synthese:**
|
||||||
|
* `DecisionEngine._generate_final_answer()` kombiniert alle Streams.
|
||||||
|
* Template-basierte Prompt-Konstruktion mit Stream-Variablen.
|
||||||
|
5. **Response:**
|
||||||
|
* LLM-Antwort wird generiert (provider-spezifisch).
|
||||||
|
* **Sources:** Alle Treffer aus allen Streams werden dedupliziert und zurückgegeben.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 2. Traffic Control (WP-15)
|
## 2. LLM Service & Traffic Control (WP-20 / WP-25)
|
||||||
|
|
||||||
Das Traffic Control System (`app/core/llm_service.py`) schützt das System vor Überlastung, wenn rechenintensive Hintergrundprozesse (Smart Edge Import) und Latenz-kritische Chat-Anfragen gleichzeitig laufen.
|
Der `LLMService` (`app/services/llm_service.py`, v3.4.2) fungiert als zentraler Hybrid-Client für OpenRouter, Google Gemini und Ollama. Er schützt das System vor Überlastung und verwaltet Quoten.
|
||||||
|
|
||||||
|
**WP-25 Integration:**
|
||||||
|
* **Lazy Initialization:** `DecisionEngine` wird erst bei Bedarf initialisiert (verhindert Circular Imports).
|
||||||
|
* **Ingest-Stability Patch:** Entfernung des <5-Zeichen Guards ermöglicht YES/NO Validierungen beim Vault-Import.
|
||||||
|
* **Empty Response Guard:** Sicherung gegen leere `choices` Arrays bei OpenRouter (verhindert JSON-Errors).
|
||||||
|
|
||||||
|
Mit Version 2.8.1 wurde die Architektur der Antwort-Generierung grundlegend gehärtet:
|
||||||
|
|
||||||
|
A. Fail-Fast Prinzip (No-Retry Chat)
|
||||||
|
Im Gegensatz zur Ingestion-Pipeline nutzt das Chat-Backend für Echtzeit-Anfragen keine internen Retries (max_retries=0).
|
||||||
|
|
||||||
|
Scheitert ein Provider (Timeout/Fehler), wird sofort die Fallback-Kaskade eingeleitet oder der Deep Fallback zu Ollama getriggert.
|
||||||
|
|
||||||
|
Dies verhindert die kumulative Wartezeit von mehreren Minuten bei Provider-Störungen.
|
||||||
|
|
||||||
|
B. Context-Throttling & Memory Guard
|
||||||
|
Drosselung: Vor der Übergabe an Ollama prüft die chat.py, ob der Kontext (RAG-Hits) die Grenze von MAX_OLLAMA_CHARS überschreitet und kürzt diesen ggf..
|
||||||
|
|
||||||
|
Modell-Lock: Der LLMService erzwingt im Ollama-Payload den Parameter num_ctx: 8192. Dies stabilisiert den VRAM-Verbrauch und verhindert, dass das Modell versucht, speicherintensive 128k-Kontexte zu reservieren.
|
||||||
|
|
||||||
### 2.1 Prioritäts-Semaphor
|
### 2.1 Prioritäts-Semaphor
|
||||||
|
|
||||||
Jeder LLM-Request muss ein `priority`-Flag setzen.
|
Jeder LLM-Request steuert über ein `priority`-Flag den Zugriff auf Hardware- und API-Ressourcen:
|
||||||
|
|
||||||
**Prioritäten-Levels:**
|
|
||||||
|
|
||||||
| Priority | Verwendung | Limitierung |
|
| Priority | Verwendung | Limitierung |
|
||||||
| :--- | :--- | :--- |
|
| :--- | :--- | :--- |
|
||||||
| **realtime** | Chat-Anfragen | Keine (Hardware-Limit) |
|
| **realtime** | Chat-Anfragen, Intent-Routing | Keine (Hardware-Limit) |
|
||||||
| **background** | Smart Edge Allocation, Drafts | `MINDNET_LLM_BACKGROUND_LIMIT` |
|
| **background** | Smart Edge Allocation, Import-Tasks | `MINDNET_LLM_BACKGROUND_LIMIT` |
|
||||||
|
|
||||||
**Funktionsweise:**
|
**Funktionsweise:**
|
||||||
* Hintergrund-Tasks nutzen `asyncio.Semaphore`.
|
* Hintergrund-Tasks nutzen ein globales `asyncio.Semaphore`.
|
||||||
* Wenn das Limit (Default: 2) erreicht ist, warten weitere Import-Tasks.
|
* Das Limit (Standard: 2) verhindert, dass parallele Import-Vorgänge die API-Quoten oder die lokale CPU erschöpfen.
|
||||||
* Chat-Tasks umgehen die Semaphore und werden sofort bearbeitet.
|
* Chat-Tasks umgehen die Semaphore für minimale Latenz.
|
||||||
|
|
||||||
### 2.2 Timeout-Konfiguration
|
### 2.2 Task-Mapping & Model Selection
|
||||||
|
|
||||||
Deadlocks werden durch strikte Timeouts verhindert, die in der `.env` definiert sind.
|
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**.
|
||||||
|
|
||||||
* **Chat:** `MINDNET_LLM_TIMEOUT` (Default: 300s).
|
### 2.3 Timeout-Konfiguration
|
||||||
* **Frontend:** `MINDNET_API_TIMEOUT` (Default: 300s).
|
|
||||||
|
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. Feedback Traceability
|
## 3. Resilience & Quota Management (WP-20)
|
||||||
|
|
||||||
Unterstützt das geplante Self-Tuning (WP08).
|
In v2.8 wurde ein intelligentes Fehler-Handling für Cloud-Provider implementiert:
|
||||||
|
|
||||||
1. **Query ID:** Generiert bei jedem `/query` Call eine `UUIDv4`.
|
1. **Rate-Limit Erkennung:** Der Service erkennt HTTP 429 Fehler sowie provider-spezifische Meldungen wie `RESOURCE_EXHAUSTED`.
|
||||||
2. **Logging:** Speichert einen Snapshot in `data/logs/query_snapshot.jsonl` (Input + Retrieved Context).
|
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. **Feedback:** Der `/feedback` Endpoint verknüpft das User-Rating (1-5) mit der `query_id`.
|
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 & Stream-Tracing (WP-25)
|
||||||
|
|
||||||
|
Unterstützt das geplante Self-Tuning (WP08) und ermöglicht Stream-spezifische Optimierung.
|
||||||
|
|
||||||
|
1. **Query ID:** Generiert bei jedem `/chat` Call eine `UUIDv4`.
|
||||||
|
2. **Stream-Tracing:** Jeder Treffer enthält `stream_origin` für Zuordnung zum Quell-Stream.
|
||||||
|
3. **Logging:** Speichert einen Snapshot in `data/logs/query_snapshot.jsonl` (Input + Retrieved Context + Intent).
|
||||||
|
4. **Feedback:** Der `/feedback` Endpoint verknüpft das User-Rating (1-5) mit der `query_id` und `stream_origin`.
|
||||||
|
|
||||||
|
## 5. Lifespan Management (WP-25)
|
||||||
|
|
||||||
|
Die FastAPI-Anwendung (`app/main.py`, v1.0.0) implementiert **Lifespan-Management** für sauberen Startup und Shutdown:
|
||||||
|
|
||||||
|
**Startup:**
|
||||||
|
* Integritäts-Check der WP-25 Konfiguration (`decision_engine.yaml`, `prompts.yaml`).
|
||||||
|
* Validierung kritischer Dateien vor dem Start.
|
||||||
|
|
||||||
|
**Shutdown:**
|
||||||
|
* Ressourcen-Cleanup (LLMService-Connections schließen).
|
||||||
|
* Graceful Shutdown für asynchrone Prozesse.
|
||||||
|
|
||||||
|
**Globale Fehlerbehandlung:**
|
||||||
|
* Fängt unerwartete Fehler in der Multi-Stream Kette ab.
|
||||||
|
* Strukturierte JSON-Responses bei Engine-Fehlern.
|
||||||
@@ -1,69 +1,119 @@
|
|||||||
---
|
---
|
||||||
doc_type: technical_reference
|
doc_type: technical_reference
|
||||||
audience: developer, admin
|
audience: developer, admin
|
||||||
scope: configuration, env, registry, scoring
|
scope: configuration, env, registry, scoring, resilience, modularization, agentic_rag, moe, lazy_prompts
|
||||||
status: active
|
status: active
|
||||||
version: 2.7.2
|
version: 3.1.1
|
||||||
context: "Umfassende Referenztabellen für Umgebungsvariablen, YAML-Konfigurationen und die Edge Registry Struktur."
|
context: "Umfassende Referenztabellen für Umgebungsvariablen (inkl. Hybrid-Cloud & WP-76), YAML-Konfigurationen, Edge Registry Struktur, WP-25 Multi-Stream RAG, WP-25a Mixture of Experts (MoE) und WP-25b Lazy-Prompt-Orchestration unter Berücksichtigung von WP-14."
|
||||||
---
|
---
|
||||||
|
|
||||||
# Konfigurations-Referenz
|
# Konfigurations-Referenz
|
||||||
|
|
||||||
Dieses Dokument beschreibt alle Steuerungsdateien von Mindnet. In der Version 2.7 wurde die Konfiguration professionalisiert, um die Edge Registry und dynamische Scoring-Parameter (Lifecycle & Intent) zu unterstützen.
|
Dieses Dokument beschreibt alle Steuerungsdateien von Mindnet. In der Version 2.9.1 wurde die Konfiguration professionalisiert, um die Edge Registry, dynamische Scoring-Parameter (Lifecycle & Intent), die neue Hybrid-Cloud-Resilienz sowie die modulare Datenbank-Infrastruktur (WP-14) zu unterstützen.
|
||||||
|
|
||||||
## 1. Environment Variablen (`.env`)
|
## 1. Environment Variablen (`.env`)
|
||||||
|
|
||||||
Diese Variablen steuern die Infrastruktur, Pfade und globale Timeouts.
|
Diese Variablen steuern die Infrastruktur, Pfade und globale Timeouts. Seit der Modularisierung in WP-14 unterstützen sie zudem die explizite Benennung von Vektoren für verschiedene Collections.
|
||||||
|
|
||||||
| Variable | Default | Beschreibung |
|
| Variable | Default | Beschreibung |
|
||||||
| :--- | :--- | :--- |
|
| :--- | :--- | :--- |
|
||||||
| `QDRANT_URL` | `http://localhost:6333` | URL zur Vektor-DB API. |
|
| `QDRANT_URL` | `http://localhost:6333` | URL zur Vektor-DB API. |
|
||||||
| `QDRANT_API_KEY` | *(leer)* | Optionaler Key für Absicherung. |
|
| `QDRANT_API_KEY` | *(leer)* | Optionaler Key für Absicherung. |
|
||||||
| `COLLECTION_PREFIX` | `mindnet` | Namensraum für Collections (erzeugt `{prefix}_notes` etc). |
|
| `COLLECTION_PREFIX` | `mindnet` | Namensraum für Collections (erzeugt `{prefix}_notes` etc). |
|
||||||
|
| `MINDNET_PREFIX` | *(leer)* | **Alternative zu COLLECTION_PREFIX.** Falls gesetzt, wird dieser Wert verwendet. |
|
||||||
| `VECTOR_DIM` | `768` | **Muss 768 sein** (für Nomic Embeddings). |
|
| `VECTOR_DIM` | `768` | **Muss 768 sein** (für Nomic Embeddings). |
|
||||||
|
| `MINDNET_DISTANCE` | `Cosine` | Metrik für Vektor-Ähnlichkeit (`Cosine`, `Euclidean`, `Dot`). |
|
||||||
|
| `MINDNET_VECTOR_NAME` | `default` | **Neu (WP-14):** Basis-Vektorname für Named Vectors Support. |
|
||||||
|
| `NOTES_VECTOR_NAME` | *(leer)* | **Neu (WP-14):** Spezifischer Vektorname für die Notes-Collection (Override). |
|
||||||
|
| `CHUNKS_VECTOR_NAME` | *(leer)* | **Neu (WP-14):** Spezifischer Vektorname für die Chunks-Collection (Override). |
|
||||||
|
| `EDGES_VECTOR_NAME` | *(leer)* | **Neu (WP-14):** Spezifischer Vektorname für die Edges-Collection (Override). |
|
||||||
| `MINDNET_VOCAB_PATH` | *(Pfad)* | **Neu (WP-22):** Absoluter Pfad zur `01_edge_vocabulary.md`. Definiert den Ort des Dictionarys. |
|
| `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. Dient als Fallback-Basis, falls `MINDNET_VOCAB_PATH` nicht gesetzt ist. |
|
| `MINDNET_VAULT_ROOT` | `./vault_master` | **Achtung:** Standard ist `./vault_master`, nicht `./vault`! Basis-Pfad für Datei-Operationen. |
|
||||||
| `MINDNET_TYPES_FILE` | `config/types.yaml` | Pfad zur Typ-Registry. |
|
| `MINDNET_TYPES_FILE` | `config/types.yaml` | Pfad zur Typ-Registry. |
|
||||||
| `MINDNET_RETRIEVER_CONFIG`| `config/retriever.yaml`| Pfad zur Scoring-Konfiguration. |
|
| `MINDNET_RETRIEVER_CONFIG`| `config/retriever.yaml`| Pfad zur Scoring-Konfiguration. |
|
||||||
| `MINDNET_DECISION_CONFIG` | `config/decision_engine.yaml` | Pfad zur Router & Intent Config. |
|
| `MINDNET_DECISION_CONFIG` | `config/decision_engine.yaml` | Pfad zur Router & Intent Config. |
|
||||||
| `MINDNET_PROMPTS_PATH` | `config/prompts.yaml` | Pfad zu LLM Prompts. |
|
| `MINDNET_PROMPTS_PATH` | `config/prompts.yaml` | Pfad zu LLM Prompts. |
|
||||||
| `MINDNET_LLM_MODEL` | `phi3:mini` | Name des Chat-Modells (Ollama). |
|
| `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-20):** Wartezeit in Sekunden bei HTTP 429 (Rate Limit). |
|
||||||
|
| `MINDNET_LLM_RATE_LIMIT_RETRIES`| `3` | **Neu (WP-20):** 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_EMBEDDING_MODEL` | `nomic-embed-text` | Name des Embedding-Modells (Ollama). |
|
||||||
| `MINDNET_OLLAMA_URL` | `http://127.0.0.1:11434`| URL zum LLM-Server. |
|
| `MINDNET_OLLAMA_URL` | `http://127.0.0.1:11434`| URL zum lokalen LLM-Server. |
|
||||||
| `MINDNET_LLM_TIMEOUT` | `300.0` | Timeout in Sekunden (Erhöht für CPU Cold-Starts). |
|
| `MAX_OLLAMA_CHARS` | `10000`| Maximale Länge des Kontext-Strings, der an das lokale Modell gesendet wird. |
|
||||||
| `MINDNET_API_TIMEOUT` | `300.0` | Frontend Timeout (Erhöht für Smart Edge Wartezeiten). |
|
| `MINDNET_LLM_TIMEOUT` | `300.0` | Timeout in Sekunden für LLM-Anfragen. |
|
||||||
| `MINDNET_LLM_BACKGROUND_LIMIT`| `2` | **Traffic Control:** Max. parallele Hintergrund-Tasks (Semaphore). |
|
| `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). |
|
| `MINDNET_CHANGE_DETECTION_MODE` | `full` | `full` (Text + Meta) oder `body` (nur Text). |
|
||||||
|
| `MINDNET_DEFAULT_RETRIEVER_WEIGHT` | `1.0` | **Neu (WP-22):** Systemweiter Standard für das Retriever-Gewicht einer Notiz. |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 2. Typ-Registry (`types.yaml`)
|
## 2. Typ-Registry (`types.yaml`)
|
||||||
|
|
||||||
Steuert das Import-Verhalten, Chunking und die Kanten-Logik pro Typ.
|
Steuert das Import-Verhalten, Chunking und die Kanten-Logik pro Typ. Die Auflösung erfolgt zentral über die modularisierte Registry in `app.core.registry`.
|
||||||
|
|
||||||
### 2.1 Konfigurations-Hierarchie (Override-Logik)
|
### 2.1 Konfigurations-Hierarchie (Override-Logik)
|
||||||
Seit Version 2.7.0 gilt für `chunking_profile` und `retriever_weight` folgende Priorität:
|
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.
|
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`.
|
2. **Type Config:** Der Standardwert für den `type` aus `types.yaml`.
|
||||||
3. **Global Default:** Fallback aus `defaults` in `types.yaml`.
|
3. **Ingestion Settings (Neu WP-14):** Globale Konfiguration wie `default_chunk_profile` innerhalb des `ingestion_settings` Blocks.
|
||||||
|
4. **Global Default:** Fallback aus `defaults` in `types.yaml`.
|
||||||
|
|
||||||
### 2.2 Typ-Referenztabelle (Vollständig)
|
|
||||||
|
|
||||||
| Typ (`type`) | Chunk Profile (Standard) | Retriever Weight ($W_{type}$) | Smart Edges? | Beschreibung |
|
## 2.2 Typ-Referenz & Stream-Logik (Vollständige Liste: 28 Typen)
|
||||||
| :--- | :--- | :--- | :--- | :--- |
|
|
||||||
| **decision** | `structured_strict` | 1.00 | Ja | Entscheidungen. Atomar. |
|
Das System euriert Informationen in drei funktionalen Streams. Wähle den Typ danach aus, in welchem Bereich deines „Digitalen Zwillings“ die Information wirken soll.
|
||||||
| **value** | `structured_strict` | 1.00 | Ja | Werte/Prinzipien. Atomar. |
|
|
||||||
| **project** | `sliding_smart` | 0.97 | Ja | Aktive Vorhaben. |
|
### 2.2.1 Identity Stream (Der Kern / Das „Warum“)
|
||||||
| **experience** | `sliding_smart` | 0.90 | Ja | Persönliche Learnings. |
|
Dieser Stream definiert deine stabilen Merkmale und inneren Kompasse.
|
||||||
| **concept** | `sliding_smart` | 0.60 | Ja | Abstrakte Begriffe. |
|
|
||||||
| **principle** | `structured_L3` | 0.95 | Nein | Prinzipien (Tiefer Split). |
|
| Typ | Gewicht | Chunking Profil | Zweck & Inhalt |
|
||||||
| **belief** | `sliding_short` | 0.90 | Nein | Glaubenssätze. |
|
| :--- | :--- | :--- | :--- |
|
||||||
| **risk** | `sliding_short` | 0.90 | Nein | Risiken. |
|
| **`value`** | 1.00 | `structured_strict` | Fundamentale Werte und moralische Maßstäbe. |
|
||||||
| **journal** | `sliding_standard` | 0.80 | Nein | Logs / Dailies. |
|
| **`principle`** | 0.95 | `structured_strict_L3` | Handlungsleitlinien mit tiefer Hierarchie (H3-Split). |
|
||||||
| **person** | `sliding_standard` | 0.50 | Nein | Profile. |
|
| **`trait`** | 1.10 | `structured_strict` | Charakterliche Stärken und Talente. |
|
||||||
| **source** | `sliding_standard` | 0.50 | Nein | Externe Quellen. |
|
| **`belief`** | 0.90 | `sliding_short` | Tiefe Überzeugungen über dich und die Gesellschaft. |
|
||||||
| **glossary** | `sliding_short` | 0.40 | Nein | Begriffsdefinitionen. |
|
| **`profile`** | 0.70 | `structured_strict` | Rollenidentitäten (z. B. Vater, Mentor, Unternehmer). |
|
||||||
| **default** | `sliding_standard` | 1.00 | Nein | Fallback für alle anderen. |
|
| **`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).*
|
*Richtwert für $W_{type}$: 0.1 (minimale Relevanz/Filter) bis 1.0 (maximale Relevanz).*
|
||||||
|
|
||||||
@@ -71,28 +121,61 @@ Seit Version 2.7.0 gilt für `chunking_profile` und `retriever_weight` folgende
|
|||||||
|
|
||||||
## 3. Retriever Config (`retriever.yaml`)
|
## 3. Retriever Config (`retriever.yaml`)
|
||||||
|
|
||||||
Steuert die Gewichtung der Scoring-Formel und die neuen Lifecycle-Modifier.
|
Steuert die Gewichtung der Scoring-Formel und die neuen Lifecycle-Modifier. Seit WP-14 ist die mathematische Engine im Paket `app.core.retrieval` gekapselt.
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
|
version: 1.2
|
||||||
|
|
||||||
scoring:
|
scoring:
|
||||||
semantic_weight: 1.0 # Basis-Relevanz (Cosine Similarity)
|
# W_sem: skaliert den Term (semantic_score * retriever_weight)
|
||||||
edge_weight: 0.7 # Einfluss des Graphen (Bonus)
|
# Empfehlung Startwert: 1.0 → Semantik bleibt Hauptsignal
|
||||||
centrality_weight: 0.5 # Einfluss von Hubs (Zentralität)
|
semantic_weight: 1.0
|
||||||
|
|
||||||
# WP-22 Lifecycle Modifier (Multiplikativ auf Semantik)
|
# 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:
|
lifecycle_weights:
|
||||||
stable: 1.2 # Bonus: Geprüftes Wissen wird 20% höher gewichtet
|
stable: 1.2 # +20% Bonus
|
||||||
draft: 0.5 # Malus: Entwürfe werden auf 50% gedämpft
|
active: 1.0 # Standardwert
|
||||||
system: 0.0 # Ausschluss aus dem Index
|
draft: 0.5 # -50% Malus
|
||||||
|
system: 0.0 # Hard Skip via Ingestion
|
||||||
|
|
||||||
# Kanten-spezifische Basis-Gewichtung (Ohne Intent-Boost)
|
# Die nachfolgenden Werte überschreiben die Defaults aus app/core/retriever_config.
|
||||||
edge_weights:
|
edge_types:
|
||||||
depends_on: 1.5 # Harte Abhängigkeiten stark gewichten
|
# --- KATEGORIE 1: LOGIK-BOOSTS (Relevanz-Treiber) ---
|
||||||
blocks: 1.5 # Blocker/Risiken stark gewichten
|
blocks: 1.6
|
||||||
caused_by: 1.2 # Kausalitäten moderat stärken
|
solves: 1.5
|
||||||
based_on: 1.3 # Werte-Bezug stärken
|
depends_on: 1.4
|
||||||
related_to: 0.5 # Weiche Assoziation schwächen
|
resulted_in: 1.4
|
||||||
references: 0.8 # Standard-Referenzen
|
followed_by: 1.3
|
||||||
|
caused_by: 1.2
|
||||||
|
preceded_by: 1.1
|
||||||
|
|
||||||
|
# --- KATEGORIE 2: QUALITATIVER KONTEXT (Stabilitäts-Stützen) ---
|
||||||
|
guides: 1.1
|
||||||
|
part_of: 1.1
|
||||||
|
based_on: 0.8
|
||||||
|
derived_from: 0.6
|
||||||
|
uses: 0.6
|
||||||
|
|
||||||
|
# --- KATEGORIE 3: THEMATISCHE NÄHE (Ähnlichkeits-Signal) ---
|
||||||
|
similar_to: 0.4
|
||||||
|
|
||||||
|
# --- KATEGORIE 4: SYSTEM-NUDGES (Technische Struktur) ---
|
||||||
|
belongs_to: 0.2
|
||||||
|
next: 0.1
|
||||||
|
prev: 0.1
|
||||||
|
|
||||||
|
# --- KATEGORIE 5: WEICHE ASSOZIATIONEN (Rausch-Unterdrückung) ---
|
||||||
|
references: 0.1
|
||||||
|
related_to: 0.05
|
||||||
```
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
@@ -103,7 +186,7 @@ Die `EdgeRegistry` ist die **Single Source of Truth** für das Vokabular.
|
|||||||
|
|
||||||
### 4.1 Dateistruktur & Speicherort
|
### 4.1 Dateistruktur & Speicherort
|
||||||
Die Registry erwartet eine Markdown-Datei an folgendem Ort:
|
Die Registry erwartet eine Markdown-Datei an folgendem Ort:
|
||||||
* **Standard-Pfad:** `<MINDNET_VAULT_ROOT>/01_User_Manual/01_edge_vocabulary.md`.
|
* **Standard-Pfad:** `<MINDNET_VAULT_ROOT>/_system/dictionary/edge_vocabulary.md`.
|
||||||
* **Custom-Pfad:** Kann via `.env` Variable `MINDNET_VOCAB_PATH` überschrieben werden.
|
* **Custom-Pfad:** Kann via `.env` Variable `MINDNET_VOCAB_PATH` überschrieben werden.
|
||||||
|
|
||||||
### 4.2 Aufbau des Dictionaries (Markdown-Schema)
|
### 4.2 Aufbau des Dictionaries (Markdown-Schema)
|
||||||
@@ -117,45 +200,557 @@ Die Datei muss eine Markdown-Tabelle enthalten, die vom Regex-Parser gelesen wir
|
|||||||
| **`caused_by`** | `ausgelöst_durch`, `wegen` | Kausalität: A löst B aus. |
|
| **`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)
|
### 4.3 Verfügbare Kanten-Typen (System-Standard)
|
||||||
|
|
||||||
| Kind (Canonical) | Symmetrisch? | Herkunft | Bedeutung |
|
| System-Typ (Canonical) | Erlaubte Aliasse (User) | Beschreibung |
|
||||||
| :--- | :--- | :--- | :--- |
|
| :--- | :--- | :--- |
|
||||||
| `references` | Nein | Wikilink | Standard-Verweis ("Erwähnt X"). |
|
| **`caused_by`** | `ausgelöst_durch`, `wegen`, `ursache_ist` | Kausalität: A löst B aus. |
|
||||||
| `belongs_to` | Nein | Struktur | Chunk gehört zu Note. |
|
| **`derived_from`** | `abgeleitet_von`, `quelle`, `inspiriert_durch` | Herkunft: A stammt von B. |
|
||||||
| `caused_by` | Nein | Inline | Kausalität: A löst B aus. |
|
| **`based_on`** | `basiert_auf`, `fundament`, `grundlage` | Fundament: B baut auf A auf. |
|
||||||
| `based_on` | Nein | Matrix | Fundament: A fußt auf B. |
|
| **`solves`** | `löst`, `beantwortet`, `fix_für` | Lösung: A ist Lösung für Problem B. |
|
||||||
| `blocks` | Nein | Inline | Blocker: A verhindert B. |
|
| **`part_of`** | `teil_von`, `gehört_zu`, `cluster` | Hierarchie: Kind -> Eltern. |
|
||||||
| `solves` | Nein | Inline | Lösung: A ist Lösung für Problem B. |
|
| **`depends_on`** | `hängt_ab_von`, `braucht`, `requires`, `enforced_by` | Abhängigkeit: A braucht B. |
|
||||||
| `next` / `prev` | Ja | Struktur | Sequenzielle Lesereihenfolge. |
|
| **`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`)
|
## 5. Decision Engine (`decision_engine.yaml` v3.1.6)
|
||||||
|
|
||||||
Steuert den Hybrid Router und das dynamische Intent-Boosting (WP-22).
|
Die Decision Engine fungiert als zentraler **Agentic Orchestrator** für die Intent-Erkennung und das dynamische Multi-Stream Retrieval-Routing (WP-25). Sie bestimmt, wie das System auf eine Nutzeranfrage reagiert, welche Wissens-Streams aktiviert werden und wie die Ergebnisse synthetisiert werden.
|
||||||
|
|
||||||
**Beispielauszug für Intent-Boosting:**
|
### 5.1 Intent Recognition: Hybrid-Routing (WP-25)
|
||||||
|
Das System nutzt einen **Hybrid-Modus** mit Keyword Fast-Path und LLM Slow-Path:
|
||||||
|
|
||||||
|
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 (z.B. "Soll ich" → `DECISION`).
|
||||||
|
2. **Type Keywords:** Prüft `detection_keywords` aus `types.yaml` für Interview-Modus (z.B. "Projekt" + "neu" → `INTERVIEW`).
|
||||||
|
3. **Slow Path (LLM Router):** Wenn kein Keyword matcht und `llm_fallback_enabled: true` gesetzt ist, analysiert ein LLM die Nachricht mittels Few-Shot Prompting (`intent_router_v1`).
|
||||||
|
|
||||||
|
#### 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 Multi-Stream Konfiguration (WP-25)
|
||||||
|
|
||||||
|
Seit WP-25 nutzt die Decision Engine eine **Stream-Library** mit spezialisierten Wissens-Streams:
|
||||||
|
|
||||||
|
**Stream-Library (`streams_library`):**
|
||||||
|
* **`values_stream`:** Identität, Ethik und Prinzipien (filter_types: `value`, `principle`, `belief`, `trait`, `boundary`, `need`, `motivation`)
|
||||||
|
* **`facts_stream`:** Operative Daten (filter_types: `project`, `decision`, `task`, `goal`, `event`, `state`)
|
||||||
|
* **`biography_stream`:** Persönliche Erfahrungen (filter_types: `experience`, `journal`, `profile`, `person`)
|
||||||
|
* **`risk_stream`:** Hindernisse und Gefahren (filter_types: `risk`, `obstacle`, `bias`)
|
||||||
|
* **`tech_stream`:** Technisches Wissen (filter_types: `concept`, `source`, `glossary`, `idea`, `insight`, `skill`, `habit`)
|
||||||
|
|
||||||
|
**Stream-Parameter:**
|
||||||
|
* **`query_template`:** Transformiert die ursprüngliche Anfrage für spezialisierte Suche (z.B. "Welche meiner Werte und Prinzipien betreffen: {query}")
|
||||||
|
* **`filter_types`:** Strikte Synchronisation mit `types.yaml` (v2.7.0)
|
||||||
|
* **`top_k`:** Anzahl der Treffer pro Stream (z.B. 5 für Values, 3 für Risk)
|
||||||
|
* **`edge_boosts`:** Individuelle Edge-Gewichtung pro Stream (z.B. `guides: 3.0` für Values Stream)
|
||||||
|
|
||||||
|
**Strategie-Komposition (`strategies`):**
|
||||||
|
Jede Strategie definiert, welche Streams aktiviert werden:
|
||||||
|
|
||||||
|
* **`use_streams`:** Liste der Stream-Keys, die parallel abgefragt werden (z.B. `["values_stream", "facts_stream", "risk_stream"]` für `DECISION`)
|
||||||
|
* **`prompt_template`:** Template-Key aus `prompts.yaml` für die Wissens-Synthese (z.B. `decision_synthesis_v1`)
|
||||||
|
* **`prepend_instruction`:** Optional: Zusätzliche Anweisung für das LLM (z.B. "Analysiere die Fakten vor dem Hintergrund meiner Werte")
|
||||||
|
* **`preferred_provider`:** Optional: Provider-Präferenz für diese Strategie (z.B. `gemini` für DECISION)
|
||||||
|
|
||||||
|
### 5.3 Strategie-Mechaniken (Graph Shaping)
|
||||||
|
Jede Strategie definiert mehrere Hebel, um das Ergebnis zu beeinflussen:
|
||||||
|
|
||||||
|
* **`use_streams`:** Aktiviert parallele Wissens-Streams (WP-25).
|
||||||
|
* **`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.4 Übersicht der Strategien (WP-25)
|
||||||
|
|
||||||
|
| Strategie | Fokus | Aktive Streams | Bevorzugte Kanten (`edge_boosts`) |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| **FACT_WHAT** | Wissensabfrage & Listen | `facts_stream`, `tech_stream`, `biography_stream` | `part_of` (2.0), `depends_on` (1.5), `implemented_in` (1.5) |
|
||||||
|
| **FACT_WHEN** | Zeitpunkte & Termine | `facts_stream`, `biography_stream`, `tech_stream` | `part_of` (2.0), `depends_on` (1.5) |
|
||||||
|
| **DECISION** | Rat, Strategie & Abwägung | `values_stream`, `facts_stream`, `risk_stream` | `blocks` (2.5), `impacts` (2.0), `risk_of` (2.5) |
|
||||||
|
| **EMPATHY** | Emotionale Resonanz | `biography_stream`, `values_stream` | `related_to` (1.5), `experienced_in` (2.0) |
|
||||||
|
| **CODING** | Programmierung & Syntax | `tech_stream`, `facts_stream` | `uses` (2.5), `implemented_in` (3.0) |
|
||||||
|
| **INTERVIEW** | Erfassung neuer Daten | *(Keine Streams)* | *(Keine)* |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 5.5 Der Interview-Modus & Schemas
|
||||||
|
Die Strategie `INTERVIEW` dient der strukturierten Datenerfassung.
|
||||||
|
|
||||||
|
* **Trigger:** Aktiviert durch Phrasen wie "neue notiz", "festhalten" oder "dokumentieren" (Type Keywords aus `types.yaml`).
|
||||||
|
* **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.
|
||||||
|
* **Streams:** Keine Streams aktiviert (leere `use_streams` Liste).
|
||||||
|
|
||||||
|
> **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.
|
||||||
|
|
||||||
|
### 5.6 Prompts-Konfiguration (`prompts.yaml` v3.2.2 - WP-25b)
|
||||||
|
|
||||||
|
Seit WP-25b nutzt MindNet eine **hierarchische Prompt-Struktur** mit Lazy-Loading. Prompts werden erst zur Laufzeit geladen, basierend auf dem exakt aktiven Modell.
|
||||||
|
|
||||||
|
**Hierarchische Template-Struktur:**
|
||||||
```yaml
|
```yaml
|
||||||
intents:
|
decision_synthesis_v1:
|
||||||
EMPATHY:
|
# Level 1: Modell-spezifisch (höchste Priorität)
|
||||||
description: "Emotionaler Support / Werte-Fokus"
|
"google/gemini-2.0-flash-exp:free": |
|
||||||
boost_edges:
|
WERTE & PRINZIPIEN (Identität):
|
||||||
based_on: 2.0 # Verdoppelt den Einfluss von Werte-Kanten
|
{values_stream}
|
||||||
related_to: 1.5 # Stärkt assoziative Bezüge
|
|
||||||
inject_types: ["experience", "belief"]
|
|
||||||
|
|
||||||
WHY:
|
OPERATIVE FAKTEN (Realität):
|
||||||
description: "Ursachenanalyse (Kausalität)"
|
{facts_stream}
|
||||||
boost_edges:
|
|
||||||
caused_by: 2.5 # Massiver Boost für Kausalitätsketten
|
RISIKO-RADAR (Konsequenzen):
|
||||||
derived_from: 1.8 # Fokus auf die Herkunft
|
{risk_stream}
|
||||||
|
|
||||||
|
ENTSCHEIDUNGSFRAGE:
|
||||||
|
{query}
|
||||||
|
Nutze deine hohe Reasoning-Kapazität für eine tiefe Synthese.
|
||||||
|
|
||||||
|
"meta-llama/llama-3.3-70b-instruct:free": |
|
||||||
|
Erstelle eine fundierte Synthese für die Frage: "{query}"
|
||||||
|
Nutze die Daten: {values_stream}, {facts_stream} und {risk_stream}.
|
||||||
|
Trenne klare Fakten von Erfahrungen. Bleibe strikt beim bereitgestellten Kontext.
|
||||||
|
|
||||||
|
# Level 2: Provider-Fallback (mittlere Priorität)
|
||||||
|
openrouter: |
|
||||||
|
WERTE & PRINZIPIEN (Identität):
|
||||||
|
{values_stream}
|
||||||
|
|
||||||
|
OPERATIVE FAKTEN (Realität):
|
||||||
|
{facts_stream}
|
||||||
|
|
||||||
|
RISIKO-RADAR (Konsequenzen):
|
||||||
|
{risk_stream}
|
||||||
|
|
||||||
|
ENTSCHEIDUNGSFRAGE:
|
||||||
|
{query}
|
||||||
|
|
||||||
|
ollama: |
|
||||||
|
WERTE & PRINZIPIEN (Identität):
|
||||||
|
{values_stream}
|
||||||
|
|
||||||
|
OPERATIVE FAKTEN (Realität):
|
||||||
|
{facts_stream}
|
||||||
|
|
||||||
|
RISIKO-RADAR (Konsequenzen):
|
||||||
|
{risk_stream}
|
||||||
|
|
||||||
|
ENTSCHEIDUNGSFRAGE:
|
||||||
|
{query}
|
||||||
|
|
||||||
|
# Level 3: Global Default (niedrigste Priorität)
|
||||||
|
default: |
|
||||||
|
Synthetisiere die folgenden Informationen für: {query}
|
||||||
|
{values_stream} | {facts_stream} | {risk_stream}
|
||||||
```
|
```
|
||||||
|
|
||||||
*Richtwert für Kanten-Boosts: 0.1 (Abwertung) bis 3.0+ (Dominanz gegenüber Text-Match).*
|
**Auflösungs-Logik:**
|
||||||
|
1. **Level 1:** Exakte Modell-ID (z.B. `google/gemini-2.0-flash-exp:free`)
|
||||||
|
2. **Level 2:** Provider-Fallback (z.B. `openrouter`, `ollama`, `gemini`)
|
||||||
|
3. **Level 3:** Global Default (`default` → `gemini` → `ollama` → `""`)
|
||||||
|
|
||||||
|
**Lazy-Loading:**
|
||||||
|
* Prompts werden erst zur Laufzeit geladen, wenn das aktive Modell bekannt ist
|
||||||
|
* **Parameter:** `prompt_key` und `variables` statt vorformatierter Strings
|
||||||
|
* **Vorteil:** Maximale Resilienz bei Modell-Fallbacks (Cloud → Local)
|
||||||
|
|
||||||
|
**Pre-Initialization:**
|
||||||
|
Alle möglichen Stream-Variablen werden vorab initialisiert (verhindert KeyErrors bei unvollständigen Konfigurationen).
|
||||||
|
|
||||||
|
**PROMPT-TRACE Logging:**
|
||||||
|
Das System protokolliert die genutzte Auflösungs-Ebene:
|
||||||
|
* `🎯 [PROMPT-TRACE] Level 1 Match: Model-specific`
|
||||||
|
* `📡 [PROMPT-TRACE] Level 2 Match: Provider-fallback`
|
||||||
|
* `⚓ [PROMPT-TRACE] Level 3 Match: Global Default`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. LLM Profile Registry (`llm_profiles.yaml` v1.3.0)
|
||||||
|
|
||||||
|
Seit WP-25a nutzt MindNet eine **Mixture of Experts (MoE)** Architektur mit profilbasierter Experten-Steuerung. Jede Systemaufgabe (Synthese, Ingestion-Validierung, Routing, Kompression) wird einem dedizierten Profil zugewiesen, das Modell, Provider und Parameter unabhängig von der globalen Konfiguration definiert.
|
||||||
|
|
||||||
|
### 6.1 Profil-Struktur
|
||||||
|
|
||||||
|
Jedes Profil definiert:
|
||||||
|
* **`provider`:** Cloud-Provider (`openrouter`, `gemini`, `ollama`)
|
||||||
|
* **`model`:** Spezifisches Modell (z.B. `mistralai/mistral-7b-instruct:free`)
|
||||||
|
* **`temperature`:** Kreativität/Determinismus (0.0 = deterministisch, 1.0 = kreativ)
|
||||||
|
* **`fallback_profile`:** Optional: Name des Fallback-Profils bei Fehlern
|
||||||
|
* **`dimensions`:** Optional: Für Embedding-Profile (z.B. 768 für nomic-embed-text)
|
||||||
|
|
||||||
|
**Beispiel:**
|
||||||
|
```yaml
|
||||||
|
synthesis_pro:
|
||||||
|
provider: "openrouter"
|
||||||
|
model: "gemini-1.5-mistralai/mistral-7b-instruct:free"
|
||||||
|
temperature: 0.7
|
||||||
|
fallback_profile: "synthesis_backup"
|
||||||
|
```
|
||||||
|
|
||||||
|
### 6.2 Verfügbare Experten-Profile
|
||||||
|
|
||||||
|
| Profil | Provider | Modell | Temperature | Fallback | Zweck |
|
||||||
|
| :--- | :--- | :--- | :--- | :--- | :--- |
|
||||||
|
| **`synthesis_pro`** | openrouter | gemini-1.5-mistralai/mistral-7b-instruct:free | 0.7 | `synthesis_backup` | Hochwertige Synthese (Chat-Antworten) |
|
||||||
|
| **`synthesis_backup`** | openrouter | mistralai/mistral-large | 0.5 | `identity_safe` | Backup-Cloud-Experte (Resilienz) |
|
||||||
|
| **`tech_expert`** | openrouter | anthropic/claude-3.5-sonnet | 0.3 | `synthesis_pro` | Fachspezialist für Code & Technik |
|
||||||
|
| **`compression_fast`** | openrouter | mistralai/mistral-7b-instruct:free | 0.1 | `identity_safe` | Schnelle Kompression & Routing |
|
||||||
|
| **`ingest_extractor`** | openrouter | mistralai/mistral-7b-instruct:free | 0.2 | `synthesis_backup` | Extraktion komplexer Datenstrukturen |
|
||||||
|
| **`ingest_validator`** | openrouter | mistralai/mistral-7b-instruct:free | 0.0 | `compression_fast` | Binäre Prüfungen (YES/NO, deterministisch) |
|
||||||
|
| **`identity_safe`** | ollama | phi3:mini | 0.2 | *(kein Fallback)* | Lokaler Anker & Privacy (terminaler Endpunkt) |
|
||||||
|
| **`embedding_expert`** | ollama | nomic-embed-text | - | - | Embedding-Modell (dimensions: 768) |
|
||||||
|
|
||||||
|
### 6.3 Fallback-Kaskade (WP-25a)
|
||||||
|
|
||||||
|
Die Profile implementieren eine **rekursive Fallback-Kaskade**:
|
||||||
|
|
||||||
|
1. **Primäres Profil:** System versucht das angeforderte Profil (z.B. `synthesis_pro`)
|
||||||
|
2. **Fallback-Level 1:** Bei Fehler → `fallback_profile` (z.B. `synthesis_backup`)
|
||||||
|
3. **Fallback-Level 2:** Bei weiterem Fehler → nächster Fallback (z.B. `identity_safe`)
|
||||||
|
4. **Terminaler Endpunkt:** `identity_safe` hat keinen Fallback (lokales Modell als letzte Instanz)
|
||||||
|
|
||||||
|
**Schutzmechanismen:**
|
||||||
|
* **Zirkuläre Referenzen:** `visited_profiles`-Tracking verhindert Endlosschleifen
|
||||||
|
* **Background-Semaphore:** Parallele Tasks werden gedrosselt (konfigurierbar via `BACKGROUND_LIMIT`)
|
||||||
|
|
||||||
|
### 6.4 Integration in Decision Engine
|
||||||
|
|
||||||
|
Die `decision_engine.yaml` referenziert Profile über:
|
||||||
|
* **`router_profile`:** Profil für Intent-Erkennung (z.B. `compression_fast`)
|
||||||
|
* **`llm_profile`:** Profil für Strategie-spezifische Synthese (z.B. `tech_expert` für CODING)
|
||||||
|
* **`compression_profile`:** Profil für Stream-Kompression (z.B. `compression_fast`)
|
||||||
|
|
||||||
|
**Stream-Konfiguration:**
|
||||||
|
```yaml
|
||||||
|
values_stream:
|
||||||
|
llm_profile: "identity_safe" # Lokales Modell für Privacy
|
||||||
|
compression_profile: "identity_safe"
|
||||||
|
compression_threshold: 2500
|
||||||
|
```
|
||||||
|
|
||||||
|
### 6.5 Environment-Variablen
|
||||||
|
|
||||||
|
| Variable | Default | Beschreibung |
|
||||||
|
| :--- | :--- | :--- |
|
||||||
|
| `MINDNET_LLM_PROFILES_PATH` | `config/llm_profiles.yaml` | Pfad zur Profil-Registry |
|
||||||
|
|
||||||
|
**Hinweis:** Die `.env` Variablen `MINDNET_LLM_PROVIDER`, `MINDNET_LLM_MODEL` etc. dienen nur noch als Fallback, wenn kein Profil angegeben wird.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. Konfigurations-Verbindungen & Datenfluss
|
||||||
|
|
||||||
|
Die vier zentralen Konfigurationsdateien (`types.yaml`, `decision_engine.yaml`, `llm_profiles.yaml`, `prompts.yaml`) arbeiten eng zusammen, um das agentische Multi-Stream RAG System zu steuern. Diese Sektion erklärt die Verbindungen und zeigt einen konkreten Praxisablauf.
|
||||||
|
|
||||||
|
### 7.1 Architektur-Übersicht
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
graph TB
|
||||||
|
subgraph "1. Typ-Definition (types.yaml)"
|
||||||
|
T1[Typ: value<br/>chunking_profile: structured_strict<br/>retriever_weight: 1.00]
|
||||||
|
T2[Typ: risk<br/>chunking_profile: sliding_short<br/>retriever_weight: 0.85]
|
||||||
|
T3[Typ: project<br/>chunking_profile: sliding_smart_edges<br/>retriever_weight: 0.97]
|
||||||
|
end
|
||||||
|
|
||||||
|
subgraph "2. Stream-Konfiguration (decision_engine.yaml)"
|
||||||
|
D1[values_stream<br/>filter_types: value, principle, belief...<br/>llm_profile: identity_safe<br/>compression_profile: identity_safe]
|
||||||
|
D2[risk_stream<br/>filter_types: risk, obstacle, bias<br/>llm_profile: synthesis_pro<br/>compression_profile: compression_fast]
|
||||||
|
D3[facts_stream<br/>filter_types: project, decision, task...<br/>llm_profile: synthesis_pro<br/>compression_profile: compression_fast]
|
||||||
|
end
|
||||||
|
|
||||||
|
subgraph "3. Strategie-Komposition (decision_engine.yaml)"
|
||||||
|
S1[DECISION Strategie<br/>use_streams: values_stream, facts_stream, risk_stream<br/>llm_profile: synthesis_pro<br/>prompt_template: decision_synthesis_v1]
|
||||||
|
end
|
||||||
|
|
||||||
|
subgraph "4. Experten-Profile (llm_profiles.yaml)"
|
||||||
|
P1[synthesis_pro<br/>provider: openrouter<br/>model: google/gemini-2.0-flash-exp:free<br/>temperature: 0.7<br/>fallback_profile: synthesis_backup]
|
||||||
|
P2[compression_fast<br/>provider: openrouter<br/>model: mistralai/mistral-7b-instruct:free<br/>temperature: 0.1<br/>fallback_profile: identity_safe]
|
||||||
|
P3[identity_safe<br/>provider: ollama<br/>model: phi3:mini<br/>temperature: 0.2<br/>fallback_profile: null]
|
||||||
|
end
|
||||||
|
|
||||||
|
subgraph "5. Prompt-Templates (prompts.yaml)"
|
||||||
|
PR1[decision_synthesis_v1<br/>Level 1: google/gemini-2.0-flash-exp:free<br/>Level 2: openrouter<br/>Level 3: default]
|
||||||
|
end
|
||||||
|
|
||||||
|
T1 -->|filter_types| D1
|
||||||
|
T2 -->|filter_types| D2
|
||||||
|
T3 -->|filter_types| D3
|
||||||
|
|
||||||
|
D1 -->|use_streams| S1
|
||||||
|
D2 -->|use_streams| S1
|
||||||
|
D3 -->|use_streams| S1
|
||||||
|
|
||||||
|
S1 -->|llm_profile| P1
|
||||||
|
D1 -->|llm_profile| P3
|
||||||
|
D2 -->|compression_profile| P2
|
||||||
|
D3 -->|compression_profile| P2
|
||||||
|
|
||||||
|
S1 -->|prompt_template| PR1
|
||||||
|
P1 -->|model lookup| PR1
|
||||||
|
|
||||||
|
style T1 fill:#e1f5ff
|
||||||
|
style T2 fill:#e1f5ff
|
||||||
|
style T3 fill:#e1f5ff
|
||||||
|
style D1 fill:#fff4e1
|
||||||
|
style D2 fill:#fff4e1
|
||||||
|
style D3 fill:#fff4e1
|
||||||
|
style S1 fill:#ffe1f5
|
||||||
|
style P1 fill:#e1ffe1
|
||||||
|
style P2 fill:#e1ffe1
|
||||||
|
style P3 fill:#e1ffe1
|
||||||
|
style PR1 fill:#f5e1ff
|
||||||
|
```
|
||||||
|
|
||||||
|
### 7.2 Verbindungs-Matrix
|
||||||
|
|
||||||
|
| Von | Zu | Verbindung | Beschreibung |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| **`types.yaml`** | **`decision_engine.yaml`** | `filter_types` | Streams filtern Notizen basierend auf Typen aus `types.yaml`. Die Liste `filter_types: ["value", "principle", "belief"]` muss exakt den Typ-Namen aus `types.yaml` entsprechen. |
|
||||||
|
| **`types.yaml`** | **`decision_engine.yaml`** | `detection_keywords` | Keywords aus `types.yaml` werden für den Interview-Modus verwendet (z.B. "Projekt" + "neu" → `INTERVIEW`). |
|
||||||
|
| **`decision_engine.yaml`** | **`llm_profiles.yaml`** | `router_profile` | Intent-Erkennung nutzt das Profil `compression_fast` für schnelle Klassifizierung. |
|
||||||
|
| **`decision_engine.yaml`** | **`llm_profiles.yaml`** | `llm_profile` (Stream) | Jeder Stream definiert sein eigenes Profil für Retrieval und Kompression (z.B. `identity_safe` für Privacy). |
|
||||||
|
| **`decision_engine.yaml`** | **`llm_profiles.yaml`** | `llm_profile` (Strategie) | Die finale Synthese nutzt das Strategie-Profil (z.B. `synthesis_pro` für DECISION). |
|
||||||
|
| **`decision_engine.yaml`** | **`llm_profiles.yaml`** | `compression_profile` | Überlange Streams werden via `compression_profile` verdichtet (z.B. `compression_fast`). |
|
||||||
|
| **`decision_engine.yaml`** | **`prompts.yaml`** | `prompt_template` | Strategien referenzieren Template-Keys (z.B. `decision_synthesis_v1`). |
|
||||||
|
| **`llm_profiles.yaml`** | **`prompts.yaml`** | Hierarchische Auflösung | Das aktive Modell aus dem Profil bestimmt, welcher Prompt-Level geladen wird (Model-ID → Provider → Default). |
|
||||||
|
| **`llm_profiles.yaml`** | **`llm_profiles.yaml`** | `fallback_profile` | Rekursive Fallback-Kaskade bei Fehlern (z.B. `synthesis_pro` → `synthesis_backup` → `identity_safe`). |
|
||||||
|
|
||||||
|
### 7.3 Praxisbeispiel: DECISION-Anfrage
|
||||||
|
|
||||||
|
**User-Anfrage:** `"Soll ich das neue Projekt starten?"`
|
||||||
|
|
||||||
|
#### Schritt 1: Intent-Erkennung
|
||||||
|
|
||||||
|
**Datei:** `decision_engine.yaml`
|
||||||
|
```yaml
|
||||||
|
settings:
|
||||||
|
router_profile: "compression_fast" # → llm_profiles.yaml
|
||||||
|
router_prompt_key: "intent_router_v1" # → prompts.yaml
|
||||||
|
```
|
||||||
|
|
||||||
|
**Ablauf:**
|
||||||
|
1. System prüft `trigger_keywords` in `DECISION` Strategie → findet `"soll ich"` → **Intent: DECISION**
|
||||||
|
2. Falls kein Keyword-Match: LLM-Router nutzt `compression_fast` Profil aus `llm_profiles.yaml`
|
||||||
|
3. Router lädt `intent_router_v1` aus `prompts.yaml` (hierarchisch basierend auf aktivem Modell)
|
||||||
|
|
||||||
|
#### Schritt 2: Stream-Aktivierung
|
||||||
|
|
||||||
|
**Datei:** `decision_engine.yaml`
|
||||||
|
```yaml
|
||||||
|
strategies:
|
||||||
|
DECISION:
|
||||||
|
use_streams: ["values_stream", "facts_stream", "risk_stream"]
|
||||||
|
llm_profile: "synthesis_pro" # → llm_profiles.yaml
|
||||||
|
prompt_template: "decision_synthesis_v1" # → prompts.yaml
|
||||||
|
```
|
||||||
|
|
||||||
|
**Ablauf:**
|
||||||
|
1. System aktiviert drei parallele Streams: `values_stream`, `facts_stream`, `risk_stream`
|
||||||
|
|
||||||
|
#### Schritt 3: Stream-Konfiguration & Typ-Filterung
|
||||||
|
|
||||||
|
**Datei:** `decision_engine.yaml` (Streams) + `types.yaml` (Typ-Definitionen)
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
# decision_engine.yaml
|
||||||
|
values_stream:
|
||||||
|
filter_types: ["value", "principle", "belief", "trait", "boundary", "need", "motivation"]
|
||||||
|
llm_profile: "identity_safe" # → llm_profiles.yaml
|
||||||
|
compression_profile: "identity_safe" # → llm_profiles.yaml
|
||||||
|
query_template: "Welche meiner Werte und Prinzipien betreffen: {query}"
|
||||||
|
|
||||||
|
facts_stream:
|
||||||
|
filter_types: ["project", "decision", "task", "goal", "event", "state"]
|
||||||
|
llm_profile: "synthesis_pro" # → llm_profiles.yaml
|
||||||
|
compression_profile: "compression_fast" # → llm_profiles.yaml
|
||||||
|
query_template: "Status, Ressourcen und Fakten zu: {query}"
|
||||||
|
|
||||||
|
risk_stream:
|
||||||
|
filter_types: ["risk", "obstacle", "bias"]
|
||||||
|
llm_profile: "synthesis_pro" # → llm_profiles.yaml
|
||||||
|
compression_profile: "compression_fast" # → llm_profiles.yaml
|
||||||
|
query_template: "Gefahren, Hindernisse oder Risiken bei: {query}"
|
||||||
|
```
|
||||||
|
|
||||||
|
**Ablauf:**
|
||||||
|
1. **Values Stream:** Sucht in Qdrant nach Notizen mit `type IN ["value", "principle", "belief", ...]` (definiert in `types.yaml`)
|
||||||
|
2. **Facts Stream:** Sucht nach Notizen mit `type IN ["project", "decision", "task", ...]` (definiert in `types.yaml`)
|
||||||
|
3. **Risk Stream:** Sucht nach Notizen mit `type IN ["risk", "obstacle", "bias"]` (definiert in `types.yaml`)
|
||||||
|
|
||||||
|
#### Schritt 4: Profil-Auflösung & Modell-Auswahl
|
||||||
|
|
||||||
|
**Datei:** `llm_profiles.yaml`
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
synthesis_pro:
|
||||||
|
provider: "openrouter"
|
||||||
|
model: "google/gemini-2.0-flash-exp:free"
|
||||||
|
temperature: 0.7
|
||||||
|
fallback_profile: "synthesis_backup" # → Rekursiver Fallback
|
||||||
|
|
||||||
|
compression_fast:
|
||||||
|
provider: "openrouter"
|
||||||
|
model: "mistralai/mistral-7b-instruct:free"
|
||||||
|
temperature: 0.1
|
||||||
|
fallback_profile: "identity_safe"
|
||||||
|
|
||||||
|
identity_safe:
|
||||||
|
provider: "ollama"
|
||||||
|
model: "phi3:mini"
|
||||||
|
temperature: 0.2
|
||||||
|
fallback_profile: null # Terminaler Endpunkt
|
||||||
|
```
|
||||||
|
|
||||||
|
**Ablauf:**
|
||||||
|
1. **Values Stream:** Nutzt `identity_safe` → Ollama/phi3:mini (lokal, Privacy)
|
||||||
|
2. **Facts Stream:** Nutzt `synthesis_pro` → OpenRouter/Gemini 2.0 (Cloud)
|
||||||
|
3. **Risk Stream:** Nutzt `synthesis_pro` → OpenRouter/Gemini 2.0 (Cloud)
|
||||||
|
4. **Kompression:** Falls Stream > `compression_threshold`, nutzt `compression_fast` → OpenRouter/Mistral 7B
|
||||||
|
|
||||||
|
#### Schritt 5: Prompt-Loading (Hierarchische Auflösung)
|
||||||
|
|
||||||
|
**Datei:** `prompts.yaml`
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
decision_synthesis_v1:
|
||||||
|
# Level 1: Modell-spezifisch (höchste Priorität)
|
||||||
|
"google/gemini-2.0-flash-exp:free": |
|
||||||
|
Agiere als strategischer Partner für: {query}
|
||||||
|
WERTE: {values_stream} | FAKTEN: {facts_stream} | RISIKEN: {risk_stream}
|
||||||
|
Prüfe die Fakten gegen meine Werte. Zeige Zielkonflikte auf. Gib eine klare Empfehlung.
|
||||||
|
|
||||||
|
# Level 2: Provider-Fallback
|
||||||
|
openrouter: |
|
||||||
|
Strategische Multi-Stream Analyse für: {query}
|
||||||
|
Werte-Basis: {values_stream} | Fakten: {facts_stream} | Risiken: {risk_stream}
|
||||||
|
Bitte wäge ab und gib eine Empfehlung.
|
||||||
|
|
||||||
|
# Level 3: Global Default
|
||||||
|
default: "Prüfe {query} gegen Werte {values_stream} und Fakten {facts_stream}."
|
||||||
|
```
|
||||||
|
|
||||||
|
**Ablauf:**
|
||||||
|
1. System hat `synthesis_pro` Profil geladen → Modell: `google/gemini-2.0-flash-exp:free`
|
||||||
|
2. System sucht in `prompts.yaml` nach `decision_synthesis_v1`:
|
||||||
|
- **Level 1:** Findet exakten Match für `google/gemini-2.0-flash-exp:free` → **Verwendet diesen Prompt**
|
||||||
|
- Falls nicht gefunden: **Level 2** → `openrouter` Fallback
|
||||||
|
- Falls nicht gefunden: **Level 3** → `default` Fallback
|
||||||
|
3. Prompt wird mit Stream-Variablen formatiert: `{values_stream}`, `{facts_stream}`, `{risk_stream}`, `{query}`
|
||||||
|
|
||||||
|
#### Schritt 6: Finale Synthese
|
||||||
|
|
||||||
|
**Ablauf:**
|
||||||
|
1. System ruft LLM auf mit:
|
||||||
|
- **Profil:** `synthesis_pro` (OpenRouter/Gemini 2.0, Temperature 0.7)
|
||||||
|
- **Prompt:** Level-1 Template aus `prompts.yaml` (modell-spezifisch optimiert)
|
||||||
|
- **Variablen:** Formatierte Stream-Inhalte
|
||||||
|
2. Falls Fehler (z.B. Rate-Limit 429):
|
||||||
|
- **Fallback:** `synthesis_backup` (Llama 3.3)
|
||||||
|
- **Prompt:** Automatisch Level-2 (`openrouter`) oder Level-3 (`default`) geladen
|
||||||
|
3. Antwort wird an User zurückgegeben
|
||||||
|
|
||||||
|
### 7.4 Konfigurations-Synchronisation Checkliste
|
||||||
|
|
||||||
|
Beim Ändern einer Konfigurationsdatei müssen folgende Abhängigkeiten geprüft werden:
|
||||||
|
|
||||||
|
**✅ `types.yaml` ändern:**
|
||||||
|
- [ ] Prüfe, ob `filter_types` in `decision_engine.yaml` Streams noch gültig sind
|
||||||
|
- [ ] Prüfe, ob `detection_keywords` für Interview-Modus noch passen
|
||||||
|
- [ ] Prüfe, ob `chunking_profile` noch existiert (in `types.yaml` definiert)
|
||||||
|
|
||||||
|
**✅ `decision_engine.yaml` ändern:**
|
||||||
|
- [ ] Prüfe, ob alle `filter_types` in Streams existieren in `types.yaml`
|
||||||
|
- [ ] Prüfe, ob alle `llm_profile` / `compression_profile` existieren in `llm_profiles.yaml`
|
||||||
|
- [ ] Prüfe, ob alle `prompt_template` Keys existieren in `prompts.yaml`
|
||||||
|
|
||||||
|
**✅ `llm_profiles.yaml` ändern:**
|
||||||
|
- [ ] Prüfe, ob `fallback_profile` Referenzen zirkulär sind (Schutz: `visited_profiles`)
|
||||||
|
- [ ] Prüfe, ob alle referenzierten Profile existieren
|
||||||
|
- [ ] Prüfe, ob Modell-IDs mit `prompts.yaml` Level-1 Keys übereinstimmen (optional, aber empfohlen)
|
||||||
|
|
||||||
|
**✅ `prompts.yaml` ändern:**
|
||||||
|
- [ ] Prüfe, ob alle `prompt_template` Keys aus `decision_engine.yaml` existieren
|
||||||
|
- [ ] Prüfe, ob Modell-spezifische Keys (Level 1) mit `llm_profiles.yaml` Modell-IDs übereinstimmen
|
||||||
|
- [ ] Prüfe, ob alle Stream-Variablen (`{values_stream}`, `{facts_stream}`, etc.) initialisiert werden
|
||||||
|
|
||||||
|
### 7.5 Debugging-Tipps
|
||||||
|
|
||||||
|
**Problem:** Stream findet keine Notizen
|
||||||
|
- **Prüfung:** `filter_types` in Stream stimmt mit Typ-Namen in `types.yaml` überein? (Case-sensitive!)
|
||||||
|
- **Prüfung:** Existieren Notizen mit diesen Typen im Vault?
|
||||||
|
|
||||||
|
**Problem:** Falsches Modell wird verwendet
|
||||||
|
- **Prüfung:** `llm_profile` in Stream/Strategie existiert in `llm_profiles.yaml`?
|
||||||
|
- **Prüfung:** `fallback_profile` Kaskade führt zu unerwartetem Modell?
|
||||||
|
|
||||||
|
**Problem:** Prompt wird nicht gefunden
|
||||||
|
- **Prüfung:** `prompt_template` Key existiert in `prompts.yaml`?
|
||||||
|
- **Prüfung:** Hierarchische Auflösung (Level 1 → 2 → 3) funktioniert? (Logs: `[PROMPT-TRACE]`)
|
||||||
|
|
||||||
|
**Problem:** Kompression wird nicht ausgelöst
|
||||||
|
- **Prüfung:** `compression_threshold` in Stream-Konfiguration gesetzt?
|
||||||
|
- **Prüfung:** `compression_profile` existiert in `llm_profiles.yaml`?
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
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
|
||||||
|
```
|
||||||
@@ -3,15 +3,15 @@ doc_type: technical_reference
|
|||||||
audience: developer, architect
|
audience: developer, architect
|
||||||
scope: database, qdrant, schema
|
scope: database, qdrant, schema
|
||||||
status: active
|
status: active
|
||||||
version: 2.7.0
|
version: 2.9.1
|
||||||
context: "Exakte Definition der Datenmodelle (Payloads) in Qdrant und Index-Anforderungen."
|
context: "Exakte Definition der Datenmodelle (Payloads) in Qdrant und Index-Anforderungen. Berücksichtigt WP-14 Modularisierung und WP-15b Multi-Hashes."
|
||||||
---
|
---
|
||||||
|
|
||||||
# Technisches Datenmodell (Qdrant Schema)
|
# Technisches Datenmodell (Qdrant Schema)
|
||||||
|
|
||||||
## 1. Collections & Namenskonvention
|
## 1. Collections & Namenskonvention
|
||||||
|
|
||||||
Mindnet speichert Daten in drei getrennten Qdrant-Collections. Der Prefix ist via ENV `COLLECTION_PREFIX` konfigurierbar (Default: `mindnet`).
|
Mindnet speichert Daten in drei getrennten Qdrant-Collections. Der Prefix ist via ENV `COLLECTION_PREFIX` konfigurierbar (Default: `mindnet`). Die Auflösung erfolgt zentral über `app.core.database.collection_names`.
|
||||||
|
|
||||||
Das System nutzt folgende drei Collections:
|
Das System nutzt folgende drei Collections:
|
||||||
* `{prefix}_notes`: Metadaten der Dateien.
|
* `{prefix}_notes`: Metadaten der Dateien.
|
||||||
@@ -28,9 +28,10 @@ Repräsentiert die Metadaten einer Markdown-Datei (1:1 Beziehung).
|
|||||||
|
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
"note_id": "string (keyword)", // UUIDv5 (deterministisch) oder Slug
|
"note_id": "string (keyword)", // UUIDv5 (deterministisch via NAMESPACE_URL)
|
||||||
"title": "string (text)", // Titel aus Frontmatter
|
"title": "string (text)", // Titel aus Frontmatter
|
||||||
"type": "string (keyword)", // Logischer Typ (z.B. 'project', 'concept')
|
"type": "string (keyword)", // Logischer Typ (z.B. 'project', 'concept')
|
||||||
|
"status": "string (keyword)", // Lifecycle: 'stable', 'active', 'draft', 'system' (WP-22)
|
||||||
"retriever_weight": "float", // Effektive Wichtigkeit (Frontmatter > Type > Default)
|
"retriever_weight": "float", // Effektive Wichtigkeit (Frontmatter > Type > Default)
|
||||||
"chunk_profile": "string", // Effektives Profil (Frontmatter > Type > Default)
|
"chunk_profile": "string", // Effektives Profil (Frontmatter > Type > Default)
|
||||||
"edge_defaults": ["string"], // Liste der aktiven Default-Kanten
|
"edge_defaults": ["string"], // Liste der aktiven Default-Kanten
|
||||||
@@ -40,7 +41,7 @@ Repräsentiert die Metadaten einer Markdown-Datei (1:1 Beziehung).
|
|||||||
"updated": "integer", // Timestamp (File Modification Time)
|
"updated": "integer", // Timestamp (File Modification Time)
|
||||||
"fulltext": "string (no-index)", // Gesamter Text (nur für Recovery/Export)
|
"fulltext": "string (no-index)", // Gesamter Text (nur für Recovery/Export)
|
||||||
|
|
||||||
// NEU in v2.7: Multi-Hash für flexible Change Detection
|
// Multi-Hash für flexible Change Detection (WP-15b)
|
||||||
"hashes": {
|
"hashes": {
|
||||||
"body:parsed:canonical": "string", // Hash nur über den Text-Body
|
"body:parsed:canonical": "string", // Hash nur über den Text-Body
|
||||||
"full:parsed:canonical": "string" // Hash über Text + Metadaten (Tags, Title, Config)
|
"full:parsed:canonical": "string" // Hash über Text + Metadaten (Tags, Title, Config)
|
||||||
@@ -52,6 +53,7 @@ Repräsentiert die Metadaten einer Markdown-Datei (1:1 Beziehung).
|
|||||||
Es müssen Payload-Indizes für folgende Felder existieren:
|
Es müssen Payload-Indizes für folgende Felder existieren:
|
||||||
* `note_id`
|
* `note_id`
|
||||||
* `type`
|
* `type`
|
||||||
|
* `status`
|
||||||
* `tags`
|
* `tags`
|
||||||
|
|
||||||
---
|
---
|
||||||
@@ -61,7 +63,7 @@ Es müssen Payload-Indizes für folgende Felder existieren:
|
|||||||
Die atomare Sucheinheit. Enthält den Vektor.
|
Die atomare Sucheinheit. Enthält den Vektor.
|
||||||
|
|
||||||
**Vektor-Konfiguration:**
|
**Vektor-Konfiguration:**
|
||||||
* Modell: `nomic-embed-text`
|
* Modell: `nomic-embed-text` (via Ollama oder Cloud)
|
||||||
* Dimension: **768**
|
* Dimension: **768**
|
||||||
* Metrik: Cosine Similarity
|
* Metrik: Cosine Similarity
|
||||||
|
|
||||||
@@ -69,7 +71,7 @@ Die atomare Sucheinheit. Enthält den Vektor.
|
|||||||
|
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
"chunk_id": "string (keyword)", // Format: {note_id}#c{index} (z.B. 'abc-123#c01')
|
"chunk_id": "string (keyword)", // Format: UUIDv5 aus {note_id}#c{index}
|
||||||
"note_id": "string (keyword)", // Foreign Key zur Note
|
"note_id": "string (keyword)", // Foreign Key zur Note
|
||||||
"type": "string (keyword)", // Kopie aus Note (Denormalisiert für Filterung)
|
"type": "string (keyword)", // Kopie aus Note (Denormalisiert für Filterung)
|
||||||
"text": "string (text)", // Reintext für Anzeige (ohne Overlap)
|
"text": "string (text)", // Reintext für Anzeige (ohne Overlap)
|
||||||
@@ -94,15 +96,19 @@ Es müssen Payload-Indizes für folgende Felder existieren:
|
|||||||
|
|
||||||
## 4. Edge Payload (`mindnet_edges`)
|
## 4. Edge Payload (`mindnet_edges`)
|
||||||
|
|
||||||
Gerichtete Kanten zwischen Knoten. Stark erweitert in v2.6 für Provenienz-Tracking.
|
Gerichtete Kanten zwischen Knoten. Stark erweitert in v2.6 für Provenienz-Tracking. Seit v2.9.1 unterstützt das System **Section-basierte Links** (`[[Note#Section]]`), die in `target_id` und `target_section` aufgeteilt werden.
|
||||||
|
|
||||||
**JSON-Schema:**
|
**JSON-Schema:**
|
||||||
|
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
"edge_id": "string (keyword)", // Deterministischer Hash aus (src, dst, kind)
|
"edge_id": "string (keyword)", // Deterministischer Hash aus (src, dst, kind, variant)
|
||||||
|
// variant = target_section (erlaubt Multigraph für Sections)
|
||||||
"source_id": "string (keyword)", // Chunk-ID (Start)
|
"source_id": "string (keyword)", // Chunk-ID (Start)
|
||||||
"target_id": "string (keyword)", // Chunk-ID oder Note-Titel (bei Unresolved)
|
"target_id": "string (keyword)", // Chunk-ID oder Note-Titel (bei Unresolved)
|
||||||
|
// WICHTIG: Enthält NUR den Note-Namen, KEINE Section-Info
|
||||||
|
"target_section": "string (keyword)", // Optional: Abschnitts-Name (z.B. "P3 – Disziplin")
|
||||||
|
// Wird aus [[Note#Section]] extrahiert
|
||||||
"kind": "string (keyword)", // Beziehungsart (z.B. 'depends_on')
|
"kind": "string (keyword)", // Beziehungsart (z.B. 'depends_on')
|
||||||
"scope": "string (keyword)", // Immer 'chunk' (Legacy-Support: 'note')
|
"scope": "string (keyword)", // Immer 'chunk' (Legacy-Support: 'note')
|
||||||
"note_id": "string (keyword)", // Owner Note ID (Ursprung der Kante)
|
"note_id": "string (keyword)", // Owner Note ID (Ursprung der Kante)
|
||||||
@@ -114,10 +120,19 @@ Gerichtete Kanten zwischen Knoten. Stark erweitert in v2.6 für Provenienz-Track
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
**Section-Support (WP-15c):**
|
||||||
|
* Links wie `[[Note#Section]]` werden in `target_id="Note"` und `target_section="Section"` aufgeteilt.
|
||||||
|
* **Self-Links:** `[[#Section]]` wird zu `target_id="current_note_id"` und `target_section="Section"` aufgelöst.
|
||||||
|
* Die Edge-ID enthält die Section als `variant`, sodass mehrere Kanten zwischen denselben Knoten existieren können, wenn sie auf verschiedene Sections zeigen (Multigraph-Modus).
|
||||||
|
* Semantische Deduplizierung basiert auf `src->tgt:kind@sec` Key, um "Phantom-Knoten" zu vermeiden.
|
||||||
|
* **Metadaten-Persistenz:** `target_section`, `provenance` und `confidence` werden durchgängig im In-Memory Subgraph und Datenbank-Adapter erhalten.
|
||||||
|
|
||||||
**Erforderliche Indizes:**
|
**Erforderliche Indizes:**
|
||||||
Es müssen Payload-Indizes für folgende Felder existieren:
|
Es müssen Payload-Indizes für folgende Felder existieren:
|
||||||
* `source_id`
|
* `source_id`
|
||||||
* `target_id`
|
* `target_id`
|
||||||
|
* `target_section` (neu: Keyword-Index für Section-basierte Filterung)
|
||||||
* `kind`
|
* `kind`
|
||||||
* `scope`
|
* `scope`
|
||||||
* `note_id`
|
* `note_id`
|
||||||
|
```
|
||||||
@@ -3,7 +3,7 @@ doc_type: technical_reference
|
|||||||
audience: developer, frontend_architect
|
audience: developer, frontend_architect
|
||||||
scope: architecture, graph_viz, state_management
|
scope: architecture, graph_viz, state_management
|
||||||
status: active
|
status: active
|
||||||
version: 2.7.0
|
version: 2.9.1
|
||||||
context: "Technische Dokumentation des modularen Streamlit-Frontends, der Graph-Engines und des Editors."
|
context: "Technische Dokumentation des modularen Streamlit-Frontends, der Graph-Engines und des Editors."
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
@@ -1,71 +1,104 @@
|
|||||||
---
|
---
|
||||||
doc_type: technical_reference
|
doc_type: technical_reference
|
||||||
audience: developer, devops
|
audience: developer, devops
|
||||||
scope: backend, ingestion, smart_edges, edge_registry
|
scope: backend, ingestion, smart_edges, edge_registry, modularization, moe, lazy_prompts
|
||||||
status: active
|
status: active
|
||||||
version: 2.7.1
|
version: 2.14.0
|
||||||
context: "Detaillierte technische Beschreibung der Import-Pipeline, Chunking-Strategien und CLI-Befehle."
|
context: "Detaillierte technische Beschreibung der Import-Pipeline, Two-Pass-Workflow (WP-15b), modularer Datenbank-Architektur (WP-14), WP-25a profilgesteuerte Validierung und WP-25b Lazy-Prompt-Orchestration. Integriert Mistral-safe Parsing und Deep Fallback."
|
||||||
---
|
---
|
||||||
|
|
||||||
# Ingestion Pipeline & Smart Processing
|
# Ingestion Pipeline & Smart Processing
|
||||||
|
|
||||||
**Quellen:** `pipeline_playbook.md`, `Handbuch.md`, `edge_registry.py`, `01_edge_vocabulary.md`, `06_active_roadmap.md`
|
**Quellen:** `pipeline_playbook.md`, `ingestion_processor.py`, `ingestion_db.py`, `ingestion_validation.py`, `registry.py`, `edge_registry.py`
|
||||||
|
|
||||||
Die Ingestion transformiert Markdown in den Graphen. Entrypoint: `scripts/import_markdown.py` (CLI) oder `routers/ingest.py` (API). Seit v2.7 integriert dieser Prozess die **Edge Registry** zur Normalisierung des Vokabulars und beachtet den **Content Lifecycle**.
|
Die Ingestion transformiert Markdown in den Graphen. Entrypoint: `scripts/import_markdown.py` (CLI) oder `routers/ingest.py` (API). Seit v2.9 nutzt dieser Prozess ein hocheffizientes **Two-Pass-Verfahren**, um globale Kontext-Informationen für die semantische Validierung bereitzustellen, ohne die Idempotenz oder die Change-Detection zu verletzen.
|
||||||
|
|
||||||
## 1. Der Import-Prozess (15-Schritte-Workflow)
|
|
||||||
|
|
||||||
Der Prozess ist **asynchron** und **idempotent**.
|
|
||||||
|
|
||||||
|
## 1. Der Import-Prozess (16-Schritte-Workflow)
|
||||||
|
|
||||||
|
Der Prozess ist **asynchron**, **idempotent** und wird nun in zwei logische Durchläufe (Passes) unterteilt, um die semantische Genauigkeit zu maximieren.
|
||||||
|
|
||||||
|
### Phase 1: Pre-Scan & Context (Pass 1)
|
||||||
1. **Trigger & Async Dispatch:**
|
1. **Trigger & Async Dispatch:**
|
||||||
* **API (`/save`):** Nimmt Request entgegen, validiert und startet Background-Task ("Fire & Forget"). Antwortet sofort mit `202/Queued`.
|
* **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.
|
* **CLI:** Iteriert über Dateien und nutzt `asyncio.Semaphore` zur Drosselung.
|
||||||
2. **Markdown lesen:** Rekursives Scannen des Vaults.
|
2. **Markdown lesen:** Rekursives Scannen des Vaults zur Erstellung des Dateiinventars.
|
||||||
3. **Frontmatter Check & Hard Skip (WP-22):**
|
3. **Frontmatter Check & Hard Skip (WP-22):**
|
||||||
* Extraktion von `status` und `type`.
|
* Extraktion von `status` und `type`.
|
||||||
* **Hard Skip Rule:** Wenn `status` in `['system', 'template']` ist, wird die Datei **sofort übersprungen**. Sie wird weder vektorisiert noch in den Graphen aufgenommen.
|
* **Hard Skip Rule:** Wenn `status` in `['system', 'template', 'archive', 'hidden']` ist, wird die Datei für das Deep-Processing übersprungen, ihre Metadaten werden jedoch für den Kontext-Cache erfasst.
|
||||||
* Validierung der Pflichtfelder (`id`, `title`) für alle anderen Dateien.
|
* Validierung der Pflichtfelder (`id`, `title`) für alle anderen Dateien.
|
||||||
4. **Edge Registry Initialisierung (WP-22):**
|
4. **Edge Registry Initialisierung (WP-22):**
|
||||||
* Laden der Singleton-Instanz der `EdgeRegistry`.
|
* Laden der Singleton-Instanz der `EdgeRegistry`.
|
||||||
* Validierung der Vokabular-Datei unter `MINDNET_VOCAB_PATH`.
|
* Validierung der Vokabular-Datei unter `MINDNET_VOCAB_PATH`.
|
||||||
5. **Config Resolution:**
|
5. **Config Resolution (WP-14 / v2.13.12):**
|
||||||
* Bestimmung von `chunking_profile` und `retriever_weight`.
|
* Bestimmung von `chunking_profile` und `retriever_weight` via zentraler `TypeRegistry`.
|
||||||
* **Priorität:** 1. Frontmatter (Override) -> 2. `types.yaml` (Type) -> 3. Global Default.
|
* **Priorität:** 1. Frontmatter (Override) -> 2. `types.yaml` (Type) -> 3. Global Default.
|
||||||
6. **Note-Payload generieren:**
|
* **Registry-First Profiling:** Automatische Anwendung der korrekten Profile basierend auf dem Note-Typ (z.B. `value` nutzt automatisch `structured_smart_edges_strict`).
|
||||||
* Erstellen des JSON-Objekts inklusive `status` (für Scoring).
|
6. **LocalBatchCache & Summary Generation (WP-15b):**
|
||||||
* **Multi-Hash Calculation:** Berechnet Hashtabellen für `body` (nur Text) und `full` (Text + Metadaten).
|
* Erstellung von Kurz-Zusammenfassungen für jede Note.
|
||||||
7. **Change Detection:**
|
* Speicherung im `batch_cache` als Referenzrahmen für die spätere Kantenvalidierung.
|
||||||
* Vergleich des Hashes mit Qdrant.
|
|
||||||
* Strategie wählbar via ENV `MINDNET_CHANGE_DETECTION_MODE` (`full` oder `body`).
|
### Phase 2: Semantic Processing & Persistence (Pass 2)
|
||||||
8. **Chunking anwenden:** Zerlegung des Textes basierend auf dem ermittelten Profil (siehe Kap. 3).
|
7. **Note-Payload & Multi-Hash (WP-15b):**
|
||||||
9. **Smart Edge Allocation (WP15):**
|
* Erstellen des JSON-Objekts inklusive `status`.
|
||||||
* Wenn `enable_smart_edge_allocation: true`: Der `SemanticAnalyzer` sendet Chunks an das LLM.
|
* **Multi-Hash Calculation:** Berechnet Hashtabellen für `body` (nur Text) und `full` (Text + Metadaten) zur präzisen Änderungskontrolle.
|
||||||
* **Traffic Control:** Request nutzt `priority="background"`. Semaphore (Limit via `.env`) drosselt die Last.
|
8. **Change Detection:**
|
||||||
* **Resilienz:** Bei Timeout (Ollama) greift ein Fallback (Broadcasting an alle Chunks).
|
* Vergleich des aktuellen Hashes mit den Daten in Qdrant (Collection `{prefix}_notes`).
|
||||||
10. **Inline-Kanten finden:** Parsing von `[[rel:...]]`.
|
* Strategie wählbar via ENV `MINDNET_CHANGE_DETECTION_MODE` (`full` oder `body`). Unveränderte Dateien werden hier final übersprungen.
|
||||||
11. **Alias-Auflösung & Kanonisierung (WP-22):**
|
9. **Purge Old Artifacts (WP-14):**
|
||||||
* Jede Kante wird via `edge_registry.resolve()` normalisiert.
|
* Bei Änderungen löscht `purge_artifacts()` via `app.core.ingestion.ingestion_db` alle alten Chunks und Edges der Note.
|
||||||
* Aliase (z.B. `basiert_auf`) werden zu kanonischen Typen (z.B. `based_on`) aufgelöst.
|
* Die Namensauflösung erfolgt nun über das modularisierte `database`-Paket.
|
||||||
|
10. **Chunking anwenden:** Zerlegung des Textes basierend auf dem ermittelten Profil (siehe Kap. 3).
|
||||||
|
11. **Smart Edge Allocation & Semantic Validation (WP-15b / WP-25a / WP-25b):**
|
||||||
|
* Der `SemanticAnalyzer` schlägt Kanten-Kandidaten vor.
|
||||||
|
* **Validierung (WP-25a/25b):** Jeder Kandidat wird durch das LLM semantisch gegen das Ziel im **LocalBatchCache** geprüft.
|
||||||
|
* **Profilgesteuerte Validierung:** Nutzt das MoE-Profil `ingest_validator` (Temperature 0.0 für maximale Determinismus).
|
||||||
|
* **Lazy-Prompt-Loading (WP-25b):** Nutzt `prompt_key="edge_validation"` mit `variables` statt vorformatierter Strings.
|
||||||
|
* **Hierarchische Resolution:** Level 1 (Modell-ID) → Level 2 (Provider) → Level 3 (Default)
|
||||||
|
* **Differenzierte Fehlerbehandlung (WP-25b):** Unterscheidung zwischen transienten (Netzwerk) und permanenten (Config) Fehlern:
|
||||||
|
* **Transiente Fehler:** Timeout, Connection, Network → Kante wird erlaubt (Datenverlust vermeiden)
|
||||||
|
* **Permanente Fehler:** Config, Validation, Invalid Response → Kante wird abgelehnt (Graph-Qualität schützen)
|
||||||
|
* **Fallback-Kaskade:** Bei Fehlern erfolgt automatischer Fallback via `fallback_profile` (z.B. `compression_fast` → `identity_safe`).
|
||||||
|
* **Traffic Control:** Nutzung der neutralen `clean_llm_text` Funktion zur Bereinigung von Steuerzeichen (<s>, [OUT]).
|
||||||
|
* **Deep Fallback (v2.11.14):** Erkennt "Silent Refusals". Liefert die Cloud keine verwertbaren Kanten, wird ein lokaler Fallback via Ollama erzwungen.
|
||||||
|
12. **Inline-Kanten finden:** Parsing von `[[rel:...]]` und Callouts.
|
||||||
|
13. **Alias-Auflösung & Kanonisierung (WP-22):**
|
||||||
|
* Jede Kante wird via `EdgeRegistry` normalisiert (z.B. `basiert_auf` -> `based_on`).
|
||||||
* Unbekannte Typen werden in `unknown_edges.jsonl` protokolliert.
|
* Unbekannte Typen werden in `unknown_edges.jsonl` protokolliert.
|
||||||
12. **Callout-Kanten finden:** Parsing von `> [!edge]`.
|
14. **Default- & Strukturkanten:** Anwendung der `edge_defaults` und Erzeugung von Systemkanten (`belongs_to`, `next`, `prev`).
|
||||||
13. **Default- & Matrix-Edges erzeugen:** Anwendung der `edge_defaults` aus Registry und Matrix-Logik.
|
15. **Embedding (Async - WP-25a):** Generierung der Vektoren via `embedding_expert` Profil aus `llm_profiles.yaml`.
|
||||||
14. **Strukturkanten erzeugen:** `belongs_to`, `next`, `prev`.
|
* **Profil-Auflösung:** Das `EmbeddingsClient` lädt Modell und Dimensionen direkt aus dem Profil (z.B. `nomic-embed-text`, 768 Dimensionen).
|
||||||
15. **Embedding (Async):** Generierung via `nomic-embed-text` (768 Dim).
|
* **Konsolidierung:** Entfernung der Embedding-Konfiguration aus der `.env` zugunsten zentraler Profil-Registry.
|
||||||
16. **Diagnose:** Integritäts-Check nach dem Lauf.
|
16. **Database Sync (WP-14):** Batch-Upsert aller Points in die Collections `{prefix}_chunks` und `{prefix}_edges` über die zentrale Infrastruktur.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 2. Betrieb & CLI Befehle
|
## 2. Betrieb & CLI Befehle
|
||||||
|
|
||||||
### 2.1 Standard-Betrieb (Inkrementell)
|
### 2.1 API-Endpunkt: `/ingest/save` (Background Tasks)
|
||||||
Für regelmäßige Updates (Cronjob). Erkennt Änderungen via Hash.
|
|
||||||
|
Seit WP-14 nutzt der `/ingest/save` Endpunkt **Background Tasks** für non-blocking Ingestion:
|
||||||
|
|
||||||
|
**Workflow:**
|
||||||
|
1. **Request:** Frontend sendet Markdown an `/ingest/save`
|
||||||
|
2. **Sofortige Antwort:** API antwortet mit `status: "queued"` und `note_id: "pending"`
|
||||||
|
3. **Datei-Persistenz:** Markdown wird sofort auf Festplatte geschrieben
|
||||||
|
4. **Background Task:** Ingestion läuft asynchron im Hintergrund
|
||||||
|
- Chunking
|
||||||
|
- Embedding-Generierung
|
||||||
|
- Smart Edge Allocation (WP-15)
|
||||||
|
- Hybrid-Cloud-Analyse (WP-20)
|
||||||
|
5. **Vorteil:** Keine Timeouts bei großen Dateien oder langsamen LLM-Calls
|
||||||
|
|
||||||
|
**Hinweis:** Die tatsächliche `note_id` steht erst nach dem Parsing fest. Das Frontend sollte den `file_path` für Tracking nutzen.
|
||||||
|
|
||||||
|
### 2.2 CLI-Betrieb (Inkrementell)
|
||||||
|
Erkennt Änderungen via Multi-Hash.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
export QDRANT_URL="http://localhost:6333"
|
export QDRANT_URL="http://localhost:6333"
|
||||||
export COLLECTION_PREFIX="mindnet"
|
export COLLECTION_PREFIX="mindnet"
|
||||||
# Steuert, wann eine Datei als "geändert" gilt
|
|
||||||
export MINDNET_CHANGE_DETECTION_MODE="full"
|
export MINDNET_CHANGE_DETECTION_MODE="full"
|
||||||
|
|
||||||
# Nutzt das Venv der Produktionsumgebung
|
# Nutzt das Venv der Produktionsumgebung
|
||||||
@@ -78,20 +111,13 @@ export MINDNET_CHANGE_DETECTION_MODE="full"
|
|||||||
```
|
```
|
||||||
|
|
||||||
> **[!WARNING] Purge-Before-Upsert**
|
> **[!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).
|
> Das Flag `--purge-before-upsert` nutzt nun `ingestion_db.purge_artifacts`. Es ist kritisch, um "Geister-Chunks" (verwaiste Daten nach Textlöschung) konsistent aus den spezialisierten Collections zu entfernen.
|
||||||
|
|
||||||
### 2.2 Full Rebuild (Clean Slate)
|
### 2.2 Full Rebuild (Clean Slate)
|
||||||
Notwendig bei Änderungen an `types.yaml` (z.B. neue Chunking-Profile), der Registry oder Modell-Wechsel.
|
Notwendig bei Änderungen an `types.yaml`, der Registry oder Modell-Wechsel.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# 0. Modell sicherstellen
|
# --force ignoriert alle Hashes und erzwingt den vollständigen Two-Pass Workflow
|
||||||
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
|
python3 -m scripts.import_markdown --vault ./vault --prefix "mindnet" --apply --force
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -99,38 +125,55 @@ python3 -m scripts.import_markdown --vault ./vault --prefix "mindnet" --apply --
|
|||||||
|
|
||||||
## 3. Chunking & Payload
|
## 3. Chunking & Payload
|
||||||
|
|
||||||
Das Chunking ist profilbasiert und in `types.yaml` konfiguriert.
|
Das Chunking ist profilbasiert und bezieht seine Konfiguration dynamisch aus der `TypeRegistry`.
|
||||||
|
|
||||||
### 3.1 Profile und Strategien (Vollständige Referenz)
|
### 3.1 Profile und Strategien
|
||||||
|
|
||||||
| Profil | Strategie | Parameter | Einsatzgebiet |
|
| Profil | Strategie | Parameter | Einsatzgebiet |
|
||||||
| :--- | :--- | :--- | :--- |
|
| :--- | :--- | :--- | :--- |
|
||||||
| `sliding_short` | `sliding_window` | Max: 350, Target: 200 | Kurze Logs, Chats, Risiken. |
|
| `sliding_short` | `sliding_window` | Max: 350, Target: 200 | Kurze Logs, Chats. |
|
||||||
| `sliding_standard` | `sliding_window` | Max: 650, Target: 450 | Massendaten (Journal, Quellen). |
|
| `sliding_standard` | `sliding_window` | Max: 650, Target: 450 | Standard-Wissen. |
|
||||||
| `sliding_smart_edges`| `sliding_window` | Max: 600, Target: 400 | Fließtexte mit hohem Wert (Projekte). |
|
| `sliding_smart_edges`| `sliding_window` | Max: 600, Target: 400 | Fließtexte (Projekte). |
|
||||||
| `structured_smart_edges` | `by_heading` | `strict: false` (Soft) | Strukturierte Texte, Merging erlaubt. |
|
| `structured_smart_edges` | `by_heading` | `strict: false` | Strukturierte Texte. |
|
||||||
| `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)
|
### 3.2 Die `by_heading` Logik (v3.9.9 Atomic Section Logic)
|
||||||
|
|
||||||
Die Strategie `by_heading` zerlegt Texte anhand ihrer Struktur (Überschriften). Sie unterstützt seit v2.9 ein "Safety Net" gegen zu große Chunks.
|
Die Strategie `by_heading` implementiert seit v3.9.9 das **"Pack-and-Carry-Over"** Verfahren (Regel 1-3), um Sektions-Überschriften und deren Inhalte atomar in Chunks zu halten.
|
||||||
|
|
||||||
* **Split Level:** Definiert die Tiefe (z.B. `2` = H1 & H2 triggern Split).
|
**Kernprinzipien:**
|
||||||
* **Modus "Strict" (`strict_heading_split: true`):**
|
* **Atomic Section Logic:** Überschriften und deren Inhalte werden als atomare Einheiten behandelt und nicht über Chunk-Grenzen hinweg getrennt.
|
||||||
* Jede Überschrift (`<= split_level`) erzwingt einen neuen Chunk.
|
* **H1-Context Preservation:** Der Dokumenttitel (H1) wird zuverlässig als Breadcrumb in das Embedding-Fenster (`window`) aller Chunks injiziert.
|
||||||
* *Merge-Check:* Wenn der vorherige Chunk leer war (nur Überschriften), wird gemergt (verhindert verwaiste Überschriften).
|
* **Signature Alignment:** Parameter-Synchronisierung zwischen Orchestrator und Strategien (`context_prefix` statt `doc_title`).
|
||||||
* *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 (z.B. H2) 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)
|
**Split Level:** Definiert die Tiefe (z.B. `2` = H1 & H2 triggern Split).
|
||||||
|
|
||||||
* `text`: Der reine Inhalt (Anzeige im UI).
|
**Modus "Strict" (`strict_heading_split: true`):**
|
||||||
* `window`: Inhalt plus Overlap (für Embedding).
|
* Jede Überschrift (`<= split_level`) erzwingt einen neuen Chunk.
|
||||||
* `chunk_profile`: Das effektiv genutzte Profil (zur Nachverfolgung).
|
* *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.
|
||||||
|
* **Pack-and-Carry-Over:** Wenn ein Abschnitt zu groß ist, wird er intelligent zerlegt, wobei der Rest (mit Überschrift) zurück in die Queue gelegt wird.
|
||||||
|
* *Safety Net:* Auch hier greift das `max` Token Limit.
|
||||||
|
|
||||||
|
### 3.3 Registry-First Profiling (v2.13.12)
|
||||||
|
|
||||||
|
Seit v2.13.12 nutzt der `IngestionService` die korrekte Hierarchie zur Ermittlung des Chunking-Profils:
|
||||||
|
|
||||||
|
**Priorität:**
|
||||||
|
1. **Frontmatter** (Override) - Explizite `chunking_profile` Angabe
|
||||||
|
2. **`types.yaml` Typ-Config** - Profil basierend auf `type`
|
||||||
|
3. **Global Defaults** - Fallback auf `sliding_standard`
|
||||||
|
|
||||||
|
**Wichtig:** Ein Hard-Fallback auf `sliding_standard` erfolgt nur noch, wenn keine Konfiguration existiert. Dies stellt sicher, dass Note-Typen wie `value` automatisch das korrekte Profil (z.B. `structured_smart_edges_strict`) erhalten.
|
||||||
|
|
||||||
|
### 3.4 Deterministic Hashing (v2.13.12)
|
||||||
|
|
||||||
|
Der `full`-Hash inkludiert nun alle strategischen Parameter (z.B. `split_level`, `strict_heading_split`), sodass Konfigurationsänderungen im Frontmatter zwingend einen Re-Import auslösen.
|
||||||
|
|
||||||
|
**Impact:** Änderungen an Chunking-Parametern werden zuverlässig erkannt, auch wenn der Text unverändert bleibt.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -138,31 +181,23 @@ Die Strategie `by_heading` zerlegt Texte anhand ihrer Struktur (Überschriften).
|
|||||||
|
|
||||||
Kanten werden nach Vertrauenswürdigkeit (`provenance`) priorisiert. Die höhere Prio gewinnt.
|
Kanten werden nach Vertrauenswürdigkeit (`provenance`) priorisiert. Die höhere Prio gewinnt.
|
||||||
|
|
||||||
| Prio | Quelle | Rule ID | Confidence | Erläuterung |
|
| Prio | Quelle | Rule ID / Provenance | Confidence | Erläuterung |
|
||||||
| :--- | :--- | :--- | :--- | :--- |
|
| :--- | :--- | :--- | :--- | :--- |
|
||||||
| **1** | Wikilink | `explicit:wikilink` | **1.00** | Harte menschliche Setzung. |
|
| **1** | Wikilink | `explicit:wikilink` | **1.00** | Harte menschliche Setzung. |
|
||||||
| **2** | Inline | `inline:rel` | **0.95** | Typisierte menschliche Kante. |
|
| **2** | Inline | `inline:rel` | **0.95** | Typisierte menschliche Kante. |
|
||||||
| **3** | Callout | `callout:edge` | **0.90** | Explizite Meta-Information. |
|
| **3** | Callout | `callout:edge` | **0.90** | Explizite Meta-Information. |
|
||||||
| **4** | Smart Edge | `smart:llm_filter` | **0.90** | KI-validierte Verbindung. |
|
| **4** | Semantic AI | `semantic_ai` | **0.90** | KI-validiert gegen LocalBatchCache. |
|
||||||
| **5** | Type Default | `edge_defaults` | **0.70** | Heuristik aus der Registry. |
|
| **5** | Type Default | `edge_defaults` | **0.70** | Heuristik aus der Registry. |
|
||||||
| **6** | Struktur | `structure` | **1.00** | System-interne Verkettung. |
|
| **6** | Struktur | `structure` | **1.00** | System-interne Verkettung (`belongs_to`). |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 5. Quality Gates & Monitoring
|
## 5. Quality Gates & Monitoring
|
||||||
|
|
||||||
In v2.7 wurden Tools zur Überwachung der Datenqualität integriert:
|
**1. Registry Review (WP-14):** Prüfung der `data/logs/unknown_edges.jsonl`. Die zentrale Auflösung via `registry.py` verhindert Inkonsistenzen zwischen Import und Retrieval.
|
||||||
|
|
||||||
**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. Mistral-safe Parsing:** Automatisierte Bereinigung von LLM-Antworten in `ingestion_validation.py`. Stellt sicher, dass semantische Entscheidungen ("YES"/"NO") nicht durch technische Header verfälscht werden.
|
||||||
|
|
||||||
**2. Payload Dryrun (Schema-Check):**
|
**3. Profilgesteuerte Validierung (WP-25a):** Die semantische Kanten-Validierung erfolgt zwingend über das MoE-Profil `ingest_validator` (Temperature 0.0 für Determinismus). Dies gewährleistet konsistente binäre Entscheidungen (YES/NO) unabhängig von der globalen Provider-Konfiguration.
|
||||||
Simuliert Import, prüft JSON-Schema Konformität.
|
|
||||||
```bash
|
|
||||||
python3 -m scripts.payload_dryrun --vault ./test_vault
|
|
||||||
```
|
|
||||||
|
|
||||||
**3. Full Edge Check (Graph-Integrität):**
|
**3. Purge Integrity:** Validierung, dass vor jedem Upsert alle assoziierten Artefakte in den Collections `{prefix}_chunks` und `{prefix}_edges` gelöscht wurden, um Daten-Duplikate zu vermeiden.
|
||||||
Prüft Invarianten (z.B. `next` muss reziprok zu `prev` sein).
|
|
||||||
```bash
|
|
||||||
python3 -m scripts.edges_full_check
|
|
||||||
```
|
|
||||||
@@ -3,22 +3,29 @@ doc_type: technical_reference
|
|||||||
audience: developer, data_scientist
|
audience: developer, data_scientist
|
||||||
scope: backend, retrieval, scoring, modularization
|
scope: backend, retrieval, scoring, modularization
|
||||||
status: active
|
status: active
|
||||||
version: 2.7.1
|
version: 2.9.1
|
||||||
context: "Detaillierte Dokumentation der Scoring-Algorithmen, inklusive WP-22 Lifecycle-Modifier, Intent-Boosting und Modularisierung."
|
context: "Detaillierte Dokumentation der Scoring-Algorithmen, inklusive WP-22 Lifecycle-Modifier, Intent-Boosting, WP-15c Diversity Engine und WP-14 Modularisierung."
|
||||||
---
|
---
|
||||||
|
|
||||||
# Retrieval & Scoring Algorithmen
|
# 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.
|
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 (WP-14).
|
||||||
|
|
||||||
## 1. Scoring Formel (v2.7.0)
|
## 1. Scoring Formel (WP-15c / v1.0.3)
|
||||||
|
|
||||||
Der Gesamtscore eines Treffers berechnet sich als gewichtete Summe. Alle Gewichte ($W$) und Modifier ($M$) sind in `retriever.yaml` und `decision_engine.yaml` konfigurierbar.
|
Seit WP-15c nutzt Mindnet eine **hybride Multiplikations-Formel** für präziseres Scoring. 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}
|
Final = (Semantic \cdot StatusMult) \cdot (1 + TypeBoost + EdgeBonus + CentBonus)
|
||||||
$$
|
$$
|
||||||
|
|
||||||
|
**Komponenten:**
|
||||||
|
* **Base Score:** `Semantic * StatusMult` (Lifecycle-Filter)
|
||||||
|
* **Boosts:** `TypeBoost + EdgeBonus + CentBonus` (additiv, dann multiplikativ auf Base)
|
||||||
|
* **Graph Boost Factor:** Intent-spezifische Verstärkung (1.5x bei aktivem Intent)
|
||||||
|
|
||||||
|
**Vorteil:** Status wirkt als Multiplikator auf die Basis-Relevanz, Graph-Boni werden proportional verstärkt.
|
||||||
|
|
||||||
### Die Komponenten (Klassisch v2.4)
|
### Die Komponenten (Klassisch v2.4)
|
||||||
|
|
||||||
**1. Semantic Score ($S_{sem}$):**
|
**1. Semantic Score ($S_{sem}$):**
|
||||||
@@ -37,18 +44,21 @@ $$
|
|||||||
* **Zweck:** Belohnt Chunks, die "im Thema" vernetzt sind.
|
* **Zweck:** Belohnt Chunks, die "im Thema" vernetzt sind.
|
||||||
|
|
||||||
**4. Centrality Bonus ($B_{cent}$):**
|
**4. Centrality Bonus ($B_{cent}$):**
|
||||||
* **Kontext:** Berechnet im lokalen Subgraphen.
|
* **Kontext:** Berechnet im lokalen Subgraphen via `graph_subgraph.centrality_bonus`.
|
||||||
* **Logik:** Vereinfachte PageRank-Metrik (Degree Centrality).
|
* **Logik:** Vereinfachte PageRank-Metrik (Degree Centrality).
|
||||||
* **Zweck:** Belohnt "Hubs" mit vielen Verbindungen zu anderen Treffern.
|
* **Zweck:** Belohnt "Hubs" mit vielen Verbindungen zu anderen Treffern.
|
||||||
|
|
||||||
### Die WP-22 Erweiterungen (v2.7.0)
|
### Die WP-22 Erweiterungen (v2.7.0)
|
||||||
|
|
||||||
**5. Status Modifier ($M_{status}$):**
|
**5. Status Modifier ($M_{status}$) - Status-Gatekeeper:**
|
||||||
* **Herkunft:** Feld `status` aus dem Frontmatter.
|
* **Herkunft:** Feld `status` aus dem Frontmatter (verarbeitet in `retriever_scoring.get_status_multiplier`).
|
||||||
* **Zweck:** Bestraft unfertiges Wissen (Drafts) oder bevorzugt stabiles Wissen.
|
* **Zweck:** Wirkt als **Multiplikator** auf die Basis-Semantik. Bestraft unfertiges Wissen (Drafts) oder bevorzugt stabiles Wissen.
|
||||||
* **Werte (Auftrag WP-22):** * `stable`: **1.2** (Bonus für Qualität).
|
* **Werte (WP-15c):**
|
||||||
* `draft`: **0.5** (Malus für Entwürfe).
|
* `stable`: **1.2** (Belohnung für verifiziertes Wissen)
|
||||||
* `system`: Exkludiert (siehe Ingestion).
|
* `active`: **1.0** (Standard-Gewichtung)
|
||||||
|
* `draft`: **0.5** (Malus für unfertige Fragmente)
|
||||||
|
* `system`: Exkludiert (siehe Ingestion Lifecycle Filter)
|
||||||
|
* **Impact:** Der Status wirkt direkt auf die semantische Ähnlichkeit, bevor Graph-Boni berechnet werden.
|
||||||
|
|
||||||
**6. Intent Boost ($B_{intent}$):**
|
**6. Intent Boost ($B_{intent}$):**
|
||||||
* **Herkunft:** Dynamische Injektion durch die Decision Engine basierend auf der Nutzerfrage.
|
* **Herkunft:** Dynamische Injektion durch die Decision Engine basierend auf der Nutzerfrage.
|
||||||
@@ -56,47 +66,70 @@ $$
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 2. Hybrid Retrieval Flow & Modularisierung
|
## 2. Hybrid Retrieval Flow & Modularisierung (WP-14)
|
||||||
|
|
||||||
In v2.7 wurde die Engine in einen Orchestrator (`retriever.py`) und eine Scoring-Engine (`retriever_scoring.py`) aufgeteilt.
|
Seit v2.9 ist die Retrieval-Engine im spezialisierten Paket `app.core.retrieval` gekapselt. Die Zuständigkeiten sind strikt zwischen Orchestrierung und mathematischer Bewertung getrennt.
|
||||||
|
|
||||||
**Phase 1: Vector Search (Seed Generation)**
|
**Phase 1: Vector Search (Seed Generation)**
|
||||||
* Der Orchestrator sucht Top-K (Standard: 20) Kandidaten via Embeddings in Qdrant.
|
* Der Orchestrator (`retriever.py`) sucht Top-K (Standard: 20) Kandidaten via Embeddings in Qdrant über das modularisierte `app.core.database` Paket.
|
||||||
* Diese bilden die "Seeds" für den Graphen.
|
* Diese bilden die "Seeds" für den Graphen.
|
||||||
|
|
||||||
**Phase 2: Graph Expansion**
|
**Phase 2: Graph Expansion**
|
||||||
* Nutze `graph_adapter.expand(seeds, depth=1)`.
|
* Nutze die Fassade `app.core.graph_adapter.expand(seeds, depth=1)`.
|
||||||
* Lade direkte Nachbarn aus der `_edges` Collection.
|
* Diese delegiert an `app.core.graph.graph_subgraph`, um direkte Nachbarn aus der `_edges` Collection zu laden.
|
||||||
* Konstruiere einen `NetworkX`-Graphen im Speicher.
|
* Konstruktion eines in-memory Graphen zur Berechnung topologischer Boni.
|
||||||
|
|
||||||
**Phase 3: Re-Ranking (Modular)**
|
**Phase 3: Graph-Intelligenz & Super-Edge Aggregation (WP-15c)**
|
||||||
* Der Orchestrator übergibt den Graphen und die Seeds an die `ScoringEngine`.
|
* **Super-Edge Aggregation:** Parallele Kanten zwischen zwei Notizen (z.B. auf verschiedene Sections) werden mathematisch zu einer "Super-Edge" aggregiert:
|
||||||
* Berechne Boni ($B_{edge}$, $B_{cent}$) sowie die neuen Lifecycle- und Intent-Modifier.
|
* Primäre Kante zählt voll (höchstes Gewicht)
|
||||||
* Sortierung absteigend nach `TotalScore` und Limitierung auf Top-Resultate (z.B. 5).
|
* Weitere Kanten werden mit Dämpfungsfaktor **0.1** gewichtet
|
||||||
|
* Verhindert Score-Explosionen durch multiple Links
|
||||||
|
* **Provenance Weighting:** Kanten werden nach Provenance gewichtet (`explicit`=1.0, `smart`=0.9, `rule`=0.7)
|
||||||
|
* **Intent Boost:** Dynamische Multiplikatoren für spezifische Kanten-Typen (z.B. `caused_by` bei "Warum"-Fragen)
|
||||||
|
|
||||||
|
**Phase 4: Re-Ranking & Diversity Pooling (WP-15c)**
|
||||||
|
* Der Orchestrator übergibt den Graphen und die Seeds an die `ScoringEngine` (`retriever_scoring.py`).
|
||||||
|
* Berechnung der finalen Scores unter Berücksichtigung von $B_{edge}$, $B_{cent}$ sowie der Lifecycle- und Intent-Modifier.
|
||||||
|
* **Note-Level Diversity Pooling:** Pro `note_id` wird nur der relevanteste Treffer behalten (verhindert "Note-Flooding").
|
||||||
|
* Sortierung absteigend nach `TotalScore` und Limitierung auf die angeforderten Top-Resultate.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 3. Explanation Layer (WP-22 Update)
|
## 3. Explanation Layer (WP-15c)
|
||||||
|
|
||||||
Bei `explain=True` generiert das System eine detaillierte Begründung.
|
Bei `explain=True` generiert das System eine detaillierte Begründung inklusive Provenienz-Informationen. Der Explanation Layer liefert detaillierte Begründungen für jeden Bonus (z.B. Sektions-Links oder Hub-Zentralität), was die Transparenz massiv erhöht.
|
||||||
|
|
||||||
**Erweiterte JSON-Struktur:**
|
**Erweiterte JSON-Struktur:**
|
||||||
|
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
"score_breakdown": {
|
"score_breakdown": {
|
||||||
"semantic": 0.85,
|
"semantic_contribution": 0.85,
|
||||||
"type_boost": 1.0,
|
"edge_contribution": 0.4,
|
||||||
"lifecycle_modifier": 0.5,
|
"centrality_contribution": 0.1,
|
||||||
"edge_bonus": 0.4,
|
"raw_semantic": 0.85,
|
||||||
"intent_boost": 0.5,
|
"raw_edge_bonus": 0.3,
|
||||||
"centrality": 0.1
|
"raw_centrality": 0.1,
|
||||||
|
"node_weight": 1.0,
|
||||||
|
"status_multiplier": 1.2,
|
||||||
|
"graph_boost_factor": 1.5
|
||||||
},
|
},
|
||||||
"reasons": [
|
"reasons": [
|
||||||
"Hohe textuelle Übereinstimmung (>0.85).",
|
{
|
||||||
"Status 'draft' reduziert Relevanz (Modifier 0.5).",
|
"kind": "semantic",
|
||||||
"Wird referenziert via 'caused_by' (Intent-Bonus 0.5).",
|
"message": "Hohe textuelle Übereinstimmung (>0.85).",
|
||||||
"Bevorzugt, da Typ 'decision' (Gewicht 1.0)."
|
"score_impact": 0.85
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"kind": "type",
|
||||||
|
"message": "Bevorzugt durch Typ-Profil.",
|
||||||
|
"score_impact": 0.1
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"kind": "edge",
|
||||||
|
"message": "Bestätigte Kante 'caused_by' [Boost x1.5] von 'Note-A'.",
|
||||||
|
"score_impact": 0.4
|
||||||
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
@@ -105,18 +138,18 @@ Bei `explain=True` generiert das System eine detaillierte Begründung.
|
|||||||
|
|
||||||
## 4. Konfiguration (`retriever.yaml`)
|
## 4. Konfiguration (`retriever.yaml`)
|
||||||
|
|
||||||
Steuert die Gewichtung der mathematischen Komponenten.
|
Steuert die globale Gewichtung der mathematischen Komponenten.
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
scoring:
|
scoring:
|
||||||
semantic_weight: 1.0 # Basis-Relevanz
|
semantic_weight: 1.0 # Basis-Relevanz (W_sem)
|
||||||
edge_weight: 0.7 # Graphen-Einfluss
|
edge_weight: 0.7 # Graphen-Einfluss (W_edge)
|
||||||
centrality_weight: 0.5 # Hub-Einfluss
|
centrality_weight: 0.5 # Hub-Einfluss (W_cent)
|
||||||
|
|
||||||
# WP-22 Lifecycle Konfiguration (Abgleich mit Auftrag)
|
# WP-22 Lifecycle Konfiguration
|
||||||
lifecycle_weights:
|
lifecycle_weights:
|
||||||
stable: 1.2 # Bonus für Qualität
|
stable: 1.2 # Modifier für Qualität
|
||||||
draft: 0.5 # Malus für Entwürfe
|
draft: 0.5 # Modifier für Entwürfe
|
||||||
|
|
||||||
# Kanten-Gewichtung für den Edge-Bonus (Basis)
|
# Kanten-Gewichtung für den Edge-Bonus (Basis)
|
||||||
edge_weights:
|
edge_weights:
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
---
|
---
|
||||||
doc_type: operations_manual
|
doc_type: operations_manual
|
||||||
audience: admin, devops
|
audience: admin, devops
|
||||||
scope: deployment, maintenance, backup, edge_registry
|
scope: deployment, maintenance, backup, edge_registry, moe, lazy_prompts
|
||||||
status: active
|
status: active
|
||||||
version: 2.7.0
|
version: 3.1.1
|
||||||
context: "Installationsanleitung, Systemd-Units und Wartungsprozesse für Mindnet v2.7."
|
context: "Installationsanleitung, Systemd-Units und Wartungsprozesse für Mindnet v3.1.1 inklusive WP-25a Mixture of Experts (MoE) und WP-25b Lazy-Prompt-Orchestration Konfiguration."
|
||||||
---
|
---
|
||||||
|
|
||||||
# Admin Operations Guide
|
# Admin Operations Guide
|
||||||
@@ -19,17 +19,34 @@ context: "Installationsanleitung, Systemd-Units und Wartungsprozesse für Mindne
|
|||||||
### 1.2 Qdrant (Docker)
|
### 1.2 Qdrant (Docker)
|
||||||
Startet die Vektor-DB mit persistentem Storage auf Port 6333.
|
Startet die Vektor-DB mit persistentem Storage auf Port 6333.
|
||||||
|
|
||||||
|
dockercompose.yaml
|
||||||
```bash
|
```bash
|
||||||
docker run -d \
|
services:
|
||||||
--name mindnet_qdrant \
|
qdrant:
|
||||||
--restart always \
|
image: qdrant/qdrant
|
||||||
-p 6333:6333 \
|
container_name: qdrant
|
||||||
-v $(pwd)/qdrant_storage:/qdrant/storage \
|
ports:
|
||||||
qdrant/qdrant
|
- "6333:6333"
|
||||||
|
volumes:
|
||||||
|
- ./qdrant_data:/qdrant/storage
|
||||||
|
|
||||||
|
ulimits:
|
||||||
|
nofile:
|
||||||
|
soft: 65535
|
||||||
|
hard: 65535
|
||||||
|
restart: unless-stopped
|
||||||
|
|
||||||
|
```
|
||||||
|
```bash
|
||||||
|
docker compose up -d
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
|
Um Abstürze der Vektordatenbank bei einer hohen Anzahl an Collections (z. B. durch viele Notiz-Typen oder Dev-Umgebungen) zu vermeiden, müssen die System-Limits für den Container angepasst werden.
|
||||||
|
Hintergrund: Qdrant öffnet für jedes Segment einer Collection mehrere Dateien. Ohne diese Erhöhung führt das Standard-Linux-Limit (1024) zum Absturz mit dem Fehler os error 24 (Too many open files).
|
||||||
|
|
||||||
### 1.3 Ollama (Modelle)
|
### 1.3 Ollama (Modelle)
|
||||||
**Wichtig:** Seit v2.4 ist `nomic-embed-text` Pflicht für Embeddings.
|
**Wichtig:** Seit v2.4 ist `nomic-embed-text` Pflicht für Embeddings. Seit WP-25a wird die Modell-Konfiguration zentral über `llm_profiles.yaml` gesteuert.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Modelle laden
|
# Modelle laden
|
||||||
@@ -40,6 +57,14 @@ ollama pull nomic-embed-text
|
|||||||
curl http://localhost:11434/api/generate -d '{"model": "phi3:mini", "prompt":"Hi"}'
|
curl http://localhost:11434/api/generate -d '{"model": "phi3:mini", "prompt":"Hi"}'
|
||||||
```
|
```
|
||||||
|
|
||||||
|
**WP-25a: LLM-Profil-Konfiguration**
|
||||||
|
Die LLM-Steuerung erfolgt nun primär über `config/llm_profiles.yaml` statt ENV-Variablen:
|
||||||
|
* **Zentrale Registry:** Alle Experten-Profile (Synthese, Validierung, Kompression) sind in einer Datei definiert
|
||||||
|
* **Fallback-Kaskade:** Automatische Resilienz bei Provider-Fehlern
|
||||||
|
* **ENV-Variablen:** `MINDNET_LLM_PROVIDER`, `MINDNET_LLM_MODEL` etc. dienen nur noch als Fallback
|
||||||
|
|
||||||
|
Siehe [Konfigurations-Referenz](../03_Technical_References/03_tech_configuration.md#6-llm-profile-registry-llm_profilesyaml-v130) für Details.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 2. Deployment (Systemd Services)
|
## 2. Deployment (Systemd Services)
|
||||||
@@ -114,30 +139,131 @@ Administratoren sollten regelmäßig das Log für unbekannte Kanten-Typen prüfe
|
|||||||
|
|
||||||
### 3.3 Troubleshooting Guide
|
### 3.3 Troubleshooting Guide
|
||||||
|
|
||||||
|
Dieser Abschnitt hilft bei häufigen Problemen und deren Lösung.
|
||||||
|
|
||||||
|
#### Allgemeine Diagnose-Schritte
|
||||||
|
|
||||||
|
Bevor du spezifische Fehler behebst, führe diese Checks durch:
|
||||||
|
|
||||||
|
1. **Service-Status prüfen:**
|
||||||
|
```bash
|
||||||
|
systemctl status mindnet-prod
|
||||||
|
systemctl status mindnet-ui-prod
|
||||||
|
docker ps | grep qdrant
|
||||||
|
```
|
||||||
|
|
||||||
|
2. **Logs analysieren:**
|
||||||
|
```bash
|
||||||
|
journalctl -u mindnet-prod -n 50 --no-pager
|
||||||
|
journalctl -u mindnet-ui-prod -n 50 --no-pager
|
||||||
|
docker logs qdrant --tail 50
|
||||||
|
```
|
||||||
|
|
||||||
|
3. **API-Verfügbarkeit testen:**
|
||||||
|
```bash
|
||||||
|
curl http://localhost:8001/health
|
||||||
|
curl http://localhost:8001/query -X POST -H "Content-Type: application/json" -d '{"query": "test", "top_k": 1}'
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Häufige Fehler & Lösungen
|
||||||
|
|
||||||
**Fehler: "Registry Initialization Failure" (Neu in v2.7)**
|
**Fehler: "Registry Initialization Failure" (Neu in v2.7)**
|
||||||
* **Symptom:** API startet, aber Kanten werden nicht gewichtet oder Fehlermeldung im Log.
|
* **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.
|
* **Diagnose:** Prüfe die Logs auf `EdgeRegistry`-Fehler.
|
||||||
|
* **Lösung:**
|
||||||
|
1. Prüfe `MINDNET_VOCAB_PATH` in der `.env`. Der Pfad muss absolut sein.
|
||||||
|
2. Stelle sicher, dass die Datei `01_edge_vocabulary.md` existiert und eine gültige Markdown-Tabelle enthält.
|
||||||
|
3. Prüfe Dateiberechtigungen: `ls -l $MINDNET_VOCAB_PATH`
|
||||||
|
|
||||||
**Fehler: "ModuleNotFoundError: No module named 'st_cytoscape'"**
|
**Fehler: "ModuleNotFoundError: No module named 'st_cytoscape'"**
|
||||||
* Ursache: Alte Dependencies oder falsches Paket installiert.
|
* **Ursache:** Alte Dependencies oder falsches Paket installiert.
|
||||||
* Lösung: Environment aktualisieren.
|
* **Lösung:** Environment aktualisieren.
|
||||||
```bash
|
```bash
|
||||||
source .venv/bin/activate
|
source .venv/bin/activate
|
||||||
pip uninstall streamlit-cytoscapejs
|
pip uninstall streamlit-cytoscapejs
|
||||||
pip install st-cytoscape
|
pip install st-cytoscape
|
||||||
|
pip install -r requirements.txt # Vollständige Synchronisation
|
||||||
```
|
```
|
||||||
|
|
||||||
**Fehler: "Vector dimension error: expected 768, got 384"**
|
**Fehler: "Vector dimension error: expected 768, got 384"**
|
||||||
* Ursache: Alte DB (v2.2), neues Modell (v2.4).
|
* **Ursache:** Alte DB (v2.2), neues Modell (v2.4) oder falsches Embedding-Modell.
|
||||||
* Lösung: **Full Reset** (siehe Kap. 4.2).
|
* **Diagnose:** Prüfe die Collection-Konfiguration in Qdrant.
|
||||||
|
* **Lösung:** **Full Reset** (siehe Kap. 4.2) oder Collection neu erstellen:
|
||||||
|
```bash
|
||||||
|
python3 -m scripts.reset_qdrant --mode wipe --prefix mindnet --yes
|
||||||
|
python3 -m scripts.import_markdown --vault ./vault --prefix mindnet --apply --force
|
||||||
|
```
|
||||||
|
|
||||||
**Fehler: Import sehr langsam**
|
**Fehler: Import sehr langsam**
|
||||||
* Ursache: Smart Edges sind aktiv und analysieren jeden Chunk.
|
* **Ursache:** Smart Edges sind aktiv und analysieren jeden Chunk mit LLM-Calls.
|
||||||
* Lösung: `MINDNET_LLM_BACKGROUND_LIMIT` prüfen oder Feature in `types.yaml` deaktivieren.
|
* **Diagnose:** Prüfe `MINDNET_LLM_BACKGROUND_LIMIT` und LLM-Provider-Status.
|
||||||
|
* **Lösung:**
|
||||||
|
1. Erhöhe `MINDNET_LLM_BACKGROUND_LIMIT` in `.env` (Standard: 2)
|
||||||
|
2. Oder deaktiviere Smart Edges temporär in `types.yaml` für bestimmte Typen
|
||||||
|
3. Prüfe, ob Ollama/Cloud-Provider erreichbar ist
|
||||||
|
|
||||||
**Fehler: UI "Read timed out"**
|
**Fehler: UI "Read timed out"**
|
||||||
* Ursache: Backend braucht für Smart Edges länger als 60s.
|
* **Ursache:** Backend braucht für Smart Edges länger als das Timeout-Limit.
|
||||||
* Lösung: `MINDNET_API_TIMEOUT=300.0` in `.env` setzen (oder im Systemd Service).
|
* **Diagnose:** Prüfe Backend-Logs auf langsame LLM-Calls.
|
||||||
|
* **Lösung:**
|
||||||
|
1. Erhöhe `MINDNET_API_TIMEOUT=300.0` in `.env` (oder im Systemd Service)
|
||||||
|
2. Prüfe `MINDNET_LLM_TIMEOUT` für einzelne LLM-Requests
|
||||||
|
3. Erwäge, Smart Edges für große Imports zu deaktivieren
|
||||||
|
|
||||||
|
**Fehler: "Qdrant connection refused"**
|
||||||
|
* **Ursache:** Qdrant-Container läuft nicht oder falsche URL.
|
||||||
|
* **Lösung:**
|
||||||
|
```bash
|
||||||
|
docker ps | grep qdrant # Prüfe Container-Status
|
||||||
|
docker start qdrant # Starte Container falls gestoppt
|
||||||
|
docker logs qdrant # Prüfe Container-Logs
|
||||||
|
# Prüfe QDRANT_URL in .env
|
||||||
|
```
|
||||||
|
|
||||||
|
**Fehler: "Ollama model not found"**
|
||||||
|
* **Ursache:** Modell nicht geladen oder falscher Modellname.
|
||||||
|
* **Lösung:**
|
||||||
|
```bash
|
||||||
|
ollama list # Zeige geladene Modelle
|
||||||
|
ollama pull phi3:mini # Lade fehlendes Modell
|
||||||
|
ollama pull nomic-embed-text
|
||||||
|
# Prüfe MINDNET_LLM_MODEL und MINDNET_EMBEDDING_MODEL in .env
|
||||||
|
```
|
||||||
|
|
||||||
|
**Fehler: "Too many open files" (Qdrant)**
|
||||||
|
* **Ursache:** System-Limit für offene Dateien zu niedrig (besonders bei vielen Collections).
|
||||||
|
* **Lösung:** Erhöhe `ulimits` im Docker-Compose (siehe Kap. 1.2) oder systemweit:
|
||||||
|
```bash
|
||||||
|
# Temporär
|
||||||
|
ulimit -n 65535
|
||||||
|
# Permanently: /etc/security/limits.conf
|
||||||
|
```
|
||||||
|
|
||||||
|
**Fehler: "Unknown edge type" in Logs**
|
||||||
|
* **Ursache:** Neue Kanten-Typen im Vault, die nicht in `edge_vocabulary.md` definiert sind.
|
||||||
|
* **Diagnose:** Prüfe `data/logs/unknown_edges.jsonl`.
|
||||||
|
* **Lösung:**
|
||||||
|
1. Füge fehlende Typen als Aliase in `01_edge_vocabulary.md` hinzu
|
||||||
|
2. Oder verwende kanonische Typen aus der Registry
|
||||||
|
|
||||||
|
#### Performance-Optimierung
|
||||||
|
|
||||||
|
**Problem: Langsame Chat-Antworten**
|
||||||
|
* Prüfe LLM-Provider (Cloud vs. lokal)
|
||||||
|
* Reduziere `top_k` in Query-Requests
|
||||||
|
* Prüfe Qdrant-Performance (Anzahl Collections, Index-Größe)
|
||||||
|
|
||||||
|
**Problem: Hoher Speicherverbrauch**
|
||||||
|
* Reduziere `MINDNET_LLM_BACKGROUND_LIMIT`
|
||||||
|
* Prüfe Qdrant-Speicherverbrauch: `docker stats qdrant`
|
||||||
|
* Erwäge, alte Collections zu archivieren
|
||||||
|
|
||||||
|
#### Weitere Hilfe
|
||||||
|
|
||||||
|
Für detaillierte Informationen zu:
|
||||||
|
- **Server-Betrieb:** Siehe [Server Operations Manual](04_server_operation_manual.md)
|
||||||
|
- **Entwicklung:** Siehe [Developer Guide](../05_Development/05_developer_guide.md#10-troubleshooting--one-liners)
|
||||||
|
- **Konfiguration:** Siehe [Configuration Reference](../03_Technical_References/03_tech_configuration.md)
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -162,3 +288,10 @@ python3 -m scripts.reset_qdrant --mode wipe --prefix "mindnet" --yes
|
|||||||
# 2. Neu importieren (Force Hash recalculation)
|
# 2. Neu importieren (Force Hash recalculation)
|
||||||
python3 -m scripts.import_markdown --vault ./vault --prefix "mindnet" --apply --force
|
python3 -m scripts.import_markdown --vault ./vault --prefix "mindnet" --apply --force
|
||||||
```
|
```
|
||||||
|
|
||||||
|
**Wichtig (v2.9.1 Migration):**
|
||||||
|
Nach dem Update auf v2.9.1 (Section-basierte Links, Multigraph-Support) ist ein vollständiger Re-Import erforderlich, um "Phantom-Knoten" zu beheben und die neue Edge-Struktur zu konsolidieren:
|
||||||
|
```bash
|
||||||
|
python3 -m scripts.import_markdown --vault ./vault --prefix "mindnet" --apply --force
|
||||||
|
```
|
||||||
|
Dies stellt sicher, dass alle bestehenden Links korrekt in `target_id` und `target_section` aufgeteilt werden.
|
||||||
@@ -0,0 +1,474 @@
|
|||||||
|
---
|
||||||
|
doc_type: operations_manual
|
||||||
|
audience: devops, deployment_engineer
|
||||||
|
scope: deployment, ci_cd, rollout, versioning
|
||||||
|
status: active
|
||||||
|
version: 2.9.1
|
||||||
|
context: "Vollständiger Deployment-Guide für Mindnet: CI/CD, Rollout-Strategien, Versionierung und Rollback."
|
||||||
|
---
|
||||||
|
|
||||||
|
# Deployment Guide
|
||||||
|
|
||||||
|
Dieses Dokument beschreibt die Deployment-Prozesse, CI/CD-Pipelines und Rollout-Strategien für Mindnet.
|
||||||
|
|
||||||
|
## 1. Deployment-Architektur
|
||||||
|
|
||||||
|
Mindnet läuft in einer **Multi-Environment-Architektur**:
|
||||||
|
|
||||||
|
| Environment | Ports | Zweck | User |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| **Production** | 8001 (API), 8501 (UI) | Live-System | `llmadmin` |
|
||||||
|
| **Development** | 8002 (API), 8502 (UI) | Test & Entwicklung | `llmadmin` |
|
||||||
|
|
||||||
|
**Wichtig:** Beide Environments teilen sich die gleiche Qdrant-Instanz, nutzen aber unterschiedliche Collection-Prefixes.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Deployment-Methoden
|
||||||
|
|
||||||
|
### 2.1 Automatisches Deployment (CI/CD)
|
||||||
|
|
||||||
|
**Tool:** Gitea Actions (`.gitea/workflows/deploy.yml`)
|
||||||
|
|
||||||
|
**Trigger:** Push auf `main` Branch
|
||||||
|
|
||||||
|
**Prozess:**
|
||||||
|
1. **Checkout:** Code wird ausgecheckt
|
||||||
|
2. **Stop API:** Graceful Stop des API-Services
|
||||||
|
3. **Deploy:** Rsync der whitelisted Verzeichnisse
|
||||||
|
4. **Dependencies:** Python venv & requirements aktualisieren
|
||||||
|
5. **Restart:** API-Service neu starten
|
||||||
|
|
||||||
|
**Deployierte Verzeichnisse:**
|
||||||
|
- `app/` - Backend-Code
|
||||||
|
- `scripts/` - Admin-Tools
|
||||||
|
- `config/` - Konfigurationsdateien
|
||||||
|
- `tests/` - Test-Suite
|
||||||
|
- `requirements.txt` - Dependencies
|
||||||
|
|
||||||
|
**Ausgeschlossen:**
|
||||||
|
- `.env*` - Umgebungsvariablen (bleiben auf Server)
|
||||||
|
- `.venv` - Virtuelle Umgebung (wird neu erstellt)
|
||||||
|
- `vault/` - Content (bleibt auf Server)
|
||||||
|
|
||||||
|
### 2.2 Manuelles Deployment
|
||||||
|
|
||||||
|
**Für:** Hotfixes, manuelle Rollouts, Debugging
|
||||||
|
|
||||||
|
**Prozess:**
|
||||||
|
```bash
|
||||||
|
# 1. Auf Server einloggen
|
||||||
|
ssh llmadmin@llm-node
|
||||||
|
|
||||||
|
# 2. In Produktions-Verzeichnis wechseln
|
||||||
|
cd ~/mindnet
|
||||||
|
|
||||||
|
# 3. Code aktualisieren
|
||||||
|
git fetch origin
|
||||||
|
git checkout main
|
||||||
|
git pull origin main
|
||||||
|
|
||||||
|
# 4. Dependencies aktualisieren
|
||||||
|
source .venv/bin/activate
|
||||||
|
pip install -r requirements.txt
|
||||||
|
|
||||||
|
# 5. Services neu starten
|
||||||
|
sudo systemctl restart mindnet-prod
|
||||||
|
sudo systemctl restart mindnet-ui-prod
|
||||||
|
|
||||||
|
# 6. Status prüfen
|
||||||
|
sudo systemctl status mindnet-prod
|
||||||
|
sudo systemctl status mindnet-ui-prod
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Systemd Services
|
||||||
|
|
||||||
|
### 3.1 Backend Service (API)
|
||||||
|
|
||||||
|
**Datei:** `/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
|
||||||
|
ExecStart=/home/llmadmin/mindnet/.venv/bin/uvicorn app.main:app --host 0.0.0.0 --port 8001 --env-file .env
|
||||||
|
Restart=always
|
||||||
|
RestartSec=5
|
||||||
|
Environment="MINDNET_VOCAB_PATH=/home/llmadmin/mindnet/vault/_system/dictionary/edge_vocabulary.md"
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
|
```
|
||||||
|
|
||||||
|
**Wichtig:**
|
||||||
|
- `--env-file .env` lädt Umgebungsvariablen
|
||||||
|
- `MINDNET_VOCAB_PATH` muss absolut sein (für Edge Registry)
|
||||||
|
|
||||||
|
### 3.2 Frontend Service (UI)
|
||||||
|
|
||||||
|
**Datei:** `/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="MINDNET_API_URL=http://localhost:8001"
|
||||||
|
Environment="MINDNET_API_TIMEOUT=300"
|
||||||
|
Environment="STREAMLIT_SERVER_PORT=8501"
|
||||||
|
Environment="STREAMLIT_SERVER_ADDRESS=0.0.0.0"
|
||||||
|
Environment="STREAMLIT_SERVER_HEADLESS=true"
|
||||||
|
ExecStart=/home/llmadmin/mindnet/.venv/bin/streamlit run app/frontend/ui.py
|
||||||
|
Restart=always
|
||||||
|
RestartSec=5
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3.3 Service-Management
|
||||||
|
|
||||||
|
**Befehle:**
|
||||||
|
```bash
|
||||||
|
# Status prüfen
|
||||||
|
sudo systemctl status mindnet-prod
|
||||||
|
sudo systemctl status mindnet-ui-prod
|
||||||
|
|
||||||
|
# Starten
|
||||||
|
sudo systemctl start mindnet-prod
|
||||||
|
sudo systemctl start mindnet-ui-prod
|
||||||
|
|
||||||
|
# Stoppen
|
||||||
|
sudo systemctl stop mindnet-prod
|
||||||
|
sudo systemctl stop mindnet-ui-prod
|
||||||
|
|
||||||
|
# Neustart
|
||||||
|
sudo systemctl restart mindnet-prod
|
||||||
|
sudo systemctl restart mindnet-ui-prod
|
||||||
|
|
||||||
|
# Logs anzeigen
|
||||||
|
sudo journalctl -u mindnet-prod -f
|
||||||
|
sudo journalctl -u mindnet-ui-prod -f
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Rollout-Strategien
|
||||||
|
|
||||||
|
### 4.1 Blue-Green Deployment (Empfohlen)
|
||||||
|
|
||||||
|
**Konzept:** Zwei identische Environments, Switch zwischen ihnen.
|
||||||
|
|
||||||
|
**Aktuell:** Prod/Dev als Blue-Green Setup
|
||||||
|
|
||||||
|
**Vorgehen:**
|
||||||
|
1. Deploy auf Dev (Port 8002/8502)
|
||||||
|
2. Tests auf Dev durchführen
|
||||||
|
3. Wenn erfolgreich: Deploy auf Prod (Port 8001/8501)
|
||||||
|
4. Switch erfolgt durch Service-Restart
|
||||||
|
|
||||||
|
**Vorteile:**
|
||||||
|
- Schneller Rollback (alte Version läuft noch)
|
||||||
|
- Keine Downtime
|
||||||
|
- Test vor Produktion
|
||||||
|
|
||||||
|
### 4.2 Canary Deployment (Zukünftig)
|
||||||
|
|
||||||
|
**Konzept:** Schrittweise Rollout an einen Teil der Nutzer.
|
||||||
|
|
||||||
|
**Umsetzung:**
|
||||||
|
- Load Balancer mit Traffic-Splitting
|
||||||
|
- Monitoring der Fehlerrate
|
||||||
|
- Automatischer Rollback bei Fehlern
|
||||||
|
|
||||||
|
**Status:** Noch nicht implementiert (Single-User-Szenario)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Versionierung & Releases
|
||||||
|
|
||||||
|
### 5.1 Version-Schema
|
||||||
|
|
||||||
|
**Format:** `v2.9.1`
|
||||||
|
|
||||||
|
- **Major (2):** Breaking Changes
|
||||||
|
- **Minor (9):** Neue Features, Backward Compatible
|
||||||
|
- **Patch (1):** Bugfixes, kleine Verbesserungen
|
||||||
|
|
||||||
|
### 5.2 Release-Prozess
|
||||||
|
|
||||||
|
**1. Feature-Entwicklung:**
|
||||||
|
```bash
|
||||||
|
git checkout -b feature/neue-funktion
|
||||||
|
# ... Entwicklung ...
|
||||||
|
git push origin feature/neue-funktion
|
||||||
|
```
|
||||||
|
|
||||||
|
**2. Testing:**
|
||||||
|
- Unit Tests
|
||||||
|
- Integration Tests
|
||||||
|
- Smoke Tests auf Dev
|
||||||
|
|
||||||
|
**3. Merge:**
|
||||||
|
```bash
|
||||||
|
# Pull Request in Gitea
|
||||||
|
# Review & Merge nach main
|
||||||
|
```
|
||||||
|
|
||||||
|
**4. Deployment:**
|
||||||
|
- Automatisch via CI/CD (bei Push auf main)
|
||||||
|
- Oder manuell (siehe 2.2)
|
||||||
|
|
||||||
|
**5. Tagging (Optional):**
|
||||||
|
```bash
|
||||||
|
git tag -a v2.9.2 -m "Release v2.9.2: Neue Funktion X"
|
||||||
|
git push origin v2.9.2
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Rollback-Strategien
|
||||||
|
|
||||||
|
### 6.1 Code-Rollback
|
||||||
|
|
||||||
|
**Methode 1: Git Revert**
|
||||||
|
```bash
|
||||||
|
cd ~/mindnet
|
||||||
|
git log --oneline -10 # Finde letzten guten Commit
|
||||||
|
git checkout <commit-hash>
|
||||||
|
sudo systemctl restart mindnet-prod
|
||||||
|
```
|
||||||
|
|
||||||
|
**Methode 2: Git Reset (Vorsicht!)**
|
||||||
|
```bash
|
||||||
|
cd ~/mindnet
|
||||||
|
git reset --hard <commit-hash>
|
||||||
|
sudo systemctl restart mindnet-prod
|
||||||
|
```
|
||||||
|
|
||||||
|
### 6.2 Datenbank-Rollback
|
||||||
|
|
||||||
|
**Problem:** Code-Rollback hilft nicht bei Schema-Änderungen.
|
||||||
|
|
||||||
|
**Lösung:**
|
||||||
|
- **Qdrant-Snapshots:** Regelmäßige Backups (siehe [Server Operations Manual](04_server_operation_manual.md))
|
||||||
|
- **Collection-Versionierung:** Separate Collections pro Version (nicht empfohlen)
|
||||||
|
|
||||||
|
**Vorgehen bei Schema-Änderung:**
|
||||||
|
1. Snapshot vor Deployment erstellen
|
||||||
|
2. Deployment durchführen
|
||||||
|
3. Bei Problemen: Snapshot wiederherstellen
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. Pre-Deployment Checkliste
|
||||||
|
|
||||||
|
Vor jedem Deployment sollten folgende Punkte geprüft werden:
|
||||||
|
|
||||||
|
- [ ] **Code-Qualität:**
|
||||||
|
- [ ] Unit Tests bestehen
|
||||||
|
- [ ] Integration Tests bestehen
|
||||||
|
- [ ] Linting bestanden
|
||||||
|
|
||||||
|
- [ ] **Dependencies:**
|
||||||
|
- [ ] `requirements.txt` aktualisiert
|
||||||
|
- [ ] Neue Dependencies dokumentiert
|
||||||
|
- [ ] Breaking Changes in Dependencies geprüft
|
||||||
|
|
||||||
|
- [ ] **Konfiguration:**
|
||||||
|
- [ ] `.env` Variablen dokumentiert (falls neu)
|
||||||
|
- [ ] Config-Dateien (`types.yaml`, etc.) kompatibel
|
||||||
|
- [ ] Edge Registry Pfad korrekt
|
||||||
|
|
||||||
|
- [ ] **Datenbank:**
|
||||||
|
- [ ] Schema-Änderungen dokumentiert
|
||||||
|
- [ ] Migration-Skripte vorhanden (falls nötig)
|
||||||
|
- [ ] Backup erstellt
|
||||||
|
|
||||||
|
- [ ] **Dokumentation:**
|
||||||
|
- [ ] Changelog aktualisiert
|
||||||
|
- [ ] Dokumentation synchronisiert
|
||||||
|
- [ ] Breaking Changes dokumentiert
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. Post-Deployment Validierung
|
||||||
|
|
||||||
|
Nach jedem Deployment sollten folgende Checks durchgeführt werden:
|
||||||
|
|
||||||
|
### 8.1 Service-Status
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Services laufen
|
||||||
|
sudo systemctl status mindnet-prod
|
||||||
|
sudo systemctl status mindnet-ui-prod
|
||||||
|
|
||||||
|
# Health Check
|
||||||
|
curl http://localhost:8001/healthz
|
||||||
|
```
|
||||||
|
|
||||||
|
### 8.2 Funktionalität
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# API-Test
|
||||||
|
curl -X POST http://localhost:8001/query \
|
||||||
|
-H "Content-Type: application/json" \
|
||||||
|
-d '{"query": "test", "top_k": 1}'
|
||||||
|
|
||||||
|
# UI-Test (Manuell)
|
||||||
|
# Öffne http://localhost:8501 im Browser
|
||||||
|
```
|
||||||
|
|
||||||
|
### 8.3 Logs prüfen
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Fehler in Logs
|
||||||
|
sudo journalctl -u mindnet-prod --since "5 minutes ago" | grep -i error
|
||||||
|
|
||||||
|
# Warnings
|
||||||
|
sudo journalctl -u mindnet-prod --since "5 minutes ago" | grep -i warning
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9. CI/CD Pipeline Details
|
||||||
|
|
||||||
|
### 9.1 Gitea Actions Workflow
|
||||||
|
|
||||||
|
**Datei:** `.gitea/workflows/deploy.yml`
|
||||||
|
|
||||||
|
**Trigger:**
|
||||||
|
- Push auf `main` Branch
|
||||||
|
- Concurrency: Nur ein Deployment gleichzeitig
|
||||||
|
|
||||||
|
**Schritte:**
|
||||||
|
1. **Checkout:** Code aus Repository
|
||||||
|
2. **Stop API:** Graceful Stop (continue-on-error)
|
||||||
|
3. **Deploy:** Rsync der Verzeichnisse
|
||||||
|
4. **Python Setup:** Venv & Requirements
|
||||||
|
5. **Start API:** Service neu starten
|
||||||
|
|
||||||
|
**Wichtig:**
|
||||||
|
- `.env` wird **nicht** deployed (bleibt auf Server)
|
||||||
|
- Vault wird **nicht** deployed (bleibt auf Server)
|
||||||
|
|
||||||
|
### 9.2 Deployment-Verzeichnisse
|
||||||
|
|
||||||
|
**Whitelist:**
|
||||||
|
```
|
||||||
|
app scripts schemas docker tests config requirements.txt README.md
|
||||||
|
```
|
||||||
|
|
||||||
|
**Excluded:**
|
||||||
|
- `.git/`
|
||||||
|
- `.env*`
|
||||||
|
- `.venv/`
|
||||||
|
- `vault/`
|
||||||
|
- `hf_cache/`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 10. Monitoring & Alerting
|
||||||
|
|
||||||
|
### 10.1 Health Checks
|
||||||
|
|
||||||
|
**API Health Endpoint:**
|
||||||
|
```bash
|
||||||
|
curl http://localhost:8001/healthz
|
||||||
|
```
|
||||||
|
|
||||||
|
**Response:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"status": "ok",
|
||||||
|
"qdrant": "http://localhost:6333",
|
||||||
|
"prefix": "mindnet"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Monitoring-Script:**
|
||||||
|
```bash
|
||||||
|
python3 -m scripts.health_check_mindnet --url http://localhost:8001 --strict
|
||||||
|
```
|
||||||
|
|
||||||
|
### 10.2 Log-Monitoring
|
||||||
|
|
||||||
|
**Systemd Journal:**
|
||||||
|
```bash
|
||||||
|
# Live-Logs
|
||||||
|
sudo journalctl -u mindnet-prod -f
|
||||||
|
|
||||||
|
# Letzte 100 Zeilen
|
||||||
|
sudo journalctl -u mindnet-prod -n 100
|
||||||
|
|
||||||
|
# Seit gestern
|
||||||
|
sudo journalctl -u mindnet-prod --since "yesterday"
|
||||||
|
```
|
||||||
|
|
||||||
|
### 10.3 Metriken (Zukünftig)
|
||||||
|
|
||||||
|
**Geplante Metriken:**
|
||||||
|
- Request-Rate
|
||||||
|
- Response-Zeiten
|
||||||
|
- Fehler-Rate
|
||||||
|
- LLM-Call-Dauer
|
||||||
|
- Qdrant-Performance
|
||||||
|
|
||||||
|
**Tools:** Prometheus + Grafana (noch nicht implementiert)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 11. Disaster Recovery
|
||||||
|
|
||||||
|
Siehe [Server Operations Manual](04_server_operation_manual.md#5-disaster-recovery-wiederherstellung-two-stage-dr) für detaillierte Disaster-Recovery-Prozeduren.
|
||||||
|
|
||||||
|
**Kurzfassung:**
|
||||||
|
1. **Stage 1:** Basis-Image Restore (Bare Metal)
|
||||||
|
2. **Stage 2:** Daten-Update via Borgmatic
|
||||||
|
3. **Dienste:** Gitea, Qdrant, Ollama spezifisch wiederherstellen
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 12. Best Practices
|
||||||
|
|
||||||
|
### 12.1 Deployment-Zeiten
|
||||||
|
|
||||||
|
- **Produktion:** Während Wartungsfenstern (nachts, Wochenenden)
|
||||||
|
- **Development:** Jederzeit (ist Test-Umgebung)
|
||||||
|
|
||||||
|
### 12.2 Kommunikation
|
||||||
|
|
||||||
|
- **Breaking Changes:** Vorher ankündigen
|
||||||
|
- **Downtime:** Bei größeren Deployments kommunizieren
|
||||||
|
- **Rollback-Plan:** Immer bereit haben
|
||||||
|
|
||||||
|
### 12.3 Testing
|
||||||
|
|
||||||
|
- **Immer zuerst auf Dev testen**
|
||||||
|
- **Smoke Tests nach Deployment**
|
||||||
|
- **Monitoring für erste Stunden nach Deployment**
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 13. Weitere Informationen
|
||||||
|
|
||||||
|
- **Admin Operations:** Siehe [Admin Operations Guide](04_admin_operations.md)
|
||||||
|
- **Server Operations:** Siehe [Server Operations Manual](04_server_operation_manual.md)
|
||||||
|
- **Troubleshooting:** Siehe [Admin Operations - Troubleshooting](04_admin_operations.md#33-troubleshooting-guide)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**Letzte Aktualisierung:** 2025-01-XX
|
||||||
|
**Version:** 2.9.1
|
||||||
|
|
||||||
@@ -1,10 +1,10 @@
|
|||||||
---
|
---
|
||||||
doc_type: developer_guide
|
doc_type: developer_guide
|
||||||
audience: developer
|
audience: developer
|
||||||
scope: workflow, testing, architecture, modules
|
scope: workflow, testing, architecture, modules, modularization, agentic_rag, lazy_prompts
|
||||||
status: active
|
status: active
|
||||||
version: 2.6.1
|
version: 3.1.1
|
||||||
context: "Umfassender Guide für Entwickler: Architektur, Modul-Interna (Deep Dive), Setup, Git-Workflow und Erweiterungs-Anleitungen."
|
context: "Umfassender Guide für Entwickler: Modularisierte Architektur (WP-14), Two-Pass Ingestion (WP-15b), WP-25 Agentic Multi-Stream RAG, WP-25a MoE, WP-25b Lazy-Prompt-Orchestration, Modul-Interna, Setup und Git-Workflow."
|
||||||
---
|
---
|
||||||
|
|
||||||
# Mindnet Developer Guide & Workflow
|
# Mindnet Developer Guide & Workflow
|
||||||
@@ -23,8 +23,6 @@ Dieser Guide ist die zentrale technische Referenz für Mindnet v2.6. Er vereint
|
|||||||
- [Kern-Philosophie](#kern-philosophie)
|
- [Kern-Philosophie](#kern-philosophie)
|
||||||
- [2. Architektur](#2-architektur)
|
- [2. Architektur](#2-architektur)
|
||||||
- [2.1 High-Level Übersicht](#21-high-level-übersicht)
|
- [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)
|
- [B. Retrieval (Read)](#b-retrieval-read)
|
||||||
- [C. Visualisierung (Graph)](#c-visualisierung-graph)
|
- [C. Visualisierung (Graph)](#c-visualisierung-graph)
|
||||||
- [3. Physische Architektur](#3-physische-architektur)
|
- [3. Physische Architektur](#3-physische-architektur)
|
||||||
@@ -84,23 +82,28 @@ graph TD
|
|||||||
API["main.py"]
|
API["main.py"]
|
||||||
RouterChat["Chat / RAG"]
|
RouterChat["Chat / RAG"]
|
||||||
RouterIngest["Ingest / Write"]
|
RouterIngest["Ingest / Write"]
|
||||||
CoreRet["Retriever Engine"]
|
|
||||||
CoreIngest["Ingestion Pipeline"]
|
subgraph "Core Packages (WP-14)"
|
||||||
|
PkgRet["retrieval/ (Search)"]
|
||||||
|
PkgIng["ingestion/ (Import)"]
|
||||||
|
PkgGra["graph/ (Logic)"]
|
||||||
|
PkgDb["database/ (Infrastr.)"]
|
||||||
|
Registry["registry.py (Neutral)"]
|
||||||
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
subgraph "Infrastructure & Services"
|
subgraph "Infrastructure & Services"
|
||||||
LLM["Ollama (Phi3/Nomic)"]
|
LLM["Ollama / Cloud (Hybrid)"]
|
||||||
DB[("Qdrant Vector DB")]
|
DB[("Qdrant Vector DB")]
|
||||||
FS["File System (.md)"]
|
FS["File System (.md)"]
|
||||||
end
|
end
|
||||||
|
|
||||||
User <--> UI
|
User <--> UI
|
||||||
UI -- "REST (Chat, Save, Feedback)" --> API
|
UI -- "REST Call" --> API
|
||||||
UI -. "Direct Read (Graph Viz Performance)" .-> DB
|
PkgRet -- "Direct Query" --> PkgDb
|
||||||
API -- "Embeddings & Completion" --> LLM
|
PkgIng -- "Process & Write" --> PkgDb
|
||||||
API -- "Read/Write" --> DB
|
PkgDb -- "API" --> DB
|
||||||
API -- "Read/Write (Source of Truth)" --> FS
|
API -- "Inference" --> LLM```
|
||||||
```
|
|
||||||
|
|
||||||
### 2.2 Datenfluss-Muster
|
### 2.2 Datenfluss-Muster
|
||||||
|
|
||||||
@@ -108,14 +111,12 @@ graph TD
|
|||||||
Vom Markdown zur Vektor-Datenbank.
|
Vom Markdown zur Vektor-Datenbank.
|
||||||
```mermaid
|
```mermaid
|
||||||
graph LR
|
graph LR
|
||||||
MD["Markdown File"] --> Parser("Parser")
|
MD["Markdown File"] --> Pass1["Pass 1: Pre-Scan"]
|
||||||
Parser --> Chunker("Chunker")
|
Pass1 --> Cache[("LocalBatchCache<br/>(Titles/Summaries)")]
|
||||||
Chunker -- "Text Chunks" --> SemAn{"SemanticAnalyzer<br/>(LLM)"}
|
MD --> Pass2["Pass 2: Processing"]
|
||||||
SemAn -- "Smart Edges" --> Embedder("Embedder")
|
Cache -- "Context" --> SmartEdges{"Smart Edge<br/>Validation"}
|
||||||
Embedder --> DB[("Qdrant<br/>Points")]
|
SmartEdges --> Embedder("Embedder")
|
||||||
|
Embedder --> DB[("Qdrant Points")]
|
||||||
style DB fill:#f9f,stroke:#333,stroke-width:2px
|
|
||||||
style SemAn fill:#ff9,stroke:#333,stroke-width:2px
|
|
||||||
```
|
```
|
||||||
|
|
||||||
#### B. Retrieval (Read)
|
#### B. Retrieval (Read)
|
||||||
@@ -123,17 +124,10 @@ Die hybride Suche für Chat & RAG.
|
|||||||
```mermaid
|
```mermaid
|
||||||
graph LR
|
graph LR
|
||||||
Query(["Query"]) --> Embed("Embedding")
|
Query(["Query"]) --> Embed("Embedding")
|
||||||
Embed --> Hybrid{"Hybrid Search"}
|
Embed --> Seed["Seed Search (Vector)"]
|
||||||
|
Seed --> Expand{"Graph Expansion"}
|
||||||
subgraph Search Components
|
Expand --> Scoring["Scoring Engine (WP-22)"]
|
||||||
Vec["Vector Score"]
|
Scoring --> Rank("Final Ranking")
|
||||||
Graph["Graph/Edge Bonus"]
|
|
||||||
end
|
|
||||||
|
|
||||||
Vec --> Hybrid
|
|
||||||
Graph --> Hybrid
|
|
||||||
|
|
||||||
Hybrid --> Rank("Re-Ranking")
|
|
||||||
Rank --> Ctx["LLM Context"]
|
Rank --> Ctx["LLM Context"]
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -170,6 +164,12 @@ Das System ist modular aufgebaut. Hier ist die detaillierte Analyse aller Kompon
|
|||||||
mindnet/
|
mindnet/
|
||||||
├── app/
|
├── app/
|
||||||
│ ├── core/ # Business Logic & Algorithms
|
│ ├── core/ # Business Logic & Algorithms
|
||||||
|
│ │ ├── database/ # WP-14: Qdrant Client & Point Mapping
|
||||||
|
│ │ ├── ingestion/ # WP-14: Pipeline, Multi-Hash, Validation
|
||||||
|
│ │ ├── retrieval/ # WP-14: Search Orchestrator & Scoring
|
||||||
|
│ │ ├── graph/ # WP-14: Subgraph-Logik & Weights
|
||||||
|
│ │ ├── registry.py # SSOT: Circular Import Fix & Text Cleanup
|
||||||
|
│ │ └── *.py (Proxy) # Legacy Bridges für Abwärtskompatibilität
|
||||||
│ ├── routers/ # API Interface (FastAPI)
|
│ ├── routers/ # API Interface (FastAPI)
|
||||||
│ ├── services/ # External Integrations (LLM, DB)
|
│ ├── services/ # External Integrations (LLM, DB)
|
||||||
│ ├── models/ # Pydantic DTOs
|
│ ├── models/ # Pydantic DTOs
|
||||||
@@ -216,11 +216,27 @@ Das Frontend ist eine Streamlit-App, die sich wie eine Single-Page-Application (
|
|||||||
|
|
||||||
Das Backend ist das Herzstück. Es stellt die Logik via REST-API bereit.
|
Das Backend ist das Herzstück. Es stellt die Logik via REST-API bereit.
|
||||||
|
|
||||||
|
**Wichtig:** Seit WP-14 ist die Core-Logik in spezialisierte Pakete unterteilt:
|
||||||
|
|
||||||
|
#### Core-Pakete (Modularisierung WP-14)
|
||||||
|
|
||||||
|
| Paket | Zweck | Wichtige Module |
|
||||||
|
| :--- | :--- | :--- |
|
||||||
|
| **`app/core/chunking/`** | Text-Segmentierung | `chunking_strategies.py` (Sliding/Heading), `chunking_processor.py` (Orchestrierung) |
|
||||||
|
| **`app/core/database/`** | Qdrant-Infrastruktur | `qdrant.py` (Client), `qdrant_points.py` (Point-Mapping) |
|
||||||
|
| **`app/core/graph/`** | Graph-Logik | `graph_subgraph.py` (Expansion), `graph_weights.py` (Scoring) |
|
||||||
|
| **`app/core/ingestion/`** | Import-Pipeline | `ingestion_processor.py` (Two-Pass), `ingestion_validation.py` (Mistral-safe Parsing) |
|
||||||
|
| **`app/core/parser/`** | Markdown-Parsing | `parsing_markdown.py` (Frontmatter/Body), `parsing_scanner.py` (File-Scan) |
|
||||||
|
| **`app/core/retrieval/`** | Suche & Scoring | `retriever.py` (Orchestrator), `retriever_scoring.py` (Mathematik) |
|
||||||
|
| **`app/core/registry.py`** | SSOT & Utilities | Text-Bereinigung, Circular-Import-Fix |
|
||||||
|
|
||||||
|
**Legacy-Bridges:** Die alten Dateien (`app/core/retriever.py`, `app/core/qdrant.py`) existieren noch als Proxy-Adapter für Abwärtskompatibilität, delegieren aber an die neuen Pakete.
|
||||||
|
|
||||||
| Layer | Datei | Status | Verantwortung |
|
| Layer | Datei | Status | Verantwortung |
|
||||||
| :--- | :--- | :--- | :--- |
|
| :--- | :--- | :--- | :--- |
|
||||||
| **Entry** | `app/main.py` | 🟢 **Core** | **Entrypoint.** Initialisiert FastAPI, CORS, und bindet alle Router ein. |
|
| **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. |
|
| **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. |
|
| **Router** | `app/routers/chat.py` | 🟢 **API** | **Conversation API (WP-25).** Haupt-Endpunkt für Chat. Hybrid Router mit Intent-Erkennung, Multi-Stream Orchestration und Wissens-Synthese. |
|
||||||
| | `app/routers/ingest.py` | 🟢 **API** | **Write API.** Nimmt Markdown entgegen, steuert Ingestion und Discovery-Analyse. |
|
| | `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/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/graph.py` | 🟢 **API** | **Viz API.** Liefert Knoten/Kanten für Frontend-Graphen (Cytoscape). |
|
||||||
@@ -285,6 +301,8 @@ Folgende Dateien wurden im Audit v2.6 als veraltet, redundant oder "Zombie-Code"
|
|||||||
| `app/core/type_registry.py` | **Redundant.** Logik in `ingestion.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/core/env_vars.py` | **Veraltet.** Ersetzt durch `config.py`. | 🗑️ Löschen |
|
||||||
| `app/services/llm_ollama.py` | **Veraltet.** Ersetzt durch `llm_service.py`. | 🗑️ Löschen |
|
| `app/services/llm_ollama.py` | **Veraltet.** Ersetzt durch `llm_service.py`. | 🗑️ Löschen |
|
||||||
|
| `app/core/type_registry.py` | **Redundant.** Logik in `app/core/registry.py` integriert. | 🗑️ Löschen |
|
||||||
|
| `app/core/ranking.py` | **Redundant.** Logik in `retrieval/retriever_scoring.py` integriert. | 🗑️ Löschen |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -375,12 +393,46 @@ Mindnet lernt nicht durch Training (Fine-Tuning), sondern durch **Konfiguration*
|
|||||||
edge_defaults: ["blocks"] # Automatische Kante
|
edge_defaults: ["blocks"] # Automatische Kante
|
||||||
detection_keywords: ["gefahr", "risiko"]
|
detection_keywords: ["gefahr", "risiko"]
|
||||||
```
|
```
|
||||||
2. **Strategie (`config/decision_engine.yaml`):**
|
2. **Strategie (`config/decision_engine.yaml` v3.2.2, WP-25/25a):**
|
||||||
```yaml
|
```yaml
|
||||||
DECISION:
|
DECISION:
|
||||||
inject_types: ["value", "risk"] # <--- "risk" hinzufügen
|
use_streams: ["values_stream", "facts_stream", "risk_stream"] # WP-25: Multi-Stream
|
||||||
|
llm_profile: "synthesis_pro" # WP-25a: MoE-Profil für Synthese
|
||||||
|
inject_types: ["value", "risk"] # Legacy: Fallback für nicht-Stream-Typen
|
||||||
```
|
```
|
||||||
*Ergebnis:* Wenn der Intent `DECISION` erkannt wird, sucht das System nun auch aktiv nach Risiken.
|
*Ergebnis (WP-25/25a):* Wenn der Intent `DECISION` erkannt wird, führt das System parallele Abfragen in Values, Facts und Risk Streams aus, komprimiert überlange Streams via `compression_profile` und synthetisiert die Ergebnisse mit dem `synthesis_pro` Profil.
|
||||||
|
|
||||||
|
3. **LLM-Profil (`config/llm_profiles.yaml` v1.3.0, WP-25a):**
|
||||||
|
```yaml
|
||||||
|
synthesis_pro:
|
||||||
|
provider: "openrouter"
|
||||||
|
model: "google/gemini-2.0-flash-exp:free"
|
||||||
|
temperature: 0.7
|
||||||
|
fallback_profile: "synthesis_backup"
|
||||||
|
```
|
||||||
|
*Ergebnis (WP-25a):* Zentrale Steuerung von Provider, Modell und Temperature pro Aufgabe. Automatische Fallback-Kaskade bei Fehlern.
|
||||||
|
|
||||||
|
4. **Prompt-Template (`config/prompts.yaml` v3.2.2, WP-25b):**
|
||||||
|
```yaml
|
||||||
|
decision_synthesis_v1:
|
||||||
|
# Level 1: Modell-spezifisch (höchste Priorität)
|
||||||
|
"google/gemini-2.0-flash-exp:free": |
|
||||||
|
WERTE & PRINZIPIEN (Identität):
|
||||||
|
{values_stream}
|
||||||
|
...
|
||||||
|
|
||||||
|
# Level 2: Provider-Fallback
|
||||||
|
openrouter: |
|
||||||
|
WERTE & PRINZIPIEN (Identität):
|
||||||
|
{values_stream}
|
||||||
|
...
|
||||||
|
|
||||||
|
# Level 3: Global Default
|
||||||
|
default: |
|
||||||
|
Synthetisiere die folgenden Informationen für: {query}
|
||||||
|
...
|
||||||
|
```
|
||||||
|
*Ergebnis (WP-25b):* Hierarchische Prompt-Resolution mit Lazy-Loading. Prompts werden erst zur Laufzeit geladen, basierend auf aktivem Modell. Maximale Resilienz bei Modell-Fallbacks.
|
||||||
|
|
||||||
### Workflow B: Graph-Farben ändern
|
### Workflow B: Graph-Farben ändern
|
||||||
1. Öffne `app/frontend/ui_config.py`.
|
1. Öffne `app/frontend/ui_config.py`.
|
||||||
|
|||||||
@@ -0,0 +1,402 @@
|
|||||||
|
---
|
||||||
|
doc_type: developer_guide
|
||||||
|
audience: developer, tester
|
||||||
|
scope: testing, quality_assurance, test_strategies
|
||||||
|
status: active
|
||||||
|
version: 2.9.3
|
||||||
|
context: "Umfassender Test-Guide für Mindnet: Test-Strategien, Test-Frameworks, Test-Daten und Best Practices inklusive WP-25 Multi-Stream RAG."
|
||||||
|
---
|
||||||
|
|
||||||
|
# Testing Guide
|
||||||
|
|
||||||
|
Dieses Dokument beschreibt die Test-Strategien, Test-Frameworks und Best Practices für die Qualitätssicherung von Mindnet.
|
||||||
|
|
||||||
|
## 1. Test-Strategie & Ebenen
|
||||||
|
|
||||||
|
Mindnet nutzt eine **dreistufige Test-Pyramide**:
|
||||||
|
|
||||||
|
```
|
||||||
|
/\
|
||||||
|
/E2E\ ← Wenige, langsame, teure Tests
|
||||||
|
/------\
|
||||||
|
/Integration\ ← Mittlere Anzahl, mittlere Geschwindigkeit
|
||||||
|
/------------\
|
||||||
|
/ Unit Tests \ ← Viele, schnelle, isolierte Tests
|
||||||
|
/----------------\
|
||||||
|
```
|
||||||
|
|
||||||
|
### 1.1 Unit Tests (Pytest)
|
||||||
|
|
||||||
|
**Zweck:** Isolierte Logik-Tests ohne externe Abhängigkeiten.
|
||||||
|
|
||||||
|
**Framework:** `pytest`
|
||||||
|
|
||||||
|
**Beispiele:**
|
||||||
|
- `tests/test_retriever_basic.py` - Scoring-Logik
|
||||||
|
- `tests/test_chunking.py` - Chunking-Strategien
|
||||||
|
- `tests/test_edges_all.py` - Edge-Logik
|
||||||
|
- `tests/test_type_registry.py` - Registry-Funktionen
|
||||||
|
|
||||||
|
**Ausführung:**
|
||||||
|
```bash
|
||||||
|
# Einzelner Test
|
||||||
|
pytest tests/test_retriever_basic.py -v
|
||||||
|
|
||||||
|
# Alle Unit Tests
|
||||||
|
pytest tests/ -k "test_" --ignore=tests/test_*_smoke.py
|
||||||
|
|
||||||
|
# Mit Coverage
|
||||||
|
pytest tests/ --cov=app --cov-report=html
|
||||||
|
```
|
||||||
|
|
||||||
|
**Best Practices:**
|
||||||
|
- Tests sollten isoliert sein (keine Abhängigkeiten zu Qdrant/Ollama)
|
||||||
|
- Mock externe Services (LLM, Qdrant)
|
||||||
|
- Schnelle Ausführung (< 1 Sekunde pro Test)
|
||||||
|
|
||||||
|
### 1.2 Integration Tests
|
||||||
|
|
||||||
|
**Zweck:** Prüfen den Datenfluss von Markdown bis Qdrant.
|
||||||
|
|
||||||
|
**Tools:**
|
||||||
|
- `scripts/payload_dryrun.py` - JSON-Schema-Konformität
|
||||||
|
- `scripts/edges_full_check.py` - Graph-Integrität
|
||||||
|
- `scripts/make_test_vault.py` - Test-Daten-Generierung
|
||||||
|
|
||||||
|
**Ausführung:**
|
||||||
|
```bash
|
||||||
|
# Payload-Validierung
|
||||||
|
python3 -m scripts.payload_dryrun --vault ./test_vault --with-edges
|
||||||
|
|
||||||
|
# Graph-Integrität
|
||||||
|
python3 -m scripts.edges_full_check
|
||||||
|
|
||||||
|
# Test-Vault erstellen
|
||||||
|
python3 -m scripts.make_test_vault --out ./test_vault --force
|
||||||
|
```
|
||||||
|
|
||||||
|
**Was wird geprüft:**
|
||||||
|
- Frontmatter-Parsing
|
||||||
|
- Chunk-Generierung
|
||||||
|
- Edge-Erstellung
|
||||||
|
- Payload-Schema-Konformität
|
||||||
|
- Graph-Invarianten (keine Dangling Edges)
|
||||||
|
|
||||||
|
### 1.3 E2E / Smoke Tests
|
||||||
|
|
||||||
|
**Zweck:** Prüfen das laufende System gegen echte Infrastruktur (Qdrant, Ollama).
|
||||||
|
|
||||||
|
**Framework:** Python `unittest` + Shell-Skripte
|
||||||
|
|
||||||
|
**Beispiele:**
|
||||||
|
- `tests/test_wp06_decision.py` - Decision Engine
|
||||||
|
- `tests/test_feedback_smoke.py` - Feedback-Loop
|
||||||
|
- `tests/test_dialog_full_flow.py` - Vollständiger Dialog-Flow
|
||||||
|
- `tests/run_e2e_roundtrip.sh` - Kompletter Roundtrip (Import → Export)
|
||||||
|
|
||||||
|
**Ausführung:**
|
||||||
|
```bash
|
||||||
|
# Decision Engine Test
|
||||||
|
python tests/test_wp06_decision.py -p 8002 -e DECISION -q "Soll ich X tun?"
|
||||||
|
|
||||||
|
# Feedback Test
|
||||||
|
python tests/test_feedback_smoke.py --url http://localhost:8002/query
|
||||||
|
|
||||||
|
# E2E Roundtrip
|
||||||
|
./tests/run_e2e_roundtrip.sh --vault ./test_vault --prefix mindnet_test
|
||||||
|
```
|
||||||
|
|
||||||
|
**Voraussetzungen:**
|
||||||
|
- Qdrant läuft auf `localhost:6333`
|
||||||
|
- Ollama läuft auf `localhost:11434`
|
||||||
|
- API läuft auf Port 8002 (Dev)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Test-Daten & Vaults
|
||||||
|
|
||||||
|
### 2.1 Test-Vault erstellen
|
||||||
|
|
||||||
|
**Tool:** `scripts/make_test_vault.py`
|
||||||
|
|
||||||
|
**Zweck:** Erstellt einen minimalen, nachvollziehbaren Test-Vault.
|
||||||
|
|
||||||
|
**Inhalt:**
|
||||||
|
- Verschiedene Note-Typen (`concept`, `experience`, `project`)
|
||||||
|
- Verschiedene Edge-Szenarien (explicit, implicit, missing links)
|
||||||
|
- Externe Links für Edge-Tests
|
||||||
|
|
||||||
|
**Verwendung:**
|
||||||
|
```bash
|
||||||
|
# Standard
|
||||||
|
python3 -m scripts.make_test_vault --out ./test_vault
|
||||||
|
|
||||||
|
# Mit fehlenden Links (für Link-Auflösungs-Tests)
|
||||||
|
python3 -m scripts.make_test_vault --out ./test_vault --with-missing
|
||||||
|
|
||||||
|
# Überschreiben bestehenden Vault
|
||||||
|
python3 -m scripts.make_test_vault --out ./test_vault --force
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2.2 Test-Collection Prefix
|
||||||
|
|
||||||
|
**Wichtig:** Nutze separate Prefixes für Tests, um Produktionsdaten nicht zu beeinflussen.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
export COLLECTION_PREFIX="mindnet_test"
|
||||||
|
python3 -m scripts.import_markdown --vault ./test_vault --prefix mindnet_test --apply
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Test-Frameworks & Tools
|
||||||
|
|
||||||
|
### 3.1 Pytest (Unit Tests)
|
||||||
|
|
||||||
|
**Installation:**
|
||||||
|
```bash
|
||||||
|
pip install pytest pytest-asyncio pytest-cov
|
||||||
|
```
|
||||||
|
|
||||||
|
**Konfiguration:** `pytest.ini` oder `pyproject.toml`
|
||||||
|
|
||||||
|
**Async Tests:**
|
||||||
|
```python
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_async_function():
|
||||||
|
result = await async_function()
|
||||||
|
assert result == expected
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3.2 Unittest (E2E Tests)
|
||||||
|
|
||||||
|
**Framework:** Python `unittest`
|
||||||
|
|
||||||
|
**Beispiel:**
|
||||||
|
```python
|
||||||
|
import unittest
|
||||||
|
from app.routers.ingest import save_note, SaveRequest
|
||||||
|
|
||||||
|
class TestIngest(unittest.IsolatedAsyncioTestCase):
|
||||||
|
async def test_save_note(self):
|
||||||
|
req = SaveRequest(markdown_content="...", filename="test.md")
|
||||||
|
response = await save_note(req)
|
||||||
|
self.assertEqual(response.status, "queued")
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3.3 Shell-Skripte (E2E Roundtrip)
|
||||||
|
|
||||||
|
**Tool:** `tests/run_e2e_roundtrip.sh`
|
||||||
|
|
||||||
|
**Zweck:** Vollständiger Test-Zyklus (Import → Export → Vergleich)
|
||||||
|
|
||||||
|
**Schritte:**
|
||||||
|
1. Qdrant truncate
|
||||||
|
2. Import (Create-Fall)
|
||||||
|
3. Import (Idempotenz-Test)
|
||||||
|
4. Hash-Reporter
|
||||||
|
5. Export
|
||||||
|
6. Vergleich Vault vs. Export
|
||||||
|
7. Sync-Deletes Test
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Test-Szenarien
|
||||||
|
|
||||||
|
### 4.1 Chunking-Tests
|
||||||
|
|
||||||
|
**Was wird getestet:**
|
||||||
|
- Sliding Window Strategie
|
||||||
|
- Heading-basierte Strategie
|
||||||
|
- Edge-Vererbung
|
||||||
|
- Chunk-Größen-Limits
|
||||||
|
|
||||||
|
**Tests:**
|
||||||
|
- `tests/test_smart_chunking_integration.py`
|
||||||
|
- `scripts/preview_chunks.py` (Manuelle Inspektion)
|
||||||
|
|
||||||
|
### 4.2 Retrieval-Tests
|
||||||
|
|
||||||
|
**Was wird getestet:**
|
||||||
|
- Semantic Search
|
||||||
|
- Hybrid Search (Semantik + Graph)
|
||||||
|
- Scoring-Formel
|
||||||
|
- Explanation Layer
|
||||||
|
|
||||||
|
**Tests:**
|
||||||
|
- `tests/test_retriever_basic.py`
|
||||||
|
- `tests/test_retriever_edges.py`
|
||||||
|
- `tests/test_retriever_weight.py`
|
||||||
|
- `tests/test_explanation_smoke.py`
|
||||||
|
|
||||||
|
### 4.3 Edge-Tests
|
||||||
|
|
||||||
|
**Was wird getestet:**
|
||||||
|
- Edge-Erstellung (explicit, smart, rule)
|
||||||
|
- Edge-Validierung (Registry)
|
||||||
|
- Edge-Vererbung
|
||||||
|
- Unresolved References
|
||||||
|
|
||||||
|
**Tests:**
|
||||||
|
- `tests/test_edges_all.py`
|
||||||
|
- `tests/test_edges_smoke.py`
|
||||||
|
- `tests/test_edges_defaults_smoke.py`
|
||||||
|
- `scripts/edges_full_check.py`
|
||||||
|
|
||||||
|
### 4.4 Chat & Intent-Tests (WP-25)
|
||||||
|
|
||||||
|
**Was wird getestet:**
|
||||||
|
- Intent-Erkennung (FACT_WHAT, FACT_WHEN, DECISION, EMPATHY, CODING, INTERVIEW)
|
||||||
|
- Hybrid Router (Keyword Fast-Path + LLM Slow-Path)
|
||||||
|
- Decision Engine (Multi-Stream Orchestration)
|
||||||
|
- Parallele Stream-Abfragen (Values, Facts, Biography, Risk, Tech)
|
||||||
|
- Stream-Tracing (`stream_origin` Markierung)
|
||||||
|
- Wissens-Synthese (Template-basierte Zusammenführung)
|
||||||
|
- Interview-Modus
|
||||||
|
- Feedback-Loop
|
||||||
|
|
||||||
|
**Tests:**
|
||||||
|
- `tests/test_wp06_decision.py` - Decision Engine (Legacy)
|
||||||
|
- `tests/test_interview_intent.py` - Interview-Modus
|
||||||
|
- `tests/test_chat_wp05.py` - Chat-Backend (Legacy)
|
||||||
|
- `tests/test_feedback_smoke.py` - Feedback-Loop
|
||||||
|
|
||||||
|
**WP-25 Spezifische Tests (geplant):**
|
||||||
|
- Multi-Stream Retrieval (parallele Abfragen)
|
||||||
|
- Stream-Tracing (stream_origin Zuordnung)
|
||||||
|
- Template-Robustheit (Pre-Initialization)
|
||||||
|
- Intent-Kollision (Keyword-Fast-Path Präzision)
|
||||||
|
|
||||||
|
### 4.5 Ingestion-Tests
|
||||||
|
|
||||||
|
**Was wird getestet:**
|
||||||
|
- Two-Pass Workflow
|
||||||
|
- Change Detection (Hash-basiert)
|
||||||
|
- Background Tasks
|
||||||
|
- Smart Edge Allocation
|
||||||
|
|
||||||
|
**Tests:**
|
||||||
|
- `tests/test_dialog_full_flow.py`
|
||||||
|
- `tests/test_WP22_intelligence.py`
|
||||||
|
- `scripts/import_markdown.py` (mit `--dry-run`)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Continuous Integration
|
||||||
|
|
||||||
|
### 5.1 Pre-Commit Checks
|
||||||
|
|
||||||
|
**Empfohlene Checks:**
|
||||||
|
```bash
|
||||||
|
# Linting
|
||||||
|
flake8 app/ scripts/
|
||||||
|
|
||||||
|
# Type Checking (optional)
|
||||||
|
mypy app/
|
||||||
|
|
||||||
|
# Unit Tests
|
||||||
|
pytest tests/ -k "test_" --ignore=tests/test_*_smoke.py
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5.2 CI/CD Pipeline
|
||||||
|
|
||||||
|
**Gitea Actions:** `.gitea/workflows/`
|
||||||
|
|
||||||
|
**Typische Pipeline:**
|
||||||
|
1. Checkout
|
||||||
|
2. Python Setup
|
||||||
|
3. Dependencies installieren
|
||||||
|
4. Unit Tests
|
||||||
|
5. Integration Tests (optional)
|
||||||
|
6. Deployment (bei main branch)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Test-Best Practices
|
||||||
|
|
||||||
|
### 6.1 Isolation
|
||||||
|
|
||||||
|
- **Unit Tests:** Keine externen Abhängigkeiten (Mock alles)
|
||||||
|
- **Integration Tests:** Echte Qdrant, aber isolierte Collections
|
||||||
|
- **E2E Tests:** Separate Test-Umgebung (Port 8002)
|
||||||
|
|
||||||
|
### 6.2 Test-Daten
|
||||||
|
|
||||||
|
- Nutze `make_test_vault.py` für konsistente Test-Daten
|
||||||
|
- Separate Collection-Prefixes für Tests
|
||||||
|
- Cleanup nach Tests (oder isolierte Collections)
|
||||||
|
|
||||||
|
### 6.3 Performance
|
||||||
|
|
||||||
|
- Unit Tests sollten < 1 Sekunde dauern
|
||||||
|
- Integration Tests können länger dauern (10-30 Sekunden)
|
||||||
|
- E2E Tests sind langsam (1-5 Minuten)
|
||||||
|
|
||||||
|
### 6.4 Wartbarkeit
|
||||||
|
|
||||||
|
- Klare Test-Namen (`test_<functionality>_<scenario>`)
|
||||||
|
- Dokumentation in Test-Docstrings
|
||||||
|
- Keine Hardcoded-Pfade (nutze `os.path`)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. Debugging & Diagnose
|
||||||
|
|
||||||
|
### 7.1 Test-Debugging
|
||||||
|
|
||||||
|
**Pytest Debug-Modus:**
|
||||||
|
```bash
|
||||||
|
pytest tests/test_retriever_basic.py -v --pdb
|
||||||
|
```
|
||||||
|
|
||||||
|
**Einzelnen Test inspizieren:**
|
||||||
|
```bash
|
||||||
|
python3 -m scripts.payload_dryrun --vault ./test_vault --note-id "test-note"
|
||||||
|
```
|
||||||
|
|
||||||
|
### 7.2 Qdrant-State prüfen
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Collection-Status
|
||||||
|
python3 -m scripts.debug_qdrant_state --prefix mindnet_test
|
||||||
|
|
||||||
|
# Payload-Indexe prüfen
|
||||||
|
python3 -m scripts.diag_payload_indexes --prefix mindnet_test
|
||||||
|
```
|
||||||
|
|
||||||
|
### 7.3 Chunk-Inspektion
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Chunks für eine Note anzeigen
|
||||||
|
python3 -m scripts.dump_note_chunks --note-id "test-note" --prefix mindnet_test
|
||||||
|
|
||||||
|
# Chunk-Text-Verifikation
|
||||||
|
python3 -m scripts.verify_chunk_texts --prefix mindnet_test
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. Test-Checkliste für Pull Requests
|
||||||
|
|
||||||
|
Vor jedem PR sollten folgende Tests durchlaufen:
|
||||||
|
|
||||||
|
- [ ] Unit Tests: `pytest tests/ -k "test_" --ignore=tests/test_*_smoke.py`
|
||||||
|
- [ ] Payload-Validierung: `python3 -m scripts.payload_dryrun --vault ./test_vault`
|
||||||
|
- [ ] Graph-Integrität: `python3 -m scripts.edges_full_check`
|
||||||
|
- [ ] Smoke Test (wenn API läuft): `python tests/test_wp06_decision.py -p 8002`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9. Weitere Informationen
|
||||||
|
|
||||||
|
- **Developer Guide:** Siehe [Developer Guide](05_developer_guide.md)
|
||||||
|
- **Scripts-Übersicht:** Siehe [Developer Guide - Scripts](05_developer_guide.md#44-scripts--tooling-die-admin-toolbox)
|
||||||
|
- **Troubleshooting:** Siehe [Admin Operations - Troubleshooting](../04_Operations/04_admin_operations.md#33-troubleshooting-guide)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**Letzte Aktualisierung:** 2025-01-XX
|
||||||
|
**Version:** 2.9.1
|
||||||
|
|
||||||
@@ -2,18 +2,14 @@
|
|||||||
doc_type: roadmap
|
doc_type: roadmap
|
||||||
audience: product_owner, developer
|
audience: product_owner, developer
|
||||||
status: active
|
status: active
|
||||||
version: 2.7
|
version: 3.1.1
|
||||||
context: "Aktuelle Planung für kommende Features (ab WP16), Release-Strategie und Historie der abgeschlossenen WPs."
|
context: "Aktuelle Planung für kommende Features (ab WP16), Release-Strategie und Historie der abgeschlossenen WPs nach WP-14/15b/15c/25/25a/25b."
|
||||||
---
|
---
|
||||||
|
|
||||||
# Mindnet Active Roadmap
|
# Mindnet Active Roadmap
|
||||||
|
|
||||||
**Aktueller Stand:** v2.6.0 (Post-WP15/WP19)
|
**Aktueller Stand:** v3.1.1 (Post-WP25b: Lazy-Prompt-Orchestration & Full Resilience)
|
||||||
**Fokus:** Visualisierung, Exploration & Intelligent Ingestion.
|
**Fokus:** Hierarchische Prompt-Resolution, Modell-spezifisches Tuning & maximale Resilienz.
|
||||||
|
|
||||||
## 1. Programmstatus
|
|
||||||
|
|
||||||
Wir haben mit der Implementierung des Graph Explorers (WP19) und der Smart Edge Allocation (WP15) 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 | Fokus | Status |
|
||||||
| :--- | :--- | :--- |
|
| :--- | :--- | :--- |
|
||||||
@@ -45,17 +41,30 @@ Eine Übersicht der implementierten Features zum schnellen Auffinden von Funktio
|
|||||||
| **WP-10** | Web UI | Streamlit-Frontend als Ersatz für das Terminal. |
|
| **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-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-11** | Backend Intelligence | `nomic-embed-text` (768d) und Matrix-Logik für Kanten-Typisierung. |
|
||||||
|
| **WP-14** | **Modularisierung & Refactoring** | **Ergebnis:** Aufteilung in domänenspezifische Pakete (`database`, `ingestion`, `retrieval`, `graph`). Implementierung von Proxy-Adaptern für Abwärtskompatibilität und `registry.py` zur Lösung von Zirkelbezügen. |
|
||||||
|
| **WP-15b**| **Candidate-Based Validation** | **Ergebnis:** Implementierung des **Two-Pass Workflows**. Einführung des `LocalBatchCache` und binäre semantische Validierung von Kanten-Kandidaten zur Vermeidung von Halluzinationen. |
|
||||||
| **WP-15** | Smart Edge Allocation | LLM-Filter für Kanten in Chunks + Traffic Control (Semaphore) + Strict Chunking. |
|
| **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-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 | Nutzung von Public LLM für schnellere Verarbeitung und bestimmte Aufgaben |
|
| **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-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. |
|
| **WP-22** | **Content Lifecycle & Registry** | **Ergebnis:** SSOT via `01_edge_vocabulary.md`, Alias-Mapping, Status-Scoring (`stable`/`draft`) und Modularisierung der Scoring-Engine. |
|
||||||
|
| **WP-15c** | **Multigraph-Support & Diversity Engine** | **Ergebnis:** Section-basierte Links, Note-Level Diversity Pooling, Super-Edge Aggregation, Provenance Firewall. Transformation zu einem hochpräzisen Multigraphen. |
|
||||||
|
| **WP-25** | **Agentic Multi-Stream RAG Orchestration** | **Ergebnis:** Übergang von linearer RAG-Architektur zu paralleler Multi-Stream Engine. Intent-basiertes Routing (Hybrid Fast/Slow-Path), parallele Wissens-Streams (Values, Facts, Biography, Risk, Tech), Stream-Tracing und Template-basierte Wissens-Synthese. |
|
||||||
|
| **WP-25a** | **Mixture of Experts (MoE) & Fallback-Kaskade** | **Ergebnis:** Profilbasierte Experten-Architektur, rekursive Fallback-Kaskade, Pre-Synthesis Kompression, profilgesteuerte Ingestion und Embedding-Konsolidierung. |
|
||||||
|
| **WP-25b** | **Lazy-Prompt-Orchestration & Full Resilience** | **Ergebnis:** Hierarchisches Prompt-Resolution-System (3-stufig), Lazy-Prompt-Loading, ultra-robustes Intent-Parsing, differenzierte Ingestion-Validierung und PROMPT-TRACE Logging. |
|
||||||
|
|
||||||
### 2.1 WP-22 Lessons Learned
|
### 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.
|
* **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.
|
* **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.
|
||||||
|
|
||||||
|
### 2.3 WP-14 & WP-15b Lessons Learned
|
||||||
|
* **Performance:** Der Pre-Scan (Pass 1) ist minimal invasiv, ermöglicht aber in Pass 2 eine drastische Reduktion der LLM-Kosten, da nur noch binär validiert werden muss, anstatt komplexe Extraktionen durchzuführen.
|
||||||
|
* **Wartbarkeit:** Durch die Paket-Struktur können DB-Adapter (z.B. für Qdrant) nun unabhängig von der Business-Logik (Scoring) aktualisiert werden.
|
||||||
|
*
|
||||||
---
|
---
|
||||||
|
|
||||||
## 3. Offene Workpackages (Planung)
|
## 3. Offene Workpackages (Planung)
|
||||||
@@ -80,7 +89,7 @@ Diese Features stehen als nächstes an oder befinden sich in der Umsetzung.
|
|||||||
**Phase:** B
|
**Phase:** B
|
||||||
**Status:** 🟡 geplant
|
**Status:** 🟡 geplant
|
||||||
|
|
||||||
**Ziel:** Sicherstellen, dass bestehende und neue Obsidian-Vaults schrittweise in mindnet integriert werden können – ohne Massenumbau.
|
**Ziel:** Sicherstellen, dass bestehende und neue Obsidian-Vaults schrittweise in mindnet installiert werden können – ohne Massenumbau.
|
||||||
|
|
||||||
**Umfang:**
|
**Umfang:**
|
||||||
- Tools zur Analyse des Vault-Status.
|
- Tools zur Analyse des Vault-Status.
|
||||||
@@ -90,19 +99,40 @@ Diese Features stehen als nächstes an oder befinden sich in der Umsetzung.
|
|||||||
- Aufwand: Mittel
|
- Aufwand: Mittel
|
||||||
- Komplexität: Niedrig/Mittel
|
- Komplexität: Niedrig/Mittel
|
||||||
|
|
||||||
### WP-19a – Graph Intelligence & Discovery (Sprint-Fokus)
|
|
||||||
**Status:** 🚀 Startklar
|
|
||||||
**Ziel:** Vom "Anschauen" zum "Verstehen". Deep-Dive Werkzeuge für den Graphen.
|
### WP-13 – MCP-Integration & Agenten-Layer
|
||||||
* **Discovery Screen:** Neuer Tab für semantische Suche ("Finde Notizen über Vaterschaft") und Wildcard-Filter.
|
**Status:** 🟡 Geplant
|
||||||
* **Filter-Logik:** "Zeige nur Wege, die zu `type:decision` führen".
|
**Ziel:** mindnet als MCP-Server bereitstellen, damit Agenten (Claude Desktop, OpenAI) standardisierte Tools nutzen können.
|
||||||
* **Chunk Inspection:** Umschaltbare Granularität (Notiz vs. Chunk) zur Validierung des Smart Chunkers.
|
* **Umfang:** MCP-Server mit Tools (`mindnet_query`, `mindnet_explain`, etc.).
|
||||||
|
|
||||||
### WP-14 – Review / Refactoring / Dokumentation
|
### WP-14 – Review / Refactoring / Dokumentation
|
||||||
**Status:** 🟡 Laufend (Phase E)
|
**Status:** 🟡 Laufend (Phase E)
|
||||||
**Ziel:** Technische Schulden abbauen, die durch schnelle Feature-Entwicklung (WP15/WP19) entstanden sind.
|
**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).
|
* **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`).
|
* *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.6 Stand).
|
* **Dokumentation:** Kontinuierliche Synchronisation von Code und Docs (v2.8 Stand).
|
||||||
|
|
||||||
|
### 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-16 – Auto-Discovery & Intelligent Ingestion
|
### WP-16 – Auto-Discovery & Intelligent Ingestion
|
||||||
**Status:** 🟡 Geplant
|
**Status:** 🟡 Geplant
|
||||||
@@ -130,15 +160,13 @@ Diese Features stehen als nächstes an oder befinden sich in der Umsetzung.
|
|||||||
* **Feature:** Cronjob `check_graph_integrity.py`.
|
* **Feature:** Cronjob `check_graph_integrity.py`.
|
||||||
* **Funktion:** Findet "Dangling Edges" (Links auf gelöschte Notizen) und repariert/löscht sie.
|
* **Funktion:** Findet "Dangling Edges" (Links auf gelöschte Notizen) und repariert/löscht sie.
|
||||||
|
|
||||||
### WP-13 – MCP-Integration & Agenten-Layer
|
### WP-19a – Graph Intelligence & Discovery (Sprint-Fokus)
|
||||||
**Status:** 🟡 Geplant
|
**Status:** 🚀 Startklar
|
||||||
**Ziel:** mindnet als MCP-Server bereitstellen, damit Agenten (Claude Desktop, OpenAI) standardisierte Tools nutzen können.
|
**Ziel:** Vom "Anschauen" zum "Verstehen". Deep-Dive Werkzeuge für den Graphen.
|
||||||
* **Umfang:** MCP-Server mit Tools (`mindnet_query`, `mindnet_explain`, etc.).
|
* **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-20 – Cloud Hybrid Mode (Optional)
|
|
||||||
**Status:** ⚪ Optional
|
|
||||||
**Ziel:** "Turbo-Modus" für Massen-Imports.
|
|
||||||
* **Konzept:** Switch in `.env`, um statt Ollama (Lokal) auf Google Gemini (Cloud) umzuschalten.
|
|
||||||
|
|
||||||
### WP-21 – Semantic Graph Routing & Canonical Edges
|
### WP-21 – Semantic Graph Routing & Canonical Edges
|
||||||
**Status:** 🟡 Geplant
|
**Status:** 🟡 Geplant
|
||||||
@@ -167,9 +195,81 @@ Diese Features stehen als nächstes an oder befinden sich in der Umsetzung.
|
|||||||
2. **Single Source of Truth (SSOT):** Die Registry nutzt `01_edge_vocabulary.md` als führende Konfiguration.
|
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`.
|
3. **Self-Learning Loop:** Protokollierung unbekannter Kanten in `unknown_edges.jsonl`.
|
||||||
|
|
||||||
|
### WP-25: Agentic Multi-Stream RAG Orchestration
|
||||||
|
**Status:** ✅ Fertig (v3.0.0)
|
||||||
|
|
||||||
|
### WP-25a: Mixture of Experts (MoE) & Fallback-Kaskade
|
||||||
|
**Status:** ✅ Fertig (v3.1.0)
|
||||||
|
|
||||||
|
**Ergebnis:** Transformation von MindNet von einer provider-basierten Steuerung auf eine **profilbasierte Experten-Architektur (Mixture of Experts)**. Jede Systemaufgabe wird einem dedizierten Profil zugewiesen, das Modell, Provider und Parameter unabhängig definiert.
|
||||||
|
|
||||||
|
**Kern-Features:**
|
||||||
|
1. **Experten-Steuerung:** Zentrale Profile-Registry (`llm_profiles.yaml`) für alle LLM-Aufgaben
|
||||||
|
2. **Rekursive Fallback-Kaskade:** Automatische Resilienz bei Provider-Fehlern mit Schutz gegen Zirkel-Referenzen
|
||||||
|
3. **Pre-Synthesis Kompression:** Asynchrone Verdichtung überlanger Wissens-Streams vor der Synthese
|
||||||
|
4. **Profilgesteuerte Ingestion:** Deterministische Validierung via `ingest_validator` (Temperature 0.0)
|
||||||
|
5. **Embedding-Konsolidierung:** Zentrale Steuerung des Embedding-Modells über `embedding_expert` Profil
|
||||||
|
6. **Startup-Schutz:** Validierung der YAML-Konfigurationen beim Booten
|
||||||
|
|
||||||
|
**Technische Details:**
|
||||||
|
- LLM Service v3.5.2: Rekursive Fallback-Kaskade
|
||||||
|
- Decision Engine v1.2.1: Profile-Driven Orchestration
|
||||||
|
- Ingestion Processor v2.14.0: Profilgesteuerte Validierung
|
||||||
|
- Embeddings Client v2.6.0: Profil-basierte Modell-Auflösung
|
||||||
|
- llm_profiles.yaml v1.3.0: Zentrale Experten-Registry
|
||||||
|
- decision_engine.yaml v3.2.2: Decoupled MoE Logic
|
||||||
|
|
||||||
|
### WP-25b: Lazy-Prompt-Orchestration & Full Resilience
|
||||||
|
**Status:** ✅ Fertig (v3.1.1)
|
||||||
|
|
||||||
|
**Ergebnis:** Umstellung von statischer Prompt-Formatierung auf eine **hierarchische Lazy-Prompt-Orchestration**. Prompts werden erst im Moment des Modellaustauschs geladen, basierend auf dem exakt aktiven Modell. Dies ermöglicht modell-spezifisches Tuning und maximale Resilienz bei Modell-Fallbacks.
|
||||||
|
|
||||||
|
**Kern-Features:**
|
||||||
|
1. **Hierarchisches Prompt-Resolution-System:** Dreistufige Auflösung (Modell-ID → Provider → Default)
|
||||||
|
2. **Lazy-Loading:** Prompts werden erst zur Laufzeit geladen, wenn das aktive Modell bekannt ist
|
||||||
|
3. **Ultra-robustes Intent-Parsing:** Regex-basierter Parser bereinigt Modell-Artefakte (z.B. `CODING[/S]` → `CODING`)
|
||||||
|
4. **Differenzierte Ingestion-Validierung:** Unterscheidung zwischen transienten (Netzwerk) und permanenten (Config) Fehlern
|
||||||
|
5. **PROMPT-TRACE Logging:** Vollständige Transparenz über genutzte Instruktionen
|
||||||
|
|
||||||
|
**Technische Details:**
|
||||||
|
- LLM Service v3.5.5: Hierarchische Prompt-Resolution mit Lazy-Loading
|
||||||
|
- Decision Engine v1.3.2: Ultra-robustes Intent-Parsing via Regex
|
||||||
|
- Ingestion Validation v2.14.0: Lazy-Prompt-Integration, differenzierte Fehlerbehandlung
|
||||||
|
- prompts.yaml v3.2.2: Hierarchische Struktur mit Modell-spezifischen Overrides
|
||||||
|
|
||||||
|
**Ausblick (WP-25c):**
|
||||||
|
- Kontext-Budgeting: Intelligente Token-Verteilung
|
||||||
|
- Stream-specific Provider: Unterschiedliche KI-Modelle pro Wissensbereich
|
||||||
|
- Erweiterte Prompt-Optimierung: Dynamische Anpassung basierend auf Kontext und Historie
|
||||||
---
|
---
|
||||||
|
|
||||||
|
### WP-24 – Proactive Discovery & Agentic Knowledge Mining
|
||||||
|
**Status:** 🚀 In Planung (Nächster Architektur-Sprung)
|
||||||
|
**Ziel:** Transformation von Mindnet von einem reaktiven Archiv zu einem aktiven Denkpartner. Das System soll aktiv Wissenslücken schließen und verborgene Querverbindungen in großen Vaults sowie in Chat-Dialogen aufspüren.
|
||||||
|
|
||||||
|
**Herausforderung:**
|
||||||
|
1. **Silo-Effekt:** Bei wachsenden Vaults vergisst der Nutzer existierende Notizen und erstellt redundante Inhalte ohne Verknüpfung.
|
||||||
|
2. **Insight-Verlust:** Im Chat entstehen wertvolle Synthesen, die momentan im flüchtigen Chat-Log vergraben bleiben.
|
||||||
|
|
||||||
|
**Lösungsskizze & Strategie:**
|
||||||
|
|
||||||
|
#### A. Proactive Discovery (Vault-Scanning)
|
||||||
|
Das System nutzt die existierende `candidate_pool` Logik aus WP-15b, befüllt diese jedoch automatisiert:
|
||||||
|
* **Vector Similarity Search**: Beim Import einer Note (oder als periodischer Hintergrundprozess) sucht der neue `RecommenderService` in Qdrant nach den Top-X semantisch ähnlichsten Chunks im gesamten Vault.
|
||||||
|
* **Auto-Injection**: Diese Funde werden automatisch als `related_to` Kandidaten in den `candidate_pool` der neuen Note injiziert.
|
||||||
|
* **WP-15b Filter**: Das LLM validiert diese Vorschläge im zweiten Pass der Ingestion gegen den Kontext. Nur was semantisch wirklich passt, wird als Kante im Graphen persistiert.
|
||||||
|
|
||||||
|
#### B. Agentic Knowledge Mining (Chat-to-Vault)
|
||||||
|
Integration von Informationen aus dem Dialog direkt in den Graphen:
|
||||||
|
* **Intent Detection**: Das Chat-Backend erkennt „notierwürdige“ Informationen (z.B. neue Prinzipien, Strategie-Entwürfe oder Werte-Anpassungen).
|
||||||
|
* **Auto-Drafting**: Das LLM nutzt das `interview_template`, um aus dem Chat-Fragment eine valide Markdown-Datei mit Frontmatter (Status: `draft`) zu generieren.
|
||||||
|
* **Real-Time Linking**: Die neue Datei wird sofort dem „Discovery-Lauf“ (Teil A) unterzogen, um sie mit dem bestehenden Wissensschatz zu vernetzen.
|
||||||
|
* **User Review**: Die generierte Notiz erscheint im `00_Inbox` Ordner. Der Nutzer muss lediglich den Status auf `stable` setzen, um die Entdeckungen final zu integrieren.
|
||||||
|
|
||||||
|
**Erwartete Ergebnisse:**
|
||||||
|
* Eliminierung von Wissens-Silos durch automatische Vernetzung.
|
||||||
|
* Nahtloser Übergang von der Exploration (Chat) zur Konsolidierung (Vault).
|
||||||
|
* Vermeidung von Dubletten durch Ähnlichkeits-Warnungen beim Import.
|
||||||
## 4. Abhängigkeiten & Release-Plan
|
## 4. Abhängigkeiten & Release-Plan
|
||||||
|
|
||||||
```mermaid
|
```mermaid
|
||||||
@@ -178,6 +278,8 @@ graph TD
|
|||||||
WP19a --> WP17(Memory)
|
WP19a --> WP17(Memory)
|
||||||
WP15(Smart Edges) --> WP16(Auto-Discovery)
|
WP15(Smart Edges) --> WP16(Auto-Discovery)
|
||||||
WP15 --> WP14(Refactoring)
|
WP15 --> WP14(Refactoring)
|
||||||
|
WP15(Smart Edges) --> WP15b(Candidate Validation)
|
||||||
|
WP15b --> WP24(Proactive Discovery)
|
||||||
WP03(Import) --> WP18(Health Check)
|
WP03(Import) --> WP18(Health Check)
|
||||||
WP03 --> WP13(MCP)
|
WP03 --> WP13(MCP)
|
||||||
WP04 --> WP13(MCP)
|
WP04 --> WP13(MCP)
|
||||||
@@ -186,3 +288,6 @@ graph TD
|
|||||||
WP21 --> WP22(Lifecycle & Registry)
|
WP21 --> WP22(Lifecycle & Registry)
|
||||||
WP22 --> WP14
|
WP22 --> WP14
|
||||||
WP15(Smart Edges) --> WP21
|
WP15(Smart Edges) --> WP21
|
||||||
|
WP20(Cloud Hybrid) --> WP15b
|
||||||
|
WP24 --> WP23(Multi-Stream Reasoning)
|
||||||
|
```
|
||||||
@@ -254,6 +254,9 @@ Bitte bestätige die Übernahme, erstelle die `edge_mappings.yaml` Struktur und
|
|||||||
* Es ist der logisch perfekte Ort, um zu sagen: "Wenn der User im Analyse-Modus ist, sind Fakten-Kanten wichtiger als Gefühls-Kanten."
|
* 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!
|
Damit hast du das perfekte Paket für den nächsten Entwicklungsschritt geschnürt!
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## WP-22: Content Lifecycle & Meta-Config
|
## WP-22: Content Lifecycle & Meta-Config
|
||||||
|
|
||||||
@@ -271,8 +274,6 @@ Wir haben eine Markdown-Datei (`01_edge_vocabulary.md`), die als Single-Source-o
|
|||||||
**Dein Auftrag:**
|
**Dein Auftrag:**
|
||||||
Implementiere (A) den Content-Lifecycle, (B) die Edge-Registry und (C) das Semantic Routing.
|
Implementiere (A) den Content-Lifecycle, (B) die Edge-Registry und (C) das Semantic Routing.
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### Teil A: Content Lifecycle (Ingestion Logic)
|
### Teil A: Content Lifecycle (Ingestion Logic)
|
||||||
Steuerung über Frontmatter `status`:
|
Steuerung über Frontmatter `status`:
|
||||||
1. **System-Dateien (No-Index):**
|
1. **System-Dateien (No-Index):**
|
||||||
@@ -281,8 +282,6 @@ Steuerung über Frontmatter `status`:
|
|||||||
* Wenn `status` in `['draft', 'active', 'stable']`: Status wird im Payload gespeichert.
|
* 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`).
|
* **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
|
### Teil B: Central Edge Registry & Validation
|
||||||
1. **Registry Klasse:**
|
1. **Registry Klasse:**
|
||||||
* Erstelle `EdgeRegistry` (Singleton).
|
* Erstelle `EdgeRegistry` (Singleton).
|
||||||
@@ -292,8 +291,6 @@ Steuerung über Frontmatter `status`:
|
|||||||
* Prüfe beim Import jede Kante gegen die Registry.
|
* 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).
|
* 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)
|
### Teil C: Semantic Graph Routing (Dynamic Boosting)
|
||||||
**Ziel:** Die Bedeutung einer Kante soll sich je nach Frage-Typ ändern ("Warum" vs. "Wie").
|
**Ziel:** Die Bedeutung einer Kante soll sich je nach Frage-Typ ändern ("Warum" vs. "Wie").
|
||||||
|
|
||||||
@@ -308,7 +305,6 @@ Die Gewichtung findet **Pre-Retrieval** (im Scoring-Algorithmus) statt, **nicht*
|
|||||||
* Der `Retriever` erhält vom Router die `boost_edges` Map.
|
* Der `Retriever` erhält vom Router die `boost_edges` Map.
|
||||||
* Berechne Score: `BaseScore * (1 + ConfigWeight + DynamicBoost)`.
|
* Berechne Score: `BaseScore * (1 + ConfigWeight + DynamicBoost)`.
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
**Deine Aufgaben:**
|
**Deine Aufgaben:**
|
||||||
1. Zeige die `EdgeRegistry` Klasse (Parsing Logik).
|
1. Zeige die `EdgeRegistry` Klasse (Parsing Logik).
|
||||||
@@ -316,3 +312,124 @@ Die Gewichtung findet **Pre-Retrieval** (im Scoring-Algorithmus) statt, **nicht*
|
|||||||
3. Zeige die Erweiterung in `scoring.py` (Status-Gewicht & Dynamic Edge Boosting).
|
3. Zeige die Erweiterung in `scoring.py` (Status-Gewicht & Dynamic Edge Boosting).
|
||||||
|
|
||||||
Bitte bestätige die Übernahme dieses Architektur-Pakets.
|
Bitte bestätige die Übernahme dieses Architektur-Pakets.
|
||||||
|
```
|
||||||
|
|
||||||
|
## WP24
|
||||||
|
```text
|
||||||
|
|
||||||
|
Übergabe Arbeitspaket: WP-24 – Proactive Discovery & Agentic Knowledge Mining
|
||||||
|
|
||||||
|
## 1. Projekt-Kontext
|
||||||
|
Wir arbeiten an **Mindnet**, einem System für einen "digitalen Zwilling". Das System nutzt einen Wissensgraph (Qdrant), asynchrone Ingestion und eine hybride LLM-Infrastruktur (Cloud/Lokal).
|
||||||
|
|
||||||
|
## 2. Status Quo (Abgeschlossen: WP-15b)
|
||||||
|
Das Arbeitspaket **WP-15b (Candidate-Based Validation)** wurde gerade erfolgreich implementiert.
|
||||||
|
* **Two-Pass Workflow:** In Pass 1 wird ein globaler `LocalBatchCache` aufgebaut (ID, Titel, Dateiname). In Pass 2 findet eine semantische binäre Validierung (YES/NO) statt.
|
||||||
|
* **Edge Inheritance:** Kanten werden aus Sektionen und Frontmatter an Chunks vererbt.
|
||||||
|
* **Candidate Pool:** Nur Kanten in der Sektion `## Unzugeordnete Kanten` (Provenienz: `global_pool`) werden vom LLM geprüft. Explizite Kanten (`[!edge]` im Text) werden direkt übernommen.
|
||||||
|
|
||||||
|
## 3. Auftrag: WP-24 – Proactive Discovery & Agentic Knowledge Mining
|
||||||
|
Das Ziel ist die Transformation von Mindnet zu einem aktiven Denkpartner.
|
||||||
|
|
||||||
|
### Teil A: Proactive Discovery (Vault-Scanning)
|
||||||
|
* **Mechanismus:** Automatisches Befüllen des `candidate_pool` via Vektor-Ähnlichkeit.
|
||||||
|
* **Logik:** Beim Import einer Note sucht ein neuer Service in Qdrant nach den semantisch ähnlichsten Chunks im Vault und fügt diese als `related_to` Kandidaten hinzu.
|
||||||
|
* **Filter:** Die WP-15b Validierungs-Logik filtert diese Vorschläge anschließend.
|
||||||
|
|
||||||
|
### Teil B: Agentic Knowledge Mining (Chat-to-Vault)
|
||||||
|
* **Mechanismus:** Extraktion notierwürdiger Informationen aus dem Chat.
|
||||||
|
* **Logik:** Erstellung von Markdown-Drafts im `00_Inbox` Ordner basierend auf dem Chat-Kontext unter Nutzung des `interview_template`.
|
||||||
|
|
||||||
|
## 4. Erforderliche Code-Basis (Dateien)
|
||||||
|
Stelle sicher, dass dir folgende Dateien vorliegen, um die Logik zu verstehen und zu erweitern:
|
||||||
|
|
||||||
|
1. **`app/core/ingestion.py` (v2.12.2):** Zentraler Two-Pass Workflow und Validierungsgate.
|
||||||
|
2. **`app/core/chunker.py` (v3.2.0):** Vorbereitung des Candidate-Pools und Vererbungslogik.
|
||||||
|
3. **`scripts/import_markdown.py` (v2.4.1):** Entry-Point und Pre-Scan Harvester für den Cache.
|
||||||
|
4. **`app/core/derive_edges.py` (v2.1.0):** Aggregator für Kanten mit Provenance-Priorisierung.
|
||||||
|
5. **`app/services/edge_registry.py` (v0.8.0):** Validierung gegen das Kanten-Vokabular.
|
||||||
|
6. **`config/prompts.yaml` (v2.6.0):** Enthält die `edge_validation` und `interview_template` Prompts.
|
||||||
|
7. **`06_active_roadmap.md` (v2.9.0):** Enthält die detaillierte Planung für WP-24.
|
||||||
|
|
||||||
|
## 5. Nächste technische Schritte
|
||||||
|
1. Entwurf eines `RecommenderService` für die Vektor-Suche in Qdrant.
|
||||||
|
2. Integration des Services in die `ingestion.py` zur automatischen Befüllung des `candidate_pool`.
|
||||||
|
3. Erweiterung des Chat-Backends um die "Capture-to-Vault" Funktionalität.
|
||||||
|
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
## WP-25: Advanced Reasoning Engine (Agentic RAG)
|
||||||
|
|
||||||
|
``` Text
|
||||||
|
**Status:** 🚀 High-Priority Upgrade
|
||||||
|
**Ziel:** Implementierung einer mehrstufigen Entscheidungs-Architektur ("Multi-Hop").
|
||||||
|
|
||||||
|
|
||||||
|
**Das Problem:**
|
||||||
|
Single-Step-Retrieval verwässert Ergebnisse. Eine Suche nach "Projekt-Entscheidung" findet oft operative Details, übersieht aber fundamentale Werte ("Wertekompass"), weil diese semantisch distanziert sind.
|
||||||
|
|
||||||
|
**Die Lösung (Architektur):**
|
||||||
|
Wir ersetzen die flache Suche durch eine **Orchestrator-Logik**, die parallele Streams ausführt.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Teil A: Configuration Upgrade (`decision_engine.yaml`)
|
||||||
|
Erweitere die Config-Struktur, um statt einfacher Listen echte **Sub-Queries** zu definieren.
|
||||||
|
|
||||||
|
*Neu (Vorschlag):*
|
||||||
|
````yaml
|
||||||
|
strategies:
|
||||||
|
DECISION:
|
||||||
|
description: "Komplexe Abwägung"
|
||||||
|
# Der Orchestrator führt diese 3 Streams parallel aus:
|
||||||
|
streams:
|
||||||
|
- name: "facts"
|
||||||
|
query_template: "Status und Fakten zu: {query}"
|
||||||
|
filter_types: ["project", "journal", "decision"]
|
||||||
|
edge_boosts: {part_of: 1.5}
|
||||||
|
|
||||||
|
- name: "values"
|
||||||
|
query_template: "Welche Werte und Prinzipien sind relevant für: {query}"
|
||||||
|
filter_types: ["value", "principle", "belief"]
|
||||||
|
edge_boosts: {derived_from: 2.0, enforced_by: 2.0} # Findet den "Wertekompass"!
|
||||||
|
|
||||||
|
- name: "risks"
|
||||||
|
query_template: "Risiken und Gefahren bei: {query}"
|
||||||
|
filter_types: ["risk", "obstacle"]
|
||||||
|
edge_boosts: {blocks: 2.5, impacts: 2.0}
|
||||||
|
````
|
||||||
|
``` Text
|
||||||
|
### Teil B: Implementation (`DecisionEngine.py`)
|
||||||
|
1. **Decomposition:** Wenn eine Strategie `streams` definiert, darf nicht mehr *ein* `retrieve()` Aufruf erfolgen.
|
||||||
|
2. **Parallel Execution:**
|
||||||
|
* Iteriere über alle Streams.
|
||||||
|
* Führe für jeden Stream einen eigenen `retriever.retrieve()` aus – mit dessen spezifischen Filtern, Query und Edge-Boosts.
|
||||||
|
3. **Intermediate Summarization (Optional/Later):**
|
||||||
|
* (Für Version 1 reicht es, die Ergebnisse der Streams in markierten Blöcken an den Prompt zu geben).
|
||||||
|
|
||||||
|
### Teil C: The Synthesis (Prompting)
|
||||||
|
Passe das Prompt-Template an, um die getrennten Streams zu nutzen:
|
||||||
|
|
||||||
|
...
|
||||||
|
HIER SIND DIE FAKTEN:
|
||||||
|
{stream_results_facts}
|
||||||
|
|
||||||
|
HIER SIND DIE RELEVANTEN WERTE/PRINZIPIEN:
|
||||||
|
{stream_results_values}
|
||||||
|
|
||||||
|
HIER SIND DIE RISIKEN:
|
||||||
|
{stream_results_risks}
|
||||||
|
|
||||||
|
AUFGABE: Wäge die Fakten gegen die Werte ab.
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**Deine Aufgaben:**
|
||||||
|
1. **Refactor Config:** Zeige, wie die `decision_engine.yaml` für Multi-Stream angepasst wird.
|
||||||
|
2. **Orchestrator Logic:** Schreibe die Python-Logik, die diese Streams parallel abfeuert und die Ergebnisse aggregiert.
|
||||||
|
3. **Integration:** Nutze die `EdgeRegistry` (aus WP-22) für die Boosts in jedem Stream.
|
||||||
|
|
||||||
|
Bitte bestätige die Übernahme dieser "Agentic Architecture" (WP-25).
|
||||||
|
|
||||||
@@ -92,3 +92,22 @@ Dieses Dokument dient als Referenz für die Entstehungsgeschichte von Mindnet v2
|
|||||||
* **Graph Explorer:** Einführung von `st-cytoscape` für stabile, nicht-überlappende Layouts (COSE) als Ergänzung zur Legacy-Engine (Agraph).
|
* **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.
|
* **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.
|
* **UX:** Einführung von URL-Persistenz für Layout-Settings und CSS-basiertes Highlighting zur Vermeidung von Re-Renders.
|
||||||
|
|
||||||
|
|
||||||
|
## Phase E+: Architektur-Konsolidierung (WP-14)
|
||||||
|
|
||||||
|
### WP-14 – Modularisierung & Paket-Struktur
|
||||||
|
* **Ziel:** Auflösung technischer Schulden und Beseitigung von Zirkelbezügen (Circular Imports).
|
||||||
|
* **Ergebnis:**
|
||||||
|
* **Domänen-Pakete:** Aufteilung der monolithischen `app/core/` Struktur in spezialisierte Pakete: `database/`, `ingestion/`, `retrieval/` und `graph/`.
|
||||||
|
* **Proxy-Pattern:** Einsatz von Fassaden-Modulen (z. B. `graph_adapter.py`) zur Aufrechterhaltung der Abwärtskompatibilität für bestehende API-Endpunkte.
|
||||||
|
* **Registry-Zentralisierung:** Auslagerung neutraler Hilfsfunktionen (wie `clean_llm_text`) in eine unabhängige `registry.py`, um Abhängigkeitsschleifen zwischen Diensten zu brechen.
|
||||||
|
* **Tech:** Einführung von `__init__.py` Exporten zur Definition sauberer Paket-Schnittstellen.
|
||||||
|
|
||||||
|
### WP-15b – Two-Pass Ingestion & Candidate Validation
|
||||||
|
* **Problem:** Die ursprüngliche Smart Edge Extraktion (WP-15) war teuer und neigte zu Halluzinationen, da sie ohne globalen Kontext operierte.
|
||||||
|
* **Lösung:** Implementierung eines **Two-Pass Workflows**.
|
||||||
|
* **Pass 1 (Pre-Scan):** Schnelles Einlesen aller Notizen zur Erstellung eines `LocalBatchCache` (Metadaten & Summaries).
|
||||||
|
* **Pass 2 (Processing):** Gezielte semantische Verarbeitung nur für geänderte Dateien.
|
||||||
|
* **Feature:** **Binary Validation Gate**. Statt Kanten frei zu erfinden, validiert das LLM nun Kanten-Kandidaten aus einem Pool gegen den Kontext des `LocalBatchCache`. Dies garantiert 100% Konformität mit der Edge Registry.
|
||||||
|
* **Ergebnis:** Höhere Geschwindigkeit durch Reduktion komplexer LLM-Prompts auf binäre Entscheidungen (VALID/INVALID).
|
||||||
@@ -0,0 +1,123 @@
|
|||||||
|
# Branch Merge Commit Message: WP15c
|
||||||
|
|
||||||
|
```
|
||||||
|
feat: Multigraph-Support, Diversity Engine & Provenance Firewall (v2.9.1)
|
||||||
|
|
||||||
|
## Graph Topology & Edge Management (WP-15c)
|
||||||
|
|
||||||
|
### Section-Präzision & Multigraph-Modus
|
||||||
|
- Präzise Erkennung von Obsidian-Ankern (`[[Note#Section]]`) und Self-Links (`[[#Section]]`)
|
||||||
|
- Links werden in `target_id="Note"` und `target_section="Section"` aufgelöst
|
||||||
|
- Edge-ID enthält `variant` (Section) für eindeutige Identifikation
|
||||||
|
- Multigraph-Modus: Mehrere Kanten zwischen denselben Notizen möglich, wenn sie auf verschiedene Sections zeigen
|
||||||
|
- Behebt "Phantom-Knoten" durch korrekte Trennung von Note-Name und Abschnitt
|
||||||
|
|
||||||
|
**Geänderte Dateien:**
|
||||||
|
- `app/core/graph/graph_utils.py`: `parse_link_target()` für Section-Extraktion & Self-Links (v1.1.2)
|
||||||
|
- `app/core/graph/graph_derive_edges.py`: Multigraph-Support, `target_section` in Edge-Payload (v1.1.2)
|
||||||
|
- `app/core/graph/graph_subgraph.py`: Metadaten-Persistenz (v1.2.0)
|
||||||
|
- `app/core/graph/graph_db_adapter.py`: Vollständige Metadaten-Durchreichung (v1.1.1)
|
||||||
|
|
||||||
|
### Provenance Firewall (Edge Registry v0.8.0)
|
||||||
|
- System-Kanten (`next`, `prev`, `belongs_to`) dürfen nur mit `provenance="structure"` gesetzt werden
|
||||||
|
- Alle anderen Provenienzen (`explicit`, `semantic_ai`, `inherited`, `global_pool`, `rule`) werden blockiert
|
||||||
|
- Automatischer Fallback auf `related_to` bei unerlaubter Verwendung
|
||||||
|
- Logging in `data/logs/unknown_edges.jsonl` für Admin-Review
|
||||||
|
|
||||||
|
**Geänderte Dateien:**
|
||||||
|
- `app/services/edge_registry.py`: Provenance Firewall (v0.8.0)
|
||||||
|
|
||||||
|
## Retrieval-Intelligenz (The Diversity Engine)
|
||||||
|
|
||||||
|
### Note-Level Diversity Pooling
|
||||||
|
- Pro `note_id` wird nur der relevanteste Treffer im Endergebnis behalten
|
||||||
|
- Verhindert "Note-Flooding" (Dominanz einer einzigen Notiz durch viele ähnliche Chunks)
|
||||||
|
- Workflow: Sortierung nach finalem Score → Diversity-Pooling → Begrenzung auf `top_k`
|
||||||
|
|
||||||
|
**Geänderte Dateien:**
|
||||||
|
- `app/core/retrieval/retriever.py`: Note-Level Diversity Pooling (v0.7.0)
|
||||||
|
|
||||||
|
### Super-Edge Aggregation
|
||||||
|
- Parallele Kanten zwischen zwei Notizen werden mathematisch zu einer "Super-Edge" aggregiert
|
||||||
|
- Primäre Kante zählt voll, weitere Kanten werden mit Dämpfungsfaktor **0.1** gewichtet
|
||||||
|
- Verhindert Score-Explosionen durch multiple Links auf verschiedene Sections
|
||||||
|
- Metadaten: `is_super_edge` Flag und `edge_count` für Explanation Layer
|
||||||
|
|
||||||
|
**Geänderte Dateien:**
|
||||||
|
- `app/core/retrieval/retriever.py`: Super-Edge Aggregation (v0.7.0)
|
||||||
|
|
||||||
|
### Metadaten-Persistenz
|
||||||
|
- In-Memory Subgraph und Datenbank-Adapter erweitert für durchgängige Metadaten-Erhaltung
|
||||||
|
- `target_section`, `provenance` und `confidence` werden vollständig erhalten
|
||||||
|
- Ermöglicht präzises Retrieval-Reasoning und Explanation Layer
|
||||||
|
|
||||||
|
**Geänderte Dateien:**
|
||||||
|
- `app/core/graph/graph_subgraph.py`: Metadaten-Persistenz (v1.2.0)
|
||||||
|
- `app/core/graph/graph_db_adapter.py`: Vollständige Metadaten-Durchreichung (v1.1.1)
|
||||||
|
|
||||||
|
## Mathematisches Scoring (WP-22 Integration)
|
||||||
|
|
||||||
|
### Hybrid Scoring Formula (v1.0.3)
|
||||||
|
- Neue Formel: `Final = (Semantic * StatusMult) * (1 + TypeBoost + EdgeBonus + CentBonus)`
|
||||||
|
- Status-Gatekeeper: `stable` = 1.2, `draft` = 0.5, `active` = 1.0
|
||||||
|
- Graph Boost Factor: Intent-spezifische Verstärkung (1.5x bei aktivem Intent)
|
||||||
|
- Status wirkt als Multiplikator auf die Basis-Relevanz, Graph-Boni werden proportional verstärkt
|
||||||
|
|
||||||
|
**Geänderte Dateien:**
|
||||||
|
- `app/core/retrieval/retriever_scoring.py`: Hybrid Scoring Formula (v1.0.3)
|
||||||
|
|
||||||
|
### Explanation Layer
|
||||||
|
- Detaillierte Begründungen für jeden Bonus (Sektions-Links, Hub-Zentralität, Super-Edge-Informationen)
|
||||||
|
- Provenance-Informationen für erhöhte Transparenz
|
||||||
|
- Massiv erhöhte Transparenz für Debugging und Nutzer-Vertrauen
|
||||||
|
|
||||||
|
**Geänderte Dateien:**
|
||||||
|
- `app/core/retrieval/retriever.py`: Explanation Layer (v0.7.0)
|
||||||
|
|
||||||
|
## Ingestion & Profil-Synchronisation
|
||||||
|
|
||||||
|
### Registry-First Profiling (v2.13.12)
|
||||||
|
- Hierarchische Auflösung: Frontmatter > types.yaml Typ-Config > Global Defaults
|
||||||
|
- Konsistente Verarbeitung je nach Notiz-Typ
|
||||||
|
- Note-Typen wie `value` erhalten automatisch das korrekte Profil (`structured_smart_edges_strict`)
|
||||||
|
|
||||||
|
**Geänderte Dateien:**
|
||||||
|
- `app/core/ingestion/ingestion_processor.py`: Registry-First Profiling (v2.13.12)
|
||||||
|
|
||||||
|
## Impact & Breaking Changes
|
||||||
|
|
||||||
|
### Keine Migration erforderlich
|
||||||
|
**WICHTIG:** Diese Version ist **rückwärtskompatibel**. Bestehende Vaults funktionieren ohne Re-Import.
|
||||||
|
|
||||||
|
**Empfehlung:** Optionaler Re-Import für optimale Nutzung der neuen Features:
|
||||||
|
```bash
|
||||||
|
python3 -m scripts.import_markdown --vault ./vault --prefix "mindnet" --apply --force
|
||||||
|
```
|
||||||
|
|
||||||
|
### Fixes
|
||||||
|
- ✅ Resolves: "Phantom-Knoten" durch korrekte Trennung von Note-Name und Section
|
||||||
|
- ✅ Resolves: Score-Explosionen durch multiple Links auf verschiedene Sections
|
||||||
|
- ✅ Resolves: "Note-Flooding" durch fehlende Diversity-Filterung
|
||||||
|
- ✅ Resolves: Inkonsistente Metadaten durch fehlende Persistenz im Subgraph
|
||||||
|
- ✅ Resolves: Manipulation von System-Kanten durch Provenance Firewall
|
||||||
|
|
||||||
|
## Dokumentation
|
||||||
|
|
||||||
|
Alle relevanten Dokumente aktualisiert:
|
||||||
|
- `02_concept_graph_logic.md`: Provenance Firewall, Self-Links, Multigraph-Support
|
||||||
|
- `03_tech_retrieval_scoring.md`: Hybrid Scoring Formula, Note-Level Diversity, Super-Edge Aggregation
|
||||||
|
- `03_tech_data_model.md`: Section-Support, Metadaten-Persistenz
|
||||||
|
- `03_tech_ingestion_pipeline.md`: Registry-First Profiling (bereits dokumentiert)
|
||||||
|
|
||||||
|
## Versionen
|
||||||
|
|
||||||
|
- Edge Registry: v0.8.0
|
||||||
|
- Graph Utils / Derive Edges: v1.1.2
|
||||||
|
- Graph Subgraph: v1.2.0
|
||||||
|
- Graph DB Adapter: v1.1.1
|
||||||
|
- Retriever: v0.7.0
|
||||||
|
- Retriever Scoring: v1.0.3
|
||||||
|
- Ingestion Processor: v2.13.12
|
||||||
|
|
||||||
|
Closes #[issue-number]
|
||||||
|
```
|
||||||
@@ -0,0 +1,267 @@
|
|||||||
|
# Release Notes: Mindnet v2.9.3 (WP15c)
|
||||||
|
|
||||||
|
**Release Date:** 2025-12-31
|
||||||
|
**Type:** Feature Release - Multigraph & Diversity Engine
|
||||||
|
**Branch:** WP15c
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🎯 Übersicht
|
||||||
|
|
||||||
|
Diese Version transformiert den Graphen von einer flachen Struktur zu einem **hochpräzisen Multigraphen** mit intelligenter Ergebnis-Filterung (Diversity) und gewichtetem Scoring. Die Änderungen verbessern die Retrieval-Qualität durch präzise Sektions-Links, Note-Level Diversity Pooling und mathematische Super-Edge Aggregation.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## ✨ Neue Features
|
||||||
|
|
||||||
|
### Section-Präzision & Multigraph-Modus
|
||||||
|
|
||||||
|
Mindnet erkennt nun präzise **Obsidian-Anker** (`[[Note#Section]]`) und **Self-Links** (`[[#Section]]`):
|
||||||
|
|
||||||
|
**Obsidian-Anker:**
|
||||||
|
```markdown
|
||||||
|
[[rel:based_on Mein Leitbild#P3 – Disziplin]]
|
||||||
|
```
|
||||||
|
|
||||||
|
**Self-Links:**
|
||||||
|
```markdown
|
||||||
|
[[#P3 – Disziplin]] → Verlinkt innerhalb derselben Note
|
||||||
|
```
|
||||||
|
|
||||||
|
**Technische Details:**
|
||||||
|
- Links werden in `target_id="Note"` und `target_section="Section"` aufgelöst
|
||||||
|
- Edge-IDs enthalten `variant` (Section) für eindeutige Identifikation
|
||||||
|
- **Multigraph-Modus:** Mehrere Kanten zwischen denselben Notizen möglich, wenn sie auf verschiedene Sections zeigen
|
||||||
|
- Verhindert "Phantom-Knoten" durch korrekte Trennung von Note-Name und Abschnitt
|
||||||
|
|
||||||
|
### Provenance Firewall (Edge Registry v0.8.0)
|
||||||
|
|
||||||
|
Die **Edge Registry** stellt sicher, dass System-Kanten (`next`, `prev`, `belongs_to`) ausschließlich durch interne Struktur-Prozesse und nicht durch Nutzer oder KI manipuliert werden können:
|
||||||
|
|
||||||
|
**Schutz-Mechanismus:**
|
||||||
|
- System-Kanten dürfen nur mit `provenance="structure"` gesetzt werden
|
||||||
|
- Alle anderen Provenienzen (`explicit`, `semantic_ai`, `inherited`, `global_pool`, `rule`) werden blockiert
|
||||||
|
- Automatischer Fallback auf `related_to` bei unerlaubter Verwendung
|
||||||
|
- Logging in `data/logs/unknown_edges.jsonl` für Admin-Review
|
||||||
|
|
||||||
|
**Vorteil:** Garantiert Graph-Integrität und verhindert Manipulationen an der internen Struktur.
|
||||||
|
|
||||||
|
### Note-Level Diversity Pooling
|
||||||
|
|
||||||
|
Um das **"Note-Flooding"** (Dominanz einer einzigen Notiz durch viele ähnliche Chunks) zu verhindern, wird pro `note_id` nur noch der relevanteste Treffer im Endergebnis behalten:
|
||||||
|
|
||||||
|
**Workflow:**
|
||||||
|
1. Alle Kandidaten werden nach finalem Score sortiert
|
||||||
|
2. Pro `note_id` wird nur der Hit mit dem höchsten `total_score` behalten
|
||||||
|
3. Begrenzung auf `top_k` nach dem Diversity-Pooling
|
||||||
|
|
||||||
|
**Impact:** Verhindert, dass 10 Chunks derselben Note andere KeyNotes verdrängen. Erhöht die Vielfalt der Suchergebnisse.
|
||||||
|
|
||||||
|
### Super-Edge Aggregation
|
||||||
|
|
||||||
|
Parallele Kanten zwischen zwei Notizen werden mathematisch zu einer **"Super-Edge"** aggregiert:
|
||||||
|
|
||||||
|
**Aggregations-Logik:**
|
||||||
|
- Primäre Kante (höchstes Gewicht) zählt voll
|
||||||
|
- Jede weitere Kante (z.B. auf eine andere Sektion) wird mit Dämpfungsfaktor **0.1** gewichtet
|
||||||
|
- Formel: `total_weight = primary_weight + sum(secondary_weights * 0.1)`
|
||||||
|
|
||||||
|
**Vorteil:** Verhindert Score-Explosionen durch multiple Links auf verschiedene Sections derselben Note.
|
||||||
|
|
||||||
|
**Metadaten:**
|
||||||
|
- `is_super_edge`: Flag für Explanation Layer
|
||||||
|
- `edge_count`: Anzahl der aggregierten Kanten
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🔧 Verbesserungen
|
||||||
|
|
||||||
|
### Mathematisches Scoring (WP-22 Integration)
|
||||||
|
|
||||||
|
Die Engine berechnet den finalen Score basierend auf einer **hybriden Multiplikations-Formel**:
|
||||||
|
|
||||||
|
```
|
||||||
|
Final = (Semantic * StatusMult) * (1 + TypeBoost + EdgeBonus + CentBonus)
|
||||||
|
```
|
||||||
|
|
||||||
|
**Komponenten:**
|
||||||
|
- **Base Score:** `Semantic * StatusMult` (Lifecycle-Filter)
|
||||||
|
- **Status-Gatekeeper:** `stable` = 1.2, `draft` = 0.5, `active` = 1.0
|
||||||
|
- **Boosts:** `TypeBoost + EdgeBonus + CentBonus` (additiv, dann multiplikativ auf Base)
|
||||||
|
- **Graph Boost Factor:** Intent-spezifische Verstärkung (1.5x bei aktivem Intent)
|
||||||
|
|
||||||
|
**Vorteil:** Status wirkt als Multiplikator auf die Basis-Relevanz, Graph-Boni werden proportional verstärkt.
|
||||||
|
|
||||||
|
### Explanation Layer
|
||||||
|
|
||||||
|
Der Retriever liefert detaillierte Begründungen für jeden Bonus:
|
||||||
|
- Sektions-Links (z.B. "Link zu 'Mein Leitbild#P3 – Disziplin'")
|
||||||
|
- Hub-Zentralität (z.B. "Note ist zentraler Knoten mit 5 eingehenden Kanten")
|
||||||
|
- Super-Edge-Informationen (z.B. "3 parallele Kanten aggregiert")
|
||||||
|
- Provenance-Informationen (z.B. "Explizite Kante vom Nutzer")
|
||||||
|
|
||||||
|
**Impact:** Massiv erhöhte Transparenz für Debugging und Nutzer-Vertrauen.
|
||||||
|
|
||||||
|
### Metadaten-Persistenz
|
||||||
|
|
||||||
|
Der In-Memory Subgraph und der Datenbank-Adapter wurden so erweitert, dass Metadaten durchgängig erhalten bleiben:
|
||||||
|
|
||||||
|
**Erhaltene Metadaten:**
|
||||||
|
- `target_section`: Abschnitts-Name für präzise Verlinkung
|
||||||
|
- `provenance`: Herkunft der Kante (explicit, smart, rule, structure)
|
||||||
|
- `confidence`: Vertrauenswürdigkeit (0.0 - 1.0)
|
||||||
|
- `is_super_edge`: Flag für aggregierte Kanten
|
||||||
|
|
||||||
|
**Vorteil:** Ermöglicht präzises Retrieval-Reasoning und Explanation Layer.
|
||||||
|
|
||||||
|
### Profil-Synchronisation (Ingestion v2.13.12)
|
||||||
|
|
||||||
|
Der Ingestion-Prozessor löst Chunking-Profile hierarchisch über die `types.yaml` auf:
|
||||||
|
|
||||||
|
**Hierarchie:**
|
||||||
|
1. **Frontmatter** (höchste Priorität)
|
||||||
|
2. **types.yaml Typ-Config**
|
||||||
|
3. **Global Defaults**
|
||||||
|
|
||||||
|
**Impact:** Konsistente Verarbeitung je nach Notiz-Typ. Note-Typen wie `value` erhalten automatisch das korrekte Profil (`structured_smart_edges_strict`).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🐛 Bugfixes
|
||||||
|
|
||||||
|
- ✅ **Behoben:** "Phantom-Knoten" durch korrekte Trennung von Note-Name und Section in `target_id`
|
||||||
|
- ✅ **Behoben:** Score-Explosionen durch multiple Links auf verschiedene Sections
|
||||||
|
- ✅ **Behoben:** "Note-Flooding" durch fehlende Diversity-Filterung
|
||||||
|
- ✅ **Behoben:** Inkonsistente Metadaten durch fehlende Persistenz im Subgraph
|
||||||
|
- ✅ **Behoben:** Manipulation von System-Kanten durch Provenance Firewall
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## ⚠️ Breaking Changes & Migration
|
||||||
|
|
||||||
|
### Keine Migration erforderlich
|
||||||
|
|
||||||
|
**WICHTIG:** Diese Version ist **rückwärtskompatibel**. Bestehende Vaults funktionieren ohne Re-Import.
|
||||||
|
|
||||||
|
**Empfehlung:** Optionaler Re-Import für optimale Nutzung der neuen Features:
|
||||||
|
```bash
|
||||||
|
python3 -m scripts.import_markdown --vault ./vault --prefix "mindnet" --apply --force
|
||||||
|
```
|
||||||
|
|
||||||
|
**Was passiert beim Re-Import?**
|
||||||
|
- Bestehende Links werden neu geparst und in `target_id` + `target_section` aufgeteilt
|
||||||
|
- Self-Links (`[[#Section]]`) werden korrekt aufgelöst
|
||||||
|
- Edge-Struktur wird konsolidiert (Multigraph-Support)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📚 API-Änderungen
|
||||||
|
|
||||||
|
### Keine Breaking Changes
|
||||||
|
|
||||||
|
Die API bleibt vollständig kompatibel. Neue Metadaten werden optional zurückgegeben:
|
||||||
|
|
||||||
|
**EdgeDTO (erweitert):**
|
||||||
|
```python
|
||||||
|
class EdgeDTO(BaseModel):
|
||||||
|
# ... bestehende Felder ...
|
||||||
|
target_section: Optional[str] = None # Neu: Abschnitts-Name
|
||||||
|
is_super_edge: Optional[bool] = False # Neu: Aggregations-Flag
|
||||||
|
```
|
||||||
|
|
||||||
|
**QueryResponse (erweitert):**
|
||||||
|
- Explanation Layer enthält nun Super-Edge-Informationen
|
||||||
|
- Metadaten wie `target_section` werden in Edge-Objekten zurückgegeben
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📖 Dokumentation
|
||||||
|
|
||||||
|
Alle relevanten Dokumente wurden aktualisiert:
|
||||||
|
|
||||||
|
- ✅ `02_concept_graph_logic.md`: Provenance Firewall, Self-Links, Multigraph-Support
|
||||||
|
- ✅ `03_tech_retrieval_scoring.md`: Hybrid Scoring Formula, Note-Level Diversity, Super-Edge Aggregation
|
||||||
|
- ✅ `03_tech_data_model.md`: Section-Support, Metadaten-Persistenz
|
||||||
|
- ✅ `03_tech_ingestion_pipeline.md`: Registry-First Profiling (bereits dokumentiert)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🔄 Technische Details
|
||||||
|
|
||||||
|
### Geänderte Module
|
||||||
|
|
||||||
|
**Graph Topology:**
|
||||||
|
- `app/services/edge_registry.py`: Provenance Firewall (v0.8.0)
|
||||||
|
- `app/core/graph/graph_utils.py`: `parse_link_target()` für Section-Extraktion & Self-Links (v1.1.2)
|
||||||
|
- `app/core/graph/graph_derive_edges.py`: Multigraph-Support, `target_section` in Edge-Payload (v1.1.2)
|
||||||
|
- `app/core/graph/graph_subgraph.py`: Metadaten-Persistenz (v1.2.0)
|
||||||
|
- `app/core/graph/graph_db_adapter.py`: Vollständige Metadaten-Durchreichung (v1.1.1)
|
||||||
|
|
||||||
|
**Retrieval:**
|
||||||
|
- `app/core/retrieval/retriever.py`: Note-Level Diversity Pooling, Super-Edge Aggregation (v0.7.0)
|
||||||
|
- `app/core/retrieval/retriever_scoring.py`: Hybrid Scoring Formula (v1.0.3)
|
||||||
|
|
||||||
|
**Ingestion:**
|
||||||
|
- `app/core/ingestion/ingestion_processor.py`: Registry-First Profiling (v2.13.12)
|
||||||
|
|
||||||
|
### Versionsnummern
|
||||||
|
|
||||||
|
- Edge Registry: **v0.8.0**
|
||||||
|
- Graph Utils / Derive Edges: **v1.1.2**
|
||||||
|
- Graph Subgraph: **v1.2.0**
|
||||||
|
- Graph DB Adapter: **v1.1.1**
|
||||||
|
- Retriever: **v0.7.0**
|
||||||
|
- Retriever Scoring: **v1.0.3**
|
||||||
|
- Ingestion Processor: **v2.13.12**
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🚀 Upgrade-Pfad
|
||||||
|
|
||||||
|
### Für Administratoren
|
||||||
|
|
||||||
|
1. **Code aktualisieren:**
|
||||||
|
```bash
|
||||||
|
git pull origin main
|
||||||
|
source .venv/bin/activate
|
||||||
|
pip install -r requirements.txt
|
||||||
|
```
|
||||||
|
|
||||||
|
2. **Services neu starten:**
|
||||||
|
```bash
|
||||||
|
sudo systemctl restart mindnet-prod
|
||||||
|
sudo systemctl restart mindnet-ui-prod
|
||||||
|
```
|
||||||
|
|
||||||
|
3. **Optional: Re-Import für optimale Nutzung:**
|
||||||
|
```bash
|
||||||
|
python3 -m scripts.import_markdown --vault ./vault --prefix "mindnet" --apply --force
|
||||||
|
```
|
||||||
|
|
||||||
|
### Für Entwickler
|
||||||
|
|
||||||
|
- Keine Code-Änderungen erforderlich, wenn nur API genutzt wird
|
||||||
|
- Frontend kann neue Metadaten (`target_section`, `is_super_edge`) optional nutzen
|
||||||
|
- Explanation Layer enthält nun Super-Edge-Informationen
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📝 Bekannte Einschränkungen
|
||||||
|
|
||||||
|
- **Re-Import-Dauer:** Große Vaults (>10.000 Notizen) können 30+ Minuten benötigen (optional)
|
||||||
|
- **Temporärer Speicher:** Während des Re-Imports kann Qdrant-Speicher temporär ansteigen
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🙏 Danksagungen
|
||||||
|
|
||||||
|
Diese Version wurde durch umfangreiche Code-Analyse und Dokumentationsprüfung ermöglicht. Besonderer Fokus lag auf:
|
||||||
|
- Transformation zu einem hochpräzisen Multigraphen
|
||||||
|
- Intelligente Ergebnis-Filterung (Diversity Engine)
|
||||||
|
- Mathematisches Scoring mit gewichteten Boni
|
||||||
|
- Graph-Integrität durch Provenance Firewall
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**Vollständige Changelog:** Siehe Git-Commits für detaillierte Änderungen
|
||||||
|
**Support:** Bei Fragen siehe [Admin Operations Guide](../04_Operations/04_admin_operations.md)
|
||||||
@@ -0,0 +1,138 @@
|
|||||||
|
# Branch Merge Commit Message: WP25
|
||||||
|
|
||||||
|
```
|
||||||
|
feat: Agentic Multi-Stream RAG Orchestration (v3.0)
|
||||||
|
|
||||||
|
## Architektur-Transformation (WP-25)
|
||||||
|
|
||||||
|
### Agentic Multi-Stream RAG Orchestration
|
||||||
|
- Übergang von linearer RAG-Architektur zu paralleler Multi-Stream Engine
|
||||||
|
- Parallele Abfragen in spezialisierten Wissens-Streams (Values, Facts, Biography, Risk, Tech)
|
||||||
|
- Stream-Tracing: Jeder Treffer wird mit `stream_origin` markiert
|
||||||
|
- Fehler-Resilienz: Einzelne Stream-Fehler blockieren nicht die gesamte Anfrage
|
||||||
|
|
||||||
|
**Geänderte Dateien:**
|
||||||
|
- `app/core/retrieval/decision_engine.py`: Multi-Stream Orchestrator (v1.0.3)
|
||||||
|
- `app/routers/chat.py`: Hybrid Router Integration (v3.0.2)
|
||||||
|
- `app/models/dto.py`: Stream-Tracing Support (v0.7.1)
|
||||||
|
|
||||||
|
### Intent-basiertes Routing ("The Brain")
|
||||||
|
- Hybrid-Modus: Keyword Fast-Path + LLM Slow-Path
|
||||||
|
- Strategien: FACT_WHAT, FACT_WHEN, DECISION, EMPATHY, CODING, INTERVIEW
|
||||||
|
- Sofortige Erkennung von Triggern wie "Soll ich" oder "Wann" ohne LLM-Call
|
||||||
|
- Komplexe semantische Analyse für unklare Anfragen
|
||||||
|
|
||||||
|
**Geänderte Dateien:**
|
||||||
|
- `app/routers/chat.py`: Hybrid Router mit Keyword-Fast-Path (v3.0.2)
|
||||||
|
- `app/core/retrieval/decision_engine.py`: LLM-basiertes Routing (v1.0.3)
|
||||||
|
|
||||||
|
### Wissens-Synthese
|
||||||
|
- Spezialisierte Templates in `prompts.yaml` mit expliziten Stream-Variablen
|
||||||
|
- Pre-Initialization aller Stream-Variablen (verhindert KeyErrors)
|
||||||
|
- Provider-spezifische Templates für Ollama, Gemini und OpenRouter
|
||||||
|
- Differenzierte Abwägung zwischen Fakten und persönlichen Werten
|
||||||
|
|
||||||
|
**Geänderte Dateien:**
|
||||||
|
- `config/prompts.yaml`: Stream-Templates (v3.1.2)
|
||||||
|
- `app/core/retrieval/decision_engine.py`: Synthese-Logik (v1.0.3)
|
||||||
|
|
||||||
|
## Stream-Konfiguration & Typ-Synchronisation
|
||||||
|
|
||||||
|
### Stream-Library (decision_engine.yaml v3.1.6)
|
||||||
|
- **Values Stream:** Identität, Ethik und Prinzipien (filter_types: value, principle, belief, etc.)
|
||||||
|
- **Facts Stream:** Operative Daten (filter_types: project, decision, task, etc.)
|
||||||
|
- **Biography Stream:** Persönliche Erfahrungen (filter_types: experience, journal, profile)
|
||||||
|
- **Risk Stream:** Hindernisse und Gefahren (filter_types: risk, obstacle, bias)
|
||||||
|
- **Tech Stream:** Technisches Wissen (filter_types: concept, source, glossary, etc.)
|
||||||
|
|
||||||
|
**Edge-Boosts pro Stream:**
|
||||||
|
- Values: `guides: 3.0`, `enforced_by: 2.5`, `based_on: 2.0`
|
||||||
|
- Facts: `part_of: 2.0`, `depends_on: 1.5`, `implemented_in: 1.5`
|
||||||
|
- Risk: `blocks: 2.5`, `impacts: 2.0`, `risk_of: 2.5`
|
||||||
|
|
||||||
|
**Geänderte Dateien:**
|
||||||
|
- `config/decision_engine.yaml`: Multi-Stream Konfiguration (v3.1.6)
|
||||||
|
|
||||||
|
## Bugfixes & Optimierungen
|
||||||
|
|
||||||
|
### Vault-Import Performance
|
||||||
|
- "Empty Response Guard" korrigiert: Kurze Ingest-Antworten (YES/NO) lösen nicht mehr fälschlicherweise langsame Fallbacks aus
|
||||||
|
- Entfernung des <5-Zeichen Guards ermöglicht YES/NO Validierungen
|
||||||
|
|
||||||
|
**Geänderte Dateien:**
|
||||||
|
- `app/services/llm_service.py`: Ingest-Stability Patch (v3.4.2)
|
||||||
|
|
||||||
|
### Cloud-Resilienz
|
||||||
|
- Sicherheitscheck für das `choices`-Array in `_execute_openrouter` implementiert
|
||||||
|
- Verhindert JSON-Errors bei überlasteten APIs
|
||||||
|
|
||||||
|
**Geänderte Dateien:**
|
||||||
|
- `app/services/llm_service.py`: Empty Response Guard (v3.4.2)
|
||||||
|
|
||||||
|
### Template-Robustheit
|
||||||
|
- Automatische Vor-Initialisierung aller Stream-Variablen in der `DecisionEngine`
|
||||||
|
- Verhindert `KeyError`-Abstürze bei unvollständigen Konfigurationen
|
||||||
|
- Fallback-Mechanismus bei Template-Fehlern
|
||||||
|
|
||||||
|
**Geänderte Dateien:**
|
||||||
|
- `app/core/retrieval/decision_engine.py`: Pre-Initialization (v1.0.3)
|
||||||
|
|
||||||
|
### Intent-Kollision
|
||||||
|
- Generische Begriffe (wie "Projekt") wurden aus den Keyword-Triggern entfernt
|
||||||
|
- Sicherstellt, dass strategische Fragen (z.B. "Soll ich...?") korrekt als `DECISION` geroutet werden
|
||||||
|
|
||||||
|
**Geänderte Dateien:**
|
||||||
|
- `config/decision_engine.yaml`: Keyword-Fix (v3.1.6)
|
||||||
|
|
||||||
|
## Ollama Context-Throttling
|
||||||
|
|
||||||
|
- Vor der Übergabe an Ollama prüft der Chat-Router, ob der Kontext die Grenze von `MAX_OLLAMA_CHARS` überschreitet (Standard: 10.000)
|
||||||
|
- Automatische Kürzung bei großen Kontexten
|
||||||
|
|
||||||
|
**Geänderte Dateien:**
|
||||||
|
- `app/routers/chat.py`: Context-Throttling (v3.0.2)
|
||||||
|
|
||||||
|
## Lifespan Management
|
||||||
|
|
||||||
|
- FastAPI-Anwendung implementiert Lifespan-Management für sauberen Startup und Shutdown
|
||||||
|
- Integritäts-Check der WP-25 Konfiguration beim Startup
|
||||||
|
- Ressourcen-Cleanup beim Shutdown
|
||||||
|
- Globale Fehlerbehandlung für asynchrone Prozesse
|
||||||
|
|
||||||
|
**Geänderte Dateien:**
|
||||||
|
- `app/main.py`: Lifespan Management (v1.0.0)
|
||||||
|
|
||||||
|
## Impact & Breaking Changes
|
||||||
|
|
||||||
|
### Keine Migration erforderlich
|
||||||
|
**WICHTIG:** Diese Version ist **rückwärtskompatibel**. Bestehende Vaults funktionieren ohne Re-Import.
|
||||||
|
|
||||||
|
**Konfigurations-Updates:**
|
||||||
|
- `decision_engine.yaml` wurde auf v3.1.6 aktualisiert (Multi-Stream Struktur)
|
||||||
|
- `prompts.yaml` wurde auf v3.1.2 aktualisiert (Stream-Templates)
|
||||||
|
- **Empfehlung:** Backup der alten Konfigurationsdateien vor dem Update
|
||||||
|
|
||||||
|
### API-Erweiterungen
|
||||||
|
- `QueryHit.stream_origin`: Name des Ursprungs-Streams (optional)
|
||||||
|
- `ChatResponse.intent`: Die gewählte WP-25 Strategie (optional)
|
||||||
|
- `ChatResponse.intent_source`: Quelle der Intent-Erkennung (optional)
|
||||||
|
|
||||||
|
## Dokumentation
|
||||||
|
|
||||||
|
Alle relevanten Dokumente aktualisiert:
|
||||||
|
- `03_tech_chat_backend.md`: Agentic Multi-Stream RAG, Intent-basiertes Routing, Wissens-Synthese
|
||||||
|
- `03_tech_configuration.md`: decision_engine.yaml, prompts.yaml (Stream-Struktur)
|
||||||
|
- `03_tech_api_reference.md`: Erweiterte DTOs (stream_origin, intent)
|
||||||
|
|
||||||
|
## Versionen
|
||||||
|
|
||||||
|
- Decision Engine: v1.0.3
|
||||||
|
- Chat Router: v3.0.2
|
||||||
|
- LLM Service: v3.4.2
|
||||||
|
- DTOs: v0.7.1
|
||||||
|
- Main: v1.0.0
|
||||||
|
- decision_engine.yaml: v3.1.6
|
||||||
|
- prompts.yaml: v3.1.2
|
||||||
|
|
||||||
|
Closes #[issue-number]
|
||||||
|
```
|
||||||
@@ -0,0 +1,268 @@
|
|||||||
|
# Release Notes: Mindnet v3.0.0 (WP25)
|
||||||
|
|
||||||
|
**Release Date:** 2026-01-01
|
||||||
|
**Type:** Feature Release - Agentic Multi-Stream RAG Orchestration
|
||||||
|
**Branch:** WP25
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🎯 Übersicht
|
||||||
|
|
||||||
|
Diese Version markiert den Übergang von Mindnet von einer klassischen, linearen RAG-Architektur zu einer **Agentic Multi-Stream Engine**. Das System agiert nun als intelligenter Orchestrator, der Nutzeranfragen analysiert, in parallele Wissens-Streams aufteilt und diese zu einer kontextreichen, wertebasierten Antwort synthetisiert.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## ✨ Neue Features
|
||||||
|
|
||||||
|
### Agentic Multi-Stream RAG Orchestration
|
||||||
|
|
||||||
|
Mindnet führt nun **parallele Abfragen** in spezialisierten Wissens-Streams aus, anstatt einer einzelnen Suche:
|
||||||
|
|
||||||
|
**Stream-Library:**
|
||||||
|
* **Values Stream:** Extrahiert Identität, Ethik und Prinzipien (`value`, `principle`, `belief`, `trait`, `boundary`, `need`, `motivation`).
|
||||||
|
* **Facts Stream:** Liefert operative Daten zu Projekten, Tasks und Status (`project`, `decision`, `task`, `goal`, `event`, `state`).
|
||||||
|
* **Biography Stream:** Greift auf persönliche Erfahrungen und Journal-Einträge zu (`experience`, `journal`, `profile`, `person`).
|
||||||
|
* **Risk Stream:** Identifiziert Hindernisse und potenzielle Gefahren (`risk`, `obstacle`, `bias`).
|
||||||
|
* **Tech Stream:** Bündelt technisches Wissen, Code und Dokumentation (`concept`, `source`, `glossary`, `idea`, `insight`, `skill`, `habit`).
|
||||||
|
|
||||||
|
**Vorteile:**
|
||||||
|
* **Präzise Kontext-Ladung:** Jeder Stream fokussiert auf spezifische Wissensbereiche.
|
||||||
|
* **Parallele Ausführung:** Alle Streams werden gleichzeitig abgefragt (asyncio.gather).
|
||||||
|
* **Stream-Tracing:** Jeder Treffer wird mit `stream_origin` markiert für Feedback-Optimierung.
|
||||||
|
* **Fehler-Resilienz:** Einzelne Stream-Fehler blockieren nicht die gesamte Anfrage.
|
||||||
|
|
||||||
|
### Intent-basiertes Routing ("The Brain")
|
||||||
|
|
||||||
|
Der Router wurde zu einem **hybriden System** erweitert, das Anfragen klassifiziert, bevor die Suche beginnt:
|
||||||
|
|
||||||
|
**Strategien:**
|
||||||
|
* **FACT_WHAT:** Wissen/Listen (z.B. "Was ist...", "Welche sind...").
|
||||||
|
* **FACT_WHEN:** Zeitpunkte (z.B. "Wann...", "Datum...").
|
||||||
|
* **DECISION:** Beratung (z.B. "Soll ich...", "Sollte ich...", "Empfehlung...").
|
||||||
|
* **EMPATHY:** Reflexion (z.B. "Fühle...", "Stress...", "Angst...").
|
||||||
|
* **CODING:** Technik (z.B. "Code...", "Python...", "Bug...").
|
||||||
|
* **INTERVIEW:** Datenerfassung (z.B. "Neues Projekt...", "Erfahrung...").
|
||||||
|
|
||||||
|
**Hybrid-Modus:**
|
||||||
|
* **Keyword Fast-Path:** Sofortige Erkennung von Triggern wie "Soll ich" oder "Wann" ohne LLM-Call.
|
||||||
|
* **LLM Slow-Path:** Komplexe semantische Analyse für unklare Anfragen.
|
||||||
|
* **Type Keywords:** Automatische Erkennung von Objekt-Typen für Interview-Modus.
|
||||||
|
|
||||||
|
**Vorteil:** Reduziert Latenz durch schnelle Keyword-Erkennung, nutzt LLM nur bei Bedarf.
|
||||||
|
|
||||||
|
### Wissens-Synthese
|
||||||
|
|
||||||
|
Die Zusammenführung der Daten erfolgt über spezialisierte Templates in der `prompts.yaml`:
|
||||||
|
|
||||||
|
**Template-Struktur:**
|
||||||
|
* Explizite Variablen für jeden Stream (z.B. `{values_stream}`, `{risk_stream}`).
|
||||||
|
* **Pre-Initialization:** Alle möglichen Stream-Variablen werden vorab initialisiert (verhindert KeyErrors).
|
||||||
|
* **Provider-spezifische Templates:** Separate Versionen für Ollama, Gemini und OpenRouter.
|
||||||
|
|
||||||
|
**Synthese-Strategien:**
|
||||||
|
* **FACT_WHAT/FACT_WHEN:** Kombiniert Fakten, Biographie und Technik.
|
||||||
|
* **DECISION:** Wägt Fakten gegen Werte ab, evaluiert Risiken.
|
||||||
|
* **EMPATHY:** Fokus auf Biographie und Werte.
|
||||||
|
* **CODING:** Technik und Fakten.
|
||||||
|
|
||||||
|
**Vorteil:** Ermöglicht dem LLM eine differenzierte Abwägung zwischen Fakten und persönlichen Werten.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🔧 Verbesserungen
|
||||||
|
|
||||||
|
### Stream-Konfiguration & Typ-Synchronisation
|
||||||
|
|
||||||
|
Jeder Stream nutzt individuelle **Edge-Boosts** und **Filter-Types**, die strikt mit der `types.yaml` (v2.7.0) synchronisiert sind:
|
||||||
|
|
||||||
|
**Beispiele:**
|
||||||
|
* **Values Stream:** `guides: 3.0`, `enforced_by: 2.5`, `based_on: 2.0`.
|
||||||
|
* **Facts Stream:** `part_of: 2.0`, `depends_on: 1.5`, `implemented_in: 1.5`.
|
||||||
|
* **Risk Stream:** `blocks: 2.5`, `impacts: 2.0`, `risk_of: 2.5`.
|
||||||
|
|
||||||
|
**Vorteil:** Präzise Gewichtung der Graph-Kanten je nach Wissensbereich.
|
||||||
|
|
||||||
|
### Template-Robustheit
|
||||||
|
|
||||||
|
**Pre-Initialization:** Automatische Vor-Initialisierung aller Stream-Variablen in der `DecisionEngine` verhindert `KeyError`-Abstürze bei unvollständigen Konfigurationen.
|
||||||
|
|
||||||
|
**Fallback-Mechanismus:** Bei Template-Fehlern wird ein vereinfachter Prompt mit allen verfügbaren Stream-Ergebnissen verwendet.
|
||||||
|
|
||||||
|
### Ollama Context-Throttling
|
||||||
|
|
||||||
|
Vor der Übergabe an Ollama prüft der Chat-Router, ob der Kontext (RAG-Hits) die Grenze von `MAX_OLLAMA_CHARS` überschreitet (Standard: 10.000) und kürzt diesen ggf.
|
||||||
|
|
||||||
|
**Vorteil:** Verhindert VRAM-Überlastung bei großen Kontexten.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🐛 Bugfixes
|
||||||
|
|
||||||
|
- ✅ **Behoben:** Vault-Import Performance - "Empty Response Guard" korrigiert, damit kurze Ingest-Antworten (YES/NO) nicht mehr fälschlicherweise langsame Fallbacks auslösen.
|
||||||
|
- ✅ **Behoben:** Cloud-Resilienz - Sicherheitscheck für das `choices`-Array in `_execute_openrouter` implementiert, um JSON-Errors bei überlasteten APIs zu verhindern.
|
||||||
|
- ✅ **Behoben:** Template-Robustheit - Automatische Vor-Initialisierung aller Stream-Variablen verhindert `KeyError`-Abstürze.
|
||||||
|
- ✅ **Behoben:** Intent-Kollision - Generische Begriffe (wie "Projekt") wurden aus den Keyword-Triggern entfernt, um sicherzustellen, dass strategische Fragen (z.B. "Soll ich...?") korrekt als `DECISION` geroutet werden.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## ⚠️ Breaking Changes & Migration
|
||||||
|
|
||||||
|
### Keine Migration erforderlich
|
||||||
|
|
||||||
|
**WICHTIG:** Diese Version ist **rückwärtskompatibel**. Bestehende Vaults funktionieren ohne Re-Import.
|
||||||
|
|
||||||
|
**Konfigurations-Updates:**
|
||||||
|
* `decision_engine.yaml` wurde auf v3.1.6 aktualisiert (Multi-Stream Struktur).
|
||||||
|
* `prompts.yaml` wurde auf v3.1.2 aktualisiert (Stream-Templates).
|
||||||
|
* **Empfehlung:** Backup der alten Konfigurationsdateien vor dem Update.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📚 API-Änderungen
|
||||||
|
|
||||||
|
### Erweiterte DTOs
|
||||||
|
|
||||||
|
**QueryHit (erweitert):**
|
||||||
|
```python
|
||||||
|
class QueryHit(BaseModel):
|
||||||
|
# ... bestehende Felder ...
|
||||||
|
stream_origin: Optional[str] = None # Neu: Name des Ursprungs-Streams
|
||||||
|
```
|
||||||
|
|
||||||
|
**ChatResponse (erweitert):**
|
||||||
|
```python
|
||||||
|
class ChatResponse(BaseModel):
|
||||||
|
# ... bestehende Felder ...
|
||||||
|
intent: Optional[str] = "FACT" # Neu: Die gewählte WP-25 Strategie
|
||||||
|
intent_source: Optional[str] = "LLM_Router" # Neu: Quelle der Intent-Erkennung
|
||||||
|
```
|
||||||
|
|
||||||
|
**Impact für API-Consumer:**
|
||||||
|
* Frontend kann `stream_origin` für visuelle Kennzeichnung der Quellen nutzen.
|
||||||
|
* `intent` und `intent_source` ermöglichen Debugging und Analytics.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📖 Dokumentation
|
||||||
|
|
||||||
|
Alle relevanten Dokumente wurden aktualisiert:
|
||||||
|
|
||||||
|
- ✅ `03_tech_chat_backend.md`: Agentic Multi-Stream RAG, Intent-basiertes Routing, Wissens-Synthese
|
||||||
|
- ✅ `03_tech_configuration.md`: decision_engine.yaml, prompts.yaml (Stream-Struktur)
|
||||||
|
- ✅ `03_tech_api_reference.md`: Erweiterte DTOs (stream_origin, intent)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🔄 Technische Details
|
||||||
|
|
||||||
|
### Geänderte Module
|
||||||
|
|
||||||
|
**Decision Engine:**
|
||||||
|
- `app/core/retrieval/decision_engine.py`: Multi-Stream Orchestrator (v1.0.3)
|
||||||
|
- Paralleles Retrieval via `_execute_parallel_streams()`
|
||||||
|
- Stream-Tracing mit `stream_origin`
|
||||||
|
- Pre-Initialization der Stream-Variablen
|
||||||
|
|
||||||
|
**Chat Router:**
|
||||||
|
- `app/routers/chat.py`: Hybrid Router Integration (v3.0.2)
|
||||||
|
- Keyword Fast-Path + LLM Slow-Path
|
||||||
|
- Multi-Stream Orchestrierung
|
||||||
|
- Ollama Context-Throttling
|
||||||
|
|
||||||
|
**LLM Service:**
|
||||||
|
- `app/services/llm_service.py`: Ingest-Stability Patch (v3.4.2)
|
||||||
|
- Entfernung des <5-Zeichen Guards
|
||||||
|
- Empty Response Guard für OpenRouter
|
||||||
|
- Lazy Initialization der DecisionEngine
|
||||||
|
|
||||||
|
**DTOs:**
|
||||||
|
- `app/models/dto.py`: Stream-Tracing Support (v0.7.1)
|
||||||
|
- `stream_origin` in `QueryHit`
|
||||||
|
- `intent` und `intent_source` in `ChatResponse`
|
||||||
|
|
||||||
|
**Main:**
|
||||||
|
- `app/main.py`: Lifespan Management (v1.0.0)
|
||||||
|
- Startup-Integritäts-Check
|
||||||
|
- Ressourcen-Cleanup beim Shutdown
|
||||||
|
- Globale Fehlerbehandlung
|
||||||
|
|
||||||
|
**Konfiguration:**
|
||||||
|
- `config/decision_engine.yaml`: Multi-Stream Konfiguration (v3.1.6)
|
||||||
|
- `config/prompts.yaml`: Stream-Templates (v3.1.2)
|
||||||
|
|
||||||
|
### Versionsnummern
|
||||||
|
|
||||||
|
- Decision Engine: **v1.0.3**
|
||||||
|
- Chat Router: **v3.0.2**
|
||||||
|
- LLM Service: **v3.4.2**
|
||||||
|
- DTOs: **v0.7.1**
|
||||||
|
- Main: **v1.0.0**
|
||||||
|
- decision_engine.yaml: **v3.1.6**
|
||||||
|
- prompts.yaml: **v3.1.2**
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🚀 Upgrade-Pfad
|
||||||
|
|
||||||
|
### Für Administratoren
|
||||||
|
|
||||||
|
1. **Code aktualisieren:**
|
||||||
|
```bash
|
||||||
|
git pull origin main
|
||||||
|
source .venv/bin/activate
|
||||||
|
pip install -r requirements.txt
|
||||||
|
```
|
||||||
|
|
||||||
|
2. **Konfiguration prüfen:**
|
||||||
|
```bash
|
||||||
|
# Backup der alten Konfigurationen
|
||||||
|
cp config/decision_engine.yaml config/decision_engine.yaml.backup
|
||||||
|
cp config/prompts.yaml config/prompts.yaml.backup
|
||||||
|
|
||||||
|
# Prüfen, ob neue Konfigurationen vorhanden sind
|
||||||
|
ls -la config/decision_engine.yaml config/prompts.yaml
|
||||||
|
```
|
||||||
|
|
||||||
|
3. **Services neu starten:**
|
||||||
|
```bash
|
||||||
|
sudo systemctl restart mindnet-prod
|
||||||
|
sudo systemctl restart mindnet-ui-prod
|
||||||
|
```
|
||||||
|
|
||||||
|
### Für Entwickler
|
||||||
|
|
||||||
|
- Keine Code-Änderungen erforderlich, wenn nur API genutzt wird
|
||||||
|
- Frontend kann neue Felder (`stream_origin`, `intent`, `intent_source`) optional nutzen
|
||||||
|
- Stream-Tracing ermöglicht Feedback-Optimierung pro Wissensbereich
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📝 Bekannte Einschränkungen
|
||||||
|
|
||||||
|
- **Stream-Parallelität:** Maximale Anzahl paralleler Streams ist durch asyncio-Limits begrenzt (typischerweise 5-10 Streams).
|
||||||
|
- **Kontext-Größe:** Große Kontexte (>10.000 Zeichen) werden bei Ollama automatisch gekürzt.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🔮 Ausblick (WP-25a: Agentic Refinement)
|
||||||
|
|
||||||
|
Auf Basis des stabilen WP-25 Fundaments sind folgende Erweiterungen geplant:
|
||||||
|
|
||||||
|
* **Pre-Synthesis:** LLM-basierte Komprimierung überlanger Streams vor der finalen Antwortgenerierung.
|
||||||
|
* **Kontext-Budgeting:** Intelligente Verteilung der verfügbaren Token auf die aktivierten Streams.
|
||||||
|
* **Stream-specific Provider:** Zuweisung unterschiedlicher KI-Modelle pro Wissensbereich (z.B. lokales Ollama für Identitäts-Werte, Gemini für technische Fakten).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🙏 Danksagungen
|
||||||
|
|
||||||
|
Diese Version wurde durch umfangreiche Architektur-Überarbeitung ermöglicht. Besonderer Fokus lag auf:
|
||||||
|
- Transformation zu einer Agentic Multi-Stream Engine
|
||||||
|
- Intelligente Intent-Erkennung mit Hybrid-Routing
|
||||||
|
- Parallele Wissens-Synthese mit wertebasierter Abwägung
|
||||||
|
- Robustheit und Fehler-Resilienz
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**Vollständige Changelog:** Siehe Git-Commits für detaillierte Änderungen
|
||||||
|
**Support:** Bei Fragen siehe [Admin Operations Guide](../04_Operations/04_admin_operations.md)
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
# Branch Merge Commit: WP-25a
|
||||||
|
|
||||||
|
**Branch:** `WP25a`
|
||||||
|
**Target:** `main`
|
||||||
|
**Version:** v3.1.0
|
||||||
|
**Date:** 2026-01-02
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Commit Message
|
||||||
|
|
||||||
|
```
|
||||||
|
feat: Mixture of Experts (MoE) & Fallback-Kaskade (v3.0.0)
|
||||||
|
|
||||||
|
### Mixture of Experts (MoE) Architektur
|
||||||
|
- Übergang von provider-basierter zu profilbasierter Experten-Steuerung
|
||||||
|
- Zentrale Experten-Registry (`llm_profiles.yaml` v1.3.0)
|
||||||
|
- Aufgabenspezifische Profile: synthesis_pro, tech_expert, compression_fast, ingest_validator, identity_safe, embedding_expert
|
||||||
|
- Hardware-Optimierung: Lokaler Anker (Ollama/Phi-3) für maximale Privacy
|
||||||
|
|
||||||
|
### Rekursive Fallback-Kaskade
|
||||||
|
- Implementierung in `app/services/llm_service.py` (v3.5.2)
|
||||||
|
- Automatische Fallback-Logik bei Provider-Fehlern
|
||||||
|
- Schutz gegen Zirkel-Referenzen via `visited_profiles`-Tracking
|
||||||
|
- Background-Semaphore für parallele Tasks
|
||||||
|
|
||||||
|
### Pre-Synthesis Kompression (Module A)
|
||||||
|
- Asynchrone Verdichtung überlanger Wissens-Streams
|
||||||
|
- Konfigurierbare Schwellenwerte pro Stream (`compression_threshold`)
|
||||||
|
- Profil-gesteuerte Kompression via `compression_profile`
|
||||||
|
- Parallelisierung über `asyncio.gather()`
|
||||||
|
|
||||||
|
### Profilgesteuerte Ingestion
|
||||||
|
- Semantische Kanten-Validierung via `ingest_validator` (Temperature 0.0)
|
||||||
|
- Embedding-Konsolidierung über `embedding_expert` Profil
|
||||||
|
- Entfernung der Embedding-Konfiguration aus `.env`
|
||||||
|
|
||||||
|
### Startup-Schutz & Audit-Fixes
|
||||||
|
- Validierung von `llm_profiles.yaml` und `decision_engine.yaml` beim Booten
|
||||||
|
- Behebung der Sicherheitslücke in `DecisionEngine` (Fallback-Aufrufe nutzen nun `profile_name`)
|
||||||
|
- Circular Import Fix: Ingestion-Module nutzen neutrale `app.core.registry`
|
||||||
|
|
||||||
|
### Code-Komponenten
|
||||||
|
- `app/services/llm_service.py`: v3.5.2 (Rekursive Fallback-Kaskade)
|
||||||
|
- `app/core/retrieval/decision_engine.py`: v1.2.1 (Profile-Driven Orchestration)
|
||||||
|
- `app/core/ingestion/ingestion_processor.py`: v2.14.0 (Profilgesteuerte Validierung)
|
||||||
|
- `app/core/ingestion/ingestion_validation.py`: v2.13.0 (MoE-Profil Integration)
|
||||||
|
- `app/services/embeddings_client.py`: v2.6.0 (Profil-basierte Modell-Auflösung)
|
||||||
|
- `app/main.py`: v1.1.0 (Startup-Validierung)
|
||||||
|
|
||||||
|
### Konfiguration
|
||||||
|
- `config/llm_profiles.yaml`: v1.3.0 (Zentrale Experten-Registry)
|
||||||
|
- `config/decision_engine.yaml`: v3.2.2 (Decoupled MoE Logic, compression_thresholds)
|
||||||
|
|
||||||
|
### Dokumentation
|
||||||
|
- `03_tech_configuration.md`: llm_profiles.yaml Dokumentation
|
||||||
|
- `03_tech_chat_backend.md`: MoE Architektur und Fallback-Kaskade
|
||||||
|
- `02_concept_ai_personality.md`: Mixture of Experts Konzept
|
||||||
|
- `03_tech_ingestion_pipeline.md`: Profilgesteuerte Validierung
|
||||||
|
- `00_glossary.md`: Neue Begriffe (MoE, Profile, Fallback-Kaskade)
|
||||||
|
- `05_developer_guide.md`: Teach-the-AI mit Profilen
|
||||||
|
- `04_admin_operations.md`: Konfigurations-Updates
|
||||||
|
- `06_active_roadmap.md`: WP25a als abgeschlossen markiert
|
||||||
|
|
||||||
|
### Breaking Changes
|
||||||
|
- Keine Breaking Changes für Endbenutzer
|
||||||
|
- ENV-Variablen `MINDNET_LLM_PROVIDER`, `MINDNET_LLM_MODEL` etc. dienen nur noch als Fallback
|
||||||
|
- Neue Konfigurationsdatei `llm_profiles.yaml` ist erforderlich (Startup-Validierung)
|
||||||
|
|
||||||
|
### Migration
|
||||||
|
- Administratoren müssen `config/llm_profiles.yaml` erstellen
|
||||||
|
- System startet nicht, wenn `llm_profiles.yaml` fehlt oder ungültig ist
|
||||||
|
- ENV-Variablen bleiben als Fallback erhalten
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**Status:** ✅ WP-25a ist zu 100% implementiert und audit-geprüft.
|
||||||
|
**Nächster Schritt:** WP-25b (Prompt-Orchestration & Model-Specific Tuning).
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Zusammenfassung
|
||||||
|
|
||||||
|
Dieser Merge führt die **Mixture of Experts (MoE) Architektur** in MindNet ein. Das System nutzt nun eine profilbasierte Experten-Steuerung statt einer globalen Provider-Konfiguration. Jede Systemaufgabe wird einem dedizierten Profil zugewiesen, das Modell, Provider und Parameter unabhängig definiert.
|
||||||
|
|
||||||
|
**Kern-Features:**
|
||||||
|
- Zentrale Experten-Registry (`llm_profiles.yaml`)
|
||||||
|
- Rekursive Fallback-Kaskade mit Schutz gegen Zirkel-Referenzen
|
||||||
|
- Pre-Synthesis Kompression für überlange Wissens-Streams
|
||||||
|
- Profilgesteuerte Ingestion mit deterministischer Validierung
|
||||||
|
- Startup-Schutz und Audit-Fixes
|
||||||
|
|
||||||
|
**Technische Integrität:**
|
||||||
|
- Alle LLM-Aufrufe nutzen nun die Profilsteuerung
|
||||||
|
- Startup-Validierung verhindert fehlerhafte Konfigurationen
|
||||||
|
- Circular Import Fix verbessert Wartbarkeit
|
||||||
|
|
||||||
|
**Dokumentation:**
|
||||||
|
- Vollständige Aktualisierung aller relevanten Dokumente
|
||||||
|
- Neue Begriffe im Glossar
|
||||||
|
- Konfigurations-Referenz erweitert
|
||||||
|
- Developer Guide aktualisiert
|
||||||
@@ -0,0 +1,186 @@
|
|||||||
|
# MindNet v3.0.0 - Release Notes: WP-25a
|
||||||
|
|
||||||
|
**Release Date:** 2026-01-02
|
||||||
|
**Type:** Feature Release - Mixture of Experts (MoE) & Fallback-Kaskade
|
||||||
|
**Version:** 3.1.0 (WP-25a)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🎯 Überblick
|
||||||
|
|
||||||
|
Mit WP-25a wurde MindNet von einer provider-basierten Steuerung auf eine **profilbasierte Experten-Architektur (Mixture of Experts)** umgestellt. Jede Systemaufgabe (Synthese, Ingestion-Validierung, Routing, Kompression) wird nun einem dedizierten Profil zugewiesen, das Modell, Provider und Parameter unabhängig von der globalen Konfiguration definiert.
|
||||||
|
|
||||||
|
Diese Version markiert einen fundamentalen Architektur-Sprung: Von einer monolithischen LLM-Konfiguration hin zu einer modularen, aufgabenspezifischen Experten-Steuerung mit automatischer Resilienz.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## ✨ Neue Features
|
||||||
|
|
||||||
|
### 1. Mixture of Experts (MoE) Architektur
|
||||||
|
|
||||||
|
**Zentrale Experten-Steuerung (`llm_profiles.yaml` v1.3.0):**
|
||||||
|
* Einführung von Experten-Profilen für spezifische Aufgaben:
|
||||||
|
* `synthesis_pro`: Hochwertige Synthese für Chat-Antworten
|
||||||
|
* `tech_expert`: Fachspezialist für Code & Technik (Claude 3.5 Sonnet)
|
||||||
|
* `compression_fast`: Schnelle Kompression & Routing (Mistral 7B)
|
||||||
|
* `ingest_validator`: Deterministische Validierung (Temperature 0.0)
|
||||||
|
* `identity_safe`: Lokaler Anker (Ollama/Phi-3) für maximale Privacy
|
||||||
|
* `embedding_expert`: Zentrale Steuerung des Embedding-Modells
|
||||||
|
|
||||||
|
**Vorteile:**
|
||||||
|
* **Aufgabenspezifische Optimierung:** Jede Aufgabe nutzt das optimale Modell
|
||||||
|
* **Hardware-Optimierung:** Lokaler Anker für kleine Hardware-Umgebungen
|
||||||
|
* **Wartbarkeit:** Zentrale Konfiguration statt verstreuter ENV-Variablen
|
||||||
|
|
||||||
|
### 2. Rekursive Fallback-Kaskade
|
||||||
|
|
||||||
|
**Implementierung (`app/services/llm_service.py` v3.5.2):**
|
||||||
|
* Automatische Fallback-Logik bei Provider-Fehlern:
|
||||||
|
1. Versucht primäres Profil (z.B. `synthesis_pro`)
|
||||||
|
2. Bei Fehler → `fallback_profile` (z.B. `synthesis_backup`)
|
||||||
|
3. Bei weiterem Fehler → nächster Fallback (z.B. `identity_safe`)
|
||||||
|
4. Terminaler Endpunkt: `identity_safe` hat keinen Fallback (lokales Modell)
|
||||||
|
|
||||||
|
**Schutzmechanismen:**
|
||||||
|
* **Zirkuläre Referenzen:** `visited_profiles`-Tracking verhindert Endlosschleifen
|
||||||
|
* **Background-Semaphore:** Parallele Tasks werden gedrosselt (konfigurierbar via `BACKGROUND_LIMIT`)
|
||||||
|
|
||||||
|
### 3. Pre-Synthesis Kompression (Module A)
|
||||||
|
|
||||||
|
**Implementierung (`app/core/retrieval/decision_engine.py` v1.2.1):**
|
||||||
|
* Wissens-Streams, die den Schwellenwert (`compression_threshold`) überschreiten, werden **asynchron verdichtet**, bevor sie die Synthese erreichen
|
||||||
|
* **Konfigurierbar pro Stream:** Z.B. 2500 Zeichen für Values Stream, 3500 für Facts Stream
|
||||||
|
* **Profil-gesteuert:** Nutzt `compression_profile` (z.B. `compression_fast` für schnelle Zusammenfassung)
|
||||||
|
* **Parallelisierung:** Mehrere Streams können gleichzeitig komprimiert werden
|
||||||
|
|
||||||
|
**Vorteile:**
|
||||||
|
* Reduziert Token-Verbrauch bei langen Streams
|
||||||
|
* Beschleunigt Synthese durch kürzere Kontexte
|
||||||
|
* Erhält Relevanz durch intelligente Zusammenfassung
|
||||||
|
|
||||||
|
### 4. Profilgesteuerte Ingestion (Wissens-Gatekeeper)
|
||||||
|
|
||||||
|
**Implementierung:**
|
||||||
|
* `app/core/ingestion/ingestion_processor.py` v2.14.0
|
||||||
|
* `app/core/ingestion/ingestion_validation.py` v2.13.0
|
||||||
|
|
||||||
|
**Features:**
|
||||||
|
* Semantische Kanten-Validierung erfolgt zwingend über das MoE-Profil `ingest_validator` (Temperature 0.0 für Determinismus)
|
||||||
|
* **Embedding-Konsolidierung:** Der `EmbeddingsClient` (v2.6.0) bezieht Modellvorgaben und Dimensionen direkt aus dem Profil `embedding_expert`
|
||||||
|
* Entfernung der Embedding-Konfiguration aus der `.env` zugunsten zentraler Profil-Registry
|
||||||
|
|
||||||
|
### 5. Startup-Schutz & Audit-Fixes
|
||||||
|
|
||||||
|
**Implementierung (`app/main.py` v1.1.0):**
|
||||||
|
* Verifiziert beim Booten die Existenz und Validität von `llm_profiles.yaml` und `decision_engine.yaml`
|
||||||
|
* **Audit-Fix:** Behebung einer Sicherheitslücke in der `DecisionEngine`, durch die Fallback-Aufrufe bei Template-Fehlern die Profilsteuerung umgangen hätten
|
||||||
|
* **Circular Import Fix:** Ingestion-Module nutzen nun die neutrale `app.core.registry` für Text-Bereinigung und Registry-Lookups
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🔧 Technische Änderungen
|
||||||
|
|
||||||
|
### Konfigurationsdateien
|
||||||
|
|
||||||
|
**Neue Datei:**
|
||||||
|
* `config/llm_profiles.yaml` v1.3.0: Zentrale Experten-Registry
|
||||||
|
|
||||||
|
**Aktualisierte Dateien:**
|
||||||
|
* `config/decision_engine.yaml` v3.2.2: Decoupled MoE Logic, Integration von `compression_thresholds`
|
||||||
|
|
||||||
|
### Code-Komponenten
|
||||||
|
|
||||||
|
| Komponente | Version | Änderungen |
|
||||||
|
| :--- | :--- | :--- |
|
||||||
|
| `app/services/llm_service.py` | v3.5.2 | Rekursive Fallback-Kaskade, Profil-Auflösung |
|
||||||
|
| `app/core/retrieval/decision_engine.py` | v1.2.1 | Profile-Driven Orchestration, Pre-Synthesis Kompression |
|
||||||
|
| `app/core/ingestion/ingestion_processor.py` | v2.14.0 | Profilgesteuerte Validierung |
|
||||||
|
| `app/core/ingestion/ingestion_validation.py` | v2.13.0 | MoE-Profil `ingest_validator` |
|
||||||
|
| `app/services/embeddings_client.py` | v2.6.0 | Profil-basierte Modell-Auflösung |
|
||||||
|
| `app/main.py` | v1.1.0 | Startup-Validierung der YAML-Dateien |
|
||||||
|
|
||||||
|
### Environment-Variablen
|
||||||
|
|
||||||
|
**Neue Variable:**
|
||||||
|
* `MINDNET_LLM_PROFILES_PATH`: Pfad zur Profil-Registry (Default: `config/llm_profiles.yaml`)
|
||||||
|
|
||||||
|
**Legacy (nur noch Fallback):**
|
||||||
|
* `MINDNET_LLM_PROVIDER`, `MINDNET_LLM_MODEL`, etc. dienen nur noch als Fallback, wenn kein Profil angegeben wird
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🐛 Behobene Probleme
|
||||||
|
|
||||||
|
- ✅ **Behoben:** Sicherheitslücke in der `DecisionEngine` - Fallback-Aufrufe nutzen nun korrekt `profile_name`
|
||||||
|
- ✅ **Behoben:** Circular Import zwischen Ingestion-Modulen und Registry
|
||||||
|
- ✅ **Behoben:** Fehlende Startup-Validierung der YAML-Konfigurationen
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📚 Dokumentation
|
||||||
|
|
||||||
|
**Aktualisierte Dokumente:**
|
||||||
|
- ✅ `03_tech_configuration.md`: llm_profiles.yaml Dokumentation
|
||||||
|
- ✅ `03_tech_chat_backend.md`: MoE Architektur und Fallback-Kaskade
|
||||||
|
- ✅ `02_concept_ai_personality.md`: Mixture of Experts Konzept
|
||||||
|
- ✅ `03_tech_ingestion_pipeline.md`: Profilgesteuerte Validierung
|
||||||
|
- ✅ `00_glossary.md`: Neue Begriffe (MoE, Profile, Fallback-Kaskade)
|
||||||
|
- ✅ `05_developer_guide.md`: Teach-the-AI mit Profilen
|
||||||
|
- ✅ `04_admin_operations.md`: Konfigurations-Updates
|
||||||
|
- ✅ `06_active_roadmap.md`: WP25a als abgeschlossen markiert
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🚀 Migration & Upgrade
|
||||||
|
|
||||||
|
### Für Administratoren
|
||||||
|
|
||||||
|
1. **Neue Konfigurationsdatei erstellen:**
|
||||||
|
```bash
|
||||||
|
cp config/llm_profiles.yaml.example config/llm_profiles.yaml
|
||||||
|
# Anpassen nach Bedarf
|
||||||
|
```
|
||||||
|
|
||||||
|
2. **Startup-Validierung prüfen:**
|
||||||
|
```bash
|
||||||
|
# System startet nicht, wenn llm_profiles.yaml fehlt oder ungültig ist
|
||||||
|
python3 -m app.main
|
||||||
|
```
|
||||||
|
|
||||||
|
3. **ENV-Variablen (optional):**
|
||||||
|
Die `.env` Variablen `MINDNET_LLM_PROVIDER`, `MINDNET_LLM_MODEL` etc. dienen nur noch als Fallback. Die primäre Steuerung erfolgt über `llm_profiles.yaml`.
|
||||||
|
|
||||||
|
### Für Entwickler
|
||||||
|
|
||||||
|
**API-Änderungen:**
|
||||||
|
* `LLMService.generate_raw_response()` unterstützt nun `profile_name` Parameter
|
||||||
|
* Fallback-Kaskade erfolgt automatisch bei Fehlern
|
||||||
|
* `visited_profiles`-Tracking verhindert Zirkel-Referenzen
|
||||||
|
|
||||||
|
**Konfiguration:**
|
||||||
|
* Neue Profile können in `llm_profiles.yaml` definiert werden
|
||||||
|
* `decision_engine.yaml` referenziert Profile über `router_profile`, `llm_profile`, `compression_profile`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🔮 Ausblick (WP-25b: Prompt-Orchestration & Model-Specific Tuning)
|
||||||
|
|
||||||
|
- Pre-Synthesis: LLM-basierte Komprimierung überlanger Streams (✅ bereits implementiert)
|
||||||
|
- Kontext-Budgeting: Intelligente Token-Verteilung
|
||||||
|
- Stream-specific Provider: Unterschiedliche KI-Modelle pro Wissensbereich
|
||||||
|
- Prompt-Orchestration: Dynamische Prompt-Anpassung basierend auf Profil und Kontext
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📊 Metriken & Performance
|
||||||
|
|
||||||
|
**Erwartete Verbesserungen:**
|
||||||
|
* **Resilienz:** Automatische Fallback-Kaskade reduziert Ausfallzeiten
|
||||||
|
* **Token-Effizienz:** Pre-Synthesis Kompression reduziert Token-Verbrauch bei langen Streams
|
||||||
|
* **Determinismus:** Profilgesteuerte Validierung (Temperature 0.0) erhöht Konsistenz
|
||||||
|
* **Wartbarkeit:** Zentrale Profil-Registry vereinfacht Konfigurations-Management
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**Status:** ✅ WP-25a ist zu 100% implementiert und audit-geprüft.
|
||||||
|
**Nächster Schritt:** WP-25b (Prompt-Orchestration & Model-Specific Tuning).
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
# Branch Merge Commit: WP-25b
|
||||||
|
|
||||||
|
**Branch:** `WP25b`
|
||||||
|
**Target:** `main`
|
||||||
|
**Version:** v3.1.1
|
||||||
|
**Date:** 2026-01-02
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Commit Message
|
||||||
|
|
||||||
|
```
|
||||||
|
feat: Lazy-Prompt-Orchestration & Full Resilience (v3.1.1)
|
||||||
|
|
||||||
|
### Hierarchisches Prompt-Resolution-System
|
||||||
|
- Dreistufige Auflösungs-Logik: Level 1 (Modell-ID) → Level 2 (Provider) → Level 3 (Default)
|
||||||
|
- Modell-spezifische Optimierungen für Gemini 2.0, Llama 3.3, Qwen 2.5
|
||||||
|
- PROMPT-TRACE Logging für vollständige Transparenz
|
||||||
|
- Implementierung in `app/services/llm_service.py` (v3.5.5)
|
||||||
|
|
||||||
|
### Lazy-Prompt-Orchestration
|
||||||
|
- Prompts werden erst zur Laufzeit geladen, basierend auf aktivem Modell
|
||||||
|
- Parameter: `prompt_key` und `variables` statt vorformatierter Strings
|
||||||
|
- Maximale Resilienz bei Modell-Fallbacks (Cloud → Local)
|
||||||
|
- Vollständige Integration in Chat, Ingestion und DecisionEngine
|
||||||
|
|
||||||
|
### Ultra-robustes Intent-Parsing
|
||||||
|
- Regex-basierter Parser bereinigt Modell-Artefakte (z.B. `CODING[/S]` → `CODING`)
|
||||||
|
- Implementierung in `app/core/retrieval/decision_engine.py` (v1.3.2)
|
||||||
|
- Fehlerresistenz gegen Stop-Marker, Newlines oder Modell-Plaudereien
|
||||||
|
|
||||||
|
### Differenzierte Ingestion-Validierung
|
||||||
|
- Unterscheidung zwischen transienten (Netzwerk) und permanenten (Config) Fehlern
|
||||||
|
- Transiente Fehler erlauben Kante (Datenverlust vermeiden)
|
||||||
|
- Permanente Fehler lehnen Kante ab (Graph-Qualität schützen)
|
||||||
|
- Implementierung in `app/core/ingestion/ingestion_validation.py` (v2.14.0)
|
||||||
|
|
||||||
|
### Code-Komponenten
|
||||||
|
- `app/services/llm_service.py`: v3.5.5 (Hierarchische Prompt-Resolution, Lazy-Loading)
|
||||||
|
- `app/core/retrieval/decision_engine.py`: v1.3.2 (Ultra-robustes Intent-Parsing)
|
||||||
|
- `app/core/ingestion/ingestion_validation.py`: v2.14.0 (Lazy-Prompt-Integration)
|
||||||
|
- `app/routers/chat.py`: v3.0.3 (Lazy-Prompt-Loading für Chat-Synthese)
|
||||||
|
|
||||||
|
### Konfiguration
|
||||||
|
- `config/prompts.yaml`: v3.2.2 (Hierarchische Struktur mit Modell-spezifischen Overrides)
|
||||||
|
- 100% Erhalt der Original-Prompts aus v3.1.2 für Provider-Ebene
|
||||||
|
- Integration von Modell-spezifischen Overrides
|
||||||
|
- Hinzufügen von `compression_template`
|
||||||
|
|
||||||
|
### Dokumentation
|
||||||
|
- `03_tech_chat_backend.md`: Hierarchisches Prompt-Resolution-System
|
||||||
|
- `03_tech_configuration.md`: prompts.yaml hierarchische Struktur
|
||||||
|
- `02_concept_ai_personality.md`: Lazy-Prompt-Orchestration Konzept
|
||||||
|
- `03_tech_ingestion_pipeline.md`: Differenzierte Validierung
|
||||||
|
- `00_glossary.md`: Neue Begriffe (Lazy-Prompt, PROMPT-TRACE)
|
||||||
|
- `05_developer_guide.md`: Lazy-Prompt-Orchestration für Entwickler
|
||||||
|
- `06_active_roadmap.md`: WP25b als abgeschlossen markiert
|
||||||
|
|
||||||
|
### Breaking Changes
|
||||||
|
- Keine Breaking Changes für Endbenutzer
|
||||||
|
- Vorformatierte Prompts werden weiterhin unterstützt (Abwärtskompatibilität)
|
||||||
|
- Neue API-Parameter `prompt_key` und `variables` optional
|
||||||
|
|
||||||
|
### Migration
|
||||||
|
- Keine Migration erforderlich
|
||||||
|
- System funktioniert ohne Änderungen
|
||||||
|
- Optional: Modell-spezifische Prompts können in `prompts.yaml` definiert werden
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**Status:** ✅ WP-25b ist zu 100% implementiert und audit-geprüft.
|
||||||
|
**Nächster Schritt:** WP-25c (Kontext-Budgeting & Erweiterte Prompt-Optimierung).
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Zusammenfassung
|
||||||
|
|
||||||
|
Dieser Merge führt die **Lazy-Prompt-Orchestration** in MindNet ein. Das System nutzt nun eine hierarchische Prompt-Auflösung mit Lazy-Loading, die Prompts erst zur Laufzeit lädt, basierend auf dem exakt aktiven Modell.
|
||||||
|
|
||||||
|
**Kern-Features:**
|
||||||
|
- Hierarchisches Prompt-Resolution-System (3-stufig)
|
||||||
|
- Lazy-Prompt-Orchestration mit modell-spezifischem Tuning
|
||||||
|
- Ultra-robustes Intent-Parsing via Regex
|
||||||
|
- Differenzierte Ingestion-Validierung
|
||||||
|
- PROMPT-TRACE Logging für vollständige Transparenz
|
||||||
|
|
||||||
|
**Technische Integrität:**
|
||||||
|
- Alle LLM-Aufrufe nutzen nun Lazy-Prompt-Loading
|
||||||
|
- Modell-Artefakte werden zuverlässig bereinigt
|
||||||
|
- Fehlerbehandlung differenziert zwischen transienten und permanenten Fehlern
|
||||||
|
|
||||||
|
**Dokumentation:**
|
||||||
|
- Vollständige Aktualisierung aller relevanten Dokumente
|
||||||
|
- Neue Begriffe im Glossar
|
||||||
|
- Konfigurations-Referenz erweitert
|
||||||
|
- Developer Guide aktualisiert
|
||||||
@@ -0,0 +1,205 @@
|
|||||||
|
# MindNet v3.1.1 - Release Notes: WP-25b
|
||||||
|
|
||||||
|
**Release Date:** 2026-01-02
|
||||||
|
**Type:** Feature Release - Lazy-Prompt-Orchestration & Full Resilience
|
||||||
|
**Version:** 3.1.1 (WP-25b)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🎯 Überblick
|
||||||
|
|
||||||
|
Mit WP-25b wurde MindNet von statischer Prompt-Formatierung auf eine **hierarchische Lazy-Prompt-Orchestration** umgestellt. Prompts werden erst im Moment des Modellaustauschs geladen, basierend auf dem exakt aktiven Modell. Dies ermöglicht modell-spezifisches Tuning und maximale Resilienz bei Modell-Fallbacks.
|
||||||
|
|
||||||
|
Diese Version markiert einen weiteren Architektur-Sprung: Von vorformatierter Prompt-Strings hin zu einer dynamischen, modell-spezifischen Prompt-Auflösung mit vollständiger Traceability.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## ✨ Neue Features
|
||||||
|
|
||||||
|
### 1. Hierarchisches Prompt-Resolution-System
|
||||||
|
|
||||||
|
**Implementierung (`app/services/llm_service.py` v3.5.5):**
|
||||||
|
|
||||||
|
Dreistufige Auflösungs-Logik für maximale Präzision und Resilienz:
|
||||||
|
|
||||||
|
1. **Level 1 (Modell-ID):** Exakte Übereinstimmung für spezifische Modelle
|
||||||
|
* **Beispiel:** `google/gemini-2.0-flash-exp:free`, `meta-llama/llama-3.3-70b-instruct:free`
|
||||||
|
* **Vorteil:** Modell-spezifische Optimierungen für maximale Präzision
|
||||||
|
* **Logging:** `🎯 [PROMPT-TRACE] Level 1 Match: Model-specific`
|
||||||
|
|
||||||
|
2. **Level 2 (Provider):** Fallback auf Provider-Standards
|
||||||
|
* **Beispiel:** `openrouter`, `ollama`, `gemini`
|
||||||
|
* **Vorteil:** Bewährte Standards aus v3.1.2 bleiben erhalten
|
||||||
|
* **Logging:** `📡 [PROMPT-TRACE] Level 2 Match: Provider-fallback`
|
||||||
|
|
||||||
|
3. **Level 3 (Default):** Globaler Sicherheits-Satz
|
||||||
|
* **Fallback-Kette:** `default` → `gemini` → `ollama` → `""`
|
||||||
|
* **Vorteil:** Vermeidung von Fehlern bei unbekannten Konfigurationen
|
||||||
|
* **Logging:** `⚓ [PROMPT-TRACE] Level 3 Match: Global Default`
|
||||||
|
|
||||||
|
**Vorteile:**
|
||||||
|
* **Modell-spezifisches Tuning:** Jedes Modell kann optimierte Prompts erhalten
|
||||||
|
* **Maximale Resilienz:** Bei Modell-Fallbacks wird automatisch das passende Template geladen
|
||||||
|
* **Traceability:** Vollständige Transparenz über genutzte Instruktionen
|
||||||
|
|
||||||
|
### 2. Lazy-Prompt-Orchestration
|
||||||
|
|
||||||
|
**Implementierung (`app/services/llm_service.py` v3.5.5):**
|
||||||
|
|
||||||
|
* **Lazy Loading:** Prompts werden erst zur Laufzeit geladen, wenn das aktive Modell bekannt ist
|
||||||
|
* **Parameter:** `prompt_key` und `variables` statt vorformatierter Strings
|
||||||
|
* **Integration:** Vollständig in Chat, Ingestion und DecisionEngine integriert
|
||||||
|
|
||||||
|
**Vorteile:**
|
||||||
|
* **Dynamische Anpassung:** Prompt wird basierend auf aktivem Modell geladen
|
||||||
|
* **Fallback-Resilienz:** Bei Cloud → Local Fallback wird automatisch das passende Template verwendet
|
||||||
|
* **Wartbarkeit:** Zentrale Konfiguration in `prompts.yaml` statt verstreuter String-Formatierungen
|
||||||
|
|
||||||
|
### 3. Ultra-robustes Intent-Parsing
|
||||||
|
|
||||||
|
**Implementierung (`app/core/retrieval/decision_engine.py` v1.3.2):**
|
||||||
|
|
||||||
|
* **Regex-basierter Parser:** Bereinigt Modell-Artefakte zuverlässig
|
||||||
|
* **Beispiele:** `CODING[/S]` → `CODING`, `DECISION</s>` → `DECISION`
|
||||||
|
* **Robustheit:** Ignoriert Stop-Marker, Newlines oder Plaudereien des Modells
|
||||||
|
|
||||||
|
**Vorteile:**
|
||||||
|
* **Präzises Routing:** Strategie-Erkennung funktioniert auch bei freien Modellen mit Artefakten
|
||||||
|
* **Fehlerresistenz:** Systemabstürze durch fehlerhafte Modell-Antworten werden verhindert
|
||||||
|
|
||||||
|
### 4. Differenzierte Ingestion-Validierung
|
||||||
|
|
||||||
|
**Implementierung (`app/core/ingestion/ingestion_validation.py` v2.14.0):**
|
||||||
|
|
||||||
|
* **Fehler-Differenzierung:** Unterscheidung zwischen transienten und permanenten Fehlern
|
||||||
|
* **Transiente Fehler:** Timeout, Connection, Network → Kante wird erlaubt (Datenverlust vermeiden)
|
||||||
|
* **Permanente Fehler:** Config, Validation, Invalid Response → Kante wird abgelehnt (Graph-Qualität schützen)
|
||||||
|
|
||||||
|
**Vorteile:**
|
||||||
|
* **Datenintegrität:** Transiente Netzwerkfehler führen nicht zu Datenverlust
|
||||||
|
* **Graph-Qualität:** Permanente Konfigurationsfehler schützen vor fehlerhaften Kanten
|
||||||
|
|
||||||
|
### 5. PROMPT-TRACE Logging
|
||||||
|
|
||||||
|
**Implementierung (`app/services/llm_service.py` v3.5.5):**
|
||||||
|
|
||||||
|
* **Vollständige Transparenz:** Protokollierung der genutzten Prompt-Auflösungs-Ebene
|
||||||
|
* **Log-Format:** `[PROMPT-TRACE] Level X Match: ...`
|
||||||
|
* **Debugging:** Einfache Nachverfolgung von Prompt-Entscheidungen
|
||||||
|
|
||||||
|
**Vorteile:**
|
||||||
|
* **Debugging:** Schnelle Identifikation von Prompt-Problemen
|
||||||
|
* **Optimierung:** Verständnis, welche Prompts tatsächlich genutzt werden
|
||||||
|
* **Audit:** Vollständige Nachvollziehbarkeit der System-Entscheidungen
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🔧 Technische Änderungen
|
||||||
|
|
||||||
|
### Konfigurationsdateien
|
||||||
|
|
||||||
|
**Aktualisierte Dateien:**
|
||||||
|
* `config/prompts.yaml` v3.2.2: Hierarchische Struktur mit Modell-spezifischen Overrides
|
||||||
|
* **Erhalt:** 100% der Original-Prompts aus v3.1.2 für die Provider-Ebene
|
||||||
|
* **Neu:** Modell-spezifische Overrides für Gemini 2.0, Llama 3.3, Qwen 2.5
|
||||||
|
* **Neu:** `compression_template` für DecisionEngine v1.3.0
|
||||||
|
|
||||||
|
### Code-Komponenten
|
||||||
|
|
||||||
|
| Komponente | Version | Änderungen |
|
||||||
|
| :--- | :--- | :--- |
|
||||||
|
| `app/services/llm_service.py` | v3.5.5 | Hierarchische Prompt-Resolution, Lazy-Loading, PROMPT-TRACE |
|
||||||
|
| `app/core/retrieval/decision_engine.py` | v1.3.2 | Ultra-robustes Intent-Parsing via Regex |
|
||||||
|
| `app/core/ingestion/ingestion_validation.py` | v2.14.0 | Lazy-Prompt-Integration, differenzierte Fehlerbehandlung |
|
||||||
|
| `app/routers/chat.py` | v3.0.3 | Lazy-Prompt-Loading für Chat-Synthese |
|
||||||
|
|
||||||
|
### API-Änderungen
|
||||||
|
|
||||||
|
**Neue Parameter:**
|
||||||
|
* `prompt_key`: Schlüssel für Lazy-Loading (statt vorformatierter Strings)
|
||||||
|
* `variables`: Daten-Dict für Prompt-Formatierung
|
||||||
|
|
||||||
|
**Veraltete Parameter:**
|
||||||
|
* Vorformatierte `prompt` Strings werden weiterhin unterstützt (Abwärtskompatibilität)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🐛 Behobene Probleme
|
||||||
|
|
||||||
|
- ✅ **Behoben:** Modell-Artefakte in Intent-Router (z.B. `CODING[/S]` → `CODING`)
|
||||||
|
- ✅ **Behoben:** Fehlende modell-spezifische Prompt-Optimierungen
|
||||||
|
- ✅ **Behoben:** Fehlerhafte Prompt-Auflösung bei Modell-Fallbacks
|
||||||
|
- ✅ **Behoben:** Undifferenzierte Fehlerbehandlung in Ingestion-Validierung
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📚 Dokumentation
|
||||||
|
|
||||||
|
**Aktualisierte Dokumente:**
|
||||||
|
- ✅ `03_tech_chat_backend.md`: Hierarchisches Prompt-Resolution-System und Lazy-Prompt-Orchestration
|
||||||
|
- ✅ `03_tech_configuration.md`: prompts.yaml hierarchische Struktur dokumentiert
|
||||||
|
- ✅ `02_concept_ai_personality.md`: Lazy-Prompt-Orchestration Konzept
|
||||||
|
- ✅ `03_tech_ingestion_pipeline.md`: Differenzierte Validierung
|
||||||
|
- ✅ `00_glossary.md`: Neue Begriffe (Lazy-Prompt, PROMPT-TRACE, hierarchische Resolution)
|
||||||
|
- ✅ `05_developer_guide.md`: Lazy-Prompt-Orchestration für Entwickler
|
||||||
|
- ✅ `06_active_roadmap.md`: WP25b als abgeschlossen markiert
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🚀 Migration & Upgrade
|
||||||
|
|
||||||
|
### Für Administratoren
|
||||||
|
|
||||||
|
1. **Keine Breaking Changes:**
|
||||||
|
* Vorformatierte Prompts werden weiterhin unterstützt
|
||||||
|
* System funktioniert ohne Änderungen
|
||||||
|
|
||||||
|
2. **Optional: Modell-spezifische Optimierungen:**
|
||||||
|
```yaml
|
||||||
|
# config/prompts.yaml
|
||||||
|
decision_synthesis_v1:
|
||||||
|
"google/gemini-2.0-flash-exp:free": |
|
||||||
|
# Modell-spezifische Optimierung
|
||||||
|
...
|
||||||
|
```
|
||||||
|
|
||||||
|
3. **PROMPT-TRACE aktivieren:**
|
||||||
|
* Logs zeigen automatisch die genutzte Auflösungs-Ebene
|
||||||
|
* Keine zusätzliche Konfiguration erforderlich
|
||||||
|
|
||||||
|
### Für Entwickler
|
||||||
|
|
||||||
|
**API-Änderungen:**
|
||||||
|
* `LLMService.generate_raw_response()` unterstützt nun `prompt_key` und `variables`
|
||||||
|
* Vorformatierte `prompt` Strings bleiben für Abwärtskompatibilität erhalten
|
||||||
|
|
||||||
|
**Best Practice:**
|
||||||
|
* Nutze `prompt_key` und `variables` für neue Implementierungen
|
||||||
|
* Lazy-Loading ermöglicht automatische Modell-Anpassung
|
||||||
|
|
||||||
|
**Konfiguration:**
|
||||||
|
* Neue Modell-spezifische Prompts können in `prompts.yaml` definiert werden
|
||||||
|
* Hierarchische Struktur: Modell-ID → Provider → Default
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🔮 Ausblick (WP-25c)
|
||||||
|
|
||||||
|
- Kontext-Budgeting: Intelligente Token-Verteilung
|
||||||
|
- Stream-specific Provider: Unterschiedliche KI-Modelle pro Wissensbereich
|
||||||
|
- Erweiterte Prompt-Optimierung: Dynamische Anpassung basierend auf Kontext und Historie
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📊 Metriken & Performance
|
||||||
|
|
||||||
|
**Erwartete Verbesserungen:**
|
||||||
|
* **Präzision:** Modell-spezifische Prompts erhöhen Antwortqualität
|
||||||
|
* **Resilienz:** Automatische Prompt-Anpassung bei Modell-Fallbacks
|
||||||
|
* **Debugging:** PROMPT-TRACE vereinfacht Fehleranalyse
|
||||||
|
* **Wartbarkeit:** Zentrale Prompt-Konfiguration statt verstreuter Strings
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**Status:** ✅ WP-25b ist zu 100% implementiert und audit-geprüft.
|
||||||
|
**Nächster Schritt:** WP-25c (Kontext-Budgeting & Erweiterte Prompt-Optimierung).
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
# Branch Merge Commit Message: WP4d
|
||||||
|
|
||||||
|
```
|
||||||
|
feat: Section-basierte Links, Atomic Section Chunking & Registry-First Profiling (v2.9.1)
|
||||||
|
|
||||||
|
## Graph Topology & Edge Management
|
||||||
|
|
||||||
|
### Section-basierte Links (Multigraph-Support)
|
||||||
|
- Split `[[Note#Section]]` Links in `target_id="Note"` und `target_section="Section"`
|
||||||
|
- Edge-ID enthält nun `variant` (Section), ermöglicht mehrere Kanten zwischen denselben Knoten
|
||||||
|
- Semantische Deduplizierung basiert auf `src->tgt:kind@sec` Key
|
||||||
|
- Behebt "Phantom-Knoten" durch korrekte Trennung von Note-Name und Abschnitt
|
||||||
|
|
||||||
|
**Geänderte Dateien:**
|
||||||
|
- `app/core/graph/graph_utils.py`: `parse_link_target()` für Section-Extraktion
|
||||||
|
- `app/core/graph/graph_derive_edges.py`: `target_section` in Edge-Payload
|
||||||
|
- `app/core/database/qdrant.py`: Keyword-Index für `target_section`
|
||||||
|
- `app/core/database/qdrant_points.py`: Explizites Durchreichen von `target_section`
|
||||||
|
- `app/models/dto.py`: `EdgeDTO` mit `target_section` Feld
|
||||||
|
|
||||||
|
### Extraction & Parsing Verbesserungen
|
||||||
|
- Multi-line Callout-Blocks korrekt verarbeitet (stop-check logic)
|
||||||
|
- Robuster Fallback für "headless" Blocks (split chunks)
|
||||||
|
- Liberalisierte Regex für Umlaute und Sonderzeichen in Targets
|
||||||
|
|
||||||
|
**Geänderte Dateien:**
|
||||||
|
- `app/core/graph/graph_extractors.py`: Multi-line Callout-Parser, erweiterte Regex
|
||||||
|
|
||||||
|
## Chunking & Ingestion (v3.9.9 / v2.13.12)
|
||||||
|
|
||||||
|
### Atomic Section Logic (v3.9.9)
|
||||||
|
- Vollständige Implementierung des "Pack-and-Carry-Over" Verfahrens (Regel 1-3)
|
||||||
|
- Sektions-Überschriften und Inhalte bleiben atomar in Chunks
|
||||||
|
- H1-Context Preservation: Dokumenttitel als Breadcrumb in Embedding-Fenster
|
||||||
|
- Signature Alignment: Parameter-Synchronisierung (`context_prefix` statt `doc_title`)
|
||||||
|
|
||||||
|
**Geänderte Dateien:**
|
||||||
|
- `app/core/chunking/chunking_strategies.py`: Atomic Section Logic implementiert
|
||||||
|
|
||||||
|
### Format-agnostische De-Duplizierung
|
||||||
|
- Prüfung auf vorhandene Kanten basiert auf Ziel (`target`), nicht String-Match
|
||||||
|
- Verhindert Dopplung von Kanten, die bereits via `[!edge]` Callout vorhanden sind
|
||||||
|
- Global Pool Integration für unzugeordnete Kanten
|
||||||
|
|
||||||
|
**Geänderte Dateien:**
|
||||||
|
- `app/core/chunking/chunking_propagation.py`: Ziel-basierte Prüfung
|
||||||
|
|
||||||
|
### Registry-First Profiling (v2.13.12)
|
||||||
|
- Korrekte Hierarchie: Frontmatter > types.yaml Typ-Config > Global Defaults
|
||||||
|
- Hard-Fallback auf `sliding_standard` nur wenn keine Konfiguration existiert
|
||||||
|
- Automatische Anwendung korrekter Profile basierend auf Note-Typ
|
||||||
|
|
||||||
|
### Deterministic Hashing
|
||||||
|
- `full`-Hash inkludiert strategische Parameter (`split_level`, `strict_heading_split`)
|
||||||
|
- Konfigurationsänderungen im Frontmatter lösen zwingend Re-Import aus
|
||||||
|
|
||||||
|
**Geänderte Dateien:**
|
||||||
|
- `app/core/ingestion/ingestion_processor.py`: Registry-First Profiling, Deterministic Hashing
|
||||||
|
|
||||||
|
## Impact & Breaking Changes
|
||||||
|
|
||||||
|
### Migration erforderlich
|
||||||
|
**WICHTIG:** Vollständiger Re-Import erforderlich für bestehende Vaults:
|
||||||
|
```bash
|
||||||
|
python3 -m scripts.import_markdown --vault ./vault --prefix "mindnet" --apply --force
|
||||||
|
```
|
||||||
|
|
||||||
|
**Grund:**
|
||||||
|
- Behebt "Phantom-Knoten" durch korrekte Aufteilung von `[[Note#Section]]` Links
|
||||||
|
- Konsolidiert Edge-Struktur mit `target_section` Feld
|
||||||
|
- Aktualisiert Chunking basierend auf neuen Strategien
|
||||||
|
|
||||||
|
### Fixes
|
||||||
|
- ✅ Resolves: Mehrere Links zur gleichen Note in einem Callout-Block wurden zu einer Kante gemergt
|
||||||
|
- ✅ Resolves: "Phantom-Knoten" durch Einbeziehung des Anchors in `target_id`
|
||||||
|
- ✅ Resolves: Redundante `[[rel:...]]` Links in Chunks
|
||||||
|
- ✅ Resolves: Inkonsistente Metadaten in Qdrant durch Registry-First Profiling
|
||||||
|
|
||||||
|
## Dokumentation
|
||||||
|
|
||||||
|
Alle relevanten Dokumente aktualisiert:
|
||||||
|
- `03_tech_data_model.md`: Edge Payload Schema mit `target_section`
|
||||||
|
- `02_concept_graph_logic.md`: Section-basierte Links & Multigraph-Support
|
||||||
|
- `03_tech_ingestion_pipeline.md`: Chunking-Strategien, Registry-First Profiling
|
||||||
|
- `03_tech_api_reference.md`: EdgeDTO mit `target_section`
|
||||||
|
- `01_knowledge_design.md`: Deep-Links dokumentiert
|
||||||
|
- `00_glossary.md`: Neue Begriffe ergänzt
|
||||||
|
- `04_admin_operations.md`: Migration-Hinweis
|
||||||
|
|
||||||
|
## Versionen
|
||||||
|
|
||||||
|
- Graph Topology: v2.9.1
|
||||||
|
- Chunking Strategies: v3.9.9
|
||||||
|
- Ingestion Processor: v2.13.12
|
||||||
|
- API DTO: v0.6.7
|
||||||
|
|
||||||
|
Closes #[issue-number]
|
||||||
|
```
|
||||||
|
|
||||||
@@ -0,0 +1,236 @@
|
|||||||
|
# Release Notes: Mindnet v2.9.1 (WP4d)
|
||||||
|
|
||||||
|
**Release Date:** 2025-01-XX
|
||||||
|
**Type:** Feature Release mit Breaking Changes
|
||||||
|
**Branch:** WP4d
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🎯 Übersicht
|
||||||
|
|
||||||
|
Diese Version führt **Section-basierte Links** ein, verbessert das Chunking durch **Atomic Section Logic** und implementiert **Registry-First Profiling** für konsistentere Konfigurationsauflösung. Die Änderungen erfordern einen **vollständigen Re-Import** bestehender Vaults.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## ✨ Neue Features
|
||||||
|
|
||||||
|
### Section-basierte Links (Deep-Links)
|
||||||
|
|
||||||
|
Mindnet unterstützt nun **Deep-Links** zu spezifischen Abschnitten innerhalb einer Note:
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
[[rel:based_on Mein Leitbild#P3 – Disziplin]]
|
||||||
|
```
|
||||||
|
|
||||||
|
**Vorteile:**
|
||||||
|
- Mehrere Links zur gleichen Note möglich (verschiedene Sections)
|
||||||
|
- Präzise Kontext-Ladung (nur relevanter Abschnitt)
|
||||||
|
- Keine "Phantom-Knoten" mehr durch korrekte Trennung von Note-Name und Abschnitt
|
||||||
|
|
||||||
|
**Technische Details:**
|
||||||
|
- Links werden in `target_id="Note"` und `target_section="Section"` aufgeteilt
|
||||||
|
- Edge-ID enthält `variant` (Section) für Multigraph-Support
|
||||||
|
- Semantische Deduplizierung basiert auf `src->tgt:kind@sec` Key
|
||||||
|
|
||||||
|
### Atomic Section Logic (Chunking v3.9.9)
|
||||||
|
|
||||||
|
Das Chunking hält nun Sektions-Überschriften und deren Inhalte **atomar** zusammen:
|
||||||
|
|
||||||
|
**"Pack-and-Carry-Over" Verfahren:**
|
||||||
|
- Regel 1 & 2: Sektionen werden zusammengepackt, wenn sie in den Token-Limit passen
|
||||||
|
- Regel 3: Zu große Sektionen werden intelligent zerlegt, Rest wird zurück in Queue gelegt
|
||||||
|
- H1-Context Preservation: Dokumenttitel wird als Breadcrumb in alle Chunks injiziert
|
||||||
|
|
||||||
|
**Vorteile:**
|
||||||
|
- Keine getrennten Überschriften mehr
|
||||||
|
- Bessere semantische Kohärenz in Chunks
|
||||||
|
- Verbesserte Retrieval-Qualität durch vollständigen Kontext
|
||||||
|
|
||||||
|
### Registry-First Profiling (v2.13.12)
|
||||||
|
|
||||||
|
Die Konfigurationsauflösung folgt nun einer klaren Hierarchie:
|
||||||
|
|
||||||
|
1. **Frontmatter** (höchste Priorität)
|
||||||
|
2. **types.yaml Typ-Config**
|
||||||
|
3. **Global Defaults**
|
||||||
|
|
||||||
|
**Impact:**
|
||||||
|
- Note-Typen wie `value` erhalten automatisch das korrekte Profil (`structured_smart_edges_strict`)
|
||||||
|
- Keine manuellen Overrides mehr nötig für Standard-Typen
|
||||||
|
- Konsistente Metadaten in Qdrant
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🔧 Verbesserungen
|
||||||
|
|
||||||
|
### Extraction & Parsing
|
||||||
|
|
||||||
|
- **Multi-line Callout-Blocks:** Korrekte Verarbeitung von mehrzeiligen `[!edge]` Callouts
|
||||||
|
- **Robuste Fallbacks:** "Headless" Blocks werden korrekt behandelt
|
||||||
|
- **Liberalisierte Regex:** Unterstützung für Umlaute und Sonderzeichen in Link-Targets
|
||||||
|
|
||||||
|
### Format-agnostische De-Duplizierung
|
||||||
|
|
||||||
|
- Kanten werden unabhängig vom Format (Inline, Callout, Wikilink) erkannt
|
||||||
|
- Verhindert Dopplungen, wenn Kanten bereits via `[!edge]` Callout vorhanden sind
|
||||||
|
- Ziel-basierte Prüfung statt String-Match
|
||||||
|
|
||||||
|
### Deterministic Hashing
|
||||||
|
|
||||||
|
- `full`-Hash inkludiert strategische Parameter (`split_level`, `strict_heading_split`)
|
||||||
|
- Konfigurationsänderungen im Frontmatter lösen zwingend Re-Import aus
|
||||||
|
- Zuverlässigere Change Detection
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🐛 Bugfixes
|
||||||
|
|
||||||
|
- ✅ **Behoben:** Mehrere Links zur gleichen Note in einem Callout-Block wurden zu einer Kante gemergt
|
||||||
|
- ✅ **Behoben:** "Phantom-Knoten" durch Einbeziehung des Anchors in `target_id`
|
||||||
|
- ✅ **Behoben:** Redundante `[[rel:...]]` Links in Chunks
|
||||||
|
- ✅ **Behoben:** Inkonsistente Metadaten in Qdrant durch fehlerhafte Profil-Auflösung
|
||||||
|
- ✅ **Behoben:** `TypeError` durch Parameter-Mismatch zwischen Orchestrator und Strategien
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## ⚠️ Breaking Changes & Migration
|
||||||
|
|
||||||
|
### Migration erforderlich
|
||||||
|
|
||||||
|
**WICHTIG:** Nach dem Update auf v2.9.1 ist ein **vollständiger Re-Import** erforderlich:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python3 -m scripts.import_markdown --vault ./vault --prefix "mindnet" --apply --force
|
||||||
|
```
|
||||||
|
|
||||||
|
**Warum?**
|
||||||
|
- Behebt "Phantom-Knoten" durch korrekte Aufteilung von `[[Note#Section]]` Links
|
||||||
|
- Konsolidiert Edge-Struktur mit neuem `target_section` Feld
|
||||||
|
- Aktualisiert Chunking basierend auf Atomic Section Logic
|
||||||
|
|
||||||
|
**Was passiert beim Re-Import?**
|
||||||
|
- Alle bestehenden Links werden neu geparst und in `target_id` + `target_section` aufgeteilt
|
||||||
|
- Chunks werden mit neuer Atomic Section Logic neu generiert
|
||||||
|
- Edge-Struktur wird konsolidiert (Multigraph-Support)
|
||||||
|
|
||||||
|
**Dauer:** Abhängig von Vault-Größe (typischerweise 5-30 Minuten)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📚 API-Änderungen
|
||||||
|
|
||||||
|
### EdgeDTO erweitert
|
||||||
|
|
||||||
|
```python
|
||||||
|
class EdgeDTO(BaseModel):
|
||||||
|
# ... bestehende Felder ...
|
||||||
|
target_section: Optional[str] = None # Neu: Abschnitts-Name
|
||||||
|
```
|
||||||
|
|
||||||
|
**Impact für API-Consumer:**
|
||||||
|
- Graph-Endpunkte (`/graph/{note_id}`) enthalten nun `target_section` in Edge-Objekten
|
||||||
|
- Frontend kann Section-Informationen für präzisere Visualisierung nutzen
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📖 Dokumentation
|
||||||
|
|
||||||
|
Alle relevanten Dokumente wurden aktualisiert:
|
||||||
|
|
||||||
|
- ✅ `03_tech_data_model.md`: Edge Payload Schema mit `target_section`
|
||||||
|
- ✅ `02_concept_graph_logic.md`: Section-basierte Links & Multigraph-Support
|
||||||
|
- ✅ `03_tech_ingestion_pipeline.md`: Chunking-Strategien, Registry-First Profiling
|
||||||
|
- ✅ `03_tech_api_reference.md`: EdgeDTO mit `target_section`
|
||||||
|
- ✅ `01_knowledge_design.md`: Deep-Links dokumentiert
|
||||||
|
- ✅ `00_glossary.md`: Neue Begriffe ergänzt
|
||||||
|
- ✅ `04_admin_operations.md`: Migration-Hinweis
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🔄 Technische Details
|
||||||
|
|
||||||
|
### Geänderte Module
|
||||||
|
|
||||||
|
**Graph Topology:**
|
||||||
|
- `app/core/graph/graph_utils.py`: `parse_link_target()` für Section-Extraktion
|
||||||
|
- `app/core/graph/graph_derive_edges.py`: `target_section` in Edge-Payload
|
||||||
|
- `app/core/graph/graph_extractors.py`: Multi-line Callout-Parser
|
||||||
|
|
||||||
|
**Chunking:**
|
||||||
|
- `app/core/chunking/chunking_strategies.py`: Atomic Section Logic (v3.9.9)
|
||||||
|
- `app/core/chunking/chunking_propagation.py`: Format-agnostische De-Duplizierung
|
||||||
|
|
||||||
|
**Ingestion:**
|
||||||
|
- `app/core/ingestion/ingestion_processor.py`: Registry-First Profiling (v2.13.12), Deterministic Hashing
|
||||||
|
|
||||||
|
**Database:**
|
||||||
|
- `app/core/database/qdrant.py`: Keyword-Index für `target_section`
|
||||||
|
- `app/core/database/qdrant_points.py`: Explizites Durchreichen von `target_section`
|
||||||
|
|
||||||
|
**API:**
|
||||||
|
- `app/models/dto.py`: `EdgeDTO` mit `target_section` Feld (v0.6.7)
|
||||||
|
|
||||||
|
### Versionsnummern
|
||||||
|
|
||||||
|
- Graph Topology: **v2.9.1**
|
||||||
|
- Chunking Strategies: **v3.9.9**
|
||||||
|
- Ingestion Processor: **v2.13.12**
|
||||||
|
- API DTO: **v0.6.7**
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🚀 Upgrade-Pfad
|
||||||
|
|
||||||
|
### Für Administratoren
|
||||||
|
|
||||||
|
1. **Backup erstellen:**
|
||||||
|
```bash
|
||||||
|
docker stop qdrant
|
||||||
|
tar -czf qdrant_backup_$(date +%F).tar.gz ./qdrant_data
|
||||||
|
docker start qdrant
|
||||||
|
```
|
||||||
|
|
||||||
|
2. **Code aktualisieren:**
|
||||||
|
```bash
|
||||||
|
git pull origin main
|
||||||
|
source .venv/bin/activate
|
||||||
|
pip install -r requirements.txt
|
||||||
|
```
|
||||||
|
|
||||||
|
3. **Re-Import durchführen:**
|
||||||
|
```bash
|
||||||
|
python3 -m scripts.import_markdown --vault ./vault --prefix "mindnet" --apply --force
|
||||||
|
```
|
||||||
|
|
||||||
|
4. **Services neu starten:**
|
||||||
|
```bash
|
||||||
|
sudo systemctl restart mindnet-prod
|
||||||
|
sudo systemctl restart mindnet-ui-prod
|
||||||
|
```
|
||||||
|
|
||||||
|
### Für Entwickler
|
||||||
|
|
||||||
|
- Keine Code-Änderungen erforderlich, wenn nur API genutzt wird
|
||||||
|
- Frontend kann `target_section` Feld in Edge-Objekten nutzen (optional)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📝 Bekannte Einschränkungen
|
||||||
|
|
||||||
|
- **Migration-Dauer:** Große Vaults (>10.000 Notizen) können 30+ Minuten benötigen
|
||||||
|
- **Temporärer Speicher:** Während des Re-Imports kann Qdrant-Speicher temporär ansteigen
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🙏 Danksagungen
|
||||||
|
|
||||||
|
Diese Version wurde durch umfangreiche Code-Analyse und Dokumentationsprüfung ermöglicht. Besonderer Fokus lag auf:
|
||||||
|
- Konsistenz zwischen Code und Dokumentation
|
||||||
|
- Vollständige Abdeckung aller Rollen (Entwickler, Administratoren, Anwender, Tester, Deployment)
|
||||||
|
- Klare Migration-Pfade
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**Vollständige Changelog:** Siehe Git-Commits für detaillierte Änderungen
|
||||||
|
**Support:** Bei Fragen zur Migration siehe [Admin Operations Guide](../04_Operations/04_admin_operations.md)
|
||||||
|
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
# Audit: LLM-Profilsteuerung Integration (WP-25a)
|
||||||
|
|
||||||
|
**Datum:** 2025-01-XX
|
||||||
|
**Version:** WP-25a
|
||||||
|
**Status:** ✅ Abgeschlossen mit Verbesserungen
|
||||||
|
|
||||||
|
## Zusammenfassung
|
||||||
|
|
||||||
|
Dieses Audit prüft die Vollständigkeit der neuen LLM-Profilsteuerung (MoE - Mixture of Experts) und identifiziert alle Stellen, die die zentrale Steuerung umgehen könnten.
|
||||||
|
|
||||||
|
## Gefundene Probleme & Lösungen
|
||||||
|
|
||||||
|
### ✅ Problem 1: Fehlendes `profile_name` im Fallback-Code
|
||||||
|
**Datei:** `app/core/retrieval/decision_engine.py` (Zeile 253-255)
|
||||||
|
**Problem:** Der Fallback-Aufruf in `_generate_final_answer` nutzte kein `profile_name`, wodurch die Profilsteuerung umgangen wurde.
|
||||||
|
**Lösung:** ✅ Behoben - Nutzt nun `profile_name=profile` für Konsistenz.
|
||||||
|
|
||||||
|
### ⚠️ Problem 2: Ungenutztes Profil `ingest_extractor`
|
||||||
|
**Datei:** `config/llm_profiles.yaml`
|
||||||
|
**Problem:** Das Profil `ingest_extractor` ist definiert, wird aber nirgendwo im Code verwendet.
|
||||||
|
**Status:** ⚠️ Offene Lücke - Profil ist für zukünftige Extraktions-Aufgaben vorgesehen, aktuell nicht benötigt.
|
||||||
|
|
||||||
|
### ✅ Problem 3: Externes Script umgeht Steuerung
|
||||||
|
**Datei:** `scripts/ollama_tool_runner.py`
|
||||||
|
**Problem:** Script macht direkte Ollama-Aufrufe ohne LLMService.
|
||||||
|
**Status:** ✅ Akzeptabel - Dies ist ein externes Test-/Demo-Script, kein Teil der Hauptanwendung.
|
||||||
|
|
||||||
|
## Vollständige Prüfung aller LLM-Aufrufe
|
||||||
|
|
||||||
|
### ✅ Korrekt implementiert (nutzen Profilsteuerung):
|
||||||
|
|
||||||
|
1. **`app/core/ingestion/ingestion_validation.py`**
|
||||||
|
- ✅ Nutzt `profile_name="ingest_validator"` (Zeile 61-64)
|
||||||
|
- ✅ Delegiert Fallback-Kaskade an LLMService
|
||||||
|
|
||||||
|
2. **`app/core/retrieval/decision_engine.py`**
|
||||||
|
- ✅ `_determine_strategy()`: Nutzt `router_profile` (Zeile 94-96)
|
||||||
|
- ✅ `_compress_stream_content()`: Nutzt `compression_profile` (Zeile 169-174)
|
||||||
|
- ✅ `_generate_final_answer()`: Nutzt `llm_profile` aus Strategie (Zeile 244-246)
|
||||||
|
- ✅ **BEHOBEN:** Fallback nutzt nun auch `profile_name` (Zeile 253-256)
|
||||||
|
|
||||||
|
3. **`app/routers/chat.py`**
|
||||||
|
- ✅ Interview-Modus: Nutzt `profile_name="compression_fast"` (Zeile 204-207)
|
||||||
|
- ✅ RAG-Modus: Delegiert an DecisionEngine (nutzt Strategie-Profile)
|
||||||
|
|
||||||
|
4. **`app/services/embeddings_client.py`**
|
||||||
|
- ✅ Nutzt `embedding_expert` Profil aus `llm_profiles.yaml` (Zeile 29-47)
|
||||||
|
- ✅ Konsistente Modellsteuerung für Embeddings
|
||||||
|
|
||||||
|
5. **`app/services/llm_service.py`**
|
||||||
|
- ✅ Zentrale Implementierung der Profilsteuerung
|
||||||
|
- ✅ Rekursive Fallback-Kaskade implementiert
|
||||||
|
- ✅ Schutz gegen zirkuläre Referenzen (`visited_profiles`)
|
||||||
|
|
||||||
|
### ✅ Keine LLM-Aufrufe (korrekt):
|
||||||
|
|
||||||
|
1. **`app/routers/ingest.py`**
|
||||||
|
- Nutzt nur IngestionService (der wiederum LLMService nutzt)
|
||||||
|
|
||||||
|
2. **`app/services/discovery.py`**
|
||||||
|
- Nutzt nur Retrieval, keine LLM-Aufrufe
|
||||||
|
|
||||||
|
3. **`app/frontend/ui_api.py`**
|
||||||
|
- Macht nur HTTP-Requests zu API-Endpunkten
|
||||||
|
|
||||||
|
## Konfigurationsprüfung
|
||||||
|
|
||||||
|
### ✅ `config/llm_profiles.yaml`
|
||||||
|
- ✅ Alle benötigten Profile definiert:
|
||||||
|
- `synthesis_pro` - Hauptsynthese
|
||||||
|
- `synthesis_backup` - Backup-Synthese
|
||||||
|
- `tech_expert` - Code/Technik
|
||||||
|
- `compression_fast` - Kompression/Routing
|
||||||
|
- `ingest_validator` - Validierung (YES/NO)
|
||||||
|
- `ingest_extractor` - Extraktion (aktuell ungenutzt)
|
||||||
|
- `identity_safe` - Lokaler Privacy-Anker
|
||||||
|
- `embedding_expert` - Embeddings
|
||||||
|
- ✅ Fallback-Kaskaden korrekt definiert
|
||||||
|
- ✅ Temperaturen angemessen gesetzt
|
||||||
|
|
||||||
|
### ✅ `config/decision_engine.yaml`
|
||||||
|
- ✅ Nutzt `router_profile` für Intent-Erkennung
|
||||||
|
- ✅ Strategien referenzieren `llm_profile`
|
||||||
|
- ✅ Streams nutzen `compression_profile`
|
||||||
|
|
||||||
|
## Empfehlungen
|
||||||
|
|
||||||
|
### Sofort umsetzbar:
|
||||||
|
1. ✅ **BEHOBEN:** Fallback in DecisionEngine nutzt nun Profilsteuerung
|
||||||
|
|
||||||
|
### Zukünftige Verbesserungen:
|
||||||
|
1. **`ingest_extractor` Profil:** Wenn Extraktions-Aufgaben hinzukommen, sollte dieses Profil genutzt werden
|
||||||
|
2. **Monitoring:** Logging erweitern, um Profil-Nutzung zu tracken
|
||||||
|
3. **Dokumentation:** Profil-Auswahl-Logik in Entwickler-Dokumentation aufnehmen
|
||||||
|
|
||||||
|
## Fazit
|
||||||
|
|
||||||
|
✅ **Die LLM-Profilsteuerung ist vollständig integriert.**
|
||||||
|
✅ **Alle kritischen LLM-Aufrufe nutzen die zentrale Steuerung.**
|
||||||
|
✅ **Ein kleiner Bug wurde behoben (Fallback ohne Profil).**
|
||||||
|
⚠️ **Ein Profil (`ingest_extractor`) ist definiert, aber aktuell ungenutzt - dies ist akzeptabel für zukünftige Features.**
|
||||||
|
|
||||||
|
Die Architektur ist robust und folgt dem MoE-Prinzip konsequent.
|
||||||
Loaded 100 of 157 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user