Google SQL for MySQL
Cloud Cloud SQL 是一项完全托管的关系数据库服务,提供高性能、无缝集成和卓越的可扩展性。它提供了
MySQL、PostgreSQL和SQL Server数据库引擎。通过利用 Cloud SQL 的 Langchain 集成,扩展您的数据库应用程序以构建由 AI 驱动的体验。
本 Notebook 将介绍如何使用 Google Cloud SQL for MySQL 通过 MySQLChatMessageHistory 类来存储聊天消息历史记录。
在 GitHub 上了解有关该软件包的更多信息 。
开始之前
要运行此笔记本,您需要执行以下操作:
- 创建 Google Cloud 项目
- 启用 Cloud SQL Admin API
- 创建 Cloud SQL for MySQL 实例
- 创建 Cloud SQL 数据库
- 向数据库添加 IAM 数据库用户 (可选)
🦜🔗 库安装
该集成位于其自己的 langchain-google-cloud-sql-mysql 包中,因此我们需要安装它。
%pip install --upgrade --quiet langchain-google-cloud-sql-mysql langchain-google-vertexai
仅限 Colab: 取消注释以下单元格以重启内核或使用按钮重启内核。对于 Vertex AI Workbench,您可以使用顶部的按钮重启终端。
# # Automatically restart kernel after installs so that your environment can access the new packages
# import IPython
# app = IPython.Application.instance()
# app.kernel.do_shutdown(True)
🔐 身份验证
使用此 notebook 中登录的 IAM 用户向 Google Cloud 进行身份验证,以便访问您的 Google Cloud 项目。
- 如果您正在使用 Colab 运行此 notebook,请使用下方的单元格并继续。
- 如果您正在使用 Vertex AI Workbench,请查看设置说明 在此处。
from google.colab import auth
auth.authenticate_user()
### ☁ 设置你的 Google Cloud 项目 设置你的 Google Cloud 项目,以便在这个 Notebook 中使用 Google Cloud 资源。
如果你不知道你的项目 ID,可以尝试以下方法:
- 运行
gcloud config list。 - 运行
gcloud projects list。 - 查看支持页面:查找项目 ID。
# @markdown Please fill in the value below with your Google Cloud project ID and then run the cell.
PROJECT_ID = "my-project-id" # @param {type:"string"}
# Set the project id
!gcloud config set project {PROJECT_ID}
💡 API 启用
langchain-google-cloud-sql-mysql 包要求您在 Google Cloud 项目中启用 Cloud SQL Admin API。
# enable Cloud SQL Admin API
!gcloud services enable sqladmin.googleapis.com
基本用法
设置 Cloud SQL 数据库值
在Cloud SQL 实例页面查找您的数据库值。
# @title Set Your Values Here { display-mode: "form" }
REGION = "us-central1" # @param {type: "string"}
INSTANCE = "my-mysql-instance" # @param {type: "string"}
DATABASE = "my-database" # @param {type: "string"}
TABLE_NAME = "message_store" # @param {type: "string"}
MySQLEngine 连接池
将 Cloud SQL 设置为 ChatMessageHistory 内存存储的要求之一是需要一个 MySQLEngine 对象。MySQLEngine 可为您的 Cloud SQL 数据库配置连接池,从而实现您的应用程序成功连接并遵循行业最佳实践。
要使用 MySQLEngine.from_instance() 创建 MySQLEngine,您只需要提供 4 项内容:
project_id: Cloud SQL 实例所在 Google Cloud 项目的项目 ID。region: Cloud SQL 实例所在的区域。instance: Cloud SQL 实例的名称。database: 要连接到 Cloud SQL 实例上的数据库的名称。
默认情况下,将使用 IAM 数据库身份验证 作为数据库身份验证方法。此库使用来自环境的 应用程序默认凭据 (ADC) 所属的 IAM principal。
有关 IAM 数据库身份验证的更多信息,请参阅:
也可以选择使用 内置数据库身份验证,即使用用户名和密码来访问 Cloud SQL 数据库。只需向 MySQLEngine.from_instance() 提供可选的 user 和 password 参数即可:
user: 用于内置数据库身份验证和登录的数据库用户。password: 用于内置数据库身份验证和登录的数据库密码。
from langchain_google_cloud_sql_mysql import MySQLEngine
engine = MySQLEngine.from_instance(
project_id=PROJECT_ID, region=REGION, instance=INSTANCE, database=DATABASE
)
初始化表
MySQLChatMessageHistory 类需要一个具有特 定架构的数据库表来存储聊天消息历史记录。
MySQLEngine 引擎有一个名为 init_chat_history_table() 的辅助方法,可以使用它为你创建具有正确架构的表。
engine.init_chat_history_table(table_name=TABLE_NAME)
MySQLChatMessageHistory
初始化 MySQLChatMessageHistory 类只需要提供 3 个参数:
engine-MySQLEngine引擎的实例。session_id- 一个唯一的标识符字符串,用于指定会话的 ID。table_name: 用于在 Cloud SQL 数据库中存储聊天消息历史的表名。
from langchain_google_cloud_sql_mysql import MySQLChatMessageHistory
history = MySQLChatMessageHistory(
engine, session_id="test_session", table_name=TABLE_NAME
)
history.add_user_message("hi!")
history.add_ai_message("whats up?")
history.messages
[HumanMessage(content='hi!'), AIMessage(content='whats up?')]
清理
当特定会话的历史记录已过时且可以删 除时,可以按以下方式进行。
注意: 删除后,数据将不再存储在 Cloud SQL 中,并且将永远消失。
history.clear()
🔗 链式调用
我们可以轻松地将此消息历史类与 LCEL Runnables 结合使用。
为此,我们将使用 Google 的 Vertex AI 聊天模型之一,这要求您在 Google Cloud 项目中 启用 Vertex AI API。
# enable Vertex AI API
!gcloud services enable aiplatform.googleapis.com
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_core.runnables.history import RunnableWithMessageHistory
from langchain_google_vertexai import ChatVertexAI
prompt = ChatPromptTemplate.from_messages(
[
("system", "You are a helpful assistant."),
MessagesPlaceholder(variable_name="history"),
("human", "{question}"),
]
)
chain = prompt | ChatVertexAI(project=PROJECT_ID)
chain_with_history = RunnableWithMessageHistory(
chain,
lambda session_id: MySQLChatMessageHistory(
engine,
session_id=session_id,
table_name=TABLE_NAME,
),
input_messages_key="question",
history_messages_key="history",
)
# This is where we configure the session id
config = {"configurable": {"session_id": "test_session"}}
chain_with_history.invoke({"question": "Hi! I'm bob"}, config=config)
AIMessage(content=' Hello Bob, how can I help you today?')
chain_with_history.invoke({"question": "Whats my name"}, config=config)
AIMessage(content=' Your name is Bob.')