Google Spanner
Google Cloud Spanner 是一个高度可扩展的数据库,它将无限的可扩展性与关系语义(例如二级索引、强一致性、模式和 SQL)相结合,在一个简单的解决方案中提供 99.999% 的可用性。
本笔记本介绍了如何使用 Spanner
和 SpannerChatMessageHistory
类来存储聊天消息历史记录。请访问 GitHub 了解有关该软件包的更多信息。
开始之前
要运行此笔记本,您需要执行以下操作
🦜🔗 库安装
该集成位于其自己的 langchain-google-spanner
软件包中,因此我们需要安装它。
%pip install --upgrade --quiet langchain-google-spanner
仅限 Colab: 取消注释以下单元格以重启内核,或使用按钮重启内核。对于 Vertex AI Workbench,您可以使用顶部的按钮重启终端。
# # Automatically restart kernel after installs so that your environment can access the new packages
# import IPython
# app = IPython.Application.instance()
# app.kernel.do_shutdown(True)
🔐 身份验证
以 IAM 用户身份验证到 Google Cloud,该用户已登录到此笔记本,以便访问您的 Google Cloud 项目。
- 如果您使用 Colab 运行此笔记本,请使用以下单元格并继续。
- 如果您使用 Vertex AI Workbench,请查看 此处 的设置说明。
from google.colab import auth
auth.authenticate_user()
☁ 设置您的 Google Cloud 项目
设置您的 Google Cloud 项目,以便您可以在此笔记本中利用 Google Cloud 资源。
如果您不知道您的项目 ID,请尝试以下操作
- 运行
gcloud config list
。 - 运行
gcloud projects list
。 - 请参阅支持页面:查找项目 ID。
# @markdown Please fill in the value below with your Google Cloud project ID and then run the cell.
PROJECT_ID = "my-project-id" # @param {type:"string"}
# Set the project id
!gcloud config set project {PROJECT_ID}
💡 API 启用
langchain-google-spanner
软件包要求您在您的 Google Cloud 项目中启用 Spanner API。
# enable Spanner API
!gcloud services enable spanner.googleapis.com
基本用法
设置 Spanner 数据库值
在 Spanner 实例页面 中找到您的数据库值。
# @title Set Your Values Here { display-mode: "form" }
INSTANCE = "my-instance" # @param {type: "string"}
DATABASE = "my-database" # @param {type: "string"}
TABLE_NAME = "message_store" # @param {type: "string"}
初始化表
SpannerChatMessageHistory
类需要具有特定架构的数据库表才能存储聊天消息历史记录。
辅助方法 init_chat_history_table()
可用于创建一个具有正确架构的表。
from langchain_google_spanner import (
SpannerChatMessageHistory,
)
SpannerChatMessageHistory.init_chat_history_table(table_name=TABLE_NAME)
SpannerChatMessageHistory
要初始化 SpannerChatMessageHistory
类,您只需要提供 3 件事
instance_id
- Spanner 实例的名称database_id
- Spanner 数据库的名称session_id
- 一个唯一的标识符字符串,用于指定会话的 ID。table_name
- 数据库中用于存储聊天消息历史记录的表的名称。
message_history = SpannerChatMessageHistory(
instance_id=INSTANCE,
database_id=DATABASE,
table_name=TABLE_NAME,
session_id="user-session-id",
)
message_history.add_user_message("hi!")
message_history.add_ai_message("whats up?")
message_history.messages
自定义客户端
默认创建的客户端是默认客户端。要使用非默认客户端,可以将自定义客户端传递给构造函数。
from google.cloud import spanner
custom_client_message_history = SpannerChatMessageHistory(
instance_id="my-instance",
database_id="my-database",
client=spanner.Client(...),
)
清理
当特定会话的历史记录过时且可以删除时,可以按以下方式完成。注意:一旦删除,数据将不再存储在 Cloud Spanner 中,并且将永久丢失。
message_history = SpannerChatMessageHistory(
instance_id=INSTANCE,
database_id=DATABASE,
table_name=TABLE_NAME,
session_id="user-session-id",
)
message_history.clear()