Langchain中ConversationChain的PromptTemplate验证报错解决咨询
解决Langchain ConversationChain的ValidationError问题
问题根源
你的Prompt模板定义了三个输入变量:history、input、daily_context,但默认的ConversationBufferMemory只负责提供history变量,input会在调用predict()时自动传入,daily_context没有被注入到变量池中,因此触发ValidationError。
可行解决方案
方案1:调用时显式传入daily_context
在调用对话链的predict()方法时,直接传入daily_context参数,确保Prompt能获取到所有需要的变量:
daily_context = "It is a Saturday, the office is open." # 原代码中初始化对话链的部分保持不变 response = conversation.predict(input="Can I leave early today?", daily_context=daily_context)
方案2:通过内存注入固定的daily_context
如果daily_context是固定值,可通过ConversationBufferMemory的extra_context参数将其注入,无需每次调用都传参:
daily_context = "It is a Saturday, the office is open." memory = ConversationBufferMemory(extra_context={"daily_context": daily_context}) conversation = ConversationChain( prompt=PROMPT, llm=llm, verbose=True, memory=memory, ) # 调用时只需传入input response = conversation.predict(input="Can I leave early today?")
方案3:将daily_context设为模板固定内容
若daily_context不需要动态修改,可直接将其写入Prompt模板,不再作为变量,减少输入变量的依赖:
template = """You are Jane's Boss. Here is some context about today: It is a Saturday, the office is open. Current conversation: {history} Jane: {input} AI:""" PROMPT = PromptTemplate(input_variables=["history", "input"], template=template) # 后续初始化对话链的代码保持不变
注意事项
自定义Prompt时,必须保证所有input_variables都有对应的数据源:
history:由对话内存提供input:调用predict()时传入的用户输入- 额外变量:需通过显式传参、内存注入或固定模板的方式提供
内容的提问来源于stack exchange,提问作者jKraut
相关产品推荐
相关产品推荐

