如何使用Poetry管理LangChain项目依赖并进行本地开发
引言
在构建依赖管理和虚拟环境时,选择合适的工具可以为开发流程大大简化。本文将详细教你如何使用Poetry安装和管理LangChain项目的依赖,并在本地进行开发。我们将介绍Poetry的安装、依赖管理、单元测试、格式化和拼写检查等实用操作。
主要内容
1. 安装Poetry
首先,确保Poetry已经安装。可以参考Poetry安装文档进行安装。请注意,如果你使用Conda或Pyenv作为环境/包管理器,安装完Poetry后,需配置Poetry使用虚拟环境中的Python:
poetry config virtualenvs.prefer-active-python true
2. 创建和激活Conda环境
在安装Poetry前,若使用Conda进行环境管理,请先创建并激活新的Conda环境:
conda create -n langchain python=3.9
conda activate langchain
3. 项目结构
LangChain项目分为多个包:
- langchain-core:基础接口和组合逻辑。
- langchain-community:第三方集成组件。
- langchain:认知架构应用的核心逻辑。
- langchain-experimental:实验性组件和链。
我们将以langchain-community为例进行演示:
cd libs/community
4. 安装依赖
在langchain-community目录下,安装开发所需的依赖:
poetry install --with lint,typing,test,test_integration
5. 验证依赖安装
通过以下命令验证依赖是否安装成功:
make test
6. 处理Poetry的潜在问题
如果在安装过程中收到WheelFileValidationError错误,可能是Poetry版本过旧,需升级到1.6.1+以上版本。如果问题仍然存在,可以尝试禁用“现代安装”方式:
poetry config installer.modern-installation false
7. 运行单元测试
在本地运行单元测试以确保新逻辑正确:
make test
或者在Docker中运行单元测试:
make docker_tests
8. 代码格式化
在提交PR之前,确保代码格式化一致。项目使用ruff进行代码格式化:
make format
你可以在库目录内运行同样的命令,例如:
cd libs/{LIBRARY}
make format
9. 代码Linting
项目使用ruff和mypy进行代码Linting:
make lint
同样可以在库目录内运行:
cd libs/{LIBRARY}
make lint
10. 拼写检查
使用codespell进行拼写检查:
make spell_check
make spell_fix
如果codespell错误地标记了单词,可以将该单词添加到pyproject.toml配置文件中以忽略:
[tool.codespell]
ignore-words-list = 'your_word'
11. 添加新的依赖
LangChain某些子库使用可选依赖,来保持包的轻量化。添加新的依赖时,请将依赖添加到extended_testing_deps.txt中,并在单元测试中使用@pytest.mark.requires('package_name')标记受依赖的新单元测试。
12. 添加Jupyter Notebook示例
如需添加Jupyter Notebook示例,需安装开发依赖:
poetry install --with dev
启动Notebook:
poetry run jupyter notebook
代码示例
以下是一个完整的代码示例,展示如何安装依赖和运行单元测试:
# 激活Conda环境
conda create -n langchain python=3.9
conda activate langchain
# 安装Poetry
curl -sSL https://install.python-poetry.org | python3 -
# 配置Poetry使用虚拟环境中的Python
poetry config virtualenvs.prefer-active-python true
# 切换到langchain-community目录
cd libs/community
# 安装依赖
poetry install --with lint,typing,test,test_integration
# 运行单元测试
make test
常见问题和解决方案
-
WheelFileValidationError
确保Poetry版本为1.6.1+,或尝试禁用“现代安装”:
poetry config installer.modern-installation false -
依赖冲突
确保在不同项目之间隔离开发环境,使用Poetry的虚拟环境管理功能。
总结和进一步学习资源
通过本文的介绍,你已经了解了如何使用Poetry进行LangChain项目的依赖管理和本地开发。使用这种方法,你可以轻松管理项目的依赖,并确保代码的一致性和高质量。
进一步学习资源:
参考资料
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---