使用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
相关产品推荐
相关产品推荐

