Code-aware splitting (CodeSplitter)
CompletionExercise: Code-Aware Splitting for Grounded Retrieval
In the LlamaIndex + Qdrant retrieval pipeline you've been studying, source files are split into nodes for indexing. The repository uses two different splitters depending on whether the file is code (.py, .ts) or prose (everything else).
Your task is to implement the function split_source_file(file_path: Path, text: str) -> list[BaseNode] that mimics the logic in _load_nodes and _code_splitter from the real source above. Specifically:
- Determine the programming language using the mapping from file suffix (
.py→"python",.ts/.tsx→"typescript"). If the suffix does not match, treat the file as prose. - For code files: build a
CodeSplitterwith an explicit tree-sitterParser(obtained fromtree_sitter_language_pack.get_language) and chunk settingsCODE_CHUNK_LINES=60,CODE_CHUNK_OVERLAP=12. For prose: use aSentenceSplitterwithchunk_size=512,chunk_overlap=64. - Wrap the text in a
Documentwith metadata{"file": file_path.name}and split it. If tree-sitter parsing fails, fall back to prose splitting. - Return the list of nodes.
The scaffold below already imports all required libraries and partially fills in the logic. Replace the # TODO: placeholders with the correct code.
Hint: Look at _lang_for, _code_splitter, and the try/except fallback in _load_nodes from the repository source.
Your code
Sources
- roadmap-kg/kg/rerank.py:151-186
- roadmap-kg/kg/glossary_llamaindex.py:215-223
- roadmap-kg/kg/ground_content.py:218-261