pythonpydanticlangchainpydantic-v2

Pydantic is not compatible with LangChain Documents


I am using LangChain 0.2.34 together with Python 3.12.5 to build a RAG architecture and Pydantic 2.8.2 for validation. It appears that some LangChain classes are not compatible with Pydantic although I explicitly allow arbitrary types. Or am I missing something?

Here is a code sample and the respective error.

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)

Error:

TypeError: BaseModel.validate() takes 2 positional arguments but 3 were given

Solution

  • Langchain is using the functionality in pydantic v1. Define your model with v1 syntax:

    from pydantic.v1 import BaseModel, ConfigDict
    
    ...
    

    You can read about their migration plan + pydantic compatibility here: How to use LangChain with different Pydantic versions