如何在LangChain与Ollama中保存对话历史并从断点重启对话
问题分析
错误核心是自定义Prompt仅声明history为输入变量,但ConversationChain结合ConversationBufferMemory使用时,默认会传入input(当前用户提问)和history(对话历史)两个变量,导致变量不匹配;同时未将存储的历史数据加载到memory中。
解决步骤
1. 修正Prompt模板
确保Prompt包含history和input两个变量,匹配ConversationChain的默认输入要求:
PROMPT_TEMPLATE = """ {history} Human: {input} AI: """ custom_prompt = PromptTemplate( input_variables=["history", "input"], template=PROMPT_TEMPLATE )
2. 加载存储的对话历史到Memory
将数据库中存储的历史数据整理后,传入ConversationBufferMemory初始化:
# 从数据库取出的历史数据 history_data = {'input': 'What is life?', 'history': 'Human: What is life?\nAI: {}', 'response': '{ "Life" : {\n "Definition" : "A complex and multifaceted phenomenon characterized by the presence of organization, metabolism, homeostasis, and reproduction.",\n "Context" : ["Biology", "Philosophy", "Psychology"],\n "Subtopics" : [\n {"Self-awareness": "The capacity to have subjective experiences, such as sensations, emotions, and thoughts."},\n {"Evolutionary perspective": "A process driven by natural selection, genetic drift, and other mechanisms that shape the diversity of life on Earth."},\n {"Quantum perspective": "A realm where quantum mechanics and general relativity intersect, potentially influencing the emergence of consciousness."}\n ]\n} }'} # 初始化Memory并加载历史 memory = ConversationBufferMemory(initial_history=[ {"input": history_data['input'], "output": history_data['response']} ]) # 也可通过手动添加方式加载: # memory.chat_memory.add_user_message(history_data['input']) # memory.chat_memory.add_ai_message(history_data['response'])
3. 重新初始化对话链并调用
chain = ConversationChain( prompt=custom_prompt, llm=llm, memory=memory ) prompt = "How to live it properly?" answer = chain.invoke(input=prompt) print(answer)
关键说明
ConversationBufferMemory支持通过initial_history传入对话历史列表(每个元素含input和output字段),或通过chat_memory的方法手动添加单条对话。- 自定义Prompt必须包含
history和input两个变量,否则会与ConversationChain默认输入逻辑冲突,触发ValidationError。
内容的提问来源于stack exchange,提问作者jolly
相关产品推荐
相关产品推荐

