07 - 构建与分发:Hatchling + uv + 300+ 包管理
07 - 构建与分发:Hatchling + uv + 300+ 包管理
学习目标
本章将带你分析 LlamaIndex 的构建与分发系统。你将学到:
- Hatchling 构建系统的配置
- uv monorepo 依赖锁定
- 内置 nltk/tiktoken 缓存的 attestation 验证
- pre-commit 多工具流水线
- 300+ 包的版本管理与发布策略
项目实践
Hatchling 构建配置
LlamaIndex 使用 Hatchling 作为构建系统(遵循 PEP 621 标准):
[build-system]build-backend = "hatchling.build"requires = ["hatchling"]核心包的构建配置(llama-index-core/pyproject.toml):
[tool.hatch.build.targets.wheel]include = [ "llama_index", "llama_index/core/_static/nltk_cache/corpora/stopwords/**", "llama_index/core/_static/nltk_cache/tokenizers/punkt_tab/**", "llama_index/core/_static/tiktoken_cache/**",]exclude = ["**/BUILD"]关键设计:将 nltk 和 tiktoken 的缓存文件打包到 wheel 中,确保用户在受限环境中(如无网络访问或严格磁盘权限)也能正常运行。
内置缓存的 Attestation 验证
打包的 _static 目录包含预下载的 nltk 和 tiktoken 缓存。为防止这些文件被篡改,LlamaIndex 使用 GitHub 的 attest-build-provenance action 验证构建资产:
#!/bin/bashSTATIC_DIR="venv/lib/python3.13/site-packages/llama_index/core/_static"REPO="run-llama/llama_index"
find "$STATIC_DIR" -type f | while read -r file; do echo "Verifying: $file" gh attestation verify "$file" -R "$REPO" || echo "Failed to verify: $file"done验证流程:
设计原因:预下载的缓存文件减少了用户首次使用时的网络请求。但也引入了供应链风险——如果缓存文件被恶意替换,所有用户都会受到影响。Attestation 验证确保文件的来源和完整性。
uv Monorepo 依赖锁定
LlamaIndex 使用 uv 管理整个 monorepo 的依赖:
[tool.uv.sources]llama-index-llms-openai = {path = "../llama-index-integrations/llms/llama-index-llms-openai"}关键设计:通过 [tool.uv.sources] 指定集成包的本地路径,确保开发和测试时使用本地版本而非 PyPI 版本。uv.lock 文件锁定整个 monorepo 的依赖图。
Pre-commit 多工具流水线
.pre-commit-config.yaml 配置了多工具流水线:
| 工具 | 作用 | 阶段 |
|---|---|---|
black | 代码格式化 | commit |
ruff | lint 检查 | commit |
mypy | 类型检查 | CI |
codespell | 拼写检查 | commit |
prettier | 文档格式化 | commit |
设计优势:在 commit 前自动捕获格式和 lint 问题,减少 CI 失败率和代码审查迭代。
300+ 包的版本管理
每个集成包有独立的版本号:
llama-index-core: v0.14.22llama-index-llms-openai: v0.3.15llama-index-vector-stores-chroma: v0.1.10版本约束:每个集成包的 pyproject.toml 声明对 core 的依赖版本范围:
dependencies = [ "llama-index-core>=0.14.0,<0.15.0",]发布流程:
问题与规避
| 陷阱 | 对策 |
|---|---|
_static attestation 验证失败 | 不要手动修改 _static 目录文件;使用 uv sync 重新安装 |
| uv.lock 与其他包管理工具冲突 | 统一团队使用 uv;删除 requirements.txt 和 Pipfile.lock |
| 集成包与 core 版本不兼容 | 检查集成包的 llama-index-core 依赖版本范围 |
| pre-commit hook 慢(mypy 全量检查) | 使用 mypy 仅在 CI 运行;commit hook 只运行 black + ruff |
设计取舍
Hatchling vs Setuptools
| 维度 | Hatchling (PEP 621) | Setuptools |
|---|---|---|
| 配置标准 | 现代 (pyproject.toml) | 传统 (setup.py / setup.cfg) |
| 依赖声明 | 标准 PEP 621 dependencies | 非标准 install_requires |
| 构建速度 | 快 | 慢 |
| 生态兼容 | 中(较新,部分工具不支持) | 高(行业标准) |
选择 Hatchling 的原因:遵循 PEP 621 标准,配置更简洁,构建速度更快。代价是部分旧版工具可能需要适配。
参考来源
- Hatchling 文档:https://hatch.pypa.io/
- GitHub Attestation:https://docs.github.com/en/actions/security-for-github-actions/using-artifact-attestations
- uv 文档:https://docs.astral.sh/uv/