跳到主要內容
Open In ColabOpen on GitHub

SQL (SQLAlchemy)

結構化查詢語言 (SQL) 是一種用於程式設計的領域特定語言,旨在管理關聯式資料庫管理系統 (RDBMS) 中保存的資料,或用於關聯式資料流管理系統 (RDSMS) 中的流處理。它在處理結構化資料時特別有用,即包含實體和變數之間關係的資料。

SQLAlchemy 是一個開源 SQL 工具組和物件關聯對應器 (ORM),適用於 MIT 許可證下發布的 Python 程式設計語言。

此筆記本介紹了 SQLChatMessageHistory 類別,該類別允許將聊天歷史記錄儲存在 SQLAlchemy 支援的任何資料庫中。

請注意,若要將其與 SQLite 以外的資料庫一起使用,您需要安裝相應的資料庫驅動程式。

設定

整合存在於 langchain-community 套件中,因此我們需要安裝它。我們還需要安裝 SQLAlchemy 套件。

pip install -U langchain-community SQLAlchemy langchain-openai

設定 LangSmith 以獲得同類最佳的可觀察性也很有幫助(但不是必需的)

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

用法

若要使用儲存,您只需要提供 2 件事

  1. 工作階段 ID - 工作階段的唯一識別符,例如使用者名稱、電子郵件、聊天 ID 等。
  2. 連線字串 - 指定資料庫連線的字串。它將傳遞給 SQLAlchemy create_engine 函數。
from langchain_community.chat_message_histories import SQLChatMessageHistory

chat_message_history = SQLChatMessageHistory(
session_id="test_session", 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,因此我們需要安裝它

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": "<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?')

此頁面是否對您有幫助?