LangChain带记忆多输入报错:期望单输入键却获['text_one','text_two']
解决LangChain多输入LLMChain结合记忆的ValueError问题
运行带记忆功能的多输入LLMChain时,触发错误:ValueError: One input key expected got ['text_one', 'text_two'],尝试多种调用方式(predict、直接传参等)均无法解决。
核心原因
默认的ConversationBufferMemory仅支持单一输入键(默认是input),当LLMChain存在多个输入键时,它无法识别需要将哪些输入内容存入聊天历史,从而引发错误。
解决方法
方法一:自定义Memory的上下文保存逻辑
通过重写ConversationBufferMemory的save_context方法,将多个输入内容合并后存入聊天历史,修改后的完整代码如下:
from langchain.llms import OpenAI from langchain.chains import LLMChain from langchain.prompts import PromptTemplate from langchain.memory import ConversationBufferMemory llm = OpenAI( model="text-davinci-003", openai_api_key=environment_values["OPEN_AI_KEY"], # 使用dotenv存储API密钥 temperature=0.9, client="", ) memory = ConversationBufferMemory(memory_key="chat_history") # 重写save_context方法,合并text_one和text_two为用户消息 def custom_save_context(self, inputs, outputs): user_message = f"Text one: {inputs['text_one']}\nText two: {inputs['text_two']}" ai_message = outputs[self.output_key] self.chat_memory.add_user_message(user_message) self.chat_memory.add_ai_message(ai_message) # 将自定义方法绑定到memory实例 memory.save_context = custom_save_context.__get__(memory, ConversationBufferMemory) prompt = PromptTemplate( input_variables=[ "text_one", "text_two", "chat_history" ], template=( """You are an AI talking to a human. Here is the chat history so far: {chat_history} Here is some more text: {text_one} and here is even more text: {text_two} """ ) ) chain = LLMChain( llm=llm, prompt=prompt, memory=memory, verbose=False )
调用代码保持不变即可正常运行:
output = chain.predict( text_one="Hello", text_two="World" )
方法二:合并多输入为单一变量
如果希望保留默认Memory逻辑,可将多个输入合并为单一输入变量,调整如下:
- 修改Prompt模板,只保留一个用户输入变量:
prompt = PromptTemplate( input_variables=["user_input", "chat_history"], template=( """You are an AI talking to a human. Here is the chat history so far: {chat_history} {user_input} """ ) )
- 创建Memory时指定输入键:
memory = ConversationBufferMemory(memory_key="chat_history", input_key="user_input")
- 调用时合并输入内容:
output = chain.predict( user_input="Text one: Hello\nText two: World" )
内容的提问来源于stack exchange,提问作者pvasudev16
相关产品推荐
相关产品推荐

