開始使用 Spanner Vector Search

1. 簡介

Spanner 是全代管且遍及全球的全代管資料庫服務,非常適合關聯式和非關聯作業工作負載。

Spanner 現在推出精準 K-nearest 相鄰功能,現在也成為高擴充性的向量資料庫,可讓您在生成式 AI 應用程式中大規模執行相似度和語意搜尋,以及大規模導入擷取增強生成 (RAG) 功能。交易完成後,Spanner 的向量搜尋查詢就會立即傳回最新即時資料,就像任何其他查詢作業資料一樣。

本研究室將逐步說明如何設定基本功能,運用 Spanner 執行向量搜尋,並透過 SQL 存取 Vertex AI 模型花園中的嵌入和 LLM 模型。

架構應如下所示:

d179a760add7adc0.png

建構項目

在這個研究室中,您將完成以下工作:

  • 可建立 Spanner 執行個體
  • 設定 Spanner 的資料庫結構定義,以與 Vertex AI 中的嵌入和大型語言模型整合
  • 載入零售資料集
  • 對資料集發出相似度搜尋查詢
  • 為 LLM 模型提供背景資訊,生成產品相關建議。

課程內容

  • 如何設定 Spanner 執行個體
  • 如何整合 VertexAI
  • 如何使用 Spanner 執行向量搜尋功能,尋找零售資料集內的類似項目

事前準備

  • 連結至帳單帳戶的 Google Cloud 專案。
  • 使用網路瀏覽器,例如 ChromeFirefox

2. 設定和需求

建立專案

如果您還沒有 Google 帳戶 (Gmail 或 Google Apps),請先建立帳戶。登入 Google Cloud Platform 控制台 ( console.cloud.google.com),並建立新專案。

如果您已有專案,請按一下控制台左上方的專案選取下拉式選單:

6c9406d9b014760.png

然後在結果對話方塊中按一下 [新增專案] 按鈕,就能建立新專案:

949d83c8a4ee17d9.png

如果您還沒有專案,系統會顯示如下的對話方塊,讓您建立第一個專案:

870a3cbd6541ee86.png

後續的專案建立對話方塊可讓您輸入新專案的詳細資料:

6a92c57d3250a4b3.png

請記住,專案 ID 在所有的 Google Cloud 專案中是不重複的名稱 (已經有人使用上述名稱,目前無法為您解決問題!)。稍後在本程式碼研究室中會稱為 PROJECT_ID。

接下來,如果您尚未在 Developers Console 中啟用計費功能,必須完成此步驟,才能使用 Google Cloud 資源並啟用 Spanner API

15d0ef27a8fbab27.png

執行本程式碼研究室所需的費用不應超過數美元,但如果您決定使用更多資源,或讓這些資源繼續運作,費用會增加 (請參閱本文件結尾的「清理」一節)。如需 Google Cloud Spanner 的定價資訊,請參閱這裡

Google Cloud Platform 的新使用者符合 $300 美元的免費試用資格,應該可以免費使用本程式碼研究室。

Google Cloud Shell 設定

雖然 Google Cloud 和 Spanner 可以在筆記型電腦上遠端運作,但在本程式碼研究室中,我們會使用 Google Cloud Shell,這是一種在 Cloud 中執行的指令列環境。

這種以 Debian 為基礎的虛擬機器,搭載各種您需要的開發工具。提供永久的 5 GB 主目錄,而且在 Google Cloud 中運作,大幅提高網路效能和驗證能力。換言之,本程式碼研究室只需要在 Chromebook 上運作即可。

  1. 如要透過 Cloud 控制台啟用 Cloud Shell,只要點選「啟用 Cloud Shell」圖示 gcLMt5IuEcJJNnMId-Bcz3sxCd0rZn7IzT_r95C8UZeqML68Y1efBG_B0VRp7hc7qiZTLAF-TXD7SsOadxn8uadgHhaLeASnVS3ZHK39eOlKJOgj9SJua_oeGhMxRrbOg3qigddS2A,即可佈建並連線至環境,操作只需幾分鐘的時間。

JjEuRXGg0AYYIY6QZ8d-66gx_Mtc-_jDE9ijmbXLJSAXFvJt-qUpNtsBsYjNpv2W6BQSrDc1D-ARINNQ-1EkwUhz-iUK-FUCZhJ-NtjvIEx9pIkE-246DomWuCfiGHK78DgoeWkHRw

Screen Shot 2017-06-14 at 10.13.43 PM.png

連線至 Cloud Shell 後,您應會發現自己通過驗證,且專案已設為 PROJECT_ID。

gcloud auth list

指令輸出

