Astra DB Vector Store(Astra DB 向量儲存)
本頁面提供使用 Astra DB 作為向量儲存的快速入門指南。
DataStax Astra DB 是一個基於 Apache Cassandra® 构建的 serverless 向量資料庫,並通過易於使用的 JSON API 方便地提供。
設定
使用此整合需要 langchain-astradb
合作夥伴套件
pip install -qU "langchain-astradb>=0.3.3"
憑證
為了使用 AstraDB 向量儲存,您必須首先前往 AstraDB 網站,建立一個帳戶,然後建立一個新的資料庫 - 初始化可能需要幾分鐘。
資料庫初始化完成後,您應該建立一個應用程式 Token 並儲存以備後用。
您還需要從Database Details
複製 API Endpoint
,並將其儲存在 ASTRA_DB_API_ENDPOINT
變數中。
您可以選擇性地提供命名空間,您可以從資料庫儀表板的 Data Explorer
標籤中管理。 如果您不希望設定命名空間,您可以將 ASTRA_DB_NAMESPACE
的 getpass
提示留空。
import getpass
ASTRA_DB_API_ENDPOINT = getpass.getpass("ASTRA_DB_API_ENDPOINT = ")
ASTRA_DB_APPLICATION_TOKEN = getpass.getpass("ASTRA_DB_APPLICATION_TOKEN = ")
desired_namespace = getpass.getpass("ASTRA_DB_NAMESPACE = ")
if desired_namespace:
ASTRA_DB_NAMESPACE = desired_namespace
else:
ASTRA_DB_NAMESPACE = None
如果您希望獲得一流的自動化模型調用追蹤,您也可以通過取消註釋下方內容來設定您的 LangSmith API 密鑰
# os.environ["LANGSMITH_API_KEY"] = getpass.getpass("Enter your LangSmith API key: ")
# os.environ["LANGSMITH_TRACING"] = "true"
初始化
有兩種創建 Astra DB 向量儲存的方法,它們的不同之處在於嵌入的計算方式。
方法 1:顯式嵌入
您可以單獨實例化一個 langchain_core.embeddings.Embeddings
類,並將其傳遞給 AstraDBVectorStore
建構子,就像大多數其他 LangChain 向量儲存一樣。
方法 2:整合的嵌入計算
或者,您可以使用 Astra DB 的 Vectorize 功能,只需在創建儲存時指定支援的嵌入模型的名稱即可。 嵌入計算完全在資料庫中處理。(要繼續使用此方法,您必須為您的資料庫啟用所需的嵌入整合,如 文件中所述。)
顯式嵌入初始化
以下,我們使用顯式嵌入類實例化我們的向量儲存
pip install -qU langchain-openai
import getpass
import os
if not os.environ.get("OPENAI_API_KEY"):
os.environ["OPENAI_API_KEY"] = getpass.getpass("Enter API key for OpenAI: ")
from langchain_openai import OpenAIEmbeddings
embeddings = OpenAIEmbeddings(model="text-embedding-3-large")
from langchain_astradb import AstraDBVectorStore
vector_store = AstraDBVectorStore(
collection_name="astra_vector_langchain",
embedding=embeddings,
api_endpoint=ASTRA_DB_API_ENDPOINT,
token=ASTRA_DB_APPLICATION_TOKEN,
namespace=ASTRA_DB_NAMESPACE,
)
整合的嵌入初始化
這裡假設您已
- 在您的 Astra DB 組織中啟用了 OpenAI 整合,
- 向整合添加了名為
"OPENAI_API_KEY"
的 API 密鑰,並將其範圍限定為您正在使用的資料庫。
有關如何執行此操作的更多詳細資訊,請參閱 文件。
from astrapy.info import CollectionVectorServiceOptions
openai_vectorize_options = CollectionVectorServiceOptions(
provider="openai",
model_name="text-embedding-3-small",
authentication={
"providerKey": "OPENAI_API_KEY",
},
)
vector_store_integrated = AstraDBVectorStore(
collection_name="astra_vector_langchain_integrated",
api_endpoint=ASTRA_DB_API_ENDPOINT,
token=ASTRA_DB_APPLICATION_TOKEN,
namespace=ASTRA_DB_NAMESPACE,
collection_vector_service_options=openai_vectorize_options,
)
管理向量儲存
建立向量儲存後,我們可以通過添加和刪除不同的項目與之互動。
向向量儲存添加項目
我們可以使用 add_documents
函數向向量儲存添加項目。
from uuid import uuid4
from langchain_core.documents import Document
document_1 = Document(
page_content="I had chocalate chip pancakes and scrambled eggs for breakfast this morning.",
metadata={"source": "tweet"},
)
document_2 = Document(
page_content="The weather forecast for tomorrow is cloudy and overcast, with a high of 62 degrees.",
metadata={"source": "news"},
)
document_3 = Document(
page_content="Building an exciting new project with LangChain - come check it out!",
metadata={"source": "tweet"},
)
document_4 = Document(
page_content="Robbers broke into the city bank and stole $1 million in cash.",
metadata={"source": "news"},
)
document_5 = Document(
page_content="Wow! That was an amazing movie. I can't wait to see it again.",
metadata={"source": "tweet"},
)
document_6 = Document(
page_content="Is the new iPhone worth the price? Read this review to find out.",
metadata={"source": "website"},
)
document_7 = Document(
page_content="The top 10 soccer players in the world right now.",
metadata={"source": "website"},
)
document_8 = Document(
page_content="LangGraph is the best framework for building stateful, agentic applications!",
metadata={"source": "tweet"},
)
document_9 = Document(
page_content="The stock market is down 500 points today due to fears of a recession.",
metadata={"source": "news"},
)
document_10 = Document(
page_content="I have a bad feeling I am going to get deleted :(",
metadata={"source": "tweet"},
)
documents = [
document_1,
document_2,
document_3,
document_4,
document_5,
document_6,
document_7,
document_8,
document_9,
document_10,
]
uuids = [str(uuid4()) for _ in range(len(documents))]
vector_store.add_documents(documents=documents, ids=uuids)
[UUID('89a5cea1-5f3d-47c1-89dc-7e36e12cf4de'),
UUID('d4e78c48-f954-4612-8a38-af22923ba23b'),
UUID('058e4046-ded0-4fc1-b8ac-60e5a5f08ea0'),
UUID('50ab2a9a-762c-4b78-b102-942a86d77288'),
UUID('1da5a3c1-ba51-4f2f-aaaf-79a8f5011ce3'),
UUID('f3055d9e-2eb1-4d25-838e-2c70548f91b5'),
UUID('4bf0613d-08d0-4fbc-a43c-4955e4c9e616'),
UUID('18008625-8fd4-45c2-a0d7-92a2cde23dbc'),
UUID('c712e06f-790b-4fd4-9040-7ab3898965d0'),
UUID('a9b84820-3445-4810-a46c-e77b76ab85bc')]
從向量儲存中刪除項目
我們可以使用 delete
函數通過 ID 從向量儲存中刪除項目。
vector_store.delete(ids=uuids[-1])
True
查詢向量儲存
創建了向量儲存並添加了相關文件後,您很可能希望在鏈或代理程式運行期間查詢它。
直接查詢
相似度搜尋
執行簡單的相似度搜尋,並對元數據進行過濾,可以按照以下步驟進行
results = vector_store.similarity_search(
"LangChain provides abstractions to make working with LLMs easy",
k=2,
filter={"source": "tweet"},
)
for res in results:
print(f"* {res.page_content} [{res.metadata}]")
* Building an exciting new project with LangChain - come check it out! [{'source': 'tweet'}]
* LangGraph is the best framework for building stateful, agentic applications! [{'source': 'tweet'}]
帶分數的相似度搜尋
您也可以搜尋並取得分數
results = vector_store.similarity_search_with_score(
"Will it be hot tomorrow?", k=1, filter={"source": "news"}
)
for res, score in results:
print(f"* [SIM={score:3f}] {res.page_content} [{res.metadata}]")
* [SIM=0.776585] The weather forecast for tomorrow is cloudy and overcast, with a high of 62 degrees. [{'source': 'news'}]
其他搜尋方法
還有許多其他搜尋方法未在本筆記本中涵蓋,例如 MMR 搜尋或向量搜尋。如需 AstraDBVectorStore
提供的完整搜尋功能列表,請查看API 參考文件。
轉換為檢索器進行查詢
您也可以將向量儲存轉換為檢索器,以便在您的鏈中使用。
以下是如何將您的向量儲存轉換為檢索器,然後使用簡單的查詢和過濾器來調用檢索器。
retriever = vector_store.as_retriever(
search_type="similarity_score_threshold",
search_kwargs={"k": 1, "score_threshold": 0.5},
)
retriever.invoke("Stealing from the bank is a crime", filter={"source": "news"})
[Document(metadata={'source': 'news'}, page_content='Robbers broke into the city bank and stole $1 million in cash.')]
用於檢索增強生成的使用方法
有關如何使用此向量儲存進行檢索增強生成 (RAG) 的指南,請參閱以下章節
如需更多資訊,請查看使用 Astra DB 的完整 RAG 範本此處。
清理向量儲存
如果您想從您的 Astra DB 實例中完全刪除集合,請運行此命令。
(您將遺失儲存在其中的資料。)
vector_store.delete_collection()
API 參考
如需所有 AstraDBVectorStore
功能和配置的詳細文件,請前往 API 參考:https://langchain-python.dev.org.tw/api_reference/astradb/vectorstores/langchain_astradb.vectorstores.AstraDBVectorStore.html