跳至主要內容

Google Memorystore for Redis

Google Memorystore for Redis 是一項完全託管的服務,由 Redis 記憶體內資料儲存提供支援,可建置應用程式快取,提供亞毫秒級的資料存取。 擴展您的資料庫應用程式,利用 Memorystore for Redis 的 Langchain 整合,建立 AI 驅動的體驗。

此筆記本說明如何使用 Memorystore for Redis,透過 MemorystoreVectorStore 類別儲存向量嵌入。

GitHub 上了解更多關於此套件的資訊。

Open In Colab

先決條件

開始之前

若要執行此筆記本,您需要執行下列操作

🦜🔗 函式庫安裝

此整合位於其自身的 langchain-google-memorystore-redis 套件中,因此我們需要安裝它。

%pip install -upgrade --quiet langchain-google-memorystore-redis langchain

僅限 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)

☁ 設定您的 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}

🔐 驗證

以登入此筆記本的 IAM 使用者身分驗證 Google Cloud,以便存取您的 Google Cloud 專案。

  • 如果您使用 Colab 執行此筆記本,請使用下面的儲存格並繼續。
  • 如果您使用 Vertex AI Workbench,請查看此處的設定說明。
from google.colab import auth

auth.authenticate_user()

基本用法

初始化向量索引

import redis
from langchain_google_memorystore_redis import (
DistanceStrategy,
HNSWConfig,
RedisVectorStore,
)

# Connect to a Memorystore for Redis instance
redis_client = redis.from_url("redis://127.0.0.1:6379")

# Configure HNSW index with descriptive parameters
index_config = HNSWConfig(
name="my_vector_index", distance_strategy=DistanceStrategy.COSINE, vector_size=128
)

# Initialize/create the vector store index
RedisVectorStore.init_index(client=redis_client, index_config=index_config)

準備文件

文字需要經過處理和數值表示,才能與向量儲存互動。 這包括

  • 載入文字:TextLoader 從檔案 (例如 "state_of_the_union.txt") 取得文字資料。
  • 文字分割:CharacterTextSplitter 將文字分成更小的區塊,以用於嵌入模型。
from langchain_community.document_loaders import TextLoader
from langchain_text_splitters import CharacterTextSplitter

loader = TextLoader("./state_of_the_union.txt")
documents = loader.load()
text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)
docs = text_splitter.split_documents(documents)

將文件新增至向量儲存

在文字準備和嵌入產生之後,以下方法會將它們插入到 Redis 向量儲存中。

方法 1:用於直接插入的類別方法

此方法使用 from_documents 類別方法,將嵌入建立和插入合併到單一步驟中

from langchain_community.embeddings.fake import FakeEmbeddings

embeddings = FakeEmbeddings(size=128)
redis_client = redis.from_url("redis://127.0.0.1:6379")
rvs = RedisVectorStore.from_documents(
docs, embedding=embeddings, client=redis_client, index_name="my_vector_index"
)
API 參考:FakeEmbeddings

方法 2:基於實例的插入

此方法在處理新的或現有的 RedisVectorStore 時提供靈活性

  • [可選] 建立 RedisVectorStore 實例:實例化 RedisVectorStore 物件以進行自訂。 如果您已經有實例,請繼續執行下一步。
  • 新增帶有元資料的文字:將原始文字和元資料提供給實例。 嵌入生成和插入向量儲存會自動處理。
rvs = RedisVectorStore(
client=redis_client, index_name="my_vector_index", embeddings=embeddings
)
ids = rvs.add_texts(
texts=[d.page_content for d in docs], metadatas=[d.metadata for d in docs]
)

執行相似性搜尋 (KNN)

在向量儲存填充後,可以搜尋在語義上與查詢相似的文字。 以下是如何使用具有預設設定的 KNN (K-Nearest Neighbors)

  • 制定查詢:自然語言問題表達了搜尋意圖 (例如 "總統對 Ketanji Brown Jackson 說了什麼")。
  • 檢索相似結果:similarity_search 方法在向量儲存中找到在意義上最接近查詢的項目。
import pprint

query = "What did the president say about Ketanji Brown Jackson"
knn_results = rvs.similarity_search(query=query)
pprint.pprint(knn_results)

範圍查詢透過指定期望的相似度閾值以及查詢文字,提供更佳的控制能力。

  • 制定查詢:自然語言問題定義了搜尋意圖。
  • 設定相似度閾值:distance_threshold 參數決定了多接近的匹配才被認為是相關的。
  • 檢索結果:similarity_search_with_score 方法從向量儲存區中尋找落在指定相似度閾值內的項目。
rq_results = rvs.similarity_search_with_score(query=query, distance_threshold=0.8)
pprint.pprint(rq_results)

MMR 查詢旨在尋找與查詢相關且彼此不同的結果,從而減少搜尋結果中的冗餘。

  • 制定查詢:自然語言問題定義了搜尋意圖。
  • 平衡相關性和多樣性:lambda_mult 參數控制了嚴格相關性和促進結果多樣性之間的權衡。
  • 檢索 MMR 結果:max_marginal_relevance_search 方法根據 lambda 設定,返回優化相關性和多樣性組合的項目。
mmr_results = rvs.max_marginal_relevance_search(query=query, lambda_mult=0.90)
pprint.pprint(mmr_results)

將向量儲存區用作檢索器

為了與其他 LangChain 元件無縫整合,可以將向量儲存區轉換為檢索器。 這提供了一些優勢:

  • LangChain 相容性:許多 LangChain 工具和方法都設計為直接與檢索器互動。
  • 易於使用:as_retriever() 方法將向量儲存區轉換為簡化查詢的格式。
retriever = rvs.as_retriever()
results = retriever.invoke(query)
pprint.pprint(results)

清理

從向量儲存區中刪除文件

有時,需要從向量儲存區中刪除文件(及其相關的向量)。 delete 方法提供了此功能。

rvs.delete(ids)

刪除向量索引

在某些情況下,可能需要刪除現有的向量索引。 常見原因包括:

  • 索引配置變更:如果需要修改索引參數,通常需要刪除並重新建立索引。
  • 儲存管理:刪除未使用的索引可以幫助釋放 Redis 實例中的空間。

注意:向量索引刪除是不可逆的操作。 在繼續操作之前,請確定不再需要儲存的向量和搜尋功能。

# Delete the vector index
RedisVectorStore.drop_index(client=redis_client, index_name="my_vector_index")

此頁面是否有幫助?