Skip to main content
Open In ColabOpen on GitHub

SQLite

SQLite is a database engine written in the C programming language. It is not a standalone app; rather, it is a library that software developers embed in their apps. As such, it belongs to the family of embedded databases. It is the most widely deployed database engine, as it is used by several of the top web browsers, operating systems, mobile phones, and other embedded systems.

在这个教程中,我们将创建一个简单的对话链,它使用由 SqliteEntityStore 支持的 ConversationEntityMemory

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

使用

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

  1. 会话 ID - 会话的唯一标识符,例如用户名、电子邮件、聊天 ID 等。
  2. 连接字符串 - 一个指定数据库连接的字符串。对于 SQLite,该字符串是 slqlite:/// 后跟数据库文件的名称。如果该文件不存在,它将被创建。
from langchain_community.chat_message_histories import SQLChatMessageHistory

chat_message_history = SQLChatMessageHistory(
session_id="test_session_id", connection_string="sqlite:///sqlite.db"
)

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 密钥。

pip install -U langchain-openai

export OPENAI_API_KEY='sk-xxxxxxx'
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_core.runnables.history import RunnableWithMessageHistory
from langchain_openai import ChatOpenAI
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: SQLChatMessageHistory(
session_id=session_id, connection_string="sqlite:///sqlite.db"
),
input_messages_key="question",
history_messages_key="history",
)
# This is where we configure the session id
config = {"configurable": {"session_id": "<SQL_SESSION_ID>"}}
chain_with_history.invoke({"question": "Hi! I'm bob"}, config=config)
AIMessage(content='Hello 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 specific you would like assistance with, Bob?')