Astra DB 向量資料庫
本頁提供使用 Astra DB 作為向量資料庫的快速入門指南。
DataStax Astra DB 是一個以 Apache Cassandra® 為基礎建構的無伺服器、具備向量功能的資料庫,並透過易於使用的 JSON API 方便地提供使用。
設定
整合功能的使用需要 langchain-astradb
合作夥伴套件
pip install -qU "langchain-astradb>=0.3.3"
憑證
為了使用 AstraDB 向量資料庫,您必須先前往 AstraDB 網站,建立一個帳戶,然後建立一個新的資料庫 - 初始化可能需要幾分鐘。
資料庫初始化完成後,您應該建立應用程式權杖並儲存以供日後使用。
您也會想要從「資料庫詳細資訊」中複製 API 端點
,並將其儲存在 ASTRA_DB_API_ENDPOINT
變數中。
您可以選擇性地提供命名空間,您可以從資料庫儀表板的「資料瀏覽器」標籤管理命名空間。如果您不希望設定命名空間,可以將 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')]
從向量資料庫刪除項目
我們可以透過 ID 使用 delete
函數從我們的向量資料庫中刪除項目。
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