ragdial-mcp 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- ragdial_mcp/__init__.py +3 -0
- ragdial_mcp/chunking/__init__.py +0 -0
- ragdial_mcp/chunking/boundary_audit.py +140 -0
- ragdial_mcp/chunking/strategies.py +335 -0
- ragdial_mcp/demo.py +73 -0
- ragdial_mcp/ingestion/__init__.py +0 -0
- ragdial_mcp/ingestion/parser.py +251 -0
- ragdial_mcp/lab.py +485 -0
- ragdial_mcp/models.py +141 -0
- ragdial_mcp/py.typed +0 -0
- ragdial_mcp/retrieval/__init__.py +0 -0
- ragdial_mcp/retrieval/embedders.py +136 -0
- ragdial_mcp/retrieval/hybrid.py +203 -0
- ragdial_mcp/retrieval/metrics.py +62 -0
- ragdial_mcp/sample_data/corpus/api_reference.md +77 -0
- ragdial_mcp/sample_data/corpus/architecture.md +27 -0
- ragdial_mcp/sample_data/corpus/changelog.md +51 -0
- ragdial_mcp/sample_data/corpus/config_reference.md +88 -0
- ragdial_mcp/sample_data/corpus/deployment_runbook.md +74 -0
- ragdial_mcp/sample_data/corpus/error_codes.md +57 -0
- ragdial_mcp/sample_data/corpus/faq.txt +28 -0
- ragdial_mcp/sample_data/corpus/incident_postmortem_2026_09.md +38 -0
- ragdial_mcp/sample_data/corpus/migration_v2_to_v3.md +56 -0
- ragdial_mcp/sample_data/corpus/pricing_plans.md +45 -0
- ragdial_mcp/sample_data/corpus/python_sdk.md +122 -0
- ragdial_mcp/sample_data/corpus/rate_limits.md +51 -0
- ragdial_mcp/sample_data/corpus/security_policy.md +35 -0
- ragdial_mcp/sample_data/golden_qa.jsonl +30 -0
- ragdial_mcp/samples.py +30 -0
- ragdial_mcp/server.py +205 -0
- ragdial_mcp/storage/__init__.py +0 -0
- ragdial_mcp/storage/db.py +160 -0
- ragdial_mcp/tokens.py +67 -0
- ragdial_mcp-0.1.0.dist-info/METADATA +364 -0
- ragdial_mcp-0.1.0.dist-info/RECORD +38 -0
- ragdial_mcp-0.1.0.dist-info/WHEEL +4 -0
- ragdial_mcp-0.1.0.dist-info/entry_points.txt +3 -0
- ragdial_mcp-0.1.0.dist-info/licenses/LICENSE +21 -0
ragdial_mcp/__init__.py
ADDED
|
File without changes
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
"""Boundary-damage audit.
|
|
2
|
+
|
|
3
|
+
A structure (table, code fence, list, paragraph) is **severed** when no single
|
|
4
|
+
chunk's source span contains it whole. Overlap can rescue a structure: if a
|
|
5
|
+
cut lands inside a table but another chunk still holds the full table, it is
|
|
6
|
+
intact somewhere and not counted.
|
|
7
|
+
|
|
8
|
+
A severed table is **mitigated** when every chunk touching its rows also
|
|
9
|
+
carries the table's header row in its text (the ``markdown`` chunker
|
|
10
|
+
replicates headers), so each piece is still self-describing.
|
|
11
|
+
|
|
12
|
+
``damage_score`` is the weighted share of severed structures, 0.0 (perfect)
|
|
13
|
+
to 1.0 (everything cut). Tables and code are weighted higher than prose
|
|
14
|
+
because a split row or function loses its meaning; mitigated tables count
|
|
15
|
+
at half weight.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import bisect
|
|
21
|
+
from collections import defaultdict
|
|
22
|
+
|
|
23
|
+
from pydantic import BaseModel
|
|
24
|
+
|
|
25
|
+
from ..ingestion.parser import Block, Document
|
|
26
|
+
from .strategies import Chunk
|
|
27
|
+
|
|
28
|
+
WEIGHTS = {"table": 3.0, "code": 3.0, "list": 1.5, "paragraph": 1.0}
|
|
29
|
+
KIND_PRIORITY = {"table": 0, "code": 1, "list": 2, "paragraph": 3}
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class SeveredStructure(BaseModel):
|
|
33
|
+
doc_id: str
|
|
34
|
+
section_id: str
|
|
35
|
+
kind: str
|
|
36
|
+
start: int
|
|
37
|
+
end: int
|
|
38
|
+
cut_at: int
|
|
39
|
+
left_chunk: str | None
|
|
40
|
+
right_chunk: str | None
|
|
41
|
+
mitigated: bool
|
|
42
|
+
oversized: bool # larger than the chunk size, so it could never fit in one chunk
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class KindDamage(BaseModel):
|
|
46
|
+
total: int
|
|
47
|
+
severed: int
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class AuditResult(BaseModel):
|
|
51
|
+
damage_score: float
|
|
52
|
+
structures: int
|
|
53
|
+
severed: int
|
|
54
|
+
mitigated: int
|
|
55
|
+
by_kind: dict[str, KindDamage]
|
|
56
|
+
severed_items: list[SeveredStructure]
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _severed(doc: Document, block: Block, chunks: list[Chunk], starts: list[int],
|
|
60
|
+
size: int, token_count: int) -> SeveredStructure | None:
|
|
61
|
+
# candidate chunks are those starting at or before the structure start
|
|
62
|
+
hi = bisect.bisect_right(starts, block.start)
|
|
63
|
+
for c in chunks[:hi]:
|
|
64
|
+
if c.start <= block.start and c.end >= block.end:
|
|
65
|
+
return None
|
|
66
|
+
touching = [c for c in chunks if c.start < block.end and c.end > block.start]
|
|
67
|
+
if not touching: # structure fell entirely outside chunks (e.g. whitespace-only)
|
|
68
|
+
return None
|
|
69
|
+
# first boundary strictly inside the structure
|
|
70
|
+
cut, left, right = block.start, None, None
|
|
71
|
+
candidates: list[tuple[int, str | None, str | None]] = []
|
|
72
|
+
for c in touching:
|
|
73
|
+
if block.start < c.end < block.end:
|
|
74
|
+
candidates.append((c.end, c.chunk_id, None))
|
|
75
|
+
if block.start < c.start < block.end:
|
|
76
|
+
candidates.append((c.start, None, c.chunk_id))
|
|
77
|
+
if candidates:
|
|
78
|
+
cut = min(x[0] for x in candidates)
|
|
79
|
+
left = next((c.chunk_id for c in touching if c.start < cut <= c.end), None)
|
|
80
|
+
right = next((c.chunk_id for c in touching if c.start <= cut < c.end and c.chunk_id != left), None)
|
|
81
|
+
mitigated = False
|
|
82
|
+
if block.kind == "table" and block.header_line:
|
|
83
|
+
mitigated = all(block.header_line in c.text for c in touching)
|
|
84
|
+
return SeveredStructure(doc_id=doc.doc_id, section_id=block.section_id, kind=block.kind,
|
|
85
|
+
start=block.start, end=block.end, cut_at=cut, left_chunk=left,
|
|
86
|
+
right_chunk=right, mitigated=mitigated, oversized=token_count > size)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def audit_boundaries(docs: list[Document], chunks: list[Chunk], size: int,
|
|
90
|
+
token_counts: dict[tuple[str, int, int], int] | None = None) -> AuditResult:
|
|
91
|
+
by_doc: dict[str, list[Chunk]] = defaultdict(list)
|
|
92
|
+
for c in chunks:
|
|
93
|
+
by_doc[c.doc_id].append(c)
|
|
94
|
+
totals: dict[str, int] = defaultdict(int)
|
|
95
|
+
severed_counts: dict[str, int] = defaultdict(int)
|
|
96
|
+
items: list[SeveredStructure] = []
|
|
97
|
+
weight_total = weight_damage = 0.0
|
|
98
|
+
for doc in docs:
|
|
99
|
+
doc_chunks = sorted(by_doc.get(doc.doc_id, []), key=lambda c: c.start)
|
|
100
|
+
starts = [c.start for c in doc_chunks]
|
|
101
|
+
for block in doc.structures:
|
|
102
|
+
s, e = block.start, block.end
|
|
103
|
+
while s < e and doc.text[s].isspace():
|
|
104
|
+
s += 1
|
|
105
|
+
while e > s and doc.text[e - 1].isspace():
|
|
106
|
+
e -= 1
|
|
107
|
+
if e <= s:
|
|
108
|
+
continue
|
|
109
|
+
block = block.model_copy(update={"start": s, "end": e})
|
|
110
|
+
w = WEIGHTS.get(block.kind, 1.0)
|
|
111
|
+
totals[block.kind] += 1
|
|
112
|
+
weight_total += w
|
|
113
|
+
n = (token_counts or {}).get((doc.doc_id, block.start, block.end), 0)
|
|
114
|
+
hit = _severed(doc, block, doc_chunks, starts, size, n)
|
|
115
|
+
if hit:
|
|
116
|
+
severed_counts[block.kind] += 1
|
|
117
|
+
weight_damage += w * (0.5 if hit.mitigated else 1.0)
|
|
118
|
+
items.append(hit)
|
|
119
|
+
items.sort(key=lambda s: (KIND_PRIORITY.get(s.kind, 9), s.mitigated, s.doc_id, s.start))
|
|
120
|
+
return AuditResult(
|
|
121
|
+
damage_score=round(weight_damage / weight_total, 4) if weight_total else 0.0,
|
|
122
|
+
structures=sum(totals.values()),
|
|
123
|
+
severed=len(items),
|
|
124
|
+
mitigated=sum(1 for s in items if s.mitigated),
|
|
125
|
+
by_kind={k: KindDamage(total=totals[k], severed=severed_counts[k]) for k in sorted(totals)},
|
|
126
|
+
severed_items=items,
|
|
127
|
+
)
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def excerpt(doc: Document, item: SeveredStructure, width: int = 110) -> tuple[str, str]:
|
|
131
|
+
"""Return (text before the cut, text after the cut), clipped to the structure."""
|
|
132
|
+
lo = max(item.start, item.cut_at - width)
|
|
133
|
+
hi = min(item.end, item.cut_at + width)
|
|
134
|
+
before = doc.text[lo:item.cut_at]
|
|
135
|
+
after = doc.text[item.cut_at:hi]
|
|
136
|
+
if lo > item.start:
|
|
137
|
+
before = "..." + before
|
|
138
|
+
if hi < item.end:
|
|
139
|
+
after = after + "..."
|
|
140
|
+
return before, after
|
|
@@ -0,0 +1,335 @@
|
|
|
1
|
+
"""Four chunkers that all emit chunks with exact source offsets.
|
|
2
|
+
|
|
3
|
+
================= ==========================================================
|
|
4
|
+
``fixed`` sliding token windows (``size`` tokens, ``overlap`` shared)
|
|
5
|
+
``recursive`` recursive character splitting on paragraph -> line ->
|
|
6
|
+
sentence -> word separators, merged up to ``size`` tokens
|
|
7
|
+
``markdown`` header-aware: never crosses a section boundary, keeps
|
|
8
|
+
tables / code fences / lists atomic when they fit, splits
|
|
9
|
+
oversized tables by rows *with the header row replicated*,
|
|
10
|
+
and prefixes every chunk with its section breadcrumb
|
|
11
|
+
``semantic`` embedding-based: breaks where adjacent sentences/blocks
|
|
12
|
+
are least similar, capped at ``size`` tokens
|
|
13
|
+
================= ==========================================================
|
|
14
|
+
|
|
15
|
+
Each chunk records ``start``/``end`` into the document text (the span of
|
|
16
|
+
source text it covers), while ``text`` is what gets embedded and indexed
|
|
17
|
+
(it may carry a breadcrumb or replicated table header).
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import re
|
|
23
|
+
from dataclasses import dataclass, field
|
|
24
|
+
from typing import Literal
|
|
25
|
+
|
|
26
|
+
import numpy as np
|
|
27
|
+
from pydantic import BaseModel
|
|
28
|
+
|
|
29
|
+
from ..ingestion.parser import Block, Document
|
|
30
|
+
from ..retrieval.embedders import Embedder, get_embedder
|
|
31
|
+
from ..tokens import TokenIndex, get_tokenizer
|
|
32
|
+
|
|
33
|
+
Strategy = Literal["fixed", "recursive", "markdown", "semantic"]
|
|
34
|
+
STRATEGIES: tuple[str, ...] = ("fixed", "recursive", "markdown", "semantic")
|
|
35
|
+
STRATEGY_ALIASES = {
|
|
36
|
+
"fixed_token": "fixed", "fixed-token": "fixed", "token": "fixed",
|
|
37
|
+
"recursive_character": "recursive", "recursive-character": "recursive",
|
|
38
|
+
"header": "markdown", "header_aware": "markdown", "markdown_header": "markdown",
|
|
39
|
+
"header-aware": "markdown", "md": "markdown",
|
|
40
|
+
"embedding": "semantic",
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
_SEPARATORS = ["\n\n", "\n", ". ", "? ", "! ", "; ", ", ", " "]
|
|
44
|
+
_SENTENCE_END = re.compile(r"(?<=[.!?])\s+(?=[A-Z0-9`\"'(\[])")
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class Chunk(BaseModel):
|
|
48
|
+
chunk_id: str
|
|
49
|
+
doc_id: str
|
|
50
|
+
start: int
|
|
51
|
+
end: int
|
|
52
|
+
tokens: int
|
|
53
|
+
text: str
|
|
54
|
+
section_ids: list[str]
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class ChunkConfig(BaseModel):
|
|
58
|
+
strategy: Strategy
|
|
59
|
+
size: int
|
|
60
|
+
overlap: int
|
|
61
|
+
|
|
62
|
+
@property
|
|
63
|
+
def config_id(self) -> str:
|
|
64
|
+
return f"{self.strategy}-{self.size}-o{self.overlap}"
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def normalize_strategy(name: str) -> str:
|
|
68
|
+
key = name.strip().lower()
|
|
69
|
+
key = STRATEGY_ALIASES.get(key, key)
|
|
70
|
+
if key not in STRATEGIES:
|
|
71
|
+
raise ValueError(f"Unknown strategy '{name}'. Choose from {list(STRATEGIES)}")
|
|
72
|
+
return key
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
@dataclass
|
|
76
|
+
class _Unit:
|
|
77
|
+
start: int
|
|
78
|
+
end: int
|
|
79
|
+
tokens: int
|
|
80
|
+
prefix: str = "" # text prepended when this unit is emitted (e.g. replicated table header)
|
|
81
|
+
solo: bool = False # must be emitted as its own chunk
|
|
82
|
+
breadcrumb: str = "" # section breadcrumb, for header-aware chunks
|
|
83
|
+
section_ids: list[str] = field(default_factory=list)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
# ---------------------------------------------------------------- helpers
|
|
87
|
+
|
|
88
|
+
def _split_on(text: str, start: int, end: int, sep: str) -> list[tuple[int, int]]:
|
|
89
|
+
pieces: list[tuple[int, int]] = []
|
|
90
|
+
pos = start
|
|
91
|
+
while pos < end:
|
|
92
|
+
idx = text.find(sep, pos, end)
|
|
93
|
+
if idx == -1:
|
|
94
|
+
pieces.append((pos, end))
|
|
95
|
+
break
|
|
96
|
+
pieces.append((pos, idx + len(sep)))
|
|
97
|
+
pos = idx + len(sep)
|
|
98
|
+
return [(s, e) for s, e in pieces if text[s:e].strip()]
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _token_windows(ti: TokenIndex, start: int, end: int, size: int, step: int) -> list[tuple[int, int]]:
|
|
102
|
+
spans = [sp for sp in ti.spans if sp[0] >= start and sp[1] <= end]
|
|
103
|
+
out: list[tuple[int, int]] = []
|
|
104
|
+
for i in range(0, len(spans), step):
|
|
105
|
+
window = spans[i:i + size]
|
|
106
|
+
out.append((window[0][0], window[-1][1]))
|
|
107
|
+
if i + size >= len(spans):
|
|
108
|
+
break
|
|
109
|
+
return out or [(start, end)]
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _split_region(text: str, ti: TokenIndex, start: int, end: int, size: int,
|
|
113
|
+
seps: list[str] = _SEPARATORS) -> list[tuple[int, int]]:
|
|
114
|
+
"""Recursively split ``[start, end)`` until every piece is <= ``size`` tokens."""
|
|
115
|
+
if ti.count(start, end) <= size:
|
|
116
|
+
return [(start, end)] if text[start:end].strip() else []
|
|
117
|
+
for k, sep in enumerate(seps):
|
|
118
|
+
if text.find(sep, start, end) != -1:
|
|
119
|
+
out: list[tuple[int, int]] = []
|
|
120
|
+
for s, e in _split_on(text, start, end, sep):
|
|
121
|
+
out.extend(_split_region(text, ti, s, e, size, seps[k + 1:]))
|
|
122
|
+
return out
|
|
123
|
+
return _token_windows(ti, start, end, size, size)
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _trim(text: str, start: int, end: int) -> tuple[int, int]:
|
|
127
|
+
while start < end and text[start].isspace():
|
|
128
|
+
start += 1
|
|
129
|
+
while end > start and text[end - 1].isspace():
|
|
130
|
+
end -= 1
|
|
131
|
+
return start, end
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _units_from_spans(doc: Document, ti: TokenIndex, spans: list[tuple[int, int]]) -> list[_Unit]:
|
|
135
|
+
units = []
|
|
136
|
+
for s, e in spans:
|
|
137
|
+
s, e = _trim(doc.text, s, e)
|
|
138
|
+
if e > s:
|
|
139
|
+
units.append(_Unit(s, e, ti.count(s, e)))
|
|
140
|
+
return units
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _sections_for(doc: Document, start: int, end: int) -> list[str]:
|
|
144
|
+
ids = [s.section_id for s in doc.sections if s.start < end and s.end > start]
|
|
145
|
+
return ids or ([doc.sections[0].section_id] if doc.sections else [])
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _pack(doc: Document, ti: TokenIndex, units: list[_Unit], size: int, overlap: int,
|
|
149
|
+
breaks: set[int] | None = None) -> list[Chunk]:
|
|
150
|
+
"""Greedily merge units into chunks <= size tokens, carrying ``overlap`` tokens of tail units."""
|
|
151
|
+
breaks = breaks or set()
|
|
152
|
+
tok = get_tokenizer()
|
|
153
|
+
crumb_tokens: dict[str, int] = {}
|
|
154
|
+
groups: list[list[_Unit]] = []
|
|
155
|
+
cur: list[_Unit] = []
|
|
156
|
+
|
|
157
|
+
def cur_tokens(us: list[_Unit]) -> int:
|
|
158
|
+
return ti.count(us[0].start, us[-1].end) if us else 0
|
|
159
|
+
|
|
160
|
+
for i, u in enumerate(units):
|
|
161
|
+
hard = i in breaks or u.solo or (cur and cur[-1].solo)
|
|
162
|
+
if cur and (hard or cur_tokens(cur + [u]) > size):
|
|
163
|
+
groups.append(cur)
|
|
164
|
+
carry: list[_Unit] = []
|
|
165
|
+
if overlap > 0 and not hard:
|
|
166
|
+
for prev in reversed(cur):
|
|
167
|
+
if prev.solo or cur_tokens([prev] + carry) > overlap:
|
|
168
|
+
break
|
|
169
|
+
carry.insert(0, prev)
|
|
170
|
+
if carry and cur_tokens(carry + [u]) > size:
|
|
171
|
+
carry = []
|
|
172
|
+
cur = carry
|
|
173
|
+
cur.append(u)
|
|
174
|
+
if cur:
|
|
175
|
+
groups.append(cur)
|
|
176
|
+
|
|
177
|
+
chunks: list[Chunk] = []
|
|
178
|
+
for g in groups:
|
|
179
|
+
start, end = g[0].start, g[-1].end
|
|
180
|
+
body = doc.text[start:end]
|
|
181
|
+
if g[0].solo and g[0].prefix:
|
|
182
|
+
body = g[0].prefix + body
|
|
183
|
+
crumb = g[0].breadcrumb
|
|
184
|
+
text = f"{crumb}\n\n{body}" if crumb else body
|
|
185
|
+
n = ti.count(start, end)
|
|
186
|
+
if crumb:
|
|
187
|
+
n += crumb_tokens.setdefault(crumb, tok.count(crumb))
|
|
188
|
+
if g[0].solo and g[0].prefix:
|
|
189
|
+
n += tok.count(g[0].prefix)
|
|
190
|
+
sections = list(dict.fromkeys(s for u in g for s in u.section_ids)) or _sections_for(doc, start, end)
|
|
191
|
+
chunks.append(Chunk(chunk_id=f"{doc.doc_id}::{len(chunks):04d}", doc_id=doc.doc_id, start=start,
|
|
192
|
+
end=end, tokens=n, text=text, section_ids=sections))
|
|
193
|
+
return chunks
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
# ---------------------------------------------------------------- strategies
|
|
197
|
+
|
|
198
|
+
def chunk_fixed(doc: Document, ti: TokenIndex, size: int, overlap: int) -> list[Chunk]:
|
|
199
|
+
step = max(1, size - overlap)
|
|
200
|
+
units = [_Unit(s, e, ti.count(s, e)) for s, e in _token_windows(ti, 0, len(doc.text), size, step)]
|
|
201
|
+
chunks = []
|
|
202
|
+
for u in units:
|
|
203
|
+
chunks.append(Chunk(chunk_id=f"{doc.doc_id}::{len(chunks):04d}", doc_id=doc.doc_id, start=u.start,
|
|
204
|
+
end=u.end, tokens=u.tokens, text=doc.text[u.start:u.end],
|
|
205
|
+
section_ids=_sections_for(doc, u.start, u.end)))
|
|
206
|
+
return chunks
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def chunk_recursive(doc: Document, ti: TokenIndex, size: int, overlap: int) -> list[Chunk]:
|
|
210
|
+
units = _units_from_spans(doc, ti, _split_region(doc.text, ti, 0, len(doc.text), size))
|
|
211
|
+
return _pack(doc, ti, units, size, overlap)
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def _block_units(doc: Document, ti: TokenIndex, block: Block, size: int, budget: int) -> list[_Unit]:
|
|
215
|
+
"""Units for one block: atomic if it fits, otherwise structure-aware sub-splits."""
|
|
216
|
+
text = doc.text
|
|
217
|
+
n = ti.count(block.start, block.end)
|
|
218
|
+
if n <= budget:
|
|
219
|
+
return [_Unit(block.start, block.end, n)]
|
|
220
|
+
if block.kind == "table":
|
|
221
|
+
lines = text[block.start:block.end].split("\n")
|
|
222
|
+
header = "\n".join(lines[:2]) + "\n"
|
|
223
|
+
header_tokens = get_tokenizer().count(header)
|
|
224
|
+
row_start = block.start + len(header)
|
|
225
|
+
row_budget = max(8, budget - header_tokens)
|
|
226
|
+
units = []
|
|
227
|
+
# first piece keeps the real header in its span; later pieces get it replicated
|
|
228
|
+
rows = _split_on(text, row_start, block.end, "\n")
|
|
229
|
+
group: list[tuple[int, int]] = []
|
|
230
|
+
for r in rows:
|
|
231
|
+
if group and ti.count(group[0][0], r[1]) > row_budget:
|
|
232
|
+
units.append(group)
|
|
233
|
+
group = []
|
|
234
|
+
group.append(r)
|
|
235
|
+
if group:
|
|
236
|
+
units.append(group)
|
|
237
|
+
out: list[_Unit] = []
|
|
238
|
+
for gi, grp in enumerate(units):
|
|
239
|
+
s, e = _trim(text, grp[0][0], grp[-1][1])
|
|
240
|
+
if gi == 0:
|
|
241
|
+
out.append(_Unit(block.start, e, ti.count(block.start, e), solo=True))
|
|
242
|
+
else:
|
|
243
|
+
out.append(_Unit(s, e, ti.count(s, e) + header_tokens, prefix=header, solo=True))
|
|
244
|
+
return out
|
|
245
|
+
if block.kind == "code":
|
|
246
|
+
spans = _split_region(text, ti, block.start, block.end, budget, ["\n\n", "\n", " "])
|
|
247
|
+
return [_Unit(u.start, u.end, u.tokens, solo=True) for u in _units_from_spans(doc, ti, spans)]
|
|
248
|
+
return _units_from_spans(doc, ti, _split_region(text, ti, block.start, block.end, budget))
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def chunk_markdown(doc: Document, ti: TokenIndex, size: int, overlap: int) -> list[Chunk]:
|
|
252
|
+
tok = get_tokenizer()
|
|
253
|
+
units: list[_Unit] = []
|
|
254
|
+
breaks: set[int] = set()
|
|
255
|
+
by_section: dict[str, list[Block]] = {}
|
|
256
|
+
for b in doc.blocks:
|
|
257
|
+
if b.kind != "header":
|
|
258
|
+
by_section.setdefault(b.section_id, []).append(b)
|
|
259
|
+
for section in doc.sections:
|
|
260
|
+
blocks = by_section.get(section.section_id)
|
|
261
|
+
if not blocks:
|
|
262
|
+
continue
|
|
263
|
+
crumb = " > ".join(section.path)
|
|
264
|
+
budget = max(16, size - tok.count(crumb) - 2)
|
|
265
|
+
breaks.add(len(units))
|
|
266
|
+
for b in blocks:
|
|
267
|
+
for u in _block_units(doc, ti, b, size, budget):
|
|
268
|
+
u.breadcrumb = crumb
|
|
269
|
+
u.section_ids = [section.section_id]
|
|
270
|
+
units.append(u)
|
|
271
|
+
return _pack(doc, ti, units, size, overlap, breaks)
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def chunk_semantic(doc: Document, ti: TokenIndex, size: int, overlap: int, embedder: Embedder,
|
|
275
|
+
percentile: float = 75.0) -> list[Chunk]:
|
|
276
|
+
units: list[_Unit] = []
|
|
277
|
+
is_header: list[bool] = []
|
|
278
|
+
for b in doc.blocks:
|
|
279
|
+
if b.kind in ("paragraph", "list") and ti.count(b.start, b.end) > 0:
|
|
280
|
+
spans: list[tuple[int, int]] = []
|
|
281
|
+
for s, e in _split_on(doc.text, b.start, b.end, "\n") if b.kind == "list" else [(b.start, b.end)]:
|
|
282
|
+
pos = s
|
|
283
|
+
for m in _SENTENCE_END.finditer(doc.text, s, e):
|
|
284
|
+
spans.append((pos, m.start()))
|
|
285
|
+
pos = m.end()
|
|
286
|
+
spans.append((pos, e))
|
|
287
|
+
pieces: list[tuple[int, int]] = []
|
|
288
|
+
for s, e in spans:
|
|
289
|
+
pieces.extend(_split_region(doc.text, ti, s, e, size))
|
|
290
|
+
new = _units_from_spans(doc, ti, pieces)
|
|
291
|
+
else:
|
|
292
|
+
new = _units_from_spans(doc, ti, _split_region(doc.text, ti, b.start, b.end, size))
|
|
293
|
+
units.extend(new)
|
|
294
|
+
is_header.extend([b.kind == "header"] * len(new))
|
|
295
|
+
if not units:
|
|
296
|
+
return []
|
|
297
|
+
vecs = embedder.embed_documents([doc.text[u.start:u.end] for u in units])
|
|
298
|
+
sims = np.einsum("ij,ij->i", vecs[:-1], vecs[1:]) if len(units) > 1 else np.array([])
|
|
299
|
+
breaks: set[int] = set()
|
|
300
|
+
if sims.size:
|
|
301
|
+
distances = 1.0 - sims
|
|
302
|
+
threshold = float(np.percentile(distances, percentile))
|
|
303
|
+
for i, d in enumerate(distances):
|
|
304
|
+
if d > threshold and not is_header[i]:
|
|
305
|
+
breaks.add(i + 1)
|
|
306
|
+
for i, h in enumerate(is_header): # a header always opens a new chunk
|
|
307
|
+
if h and i > 0:
|
|
308
|
+
breaks.add(i)
|
|
309
|
+
return _pack(doc, ti, units, size, overlap, breaks)
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
def chunk_document(doc: Document, config: ChunkConfig, embedder: Embedder | None = None,
|
|
313
|
+
ti: TokenIndex | None = None) -> list[Chunk]:
|
|
314
|
+
ti = ti or TokenIndex(doc.text)
|
|
315
|
+
if config.strategy == "fixed":
|
|
316
|
+
return chunk_fixed(doc, ti, config.size, config.overlap)
|
|
317
|
+
if config.strategy == "recursive":
|
|
318
|
+
return chunk_recursive(doc, ti, config.size, config.overlap)
|
|
319
|
+
if config.strategy == "markdown":
|
|
320
|
+
return chunk_markdown(doc, ti, config.size, config.overlap)
|
|
321
|
+
if config.strategy == "semantic":
|
|
322
|
+
return chunk_semantic(doc, ti, config.size, config.overlap, embedder or get_embedder("hash"))
|
|
323
|
+
raise ValueError(config.strategy)
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
def chunk_corpus(docs: list[Document], config: ChunkConfig, embedder: Embedder | None = None,
|
|
327
|
+
token_indexes: dict[str, TokenIndex] | None = None) -> list[Chunk]:
|
|
328
|
+
token_indexes = token_indexes if token_indexes is not None else {}
|
|
329
|
+
out: list[Chunk] = []
|
|
330
|
+
for doc in docs:
|
|
331
|
+
ti = token_indexes.get(doc.doc_id)
|
|
332
|
+
if ti is None:
|
|
333
|
+
ti = token_indexes[doc.doc_id] = TokenIndex(doc.text)
|
|
334
|
+
out.extend(chunk_document(doc, config, embedder, ti))
|
|
335
|
+
return out
|
ragdial_mcp/demo.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
"""``ragdial-demo``: the full before/after loop on the bundled benchmark pack, in seconds.
|
|
2
|
+
|
|
3
|
+
uv run ragdial-demo # offline, deterministic (hash embedder, BM25/RRF)
|
|
4
|
+
uv run --extra ml ragdial-demo --embedder bge-small --reranker bge-reranker-base
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import argparse
|
|
10
|
+
import tempfile
|
|
11
|
+
import time
|
|
12
|
+
|
|
13
|
+
from .lab import Lab
|
|
14
|
+
from .samples import sample_corpus, sample_golden
|
|
15
|
+
|
|
16
|
+
def _table(rows: list[list[str]], header: list[str]) -> str:
|
|
17
|
+
widths = [max(len(str(x)) for x in col) for col in zip(header, *rows)]
|
|
18
|
+
line = lambda r: " ".join(str(x).ljust(w) for x, w in zip(r, widths)) # noqa: E731
|
|
19
|
+
return "\n".join([line(header), line(["-" * w for w in widths]), *(line(r) for r in rows)])
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def main(argv: list[str] | None = None) -> None:
|
|
23
|
+
p = argparse.ArgumentParser(prog="ragdial-demo")
|
|
24
|
+
p.add_argument("--corpus", default=None, help="Corpus folder (default: bundled sample pack)")
|
|
25
|
+
p.add_argument("--dataset", default=None, help="Golden JSONL (default: bundled sample pack)")
|
|
26
|
+
p.add_argument("--embedder", default="hash")
|
|
27
|
+
p.add_argument("--reranker", default="none")
|
|
28
|
+
p.add_argument("--top-k", type=int, default=5)
|
|
29
|
+
p.add_argument("--home", default=None, help="Persist runs here (default: a temp dir)")
|
|
30
|
+
args = p.parse_args(argv)
|
|
31
|
+
args.corpus = args.corpus or str(sample_corpus())
|
|
32
|
+
args.dataset = args.dataset or str(sample_golden())
|
|
33
|
+
|
|
34
|
+
t0 = time.perf_counter()
|
|
35
|
+
lab = Lab(args.home or tempfile.mkdtemp(prefix="ragdial-demo-"))
|
|
36
|
+
ing = lab.ingest_corpus(args.corpus, "demo")
|
|
37
|
+
print(f"[1] ingest: {ing.file_count} files, {ing.total_tokens:,} tokens, {ing.detected}\n")
|
|
38
|
+
|
|
39
|
+
before = lab.run_chunking_ablation("demo", ["fixed"], [256], [0], args.embedder)
|
|
40
|
+
after = lab.run_chunking_ablation("demo", ["markdown"], [256], [0], args.embedder)
|
|
41
|
+
rows = [[c.config_id, c.chunks, c.tokens_p50, c.tokens_p95, c.damage_score, c.severed.get("table", "-")]
|
|
42
|
+
for c in before.configs + after.configs]
|
|
43
|
+
print("[2] chunking ablation")
|
|
44
|
+
print(_table(rows, ["config", "chunks", "p50 tok", "p95 tok", "damage", "tables cut"]), "\n")
|
|
45
|
+
|
|
46
|
+
insp = lab.inspect_boundary_splits(before.run_id, limit=2, kinds=["table"])
|
|
47
|
+
print("[3] boundary splits in", insp.config_id)
|
|
48
|
+
for s in insp.splits:
|
|
49
|
+
print(f" - {s.section_id} ({s.kind}) cut between {s.left_chunk} | {s.right_chunk}")
|
|
50
|
+
print(f" ...{s.before_cut[-70:]!r} <CUT> {s.after_cut[:70]!r}")
|
|
51
|
+
print()
|
|
52
|
+
|
|
53
|
+
kw = dict(retrievers=["bm25", "dense", "hybrid"], reranker=args.reranker, top_k=args.top_k,
|
|
54
|
+
embedder=args.embedder)
|
|
55
|
+
b1 = lab.benchmark_retrieval(before.run_id, args.dataset, **kw)
|
|
56
|
+
b2 = lab.benchmark_retrieval(after.run_id, args.dataset, **kw)
|
|
57
|
+
rows = [[v.variant_id, f"{v.recall_at_k:.3f}", f"{v.mrr:.3f}", f"{v.ndcg_at_k:.3f}", v.p95_ms]
|
|
58
|
+
for v in sorted(b1.results + b2.results, key=lambda v: -v.ndcg_at_k)]
|
|
59
|
+
print(f"[4] retrieval benchmark ({b1.queries} queries, embedder={b1.embedder}, store={b1.vector_store})")
|
|
60
|
+
print(_table(rows, ["variant", f"R@{args.top_k}", "MRR", f"nDCG@{args.top_k}", "p95 ms"]), "\n")
|
|
61
|
+
|
|
62
|
+
d = lab.diff_experiment_runs(b1.run_id, b2.run_id)
|
|
63
|
+
print(f"[5] diff {d.variant_a} -> {d.variant_b}")
|
|
64
|
+
for name, m in d.metrics.items():
|
|
65
|
+
print(f" {name:12s} {m.a:>8} -> {m.b:<8} ({m.delta:+})")
|
|
66
|
+
print(f" fixed: {[f.query_id for f in d.fixed]}")
|
|
67
|
+
print(f" regressed: {[f.query_id for f in d.regressed]}")
|
|
68
|
+
print(f" {d.verdict}")
|
|
69
|
+
print(f"\nDone in {time.perf_counter() - t0:.1f}s. Runs stored in {lab.home}")
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
if __name__ == "__main__":
|
|
73
|
+
main()
|
|
File without changes
|