Credentialed accounts:
 - <myaccount>@<mydomain>.com (active)
gcloud config list project

指令輸出

[core]
project = <PROJECT_ID>

如因故未設定專案,請直接發出以下指令:

gcloud config set project <PROJECT_ID>

正在尋找 PROJECT_ID 嗎?查看您在設定步驟中使用的 ID,或在 Cloud 控制台資訊主頁查詢:

158fNPfwSxsFqz9YbtJVZes8viTS3d1bV4CVhij3XPxuzVFOtTObnwsphlm6lYGmgdMFwBJtc-FaLrZU7XHAg_ZYoCrgombMRR3h-eolLPcvO351c5iBv506B3ZwghZoiRg6cz23Qw

根據預設,Cloud Shell 也會設定一些環境變數,方便您之後執行指令。

echo $GOOGLE_CLOUD_PROJECT

指令輸出

<PROJECT_ID>

啟用 Spanner API

gcloud services enable spanner.googleapis.com

摘要

如果您尚未設定專案,並啟用必要的 API,在這個步驟中就會設定專案。

下一步

接下來,您將設定 Spanner 執行個體和資料庫。

3. 建立 Spanner 執行個體和資料庫

建立 Spanner 執行個體

在這個步驟中,我們會為程式碼研究室設定 Spanner 執行個體。方法是開啟 Cloud Shell 並執行下列指令:

export SPANNER_INSTANCE_ID=retail-demo
gcloud spanner instances create $SPANNER_INSTANCE_ID \
--config=regional-us-central1 \
--description="spanner AI retail demo" \
--nodes=1

指令輸出:

$ gcloud spanner instances create $SPANNER_INSTANCE_ID \
--config=regional-us-central1 \
--description="spanner AI retail demo" \
--nodes=1
Creating instance...done.  

建立資料庫

執行個體開始運作後,您就能建立資料庫。Spanner 允許在單一執行個體上使用多個資料庫。

您可以在資料庫中定義結構定義。您也可以控管有權存取資料庫的使用者、設定自訂加密功能、設定最佳化器,以及設定保留期限。

如要建立資料庫,請再次使用 gcloud 指令列工具:

export SPANNER_DATABASE=cymbal-bikes
gcloud spanner databases create $SPANNER_DATABASE \
 --instance=$SPANNER_INSTANCE_ID

指令輸出:

$ gcloud spanner databases create $SPANNER_DATABASE \
 --instance=$SPANNER_INSTANCE_ID
Creating database...done.

摘要

在這個步驟中,您已建立 Spanner 執行個體和資料庫。

下一步

接下來,您將設定 Spanner 結構定義和資料。

4. 載入 Cymbal 結構定義和資料

建立 Cymbal 結構定義

如要設定結構定義,請前往 Spanner Studio:

3e1a0fed928b33cf.png

結構定義包含兩個部分請先新增 products 資料表。複製這個陳述式,然後貼到空白分頁中。

針對結構定義,請複製下列 DDL 並貼進方塊中:

CREATE TABLE products (
categoryId INT64 NOT NULL,
productId INT64 NOT NULL,
productName STRING(MAX) NOT NULL,
productDescription STRING(MAX) NOT NULL,
productDescriptionEmbedding ARRAY<FLOAT64>,
createTime TIMESTAMP NOT NULL OPTIONS (
allow_commit_timestamp = true
),
inventoryCount INT64 NOT NULL,
priceInCents INT64,
) PRIMARY KEY(categoryId, productId);

接著點選「run」按鈕,等待幾秒鐘,讓系統建立結構定義。

接下來,您將建立兩個模型,並設為 Vertex AI 模型端點。

第一種是嵌入模型,用於根據文字產生嵌入,而第二個模型則是能根據 Spanner 資料產生回應的 LLM 模型。

將下列結構定義貼到 Spanner Studio 的新分頁中:

CREATE MODEL EmbeddingsModel INPUT(
content STRING(MAX),
) OUTPUT(
embeddings STRUCT<statistics STRUCT<truncated BOOL, token_count FLOAT64>, values ARRAY<FLOAT64>>,
) REMOTE OPTIONS (
endpoint = '//aiplatform.googleapis.com/projects/<PROJECT_ID>/locations/us-central1/publishers/google/models/textembedding-gecko@003'
);

CREATE MODEL LLMModel INPUT(
prompt STRING(MAX),
) OUTPUT(
content STRING(MAX),
) REMOTE OPTIONS (
endpoint = '//aiplatform.googleapis.com/projects/<PROJECT_ID>/locations/us-central1/publishers/google/models/text-bison@001',
default_batch_size = 1
);

