在Google Cloud SQL上构建强大的SQL Server应用:深入集成与扩展

72 阅读2分钟

引言

在当今的技术环境中,云服务提供了一个强大的平台来提升应用程序的性能和可扩展性。Google Cloud SQL以其全面的托管服务与卓越性能成为开发者的热门选择之一。本文将深入了解如何利用Google Cloud SQL的SQL Server引擎,通过langchain-google-cloud-sql-mssql包存储聊天消息历史记录,并探讨如何集成AI以增强应用程序的功能。

主要内容

1. 设置Google Cloud环境

首先,您需要一个Google Cloud项目并启用Cloud SQL Admin API:

  1. 创建一个Google Cloud项目。
  2. 启用Cloud SQL Admin API:!gcloud services enable sqladmin.googleapis.com
  3. 创建一个Cloud SQL for SQL Server实例,并在其中创建数据库和用户。

2. 安装和认证

确保安装必要的软件包,并对Google Cloud进行认证:

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

通过以下代码对Google Cloud进行认证:

from google.colab import auth
auth.authenticate_user()

3. 配置数据库连接

设置Cloud SQL数据库的连接值,并创建MSSQLEngine连接池:

from langchain_google_cloud_sql_mssql import MSSQLEngine

PROJECT_ID = "my-project-id"
REGION = "us-central1"
INSTANCE = "my-mssql-instance"
DATABASE = "my-database"
DB_USER = "my-username"
DB_PASS = "my-password"

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

4. 初始化和使用聊天消息历史

利用MSSQLChatMessageHistory类来管理聊天消息历史记录:

from langchain_google_cloud_sql_mssql import MSSQLChatMessageHistory

TABLE_NAME = "message_store"
engine.init_chat_history_table(table_name=TABLE_NAME)

history = MSSQLChatMessageHistory(
    engine, session_id="test_session", table_name=TABLE_NAME
)
history.add_user_message("hi!")
history.add_ai_message("whats up?")

5. 清理和扩展使用

删除特定会话历史,并通过Google的Vertex AI扩展功能:

history.clear()

!gcloud services enable aiplatform.googleapis.com

from langchain_google_vertexai import ChatVertexAI

prompt = ChatPromptTemplate.from_messages(
    [
        ("system", "You are a helpful assistant."),
        MessagesPlaceholder(variable_name="history"),
        ("human", "{question}"),
    ]
)

chain_with_history = RunnableWithMessageHistory(
    prompt | ChatVertexAI(project=PROJECT_ID),
    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)

常见问题和解决方案

  1. 连接失败:确认您已正确配置防火墙和网络设置。
  2. API调用不稳定:考虑使用API代理服务以提高访问稳定性。
  3. 数据丢失风险:定期备份重要数据以防止意外的删除操作。

总结和进一步学习资源

本文介绍了如何在Google Cloud SQL上配置和使用SQL Server实例来管理和存储聊天消息历史,并通过Vertex AI扩展功能。为了进一步提升您的应用,建议深入学习Google Cloud SQL和Langchain的整合使用。

参考资料

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