You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

LangChain中MessagesPlaceholder无法加载对话历史问题求助

问题排查与修复方案

核心问题分析

  1. 重复创建对话链导致内存丢失
    在__main__代码块中,第一次创建对话链并完成交互后,你再次调用bedrock_chain()生成了全新的对话链实例。新实例会初始化新的ConversationBufferMemory,之前的对话历史自然无法被携带。

  2. Memory参数未显式对齐(可选但建议)
    虽然ConversationBufferMemory默认的memory_key是"history",与MessagesPlaceholder的variable_name匹配,但显式指定该参数能避免LangChain版本迭代带来的默认值变更风险,让代码逻辑更清晰。

修正后的代码

调整__main__代码块

不再重复创建对话链,复用同一个实例进行多轮交互:

if __name__ == "__main__":
    formatted_text = re.sub(r"[^a-zA-Z0-9 \n\.]", "", convert_pdf_to_txt("test.pdf"))
    removed_excessive_newlines = re.sub(r"\n\s*\n", "\n\n", formatted_text)

    # 只创建一次对话链
    chain = bedrock_chain(removed_excessive_newlines)
    resp = chain.predict(input="Hello there!")
    print(resp)
    # 复用同一个chain实例,内存会保留之前的对话
    resp = chain.predict(input="Does Tim know anything about New Relic?")
    print(resp)

显式配置Memory的memory_key(可选优化)

修改bedrock_chain函数中的Memory初始化代码:

memory = ConversationBufferMemory(
    human_prefix="Human", 
    ai_prefix="AI", 
    return_messages=True,
    memory_key="history"  # 显式指定与MessagesPlaceholder匹配的key
)

额外说明

  • 若需要重置对话历史,调用clear_memory(chain)即可,无需重新创建对话链。
  • 系统消息模板的format调用无需修改,当前写法能正确注入PDF上下文。

内容的提问来源于stack exchange,提问作者Tim Schill

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 23:35:34