Skip to main content

Google SQL for SQL Server

Google Cloud SQL 是一个完全托管的关系数据库服务,提供高性能、无缝集成和令人印象深刻的可扩展性。它提供 MySQLPostgreSQLSQL Server 数据库引擎。扩展您的数据库应用程序,构建利用 Cloud SQL 的 Langchain 集成的 AI 驱动体验。

本笔记本介绍了如何使用 Google Cloud SQL for SQL Server 通过 MSSQLChatMessageHistory 类存储聊天消息历史记录。

GitHub 上了解更多关于该包的信息。

Open In Colab

开始之前

要运行此笔记本,您需要执行以下操作:

🦜🔗 库安装

集成存在于其自己的 langchain-google-cloud-sql-mssql 包中,因此我们需要安装它。

%pip install --upgrade --quiet langchain-google-cloud-sql-mssql 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)

🔐 身份验证

作为登录此笔记本的 IAM 用户对 Google Cloud 进行身份验证,以便访问您的 Google Cloud 项目。

  • 如果您使用 Colab 运行此笔记本,请使用下面的单元格并继续。
  • 如果您使用 Vertex AI Workbench,请查看 这里 的设置说明。
from google.colab import auth

auth.authenticate_user()

☁ 设置您的 Google Cloud 项目

设置您的 Google Cloud 项目,以便您可以在此笔记本中利用 Google Cloud 资源。

如果您不知道您的项目 ID,请尝试以下方法:

  • 运行 gcloud config list
  • 运行 gcloud projects list
  • 请参阅支持页面:查找项目 ID
# @markdown 请在下面填写您的 Google Cloud 项目 ID,然后运行该单元格。

PROJECT_ID = "my-project-id" # @param {type:"string"}

# 设置项目 ID
!gcloud config set project {PROJECT_ID}

💡 API 启用

langchain-google-cloud-sql-mssql 包要求您在 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-mssql-instance" # @param {type: "string"}
DATABASE = "my-database" # @param {type: "string"}
DB_USER = "my-username" # @param {type: "string"}
DB_PASS = "my-password" # @param {type: "string"}
TABLE_NAME = "message_store" # @param {type: "string"}

MSSQLEngine 连接池

将 Cloud SQL 作为 ChatMessageHistory 存储的一个要求和参数是 MSSQLEngine 对象。MSSQLEngine 配置了一个连接池到您的 Cloud SQL 数据库,使您的应用程序能够成功连接并遵循行业最佳实践。

要使用 MSSQLEngine.from_instance() 创建 MSSQLEngine,您只需提供 6 个信息:

  1. project_id : Cloud SQL 实例所在的 Google Cloud 项目的项目 ID。
  2. region : Cloud SQL 实例所在的区域。
  3. instance : Cloud SQL 实例的名称。
  4. database : 要连接的 Cloud SQL 实例上的数据库名称。
  5. user : 用于内置数据库身份验证和登录的数据库用户。
  6. password : 用于内置数据库身份验证和登录的数据库密码。

默认情况下,使用用户名和密码访问 Cloud SQL 数据库的 内置数据库身份验证 用于数据库身份验证。

from langchain_google_cloud_sql_mssql import MSSQLEngine

engine = MSSQLEngine.from_instance(
project_id=PROJECT_ID,
region=REGION,
instance=INSTANCE,
database=DATABASE,
user=DB_USER,
password=DB_PASS,
)

初始化表

MSSQLChatMessageHistory 类需要一个具有特定模式的数据库表,以存储聊天消息历史记录。

MSSQLEngine 引擎有一个辅助方法 init_chat_history_table(),可以用来为您创建一个具有正确模式的表。

engine.init_chat_history_table(table_name=TABLE_NAME)

MSSQLChatMessageHistory

要初始化 MSSQLChatMessageHistory 类,您只需要提供以下三项内容:

  1. engine - 一个 MSSQLEngine 引擎的实例。
  2. session_id - 一个唯一标识符字符串,用于指定会话的 ID。
  3. table_name : 存储聊天消息历史的 Cloud SQL 数据库中的表名。
from langchain_google_cloud_sql_mssql import MSSQLChatMessageHistory

history = MSSQLChatMessageHistory(
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: MSSQLChatMessageHistory(
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.')

此页面是否有帮助?


您还可以留下详细的反馈 在 GitHub 上