向Poetry项目添加langchain-google-genai时遭遇版本依赖冲突
解决Poetry项目中langchain-google-genai与FastAPI的Pydantic版本冲突问题
问题描述
尝试为Poetry项目添加langchain-google-genai库时,出现Pydantic版本冲突:langchain-google-genai要求Pydantic >=2.7.4,而当前使用的FastAPI 0.96.x要求Pydantic <2.0。曾尝试升级FastAPI适配高版本Pydantic,但导致现有代码崩溃。
错误日志
poetry add langchain_google_genai Using version ^1.0.7 for langchain-google-genai Updating dependencies Resolving dependencies... (30.6s) Because no versions of langchain-core match >0.2.9,<0.2.10 || >0.2.10,<0.3 and langchain-core (0.2.9) depends on pydantic (>=2.7.4,<3.0.0), langchain-core (>=0.2.9,<0.2.10 || >0.2.10,<0.3) requires pydantic (>=2.7.4,<3.0.0). And because langchain-core (0.2.10) depends on pydantic (>=2.7.4,<3.0.0), langchain-core (>=0.2.9,<0.3) requires pydantic (>=2.7.4,<3.0.0). Because no versions of langchain-google-genai match >1.0.7,<2.0.0 and langchain-google-genai (1.0.7) depends on langchain-core (>=0.2.9,<0.3), langchain-google-genai (>=1.0.7,<2.0.0) requires langchain-core (>=0.2.9,<0.3). (1) Thus, langchain-google-genai (>=1.0.7,<2.0.0) requires pydantic (>=2.7.4,<3.0.0). Because no versions of fastapi match >0.96.0,<0.96.1 || >0.96.1,<0.97.0 and fastapi (0.96.0) depends on pydantic (>=1.6.2,<1.7 || >1.7,<1.7.1 || >1.7.1,<1.7.2 || >1.7.2,<1.7.3 || >1.7.3,<1.8 || >1.8,<1.8.1 || >1.8.1,<2.0.0), fastapi (>=0.96.0,<0.96.1 || >0.96.1,<0.97.0) requires pydantic (>=1.6.2,<1.7 || >1.7,<1.7.1 || >1.7.1,<1.7.2 || >1.7.2,<1.7.3 || >1.7.3,<1.8 || >1.8,<1.8.1 || >1.8.1,<2.0.0). And because fastapi (0.96.1) depends on pydantic (>=1.7.4,<1.8 || >1.8,<1.8.1 || >1.8.1,<2.0.0), fastapi (>=0.96.0,<0.97.0) requires pydantic (>=1.6.2,<1.7 || >1.7,<1.7.1 || >1.7.1,<1.7.2 || >1.7.2,<1.7.3 || >1.7.3,<1.8 || >1.8,<1.8.1 || >1.8.1,<2.0.0). And because langchain-google-genai (>=1.0.7,<2.0.0) requires pydantic (>=2.7.4,<3.0.0) (1), langchain-google-genai (>=1.0.7,<2.0.0) is incompatible with fastapi (>=0.96.0,<0.97.0) So, because persualia-langserve depends on both fastapi (^0.96.0) and langchain-google-genai (^1.0.7), version solving failed.
解决方案
1. 降级langchain-google-genai到兼容Pydantic 1.x的版本
查找依赖langchain-core <0.2.9的langchain-google-genai版本,这类版本支持Pydantic <2.0。例如安装0.1.0版本:
poetry add langchain-google-genai==0.1.0
安装后验证依赖解析是否成功,同时测试langchain-google-genai的功能是否满足需求。
2. 使用Poetry的依赖覆盖功能(风险较高)
在pyproject.toml中强制指定兼容的Pydantic版本,并覆盖langchain-core的版本要求:
[tool.poetry.dependencies] # 保留原有其他依赖 pydantic = "^1.10.12" # 选择同时满足FastAPI 0.96.x和langchain-core <0.2.9的版本 [tool.poetry.overrides] langchain-core = "<0.2.9"
执行poetry update后,必须全面测试项目,确保FastAPI和langchain-google-genai都能正常运行,避免运行时错误。
3. 逐步迁移FastAPI代码到兼容Pydantic 2.x的版本
若无法降级langchain-google-genai,可分步骤升级FastAPI并适配代码:
- 先升级FastAPI到支持Pydantic 2.x的最低版本(如0.100.0+)
- 安装
pydantic.v1兼容模块,修改原有Pydantic 1.x代码:# 兼容写法示例 from pydantic.v1 import BaseModel, Field, validator - 分模块测试功能,避免一次性全量更新导致的崩溃,逐步完成代码迁移。
4. 用虚拟环境隔离依赖
为langchain-google-genai单独创建虚拟环境,将其部署为独立服务,主项目通过HTTP接口调用该服务,彻底避免依赖冲突。
内容的提问来源于stack exchange,提问作者Carles Roch Arnau
相关产品推荐
相关产品推荐