接著,按一下「run」按鈕,等待幾秒鐘,讓系統建立模型。

Spanner Studio 的左側窗格中應會顯示下列資料表和模型:

62455aa4b0e839d9.png

載入資料

現在,請將一些產品插入資料庫。在 Spanner Studio 中開啟新分頁,然後複製並貼上下列插入陳述式:

INSERT INTO products (categoryId, productId, productName, productDescription, createTime, inventoryCount, priceInCents)
VALUES (1, 1, "Cymbal Helios Helmet", "Safety meets style with the Cymbal children's bike helmet. Its lightweight design, superior ventilation, and adjustable fit ensure comfort and protection on every ride. Stay bright and keep your child safe under the sun with Cymbal Helios!", PENDING_COMMIT_TIMESTAMP(), 100, 10999),
(1, 2, "Cymbal Sprout", "Let their cycling journey begin with the Cymbal Sprout, the ideal balance bike for beginning riders ages 2-4 years. Its lightweight frame, low seat height, and puncture-proof tires promote stability and confidence as little ones learn to balance and steer. Watch them sprout into cycling enthusiasts with Cymbal Sprout!", PENDING_COMMIT_TIMESTAMP(), 10, 13999),
(1, 3, "Cymbal Spark Jr.", "Light, vibrant, and ready for adventure, the Spark Jr. is the perfect first bike for young riders (ages 5-8). Its sturdy frame, easy-to-use brakes, and puncture-resistant tires inspire confidence and endless playtime. Let the spark of cycling ignite with Cymbal!", PENDING_COMMIT_TIMESTAMP(), 34, 13900),
(1, 4, "Cymbal Summit", "Conquering trails is a breeze with the Summit mountain bike. Its lightweight aluminum frame, responsive suspension, and powerful disc brakes provide exceptional control and comfort for experienced bikers navigating rocky climbs or shredding downhill. Reach new heights with Cymbal Summit!", PENDING_COMMIT_TIMESTAMP(), 0, 79999),
(1, 5, "Cymbal Breeze", "Cruise in style and embrace effortless pedaling with the Breeze electric bike. Its whisper-quiet motor and long-lasting battery let you conquer hills and distances with ease. Enjoy scenic rides, commutes, or errands with a boost of confidence from Cymbal Breeze!", PENDING_COMMIT_TIMESTAMP(), 72, 129999),
(1, 6, "Cymbal Trailblazer Backpack", "Carry all your essentials in style with the Trailblazer backpack. Its water-resistant material, multiple compartments, and comfortable straps keep your gear organized and accessible, allowing you to focus on the adventure. Blaze new trails with Cymbal Trailblazer!", PENDING_COMMIT_TIMESTAMP(), 24, 7999),
(1, 7, "Cymbal Phoenix Lights", "See and be seen with the Phoenix bike lights. Powerful LEDs and multiple light modes ensure superior visibility, enhancing your safety and enjoyment during day or night rides. Light up your journey with Cymbal Phoenix!", PENDING_COMMIT_TIMESTAMP(), 87, 3999),
(1, 8, "Cymbal Windstar Pump", "Flat tires are no match for the Windstar pump. Its compact design, lightweight construction, and high-pressure capacity make inflating tires quick and effortless. Get back on the road in no time with Cymbal Windstar!", PENDING_COMMIT_TIMESTAMP(), 36, 24999),
(1, 9,"Cymbal Odyssey Multi-Tool","Be prepared for anything with the Odyssey multi-tool. This handy gadget features essential tools like screwdrivers, hex wrenches, and tire levers, keeping you ready for minor repairs and adjustments on the go. Conquer your journey with Cymbal Odyssey!", PENDING_COMMIT_TIMESTAMP(), 52, 999),
(1, 10,"Cymbal Nomad Water Bottle","Stay hydrated on every ride with the Nomad water bottle. Its sleek design, BPA-free construction, and secure lock lid make it the perfect companion for staying refreshed and motivated throughout your adventures. Hydrate and explore with Cymbal Nomad!", PENDING_COMMIT_TIMESTAMP(), 42, 1299);

按一下 run 按鈕即可插入資料。

摘要

在這個步驟中,您已建立結構定義,並將部分基本資料載入 cymbal-bikes 資料庫。

下一步

接下來,您將與嵌入模型整合,產生產品說明的嵌入項目,以及將文字搜尋要求轉換成嵌入項目,以便搜尋相關產品。

5. 使用嵌入

產生產品說明的向量嵌入

為了讓產品使用相似度搜尋功能,您必須產生產品說明的嵌入項目。

