Skip to main content
Open In ColabOpen on GitHub

MongoDB

MongoDB is a source-available cross-platform document-oriented database program. Classified as a NoSQL database program, MongoDB uses JSON-like documents with optional schemas.

MongoDB is developed by MongoDB Inc. and licensed under the Server Side Public License (SSPL). - Wikipedia

本笔记本介绍了如何使用 MongoDBChatMessageHistory 类将聊天消息历史存储到 MongoDB 数据库中。

设置

集成位于 langchain-mongodb 包中,因此我们需要安装它。

pip install -U --quiet langchain-mongodb

设置LangSmith 以获得一流的可观测性也很有帮助(但不是必需的)。

# os.environ["LANGSMITH_TRACING"] = "true"
# os.environ["LANGSMITH_API_KEY"] = getpass.getpass()

使用

要使用存储,您只需要提供两样东西:

  1. 会话 ID - 会话的唯一标识符,例如用户名、电子邮件、聊天 ID 等。
  2. 连接字符串 - 一个指定数据库连接的字符串。它将传递给 MongoDB 的 create_engine 函数。

如果你想自定义聊天记录的存储位置,还可以传入:

  1. database_name - 数据库的名称
  2. collection_name - 数据库中使用的集合
from langchain_mongodb.chat_message_histories import MongoDBChatMessageHistory

chat_message_history = MongoDBChatMessageHistory(
session_id="test_session",
connection_string="mongodb://mongo_user:password123@mongo:27017",
database_name="my_db",
collection_name="chat_histories",
)

chat_message_history.add_user_message("Hello")
chat_message_history.add_ai_message("Hi")
chat_message_history.messages
[HumanMessage(content='Hello'), AIMessage(content='Hi')]

链式调用

我们可以轻松地将此消息历史类与LCEL Runnables结合

要做到这一点,我们需要使用 OpenAI,因此需要安装它。你还需要将 OPENAI_API_KEY 环境变量设置为你的 OpenAI 密钥。

from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_core.runnables.history import RunnableWithMessageHistory
from langchain_openai import ChatOpenAI
import os

assert os.environ[
"OPENAI_API_KEY"
], "Set the OPENAI_API_KEY environment variable with your OpenAI API key."
prompt = ChatPromptTemplate.from_messages(
[
("system", "You are a helpful assistant."),
MessagesPlaceholder(variable_name="history"),
("human", "{question}"),
]
)

chain = prompt | ChatOpenAI()
chain_with_history = RunnableWithMessageHistory(
chain,
lambda session_id: MongoDBChatMessageHistory(
session_id=session_id,
connection_string="mongodb://mongo_user:password123@mongo:27017",
database_name="my_db",
collection_name="chat_histories",
),
input_messages_key="question",
history_messages_key="history",
)
# This is where we configure the session id
config = {"configurable": {"session_id": "<SESSION_ID>"}}
chain_with_history.invoke({"question": "Hi! I'm bob"}, config=config)
AIMessage(content='Hi Bob! How can I assist you today?')
chain_with_history.invoke({"question": "Whats my name"}, config=config)
AIMessage(content='Your name is Bob. Is there anything else I can help you with, Bob?')