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

如何解决LangChain中Pydantic的`dict`方法弃用警告?

问题

运行基于OpenAI的LangChain RAG链代码时,出现如下警告:

PydanticDeprecatedSince20: The dict method is deprecated; use model_dump instead. Deprecated in Pydantic V2.0 to be removed in V3.0. See Pydantic V2 Migration Guide at https://errors.pydantic.dev/2.5/migration/
warnings.warn('The dict method is deprecated; use model_dump instead.', DeprecationWarning)

代码中并未显式使用dict方法,相关代码如下:

from client_setup import get_client
#from langchain_community.vectorstores import Weaviate
#from langchain_openai.OpenAI import OpenAI
from langchain_openai import OpenAI
from langchain_community.vectorstores import Weaviate
from langchain.retrievers.weaviate_hybrid_search import WeaviateHybridSearchRetriever
from langchain.prompts import ChatPromptTemplate
from langchain.schema.runnable import RunnablePassthrough
from langchain.schema.output_parser import StrOutputParser


client = get_client()

retriever = WeaviateHybridSearchRetriever(
        client=client, 
        index_name="Material",
        text_key="su",
        attributes=["material", "heat_treatment", "su", "sy"],
        create_schema_if_missing=True,
        )

llm = OpenAI(api_key="", model_name="gpt-3.5-turbo-instruct")


template = """You are an assistant for question-answering tasks. 
Use the following pieces of retrieved context to answer the question. 
If you don't know the answer, just say that you don't know. 
Use three sentences maximum and keep the answer concise.
Question: {question} 
Context: {context} 
Answer:
"""
prompt = ChatPromptTemplate.from_template(template)

#print(prompt)
query = "What heat treatment is used for Steel SAE 1040?"

rag_chain = (
        {"context": retriever,
         "question": RunnablePassthrough()}
        | prompt
        | llm
        | StrOutputParser()
        )


result = rag_chain.invoke(query)
print(result)

解决方案

这个警告是LangChain内部依赖的Pydantic库版本兼容问题导致的——LangChain部分旧版本代码仍在使用Pydantic V1的dict()方法,但你环境中安装的是Pydantic V2,因此触发了弃用警告。解决方法如下:

  • 升级LangChain到最新稳定版:LangChain后续版本已适配Pydantic V2,替换了内部的dict()调用为model_dump()。执行命令:

    pip install --upgrade langchain langchain-openai langchain-community
    
  • 临时抑制警告(不推荐长期使用):如果暂时无法升级依赖,可在代码开头添加以下代码屏蔽该类警告:

    import warnings
    warnings.filterwarnings("ignore", category=DeprecationWarning, message="The `dict` method is deprecated; use `model_dump` instead.")
    
  • 锁定Pydantic V1版本(应急方案):如果升级LangChain后出现其他兼容性问题,可临时降级Pydantic到V1.x版本:

    pip install "pydantic<2.0"
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 08:50:29