Google Cloud Memorystore for Redis
Google Cloud Memorystore for Redis 是一項全受管服務,由 Redis 記憶體內資料儲存提供支援,可建置提供亞毫秒資料存取速度的應用程式快取。擴展您的資料庫應用程式,以利用 Memorystore for Redis 的 Langchain 整合功能,建置由 AI 驅動的體驗。
本筆記本說明如何使用 Memorystore for Redis,透過 MemorystoreVectorStore
類別儲存向量嵌入。
在 GitHub 上深入瞭解套件。
先決條件
開始之前
若要執行本筆記本,您需要執行下列操作
🦜🔗 程式庫安裝
整合存在於其自身的 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"
)
方法 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 最近鄰)
- 制定查詢:自然語言問題表達搜尋意圖 (例如「總統對 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) 搜尋
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")