Back to Practice

Code-aware splitting (CodeSplitter)

Completion

Exercise: 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:

  1. 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.
  2. For code files: build a CodeSplitter with an explicit tree-sitter Parser (obtained from tree_sitter_language_pack.get_language) and chunk settings CODE_CHUNK_LINES=60, CODE_CHUNK_OVERLAP=12. For prose: use a SentenceSplitter with chunk_size=512, chunk_overlap=64.
  3. Wrap the text in a Document with metadata {"file": file_path.name} and split it. If tree-sitter parsing fails, fall back to prose splitting.
  4. 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