You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

LangChain Document与Pydantic 2.x兼容报错求助:参数数量不符

解决LangChain Document与Pydantic 2的兼容问题

这个错误源于LangChain的Document类内部沿用了Pydantic 1.x的validate方法签名,而Pydantic 2.x对该方法的参数要求已改变,即使开启arbitrary_types_allowed也无法解决签名冲突问题。以下是几种可行的解决办法:

方案1:使用LangChain适配的BaseModel

LangChain提供了兼容不同Pydantic版本的BaseModel类,直接继承它即可规避兼容问题:

from typing import List

from langchain_core.documents.base import Document
from langchain_core.base_model import BaseModel


class ResponseBody(BaseModel):
    message: List[Document]

docs = [Document(page_content="This is a document")]
res = ResponseBody(message=docs)

方案2:为Document添加自定义序列化器

若坚持使用原生Pydantic 2.x的BaseModel,可通过Annotated结合序列化器处理Document类型:

from typing import List, Annotated
from pydantic import BaseModel, PlainSerializer, WithJsonSchema
from langchain_core.documents.base import Document


def serialize_document(doc: Document) -> dict:
    return {"page_content": doc.page_content, "metadata": doc.metadata}

class ResponseBody(BaseModel):
    message: List[Annotated[
        Document,
        PlainSerializer(serialize_document),
        WithJsonSchema({"type": "object", "properties": {"page_content": {"type": "string"}, "metadata": {"type": "object"}}})
    ]]

docs = [Document(page_content="This is a document")]
res = ResponseBody(message=docs)

方案3:开启LangChain的Pydantic 2兼容模式

通过代码配置让LangChain启用Pydantic 2兼容模式,之后即可正常使用原生BaseModel并开启arbitrary_types_allowed:

import os
os.environ["LANGCHAIN_USE_PYDANTIC_V2"] = "true"

然后使用原代码即可:

from typing import List

from langchain_core.documents.base import Document
from pydantic import BaseModel, ConfigDict


class ResponseBody(BaseModel):
    message: List[Document]
    model_config = ConfigDict(arbitrary_types_allowed=True)

docs = [Document(page_content="This is a document")]
res = ResponseBody(message=docs)

内容的提问来源于stack exchange,提问作者fabiankuenzer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 08:11:14