在Google Colab运行Llama Index代码遇PydanticUserError求解决
解决Llama Index与Pydantic V2兼容性错误
用户在Google Colab中执行以下代码时出现错误:
from llama_index.prompts.prompts import SimpleInputPrompt # Create a system prompt system_prompt = """[INST] <> more string here.<> """ query_wrapper_prompt = SimpleInputPrompt("{query_str} [/INST]")
错误信息如下:
/usr/local/lib/python3.10/dist-packages/pydantic/_internal/_config.py:269: UserWarning: Valid config keys have changed in V2: * 'allow_population_by_field_name' has been renamed to 'populate_by_name' warnings.warn(message, UserWarning) --------------------------------------------------------------------------- PydanticUserError Traceback (most recent call last) <ipython-input-36-c45796b371fe> in <cell line: 3>() 1 # Import the prompt wrapper... 2 # but for llama index ----> 3 from llama_index.prompts.prompts import SimpleInputPrompt 4 # Create a system prompt 5 system_prompt = """[INST] <> 6 frames /usr/local/lib/python3.10/dist-packages/pydantic/deprecated/class_validators.py in root_validator(pre, skip_on_failure, allow_reuse, *__args) 226 mode: Literal['before', 'after'] = 'before' if pre is True else 'after' 227 if pre is False and skip_on_failure is not True: --> 228 raise PydanticUserError( 229 'If you use `@root_validator` with pre=False (the default) you MUST specify `skip_on_failure=True`.' 230 ' Note that `@root_validator` is deprecated and should be replaced with `@model_validator`.', PydanticUserError: If you use `@root_validator` with pre=False (the default) you MUST specify `skip_on_failure=True`. Note that `@root_validator` is deprecated and should be replaced with `@model_validator`. For further information visit https://errors.pydantic.dev/2.1.1/u/root-validator-pre-skip
解决方案
这个错误是旧版Llama Index与Pydantic V2不兼容导致的——Pydantic V2废弃了@root_validator的旧用法(默认pre=False时必须指定skip_on_failure=True),而旧版Llama Index仍在使用不符合V2规范的代码。
有两种解决方式:
方式一:降级Pydantic到V1版本
在Colab的代码单元格中执行以下命令,然后重启运行时:
!pip install pydantic==1.10.13
重启后重新导入模块并执行原有代码即可。
方式二:升级Llama Index到兼容Pydantic V2的版本
执行命令升级Llama Index:
!pip install --upgrade llama-index
升级后,SimpleInputPrompt的导入路径需要调整为:
from llama_index.core.prompts import SimpleInputPrompt
之后再运行你的代码就不会报错了。
内容的提问来源于stack exchange,提问作者Christian01
相关产品推荐
相关产品推荐

