AST感知的代码分块指南 概览 本指南介绍了在LEANN中使用AST感知代码分块的最佳实践。与传统的基于文本的分块方法相比,AST分块能够更好地语义理解代码结构。 快速入门 基本用法 安装 对于普通用户(通过PyPI安装) 使用 or . ,该依赖会自动从PyPI拉取,无需额外步骤。 对于开发者(从源码安装,可编辑模式) 此仓库会提供 as a git submodule at (our fork). maps the package to that path in editable mode. You can edit code under and Python will use your changes immediately (no separate 所需内容。
本指南介绍了在LEANN中使用AST感知代码分块的最佳实践。与传统的基于文本的分块方法相比,AST分块能够更好地语义理解代码结构。
# Enable AST chunking for mixed content (code + docs) python -m apps.document_rag --enable-code-chunking --data-dir ./my_project # Specialized code repository indexing python -m apps.code_rag --repo-dir ./my_codebase # Global CLI with AST support leann build my-code-index --docs ./src --use-ast-chunking
# Install LEANN with AST chunking support uv pip install -e "."
pip install leann or uv pip install leann.astchunk,该依赖会自动从PyPI拉取,无需额外步骤。git clone https://github.com/yichuan-w/LEANN.git leann cd leann git submodule update --init --recursive uv sync
astchunk as a git submodule at packages/astchunk-leann (our fork).[tool.uv.sources] maps the astchunk package to that path in editable mode.packages/astchunk-leann and Python will use your changes immediately (no separate pip install astchunk所需内容。✅ 推荐用于:
❌ 不推荐用于:
# Recommended settings for most codebases python -m apps.code_rag \ --repo-dir ./src \ --ast-chunk-size 768 \ --ast-chunk-overlap 96 \ --exclude-dirs .git __pycache__ node_modules build dist
| 扩展名 | 语言 | 状态 |
|---|---|---|
.py |
Python | ✅ Full support |
.java |
Java | ✅ Full support |
.cs |
C# | ✅ Full support |
.ts, .tsx |
TypeScript | ✅ Full support |
.js, .jsx |
JavaScript | ✅ 通过TypeScript解析器 |
# Enable code chunking in document RAG python -m apps.document_rag \ --enable-code-chunking \ --data-dir ./project \ --query "How does authentication work in the codebase?"
与Claude Code MCP服务器配合使用时,AST分块能提供更好的上下文信息:
回退到传统分块
大文件性能问题
--max-file-size parameter--exclude-dirs to skip unnecessary directoriesQuality Issues
--ast-chunk-size参数值(512、768、1024)export LEANN_LOG_LEVEL=DEBUG python -m apps.code_rag --repo-dir ./my_code
现有工作流无需更改即可继续运行。若要启用AST分块:
# Before python -m apps.document_rag --chunk-size 256 # After (maintains traditional chunking for non-code files) python -m apps.document_rag --enable-code-chunking --chunk-size 256 --ast-chunk-size 768
注:AST分块保持完全向后兼容,同时增强了代码理解能力。
免责声明:
本文档采用基于机器的 AI 翻译服务进行翻译。尽管我们力求准确,但请注意,自动翻译可能存在错误或不准确之处。应以原文语言版本的文档作为权威依据。如需获取关键信息,建议使用专业的人工翻译。对于因使用本翻译而产生的任何误解或误读,我们概不负责。