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

使用LangChain ChatPromptTemplate.from_messages出现验证错误的求助

LangChain ChatPromptTemplate 验证错误解决

你遇到的ValidationError是因为当前使用的LangChain版本中,ChatPromptTemplate.from_messages()不再支持直接传入(角色, 模板字符串)的元组格式,需要使用字典结构或对应的消息模板类。

解决方法一:使用字典格式替换元组

from langchain.prompts.chat import ChatPromptTemplate
template = "You are a helpful assistant that translates {input_language} to {output_language}."
human_template = "{text}"

chat_prompt = ChatPromptTemplate.from_messages([
    {"role": "system", "content": template},
    {"role": "human", "content": human_template},
])

chat_prompt.format_messages(input_language="English", output_language="French", text="I love programming.")

解决方法二:使用消息模板类(规范写法)

from langchain.prompts.chat import ChatPromptTemplate, SystemMessagePromptTemplate, HumanMessagePromptTemplate
template = "You are a helpful assistant that translates {input_language} to {output_language}."
human_template = "{text}"

# 分别创建系统消息和人类消息的模板实例
system_message_prompt = SystemMessagePromptTemplate.from_template(template)
human_message_prompt = HumanMessagePromptTemplate.from_template(human_template)

# 组合成ChatPromptTemplate
chat_prompt = ChatPromptTemplate.from_messages([system_message_prompt, human_message_prompt])

chat_prompt.format_messages(input_language="English", output_language="French", text="I love programming.")

以上两种写法均适配LangChain v0.1及以上版本,能有效解决参数格式不匹配导致的验证错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 11:22:37