在結構定義中建立的 EmbeddingsModel 中,這是簡單的 UPDATE DML 陳述式。

UPDATE products p1
SET productDescriptionEmbedding =
(SELECT embeddings.values from ML.PREDICT(MODEL EmbeddingsModel,
(SELECT productDescription as content FROM products p2 where p2.productId=p1.productId)))
WHERE categoryId=1;

按一下「run」按鈕即可更新產品說明。

在這個範例中,您會透過 SQL 查詢提供自然語言搜尋要求。這項查詢會將搜尋要求轉換為嵌入項目,然後依據先前步驟中產生的產品說明嵌入項目,搜尋類似的結果。

-- Use Spanner's vector search, and integration with embedding and LLM models to
-- return items that are semantically relevant and available in inventory based on
-- real-time data.


SELECT productName, productDescription, inventoryCount, COSINE_DISTANCE(
productDescriptionEmbedding,
(   SELECT embeddings.values
FROM ML.PREDICT(
MODEL EmbeddingsModel,
(SELECT "I'd like to buy a starter bike for my 3 year old child" as content)
)
)
) as distance
FROM products
WHERE inventoryCount > 0
ORDER BY distance
LIMIT 5;

按一下 run 按鈕即可尋找相似產品。結果應如下所示:

672e111753077fcf.png

請注意,查詢會使用額外的篩選器,例如只對有現貨的產品感興趣 (inventoryCount > 0)。

摘要

在這個步驟中,您利用 SQL 與 Vertex AI 中的模型整合,透過 SQL 建立產品說明嵌入和搜尋要求嵌入項目。您同時執行了向量搜尋,找出符合搜尋要求的類似產品。

後續步驟

接著,我們要使用搜尋結果將搜尋結果輸入 LLM,為每個產品生成自訂回應。

6. 使用大型語言模型

Spanner 可讓您輕鬆整合由 Vertex AI 提供的 LLM 模型。這樣一來,開發人員就能直接使用 SQL 來與 LLM 互動,不必要求應用程式執行邏輯。

例如,我們得到使用者 "I'd like to buy a starter bike for my 3 year old child". 內有關先前 SQL 查詢的結果

開發人員想根據以下提示回覆每項結果,確認產品是否適合使用者:

"Answer with ‘Yes' or ‘No' and explain why: Is this a good fit for me? I'd like to buy a starter bike for my 3 year old child"

您可以使用的查詢如下:

-- Use an LLM to analyze this list and provide a recommendation on whether each
-- product is a good fit for the user. We use the vector search and real time
-- inventory data to first filter the products to reduce the size of the prompt to
-- the LLM.
SELECT productName, productDescription, inventoryCount, content AS LLMResponse
FROM ML.PREDICT(
MODEL LLMModel,
(   SELECT
inventoryCount,
productName,
productDescription,
CONCAT(
"Answer with ‘Yes' or ‘No' and explain why: Is this a good fit for me?",
"I'd like to buy a starter bike for my 3 year old child \n",
"Product Name: ", productName, "\n",
"Product Description:", productDescription) AS prompt,
FROM products
WHERE inventoryCount > 0
ORDER by COSINE_DISTANCE(
productDescriptionEmbedding,
(   SELECT embeddings.values
FROM ML.PREDICT(
MODEL EmbeddingsModel,
( SELECT "I'd like to buy a starter bike for my 3 year old child" as content)
)
)
) LIMIT 5
),
STRUCT(256 AS maxOutputTokens)
);

按一下 run 按鈕以發出查詢。結果應如下所示:

35878cd0f88f1470.png

第一項產品符合產品說明中的年齡層 (2 至 4 歲),因此適合 3 歲。其他產品則不適合。

摘要

後續步驟

接下來是清理儲存空間的好時機!

7. 清除所用資源 (選用)

如要清除所用資源,請前往 Cloud 控制台的 Cloud Spanner 部分,然後刪除我們在程式碼研究室中建立的「retail-demo」執行個體。

41cbc1a84b3588d5.png

8. 恭喜!

恭喜!您已成功使用 Spanner 的內建向量搜尋功能執行相似度搜尋。此外,您也可以輕鬆透過嵌入和大型語言模型,使用 SQL 直接提供生成式 AI 功能。

後續步驟

如要進一步瞭解 Spanner 最鄰近 (KNN 向量搜尋) 功能,請前往:https://cloud.google.com/spanner/docs/find-k-nearest-neighbors

您也可以造訪下列網址,進一步瞭解如何使用 Spanner 的 VertexAI 整合功能以 SQL 執行線上預測:https://cloud.google.com/spanner/docs/ml