Repository navigation
feat(pipelines): implement contextual chunk retrieval with document and section breadcrumbs #296
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
3cd0666
038a0af
16200cd
fb71f1d
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -22,6 +22,9 @@ | |
| DEFAULT_TARGET_TOKENS = 350 | ||
| DEFAULT_OVERLAP_TOKENS = 50 | ||
| MAX_CONTENT_TEXT_CHARS = 2000 | ||
| CONTEXT_DELIMITER = "\n<!--kubeflow:context:end-->\n" | ||
| MAX_BREADCRUMB_HEADER_CHARS = 300 | ||
| MAX_CHUNK_BODY_CHARS = MAX_CONTENT_TEXT_CHARS - MAX_BREADCRUMB_HEADER_CHARS # 1700 | ||
| CHARS_PER_TOKEN = 4 | ||
|
|
||
| HEADING_RE = re.compile(r"^(#{1,6})\s+(.+?)\s*$") | ||
|
|
@@ -487,31 +490,28 @@ def _chunk_block( | |
| *, | ||
| target_tokens: int, | ||
| overlap_tokens: int, | ||
| max_body_chars: int = MAX_CHUNK_BODY_CHARS, | ||
| ) -> list[tuple[str, str, list[LinkRef]]]: | ||
| """Return (chunk_type, content_text, links) tuples for one canonical block.""" | ||
| heading_prefix = "" | ||
| if section.heading: | ||
| heading_prefix = f"{section.section_path}\n\n" | ||
|
|
||
| if block.block_type == "code_fence": | ||
| content = block.content.strip() | ||
| if len(content) > MAX_CONTENT_TEXT_CHARS: | ||
| content = content[:MAX_CONTENT_TEXT_CHARS] | ||
| if len(content) > max_body_chars: | ||
| content = content[:max_body_chars] | ||
| return [("code", content, block.links)] | ||
|
|
||
| if block.block_type == "table": | ||
| pieces = _split_table_by_tokens(block.content, target_tokens) | ||
| if len(pieces) == 1 and estimate_tokens(pieces[0]) <= target_tokens: | ||
| content = pieces[0] | ||
| if len(content) > MAX_CONTENT_TEXT_CHARS: | ||
| content = content[: MAX_CONTENT_TEXT_CHARS] | ||
| if len(content) > max_body_chars: | ||
| content = content[:max_body_chars] | ||
| return [("table", content, block.links)] | ||
|
|
||
| rows: list[tuple[str, str, list[LinkRef]]] = [] | ||
| for piece in pieces: | ||
| content = piece | ||
| if len(content) > MAX_CONTENT_TEXT_CHARS: | ||
| content = content[: MAX_CONTENT_TEXT_CHARS] | ||
| if len(content) > max_body_chars: | ||
| content = content[:max_body_chars] | ||
| rows.append(("table_row", content, block.links)) | ||
| return rows | ||
|
|
||
|
|
@@ -523,16 +523,16 @@ def _chunk_block( | |
| ) | ||
| output: list[tuple[str, str, list[LinkRef]]] = [] | ||
| for piece in prose_chunks: | ||
| content = heading_prefix + piece if heading_prefix else piece | ||
| if len(content) > MAX_CONTENT_TEXT_CHARS: | ||
| content = content[: MAX_CONTENT_TEXT_CHARS] | ||
| content = piece | ||
| if len(content) > max_body_chars: | ||
| content = content[:max_body_chars] | ||
| chunk_type = "admonition" if content.lstrip().startswith(("NOTE:", "WARNING:")) else "text" | ||
| output.append((chunk_type, content, block.links)) | ||
| return output | ||
|
|
||
| content = block.content.strip() | ||
| if len(content) > MAX_CONTENT_TEXT_CHARS: | ||
| content = content[: MAX_CONTENT_TEXT_CHARS] | ||
| if len(content) > max_body_chars: | ||
| content = content[:max_body_chars] | ||
| chunk_type = "admonition" if block.block_type == "admonition" else "text" | ||
| return [(chunk_type, content, block.links)] | ||
|
|
||
|
|
@@ -590,6 +590,104 @@ def chunk_canonical_document( | |
| return chunks | ||
|
|
||
|
|
||
| def build_document_breadcrumb(file_path: str, title: str = "") -> str: | ||
| """Build a human-readable document breadcrumb path from repository path and title. | ||
|
|
||
| Examples: | ||
| content/en/docs/components/katib/early-stopping.md -> | ||
| 'Kubeflow Documentation > Components > Katib > Early Stopping' | ||
| """ | ||
| parts = ["Kubeflow Documentation"] | ||
| normalized = file_path.replace("\\", "/") | ||
| if "content/en/docs" in normalized: | ||
| rel = normalized.split("content/en/docs", 1)[1].lstrip("/") | ||
| rel = re.sub(r"(/_index)?\.(md|html)$", "", rel) | ||
| segments = [s.strip() for s in rel.split("/") if s.strip()] | ||
| if segments: | ||
| nice_segments = [ | ||
| re.sub(r"[-_]+", " ", s).strip().title() | ||
| for s in segments | ||
| ] | ||
| if title and title.strip(): | ||
| nice_segments[-1] = title.strip() | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Preserve the directory name for index pages. For For index pages, retain the directory segments and append the title when needed. Keep filename replacement for ordinary pages.
|
||
| parts.extend(nice_segments) | ||
| elif title and title.strip(): | ||
| parts.append(title.strip()) | ||
| elif title and title.strip(): | ||
| parts.append(title.strip()) | ||
| elif file_path: | ||
| base = os.path.basename(normalized) | ||
| clean_base = re.sub(r"\.(md|html)$", "", base) | ||
| parts.append(re.sub(r"[-_]+", " ", clean_base).strip().title()) | ||
|
|
||
| return SECTION_PATH_SEP.join(parts) | ||
|
|
||
|
|
||
| def _build_contextual_header(document_breadcrumb: str, section_heading: str) -> str: | ||
| """Build a Document/Section header bounded by MAX_BREADCRUMB_HEADER_CHARS.""" | ||
| doc_crumb = (document_breadcrumb or "").strip() | ||
| heading = (section_heading or "").strip() | ||
| if heading == doc_crumb: | ||
| heading = "" | ||
|
|
||
| doc_line = f"Document: {doc_crumb}" if doc_crumb else "" | ||
| sec_line = f"Section: {heading}" if heading else "" | ||
| if not doc_line and not sec_line: | ||
| return "" | ||
|
|
||
| metadata_budget = MAX_BREADCRUMB_HEADER_CHARS - len(CONTEXT_DELIMITER) | ||
| if doc_line and sec_line: | ||
| if len(doc_line) + 1 + len(sec_line) > metadata_budget: | ||
| avail = metadata_budget - 1 | ||
| sec_budget = min(len(sec_line), max(90, avail - len(doc_line))) | ||
| sec_line = sec_line[:sec_budget].rstrip() | ||
| doc_budget = avail - len(sec_line) | ||
| doc_line = doc_line[:doc_budget].rstrip() | ||
| elif doc_line: | ||
| doc_line = doc_line[:metadata_budget].rstrip() | ||
| else: | ||
| sec_line = sec_line[:metadata_budget].rstrip() | ||
|
|
||
| lines = [line for line in (doc_line, sec_line) if line] | ||
| return "\n".join(lines) + CONTEXT_DELIMITER | ||
|
|
||
|
|
||
| def format_contextual_text( | ||
| content: str, | ||
| *, | ||
| document_breadcrumb: str, | ||
| section_heading: str = "", | ||
| ) -> str: | ||
| """Prepend document breadcrumb and section heading to chunk content. | ||
|
|
||
| Creates structured context: | ||
| Document: Kubeflow Documentation > Katib > Early Stopping | ||
| Section: Configuring the Median Stopping Rule | ||
| <!--kubeflow:context:end--> | ||
| [clean chunk content] | ||
| """ | ||
| clean_content = content.strip() | ||
| if not clean_content: | ||
| return "" | ||
|
|
||
| header = _build_contextual_header(document_breadcrumb, section_heading) | ||
|
|
||
| if len(header) + len(clean_content) <= MAX_CONTENT_TEXT_CHARS: | ||
| return f"{header}{clean_content}" | ||
|
|
||
| budget = max(50, MAX_CONTENT_TEXT_CHARS - len(header)) | ||
| return f"{header}{clean_content[:budget]}" | ||
|
|
||
|
|
||
| def strip_context_delimiter(text: str) -> str: | ||
| """Remove the context delimiter sentinel before dense embedding.""" | ||
| if CONTEXT_DELIMITER in text: | ||
| return text.replace(CONTEXT_DELIMITER, "\n", 1) | ||
| if "<!--kubeflow:context:end-->" in text: | ||
| return text.replace("<!--kubeflow:context:end-->", "", 1).strip() | ||
| return text | ||
|
|
||
|
|
||
| def build_citation_url(file_path: str, base_url: str) -> str: | ||
| """Build a Kubeflow docs citation URL from a repository path.""" | ||
| path_parts = file_path.split("/") | ||
|
|
@@ -762,7 +860,23 @@ def build_milvus_records( | |
| doc_status = infer_doc_status(file_path) | ||
| records: list[dict[str, Any]] = [] | ||
|
|
||
| doc_breadcrumb = build_document_breadcrumb(file_path, parsed.title) | ||
|
|
||
| for chunk_idx, chunk in enumerate(chunks): | ||
| clean_text = chunk["content_text"].strip() | ||
| raw_section = (chunk.get("section_path") or chunk.get("heading") or "").strip() | ||
| prefix = f"{title}{SECTION_PATH_SEP}" | ||
| if raw_section.startswith(prefix): | ||
| section_heading = raw_section[len(prefix) :].strip() | ||
| else: | ||
| section_heading = raw_section | ||
|
|
||
| contextual_text = format_contextual_text( | ||
| clean_text, | ||
| document_breadcrumb=doc_breadcrumb, | ||
| section_heading=section_heading, | ||
| ) | ||
|
|
||
| records.append( | ||
| { | ||
| "file_unique_id": file_unique_id, | ||
|
|
@@ -771,7 +885,7 @@ def build_milvus_records( | |
| "file_name": file_name, | ||
| "citation_url": citation_url, | ||
| "chunk_index": chunk_idx, | ||
| "content_text": chunk["content_text"][:MAX_CONTENT_TEXT_CHARS], | ||
| "content_text": contextual_text[:MAX_CONTENT_TEXT_CHARS], | ||
| "title": title[:256], | ||
| "weight": parsed.weight, | ||
| "doc_type": doc_type[:32], | ||
|
|
@@ -830,13 +944,16 @@ def dumps_jsonl(records: Iterable[dict[str, Any]]) -> str: | |
| "CanonicalDocument", | ||
| "CanonicalSection", | ||
| "build_citation_url", | ||
| "build_document_breadcrumb", | ||
| "build_milvus_records", | ||
| "is_badge_only_chunk", | ||
| "chunk_canonical_document", | ||
| "extract_release_date", | ||
| "dumps_jsonl", | ||
| "estimate_tokens", | ||
| "format_contextual_text", | ||
| "parse_and_chunk_file", | ||
| "parse_canonical_document", | ||
| "split_prose_by_tokens", | ||
| "strip_context_delimiter", | ||
| ] | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Split oversized bodies instead of discarding their tails.
If a fenced block has 1,800 characters, this change retains only the first 1,700 characters. Before this change, the complete block fit the 2,000-character limit. No subsequent chunk contains the discarded configuration or closing fence.
Split oversized bodies within the reserved budget. Apply the same correction to the table, prose and fallback branches. Update the long-code test to check content preservation instead of requiring one truncated chunk.