封装函数后Conversation Buffer Memory无法存储chat_history求助
排查Conversation Buffer Memory封装后为空的问题建议
内存实例不应在函数内部创建
当前每次调用summary_and_memory函数时,都会新建ConversationBufferMemory实例,之前的对话历史自然无法保留。需将memory对象作为函数参数传入,或作为全局/类属性维护,确保每次调用复用同一个内存实例:# 在函数外初始化内存实例 memory = ConversationBufferMemory(memory_key="chat_history") def summary_and_memory(text, memory): template = """ Chat history is: {chat_history} Your task is to write a summary based on the information provided in the data delimited by triple backticks following the steps below- Consider the chat history and try to answer based on that. 1. Analyse the input data. 2. Extract key facts out of the input data. 3. Do not add names and figures that are not present in the data. 4. Do not write numbers in scientific notation or exponents or any other special symbols. 5. Use at most 25 words. Data: ```{text_input}``` """ fact_extraction_prompt = PromptTemplate( input_variables=["text_input", "chat_history"], template=template) fact_extraction_chain = LLMChain(llm=llm, prompt=fact_extraction_prompt, memory=memory, verbose=True) output = fact_extraction_chain.run(text_input=text) return output检查参数映射是否正确
原代码中run方法直接传入text,但prompt模板的输入变量是text_input,参数名不匹配会导致输入数据无法正确绑定,还可能间接影响内存更新。需明确指定参数名:fact_extraction_chain.run(text_input=text)。确认内存更新状态
调用chain后,可通过print(memory.load_memory_variables({}))查看内存内容,验证对话历史是否被正确保存。若仍为空,检查prompt模板是否正确引用了chat_history变量——只有模板中使用该变量,LLMChain才会触发内存的读写逻辑。验证内存作用域
若在类中使用,确保内存实例是类成员变量;若为脚本场景,需保证内存实例在函数调用之间不会被销毁或重新初始化。
内容的提问来源于stack exchange,提问作者Srishino
相关产品推荐
相关产品推荐

