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

如何将MongoDB中按会话ID存储的聊天历史导入ConversationBufferMemory?

从MongoDB聊天历史构建ConversationBufferMemory并接入ConversationRetrievalChain

核心思路

先从MongoDB中读取指定会话ID的聊天记录,将其转换为ConversationBufferMemory兼容的格式,再初始化Memory并传入ConversationRetrievalChain。


步骤1:读取MongoDB中的会话历史

假设你的MongoDB集合中,每个文档结构如下(按会话ID存储聊天消息):

{
  "session_id": "xxx-xxx-xxx",
  "messages": [
    {"role": "user", "content": "你好,请问如何使用LangChain?"},
    {"role": "assistant", "content": "LangChain是一个用于构建LLM应用的框架,主要分为链、记忆、检索等模块..."},
    // 更多交替的用户/助手消息
  ]
}

使用pymongo连接并读取目标会话的历史:

from pymongo import MongoClient

# 连接MongoDB实例
client = MongoClient("mongodb://localhost:27017/")
db = client["chat_database"]
collection = db["conversation_records"]

# 指定要加载的会话ID
target_session_id = "your-target-session-id"

# 查询会话历史
conversation_doc = collection.find_one({"session_id": target_session_id})
messages = conversation_doc["messages"] if conversation_doc else []

步骤2:转换为ConversationBufferMemory兼容格式

ConversationBufferMemory支持两种主流格式,根据需求选择:

格式1:LangChain消息对象列表(推荐,类型明确)

将MongoDB中的消息转换为HumanMessage和AIMessage实例:

from langchain.schema import HumanMessage, AIMessage

chat_history = []
for msg in messages:
    if msg["role"] == "user":
        chat_history.append(HumanMessage(content=msg["content"]))
    elif msg["role"] == "assistant":
        chat_history.append(AIMessage(content=msg["content"]))

格式2:(用户输入, 助手回复)元组列表

适用于消息严格按用户-助手交替排列的场景:

chat_history = []
# 按顺序遍历每一对用户-助手消息
for i in range(0, len(messages), 2):
    if i + 1 < len(messages):
        user_content = messages[i]["content"]
        assistant_content = messages[i+1]["content"]
        chat_history.append((user_content, assistant_content))

步骤3:初始化ConversationBufferMemory

根据选择的格式,传入对应参数初始化Memory:

from langchain.memory import ConversationBufferMemory

# 对应格式1的初始化(需设置return_messages=True)
memory = ConversationBufferMemory(
    memory_key="chat_history",
    return_messages=True,
    chat_history=chat_history
)

# 对应格式2的初始化(无需return_messages)
# memory = ConversationBufferMemory(
#     memory_key="chat_history",
#     chat_history=chat_history
# )

步骤4:接入ConversationRetrievalChain

将初始化好的Memory传入链中即可:

from langchain.chains import ConversationRetrievalChain
from langchain.llms import OpenAI
from langchain.vectorstores import Chroma

# 假设已初始化向量存储和LLM
vectorstore = Chroma(persist_directory="./your-vector-store-path")
llm = OpenAI(temperature=0)

# 构建会话检索链
conversation_chain = ConversationRetrievalChain.from_llm(
    llm=llm,
    retriever=vectorstore.as_retriever(),
    memory=memory,
    verbose=True
)

注意事项

  • 确保MongoDB中的消息角色仅包含user和assistant,避免转换时遗漏消息
  • 如果会话历史为空,直接传入空列表即可,Memory会自动处理后续新增的聊天内容
  • 使用消息对象列表时,必须设置return_messages=True,否则链无法正确读取历史

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 20:42:20