Enhance chunking system with WP-24c v4.2.6 and v4.2.7 updates: Introduce is_meta_content flag for callouts in RawBlock, ensuring they are chunked but later removed for clean context. Update parse_blocks and propagate_section_edges to handle callout edges with explicit provenance for chunk attribution. Implement clean-context logic to remove callout syntax post-processing, maintaining chunk integrity. Adjust get_chunk_config to prioritize frontmatter overrides for chunking profiles. Update documentation to reflect these changes.

This commit is contained in:
Lars committed 2026-01-11 11:14:31 +01:00
1 parent 4d43cc526e
commit 55b64c331a
8 files changed
+231 -43

No files matched your search

+83 -14
View File
@@ -7,6 +7,16 @@ DESCRIPTION: Der zentrale Orchestrator für das Chunking-System.
- Stellt H1-Kontext-Fenster sicher.
- Baut den Candidate-Pool für die WP-15b Ingestion auf.
WP-24c v4.2.0: Konfigurierbare Header-Namen für LLM-Validierung.
WP-24c v4.2.5: Wiederherstellung der Chunking-Präzision
- Frontmatter-Override für chunking_profile
- Callout-Exclusion aus Chunks
- Strict-Mode ohne Carry-Over
WP-24c v4.2.6: Finale Härtung - "Semantic First, Clean Second"
- Callouts werden gechunkt (Chunk-Attribution), aber später entfernt (Clean-Context)
- remove_callouts_from_text erst nach propagate_section_edges und Candidate Pool
WP-24c v4.2.7: Wiederherstellung der Chunk-Attribution
- Callout-Kanten erhalten explicit:callout Provenance im candidate_pool
- graph_derive_edges.py erkennt diese und verhindert Note-Scope Duplikate
"""
import asyncio
import re
@@ -25,16 +35,19 @@ async def assemble_chunks(note_id: str, md_text: str, note_type: str, config: Op
"""
Hauptfunktion zur Zerlegung einer Note.
Verbindet Strategien mit physikalischer Kontext-Anreicherung.
WP-24c v4.2.5: Frontmatter-Override für chunking_profile wird berücksichtigt.
"""
# 1. Konfiguration & Parsing
if config is None:
config = get_chunk_config(note_type)
# 1. WP-24c v4.2.5: Frontmatter VOR Konfiguration extrahieren (für Override)
fm, body_text = extract_frontmatter_from_text(md_text)
# 2. Konfiguration mit Frontmatter-Override
if config is None:
config = get_chunk_config(note_type, frontmatter=fm)
blocks, doc_title = parse_blocks(md_text)
# WP-24c v4.2.0: Filtere Blöcke aus Edge-Zonen (LLM-Validierung & Note-Scope)
# Diese Bereiche sollen nicht als Chunks angelegt werden, sondern nur die Kanten extrahiert werden
# WP-24c v4.2.6: Filtere NUR Edge-Zonen (LLM-Validierung & Note-Scope)
# Callouts (is_meta_content=True) müssen durch, damit Chunk-Attribution erhalten bleibt
blocks_for_chunking = [b for b in blocks if not getattr(b, 'exclude_from_chunking', False)]
# Vorbereitung des H1-Präfix für die Embedding-Fenster (Breadcrumbs)
@@ -42,6 +55,7 @@ async def assemble_chunks(note_id: str, md_text: str, note_type: str, config: Op
# 2. Anwendung der Splitting-Strategie
# Alle Strategien nutzen nun einheitlich context_prefix für die Window-Bildung.
# WP-24c v4.2.6: Callouts sind in blocks_for_chunking enthalten (für Chunk-Attribution)
if config.get("strategy") == "by_heading":
chunks = await asyncio.to_thread(
strategy_by_heading, blocks_for_chunking, config, note_id, context_prefix=h1_prefix
@@ -55,21 +69,27 @@ async def assemble_chunks(note_id: str, md_text: str, note_type: str, config: Op
return []
# 3. Physikalische Kontext-Anreicherung (Der Qualitäts-Fix)
# WP-24c v4.2.6: Arbeite auf Original-Text inkl. Callouts (für korrekte Chunk-Attribution)
# Schreibt Kanten aus Callouts/Inlines hart in den Text für Qdrant.
chunks = propagate_section_edges(chunks)
# 4. WP-15b: Candidate Pool Aufbau (Metadaten für IngestionService)
# 5. WP-15b: Candidate Pool Aufbau (Metadaten für IngestionService)
# WP-24c v4.2.7: Markiere Callout-Kanten explizit für Chunk-Attribution
# Zuerst die explizit im Text vorhandenen Kanten sammeln.
for ch in chunks:
# Wir extrahieren aus dem bereits (durch Propagation) angereicherten Text.
# ch.candidate_pool wird im Modell-Konstruktor als leere Liste initialisiert.
for e_str in parse_edges_robust(ch.text):
parts = e_str.split(':', 1)
for edge_info in parse_edges_robust(ch.text):
edge_str = edge_info["edge"]
is_callout = edge_info.get("is_callout", False)
parts = edge_str.split(':', 1)
if len(parts) == 2:
k, t = parts
ch.candidate_pool.append({"kind": k, "to": t, "provenance": "explicit"})
# WP-24c v4.2.7: Callout-Kanten erhalten explicit:callout Provenance
provenance = "explicit:callout" if is_callout else "explicit"
ch.candidate_pool.append({"kind": k, "to": t, "provenance": provenance})
# 5. Global Pool (Unzugeordnete Kanten - kann mitten im Dokument oder am Ende stehen)
# 6. Global Pool (Unzugeordnete Kanten - kann mitten im Dokument oder am Ende stehen)
# WP-24c v4.2.0: Konfigurierbare Header-Namen und -Ebene via .env
# Sucht nach ALLEN Edge-Pool Blöcken im Original-Markdown (nicht nur am Ende).
llm_validation_headers = os.getenv(
@@ -93,15 +113,16 @@ async def assemble_chunks(note_id: str, md_text: str, note_type: str, config: Op
for pool_match in re.finditer(zone_pattern, body_text, re.DOTALL | re.IGNORECASE | re.MULTILINE):
global_edges = parse_edges_robust(pool_match.group(1))
for e_str in global_edges:
parts = e_str.split(':', 1)
for edge_info in global_edges:
edge_str = edge_info["edge"]
parts = edge_str.split(':', 1)
if len(parts) == 2:
k, t = parts
# Diese Kanten werden als "global_pool" markiert für die spätere KI-Prüfung.
for ch in chunks:
ch.candidate_pool.append({"kind": k, "to": t, "provenance": "global_pool"})
# 6. De-Duplikation des Pools & Linking
# 7. De-Duplikation des Pools & Linking
for ch in chunks:
seen = set()
unique = []
@@ -113,6 +134,54 @@ async def assemble_chunks(note_id: str, md_text: str, note_type: str, config: Op
unique.append(c)
ch.candidate_pool = unique
# 8. WP-24c v4.2.6: Clean-Context - Entferne Callout-Syntax aus Chunk-Text
# WICHTIG: Dies geschieht NACH propagate_section_edges und Candidate Pool Aufbau,
# damit Chunk-Attribution erhalten bleibt und Kanten korrekt extrahiert werden.
# Hinweis: Callouts können mehrzeilig sein (auch verschachtelt: >>)
def remove_callouts_from_text(text: str) -> str:
"""Entfernt alle Callout-Zeilen (> [!edge] oder > [!abstract]) aus dem Text."""
if not text:
return text
lines = text.split('\n')
cleaned_lines = []
i = 0
callout_start_pattern = re.compile(r'^\s*>{1,}\s*\[!(edge|abstract)\]', re.IGNORECASE)
while i < len(lines):
line = lines[i]
callout_match = callout_start_pattern.match(line)
if callout_match:
# Callout gefunden: Überspringe alle Zeilen des Callout-Blocks
leading_gt_count = len(line) - len(line.lstrip('>'))
i += 1
# Überspringe alle Zeilen, die zum Callout gehören
while i < len(lines):
next_line = lines[i]
if not next_line.strip().startswith('>'):
break
next_leading_gt = len(next_line) - len(next_line.lstrip('>'))
if next_leading_gt < leading_gt_count:
break
i += 1
else:
# Normale Zeile: Behalte
cleaned_lines.append(line)
i += 1
# Normalisiere Leerzeilen (max. 2 aufeinanderfolgende)
result = '\n'.join(cleaned_lines)
result = re.sub(r'\n\s*\n\s*\n+', '\n\n', result)
return result
for ch in chunks:
ch.text = remove_callouts_from_text(ch.text)
if ch.window:
ch.window = remove_callouts_from_text(ch.window)
# Verknüpfung der Nachbarschaften für Graph-Traversierung
for i, ch in enumerate(chunks):
ch.neighbors_prev = chunks[i-1].id if i > 0 else None