Skip to main content
Open In ColabOpen on GitHub

Google Spanner

Google Cloud Spanner 是一种高度可扩展的数据库,将无限的可扩展性与关系型语义(如二级索引、强一致性、模式和 SQL)相结合,通过一个简单易用的解决方案提供 99.999% 的可用性。

该笔记本介绍了如何使用 SpannerSpannerChatMessageHistory 类一起存储聊天消息历史。 在 GitHub 上了解有关该包的更多信息。

Open In Colab

开始之前

要运行此笔记本,您需要执行以下操作:

🦜🔗 库安装

The integration lives in its own langchain-google-spanner package, so we need to install it.

%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工作区,请参阅设置说明这里
from google.colab import auth

auth.authenticate_user()

☁ 设置您的Google云项目

设置您的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 类时,您只需提供以下三点:

  1. instance_id - Cloud Spanner 实例的名称
  2. database_id - Spanner数据库的名称
  3. session_id - 一个唯一的标识符字符串,用于指定会话的ID。
  4. 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()