Compare commits
52
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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 |
No files matched your search
+50
-13
@@ -1,40 +1,76 @@
|
||||
"""
|
||||
FILE: app/config.py
|
||||
DESCRIPTION: Zentrale Pydantic-Konfiguration (Env-Vars für Qdrant, LLM, Retriever).
|
||||
VERSION: 0.4.0
|
||||
DESCRIPTION: Zentrale Pydantic-Konfiguration.
|
||||
WP-20: Hybrid-Cloud Modus Support (OpenRouter/Gemini/Ollama).
|
||||
FIX: Einführung von Parametern zur intelligenten Rate-Limit Steuerung (429 Handling).
|
||||
VERSION: 0.6.7
|
||||
STATUS: Active
|
||||
DEPENDENCIES: os, functools, pathlib
|
||||
LAST_ANALYSIS: 2025-12-15
|
||||
DEPENDENCIES: os, functools, pathlib, python-dotenv
|
||||
"""
|
||||
from __future__ import annotations
|
||||
import os
|
||||
from functools import lru_cache
|
||||
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:
|
||||
# Qdrant
|
||||
# --- Qdrant Datenbank ---
|
||||
QDRANT_URL: str = os.getenv("QDRANT_URL", "http://127.0.0.1:6333")
|
||||
QDRANT_API_KEY: str | None = os.getenv("QDRANT_API_KEY")
|
||||
COLLECTION_PREFIX: str = os.getenv("MINDNET_PREFIX", "mindnet")
|
||||
VECTOR_SIZE: int = int(os.getenv("MINDNET_VECTOR_SIZE", "384"))
|
||||
COLLECTION_PREFIX: str = os.getenv("MINDNET_PREFIX", "mindnet_dev")
|
||||
|
||||
# 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")
|
||||
|
||||
# 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")
|
||||
|
||||
# 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")
|
||||
LLM_MODEL: str = os.getenv("MINDNET_LLM_MODEL", "phi3:mini")
|
||||
PROMPTS_PATH: str = os.getenv("MINDNET_PROMPTS_PATH", "config/prompts.yaml")
|
||||
|
||||
# NEU für WP-06
|
||||
LLM_TIMEOUT: float = float(os.getenv("MINDNET_LLM_TIMEOUT", "120.0"))
|
||||
# --- WP-06 / WP-14 Performance & Last-Steuerung ---
|
||||
LLM_TIMEOUT: float = float(os.getenv("MINDNET_LLM_TIMEOUT", "300.0"))
|
||||
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"
|
||||
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_EDGE: float = float(os.getenv("MINDNET_WP04_W_EDGE", "0.25"))
|
||||
RETRIEVER_W_CENT: float = float(os.getenv("MINDNET_WP04_W_CENT", "0.05"))
|
||||
@@ -44,4 +80,5 @@ class Settings:
|
||||
|
||||
@lru_cache
|
||||
def get_settings() -> Settings:
|
||||
"""Gibt die zentralen Einstellungen als Singleton zurück."""
|
||||
return Settings()
|
||||
+157
-184
@@ -1,13 +1,16 @@
|
||||
"""
|
||||
FILE: app/core/chunker.py
|
||||
DESCRIPTION: Zerlegt Texte in Chunks (Sliding Window oder nach Headings).
|
||||
Orchestriert die Smart-Edge-Allocation via SemanticAnalyzer.
|
||||
FIX V3: Support für mehrzeilige Callouts und Section-Propagation.
|
||||
VERSION: 3.1.0 (Full Compatibility Merge)
|
||||
WP-15b: Implementiert Edge-Inheritance und Candidate-Pool Vorbereitung.
|
||||
Zentralisiert die Kanten-Vorbereitung für die spätere binäre Validierung.
|
||||
Bietet volle Unterstützung für Hybrid-Chunking (Strict/Soft/Safety-Net).
|
||||
VERSION: 3.2.0
|
||||
STATUS: Active
|
||||
DEPENDENCIES: re, math, yaml, pathlib, asyncio, logging
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
from dataclasses import dataclass
|
||||
from dataclasses import dataclass, field
|
||||
from typing import List, Dict, Optional, Tuple, Any, Set
|
||||
import re
|
||||
import math
|
||||
@@ -17,15 +20,18 @@ import asyncio
|
||||
import logging
|
||||
|
||||
# Services
|
||||
from app.services.semantic_analyzer import get_semantic_analyzer
|
||||
# In WP-15b wird die KI-Validierung in die ingestion.py verlagert.
|
||||
# Wir behalten den Import für Abwärtskompatibilität, falls Legacy-Skripte ihn benötigen.
|
||||
try:
|
||||
from app.services.semantic_analyzer import get_semantic_analyzer
|
||||
except ImportError:
|
||||
def get_semantic_analyzer(): return None
|
||||
|
||||
# Core Imports
|
||||
# Wir importieren build_edges_for_note nur, um kompatibel zur Signatur zu bleiben
|
||||
# oder für den Fallback.
|
||||
try:
|
||||
from app.core.derive_edges import build_edges_for_note
|
||||
except ImportError:
|
||||
# Mock für Tests
|
||||
# Fallback für Standalone-Betrieb oder Tests
|
||||
def build_edges_for_note(note_id, chunks, note_level_references=None, include_note_scope_refs=False): return []
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -54,7 +60,7 @@ def _load_yaml_config() -> Dict[str, Any]:
|
||||
def get_chunk_config(note_type: str) -> Dict[str, Any]:
|
||||
"""
|
||||
Lädt die Chunking-Strategie basierend auf dem Note-Type aus types.yaml.
|
||||
Dies sichert die Kompatibilität zu WP-15 (Profile).
|
||||
Sichert die Kompatibilität zu WP-15 Profilen.
|
||||
"""
|
||||
full_config = _load_yaml_config()
|
||||
profiles = full_config.get("chunking_profiles", {})
|
||||
@@ -75,6 +81,7 @@ def get_chunk_config(note_type: str) -> Dict[str, Any]:
|
||||
return config
|
||||
|
||||
def extract_frontmatter_from_text(md_text: str) -> Tuple[Dict[str, Any], str]:
|
||||
"""Trennt YAML-Frontmatter vom eigentlichen Text."""
|
||||
fm_match = re.match(r'^\s*---\s*\n(.*?)\n---', md_text, re.DOTALL)
|
||||
if not fm_match: return {}, md_text
|
||||
try:
|
||||
@@ -89,12 +96,15 @@ def extract_frontmatter_from_text(md_text: str) -> Tuple[Dict[str, Any], str]:
|
||||
# 2. DATA CLASSES & TEXT TOOLS
|
||||
# ==========================================
|
||||
|
||||
_SENT_SPLIT = re.compile(r'(?<=[.!?])\s+(?=[A-ZÄÖÜ0-9„(])'); _WS = re.compile(r'\s+')
|
||||
_SENT_SPLIT = re.compile(r'(?<=[.!?])\s+(?=[A-ZÄÖÜ0-9„(])')
|
||||
_WS = re.compile(r'\s+')
|
||||
|
||||
def estimate_tokens(text: str) -> int:
|
||||
"""Grobe Schätzung der Token-Anzahl (4 Zeichen pro Token)."""
|
||||
return max(1, math.ceil(len(text.strip()) / 4))
|
||||
|
||||
def split_sentences(text: str) -> list[str]:
|
||||
"""Teilt Text in Sätze auf unter Berücksichtigung von Interpunktion."""
|
||||
text = _WS.sub(' ', text.strip())
|
||||
if not text: return []
|
||||
parts = _SENT_SPLIT.split(text)
|
||||
@@ -102,13 +112,26 @@ def split_sentences(text: str) -> list[str]:
|
||||
|
||||
@dataclass
|
||||
class RawBlock:
|
||||
kind: str; text: str; level: Optional[int]; section_path: str; section_title: Optional[str]
|
||||
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]
|
||||
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]
|
||||
# WP-15b: Liste von Kandidaten für die semantische Validierung
|
||||
candidate_pool: List[Dict[str, Any]] = field(default_factory=list)
|
||||
suggested_edges: Optional[List[str]] = None
|
||||
|
||||
# ==========================================
|
||||
@@ -118,7 +141,7 @@ class Chunk:
|
||||
def parse_blocks(md_text: str) -> Tuple[List[RawBlock], str]:
|
||||
"""
|
||||
Zerlegt Text in logische Blöcke (Absätze, Header).
|
||||
Wichtig für die Strategie 'by_heading'.
|
||||
Wichtig für die Strategie 'by_heading' und die Edge-Inheritance.
|
||||
"""
|
||||
blocks = []
|
||||
h1_title = "Dokument"
|
||||
@@ -165,14 +188,15 @@ def parse_blocks(md_text: str) -> Tuple[List[RawBlock], str]:
|
||||
|
||||
def _strategy_sliding_window(blocks: List[RawBlock], config: Dict[str, Any], note_id: str, doc_title: str = "", context_prefix: str = "") -> List[Chunk]:
|
||||
"""
|
||||
Die Standard-Strategie aus WP-15.
|
||||
Fasst Blöcke zusammen und schneidet bei 'target' Tokens (mit Satz-Rücksicht).
|
||||
Standard-Strategie aus WP-15.
|
||||
Fasst Blöcke zusammen und schneidet bei 'target' Tokens.
|
||||
"""
|
||||
target = config.get("target", 400)
|
||||
max_tokens = config.get("max", 600)
|
||||
overlap_val = config.get("overlap", (50, 80))
|
||||
overlap = sum(overlap_val) // 2 if isinstance(overlap_val, tuple) else overlap_val
|
||||
chunks = []; buf = []
|
||||
chunks = []
|
||||
buf = []
|
||||
|
||||
def _create_chunk(txt, win, sec, path):
|
||||
idx = len(chunks)
|
||||
@@ -180,7 +204,7 @@ def _strategy_sliding_window(blocks: List[RawBlock], config: Dict[str, Any], not
|
||||
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=[]
|
||||
candidate_pool=[]
|
||||
))
|
||||
|
||||
def flush_buffer():
|
||||
@@ -190,14 +214,11 @@ def _strategy_sliding_window(blocks: List[RawBlock], config: Dict[str, Any], not
|
||||
text_body = "\n\n".join([b.text for b in buf])
|
||||
sec_title = buf[-1].section_title if buf else None
|
||||
sec_path = buf[-1].section_path if buf else "/"
|
||||
|
||||
# Context Prefix (z.B. H1) voranstellen für Embedding-Qualität
|
||||
win_body = f"{context_prefix}\n{text_body}".strip() if context_prefix else text_body
|
||||
|
||||
if estimate_tokens(text_body) <= max_tokens:
|
||||
_create_chunk(text_body, win_body, sec_title, sec_path)
|
||||
else:
|
||||
# Zu groß -> Satzweiser Split
|
||||
sentences = split_sentences(text_body)
|
||||
current_chunk_sents = []
|
||||
current_len = 0
|
||||
@@ -209,15 +230,13 @@ def _strategy_sliding_window(blocks: List[RawBlock], config: Dict[str, Any], not
|
||||
c_win = f"{context_prefix}\n{c_txt}".strip() if context_prefix else c_txt
|
||||
_create_chunk(c_txt, c_win, sec_title, sec_path)
|
||||
|
||||
# Overlap für nächsten Chunk
|
||||
overlap_sents = []
|
||||
ov_len = 0
|
||||
for s in reversed(current_chunk_sents):
|
||||
if ov_len + estimate_tokens(s) < overlap:
|
||||
overlap_sents.insert(0, s)
|
||||
ov_len += estimate_tokens(s)
|
||||
else:
|
||||
break
|
||||
else: break
|
||||
|
||||
current_chunk_sents = list(overlap_sents)
|
||||
current_chunk_sents.append(sent)
|
||||
@@ -226,12 +245,10 @@ def _strategy_sliding_window(blocks: List[RawBlock], config: Dict[str, Any], not
|
||||
current_chunk_sents.append(sent)
|
||||
current_len += sent_len
|
||||
|
||||
# Rest
|
||||
if current_chunk_sents:
|
||||
c_txt = " ".join(current_chunk_sents)
|
||||
c_win = f"{context_prefix}\n{c_txt}".strip() if context_prefix else c_txt
|
||||
_create_chunk(c_txt, c_win, sec_title, sec_path)
|
||||
|
||||
buf = []
|
||||
|
||||
for b in blocks:
|
||||
@@ -248,132 +265,137 @@ def _strategy_sliding_window(blocks: List[RawBlock], config: Dict[str, Any], not
|
||||
|
||||
def _strategy_by_heading(blocks: List[RawBlock], config: Dict[str, Any], note_id: str, doc_title: str = "") -> List[Chunk]:
|
||||
"""
|
||||
Strategie für strukturierte Daten (Profile, Werte).
|
||||
Nutzt sliding_window, forciert aber Schnitte an Headings (via parse_blocks Vorarbeit).
|
||||
Hybrid-Strategie v2.9 (Strict/Soft/Safety-Net).
|
||||
"""
|
||||
return _strategy_sliding_window(blocks, config, note_id, doc_title, context_prefix=f"# {doc_title}")
|
||||
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)
|
||||
|
||||
chunks = []
|
||||
current_buf = []
|
||||
current_tokens = 0
|
||||
|
||||
def _flush(sec_title, sec_path):
|
||||
nonlocal current_buf, current_tokens
|
||||
if not current_buf: return
|
||||
txt = "\n\n".join(current_buf)
|
||||
win = f"# {doc_title}\n## {sec_title}\n{txt}".strip() if sec_title else txt
|
||||
idx = len(chunks)
|
||||
chunks.append(Chunk(
|
||||
id=f"{note_id}#c{idx:02d}", note_id=note_id, index=idx,
|
||||
text=txt, window=win, token_count=estimate_tokens(txt),
|
||||
section_title=sec_title, section_path=sec_path,
|
||||
neighbors_prev=None, neighbors_next=None,
|
||||
candidate_pool=[]
|
||||
))
|
||||
current_buf = []
|
||||
current_tokens = 0
|
||||
|
||||
for b in blocks:
|
||||
if b.kind == "heading":
|
||||
# Hierarchie-Check: Split bei Überschriften oberhalb des Split-Levels
|
||||
if b.level < split_level:
|
||||
_flush(b.section_title, b.section_path)
|
||||
elif b.level == split_level:
|
||||
if strict or current_tokens >= target:
|
||||
_flush(b.section_title, b.section_path)
|
||||
continue
|
||||
|
||||
block_tokens = estimate_tokens(b.text)
|
||||
if current_tokens + block_tokens > max_tokens and current_buf:
|
||||
_flush(b.section_title, b.section_path)
|
||||
|
||||
current_buf.append(b.text)
|
||||
current_tokens += block_tokens
|
||||
|
||||
if current_buf:
|
||||
last = blocks[-1] if blocks else None
|
||||
_flush(last.section_title if last else None, last.section_path if last else "/")
|
||||
|
||||
return chunks
|
||||
|
||||
# ==========================================
|
||||
# 4. ROBUST EDGE PARSING & PROPAGATION (NEU)
|
||||
# 4. ROBUST EDGE PARSING & PROPAGATION
|
||||
# ==========================================
|
||||
|
||||
def _parse_edges_robust(text: str) -> Set[str]:
|
||||
"""
|
||||
NEU: Findet Kanten im Text, auch wenn sie mehrzeilig oder 'kaputt' formatiert sind.
|
||||
Erkennt:
|
||||
> [!edge] type
|
||||
> [[Link]]
|
||||
Returns: Set von Strings "kind:target"
|
||||
Findet Kanten im Text (Wikilinks, Inlines, Callouts).
|
||||
Fix V3: Support für mehrzeilige Callouts.
|
||||
"""
|
||||
found_edges = set()
|
||||
|
||||
# A. Inline [[rel:type|target]] (Standard)
|
||||
# A. Inline [[rel:type|target]]
|
||||
inlines = re.findall(r'\[\[rel:([^\|\]]+)\|?([^\]]*)\]\]', text)
|
||||
for kind, target in inlines:
|
||||
k = kind.strip()
|
||||
k = kind.strip().lower()
|
||||
t = target.strip()
|
||||
if k and t: found_edges.add(f"{k}:{t}")
|
||||
|
||||
# B. Multiline Callouts Parsing (Der Fix für dein Problem)
|
||||
# B. Multiline Callouts Parsing (WP-15 Fix)
|
||||
lines = text.split('\n')
|
||||
current_edge_type = None
|
||||
|
||||
for line in lines:
|
||||
stripped = line.strip()
|
||||
|
||||
# 1. Start Blockquote: > [!edge] type
|
||||
# (Erlaubt optionalen Doppelpunkt)
|
||||
callout_match = re.match(r'>\s*\[!edge\]\s*([^:\s]+)', stripped)
|
||||
if callout_match:
|
||||
current_edge_type = callout_match.group(1).strip()
|
||||
|
||||
# Check: Sind Links noch in der GLEICHEN Zeile?
|
||||
current_edge_type = callout_match.group(1).strip().lower()
|
||||
links = re.findall(r'\[\[([^\]]+)\]\]', stripped)
|
||||
for l in links:
|
||||
if "rel:" not in l:
|
||||
found_edges.add(f"{current_edge_type}:{l}")
|
||||
if "rel:" not in l: found_edges.add(f"{current_edge_type}:{l}")
|
||||
continue
|
||||
|
||||
# 2. Continuation Line: > [[Target]]
|
||||
# Wenn wir noch im 'edge mode' sind und die Zeile ein Zitat ist
|
||||
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}")
|
||||
|
||||
# 3. End of Blockquote (kein '>') -> Reset Type
|
||||
if "rel:" not in l: found_edges.add(f"{current_edge_type}:{l}")
|
||||
elif not stripped.startswith('>'):
|
||||
current_edge_type = None
|
||||
|
||||
return found_edges
|
||||
|
||||
def _propagate_section_edges(chunks: List[Chunk]) -> List[Chunk]:
|
||||
def _propagate_section_edges(chunks: List[Chunk], blocks: List[RawBlock]) -> List[Chunk]:
|
||||
"""
|
||||
NEU: Verteilt Kanten innerhalb einer Sektion.
|
||||
Löst das Problem: Callout steht oben im Kapitel, gilt aber für alle Chunks darunter.
|
||||
WP-15b: Implementiert Edge-Inheritance.
|
||||
Kanten aus Überschriften werden an untergeordnete Chunks vererbt.
|
||||
"""
|
||||
# Step 1: Sammeln pro Sektion
|
||||
section_map = {} # path -> set(kind:target)
|
||||
section_inheritance: Dict[str, Set[str]] = {}
|
||||
|
||||
# 1. Sammeln aus den Heading-Blöcken
|
||||
for b in blocks:
|
||||
if b.kind == "heading":
|
||||
edges = _parse_edges_robust(b.text)
|
||||
if edges:
|
||||
if b.section_path not in section_inheritance:
|
||||
section_inheritance[b.section_path] = set()
|
||||
section_inheritance[b.section_path].update(edges)
|
||||
|
||||
# 2. Injektion in den Candidate-Pool
|
||||
for ch in chunks:
|
||||
# Root-Level "/" ignorieren wir meist, da zu global
|
||||
if not ch.section_path or ch.section_path == "/": continue
|
||||
|
||||
edges = _parse_edges_robust(ch.text)
|
||||
if edges:
|
||||
if ch.section_path not in section_map:
|
||||
section_map[ch.section_path] = set()
|
||||
section_map[ch.section_path].update(edges)
|
||||
|
||||
# Step 2: Injizieren (Broadcasting)
|
||||
for ch in chunks:
|
||||
if ch.section_path in section_map:
|
||||
edges_to_add = section_map[ch.section_path]
|
||||
if not edges_to_add: continue
|
||||
|
||||
injections = []
|
||||
for e_str in edges_to_add:
|
||||
kind, target = e_str.split(':', 1)
|
||||
# Check: Kante schon im Text?
|
||||
token = f"[[rel:{kind}|{target}]]"
|
||||
if token not in ch.text:
|
||||
injections.append(token)
|
||||
|
||||
if injections:
|
||||
# Wir schreiben die Kanten "hart" in den Text.
|
||||
# Damit findet sie derive_edges.py später garantiert.
|
||||
block = "\n\n\n" + " ".join(injections)
|
||||
ch.text += block
|
||||
# Auch ins Window schreiben für Embedding-Kontext
|
||||
ch.window += block
|
||||
inherited = section_inheritance.get(ch.section_path, set())
|
||||
for e_str in inherited:
|
||||
kind, target = e_str.split(':', 1)
|
||||
ch.candidate_pool.append({"kind": kind, "to": target, "provenance": "inherited"})
|
||||
|
||||
return chunks
|
||||
|
||||
# ==========================================
|
||||
# 5. ORCHESTRATION (ASYNC)
|
||||
# 5. ORCHESTRATION (WP-15b)
|
||||
# ==========================================
|
||||
|
||||
async def assemble_chunks(note_id: str, md_text: str, note_type: str, config: Optional[Dict] = None) -> List[Chunk]:
|
||||
"""
|
||||
Hauptfunktion. Verbindet Parsing, Splitting und Edge-Allocation.
|
||||
Hauptfunktion zur Chunk-Generierung.
|
||||
Baut den Candidate-Pool für die semantische Validierung auf.
|
||||
"""
|
||||
# 1. Config laden (WP-15 Kompatibilität)
|
||||
if config is None:
|
||||
config = get_chunk_config(note_type)
|
||||
|
||||
fm, body_text = extract_frontmatter_from_text(md_text)
|
||||
note_status = fm.get("status", "").lower()
|
||||
|
||||
primary_strategy = config.get("strategy", "sliding_window")
|
||||
enable_smart_edges = config.get("enable_smart_edge_allocation", False)
|
||||
|
||||
# Drafts skippen LLM um Kosten/Zeit zu sparen
|
||||
if enable_smart_edges and note_status in ["draft", "initial_gen"]:
|
||||
logger.info(f"Chunker: Skipping Smart Edges for draft '{note_id}'.")
|
||||
enable_smart_edges = False
|
||||
|
||||
# 2. Parsing & Splitting
|
||||
# 1. Parsing & Splitting
|
||||
blocks, doc_title = parse_blocks(md_text)
|
||||
|
||||
if primary_strategy == "by_heading":
|
||||
@@ -381,94 +403,45 @@ async def assemble_chunks(note_id: str, md_text: str, note_type: str, config: Op
|
||||
else:
|
||||
chunks = await asyncio.to_thread(_strategy_sliding_window, blocks, config, note_id, doc_title)
|
||||
|
||||
if not chunks:
|
||||
return []
|
||||
if not chunks: return []
|
||||
|
||||
# 3. NEU: Propagation VOR Smart Edge Allocation
|
||||
# Das repariert die fehlenden Kanten aus deinen Callouts.
|
||||
chunks = _propagate_section_edges(chunks)
|
||||
# 2. WP-15b: Candidate Pool Vorbereitung
|
||||
|
||||
# A. Edge Inheritance (Sektions-Propagation)
|
||||
chunks = _propagate_section_edges(chunks, blocks)
|
||||
|
||||
# B. Explicit Edges (Direkt im Chunk-Text enthalten)
|
||||
for ch in chunks:
|
||||
explicit = _parse_edges_robust(ch.text)
|
||||
for e_str in explicit:
|
||||
kind, target = e_str.split(':', 1)
|
||||
ch.candidate_pool.append({"kind": kind, "to": target, "provenance": "explicit"})
|
||||
|
||||
# 4. Smart Edges (LLM)
|
||||
if enable_smart_edges:
|
||||
chunks = await _run_smart_edge_allocation(chunks, md_text, note_id, note_type)
|
||||
# C. Global "Unassigned Pool" Detection (Safety Net)
|
||||
# Sucht nach einer Sektion "Unzugeordnete Kanten" im Body
|
||||
unassigned_pool = set()
|
||||
pool_match = re.search(r'###?\s*(?:Unzugeordnete Kanten|Edge Pool|Candidates)\s*\n(.*?)(?:\n#|$)', body_text, re.DOTALL | re.IGNORECASE)
|
||||
if pool_match:
|
||||
unassigned_pool = _parse_edges_robust(pool_match.group(1))
|
||||
for ch in chunks:
|
||||
for e_str in unassigned_pool:
|
||||
kind, target = e_str.split(':', 1)
|
||||
ch.candidate_pool.append({"kind": kind, "to": target, "provenance": "global_pool"})
|
||||
|
||||
# 5. Linking
|
||||
# D. De-Duplikation des Pools
|
||||
for ch in chunks:
|
||||
seen = set()
|
||||
unique_pool = []
|
||||
for cand in ch.candidate_pool:
|
||||
key = (cand["kind"], cand["to"])
|
||||
if key not in seen:
|
||||
seen.add(key)
|
||||
unique_pool.append(cand)
|
||||
ch.candidate_pool = unique_pool
|
||||
|
||||
# 3. Nachbarschafts-Verkettung (Struktur-Kanten)
|
||||
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]:
|
||||
"""
|
||||
Hilfsfunktion: Sammelt ALLE Kanten für den LLM-Kandidaten-Pool.
|
||||
"""
|
||||
# A. Via derive_edges (Standard)
|
||||
dummy_chunk = {
|
||||
"chunk_id": f"{note_id}#full",
|
||||
"text": md_text,
|
||||
"content": md_text,
|
||||
"window": md_text,
|
||||
"type": note_type
|
||||
}
|
||||
# Signatur-Anpassung beachten (WP-15 Fix)
|
||||
raw_edges = build_edges_for_note(
|
||||
note_id,
|
||||
[dummy_chunk],
|
||||
note_level_references=None,
|
||||
include_note_scope_refs=False
|
||||
)
|
||||
all_candidates = set()
|
||||
for e in raw_edges:
|
||||
kind = e.get("kind")
|
||||
target = e.get("target_id")
|
||||
if target and kind not in ["belongs_to", "next", "prev", "backlink"]:
|
||||
all_candidates.add(f"{kind}:{target}")
|
||||
|
||||
# B. Via Robust Parser (NEU) - fängt die multiline Callouts
|
||||
robust_edges = _parse_edges_robust(md_text)
|
||||
all_candidates.update(robust_edges)
|
||||
|
||||
return list(all_candidates)
|
||||
|
||||
async def _run_smart_edge_allocation(chunks: List[Chunk], full_text: str, note_id: str, note_type: str) -> List[Chunk]:
|
||||
"""
|
||||
Der LLM-Schritt (WP-15). Filtert irrelevante Kanten.
|
||||
"""
|
||||
analyzer = get_semantic_analyzer()
|
||||
candidate_list = _extract_all_edges_from_md(full_text, note_id, note_type)
|
||||
|
||||
if not candidate_list:
|
||||
return chunks
|
||||
|
||||
tasks = []
|
||||
for chunk in chunks:
|
||||
tasks.append(analyzer.assign_edges_to_chunk(chunk.text, candidate_list, note_type))
|
||||
|
||||
results_per_chunk = await asyncio.gather(*tasks)
|
||||
|
||||
assigned_edges_global = set()
|
||||
|
||||
for i, confirmed_edges in enumerate(results_per_chunk):
|
||||
chunk = chunks[i]
|
||||
chunk.suggested_edges = confirmed_edges
|
||||
assigned_edges_global.update(confirmed_edges)
|
||||
|
||||
if confirmed_edges:
|
||||
# Wir schreiben auch Smart Edges hart in den Text
|
||||
injection_str = "\n" + " ".join([f"[[rel:{e.split(':')[0]}|{e.split(':')[1]}]]" for e in confirmed_edges if ':' in e])
|
||||
chunk.text += injection_str
|
||||
chunk.window += injection_str
|
||||
|
||||
# Fallback für Kanten, die das LLM nirgendwo zugeordnet hat
|
||||
# (Damit nichts verloren geht -> Safety Fallback)
|
||||
unassigned = set(candidate_list) - assigned_edges_global
|
||||
if unassigned:
|
||||
fallback_str = "\n" + " ".join([f"[[rel:{e.split(':')[0]}|{e.split(':')[1]}]]" for e in unassigned if ':' in e])
|
||||
for chunk in chunks:
|
||||
chunk.text += fallback_str
|
||||
chunk.window += fallback_str
|
||||
if chunk.suggested_edges is None: chunk.suggested_edges = []
|
||||
chunk.suggested_edges.extend(list(unassigned))
|
||||
|
||||
return chunks
|
||||
+100
-126
@@ -1,17 +1,20 @@
|
||||
"""
|
||||
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
|
||||
WP-15b: Integration des Candidate-Pools und Provenance-Priorisierung.
|
||||
Sichert die Graph-Integrität durch confidence-basiertes De-Duplicating.
|
||||
VERSION: 2.1.0
|
||||
STATUS: Active
|
||||
DEPENDENCIES: re, os, yaml, typing
|
||||
DEPENDENCIES: re, os, yaml, typing, hashlib
|
||||
EXTERNAL_CONFIG: config/types.yaml
|
||||
LAST_ANALYSIS: 2025-12-15
|
||||
LAST_ANALYSIS: 2025-12-26
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
import hashlib
|
||||
from typing import Iterable, List, Optional, Tuple, Set, Dict
|
||||
|
||||
try:
|
||||
@@ -20,17 +23,18 @@ except Exception: # pragma: no cover
|
||||
yaml = None
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Utilities
|
||||
# 1. Utilities & ID Generation
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
def _get(d: dict, *keys, default=None):
|
||||
"""Sicherer Zugriff auf verschachtelte Dictionary-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 _chunk_text_for_refs(chunk: dict) -> str:
|
||||
# bevorzugt 'window' → dann 'text' → 'content' → 'raw'
|
||||
"""Extrahiert den relevanten Text für die Referenzsuche (bevorzugt Window)."""
|
||||
return (
|
||||
_get(chunk, "window")
|
||||
or _get(chunk, "text")
|
||||
@@ -40,6 +44,7 @@ def _chunk_text_for_refs(chunk: dict) -> str:
|
||||
)
|
||||
|
||||
def _dedupe_seq(seq: Iterable[str]) -> List[str]:
|
||||
"""Dedupliziert eine Sequenz von Strings unter Beibehaltung der Reihenfolge."""
|
||||
seen: Set[str] = set()
|
||||
out: List[str] = []
|
||||
for s in seq:
|
||||
@@ -49,9 +54,10 @@ def _dedupe_seq(seq: Iterable[str]) -> List[str]:
|
||||
return out
|
||||
|
||||
def _edge(kind: str, scope: str, source_id: str, target_id: str, note_id: str, extra: Optional[dict] = None) -> dict:
|
||||
"""Konstruiert ein valides Kanten-Payload-Objekt für Qdrant."""
|
||||
pl = {
|
||||
"kind": kind,
|
||||
"relation": kind, # Alias (v2)
|
||||
"relation": kind, # Alias für Abwärtskompatibilität (v2)
|
||||
"scope": scope, # "chunk" | "note"
|
||||
"source_id": source_id,
|
||||
"target_id": target_id,
|
||||
@@ -62,25 +68,38 @@ def _edge(kind: str, scope: str, source_id: str, target_id: str, note_id: str, e
|
||||
return pl
|
||||
|
||||
def _mk_edge_id(kind: str, s: str, t: str, scope: str, rule_id: Optional[str] = None) -> str:
|
||||
"""Erzeugt eine deterministische 12-Byte ID mittels BLAKE2s."""
|
||||
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)
|
||||
# 2. Konfiguration & Provenance-Skala
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
# 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 _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"""
|
||||
"""Lädt die YAML-Registry zur Ermittlung von Standard-Kanten."""
|
||||
p = _env("MINDNET_TYPES_FILE", "./config/types.yaml")
|
||||
if not os.path.isfile(p) or yaml is None:
|
||||
return {}
|
||||
@@ -97,13 +116,7 @@ def _get_types_map(reg: dict) -> dict:
|
||||
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) []
|
||||
"""
|
||||
"""Liefert die edge_defaults-Liste für den gegebenen Notiztyp."""
|
||||
types_map = _get_types_map(reg)
|
||||
if note_type and isinstance(types_map, dict):
|
||||
t = types_map.get(note_type)
|
||||
@@ -116,29 +129,19 @@ def _edge_defaults_for(note_type: Optional[str], reg: dict) -> List[str]:
|
||||
return []
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Parser für Links / Relationen
|
||||
# 3. Parser für Links / Relationen (Core Logik v2.0.0)
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
# Normale Wikilinks (Fallback)
|
||||
_WIKILINK_RE = re.compile(r"\[\[(?:[^\|\]]+\|)?([a-zA-Z0-9_\-#:. ]+)\]\]")
|
||||
|
||||
# Getypte Inline-Relationen:
|
||||
# [[rel:KIND | Target]]
|
||||
# [[rel:KIND Target]]
|
||||
# Getypte Inline-Relationen
|
||||
_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]]
|
||||
"""
|
||||
"""Extrahiert [[rel:KIND|Target]] und entfernt sie zur Vermeidung von Dubletten."""
|
||||
pairs: List[Tuple[str,str]] = []
|
||||
def _collect(m):
|
||||
k = (m.group("kind") or "").strip().lower()
|
||||
@@ -152,17 +155,13 @@ def _extract_typed_relations(text: str) -> Tuple[List[Tuple[str,str]], str]:
|
||||
text = _REL_TEXT.sub(_collect, text)
|
||||
return pairs, text
|
||||
|
||||
# Obsidian Callout Parser
|
||||
# Obsidian Callout Parser für mehrzeilige Blöcke
|
||||
_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).
|
||||
"""
|
||||
"""Verarbeitet [!edge]-Callouts und entfernt diese aus dem Textfluss."""
|
||||
if not text:
|
||||
return [], text
|
||||
|
||||
@@ -205,21 +204,20 @@ def _extract_callout_relations(text: str) -> Tuple[List[Tuple[str,str]], str]:
|
||||
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]:
|
||||
"""Extrahiert Standard-Wikilinks aus dem verbleibenden Text."""
|
||||
ids: List[str] = []
|
||||
for m in _WIKILINK_RE.finditer(text or ""):
|
||||
ids.append(m.group(1).strip())
|
||||
return ids
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Hauptfunktion
|
||||
# 4. Hauptfunktion (build_edges_for_note)
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
def build_edges_for_note(
|
||||
@@ -229,24 +227,13 @@ def build_edges_for_note(
|
||||
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
|
||||
Erzeugt und aggregiert alle Kanten für eine Note inklusive WP-15b Candidate-Processing.
|
||||
Setzt Provenance-Ranking zur Graph-Stabilisierung ein.
|
||||
"""
|
||||
edges: List[dict] = []
|
||||
note_type = _get(chunks[0], "type") if chunks else "concept"
|
||||
|
||||
# Note-Typ (aus erstem Chunk erwartet)
|
||||
note_type = None
|
||||
if chunks:
|
||||
note_type = _get(chunks[0], "type")
|
||||
|
||||
# 1) belongs_to
|
||||
# 1) Struktur-Kanten: belongs_to (Chunk -> Note)
|
||||
for ch in chunks:
|
||||
cid = _get(ch, "chunk_id", "id")
|
||||
if not cid:
|
||||
@@ -254,12 +241,12 @@ def build_edges_for_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": "rule",
|
||||
"provenance": "structure",
|
||||
"rule_id": "structure:belongs_to",
|
||||
"confidence": 1.0,
|
||||
"confidence": PROVENANCE_PRIORITY["structure:belongs_to"],
|
||||
}))
|
||||
|
||||
# 2) next / prev
|
||||
# 2) Struktur-Kanten: next / prev (Sequenz)
|
||||
for i in range(len(chunks) - 1):
|
||||
a, b = chunks[i], chunks[i + 1]
|
||||
a_id = _get(a, "chunk_id", "id")
|
||||
@@ -269,19 +256,19 @@ def build_edges_for_note(
|
||||
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",
|
||||
"provenance": "structure",
|
||||
"rule_id": "structure:order",
|
||||
"confidence": 0.95,
|
||||
"confidence": PROVENANCE_PRIORITY["structure:order"],
|
||||
}))
|
||||
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",
|
||||
"provenance": "structure",
|
||||
"rule_id": "structure:order",
|
||||
"confidence": 0.95,
|
||||
"confidence": PROVENANCE_PRIORITY["structure:order"],
|
||||
}))
|
||||
|
||||
# 3) references + typed inline + callouts + defaults (chunk-scope)
|
||||
# 3) Inhaltliche Kanten (Refs, Inlines, Callouts, Candidates)
|
||||
reg = _load_types_registry()
|
||||
defaults = _edge_defaults_for(note_type, reg)
|
||||
refs_all: List[str] = []
|
||||
@@ -292,51 +279,49 @@ def build_edges_for_note(
|
||||
continue
|
||||
raw = _chunk_text_for_refs(ch)
|
||||
|
||||
# 3a) typed inline relations
|
||||
# 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, {
|
||||
k = kind.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(kind, cid, target, "chunk", "inline:rel"),
|
||||
"edge_id": _mk_edge_id(k, cid, target, "chunk", "inline:rel"),
|
||||
"provenance": "explicit",
|
||||
"rule_id": "inline:rel",
|
||||
"confidence": 0.95,
|
||||
"confidence": PROVENANCE_PRIORITY["inline:rel"],
|
||||
}))
|
||||
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
|
||||
# 3b) WP-15b Candidate Pool Integration (KI-validierte Kanten)
|
||||
# Verarbeitet Kanten, die bereits in der Ingestion semantisch geprüft wurden.
|
||||
pool = ch.get("candidate_pool") or ch.get("candidate_edges") or []
|
||||
for cand in pool:
|
||||
target = cand.get("to")
|
||||
kind = cand.get("kind", "related_to")
|
||||
prov = cand.get("provenance", "semantic_ai")
|
||||
if not target: continue
|
||||
edges.append(_edge(kind, "chunk", cid, target, note_id, {
|
||||
"chunk_id": cid,
|
||||
"edge_id": _mk_edge_id(kind, cid, target, "chunk", f"candidate:{prov}"),
|
||||
"provenance": prov,
|
||||
"rule_id": f"candidate:{prov}",
|
||||
"confidence": PROVENANCE_PRIORITY.get(prov, 0.90),
|
||||
}))
|
||||
|
||||
# 3c) Obsidian 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
|
||||
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,
|
||||
"confidence": PROVENANCE_PRIORITY["callout:edge"],
|
||||
}))
|
||||
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)
|
||||
# 3d) Standard-Wikilinks -> references (+ defaults)
|
||||
refs = _extract_wikilinks(remainder2)
|
||||
for r in refs:
|
||||
edges.append(_edge("references", "chunk", cid, r, note_id, {
|
||||
@@ -345,76 +330,65 @@ def build_edges_for_note(
|
||||
"edge_id": _mk_edge_id("references", cid, r, "chunk", "explicit:wikilink"),
|
||||
"provenance": "explicit",
|
||||
"rule_id": "explicit:wikilink",
|
||||
"confidence": 1.0,
|
||||
"confidence": PROVENANCE_PRIORITY["explicit:wikilink"],
|
||||
}))
|
||||
# Regelbasierte Kanten aus types.yaml anhängen
|
||||
for rel in defaults:
|
||||
if rel == "references":
|
||||
continue
|
||||
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,
|
||||
"confidence": PROVENANCE_PRIORITY["edge_defaults"],
|
||||
}))
|
||||
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)
|
||||
# 4) Optionale Note-Scope Referenzen & Backlinks
|
||||
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,
|
||||
"confidence": PROVENANCE_PRIORITY["explicit:note_scope"],
|
||||
}))
|
||||
# Backlink-Erzeugung zur Graphen-Stärkung
|
||||
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,
|
||||
"confidence": PROVENANCE_PRIORITY["derived:backlink"],
|
||||
}))
|
||||
for rel in defaults:
|
||||
if rel == "references":
|
||||
continue
|
||||
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,
|
||||
"confidence": PROVENANCE_PRIORITY["edge_defaults"],
|
||||
}))
|
||||
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] = []
|
||||
# 5) WP-15b: Confidence-basierte De-Duplizierung
|
||||
# Wenn dieselbe Relation mehrfach existiert, gewinnt die mit der höchsten Confidence.
|
||||
unique_map: Dict[Tuple[str, str, str], dict] = {}
|
||||
|
||||
for e in edges:
|
||||
s = str(e.get("source_id") or "")
|
||||
t = str(e.get("target_id") or "")
|
||||
s, t = str(e.get("source_id")), str(e.get("target_id"))
|
||||
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
|
||||
key = (s, t, rel)
|
||||
|
||||
if key not in unique_map:
|
||||
unique_map[key] = e
|
||||
else:
|
||||
# Vergleich der Vertrauenswürdigkeit (Provenance Ranking)
|
||||
if e.get("confidence", 0) > unique_map[key].get("confidence", 0):
|
||||
unique_map[key] = e
|
||||
|
||||
return list(unique_map.values())
|
||||
+220
-204
@@ -1,16 +1,20 @@
|
||||
"""
|
||||
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)
|
||||
DESCRIPTION: Haupt-Ingestion-Logik. Transformiert Markdown in den Graphen.
|
||||
WP-20: Optimiert für OpenRouter (mistralai/mistral-7b-instruct:free).
|
||||
WP-22: Content Lifecycle, Edge Registry Validation & Multi-Hash.
|
||||
WP-15b: Two-Pass Ingestion mit LocalBatchCache & Candidate-Validation.
|
||||
Sichert, dass explizite Kanten direkt übernommen und nur Pool-Kanten validiert werden.
|
||||
FIX: Deep Fallback Logic (v2.11.14) für JSON-Recovery.
|
||||
Robust Lookup Fix: Adressiert Notizen im Cache via ID, Titel und Dateiname.
|
||||
VERSION: 2.12.2
|
||||
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
|
||||
DEPENDENCIES: app.core.parser, app.core.note_payload, app.core.chunker,
|
||||
app.services.llm_service, app.services.edge_registry
|
||||
"""
|
||||
import os
|
||||
import json
|
||||
import re
|
||||
import logging
|
||||
import asyncio
|
||||
import time
|
||||
@@ -19,8 +23,11 @@ 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,
|
||||
extract_edges_with_context,
|
||||
NoteContext
|
||||
)
|
||||
from app.core.note_payload import make_note_payload
|
||||
from app.core.chunker import assemble_chunks, get_chunk_config
|
||||
@@ -42,78 +49,77 @@ from app.core.qdrant_points import (
|
||||
|
||||
from app.services.embeddings_client import EmbeddingsClient
|
||||
from app.services.edge_registry import registry as edge_registry
|
||||
from app.services.llm_service import LLMService
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# --- Helper ---
|
||||
# --- Global Helpers (Full Compatibility v2.11.14) ---
|
||||
def extract_json_from_response(text: str) -> Any:
|
||||
"""
|
||||
Extrahiert JSON-Daten und bereinigt LLM-Steuerzeichen (Mistral/Llama).
|
||||
Entfernt <s>, [OUT], [/OUT] und Markdown-Blöcke für maximale Robustheit.
|
||||
"""
|
||||
if not text or not isinstance(text, str):
|
||||
return []
|
||||
|
||||
# 1. Entferne Mistral/Llama Steuerzeichen und Tags
|
||||
clean = text.replace("<s>", "").replace("</s>", "")
|
||||
clean = clean.replace("[OUT]", "").replace("[/OUT]", "")
|
||||
clean = clean.strip()
|
||||
|
||||
# 2. Suche nach Markdown JSON-Blöcken (```json ... ```)
|
||||
match = re.search(r"```(?:json)?\s*(.*?)\s*```", clean, re.DOTALL)
|
||||
payload = match.group(1) if match else clean
|
||||
|
||||
try:
|
||||
return json.loads(payload.strip())
|
||||
except json.JSONDecodeError:
|
||||
# 3. Recovery: Suche nach der ersten [ und letzten ] (Liste)
|
||||
start = payload.find('[')
|
||||
end = payload.rfind(']') + 1
|
||||
if start != -1 and end > start:
|
||||
try:
|
||||
return json.loads(payload[start:end])
|
||||
except: pass
|
||||
|
||||
# 4. Zweite Recovery: Suche nach der ersten { und letzten } (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 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")
|
||||
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 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))
|
||||
|
||||
|
||||
# --- Service Class ---
|
||||
class IngestionService:
|
||||
def __init__(self, collection_prefix: str = None):
|
||||
env_prefix = os.getenv("COLLECTION_PREFIX", "mindnet")
|
||||
self.prefix = collection_prefix or env_prefix
|
||||
from app.config import get_settings
|
||||
self.settings = get_settings()
|
||||
|
||||
self.prefix = collection_prefix or self.settings.COLLECTION_PREFIX
|
||||
self.cfg = QdrantConfig.from_env()
|
||||
self.cfg.prefix = self.prefix
|
||||
self.client = get_client(self.cfg)
|
||||
self.dim = self.cfg.dim
|
||||
self.dim = self.settings.VECTOR_SIZE
|
||||
self.registry = load_type_registry()
|
||||
self.embedder = EmbeddingsClient()
|
||||
self.llm = LLMService()
|
||||
|
||||
# Change Detection Modus (full oder body)
|
||||
self.active_hash_mode = os.getenv("MINDNET_CHANGE_DETECTION_MODE", "full")
|
||||
self.active_hash_mode = self.settings.CHANGE_DETECTION_MODE
|
||||
self.batch_cache: Dict[str, NoteContext] = {} # WP-15b LocalBatchCache
|
||||
|
||||
try:
|
||||
ensure_collections(self.client, self.prefix, self.dim)
|
||||
@@ -121,8 +127,82 @@ class IngestionService:
|
||||
except Exception as e:
|
||||
logger.warning(f"DB init 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 baut flüchtigen Kontext-Cache auf.
|
||||
Pass 2: Processing führt die eigentliche semantische Validierung durch.
|
||||
"""
|
||||
logger.info(f"🔍 [Pass 1] Pre-Scanning {len(file_paths)} files for Context Cache...")
|
||||
for path in file_paths:
|
||||
ctx = pre_scan_markdown(path)
|
||||
if ctx:
|
||||
# Mehrfache Indizierung für robusten Look-up (WP-15b Fix)
|
||||
self.batch_cache[ctx.note_id] = ctx
|
||||
self.batch_cache[ctx.title] = ctx
|
||||
# Dateiname ohne Endung als dritter Schlüssel
|
||||
fname = os.path.splitext(os.path.basename(path))[0]
|
||||
self.batch_cache[fname] = ctx
|
||||
|
||||
logger.info(f"🚀 [Pass 2] Semantic Processing of {len(file_paths)} files...")
|
||||
results = []
|
||||
for path in file_paths:
|
||||
res = await self.process_file(path, vault_root, apply=True)
|
||||
results.append(res)
|
||||
return results
|
||||
|
||||
async def _validate_candidate(self, chunk_text: str, edge: Dict) -> bool:
|
||||
"""
|
||||
WP-15b: Validiert einen Kanten-Kandidaten semantisch gegen das Ziel.
|
||||
Nutzt den Cache aus Pass 1, um dem LLM Kontext der Ziel-Note zu geben.
|
||||
"""
|
||||
target_id = edge.get("to")
|
||||
target_ctx = self.batch_cache.get(target_id)
|
||||
|
||||
# Fallback Look-up für Links mit Ankern (Anchor entfernen)
|
||||
if not target_ctx and "#" in target_id:
|
||||
base_id = target_id.split("#")[0]
|
||||
target_ctx = self.batch_cache.get(base_id)
|
||||
|
||||
# Sicherheits-Fallback: Wenn Zielnotiz nicht im aktuellen Batch ist,
|
||||
# lassen wir die Kante als 'explicit' durch (Hard-Link Integrity).
|
||||
if not target_ctx:
|
||||
logger.info(f"ℹ️ [VALIDATION SKIP] No context for '{target_id}' - allowing link.")
|
||||
return True
|
||||
|
||||
provider = self.settings.MINDNET_LLM_PROVIDER
|
||||
template = self.llm.get_prompt("edge_validation", provider)
|
||||
|
||||
try:
|
||||
logger.info(f"⚖️ [VALIDATING] Relation '{edge.get('kind')}' -> '{target_id}'...")
|
||||
prompt = template.format(
|
||||
chunk_text=chunk_text[:1500],
|
||||
target_title=target_ctx.title,
|
||||
target_summary=target_ctx.summary,
|
||||
edge_kind=edge.get("kind", "related_to")
|
||||
)
|
||||
|
||||
response = await self.llm.generate_raw_response(prompt, priority="background")
|
||||
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:
|
||||
logger.warning(f"⚠️ Semantic validation error for {target_id}: {e}")
|
||||
return True # Fallback: Im Zweifel Link behalten
|
||||
|
||||
def _resolve_note_type(self, requested: Optional[str]) -> str:
|
||||
"""Bestimmt den finalen Notiz-Typ (Fallback auf 'concept')."""
|
||||
types = self.registry.get("types", {})
|
||||
if requested and requested in types: return requested
|
||||
return "concept"
|
||||
|
||||
def _get_chunk_config_by_profile(self, profile_name: str, note_type: str) -> Dict[str, Any]:
|
||||
"""Holt die Chunker-Parameter (max, target, overlap) für ein spezifisches Profil."""
|
||||
"""Holt die Chunker-Parameter für ein spezifisches Profil aus der Registry."""
|
||||
profiles = self.registry.get("chunking_profiles", {})
|
||||
if profile_name in profiles:
|
||||
cfg = profiles[profile_name].copy()
|
||||
@@ -132,92 +212,45 @@ class IngestionService:
|
||||
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"
|
||||
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.
|
||||
"""
|
||||
"""Transformiert eine Markdown-Datei in den Graphen."""
|
||||
result = {"path": file_path, "status": "skipped", "changed": False, "error": None}
|
||||
|
||||
# 1. Parse & Frontmatter Validation
|
||||
# 1. Parse & Lifecycle Gate
|
||||
try:
|
||||
parsed = read_markdown(file_path)
|
||||
if not parsed: return {**result, "error": "Empty or unreadable file"}
|
||||
if not parsed: return {**result, "error": "Empty 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) ---
|
||||
# Lifecycle Filter (WP-22)
|
||||
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}"}
|
||||
return {**result, "status": "skipped", "reason": f"lifecycle_{status}"}
|
||||
|
||||
# 2. Type & Config Resolution
|
||||
note_type = resolve_note_type(fm.get("type"), self.registry)
|
||||
# 2. Config Resolution & Payload
|
||||
note_type = self._resolve_note_type(fm.get("type"))
|
||||
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_pl = make_note_payload(parsed, vault_root=vault_root, hash_normalize=hash_normalize, hash_source=hash_source, file_path=file_path)
|
||||
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)}"}
|
||||
return {**result, "error": f"Payload 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)
|
||||
# 3. Change Detection (v2.11.14 Logic)
|
||||
old_payload = None if force_replace else self._fetch_note_payload(note_id)
|
||||
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
|
||||
|
||||
old_hash = (old_payload or {}).get("hashes", {}).get(check_key)
|
||||
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
|
||||
chunks_missing, edges_missing = self._artifacts_missing(note_id)
|
||||
should_write = force_replace or (not old_payload) or (old_hash != new_hash) or chunks_missing or edges_missing
|
||||
|
||||
if not should_write:
|
||||
return {**result, "status": "unchanged", "note_id": note_id}
|
||||
@@ -225,133 +258,116 @@ class IngestionService:
|
||||
if not apply:
|
||||
return {**result, "status": "dry-run", "changed": True, "note_id": note_id}
|
||||
|
||||
# 5. Processing (Chunking, Embedding, Edge Generation)
|
||||
# 4. Processing (Chunking, Embedding, Validated Edges)
|
||||
try:
|
||||
body_text = getattr(parsed, "body", "") or ""
|
||||
edge_registry.ensure_latest()
|
||||
|
||||
# Chunker Resolution
|
||||
profile = fm.get("chunk_profile") or fm.get("chunking_profile") or "sliding_standard"
|
||||
chunk_cfg = self._get_chunk_config_by_profile(profile, note_type)
|
||||
enable_smart_edges = chunk_cfg.get("enable_smart_edge_allocation", False)
|
||||
|
||||
# Konfiguration für das spezifische Profil laden
|
||||
chunk_config = self._get_chunk_config_by_profile(effective_profile, note_type)
|
||||
# WP-15b: Chunker bereitet nun den Candidate-Pool vor (inkl. Inheritance).
|
||||
chunks = await assemble_chunks(fm["id"], body_text, fm["type"], config=chunk_cfg)
|
||||
|
||||
chunks = await assemble_chunks(fm["id"], body_text, fm["type"], config=chunk_config)
|
||||
|
||||
# Chunks mit Metadaten anreichern
|
||||
# WP-15b: Validierung NUR für Kandidaten aus dem global_pool (Unzugeordnete Kanten)
|
||||
for ch_obj in chunks:
|
||||
filtered_pool = []
|
||||
for cand in getattr(ch_obj, "candidate_pool", []):
|
||||
# Nur 'global_pool' erfordert LLM-Validierung.
|
||||
# 'explicit' und 'inherited' werden direkt akzeptiert.
|
||||
if cand.get("provenance") == "global_pool" and enable_smart_edges:
|
||||
if await self._validate_candidate(ch_obj.text, cand):
|
||||
filtered_pool.append(cand)
|
||||
else:
|
||||
filtered_pool.append(cand)
|
||||
ch_obj.candidate_pool = filtered_pool
|
||||
|
||||
chunk_pls = make_chunk_payloads(fm, note_pl["path"], chunks, note_text=body_text)
|
||||
|
||||
# Embeddings generieren
|
||||
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}")
|
||||
vecs = await self.embedder.embed_documents(texts)
|
||||
|
||||
# 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
|
||||
# Kanten finalisieren via derive_edges Aggregator (WP-15b kompatibel)
|
||||
# Nutzt das Provenance-Ranking (v2.1.0).
|
||||
edges = build_edges_for_note(
|
||||
note_id,
|
||||
chunk_pls,
|
||||
note_level_references=note_pl.get("references", []),
|
||||
include_note_scope_refs=note_scope_refs
|
||||
)
|
||||
|
||||
# Alias-Auflösung & Registry Enforcement
|
||||
context = {"file": file_path, "note_id": note_id}
|
||||
for e in edges:
|
||||
e["kind"] = edge_registry.resolve(
|
||||
edge_type=e.get("kind", "related_to"),
|
||||
provenance=e.get("provenance", "explicit"),
|
||||
context={**context, "line": e.get("line", "system")}
|
||||
)
|
||||
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)
|
||||
logger.error(f"Processing failed for {file_path}: {e}", exc_info=True)
|
||||
return {**result, "error": f"Processing failed: {str(e)}"}
|
||||
|
||||
# 6. Upsert in Qdrant
|
||||
# 5. DB Upsert
|
||||
try:
|
||||
# Alte Fragmente löschen, um "Geister-Chunks" zu vermeiden
|
||||
if purge_before and has_old:
|
||||
self._purge_artifacts(note_id)
|
||||
if purge_before and old_payload: 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)
|
||||
# v2.11.14 Points-Extraction Logic
|
||||
c_pts = points_for_chunks(self.prefix, chunk_pls, vecs)[1]
|
||||
upsert_batch(self.client, f"{self.prefix}_chunks", c_pts)
|
||||
|
||||
# Kanten
|
||||
if edges:
|
||||
e_name, e_pts = points_for_edges(self.prefix, edges)
|
||||
upsert_batch(self.client, e_name, e_pts)
|
||||
# v2.11.14 Points-Extraction Logic
|
||||
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)
|
||||
}
|
||||
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."""
|
||||
"""Holt die Metadaten 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)
|
||||
pts, _ = self.client.scroll(collection_name=f"{self.prefix}_notes", scroll_filter=f, limit=1, with_payload=True)
|
||||
return pts[0].payload if pts else None
|
||||
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)."""
|
||||
"""Prüft Qdrant aktiv auf vorhandene Chunks und Edges."""
|
||||
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)
|
||||
c_pts, _ = self.client.scroll(collection_name=f"{self.prefix}_chunks", scroll_filter=f, limit=1)
|
||||
e_pts, _ = self.client.scroll(collection_name=f"{self.prefix}_edges", scroll_filter=f, limit=1)
|
||||
return (not bool(c_pts)), (not bool(e_pts))
|
||||
except: return True, True
|
||||
|
||||
def _purge_artifacts(self, note_id: str):
|
||||
"""Löscht alle Chunks und Edges einer Note (vor dem Neu-Schreiben)."""
|
||||
"""Löscht verwaiste Chunks/Edges vor einem Re-Import."""
|
||||
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
|
||||
try: self.client.delete(collection_name=f"{self.prefix}_{suffix}", points_selector=rest.FilterSelector(filter=f))
|
||||
except: 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)."""
|
||||
"""Hilfsmethode zur Erstellung einer Note aus einem Textstream."""
|
||||
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)}"}
|
||||
with open(file_path, "w", encoding="utf-8") as f:
|
||||
f.write(markdown_content)
|
||||
await asyncio.sleep(0.1)
|
||||
return await self.process_file(file_path=file_path, vault_root=vault_root, apply=True, force_replace=True, purge_before=True)
|
||||
+84
-24
@@ -1,10 +1,12 @@
|
||||
"""
|
||||
FILE: app/core/parser.py
|
||||
DESCRIPTION: Liest Markdown-Dateien fehlertolerant (Encoding-Fallback). Trennt Frontmatter (YAML) vom Body.
|
||||
VERSION: 1.7.1
|
||||
WP-22 Erweiterung: Kanten-Extraktion mit Zeilennummern für die EdgeRegistry.
|
||||
WP-15b: Implementierung NoteContext und pre_scan_markdown für Pass 1 Ingestion.
|
||||
VERSION: 1.9.0
|
||||
STATUS: Active
|
||||
DEPENDENCIES: yaml, re, dataclasses, json, io, os
|
||||
LAST_ANALYSIS: 2025-12-15
|
||||
LAST_ANALYSIS: 2025-12-26
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -31,6 +33,15 @@ class ParsedNote:
|
||||
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]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------
|
||||
# Frontmatter-Erkennung
|
||||
@@ -138,13 +149,7 @@ def _read_text_with_fallback(path: str) -> Tuple[str, str, bool]:
|
||||
|
||||
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"}
|
||||
Liest eine Markdown-Datei fehlertolerant.
|
||||
"""
|
||||
if not os.path.exists(path):
|
||||
return None
|
||||
@@ -157,14 +162,36 @@ def read_markdown(path: str) -> Optional[ParsedNote]:
|
||||
return ParsedNote(frontmatter=fm or {}, body=body or "", path=path)
|
||||
|
||||
|
||||
def pre_scan_markdown(path: str) -> Optional[NoteContext]:
|
||||
"""
|
||||
WP-15b: Schneller Scan für den LocalBatchCache (Pass 1).
|
||||
Extrahiert nur Identität und Kurz-Kontext zur semantischen Validierung.
|
||||
"""
|
||||
parsed = read_markdown(path)
|
||||
if not parsed:
|
||||
return None
|
||||
|
||||
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 (erste 500 Zeichen des Body, bereinigt)
|
||||
clean_body = re.sub(r'[#*`>]', '', parsed.body[:600]).strip()
|
||||
summary = clean_body[:500] + "..." if len(clean_body) > 500 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 []
|
||||
)
|
||||
|
||||
|
||||
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 = {}
|
||||
@@ -178,17 +205,13 @@ def validate_required_frontmatter(fm: Dict[str, Any],
|
||||
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
|
||||
Normalisierung von Tags und anderen Feldern.
|
||||
"""
|
||||
out = dict(fm or {})
|
||||
if "tags" in out:
|
||||
@@ -205,15 +228,12 @@ def normalize_frontmatter(fm: Dict[str, Any]) -> Dict[str, Any]:
|
||||
|
||||
# ------------------------------ 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).
|
||||
Extrahiert Wikilinks als einfache Liste von IDs.
|
||||
"""
|
||||
if not text:
|
||||
return []
|
||||
@@ -222,12 +242,52 @@ def extract_wikilinks(text: str) -> List[str]:
|
||||
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
|
||||
|
||||
|
||||
def extract_edges_with_context(parsed: ParsedNote) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
WP-22: Extrahiert Wikilinks [[Ziel|Typ]] aus dem Body und speichert die Zeilennummer.
|
||||
Gibt eine Liste von Dictionaries zurück, die direkt von der Ingestion verarbeitet werden können.
|
||||
"""
|
||||
edges = []
|
||||
if not parsed or not parsed.body:
|
||||
return edges
|
||||
|
||||
# Wir nutzen splitlines(True), um Zeilenumbrüche für die Positionsberechnung zu erhalten,
|
||||
# oder einfaches splitlines() für die reine Zeilennummerierung.
|
||||
lines = parsed.body.splitlines()
|
||||
|
||||
for line_num, line_content in enumerate(lines, 1):
|
||||
for match in _WIKILINK_RE.finditer(line_content):
|
||||
raw = (match.group(1) or "").strip()
|
||||
if not raw:
|
||||
continue
|
||||
|
||||
# Syntax: [[Ziel|Typ]]
|
||||
if "|" in raw:
|
||||
parts = raw.split("|", 1)
|
||||
target = parts[0].strip()
|
||||
kind = parts[1].strip()
|
||||
else:
|
||||
target = raw.strip()
|
||||
kind = "related_to" # Default-Typ
|
||||
|
||||
# Anchor (#) entfernen, da Relationen auf Notiz-Ebene (ID) basieren
|
||||
if "#" in target:
|
||||
target = target.split("#", 1)[0].strip()
|
||||
|
||||
if target:
|
||||
edges.append({
|
||||
"to": target,
|
||||
"kind": kind,
|
||||
"line": line_num,
|
||||
"provenance": "explicit"
|
||||
})
|
||||
return edges
|
||||
+71
-34
@@ -1,10 +1,12 @@
|
||||
"""
|
||||
FILE: app/routers/chat.py
|
||||
DESCRIPTION: Haupt-Chat-Interface (RAG & Interview). Enthält Intent-Router (Keywords/LLM) und Prompt-Construction.
|
||||
VERSION: 2.7.0 (WP-22 Semantic Graph Routing)
|
||||
VERSION: 2.7.8 (Full Unabridged Stability Edition)
|
||||
STATUS: Active
|
||||
DEPENDENCIES: app.config, app.models.dto, app.services.llm_service, app.core.retriever, app.services.feedback_service
|
||||
EXTERNAL_CONFIG: config/decision_engine.yaml, config/types.yaml
|
||||
FIX:
|
||||
1. Implementiert Context-Throttling für Ollama (MAX_OLLAMA_CHARS).
|
||||
2. Deaktiviert LLM-Retries für den Chat (max_retries=0).
|
||||
3. Behebt Double-Fallback-Schleifen und Silent Refusals.
|
||||
"""
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Depends
|
||||
@@ -35,7 +37,7 @@ def _load_decision_config() -> Dict[str, Any]:
|
||||
path = Path(settings.DECISION_CONFIG_PATH)
|
||||
default_config = {
|
||||
"strategies": {
|
||||
"FACT": {"trigger_keywords": []}
|
||||
"FACT": {"trigger_keywords": [], "preferred_provider": "openrouter"}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -158,7 +160,7 @@ def _is_question(query: str) -> bool:
|
||||
q = query.strip().lower()
|
||||
if "?" in q: return True
|
||||
|
||||
# W-Fragen Indikatoren (falls User das ? vergisst)
|
||||
# W-Fragen Indikatoren
|
||||
starters = ["wer", "wie", "was", "wo", "wann", "warum", "weshalb", "wozu", "welche", "bist du", "entspricht"]
|
||||
if any(q.startswith(s + " ") for s in starters):
|
||||
return True
|
||||
@@ -169,7 +171,7 @@ 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!
|
||||
2. Type Keywords (Interview Trigger) -> Prio 2
|
||||
3. LLM (Fallback) -> Prio 3
|
||||
"""
|
||||
config = get_full_config()
|
||||
@@ -178,7 +180,7 @@ async def _classify_intent(query: str, llm: LLMService) -> tuple[str, str]:
|
||||
|
||||
query_lower = query.lower()
|
||||
|
||||
# 1. FAST PATH A: Strategie Keywords (z.B. "Soll ich...")
|
||||
# 1. FAST PATH A: Strategie Keywords
|
||||
for intent_name, strategy in strategies.items():
|
||||
if intent_name == "FACT": continue
|
||||
keywords = strategy.get("trigger_keywords", [])
|
||||
@@ -186,7 +188,7 @@ async def _classify_intent(query: str, llm: LLMService) -> tuple[str, str]:
|
||||
if k.lower() in query_lower:
|
||||
return intent_name, "Keyword (Strategy)"
|
||||
|
||||
# 2. FAST PATH B: Type Keywords (z.B. "Projekt", "Werte") -> INTERVIEW
|
||||
# 2. FAST PATH B: Type Keywords -> INTERVIEW
|
||||
if not _is_question(query_lower):
|
||||
types_cfg = get_types_config()
|
||||
types_def = types_cfg.get("types", {})
|
||||
@@ -199,14 +201,15 @@ async def _classify_intent(query: str, llm: LLMService) -> tuple[str, str]:
|
||||
|
||||
# 3. SLOW PATH: LLM Router
|
||||
if settings.get("llm_fallback_enabled", False):
|
||||
router_prompt_template = llm.prompts.get("router_prompt", "")
|
||||
router_prompt_template = llm.get_prompt("llm_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")
|
||||
# FIX: Auch beim Routing keine Retries im Chat-Fluss
|
||||
raw_response = await llm.generate_raw_response(prompt, priority="realtime", max_retries=0)
|
||||
llm_output_upper = raw_response.upper()
|
||||
|
||||
if "INTERVIEW" in llm_output_upper or "CREATE" in llm_output_upper:
|
||||
@@ -239,9 +242,11 @@ async def chat_endpoint(
|
||||
# Strategy Load
|
||||
strategy = get_decision_strategy(intent)
|
||||
prompt_key = strategy.get("prompt_template", "rag_template")
|
||||
preferred_provider = strategy.get("preferred_provider")
|
||||
|
||||
sources_hits = []
|
||||
final_prompt = ""
|
||||
context_str = ""
|
||||
|
||||
if intent == "INTERVIEW":
|
||||
# --- INTERVIEW MODE ---
|
||||
@@ -262,7 +267,7 @@ async def chat_endpoint(
|
||||
logger.info(f"[{query_id}] Interview Type: {target_type}. Fields: {len(fields_list)}")
|
||||
fields_str = "\n- " + "\n- ".join(fields_list)
|
||||
|
||||
template = llm.prompts.get(prompt_key, "")
|
||||
template = llm.get_prompt(prompt_key)
|
||||
final_prompt = template.replace("{context_str}", "Dialogverlauf...") \
|
||||
.replace("{query}", request.message) \
|
||||
.replace("{target_type}", target_type) \
|
||||
@@ -271,22 +276,16 @@ async def chat_endpoint(
|
||||
sources_hits = []
|
||||
|
||||
else:
|
||||
# --- RAG MODE ---
|
||||
# --- RAG MODE (FACT, DECISION, EMPATHY, CODING) ---
|
||||
inject_types = strategy.get("inject_types", [])
|
||||
prepend_instr = strategy.get("prepend_instruction", "")
|
||||
|
||||
# --- WP-22: Semantic Graph Routing (Teil C) ---
|
||||
# Wir laden die konfigurierten Edge-Boosts für diesen Intent
|
||||
edge_boosts = strategy.get("edge_boosts", {})
|
||||
if edge_boosts:
|
||||
logger.info(f"[{query_id}] Applying Edge Boosts: {edge_boosts}")
|
||||
|
||||
query_req = QueryRequest(
|
||||
query=request.message,
|
||||
mode="hybrid",
|
||||
top_k=request.top_k,
|
||||
explain=request.explain,
|
||||
# WP-22: Boosts an den Retriever weitergeben
|
||||
boost_edges=edge_boosts
|
||||
)
|
||||
retrieve_result = await retriever.search(query_req)
|
||||
@@ -299,7 +298,6 @@ async def chat_endpoint(
|
||||
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)
|
||||
@@ -308,12 +306,19 @@ async def chat_endpoint(
|
||||
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)
|
||||
context_str = _build_enriched_context(hits) if hits else "Keine relevanten Notizen gefunden."
|
||||
|
||||
# --- STABILITY FIX: OLLAMA CONTEXT THROTTLE ---
|
||||
# Begrenzt den Text, um den "decode: cannot decode batches" Fehler zu vermeiden.
|
||||
# MAX_OLLAMA_CHARS = 10000
|
||||
|
||||
template = llm.prompts.get(prompt_key, "{context_str}\n\n{query}")
|
||||
settings = get_settings() # Falls noch nicht im Scope vorhanden
|
||||
max_chars = getattr(settings, "MAX_OLLAMA_CHARS", 10000)
|
||||
if preferred_provider == "ollama" and len(context_str) > max_chars:
|
||||
logger.warning(f"⚠️ [{query_id}] Context zu groß für Ollama ({len(context_str)} chars). Kürze auf {max_chars}.")
|
||||
context_str = context_str[:max_chars] + "\n[...gekürzt zur Stabilität...]"
|
||||
|
||||
template = llm.get_prompt(prompt_key) or "{context_str}\n\n{query}"
|
||||
|
||||
if prepend_instr:
|
||||
context_str = f"{prepend_instr}\n\n{context_str}"
|
||||
@@ -321,15 +326,46 @@ async def chat_endpoint(
|
||||
final_prompt = template.replace("{context_str}", context_str).replace("{query}", request.message)
|
||||
sources_hits = hits
|
||||
|
||||
# --- GENERATION ---
|
||||
system_prompt = llm.prompts.get("system_prompt", "")
|
||||
# --- DEBUG SPOT 1: PROMPT CONSTRUCTION ---
|
||||
logger.info(f"[{query_id}] PROMPT CONSTRUCTION COMPLETE. Length: {len(final_prompt)} chars.")
|
||||
if not final_prompt.strip():
|
||||
logger.error(f"[{query_id}] CRITICAL: Final prompt is empty before sending to LLM!")
|
||||
|
||||
# --- GENERATION WITH NO-RETRY & DEEP FALLBACK ---
|
||||
system_prompt = llm.get_prompt("system_prompt")
|
||||
|
||||
# Chat nutzt IMMER realtime priority
|
||||
answer_text = await llm.generate_raw_response(
|
||||
prompt=final_prompt,
|
||||
system=system_prompt,
|
||||
priority="realtime"
|
||||
)
|
||||
# --- DEBUG SPOT 2: PRIMARY CALL ---
|
||||
logger.info(f"[{query_id}] PRIMARY CALL: Sending request to provider '{preferred_provider}' (No Retries)...")
|
||||
|
||||
answer_text = ""
|
||||
try:
|
||||
# FIX: max_retries=0 verhindert Hänger durch Retry-Kaskaden im Chat
|
||||
answer_text = await llm.generate_raw_response(
|
||||
prompt=final_prompt,
|
||||
system=system_prompt,
|
||||
priority="realtime",
|
||||
provider=preferred_provider,
|
||||
max_retries=0
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"🛑 [{query_id}] Primary Provider '{preferred_provider}' failed: {e}")
|
||||
|
||||
# DEEP FALLBACK: Wenn die Antwort leer ist (Silent Refusal) oder der Primary abgestürzt ist
|
||||
if not answer_text.strip() and preferred_provider != "ollama":
|
||||
# --- DEBUG SPOT 3: FALLBACK TRIGGER ---
|
||||
logger.warning(f"🛑 [{query_id}] PRIMARY '{preferred_provider}' returned EMPTY or FAILED. Triggering Deep Fallback to Ollama...")
|
||||
|
||||
try:
|
||||
answer_text = await llm.generate_raw_response(
|
||||
prompt=final_prompt,
|
||||
system=system_prompt,
|
||||
priority="realtime",
|
||||
provider="ollama",
|
||||
max_retries=0
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"🛑 [{query_id}] Deep Fallback to Ollama also failed: {e}")
|
||||
answer_text = "Entschuldigung, das System ist aktuell überlastet. Bitte versuche es in einem Moment erneut."
|
||||
|
||||
duration_ms = int((time.time() - start_time) * 1000)
|
||||
|
||||
@@ -340,7 +376,7 @@ async def chat_endpoint(
|
||||
query_text=request.message,
|
||||
results=sources_hits,
|
||||
mode="interview" if intent == "INTERVIEW" else "chat_rag",
|
||||
metadata={"intent": intent, "source": intent_source}
|
||||
metadata={"intent": intent, "source": intent_source, "provider": preferred_provider}
|
||||
)
|
||||
except: pass
|
||||
|
||||
@@ -355,4 +391,5 @@ async def chat_endpoint(
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error in chat endpoint: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
# Wir geben eine benutzerfreundliche Meldung zurück, statt nur den Error-Stack
|
||||
raise HTTPException(status_code=500, detail="Das System konnte die Anfrage nicht verarbeiten.")
|
||||
+10
-6
@@ -1,8 +1,9 @@
|
||||
"""
|
||||
FILE: app/routers/ingest.py
|
||||
DESCRIPTION: Endpunkte für WP-11. Nimmt Markdown entgegen.
|
||||
Refactored für WP-14: Nutzt BackgroundTasks für non-blocking Save.
|
||||
VERSION: 0.7.0 (Fix: Timeout WP-14)
|
||||
Refactored für WP-14: Nutzt BackgroundTasks für non-blocking Save.
|
||||
Update WP-20: Unterstützung für Hybrid-Cloud-Analyse Feedback.
|
||||
VERSION: 0.8.0 (WP-20 Hybrid Ready)
|
||||
STATUS: Active
|
||||
DEPENDENCIES: app.core.ingestion, app.services.discovery, fastapi, pydantic
|
||||
"""
|
||||
@@ -44,6 +45,7 @@ class SaveResponse(BaseModel):
|
||||
async def run_ingestion_task(markdown_content: str, filename: str, vault_root: str, folder: str):
|
||||
"""
|
||||
Führt die Ingestion im Hintergrund aus, damit der Request nicht blockiert.
|
||||
Integrierter WP-20 Hybrid-Modus über den IngestionService.
|
||||
"""
|
||||
logger.info(f"🔄 Background Task started: Ingesting {filename}...")
|
||||
try:
|
||||
@@ -80,15 +82,17 @@ async def analyze_draft(req: AnalyzeRequest):
|
||||
async def save_note(req: SaveRequest, background_tasks: BackgroundTasks):
|
||||
"""
|
||||
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:
|
||||
vault_root = os.getenv("MINDNET_VAULT_ROOT", "./vault")
|
||||
abs_vault_root = os.path.abspath(vault_root)
|
||||
|
||||
if not os.path.exists(abs_vault_root):
|
||||
try: os.makedirs(abs_vault_root, exist_ok=True)
|
||||
except: pass
|
||||
try:
|
||||
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"
|
||||
|
||||
@@ -109,7 +113,7 @@ async def save_note(req: SaveRequest, background_tasks: BackgroundTasks):
|
||||
status="queued",
|
||||
file_path=os.path.join(req.folder, final_filename),
|
||||
note_id="pending",
|
||||
message="Speicherung & KI-Analyse im Hintergrund gestartet.",
|
||||
message="Speicherung & Hybrid-KI-Analyse (WP-20) im Hintergrund gestartet.",
|
||||
stats={
|
||||
"chunks": -1, # Indikator für Async
|
||||
"edges": -1
|
||||
|
||||
@@ -1,23 +1,34 @@
|
||||
"""
|
||||
FILE: app/services/edge_registry.py
|
||||
DESCRIPTION: Single Source of Truth für Kanten-Typen.
|
||||
FIX: Regex angepasst auf Format **`canonical`** (Bold + Backticks).
|
||||
VERSION: 0.6.10 (Regex Precision Update)
|
||||
DESCRIPTION: Single Source of Truth für Kanten-Typen mit dynamischem Reload.
|
||||
WP-15b: Erweiterte Provenance-Prüfung für die Candidate-Validation.
|
||||
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 os
|
||||
import json
|
||||
import logging
|
||||
from typing import Dict, Optional, Set
|
||||
|
||||
print(">>> MODULE_LOAD: edge_registry.py initialized <<<", flush=True)
|
||||
import time
|
||||
from typing import Dict, Optional, Set, Tuple
|
||||
|
||||
from app.config import get_settings
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
class EdgeRegistry:
|
||||
"""
|
||||
Zentraler Verwalter für das Kanten-Vokabular.
|
||||
Implementiert das Singleton-Pattern für konsistente Validierung über alle Services.
|
||||
"""
|
||||
_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):
|
||||
if cls._instance is None:
|
||||
@@ -25,39 +36,52 @@ class EdgeRegistry:
|
||||
cls._instance.initialized = False
|
||||
return cls._instance
|
||||
|
||||
def __init__(self, vault_root: Optional[str] = None):
|
||||
def __init__(self):
|
||||
if self.initialized:
|
||||
return
|
||||
|
||||
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:
|
||||
self.full_vocab_path = os.path.abspath(env_vocab_path)
|
||||
else:
|
||||
self.full_vocab_path = os.path.abspath(
|
||||
os.path.join(env_vault_root, "01_User_Manual", "01_edge_vocabulary.md")
|
||||
)
|
||||
# 1. Pfad aus den zentralen Settings laden (WP-20 Synchronisation)
|
||||
# Priorisiert den Pfad aus der .env / config.py (v0.6.2)
|
||||
self.full_vocab_path = os.path.abspath(settings.MINDNET_VOCAB_PATH)
|
||||
|
||||
self.unknown_log_path = "data/logs/unknown_edges.jsonl"
|
||||
self.canonical_map: Dict[str, str] = {}
|
||||
self.valid_types: Set[str] = set()
|
||||
self._last_mtime = 0.0
|
||||
|
||||
self._load_vocabulary()
|
||||
# Initialer Ladevorgang
|
||||
logger.info(f">>> [EDGE-REGISTRY] Initializing with Path: {self.full_vocab_path}")
|
||||
self.ensure_latest()
|
||||
self.initialized = True
|
||||
|
||||
def _load_vocabulary(self):
|
||||
"""Parst die Markdown-Tabelle im Vault."""
|
||||
print(f">>> CHECK: Loading Vocabulary from {self.full_vocab_path}", flush=True)
|
||||
|
||||
def ensure_latest(self):
|
||||
"""
|
||||
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):
|
||||
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
|
||||
|
||||
# WP-22 Precision Regex:
|
||||
# Sucht nach | **`typ`** | oder | **typ** |
|
||||
# Die Backticks `? sind jetzt optional enthalten.
|
||||
try:
|
||||
current_mtime = os.path.getmtime(self.full_vocab_path)
|
||||
if current_mtime > self._last_mtime:
|
||||
self._load_vocabulary()
|
||||
self._last_mtime = current_mtime
|
||||
except Exception as e:
|
||||
logger.error(f"!!! [EDGE-REGISTRY] Error checking file time: {e}")
|
||||
|
||||
def _load_vocabulary(self):
|
||||
"""
|
||||
Parst das Markdown-Wörterbuch und baut die Canonical-Map auf.
|
||||
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*([^|]+)\|")
|
||||
|
||||
try:
|
||||
@@ -74,38 +98,68 @@ class EdgeRegistry:
|
||||
c_types += 1
|
||||
|
||||
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()]
|
||||
for alias in aliases:
|
||||
# Normalisierung: Kleinschreibung, Underscores statt Leerzeichen
|
||||
clean_alias = alias.replace("`", "").lower().strip().replace(" ", "_")
|
||||
self.canonical_map[clean_alias] = canonical
|
||||
c_aliases += 1
|
||||
|
||||
if c_types == 0:
|
||||
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)
|
||||
logger.info(f"=== [EDGE-REGISTRY SUCCESS] Loaded {c_types} Canonical Types and {c_aliases} Aliases ===")
|
||||
|
||||
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:
|
||||
"""Normalisiert Kanten-Typen via Registry oder loggt Unbekannte."""
|
||||
if not edge_type: return "related_to"
|
||||
clean_type = edge_type.lower().strip().replace(" ", "_").replace("-", "_")
|
||||
def resolve(self, edge_type: str, provenance: str = "explicit", context: dict = None) -> str:
|
||||
"""
|
||||
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("-", "_")
|
||||
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:
|
||||
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
|
||||
|
||||
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:
|
||||
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:
|
||||
f.write(json.dumps(entry) + "\n")
|
||||
except Exception: pass
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# Singleton Export für systemweiten Zugriff
|
||||
registry = EdgeRegistry()
|
||||
+244
-82
@@ -1,147 +1,309 @@
|
||||
"""
|
||||
FILE: app/services/llm_service.py
|
||||
DESCRIPTION: Asynchroner Client für Ollama. Verwaltet Prompts und Background-Last (Semaphore).
|
||||
VERSION: 2.8.0
|
||||
DESCRIPTION: Hybrid-Client für Ollama, Google GenAI (Gemini) und OpenRouter.
|
||||
Verwaltet provider-spezifische Prompts und Background-Last.
|
||||
WP-20: Optimiertes Fallback-Management zum Schutz von Cloud-Quoten.
|
||||
WP-20 Fix: Bulletproof Prompt-Auflösung für format() Aufrufe.
|
||||
WP-22/JSON: Optionales JSON-Schema + strict (für OpenRouter structured outputs).
|
||||
FIX: Intelligente Rate-Limit Erkennung (429 Handling), v1-API Sync & Timeouts.
|
||||
VERSION: 3.3.7
|
||||
STATUS: Active
|
||||
DEPENDENCIES: httpx, yaml, asyncio, app.config
|
||||
EXTERNAL_CONFIG: config/prompts.yaml
|
||||
LAST_ANALYSIS: 2025-12-15
|
||||
FIX:
|
||||
- Implementiert striktes max_retries Handling für alle Provider (v.a. für Chat-Stabilität).
|
||||
- Synchronisiert Rate-Limit Retries mit dem max_retries Parameter.
|
||||
- Optimiert Logging für sofortige Fehlererkennung.
|
||||
"""
|
||||
|
||||
import httpx
|
||||
import yaml
|
||||
import logging
|
||||
import os
|
||||
import asyncio
|
||||
import json
|
||||
from google import genai
|
||||
from google.genai import types
|
||||
from openai import AsyncOpenAI # Für OpenRouter (OpenAI-kompatibel)
|
||||
from pathlib import Path
|
||||
from typing import Optional, Dict, Any, Literal
|
||||
from app.config import get_settings
|
||||
|
||||
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:
|
||||
# GLOBALER SEMAPHOR (Lazy Initialization)
|
||||
# Wir initialisieren ihn erst, wenn wir die Settings kennen.
|
||||
# GLOBALER SEMAPHOR für Hintergrund-Last Steuerung (WP-06)
|
||||
_background_semaphore = None
|
||||
|
||||
def __init__(self):
|
||||
self.settings = get_settings()
|
||||
self.prompts = self._load_prompts()
|
||||
|
||||
# Initialisiere Semaphore einmalig auf Klassen-Ebene basierend auf Config
|
||||
|
||||
# Initialisiere Semaphore einmalig auf Klassen-Ebene
|
||||
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}")
|
||||
LLMService._background_semaphore = asyncio.Semaphore(limit)
|
||||
|
||||
self.timeout = httpx.Timeout(self.settings.LLM_TIMEOUT, connect=10.0)
|
||||
|
||||
self.client = httpx.AsyncClient(
|
||||
base_url=self.settings.OLLAMA_URL,
|
||||
timeout=self.timeout
|
||||
|
||||
# 1. Lokaler Ollama Client
|
||||
self.ollama_client = httpx.AsyncClient(
|
||||
base_url=self.settings.OLLAMA_URL,
|
||||
timeout=httpx.Timeout(self.settings.LLM_TIMEOUT)
|
||||
)
|
||||
|
||||
# 2. Google GenAI Client (Modern SDK)
|
||||
self.google_client = None
|
||||
if self.settings.GOOGLE_API_KEY:
|
||||
# FIX: Wir erzwingen api_version 'v1' für höhere Stabilität bei 2.5er Modellen.
|
||||
self.google_client = genai.Client(
|
||||
api_key=self.settings.GOOGLE_API_KEY,
|
||||
http_options={'api_version': 'v1'}
|
||||
)
|
||||
logger.info("✨ LLMService: Google GenAI (Gemini) active.")
|
||||
|
||||
# 3. OpenRouter Client
|
||||
self.openrouter_client = None
|
||||
if self.settings.OPENROUTER_API_KEY:
|
||||
self.openrouter_client = AsyncOpenAI(
|
||||
base_url="https://openrouter.ai/api/v1",
|
||||
api_key=self.settings.OPENROUTER_API_KEY,
|
||||
# Strikter Timeout für OpenRouter Free-Tier zur Vermeidung von Hangs.
|
||||
timeout=45.0
|
||||
)
|
||||
logger.info("🛰️ LLMService: OpenRouter Integration active.")
|
||||
|
||||
def _load_prompts(self) -> dict:
|
||||
"""Lädt die Prompt-Konfiguration aus der YAML-Datei."""
|
||||
path = Path(self.settings.PROMPTS_PATH)
|
||||
if not path.exists(): return {}
|
||||
if not path.exists():
|
||||
logger.error(f"❌ Prompts file not found at {path}")
|
||||
return {}
|
||||
try:
|
||||
with open(path, "r", encoding="utf-8") as f: return yaml.safe_load(f)
|
||||
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}")
|
||||
logger.error(f"❌ Failed to load prompts: {e}")
|
||||
return {}
|
||||
|
||||
def get_prompt(self, key: str, provider: str = None) -> str:
|
||||
"""
|
||||
Hole provider-spezifisches Template mit intelligenter Text-Kaskade.
|
||||
HINWEIS: Dies ist nur ein Text-Lookup und verbraucht kein API-Kontingent.
|
||||
Kaskade: Gewählter Provider -> Gemini (Cloud-Stil) -> Ollama (Basis-Stil).
|
||||
"""
|
||||
active_provider = provider or self.settings.MINDNET_LLM_PROVIDER
|
||||
data = self.prompts.get(key, "")
|
||||
|
||||
if isinstance(data, dict):
|
||||
# Wir versuchen erst den Provider, dann Gemini, dann Ollama
|
||||
val = data.get(active_provider, data.get("gemini", data.get("ollama", "")))
|
||||
|
||||
# Falls val durch YAML-Fehler immer noch ein Dict ist, extrahiere ersten String
|
||||
if isinstance(val, dict):
|
||||
logger.warning(f"⚠️ [LLMService] Nested dictionary detected for key '{key}'. Using first entry.")
|
||||
val = next(iter(val.values()), "") if val else ""
|
||||
return str(val)
|
||||
|
||||
return str(data)
|
||||
|
||||
async def generate_raw_response(
|
||||
self,
|
||||
prompt: str,
|
||||
system: str = None,
|
||||
self,
|
||||
prompt: str,
|
||||
system: str = None,
|
||||
force_json: bool = False,
|
||||
max_retries: int = 0,
|
||||
max_retries: int = 2,
|
||||
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
|
||||
) -> str:
|
||||
"""
|
||||
Führt einen LLM Call aus.
|
||||
priority="realtime": Chat (Sofort, keine Bremse).
|
||||
priority="background": Import/Analyse (Gedrosselt durch Semaphore).
|
||||
Haupteinstiegspunkt für LLM-Anfragen mit Priorisierung.
|
||||
"""
|
||||
|
||||
use_semaphore = (priority == "background")
|
||||
|
||||
if use_semaphore and LLMService._background_semaphore:
|
||||
async with LLMService._background_semaphore:
|
||||
return await self._execute_request(prompt, system, force_json, max_retries, base_delay)
|
||||
else:
|
||||
# Realtime oder Fallback (falls Semaphore Init fehlschlug)
|
||||
return await self._execute_request(prompt, system, force_json, max_retries, base_delay)
|
||||
target_provider = provider or self.settings.MINDNET_LLM_PROVIDER
|
||||
|
||||
async def _execute_request(self, prompt, system, force_json, max_retries, base_delay):
|
||||
payload: Dict[str, Any] = {
|
||||
if priority == "background":
|
||||
async with LLMService._background_semaphore:
|
||||
return await self._dispatch(
|
||||
target_provider, prompt, system, force_json,
|
||||
max_retries, base_delay, model_override,
|
||||
json_schema, json_schema_name, strict_json_schema
|
||||
)
|
||||
|
||||
return await self._dispatch(
|
||||
target_provider, prompt, system, force_json,
|
||||
max_retries, base_delay, model_override,
|
||||
json_schema, json_schema_name, strict_json_schema
|
||||
)
|
||||
|
||||
async def _dispatch(
|
||||
self,
|
||||
provider: str,
|
||||
prompt: str,
|
||||
system: Optional[str],
|
||||
force_json: bool,
|
||||
max_retries: int,
|
||||
base_delay: float,
|
||||
model_override: Optional[str],
|
||||
json_schema: Optional[Dict[str, Any]],
|
||||
json_schema_name: str,
|
||||
strict_json_schema: bool
|
||||
) -> str:
|
||||
"""
|
||||
Routet die Anfrage mit intelligenter Rate-Limit Erkennung.
|
||||
Nutzt max_retries um die Rate-Limit Schleife zu begrenzen.
|
||||
"""
|
||||
rate_limit_attempts = 0
|
||||
# FIX: Wir nutzen max_retries als Limit für Rate-Limit Versuche, wenn explizit klein gewählt (z.B. Chat)
|
||||
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
|
||||
)
|
||||
|
||||
if provider == "gemini" and self.google_client:
|
||||
return await self._execute_google(prompt, system, force_json, model_override)
|
||||
|
||||
# Default/Fallback zu Ollama
|
||||
return await self._execute_ollama(prompt, system, force_json, max_retries, base_delay)
|
||||
|
||||
except Exception as e:
|
||||
err_str = str(e)
|
||||
# Intelligente 429 Erkennung
|
||||
is_rate_limit = any(x in err_str for x in ["429", "RESOURCE_EXHAUSTED", "rate_limited", "Too Many Requests"])
|
||||
|
||||
if is_rate_limit and rate_limit_attempts < max_rate_retries:
|
||||
rate_limit_attempts += 1
|
||||
logger.warning(
|
||||
f"⏳ [LLMService] Rate Limit detected from {provider}. "
|
||||
f"Attempt {rate_limit_attempts}/{max_rate_retries}. Waiting {wait_time}s..."
|
||||
)
|
||||
await asyncio.sleep(wait_time)
|
||||
continue
|
||||
|
||||
# Wenn kein Rate-Limit oder Retries erschöpft -> Fallback zu Ollama (falls aktiviert)
|
||||
if self.settings.LLM_FALLBACK_ENABLED and provider != "ollama":
|
||||
logger.warning(
|
||||
f"🔄 Provider {provider} failed ({err_str}). Falling back to LOCAL OLLAMA."
|
||||
)
|
||||
return await self._execute_ollama(prompt, system, force_json, max_retries, base_delay)
|
||||
raise e
|
||||
|
||||
async def _execute_google(self, prompt, system, force_json, model_override):
|
||||
"""Native Google SDK Integration (Gemini) mit v1 Fix."""
|
||||
model = model_override or self.settings.GEMINI_MODEL
|
||||
clean_model = model.replace("models/", "")
|
||||
|
||||
config = types.GenerateContentConfig(
|
||||
system_instruction=system,
|
||||
response_mime_type="application/json" if force_json else "text/plain"
|
||||
)
|
||||
response = await asyncio.wait_for(
|
||||
asyncio.to_thread(
|
||||
self.google_client.models.generate_content,
|
||||
model=clean_model, contents=prompt, config=config
|
||||
),
|
||||
timeout=45.0
|
||||
)
|
||||
return response.text.strip()
|
||||
|
||||
async def _execute_openrouter(
|
||||
self,
|
||||
prompt: str,
|
||||
system: Optional[str],
|
||||
force_json: bool,
|
||||
model_override: Optional[str],
|
||||
json_schema: Optional[Dict[str, Any]] = None,
|
||||
json_schema_name: str = "mindnet_json",
|
||||
strict_json_schema: bool = True
|
||||
) -> str:
|
||||
"""OpenRouter API Integration (OpenAI-kompatibel)."""
|
||||
model = model_override or self.settings.OPENROUTER_MODEL
|
||||
messages = []
|
||||
if system:
|
||||
messages.append({"role": "system", "content": system})
|
||||
messages.append({"role": "user", "content": prompt})
|
||||
|
||||
kwargs: Dict[str, Any] = {}
|
||||
if force_json:
|
||||
if json_schema:
|
||||
kwargs["response_format"] = {
|
||||
"type": "json_schema",
|
||||
"json_schema": {
|
||||
"name": json_schema_name,
|
||||
"strict": strict_json_schema,
|
||||
"schema": json_schema
|
||||
}
|
||||
}
|
||||
else:
|
||||
kwargs["response_format"] = {"type": "json_object"}
|
||||
|
||||
response = await self.openrouter_client.chat.completions.create(
|
||||
model=model,
|
||||
messages=messages,
|
||||
**kwargs
|
||||
)
|
||||
return response.choices[0].message.content.strip()
|
||||
|
||||
async def _execute_ollama(self, prompt, system, force_json, max_retries, base_delay):
|
||||
"""Lokaler Ollama Call mit striktem Retry-Limit."""
|
||||
payload = {
|
||||
"model": self.settings.LLM_MODEL,
|
||||
"prompt": prompt,
|
||||
"stream": False,
|
||||
"options": {
|
||||
"temperature": 0.1 if force_json else 0.7,
|
||||
"num_ctx": 8192
|
||||
"temperature": 0.1 if force_json else 0.7,
|
||||
"num_ctx": 8192 # Begrenzung für Stabilität (WP-20)
|
||||
}
|
||||
}
|
||||
|
||||
if force_json:
|
||||
payload["format"] = "json"
|
||||
|
||||
payload["format"] = "json"
|
||||
if system:
|
||||
payload["system"] = system
|
||||
|
||||
attempt = 0
|
||||
|
||||
while True:
|
||||
try:
|
||||
response = await self.client.post("/api/generate", json=payload)
|
||||
|
||||
if response.status_code == 200:
|
||||
data = response.json()
|
||||
return data.get("response", "").strip()
|
||||
else:
|
||||
response.raise_for_status()
|
||||
|
||||
res = await self.ollama_client.post("/api/generate", json=payload)
|
||||
res.raise_for_status()
|
||||
return res.json().get("response", "").strip()
|
||||
except Exception as e:
|
||||
attempt += 1
|
||||
# WICHTIG: Wenn max_retries=0 (Chat), bricht dies nach dem 1. Versuch (attempt=1) sofort ab.
|
||||
if attempt > max_retries:
|
||||
logger.error(f"LLM Final Error (Versuch {attempt}): {e}")
|
||||
raise e
|
||||
logger.error(f"❌ Ollama request failed after {attempt} attempt(s): {e}")
|
||||
raise e
|
||||
|
||||
wait_time = base_delay * (2 ** (attempt - 1))
|
||||
logger.warning(f"⚠️ LLM Retry ({attempt}/{max_retries}) in {wait_time}s: {e}")
|
||||
logger.warning(f"⚠️ Ollama attempt {attempt} failed. Retrying in {wait_time}s...")
|
||||
await asyncio.sleep(wait_time)
|
||||
|
||||
async def generate_rag_response(self, query: str, context_str: str) -> str:
|
||||
"""
|
||||
Chat-Wrapper: Immer Realtime.
|
||||
"""
|
||||
system_prompt = self.prompts.get("system_prompt", "")
|
||||
rag_template = self.prompts.get("rag_template", "{context_str}\n\n{query}")
|
||||
|
||||
"""Vollständiges RAG Chat-Interface."""
|
||||
provider = self.settings.MINDNET_LLM_PROVIDER
|
||||
system_prompt = self.get_prompt("system_prompt", provider)
|
||||
rag_template = self.get_prompt("rag_template", provider)
|
||||
|
||||
final_prompt = rag_template.format(context_str=context_str, query=query)
|
||||
|
||||
|
||||
# RAG Aufrufe im Chat nutzen nun standardmäßig max_retries=2 (überschreibbar)
|
||||
return await self.generate_raw_response(
|
||||
final_prompt,
|
||||
system=system_prompt,
|
||||
max_retries=0,
|
||||
force_json=False,
|
||||
final_prompt,
|
||||
system=system_prompt,
|
||||
priority="realtime"
|
||||
)
|
||||
|
||||
async def close(self):
|
||||
if self.client:
|
||||
await self.client.aclose()
|
||||
"""Schließt die HTTP-Verbindungen."""
|
||||
if self.ollama_client:
|
||||
await self.ollama_client.aclose()
|
||||
@@ -1,19 +1,24 @@
|
||||
"""
|
||||
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)
|
||||
WP-20 Fix: Volle Kompatibilität mit der provider-basierten Routing-Logik (OpenRouter Primary).
|
||||
WP-22: Integration von valid_types zur Halluzinations-Vermeidung.
|
||||
FIX: Mistral-sicheres JSON-Parsing (<s> & [OUT] Handling) und 100% Logik-Erhalt.
|
||||
VERSION: 2.2.6
|
||||
STATUS: Active
|
||||
DEPENDENCIES: app.services.llm_service, json, logging
|
||||
LAST_ANALYSIS: 2025-12-16
|
||||
DEPENDENCIES: app.services.llm_service, app.services.edge_registry, json, logging, re
|
||||
"""
|
||||
|
||||
import json
|
||||
import logging
|
||||
from typing import List, Optional
|
||||
import re
|
||||
from typing import List, Optional, Any
|
||||
from dataclasses import dataclass
|
||||
|
||||
# Importe
|
||||
from app.services.llm_service import LLMService
|
||||
# WP-22: Registry für Vokabular-Erzwingung
|
||||
from app.services.edge_registry import registry as edge_registry
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -24,7 +29,7 @@ class SemanticAnalyzer:
|
||||
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.
|
||||
Verhindert, dass LLM-Geschwätz als Kante durchrutscht.
|
||||
"""
|
||||
if not isinstance(edge_str, str) or ":" not in edge_str:
|
||||
return False
|
||||
@@ -34,12 +39,10 @@ class SemanticAnalyzer:
|
||||
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
|
||||
# Regel 2: Plausible Länge für den Typ (Vermeidet Sätze als Typ)
|
||||
if len(kind) > 40 or len(kind) < 2:
|
||||
return False
|
||||
|
||||
@@ -49,24 +52,61 @@ class SemanticAnalyzer:
|
||||
|
||||
return True
|
||||
|
||||
def _extract_json_safely(self, text: str) -> Any:
|
||||
"""
|
||||
Extrahiert JSON-Daten und bereinigt LLM-Steuerzeichen (Mistral/Llama).
|
||||
Implementiert robuste Recovery-Logik für Cloud-Provider.
|
||||
"""
|
||||
if not text:
|
||||
return []
|
||||
|
||||
# 1. Entferne Mistral/Llama Steuerzeichen und Tags
|
||||
clean = text.replace("<s>", "").replace("</s>", "")
|
||||
clean = clean.replace("[OUT]", "").replace("[/OUT]", "")
|
||||
clean = clean.strip()
|
||||
|
||||
# 2. Suche nach Markdown JSON-Blöcken
|
||||
match = re.search(r"```(?:json)?\s*(.*?)\s*```", clean, re.DOTALL)
|
||||
payload = match.group(1) if match else clean
|
||||
|
||||
try:
|
||||
return json.loads(payload.strip())
|
||||
except json.JSONDecodeError:
|
||||
# 3. Recovery: Suche nach der ersten [ und letzten ]
|
||||
start = payload.find('[')
|
||||
end = payload.rfind(']') + 1
|
||||
if start != -1 and end > start:
|
||||
try:
|
||||
return json.loads(payload[start:end])
|
||||
except: pass
|
||||
|
||||
# 4. Zweite Recovery: Suche nach der ersten { und letzten }
|
||||
start_obj = payload.find('{')
|
||||
end_obj = payload.rfind('}') + 1
|
||||
if start_obj != -1 and end_obj > start_obj:
|
||||
try:
|
||||
return json.loads(payload[start_obj:end_obj])
|
||||
except: pass
|
||||
return []
|
||||
|
||||
async def assign_edges_to_chunk(self, chunk_text: str, all_edges: List[str], note_type: str) -> List[str]:
|
||||
"""
|
||||
Sendet einen Chunk und eine Liste potenzieller Kanten an das LLM.
|
||||
Das LLM filtert heraus, welche Kanten für diesen Chunk relevant sind.
|
||||
|
||||
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.
|
||||
WP-20: Nutzt primär den konfigurierten Provider (z.B. OpenRouter).
|
||||
"""
|
||||
if not all_edges:
|
||||
return []
|
||||
|
||||
# 1. Prompt laden
|
||||
prompt_template = self.llm.prompts.get("edge_allocation_template")
|
||||
# 1. Bestimmung des Providers und Modells (Dynamisch über Settings)
|
||||
provider = self.llm.settings.MINDNET_LLM_PROVIDER
|
||||
model = self.llm.settings.OPENROUTER_MODEL if provider == "openrouter" else self.llm.settings.GEMINI_MODEL
|
||||
|
||||
# 2. Prompt laden (Provider-spezifisch via get_prompt)
|
||||
prompt_template = self.llm.get_prompt("edge_allocation_template", provider)
|
||||
|
||||
if not prompt_template:
|
||||
logger.warning("⚠️ [SemanticAnalyzer] Prompt 'edge_allocation_template' fehlt. Nutze Fallback.")
|
||||
if not prompt_template or not isinstance(prompt_template, str):
|
||||
logger.warning("⚠️ [SemanticAnalyzer] Prompt 'edge_allocation_template' ungültig. Nutze Recovery-Template.")
|
||||
prompt_template = (
|
||||
"TASK: Wähle aus den Kandidaten die relevanten Kanten für den Text.\n"
|
||||
"TEXT: {chunk_text}\n"
|
||||
@@ -74,101 +114,83 @@ class SemanticAnalyzer:
|
||||
"OUTPUT: JSON Liste von Strings [\"kind:target\"]."
|
||||
)
|
||||
|
||||
# 2. Kandidaten-Liste formatieren
|
||||
# 3. Daten für Template vorbereiten (Vokabular-Check)
|
||||
edge_registry.ensure_latest()
|
||||
valid_types_str = ", ".join(sorted(list(edge_registry.valid_types)))
|
||||
edges_str = "\n".join([f"- {e}" for e in all_edges])
|
||||
|
||||
# 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
|
||||
)
|
||||
# 4. Prompt füllen mit Format-Check (Kein Shortcut)
|
||||
try:
|
||||
# Wir begrenzen den Text auf eine vernünftige Länge für das Kontextfenster
|
||||
final_prompt = prompt_template.format(
|
||||
chunk_text=chunk_text[:6000],
|
||||
edge_list=edges_str,
|
||||
valid_types=valid_types_str
|
||||
)
|
||||
except Exception as format_err:
|
||||
logger.error(f"❌ [SemanticAnalyzer] Prompt Formatting failed: {format_err}")
|
||||
return []
|
||||
|
||||
try:
|
||||
# 4. LLM Call mit Traffic Control
|
||||
# 5. LLM Call mit Background Priority & Semaphore Control
|
||||
response_json = await self.llm.generate_raw_response(
|
||||
prompt=final_prompt,
|
||||
force_json=True,
|
||||
max_retries=5,
|
||||
base_delay=5.0,
|
||||
priority="background"
|
||||
max_retries=3,
|
||||
base_delay=2.0,
|
||||
priority="background",
|
||||
provider=provider,
|
||||
model_override=model
|
||||
)
|
||||
|
||||
# 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()
|
||||
# 6. Mistral-sicheres JSON Parsing via Helper
|
||||
data = self._extract_json_safely(response_json)
|
||||
|
||||
if not clean_json:
|
||||
logger.warning("⚠️ [SemanticAnalyzer] Leere Antwort vom LLM erhalten. Trigger Fallback.")
|
||||
if not data:
|
||||
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
|
||||
# 7. Robuste Normalisierung (List vs Dict Recovery)
|
||||
raw_candidates = []
|
||||
|
||||
if isinstance(data, list):
|
||||
raw_candidates = data
|
||||
|
||||
elif isinstance(data, dict):
|
||||
logger.info(f"ℹ️ [SemanticAnalyzer] LLM 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}")
|
||||
logger.info(f"ℹ️ [SemanticAnalyzer] LLM returned dict, trying recovery.")
|
||||
for key in ["edges", "results", "kanten", "matches"]:
|
||||
if key in data and isinstance(data[key], list):
|
||||
raw_candidates.extend(data[key])
|
||||
break
|
||||
# Falls immer noch leer, nutze Schlüssel-Wert Paare als Behelf
|
||||
if not raw_candidates:
|
||||
for k, v in data.items():
|
||||
if isinstance(v, str): raw_candidates.append(f"{k}:{v}")
|
||||
elif isinstance(v, list):
|
||||
for target in v:
|
||||
if isinstance(target, str): raw_candidates.append(f"{k}:{target}")
|
||||
|
||||
# 7. Strict Validation Loop
|
||||
# 8. Strikte Validierung gegen Kanten-Format
|
||||
valid_edges = []
|
||||
for e in raw_candidates:
|
||||
e_str = str(e)
|
||||
e_str = str(e).strip()
|
||||
if self._is_valid_edge_string(e_str):
|
||||
valid_edges.append(e_str)
|
||||
else:
|
||||
logger.debug(f" [SemanticAnalyzer] Invalid edge format rejected: '{e_str}'")
|
||||
logger.debug(f" [SemanticAnalyzer] Rejected invalid edge format: '{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
|
||||
if valid_edges:
|
||||
logger.info(f"✅ [SemanticAnalyzer] Assigned {len(valid_edges)} edges to chunk.")
|
||||
return valid_edges
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"💥 [SemanticAnalyzer] Kritischer Fehler: {e}", exc_info=True)
|
||||
logger.error(f"💥 [SemanticAnalyzer] Critical error during analysis: {e}", exc_info=True)
|
||||
return []
|
||||
|
||||
async def close(self):
|
||||
if self.llm:
|
||||
await self.llm.close()
|
||||
|
||||
# Singleton Helper
|
||||
# Singleton Instanziierung
|
||||
_analyzer_instance = None
|
||||
def get_semantic_analyzer():
|
||||
global _analyzer_instance
|
||||
|
||||
+36
-37
@@ -1,43 +1,50 @@
|
||||
# config/decision_engine.yaml
|
||||
# Steuerung der Decision Engine (Intent Recognition & Graph Routing)
|
||||
# Version: 2.5.0 (WP-22: Semantic Graph Routing)
|
||||
# VERSION: 2.6.1 (WP-20: Hybrid LLM & WP-22: Semantic Graph Routing)
|
||||
# STATUS: Active
|
||||
# DoD: Keine Hardcoded Modelle, volle Integration der strategischen Boosts.
|
||||
|
||||
version: 2.5
|
||||
version: 2.6
|
||||
|
||||
settings:
|
||||
llm_fallback_enabled: true
|
||||
|
||||
# Few-Shot Prompting für den LLM-Router (Slow Path)
|
||||
# Strategie für den Router selbst (Welches Modell erkennt den Intent?)
|
||||
# "auto" nutzt den in MINDNET_LLM_PROVIDER gesetzten Standard (z.B. openrouter).
|
||||
router_provider: "auto"
|
||||
|
||||
# Few-Shot Prompting für den LLM-Router
|
||||
llm_router_prompt: |
|
||||
Du bist ein Klassifikator. Analysiere die Nachricht und wähle die passende Strategie.
|
||||
Du bist der zentrale Intent-Klassifikator für Mindnet, einen digitalen Zwilling.
|
||||
Analysiere die Nachricht und wähle die passende Strategie.
|
||||
Antworte NUR mit dem Namen der Strategie.
|
||||
|
||||
STRATEGIEN:
|
||||
- INTERVIEW: User will Wissen erfassen, Notizen anlegen oder Dinge festhalten.
|
||||
- DECISION: Rat, Strategie, Vor/Nachteile, "Soll ich".
|
||||
- EMPATHY: Gefühle, Frust, Freude, Probleme.
|
||||
- CODING: Code, Syntax, Programmierung.
|
||||
- FACT: Wissen, Fakten, Definitionen.
|
||||
- DECISION: Rat, Strategie, Abwägung von Werten, "Soll ich tun X?".
|
||||
- EMPATHY: Gefühle, Reflexion der eigenen Verfassung, Frust, Freude.
|
||||
- CODING: Code-Erstellung, Debugging, technische Dokumentation.
|
||||
- FACT: Reine Wissensabfrage, Definitionen, Suchen von Informationen.
|
||||
|
||||
BEISPIELE:
|
||||
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
|
||||
User: "Wie funktioniert die Qdrant-Vektor-DB?" -> FACT
|
||||
User: "Soll ich mein Startup jetzt verkaufen?" -> DECISION
|
||||
User: "Notiere mir kurz meine Gedanken zum Meeting." -> INTERVIEW
|
||||
User: "Ich fühle mich heute sehr erschöpft." -> EMPATHY
|
||||
User: "Schreibe eine FastAPI-Route für den Ingest." -> CODING
|
||||
|
||||
NACHRICHT: "{query}"
|
||||
|
||||
STRATEGIE:
|
||||
|
||||
strategies:
|
||||
# 1. Fakten-Abfrage (Fallback & Default)
|
||||
# 1. Fakten-Abfrage (Turbo-Modus via OpenRouter / Primary)
|
||||
FACT:
|
||||
description: "Reine Wissensabfrage."
|
||||
preferred_provider: "openrouter"
|
||||
trigger_keywords: []
|
||||
inject_types: []
|
||||
# WP-22: Definitionen & Hierarchien bevorzugen
|
||||
# WP-22: Definitionen & Hierarchien im Graphen bevorzugen
|
||||
edge_boosts:
|
||||
part_of: 2.0
|
||||
composed_of: 2.0
|
||||
@@ -46,9 +53,10 @@ strategies:
|
||||
prompt_template: "rag_template"
|
||||
prepend_instruction: null
|
||||
|
||||
# 2. Entscheidungs-Frage
|
||||
# 2. Entscheidungs-Frage (Power-Strategie via Gemini)
|
||||
DECISION:
|
||||
description: "Der User sucht Rat, Strategie oder Abwägung."
|
||||
preferred_provider: "gemini"
|
||||
trigger_keywords:
|
||||
- "soll ich"
|
||||
- "meinung"
|
||||
@@ -59,21 +67,22 @@ strategies:
|
||||
- "abwägung"
|
||||
- "vergleich"
|
||||
inject_types: ["value", "principle", "goal", "risk"]
|
||||
# WP-22: Risiken und Konsequenzen hervorheben
|
||||
# WP-22: Risiken und Konsequenzen im Graphen priorisieren
|
||||
edge_boosts:
|
||||
blocks: 2.5
|
||||
solves: 2.0
|
||||
depends_on: 1.5
|
||||
risk_of: 2.5
|
||||
impacts: 2.0 # NEU: Zeige mir alles, was von dieser Entscheidung betroffen ist!
|
||||
impacts: 2.0
|
||||
prompt_template: "decision_template"
|
||||
prepend_instruction: |
|
||||
!!! ENTSCHEIDUNGS-MODUS !!!
|
||||
!!! ENTSCHEIDUNGS-MODUS (HYBRID AI) !!!
|
||||
BITTE WÄGE FAKTEN GEGEN FOLGENDE WERTE, PRINZIPIEN UND ZIELE AB:
|
||||
|
||||
# 3. Empathie / "Ich"-Modus
|
||||
# 3. Empathie / "Ich"-Modus (Lokal & Privat via Ollama)
|
||||
EMPATHY:
|
||||
description: "Reaktion auf emotionale Zustände."
|
||||
preferred_provider: "openrouter"
|
||||
trigger_keywords:
|
||||
- "ich fühle"
|
||||
- "traurig"
|
||||
@@ -84,7 +93,6 @@ strategies:
|
||||
- "ü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
|
||||
@@ -93,9 +101,10 @@ strategies:
|
||||
prompt_template: "empathy_template"
|
||||
prepend_instruction: null
|
||||
|
||||
# 4. Coding / Technical
|
||||
# 4. Coding / Technical (Gemini Power)
|
||||
CODING:
|
||||
description: "Technische Anfragen und Programmierung."
|
||||
preferred_provider: "gemini"
|
||||
trigger_keywords:
|
||||
- "code"
|
||||
- "python"
|
||||
@@ -107,7 +116,7 @@ strategies:
|
||||
- "yaml"
|
||||
- "bash"
|
||||
inject_types: ["snippet", "reference", "source"]
|
||||
# WP-22: Technische Abhängigkeiten
|
||||
# WP-22: Technische Abhängigkeiten priorisieren
|
||||
edge_boosts:
|
||||
uses: 2.5
|
||||
depends_on: 2.0
|
||||
@@ -115,11 +124,10 @@ strategies:
|
||||
prompt_template: "technical_template"
|
||||
prepend_instruction: null
|
||||
|
||||
# 5. Interview / Datenerfassung
|
||||
# HINWEIS: Spezifische Typen (Projekt, Ziel etc.) werden automatisch
|
||||
# über die types.yaml erkannt. Hier stehen nur generische Trigger.
|
||||
# 5. Interview / Datenerfassung (Lokal)
|
||||
INTERVIEW:
|
||||
description: "Der User möchte Wissen erfassen."
|
||||
preferred_provider: "openrouter"
|
||||
trigger_keywords:
|
||||
- "neue notiz"
|
||||
- "etwas notieren"
|
||||
@@ -134,13 +142,4 @@ strategies:
|
||||
inject_types: []
|
||||
edge_boosts: {}
|
||||
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."
|
||||
prepend_instruction: null
|
||||
@@ -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
|
||||
+225
-114
@@ -1,4 +1,8 @@
|
||||
# config/prompts.yaml — Final V2.3.1 (Multi-Personality Support)
|
||||
# config/prompts.yaml — Final V2.6.0 (WP-15b Candidate-Validation)
|
||||
# WP-20: Optimierte Cloud-Templates zur Unterdrückung von Modell-Geschwätz.
|
||||
# FIX: Explizite Verbote für Einleitungstexte zur Vermeidung von JSON-Parsing-Fehlern.
|
||||
# WP-15b: Integration der binären edge_validation für den Two-Pass Workflow.
|
||||
# OLLAMA: UNVERÄNDERT laut Benutzeranweisung.
|
||||
|
||||
system_prompt: |
|
||||
Du bist 'mindnet', mein digitaler Zwilling und strategischer Partner.
|
||||
@@ -15,148 +19,255 @@ system_prompt: |
|
||||
# ---------------------------------------------------------
|
||||
# 1. STANDARD: Fakten & Wissen (Intent: FACT)
|
||||
# ---------------------------------------------------------
|
||||
rag_template: |
|
||||
QUELLEN (WISSEN):
|
||||
=========================================
|
||||
{context_str}
|
||||
=========================================
|
||||
rag_template:
|
||||
ollama: |
|
||||
QUELLEN (WISSEN):
|
||||
=========================================
|
||||
{context_str}
|
||||
=========================================
|
||||
|
||||
FRAGE:
|
||||
{query}
|
||||
FRAGE:
|
||||
{query}
|
||||
|
||||
ANWEISUNG:
|
||||
Beantworte die Frage präzise basierend auf den Quellen.
|
||||
Fasse die Informationen zusammen. Sei objektiv und neutral.
|
||||
ANWEISUNG:
|
||||
Beantworte die Frage präzise basierend auf den Quellen.
|
||||
Fasse die Informationen zusammen. Sei objektiv und neutral.
|
||||
gemini: |
|
||||
Kontext meines digitalen Zwillings: {context_str}
|
||||
Beantworte strukturiert und präzise: {query}
|
||||
openrouter: |
|
||||
Kontext-Analyse für den digitalen Zwilling:
|
||||
{context_str}
|
||||
|
||||
Anfrage: {query}
|
||||
Antworte basierend auf dem Kontext.
|
||||
|
||||
# ---------------------------------------------------------
|
||||
# 2. DECISION: Strategie & Abwägung (Intent: DECISION)
|
||||
# ---------------------------------------------------------
|
||||
decision_template: |
|
||||
KONTEXT (FAKTEN & STRATEGIE):
|
||||
=========================================
|
||||
{context_str}
|
||||
=========================================
|
||||
decision_template:
|
||||
ollama: |
|
||||
KONTEXT (FAKTEN & STRATEGIE):
|
||||
=========================================
|
||||
{context_str}
|
||||
=========================================
|
||||
|
||||
ENTSCHEIDUNGSFRAGE:
|
||||
{query}
|
||||
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 (Typ [VALUE], [PRINCIPLE], [GOAL]).
|
||||
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/Nein/Vielleicht mit Begründung)
|
||||
ANWEISUNG:
|
||||
Du agierst als mein Entscheidungs-Partner.
|
||||
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:
|
||||
- **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 strategischer Partner. Analysiere die Frage {query} basierend auf meinen Werten im Kontext {context_str}.
|
||||
openrouter: |
|
||||
Strategische Entscheidungsanalyse: {query}
|
||||
Wertebasis aus dem Graphen: {context_str}
|
||||
|
||||
# ---------------------------------------------------------
|
||||
# 3. EMPATHY: Der Spiegel / "Ich"-Modus (Intent: EMPATHY)
|
||||
# ---------------------------------------------------------
|
||||
empathy_template: |
|
||||
KONTEXT (ERFAHRUNGEN & GLAUBENSSÄTZE):
|
||||
=========================================
|
||||
{context_str}
|
||||
=========================================
|
||||
empathy_template:
|
||||
ollama: |
|
||||
KONTEXT (ERFAHRUNGEN & GLAUBENSSÄTZE):
|
||||
=========================================
|
||||
{context_str}
|
||||
=========================================
|
||||
|
||||
SITUATION:
|
||||
{query}
|
||||
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 Glaubenssätzen ([BELIEF]), 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.
|
||||
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 Glaubenssätzen ([BELIEF]), 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: {context_str}"
|
||||
openrouter: "Empathische Reflexion der Situation {query}. Persönlicher Kontext: {context_str}"
|
||||
|
||||
# ---------------------------------------------------------
|
||||
# 4. TECHNICAL: Der Coder (Intent: CODING)
|
||||
# ---------------------------------------------------------
|
||||
technical_template: |
|
||||
KONTEXT (DOCS & SNIPPETS):
|
||||
=========================================
|
||||
{context_str}
|
||||
=========================================
|
||||
technical_template:
|
||||
ollama: |
|
||||
KONTEXT (DOCS & SNIPPETS):
|
||||
=========================================
|
||||
{context_str}
|
||||
=========================================
|
||||
|
||||
TASK:
|
||||
{query}
|
||||
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 {context_str}."
|
||||
openrouter: "Technischer Support für {query}. Code-Referenzen: {context_str}"
|
||||
|
||||
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.
|
||||
# ---------------------------------------------------------
|
||||
# 5. INTERVIEW: Der "One-Shot Extractor" (Performance Mode)
|
||||
# ---------------------------------------------------------
|
||||
interview_template: |
|
||||
TASK:
|
||||
Du bist ein professioneller Ghostwriter. Verwandle den "USER INPUT" in eine strukturierte Notiz vom Typ '{target_type}'.
|
||||
|
||||
STRUKTUR (Nutze EXAKT diese Überschriften):
|
||||
{schema_fields}
|
||||
|
||||
USER INPUT:
|
||||
"{query}"
|
||||
|
||||
ANWEISUNG ZUM INHALT:
|
||||
1. Analysiere den Input genau.
|
||||
2. Schreibe die Inhalte unter die passenden Überschriften aus der STRUKTUR-Liste oben.
|
||||
3. STIL: Schreibe flüssig, professionell und in der Ich-Perspektive. Korrigiere Grammatikfehler, aber behalte den persönlichen Ton bei.
|
||||
4. Wenn Informationen für einen Abschnitt fehlen, schreibe nur: "[TODO: Ergänzen]". Erfinde nichts dazu.
|
||||
|
||||
OUTPUT FORMAT (YAML + MARKDOWN):
|
||||
---
|
||||
type: {target_type}
|
||||
status: draft
|
||||
title: (Erstelle einen treffenden, kurzen Titel für den Inhalt)
|
||||
tags: [Tag1, Tag2]
|
||||
---
|
||||
|
||||
# (Wiederhole den Titel hier)
|
||||
|
||||
## (Erster Begriff aus STRUKTUR)
|
||||
(Text...)
|
||||
|
||||
## (Zweiter Begriff aus STRUKTUR)
|
||||
(Text...)
|
||||
|
||||
(usw.)
|
||||
|
||||
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 (Intent: OFFLINE_FILTER)
|
||||
# ---------------------------------------------------------
|
||||
edge_allocation_template: |
|
||||
TASK:
|
||||
Du bist ein strikter Selektor. Du erhältst eine Liste von "Kandidaten-Kanten" (Strings).
|
||||
Wähle jene aus, die inhaltlich im "Textabschnitt" vorkommen oder relevant sind.
|
||||
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}
|
||||
"""
|
||||
TEXTABSCHNITT:
|
||||
"""
|
||||
{chunk_text}
|
||||
"""
|
||||
|
||||
KANDIDATEN (Auswahl-Pool):
|
||||
{edge_list}
|
||||
KANDIDATEN (Auswahl-Pool):
|
||||
{edge_list}
|
||||
|
||||
REGELN:
|
||||
1. Die Kanten haben das Format "typ:ziel". Der "typ" ist variabel und kann ALLES sein (z.B. uses, blocks, inspired_by, loves, etc.).
|
||||
2. Gib NUR die Strings aus der Kandidaten-Liste zurück, die zum Text passen.
|
||||
3. Erfinde KEINE neuen Kanten. Nutze exakt die Schreibweise aus der Liste.
|
||||
4. Antworte als flache JSON-Liste.
|
||||
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.
|
||||
|
||||
BEISPIEL (Zur Demonstration der Logik):
|
||||
Input Text: "Das Projekt Alpha scheitert, weil Budget fehlt."
|
||||
Input Kandidaten: ["blocks:Projekt Alpha", "inspired_by:Buch der Weisen", "needs:Budget"]
|
||||
Output: ["blocks:Projekt Alpha", "needs:Budget"]
|
||||
DEIN OUTPUT (JSON):
|
||||
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:
|
||||
|
||||
DEIN OUTPUT (JSON):
|
||||
# ---------------------------------------------------------
|
||||
# 7. SMART EDGE ALLOCATION: Extraktion (Intent: INGEST)
|
||||
# ---------------------------------------------------------
|
||||
edge_extraction:
|
||||
ollama: |
|
||||
TASK:
|
||||
Du bist ein Wissens-Ingenieur für den digitalen Zwilling 'mindnet'.
|
||||
Deine Aufgabe ist es, semantische Relationen (Kanten) aus dem Text zu extrahieren,
|
||||
die die Hauptnotiz '{note_id}' mit anderen Konzepten verbinden.
|
||||
|
||||
ANWEISUNGEN:
|
||||
1. Identifiziere wichtige Entitäten, Konzepte oder Ereignisse im Text.
|
||||
2. Bestimme die Art der Beziehung (z.B. part_of, uses, related_to, blocks, caused_by).
|
||||
3. Das Ziel (target) muss ein prägnanter Begriff sein.
|
||||
4. Antworte AUSSCHLIESSLICH in validem JSON als Liste von Objekten.
|
||||
|
||||
BEISPIEL:
|
||||
[[ {{"to": "Ziel-Konzept", \"kind\": \"beziehungs_typ\"}} ]]
|
||||
|
||||
TEXT:
|
||||
"""
|
||||
{text}
|
||||
"""
|
||||
|
||||
DEIN OUTPUT (JSON):
|
||||
gemini: |
|
||||
Analysiere '{note_id}'. Extrahiere semantische Beziehungen.
|
||||
ERLAUBTE TYPEN: {valid_types}
|
||||
TEXT: {text}
|
||||
OUTPUT: STRIKT JSON-Array von Objekten: [[{{"to\":\"Ziel\",\"kind\":\"typ\"}}]]. Kein Text davor/danach. Wenn nichts: [].
|
||||
openrouter: |
|
||||
TASK: Extrahiere semantische Relationen für '{note_id}'.
|
||||
ERLAUBTE TYPEN: {valid_types}
|
||||
TEXT: {text}
|
||||
ANWEISUNG: Antworte AUSSCHLIESSLICH mit einem JSON-Array von Objekten.
|
||||
FORMAT: [[{{"to\":\"Ziel-Begriff\",\"kind\":\"typ\"}}]]
|
||||
STRIKTES VERBOT: Schreibe keine Einleitung, keine Analyse und keine Erklärungen.
|
||||
Wenn keine Relationen existieren, antworte NUR mit: []
|
||||
OUTPUT:
|
||||
|
||||
# ---------------------------------------------------------
|
||||
# 8. WP-15b: EDGE VALIDATION (Intent: 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.
|
||||
@@ -2,13 +2,13 @@
|
||||
doc_type: glossary
|
||||
audience: all
|
||||
status: active
|
||||
version: 2.7.0
|
||||
context: "Zentrales Glossar für Mindnet v2.7. Definitionen von Entitäten, WP-22 Scoring-Konzepten und der Edge Registry."
|
||||
version: 2.8.0
|
||||
context: "Zentrales Glossar für Mindnet v2.8. Enthält Definitionen zu Hybrid-Cloud Resilienz, WP-76 Quoten-Steuerung und Mistral-safe Parsing."
|
||||
---
|
||||
|
||||
# Mindnet Glossar
|
||||
|
||||
**Quellen:** `01_edge_vocabulary.md`, `retriever_scoring.py`, `edge_registry.py`
|
||||
**Quellen:** `01_edge_vocabulary.md`, `llm_service.py`, `ingestion.py`, `edge_registry.py`
|
||||
|
||||
## Kern-Entitäten
|
||||
|
||||
@@ -21,21 +21,24 @@ context: "Zentrales Glossar für Mindnet v2.7. Definitionen von Entitäten, WP-2
|
||||
## 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.
|
||||
* **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.
|
||||
* **Retriever:** Besteht in v2.7+ aus der Orchestrierung (`retriever.py`) und der mathematischen Scoring-Engine (`retriever_scoring.py`).
|
||||
* **Decision Engine:** Teil des Routers, der Intents erkennt und entsprechende **Boost-Faktoren** für das Retrieval injiziert.
|
||||
* **Traffic Control:** Verwaltet Prioritäten und drosselt Hintergrund-Tasks (z.B. Smart Edges) mittels Semaphoren.
|
||||
* **Traffic Control:** Verwaltet Prioritäten und drosselt Hintergrund-Tasks (z.B. Smart Edges) mittels Semaphoren und Timeouts (45s) zur Vermeidung von System-Hangs.
|
||||
* **Unknown Edges Log:** Die Datei `unknown_edges.jsonl`, in der das System Kanten-Typen protokolliert, die nicht im Dictionary gefunden wurden.
|
||||
|
||||
## Konzepte & Features
|
||||
|
||||
* **Canonical Type:** Der standardisierte System-Name einer Kante (z.B. `based_on`), der in der Datenbank gespeichert wird.
|
||||
* **Alias (Edge):** Ein nutzerfreundliches Synonym (z.B. `basiert_auf`), das während der Ingestion automatisch zum Canonical Type aufgelöst 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).
|
||||
* **Deep Fallback (v2.11.14, WP20):** Ein inhaltsbasierter Rettungsmechanismus in der Ingestion. Im Gegensatz zum technischen Fallback (bei Verbindungsfehlern) wird der Deep Fallback ausgelöst, wenn ein Cloud-Modell zwar technisch erfolgreich antwortet, aber inhaltlich keine verwertbaren Daten liefert (z. B. bei "Data Policy Violations").
|
||||
* **Silent Refusal (WP20):** Ein Zustand, in dem Cloud-Provider (wie OpenRouter) die Verarbeitung eines Dokuments aufgrund interner Filter ("No data training") verweigern, ohne einen HTTP-Fehler zu senden. Wird durch Deep Fallback abgefangen.
|
||||
* **Rate-Limit Resilience (WP-20):** Automatisierte Erkennung von HTTP 429 Fehlern. Das System pausiert (konfigurierbar via `LLM_RATE_LIMIT_WAIT`) und wiederholt den Cloud-Call, bevor der langsame Fallback ausgelöst wird.
|
||||
* **Mistral-safe Parsing:** Robuste Extraktions-Logik in Ingestion und Analyzer, die technische Steuerzeichen (`<s>`, `[OUT]`) und Framework-Tags erkennt und entfernt, um valides JSON aus Free-Modellen zu gewinnen.
|
||||
* **Lifecycle Scoring (WP-22):** Ein Mechanismus, der die Relevanz einer Notiz basierend auf ihrem Status gewichtet (z.B. Bonus für `stable`, Malus für `draft`).
|
||||
* **Intent Boosting:** Dynamische Erhöhung der Kanten-Gewichte basierend auf der Nutzerfrage (z.B. Fokus auf `caused_by` bei "Warum"-Fragen).
|
||||
* **Provenance Weighting:** Gewichtung einer Kante nach ihrer Herkunft:
|
||||
* `explicit`: Vom Mensch gesetzt (Prio 1).
|
||||
* `smart`: Von der KI validiert (Prio 2).
|
||||
* `rule`: Durch System-Regeln/Matrix erzeugt (Prio 3).
|
||||
* `semantic_ai`: Von der KI im Turbo-Mode extrahiert und validiert (Prio 2).
|
||||
* `structure`: Durch System-Regeln/Matrix erzeugt (Prio 3).
|
||||
* **Smart Edge Allocation:** KI-Verfahren zur Relevanzprüfung von Links für spezifische Textabschnitte.
|
||||
* **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`).
|
||||
@@ -1,73 +1,83 @@
|
||||
---
|
||||
doc_type: concept
|
||||
audience: architect, product_owner
|
||||
scope: ai, router, personas
|
||||
scope: ai, router, personas, resilience
|
||||
status: active
|
||||
version: 2.6
|
||||
context: "Fachkonzept der KI-Persönlichkeit, der Decision Engine und Erweiterungsstrategien."
|
||||
version: 2.8.1
|
||||
context: "Fachkonzept der hybriden KI-Persönlichkeit, der Provider-Kaskade und der kognitiven Resilienz (Deep Fallback)."
|
||||
---
|
||||
|
||||
# Konzept: KI-Persönlichkeit & Router
|
||||
|
||||
**Quellen:** `mindnet_functional_architecture.md`, `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)
|
||||
|
||||
Jede Eingabe durchläuft den **Hybrid Router**. Er entscheidet über die Strategie.
|
||||
Jede Eingabe durchläuft den **Hybrid Router**. Er entscheidet über die fachliche Strategie und die technische Ausführung.
|
||||
|
||||
### Modus A: RAG (Retrieval Augmented Generation)
|
||||
* *Intent:* Der Nutzer hat eine Frage oder ein Problem (`FACT`, `DECISION`, `EMPATHY`).
|
||||
* *Aktion:* Das System sucht im Gedächtnis und generiert eine Antwort.
|
||||
* **Intent:** Der Nutzer hat eine Frage oder ein Problem (`FACT`, `DECISION`, `EMPATHY`).
|
||||
* **Aktion:** Das System sucht im Gedächtnis und generiert eine Antwort.
|
||||
|
||||
### Modus B: Interview (Knowledge Capture)
|
||||
* *Intent:* Der Nutzer will Wissen speichern (`INTERVIEW`).
|
||||
* *Aktion:* Das System sucht **nicht**, sondern fragt ab und erstellt einen Draft.
|
||||
* **Intent:** Der Nutzer will Wissen speichern (`INTERVIEW`).
|
||||
* **Aktion:** Das System sucht **nicht**, sondern fragt ab und erstellt einen Draft.
|
||||
|
||||
---
|
||||
|
||||
## 2. Die Personas (Strategien)
|
||||
## 2. Die hybride LLM-Landschaft (Resilienz-Kaskade)
|
||||
|
||||
Ein intelligenter Zwilling muss jederzeit verfügbar sein. Mindnet v2.8.1 nutzt eine **dreistufige Kaskade**, um Intelligenz, Kosten und Verfügbarkeit zu optimieren:
|
||||
|
||||
1. **Stufe 1: Cloud-Speed (Turbo-Mode):** Primäre Wahl für komplexe Extraktionsaufgaben und schnelle RAG-Antworten mittels OpenRouter (Mistral-7B) oder Google Gemini (2.5-flash-lite).
|
||||
2. **Stufe 2: Quoten-Resilienz:** Erkennt das System eine Drosselung durch Cloud-Provider (HTTP 429), pausiert es kontrolliert (`LLM_RATE_LIMIT_WAIT`), führt automatisierte Retries durch und schützt so den laufenden Prozess.
|
||||
3. **Stufe 3: Deep Fallback & lokale Souveränität (Ollama):** * **Technischer Fallback:** Schlagen alle Cloud-Versuche fehl, übernimmt das lokale Modell (Phi-3).
|
||||
* **Kognitiver Fallback (v2.11.14):** Liefert die Cloud zwar technisch eine Antwort, verweigert aber inhaltlich die Verarbeitung (Silent Refusal/Policy Violation), wird ein **Deep Fallback** erzwungen, um die Datenintegrität lokal zu retten.
|
||||
|
||||
|
||||
|
||||
---
|
||||
|
||||
## 3. Die Personas (Strategien)
|
||||
|
||||
Mindnet wechselt den Hut, je nach Situation.
|
||||
|
||||
### 2.1 Der Berater (Strategy: DECISION)
|
||||
* **Auslöser:** Fragen wie "Soll ich...?", "Was ist besser?".
|
||||
### 3.1 Der Berater (Strategy: DECISION)
|
||||
* **Auslöser:** Fragen wie „Soll ich...?“, „Was ist besser?“.
|
||||
* **Strategic Retrieval:** Lädt aktiv Notizen der Typen `value` (Werte), `goal` (Ziele) und `risk` (Risiken), auch wenn sie im Text nicht direkt vorkommen.
|
||||
* **Reasoning:** *"Wäge die Fakten gegen meine Werte ab. Sei strikt bei Risiken."*
|
||||
* **Reasoning:** *„Wäge die Fakten gegen meine Werte ab. Sei strikt bei Risiken.“*
|
||||
|
||||
### 2.2 Der Spiegel (Strategy: EMPATHY)
|
||||
* **Auslöser:** Emotionale Aussagen ("Ich bin frustriert").
|
||||
### 3.2 Der Spiegel (Strategy: EMPATHY)
|
||||
* **Auslöser:** Emotionale Aussagen („Ich bin frustriert“).
|
||||
* **Strategic Retrieval:** Lädt `experience` (Erfahrungen) und `belief` (Glaubenssätze).
|
||||
* **Reasoning:** *"Nutze meine eigenen Erfahrungen, um die Situation einzuordnen."*
|
||||
* **Reasoning:** *„Nutze meine eigenen Erfahrungen, um die Situation einzuordnen.“*
|
||||
|
||||
### 2.3 Der Bibliothekar (Strategy: FACT)
|
||||
* **Auslöser:** Sachfragen ("Was ist Qdrant?").
|
||||
### 3.3 Der Bibliothekar (Strategy: FACT)
|
||||
* **Auslöser:** Sachfragen („Was ist Qdrant?“).
|
||||
* **Behavior:** Präzise, neutral, kurz.
|
||||
|
||||
---
|
||||
|
||||
## 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
|
||||
* **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
|
||||
### 4.2 Empathie & „Ich“-Modus
|
||||
* **Konzept:** Das System antwortet im Tonfall des Nutzers.
|
||||
* **Umsetzung:** Few-Shot Prompting mit eigenen E-Mails/Texten als Stilvorlage.
|
||||
|
||||
### 3.3 Glaubenssätze & Rituale
|
||||
* **Konzept:** Berücksichtigung weicher Faktoren.
|
||||
* **Szenario:** Bei Terminplanungen werden Rituale ("Keine Meetings vor 10 Uhr") automatisch als harte Restriktion gegen Anfragen geprüft.
|
||||
### 4.3 Resilienz als Charakterzug
|
||||
Durch die **WP-20 Implementierung** zeigt das System „Geduld“: Bei Quoten-Engpässen bricht es nicht ab, sondern wartet auf freie Kapazitäten. Durch das **Deep Fallback (v2.11.14)** besitzt Mindnet eine kognitive Ausdauer, die inhaltliche Zensur oder Blockaden der Cloud erkennt und durch lokale Rechenpower auflöst.
|
||||
|
||||
---
|
||||
|
||||
## 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.**
|
||||
|
||||
@@ -87,6 +97,6 @@ DECISION:
|
||||
```
|
||||
|
||||
**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.
|
||||
@@ -1,17 +1,17 @@
|
||||
---
|
||||
doc_type: technical_reference
|
||||
audience: developer, architect
|
||||
scope: backend, chat, ollama, traffic_control
|
||||
scope: backend, chat, llm_service, traffic_control, resilience
|
||||
status: active
|
||||
version: 2.6
|
||||
context: "Technische Implementierung des FastAPI-Routers, der Decision Engine und des Traffic Control Systems."
|
||||
version: 2.8.1
|
||||
context: "Technische Implementierung des FastAPI-Routers, des hybriden LLMService (v3.3.6) und der WP-20 Resilienz-Logik."
|
||||
---
|
||||
|
||||
# Chat Backend & Traffic Control
|
||||
|
||||
## 1. Hybrid Router (Decision Engine)
|
||||
|
||||
Der zentrale Einstiegspunkt für jede Chatanfrage ist der **Hybrid Router** (`app/routers/chat.py`). Er entscheidet dynamisch, 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`). Er entscheidet dynamisch über die Strategie und nutzt den `LLMService` zur provider-agnostischen Generierung.
|
||||
|
||||
### 1.1 Intent-Erkennung (Logik)
|
||||
|
||||
@@ -21,18 +21,27 @@ Der Router prüft den Input in drei Stufen (Wasserfall-Prinzip):
|
||||
* Prüfung auf Vorhandensein von `?` oder W-Wörtern (Wer, Wie, Was, Soll ich).
|
||||
* Wenn positiv: **RAG Modus** (Interview wird blockiert).
|
||||
2. **Keyword Scan (Fast Path):**
|
||||
* Lädt `types.yaml` (Objekte, z.B. "Projekt") und `decision_engine.yaml` (Handlungen, z.B. "neu").
|
||||
* Lädt `types.yaml` (Objekte) und `decision_engine.yaml` (Handlungen).
|
||||
* Wenn Match (z.B. "Projekt" + "neu"): **INTERVIEW Modus**.
|
||||
3. **LLM Fallback (Slow Path):**
|
||||
* Wenn unklar: Anfrage an LLM zur Klassifizierung.
|
||||
* Wenn unklar: Anfrage an LLM zur Klassifizierung mittels `router_prompt`.
|
||||
|
||||
### 1.2 RAG Flow (Technisch)
|
||||
### 1.2 Prompt-Auflösung (Bulletproof Resolution)
|
||||
|
||||
Um Kompatibilitätsprobleme mit verschachtelten YAML-Prompts zu vermeiden, nutzt der Router die Methode `llm.get_prompt()`. Diese implementiert eine **Provider-Kaskade**:
|
||||
* **Spezifischer Provider:** Das System sucht zuerst nach einem Prompt für den aktiv konfigurierten Provider (z.B. `openrouter`).
|
||||
* **Cloud-Stil Fallback:** Existiert dieser nicht, erfolgt ein Fallback auf das `gemini`-Template.
|
||||
* **Basis-Fallback:** Als letzte Instanz wird das `ollama`-Template geladen.
|
||||
* **String-Garantie:** Die Methode garantiert die Rückgabe eines Strings (selbst bei verschachtelten YAML-Dicts), was 500-Fehler bei String-Operationen wie `.replace()` oder `.format()` verhindert.
|
||||
|
||||
### 1.3 RAG Flow (Technisch)
|
||||
|
||||
Wenn der Intent `FACT` oder `DECISION` ist, wird folgender Flow ausgeführt:
|
||||
|
||||
1. **Pre-Processing:** Query Rewriting (optional).
|
||||
2. **Context Enrichment:**
|
||||
* Abruf via `retriever.py` (Hybrid Search).
|
||||
* Integration von **Edge Boosts** aus der `decision_engine.yaml` zur Beeinflussung der Graph-Gewichtung.
|
||||
* Injection von Metadaten (`[TYPE]`, `[SCORE]`) in den Prompt.
|
||||
3. **Prompt Construction:** Assembly aus System-Prompt (Persona) + Context + Query.
|
||||
4. **Streaming:** LLM-Antwort wird via **SSE (Server-Sent Events)** an den Client gestreamt.
|
||||
@@ -40,36 +49,65 @@ Wenn der Intent `FACT` oder `DECISION` ist, wird folgender Flow ausgeführt:
|
||||
|
||||
---
|
||||
|
||||
## 2. Traffic Control (WP-15)
|
||||
## 2. LLM Service & Traffic Control (WP-20)
|
||||
|
||||
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`) fungiert als zentraler Hybrid-Client für OpenRouter, Google Gemini und Ollama. Er schützt das System vor Überlastung und verwaltet Quoten.
|
||||
|
||||
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
|
||||
|
||||
Jeder LLM-Request muss ein `priority`-Flag setzen.
|
||||
|
||||
**Prioritäten-Levels:**
|
||||
Jeder LLM-Request steuert über ein `priority`-Flag den Zugriff auf Hardware- und API-Ressourcen:
|
||||
|
||||
| Priority | Verwendung | Limitierung |
|
||||
| :--- | :--- | :--- |
|
||||
| **realtime** | Chat-Anfragen | Keine (Hardware-Limit) |
|
||||
| **background** | Smart Edge Allocation, Drafts | `MINDNET_LLM_BACKGROUND_LIMIT` |
|
||||
| **realtime** | Chat-Anfragen, Intent-Routing | Keine (Hardware-Limit) |
|
||||
| **background** | Smart Edge Allocation, Import-Tasks | `MINDNET_LLM_BACKGROUND_LIMIT` |
|
||||
|
||||
**Funktionsweise:**
|
||||
* Hintergrund-Tasks nutzen `asyncio.Semaphore`.
|
||||
* Wenn das Limit (Default: 2) erreicht ist, warten weitere Import-Tasks.
|
||||
* Chat-Tasks umgehen die Semaphore und werden sofort bearbeitet.
|
||||
* Hintergrund-Tasks nutzen ein globales `asyncio.Semaphore`.
|
||||
* Das Limit (Standard: 2) verhindert, dass parallele Import-Vorgänge die API-Quoten oder die lokale CPU erschöpfen.
|
||||
* Chat-Tasks umgehen die Semaphore für minimale Latenz.
|
||||
|
||||
### 2.2 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).
|
||||
* **Frontend:** `MINDNET_API_TIMEOUT` (Default: 300s).
|
||||
### 2.3 Timeout-Konfiguration
|
||||
|
||||
Deadlocks und "hängende" Importe werden durch differenzierte Timeouts verhindert:
|
||||
* **Cloud-Calls (OpenRouter/Gemini):** Strikte **45 Sekunden** zur Vermeidung von Blockaden bei Provider-Latenz.
|
||||
* **Lokales LLM (Ollama):** Konfigurierbar via `MINDNET_LLM_TIMEOUT` (Default: 300s).
|
||||
|
||||
---
|
||||
|
||||
## 3. Feedback Traceability
|
||||
## 3. Resilience & Quota Management (WP-20)
|
||||
|
||||
In v2.8 wurde ein intelligentes Fehler-Handling für Cloud-Provider implementiert:
|
||||
|
||||
1. **Rate-Limit Erkennung:** Der Service erkennt HTTP 429 Fehler sowie provider-spezifische Meldungen wie `RESOURCE_EXHAUSTED`.
|
||||
2. **Intelligenter Backoff:** Statt sofort auf das langsame lokale Modell zu wechseln, pausiert das System für die Dauer von `LLM_RATE_LIMIT_WAIT` (Standard: 60s).
|
||||
3. **Cloud-Retry:** Nach der Pause erfolgt ein erneuter Versuch (bis zu `LLM_RATE_LIMIT_RETRIES` Mal).
|
||||
4. **Ollama Fallback:** Erst nach Erschöpfung der Retries schaltet das System auf den lokalen Ollama um, um die Betriebssicherheit zu gewährleisten ("Quoten-Schutz").
|
||||
5. **Deep Fallback Support:** Der Service stellt die Infrastruktur für den inhaltsbasierten Fallback (v2.11.14) bereit, falls die Cloud zwar technisch antwortet, aber inhaltlich (z.B. wegen Policy-Filtern oder Silent Refusal) keine validen Daten liefert.
|
||||
|
||||
---
|
||||
|
||||
## 4. Feedback Traceability
|
||||
|
||||
Unterstützt das geplante Self-Tuning (WP08).
|
||||
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
---
|
||||
doc_type: technical_reference
|
||||
audience: developer, admin
|
||||
scope: configuration, env, registry, scoring
|
||||
scope: configuration, env, registry, scoring, resilience
|
||||
status: active
|
||||
version: 2.7.2
|
||||
context: "Umfassende Referenztabellen für Umgebungsvariablen, YAML-Konfigurationen und die Edge Registry Struktur."
|
||||
version: 2.8.0
|
||||
context: "Umfassende Referenztabellen für Umgebungsvariablen (inkl. Hybrid-Cloud & WP-76), YAML-Konfigurationen und die Edge Registry Struktur."
|
||||
---
|
||||
|
||||
# Konfigurations-Referenz
|
||||
|
||||
Dieses Dokument beschreibt alle Steuerungsdateien von Mindnet. In der Version 2.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.8 wurde die Konfiguration professionalisiert, um die Edge Registry, dynamische Scoring-Parameter (Lifecycle & Intent) sowie die neue Hybrid-Cloud-Resilienz zu unterstützen.
|
||||
|
||||
## 1. Environment Variablen (`.env`)
|
||||
|
||||
@@ -22,17 +22,26 @@ Diese Variablen steuern die Infrastruktur, Pfade und globale Timeouts.
|
||||
| `COLLECTION_PREFIX` | `mindnet` | Namensraum für Collections (erzeugt `{prefix}_notes` etc). |
|
||||
| `VECTOR_DIM` | `768` | **Muss 768 sein** (für Nomic Embeddings). |
|
||||
| `MINDNET_VOCAB_PATH` | *(Pfad)* | **Neu (WP-22):** Absoluter Pfad zur `01_edge_vocabulary.md`. Definiert den Ort des Dictionarys. |
|
||||
| `MINDNET_VAULT_ROOT` | `./vault` | Basis-Pfad für Datei-Operationen. Dient als Fallback-Basis, falls `MINDNET_VOCAB_PATH` nicht gesetzt ist. |
|
||||
| `MINDNET_VAULT_ROOT` | `./vault` | Basis-Pfad für Datei-Operationen. |
|
||||
| `MINDNET_TYPES_FILE` | `config/types.yaml` | Pfad zur Typ-Registry. |
|
||||
| `MINDNET_RETRIEVER_CONFIG`| `config/retriever.yaml`| Pfad zur Scoring-Konfiguration. |
|
||||
| `MINDNET_DECISION_CONFIG` | `config/decision_engine.yaml` | Pfad zur Router & Intent Config. |
|
||||
| `MINDNET_PROMPTS_PATH` | `config/prompts.yaml` | Pfad zu LLM Prompts. |
|
||||
| `MINDNET_LLM_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_OLLAMA_URL` | `http://127.0.0.1:11434`| URL zum LLM-Server. |
|
||||
| `MINDNET_LLM_TIMEOUT` | `300.0` | Timeout in Sekunden (Erhöht für CPU Cold-Starts). |
|
||||
| `MINDNET_API_TIMEOUT` | `300.0` | Frontend Timeout (Erhöht für Smart Edge Wartezeiten). |
|
||||
| `MINDNET_LLM_BACKGROUND_LIMIT`| `2` | **Traffic Control:** Max. parallele Hintergrund-Tasks (Semaphore). |
|
||||
| `MINDNET_OLLAMA_URL` | `http://127.0.0.1:11434`| URL zum lokalen LLM-Server. |
|
||||
| `MAX_OLLAMA_CHARS` | `10000`| Maximale Länge des Kontext-Strings, der an das lokale Modell gesendet wird. Verhindert Batch-Decoding-Fehler bei sehr großen Notiz-Historien. |
|
||||
| `MINDNET_LLM_TIMEOUT` | `300.0` | Timeout in Sekunden für LLM-Anfragen. |
|
||||
| `MINDNET_API_TIMEOUT` | `300.0` | Globales API-Timeout für das Frontend. |
|
||||
| `MINDNET_LL_BACKGROUND_LIMIT`| `2` | **Traffic Control:** Max. parallele Hintergrund-Tasks (Semaphore). |
|
||||
| `MINDNET_CHANGE_DETECTION_MODE` | `full` | `full` (Text + Meta) oder `body` (nur Text). |
|
||||
|
||||
---
|
||||
@@ -199,21 +208,21 @@ Die Datei muss eine Markdown-Tabelle enthalten, die vom Regex-Parser gelesen wir
|
||||
|
||||
| System-Typ (Canonical) | Erlaubte Aliasse (User) | Beschreibung |
|
||||
| :--------------------- | :--------------------------------------------------- | :-------------------------------------- |
|
||||
| **`caused_by`** | `ausgelöst_durch`, `wegen`, `ursache_ist` | Kausalität: A löst B aus. |
|
||||
| **`derived_from`** | `abgeleitet_von`, `quelle`, `inspiriert_durch` | Herkunft: A stammt von B. |
|
||||
| **`based_on`** | `basiert_auf`, `fundament`, `grundlage` | Fundament: B baut auf A auf. |
|
||||
| **`solves`** | `löst`, `beantwortet`, `fix_für` | Lösung: A ist Lösung für Problem B. |
|
||||
| **`part_of`** | `teil_von`, `gehört_zu`, `cluster` | Hierarchie: Kind -> Eltern. |
|
||||
| **`depends_on`** | `hängt_ab_von`, `braucht`, `requires`, `enforced_by` | Abhängigkeit: A braucht B. |
|
||||
| **`blocks`** | `blockiert`, `verhindert`, `risiko_für` | Blocker: A verhindert B. |
|
||||
| **`uses`** | `nutzt`, `verwendet`, `tool` | Werkzeug: A nutzt B. |
|
||||
| **`guides`** | `steuert`, `leitet`, `orientierung` | Soft-Dependency: A gibt Richtung für B. |
|
||||
| **`followed_by`** | `danach`, `folgt`, `nachfolger`, `followed_by` | Prozess: A -> B. |
|
||||
| **`preceeded_by`** | `davor`, `vorgänger`, `preceded_by` | Prozess: B <- A. |
|
||||
| **`related_to`** | `siehe_auch`, `kontext`, `thematisch` | Lose Assoziation. |
|
||||
| **`similar_to`** | `ähnlich_wie`, `vergleichbar` | Synonym / Ähnlichkeit. |
|
||||
| **`references`** | *(Kein Alias)* | Standard-Verweis (Fallback). |
|
||||
| **`resulted_in`** | `ergebnis`, `resultat`, `erzeugt` | Herkunft: A erzeugt Ergebnis B |
|
||||
| **`caused_by`** | `ausgelöst_durch`, `wegen`, `ursache_ist` | Kausalität: A löst B aus. |
|
||||
| **`derived_from`** | `abgeleitet_von`, `quelle`, `inspiriert_durch` | Herkunft: A stammt von B. |
|
||||
| **`based_on`** | `basiert_auf`, `fundament`, `grundlage` | Fundament: B baut auf A auf. |
|
||||
| **`solves`** | `löst`, `beantwortet`, `fix_für` | Lösung: A ist Lösung für Problem B. |
|
||||
| **`part_of`** | `teil_von`, `gehört_zu`, `cluster` | Hierarchie: Kind -> Eltern. |
|
||||
| **`depends_on`** | `hängt_ab_von`, `braucht`, `requires`, `enforced_by` | Abhängigkeit: A braucht B. |
|
||||
| **`blocks`** | `blockiert`, `verhindert`, `risiko_für` | Blocker: A verhindert B. |
|
||||
| **`uses`** | `nutzt`, `verwendet`, `tool` | Werkzeug: A nutzt B. |
|
||||
| **`guides`** | `steuert`, `leitet`, `orientierung` | Soft-Dependency: A gibt Richtung für B. |
|
||||
| **`followed_by`** | `danach`, `folgt`, `nachfolger`, `followed_by` | Prozess: A -> B. |
|
||||
| **`preceeded_by`** | `davor`, `vorgänger`, `preceded_by` | Prozess: B <- A. |
|
||||
| **`related_to`** | `siehe_auch`, `kontext`, `thematisch` | Lose Assoziation. |
|
||||
| **`similar_to`** | `ähnlich_wie`, `vergleichbar` | Synonym / Ähnlichkeit. |
|
||||
| **`references`** | *(Kein Alias)* | Standard-Verweis (Fallback). |
|
||||
| **`resulted_in`** | `ergebnis`, `resultat`, `erzeugt` | Herkunft: A erzeugt Ergebnis B |
|
||||
|
||||
**ACHTUNG!** Die Kantentypen
|
||||
**belongs_to**, **next** und **prev** dürfen nicht vom Nutzer gesetzt werden
|
||||
|
||||
@@ -3,17 +3,17 @@ doc_type: technical_reference
|
||||
audience: developer, devops
|
||||
scope: backend, ingestion, smart_edges, edge_registry
|
||||
status: active
|
||||
version: 2.7.1
|
||||
context: "Detaillierte technische Beschreibung der Import-Pipeline, Chunking-Strategien und CLI-Befehle."
|
||||
version: 2.8.1
|
||||
context: "Detaillierte technische Beschreibung der Import-Pipeline, Mistral-safe Parsing und Deep Fallback Resilienz."
|
||||
---
|
||||
|
||||
# Ingestion Pipeline & Smart Processing
|
||||
|
||||
**Quellen:** `pipeline_playbook.md`, `Handbuch.md`, `edge_registry.py`, `01_edge_vocabulary.md`, `06_active_roadmap.md`
|
||||
**Quellen:** `pipeline_playbook.md`, `ingestion.py`, `edge_registry.py`, `01_edge_vocabulary.md`, `llm_service.py`
|
||||
|
||||
Die Ingestion transformiert Markdown in den Graphen. Entrypoint: `scripts/import_markdown.py` (CLI) oder `routers/ingest.py` (API). Seit v2.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.8 integriert dieser Prozess eine **intelligente Quoten-Steuerung** (WP-20) und ein **robustes JSON-Parsing** für Cloud-Modelle (Mistral/Gemini).
|
||||
|
||||
## 1. Der Import-Prozess (15-Schritte-Workflow)
|
||||
## 1. Der Import-Prozess (16-Schritte-Workflow)
|
||||
|
||||
Der Prozess ist **asynchron** und **idempotent**.
|
||||
|
||||
@@ -23,7 +23,7 @@ Der Prozess ist **asynchron** und **idempotent**.
|
||||
2. **Markdown lesen:** Rekursives Scannen des Vaults.
|
||||
3. **Frontmatter Check & Hard Skip (WP-22):**
|
||||
* Extraktion von `status` und `type`.
|
||||
* **Hard Skip Rule:** Wenn `status` in `['system', 'template']` 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 **sofort übersprungen**. Sie wird weder vektorisiert noch in den Graphen aufgenommen.
|
||||
* Validierung der Pflichtfelder (`id`, `title`) für alle anderen Dateien.
|
||||
4. **Edge Registry Initialisierung (WP-22):**
|
||||
* Laden der Singleton-Instanz der `EdgeRegistry`.
|
||||
@@ -38,10 +38,12 @@ Der Prozess ist **asynchron** und **idempotent**.
|
||||
* Vergleich des Hashes mit Qdrant.
|
||||
* Strategie wählbar via ENV `MINDNET_CHANGE_DETECTION_MODE` (`full` oder `body`).
|
||||
8. **Chunking anwenden:** Zerlegung des Textes basierend auf dem ermittelten Profil (siehe Kap. 3).
|
||||
9. **Smart Edge Allocation (WP15):**
|
||||
9. **Smart Edge Allocation (WP-20):**
|
||||
* Wenn `enable_smart_edge_allocation: true`: Der `SemanticAnalyzer` sendet Chunks an das LLM.
|
||||
* **Traffic Control:** Request nutzt `priority="background"`. Semaphore (Limit via `.env`) drosselt die Last.
|
||||
* **Resilienz:** Bei Timeout (Ollama) greift ein Fallback (Broadcasting an alle Chunks).
|
||||
* **Traffic Control:** Request nutzt `priority="background"`. Semaphore drosselt die Last.
|
||||
* **Resilienz (Quota Handling):** Erkennt HTTP 429 (Rate-Limit) und pausiert kontrolliert (via `LLM_RATE_LIMIT_WAIT`), bevor ein Cloud-Retry erfolgt.
|
||||
* **Mistral-safe Parsing:** Automatisierte Bereinigung von BOS-Tokens (`<s>`) und Framework-Tags (`[OUT]`) sowie Recovery-Logik für Dictionaries (Suche nach `edges`, `links`, `results`, `kanten`).
|
||||
* **Deep Fallback (v2.11.14):** Erkennt "Silent Refusals" (Data Policy Violations). Liefert die Cloud trotz erfolgreicher Verbindung keine verwertbaren Kanten, wird ein lokaler Fallback via Ollama erzwungen, um Kantenverlust zu vermeiden.
|
||||
10. **Inline-Kanten finden:** Parsing von `[[rel:...]]`.
|
||||
11. **Alias-Auflösung & Kanonisierung (WP-22):**
|
||||
* Jede Kante wird via `edge_registry.resolve()` normalisiert.
|
||||
@@ -53,8 +55,6 @@ Der Prozess ist **asynchron** und **idempotent**.
|
||||
15. **Embedding (Async):** Generierung via `nomic-embed-text` (768 Dim).
|
||||
16. **Diagnose:** Integritäts-Check nach dem Lauf.
|
||||
|
||||
|
||||
|
||||
---
|
||||
|
||||
## 2. Betrieb & CLI Befehle
|
||||
@@ -119,11 +119,11 @@ Die Strategie `by_heading` zerlegt Texte anhand ihrer Struktur (Überschriften).
|
||||
* **Split Level:** Definiert die Tiefe (z.B. `2` = H1 & H2 triggern Split).
|
||||
* **Modus "Strict" (`strict_heading_split: true`):**
|
||||
* Jede Überschrift (`<= split_level`) erzwingt einen neuen Chunk.
|
||||
* *Merge-Check:* Wenn der vorherige Chunk leer war (nur Überschriften), wird gemergt (verhindert verwaiste Überschriften).
|
||||
* *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 (z.B. H2) lösen nur dann einen neuen Chunk aus, wenn der aktuelle Chunk die `target`-Größe erreicht hat.
|
||||
* **Füll-Logik:** Überschriften *auf* dem Split-Level lösen nur dann einen neuen Chunk aus, wenn der aktuelle Chunk die `target`-Größe erreicht hat.
|
||||
* *Safety Net:* Auch hier greift das `max` Token Limit.
|
||||
|
||||
### 3.3 Payload-Felder (Qdrant)
|
||||
@@ -138,20 +138,20 @@ Die Strategie `by_heading` zerlegt Texte anhand ihrer Struktur (Überschriften).
|
||||
|
||||
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. |
|
||||
| **2** | Inline | `inline:rel` | **0.95** | Typisierte menschliche Kante. |
|
||||
| **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-extrahierte Verbindung (Mistral-safe). |
|
||||
| **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
|
||||
|
||||
In v2.7 wurden Tools zur Überwachung der Datenqualität integriert:
|
||||
In v2.7+ wurden Tools zur Überwachung der Datenqualität integriert:
|
||||
|
||||
**1. Registry Review:** Prüfung der `data/logs/unknown_edges.jsonl`. Administratoren sollten hier gelistete Begriffe als Aliase in die `01_edge_vocabulary.md` aufnehmen.
|
||||
|
||||
|
||||
@@ -19,14 +19,31 @@ context: "Installationsanleitung, Systemd-Units und Wartungsprozesse für Mindne
|
||||
### 1.2 Qdrant (Docker)
|
||||
Startet die Vektor-DB mit persistentem Storage auf Port 6333.
|
||||
|
||||
dockercompose.yaml
|
||||
```bash
|
||||
docker run -d \
|
||||
--name mindnet_qdrant \
|
||||
--restart always \
|
||||
-p 6333:6333 \
|
||||
-v $(pwd)/qdrant_storage:/qdrant/storage \
|
||||
qdrant/qdrant
|
||||
services:
|
||||
qdrant:
|
||||
image: qdrant/qdrant
|
||||
container_name: qdrant
|
||||
ports:
|
||||
- "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)
|
||||
**Wichtig:** Seit v2.4 ist `nomic-embed-text` Pflicht für Embeddings.
|
||||
|
||||
@@ -2,18 +2,18 @@
|
||||
doc_type: roadmap
|
||||
audience: product_owner, developer
|
||||
status: active
|
||||
version: 2.7
|
||||
version: 2.8.0
|
||||
context: "Aktuelle Planung für kommende Features (ab WP16), Release-Strategie und Historie der abgeschlossenen WPs."
|
||||
---
|
||||
|
||||
# Mindnet Active Roadmap
|
||||
|
||||
**Aktueller Stand:** v2.6.0 (Post-WP15/WP19)
|
||||
**Fokus:** Visualisierung, Exploration & Intelligent Ingestion.
|
||||
**Aktueller Stand:** v2.8.0 (Post-WP20/WP76)
|
||||
**Fokus:** Visualisierung, Exploration & Cloud-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.
|
||||
Wir haben mit der Implementierung des Graph Explorers (WP19), der Smart Edge Allocation (WP15) und der hybriden Cloud-Resilienz (WP20) die Basis für ein intelligentes, robustes System gelegt. Der nächste Schritt (WP19a) vertieft die Analyse, während WP16 die "Eingangs-Intelligenz" erhöht.
|
||||
|
||||
| Phase | Fokus | Status |
|
||||
| :--- | :--- | :--- |
|
||||
@@ -47,7 +47,7 @@ Eine Übersicht der implementierten Features zum schnellen Auffinden von Funktio
|
||||
| **WP-11** | Backend Intelligence | `nomic-embed-text` (768d) und Matrix-Logik für Kanten-Typisierung. |
|
||||
| **WP-15** | Smart Edge Allocation | LLM-Filter für Kanten in Chunks + Traffic Control (Semaphore) + Strict Chunking. |
|
||||
| **WP-19** | Graph Visualisierung | **Frontend Modularisierung:** Umbau auf `ui_*.py`.<br>**Graph Engines:** Parallelbetrieb von Cytoscape (COSE) und Agraph.<br>**Tools:** "Single Source of Truth" Editor, Persistenz via URL. |
|
||||
| **WP-20** | Cloud Hybrid Mode | 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-22** | **Content Lifecycle & Registry** | **Ergebnis:** SSOT via `01_edge_vocabulary.md`, Alias-Mapping, Status-Scoring (`stable`/`draft`) und Modularisierung der Scoring-Engine. |
|
||||
|
||||
@@ -55,6 +55,9 @@ Eine Übersicht der implementierten Features zum schnellen Auffinden von Funktio
|
||||
* **Architektur:** Die Trennung von `retriever.py` und `retriever_scoring.py` war notwendig, um LLM-Context-Limits zu wahren und die Testbarkeit der mathematischen Formeln zu erhöhen.
|
||||
* **Kanten-Validierung:** Die Edge Registry muss beim Start explizit initialisiert werden (Singleton), um "Lazy Loading" Probleme in der API zu vermeiden.
|
||||
|
||||
### 2.2 WP-20 Lessons Learned (Resilienz)
|
||||
* **Quoten-Management:** Die Nutzung von Free-Tier Modellen (Mistral/OpenRouter) erfordert zwingend eine intelligente Rate-Limit-Erkennung (HTTP 429) mit automatisierten Wartezyklen, um Batch-Prozesse stabil zu halten.
|
||||
* **Parser-Robustheit:** Cloud-Modelle betten JSON oft in technische Steuerzeichen (`<s>`, `[OUT]`) ein. Ein robuster Extraktor mit Recovery-Logik ist essentiell zur Vermeidung von Datenverlust.
|
||||
|
||||
---
|
||||
|
||||
@@ -80,7 +83,7 @@ Diese Features stehen als nächstes an oder befinden sich in der Umsetzung.
|
||||
**Phase:** B
|
||||
**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:**
|
||||
- Tools zur Analyse des Vault-Status.
|
||||
@@ -90,6 +93,26 @@ Diese Features stehen als nächstes an oder befinden sich in der Umsetzung.
|
||||
- Aufwand: Mittel
|
||||
- Komplexität: Niedrig/Mittel
|
||||
|
||||
### WP-15b – Candidate-Based Edge Validation & Inheritance
|
||||
**Phase:** B/E (Refactoring & Semantic)
|
||||
**Status:** 🚀 Startklar (Ersatz für WP-15 Logik)
|
||||
**Ziel:** Ablösung der fehleranfälligen "Open-End-Extraktion" durch eine KI-gestützte Validierung menschlicher Vorarbeit zur Steigerung von Speed, Integrität und semantischer Tiefe.
|
||||
|
||||
**Herausforderung:**
|
||||
Der bisherige WP-15 Ansatz litt unter Halluzinationen (erfundene Kantentypen), hohem Token-Verbrauch und dem Verlust physikalisch gesetzter Kanten bei der Chunk-Verteilung.
|
||||
|
||||
**Anforderungen & Strategie:**
|
||||
1. **Hard-Link Integrity:** Kanten, die im Markdown-Text eines Chunks stehen, werden zwingend und ohne LLM-Prüfung gesetzt (`provenance: explicit`).
|
||||
2. **Edge Inheritance:** Kanten, die auf Dokument-Ebene (Frontmatter) oder Sektions-Ebene (Heading) definiert sind, werden automatisch an alle zugehörigen Sub-Chunks vererbt, wenn ein semantischer Block aufgrund von Größengrenzen geteilt wurde.
|
||||
3. **Candidate Pool Extraction:** Definition eines "Edge-Pools" pro Dokument. Dieser speist sich aus dem Frontmatter und einer speziellen Sektion (z. B. `### Unzugeordnete Kanten`).
|
||||
4. **Semantic Validation Gate:** Das LLM fungiert als binärer Validator. Es prüft ausschließlich Kanten aus dem Kandidaten-Pool gegen den konkreten Chunk-Inhalt UND eine Zusammenfassung der Ziel-Note (Inhalt, Typ, Kanten-Typ).
|
||||
5. **Registry Enforcement:** Strikte Blockade von Halluzinationen. Nur Kanten, die im Pool definiert UND im `edge_vocabulary.md` vorhanden sind, werden zugelassen.
|
||||
|
||||
**Lösungsskizze:**
|
||||
* **Parser-Update:** `extract_candidate_pool` zur Identifikation aller im Dokument beabsichtigten Links.
|
||||
* **Chunker-Update:** Implementierung einer `propagate_edges`-Logik für "by_heading" und "sliding_window" Strategien.
|
||||
* **Ingestion-Update:** Umstellung von `_perform_smart_edge_allocation` auf einen binären Validierungs-Prompt (VALID/INVALID).
|
||||
|
||||
### WP-19a – Graph Intelligence & Discovery (Sprint-Fokus)
|
||||
**Status:** 🚀 Startklar
|
||||
**Ziel:** Vom "Anschauen" zum "Verstehen". Deep-Dive Werkzeuge für den Graphen.
|
||||
@@ -102,7 +125,7 @@ Diese Features stehen als nächstes an oder befinden sich in der Umsetzung.
|
||||
**Ziel:** Technische Schulden abbauen, die durch schnelle Feature-Entwicklung (WP15/WP19) entstanden sind.
|
||||
* **Refactoring `chunker.py`:** Die Datei ist monolithisch geworden (Parsing, Strategien, LLM-Orchestrierung).
|
||||
* *Lösung:* Aufteilung in ein Package `app/core/chunking/` mit Modulen (`strategies.py`, `orchestration.py`, `utils.py`).
|
||||
* **Dokumentation:** Kontinuierliche Synchronisation von Code und Docs (v2.6 Stand).
|
||||
* **Dokumentation:** Kontinuierliche Synchronisation von Code und Docs (v2.8 Stand).
|
||||
|
||||
### WP-16 – Auto-Discovery & Intelligent Ingestion
|
||||
**Status:** 🟡 Geplant
|
||||
@@ -135,11 +158,6 @@ Diese Features stehen als nächstes an oder befinden sich in der Umsetzung.
|
||||
**Ziel:** mindnet als MCP-Server bereitstellen, damit Agenten (Claude Desktop, OpenAI) standardisierte Tools nutzen können.
|
||||
* **Umfang:** MCP-Server mit Tools (`mindnet_query`, `mindnet_explain`, etc.).
|
||||
|
||||
### WP-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
|
||||
**Status:** 🟡 Geplant
|
||||
**Ziel:** Transformation des Graphen von statischen Verbindungen zu dynamischen, kontextsensitiven Pfaden. Das System soll verstehen, *welche* Art von Verbindung für die aktuelle Frage relevant ist ("Warum?" vs. "Was kommt danach?").
|
||||
@@ -167,44 +185,42 @@ 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.
|
||||
3. **Self-Learning Loop:** Protokollierung unbekannter Kanten in `unknown_edges.jsonl`.
|
||||
|
||||
## 23: Agentic Multi-Stream Reasoning (Mindnet 2025)
|
||||
### WP-23: Agentic Multi-Stream Reasoning (Mindnet 2025)
|
||||
|
||||
### 1. Zielsetzung & Problemstellung
|
||||
#### 1. Zielsetzung & Problemstellung
|
||||
Das bisherige System basiert auf einem globalen Scoring-Modell, bei dem Notizen unterschiedlicher Typen (z. B. `insight` vs. `belief`) in einem einzigen Retrieval-Topf konkurrieren. Dies führt dazu, dass leiser gewichtete, aber fundamentale Identitätsmerkmale oft durch hochgewichtete aktuelle Erkenntnisse verdrängt werden. Ziel dieses Pakets ist die Einführung einer parallelen **Stream-Architektur**, um die Vielschichtigkeit menschlicher Entscheidungsprozesse (Werte + Erfahrung + Absicht) im LLM-Kontext zu garantieren.
|
||||
|
||||
---
|
||||
|
||||
### 2. Funktionsbeschreibung: Die Streams
|
||||
#### 2. Funktionsbeschreibung: Die Streams
|
||||
Die Daten aus der `types.yaml` werden in drei logische Verarbeitungseinheiten unterteilt:
|
||||
|
||||
#### A. Identity Stream (Die Wahrheitsebene)
|
||||
##### A. Identity Stream (Die Wahrheitsebene)
|
||||
* **Inhalt:** `value`, `belief`, `trait`, `principle`, `need`, `boundary`, `bias`.
|
||||
* **Zweck:** Definition des moralischen Kompasses, der psychologischen Grundbedürfnisse und kognitiven Muster.
|
||||
* **Wirkung:** Liefert das "Warum" hinter jeder Handlung.
|
||||
|
||||
#### B. History Stream (Die Evidenzebene)
|
||||
##### B. History Stream (Die Evidenzebene)
|
||||
* **Inhalt:** `experience`, `event`, `source`, `journal`, `person`.
|
||||
* **Zweck:** Bereitstellung empirischer Belege aus der Vergangenheit und sozialer Kontexte.
|
||||
* **Wirkung:** Verankert die Antwort in real erlebten Mustern und Fakten.
|
||||
|
||||
#### C. Action Stream (Die Dynamikebene)
|
||||
##### C. Action Stream (Die Dynamikebene)
|
||||
* **Inhalt:** `project`, `decision`, `goal`, `task`, `risk`, `motivation`, `habit`, `state`.
|
||||
* **Zweck:** Analyse der aktuellen Richtung, geplanter Vorhaben und des gegenwärtigen Zustands.
|
||||
* **Wirkung:** Liefert den Kontext für die Umsetzung und zukünftige Ziele.
|
||||
|
||||
|
||||
### 3. Technische Wirkungsweise (Solution Sketch)
|
||||
#### 3. Technische Wirkungsweise (Solution Sketch)
|
||||
|
||||
#### Schritt 1: Query-Decomposition
|
||||
##### Schritt 1: Query-Decomposition
|
||||
Ein initialer Klassifizierungs-Agent analysiert die Nutzeranfrage und bestimmt, welcher Stream primär angesprochen werden muss (z. B. "Wie soll ich mich entscheiden?" boostet den Identity Stream).
|
||||
|
||||
#### Schritt 2: Parallel Stream Retrieval
|
||||
##### Schritt 2: Parallel Stream Retrieval
|
||||
Anstelle einer Suche werden drei unabhängige Vektor-Suchen mit Typ-Filtern durchgeführt:
|
||||
* **Search_A (Identity):** Top-5 Ergebnisse aus Identitäts-Notizen.
|
||||
* **Search_B (History):** Top-5 Ergebnisse aus biografischen/externen Notizen.
|
||||
* **Search_C (Action):** Top-5 Ergebnisse aus operativen/strategischen Notizen.
|
||||
|
||||
#### Schritt 3: Agentic Synthesis (The Reasoning)
|
||||
##### Schritt 3: Agentic Synthesis (The Reasoning)
|
||||
Ein Synthese-Agent (LLM) erhält die aggregierten Ergebnisse in getrennten Sektionen. Die Anweisung lautet:
|
||||
1. **Prüfung:** Steht das aktuelle Vorhaben (Action) im Einklang mit den Werten (Identity)?
|
||||
2. **Abgleich:** Welche vergangenen Erfahrungen (History) stützen oder widersprechen diesem Weg?
|
||||
@@ -212,12 +228,39 @@ Ein Synthese-Agent (LLM) erhält die aggregierten Ergebnisse in getrennten Sekti
|
||||
|
||||
|
||||
|
||||
### 4. Erwartete Ergebnisse
|
||||
#### 4. Erwartete Ergebnisse
|
||||
* **Höhere Resonanz:** Antworten wirken authentischer, da sie explizit auf das Wertesystem des Nutzers Bezug nehmen.
|
||||
* **Widerspruchs-Erkennung:** Das System kann den Nutzer aktiv warnen, wenn ein Projekt gegen seine `principles` oder `needs` verstößt.
|
||||
* **Robustes Retrieval:** Wichtige Identitäts-Informationen gehen nicht mehr im "Rauschen" von hunderten Journal-Einträgen verloren.
|
||||
---
|
||||
|
||||
### 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
|
||||
|
||||
```mermaid
|
||||
@@ -226,6 +269,8 @@ graph TD
|
||||
WP19a --> WP17(Memory)
|
||||
WP15(Smart Edges) --> WP16(Auto-Discovery)
|
||||
WP15 --> WP14(Refactoring)
|
||||
WP15(Smart Edges) --> WP15b(Candidate Validation)
|
||||
WP15b --> WP24(Proactive Discovery)
|
||||
WP03(Import) --> WP18(Health Check)
|
||||
WP03 --> WP13(MCP)
|
||||
WP04 --> WP13(MCP)
|
||||
@@ -233,4 +278,7 @@ graph TD
|
||||
WP03(Import Pipeline) --> WP21
|
||||
WP21 --> WP22(Lifecycle & Registry)
|
||||
WP22 --> WP14
|
||||
WP15(Smart Edges) --> WP21
|
||||
WP15(Smart Edges) --> WP21
|
||||
WP20(Cloud Hybrid) --> WP15b
|
||||
WP24 --> WP23(Multi-Stream Reasoning)
|
||||
```
|
||||
@@ -315,4 +315,45 @@ Die Gewichtung findet **Pre-Retrieval** (im Scoring-Algorithmus) statt, **nicht*
|
||||
2. Zeige die Integration in `ingestion.py` (Status-Filter & Edge-Validierung).
|
||||
3. Zeige die Erweiterung in `scoring.py` (Status-Gewicht & Dynamic Edge Boosting).
|
||||
|
||||
Bitte bestätige die Übernahme dieses Architektur-Pakets.
|
||||
Bitte bestätige die Übernahme dieses Architektur-Pakets.
|
||||
|
||||
---
|
||||
|
||||
# Ü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.
|
||||
+7
-1
@@ -34,4 +34,10 @@ streamlit>=1.39.0
|
||||
|
||||
# Visualization (Parallelbetrieb)
|
||||
streamlit-agraph>=0.0.45
|
||||
st-cytoscape
|
||||
st-cytoscape
|
||||
|
||||
# Google gemini API
|
||||
google-genai>=0.3.0
|
||||
|
||||
# OpenAi für OpenRouter
|
||||
openai>=1.50.0
|
||||
+43
-17
@@ -2,7 +2,10 @@
|
||||
"""
|
||||
scripts/import_markdown.py
|
||||
CLI-Tool zum Importieren von Markdown-Dateien in Qdrant.
|
||||
Updated for Mindnet v2.3.6 (Async Ingestion Support).
|
||||
WP-15b: Implementiert den Two-Pass Workflow (Pre-Scan + Processing).
|
||||
Sorgt dafür, dass der LocalBatchCache vor der Verarbeitung robust gefüllt wird.
|
||||
Indiziert Notizen nach ID, Titel und Dateiname für maximale Link-Kompatibilität.
|
||||
VERSION: 2.4.1
|
||||
"""
|
||||
import asyncio
|
||||
import os
|
||||
@@ -11,21 +14,16 @@ import logging
|
||||
from pathlib import Path
|
||||
from dotenv import load_dotenv
|
||||
|
||||
import logging
|
||||
# Setzt das Level global auf INFO, damit Sie den Fortschritt sehen
|
||||
# Setzt das Level global auf INFO, damit der Fortschritt im Log sichtbar ist
|
||||
logging.basicConfig(level=logging.INFO, format='%(asctime)s [%(levelname)s] %(message)s')
|
||||
|
||||
# Wenn Sie TIEFE Einblicke wollen, setzen Sie den SemanticAnalyzer spezifisch auf DEBUG:
|
||||
logging.getLogger("app.services.semantic_analyzer").setLevel(logging.DEBUG)
|
||||
|
||||
# Importiere den neuen Async Service
|
||||
# Stellen wir sicher, dass der Pfad stimmt (Pythonpath)
|
||||
# Importiere den neuen Async Service und stelle Python-Pfad sicher
|
||||
import sys
|
||||
sys.path.append(os.getcwd())
|
||||
|
||||
from app.core.ingestion import IngestionService
|
||||
from app.core.parser import pre_scan_markdown
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
|
||||
logger = logging.getLogger("importer")
|
||||
|
||||
async def main_async(args):
|
||||
@@ -34,7 +32,7 @@ async def main_async(args):
|
||||
logger.error(f"Vault path does not exist: {vault_path}")
|
||||
return
|
||||
|
||||
# Service initialisieren (startet Async Clients)
|
||||
# 1. Service initialisieren
|
||||
logger.info(f"Initializing IngestionService (Prefix: {args.prefix})")
|
||||
service = IngestionService(collection_prefix=args.prefix)
|
||||
|
||||
@@ -46,14 +44,42 @@ async def main_async(args):
|
||||
|
||||
logger.info(f"Found {len(files)} markdown files.")
|
||||
|
||||
stats = {"processed": 0, "skipped": 0, "errors": 0}
|
||||
# =========================================================================
|
||||
# PASS 1: Global Pre-Scan (WP-15b Harvester)
|
||||
# Füllt den LocalBatchCache für die semantische Kanten-Validierung.
|
||||
# Nutzt ID, Titel und Filename für robusten Look-up.
|
||||
# =========================================================================
|
||||
logger.info(f"🔍 [Pass 1] Pre-scanning {len(files)} files for global context cache...")
|
||||
for f_path in files:
|
||||
try:
|
||||
ctx = pre_scan_markdown(str(f_path))
|
||||
if ctx:
|
||||
# 1. Look-up via Note ID (UUID oder Frontmatter ID)
|
||||
service.batch_cache[ctx.note_id] = ctx
|
||||
|
||||
# 2. Look-up via Titel (Wichtig für Wikilinks [[Titel]])
|
||||
service.batch_cache[ctx.title] = ctx
|
||||
|
||||
# 3. Look-up via Dateiname (Wichtig für Wikilinks [[Filename]])
|
||||
fname = os.path.splitext(f_path.name)[0]
|
||||
service.batch_cache[fname] = ctx
|
||||
|
||||
except Exception as e:
|
||||
logger.warning(f"⚠️ Could not pre-scan {f_path.name}: {e}")
|
||||
|
||||
# Wir nutzen eine Semaphore, um nicht zu viele Files gleichzeitig zu öffnen/embedden
|
||||
sem = asyncio.Semaphore(5) # Max 5 concurrent files to avoid OOM or Rate Limit
|
||||
logger.info(f"✅ Context Cache populated for {len(files)} notes.")
|
||||
|
||||
# =========================================================================
|
||||
# PASS 2: Processing (Semantic Batch-Verarbeitung)
|
||||
# Nutzt den gefüllten Cache zur binären Validierung semantischer Kanten.
|
||||
# =========================================================================
|
||||
stats = {"processed": 0, "skipped": 0, "errors": 0}
|
||||
sem = asyncio.Semaphore(5) # Max 5 parallele Dateien für Cloud-Stabilität
|
||||
|
||||
async def process_with_limit(f_path):
|
||||
async with sem:
|
||||
try:
|
||||
# Nutzt den nun gefüllten Batch-Cache in der process_file Logik
|
||||
res = await service.process_file(
|
||||
file_path=str(f_path),
|
||||
vault_root=str(vault_path),
|
||||
@@ -65,8 +91,8 @@ async def main_async(args):
|
||||
except Exception as e:
|
||||
return {"status": "error", "error": str(e), "path": str(f_path)}
|
||||
|
||||
# Batch Processing
|
||||
# Wir verarbeiten in Chunks, um den Progress zu sehen
|
||||
logger.info(f"🚀 [Pass 2] Starting semantic processing in batches...")
|
||||
|
||||
batch_size = 20
|
||||
for i in range(0, len(files), batch_size):
|
||||
batch = files[i:i+batch_size]
|
||||
@@ -92,7 +118,7 @@ def main():
|
||||
load_dotenv()
|
||||
default_prefix = os.getenv("COLLECTION_PREFIX", "mindnet")
|
||||
|
||||
parser = argparse.ArgumentParser(description="Import Vault to Qdrant (Async)")
|
||||
parser = argparse.ArgumentParser(description="Two-Pass Markdown Ingestion for Mindnet")
|
||||
parser.add_argument("--vault", default="./vault", help="Path to vault root")
|
||||
parser.add_argument("--prefix", default=default_prefix, help="Collection prefix")
|
||||
parser.add_argument("--force", action="store_true", help="Force re-index all files")
|
||||
@@ -100,7 +126,7 @@ def main():
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
# Starte den Async Loop
|
||||
# Starte den asynchronen Haupt-Loop
|
||||
asyncio.run(main_async(args))
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
Reference in new issue
Block a user