chunking.code_ast

chunktuner.chunking.code_ast

AST-aware chunks for Python (tree-sitter optional extra).

CodeASTStrategy

CodeASTStrategy(encoding_name='cl100k_base')

Python tree-sitter top-level definitions, with token-capped fallback splits.

Source code in src/chunktuner/chunking/code_ast.py
def __init__(self, encoding_name: str = "cl100k_base"):
    self._encoding_name = encoding_name
    self._enc = tiktoken.get_encoding(encoding_name)
    self._parser = None
    try:
        import tree_sitter_python as tsp
        from tree_sitter import Language, Parser

        self._parser = Parser(Language(tsp.language()))
    except ImportError:
        pass

chunk

chunk(doc, config)

Emit function/class chunks for Python AST; non-Python falls back to line windows.

With merge_small=True the whole file is covered: top-level definitions and the runs of other top-level code between them (imports, constants, statements) are greedily merged while the merged span stays within max_tokens.

Source code in src/chunktuner/chunking/code_ast.py
def chunk(self, doc: Document, config: ChunkConfig) -> list[Chunk]:
    """Emit function/class chunks for Python AST; non-Python falls back to line windows.

    With ``merge_small=True`` the whole file is covered: top-level definitions and the runs
    of other top-level code between them (imports, constants, statements) are greedily
    merged while the merged span stays within ``max_tokens``.
    """
    validate_content_type(self.name, self.supported_content_types, doc.content_type)
    max_tokens = int(config.params.get("max_tokens", 512))
    merge_small = bool(config.params.get("merge_small", False))
    lang = (doc.language or "").lower()
    use_ast = self._parser is not None and lang in ("", "python", "py")
    if not use_ast:
        out = self._fallback().chunk(doc, config)
        validate_chunk_offsets(doc, out)
        return out
    b = doc.content.encode("utf8")
    tree = self._parser.parse(b)
    root = tree.root_node

    def to_char(byte_off: int) -> int:
        return len(b[:byte_off].decode("utf8"))

    if merge_small:
        chunks = self._merged_chunks(doc, root, to_char, max_tokens)
    else:
        chunks = self._definition_chunks(doc, root, to_char, max_tokens)
    if not chunks:
        out = self._fallback().chunk(doc, config)
        validate_chunk_offsets(doc, out)
        return out
    validate_chunk_offsets(doc, chunks)
    return chunks