使用 Milvus 和 Cognee 建立 RAG
Cognee是一個開發者至上的平台,可透過可擴充的模組化 ECL(Extract、Cognify、Load)管道簡化 AI 應用程式開發。透過與 Milvus 的無縫整合,Cognee 可實現對話、文件和轉錄的高效連接和檢索,從而減少幻覺並優化營運成本。
憑藉對 Milvus、圖形資料庫和 LLM 等向量儲存的強大支援,Cognee 為建立檢索增強生成 (RAG) 系統提供了靈活且可定制的框架。它的生產就緒架構可確保為人工智能驅動的應用程式提高準確性和效率。
在本教程中,我們將教您如何使用 Milvus 和 Cognee 建立 RAG(檢索-增強生成)管道。
$ pip install pymilvus git+https://github.com/topoteretes/cognee.git
如果您使用的是 Google Colab,為了啟用剛安裝的相依性,您可能需要重新啟動執行時(點選畫面上方的「Runtime」功能表,並從下拉式功能表中選擇「Restart session」)。
本範例預設使用 OpenAI 作為 LLM。您應該準備api key,並在 configset_llm_api_key()
函式中設定。
若要設定 Milvus 為向量資料庫,請將VECTOR_DB_PROVIDER
設定為milvus
,並指定VECTOR_DB_URL
和VECTOR_DB_KEY
。因為我們在這個 demo 中使用 Milvus Lite 來儲存資料,所以只需要提供VECTOR_DB_URL
。
import os
import cognee
cognee.config.set_llm_api_key("YOUR_OPENAI_API_KEY")
os.environ["VECTOR_DB_PROVIDER"] = "milvus"
os.environ["VECTOR_DB_URL"] = "./milvus.db"
至於環境變數VECTOR_DB_URL
和VECTOR_DB_KEY
:
- 將
VECTOR_DB_URL
設定為本機檔案,例如./milvus.db
,是最方便的方法,因為它會自動利用Milvus Lite將所有資料儲存在這個檔案中。 - 如果您有大規模的資料,您可以在docker 或 kubernetes 上架設效能更高的 Milvus 伺服器。在此設定中,請使用伺服器的 uri,例如
http://localhost:19530
,作為您的VECTOR_DB_URL
。 - 如果您想使用Zilliz Cloud,Milvus 的完全管理雲端服務,請調整
VECTOR_DB_URL
和VECTOR_DB_KEY
,對應 Zilliz Cloud 的Public Endpoint 和 Api key。
準備資料
我們使用Milvus 文件 2.4.x中的 FAQ 頁面作為我們 RAG 中的私有知識,這是一個簡單 RAG 管道的良好資料來源。
下載 zip 檔案並解壓縮文件到資料夾milvus_docs
。
$ wget https://github.com/milvus-io/milvus-docs/releases/download/v2.4.6-preview/milvus_docs_2.4.x_en.zip
$ unzip -q milvus_docs_2.4.x_en.zip -d milvus_docs
我們從資料夾milvus_docs/en/faq
載入所有 markdown 檔案。對於每個文件,我們只需簡單地使用「#」來分隔文件中的內容,這樣就可以大致分隔出 markdown 文件中每個主要部分的內容。
from glob import glob
text_lines = []
for file_path in glob("milvus_docs/en/faq/*.md", recursive=True):
with open(file_path, "r") as file:
file_text = file.read()
text_lines += file_text.split("# ")
建立 RAG
重置 Cognee 資料
await cognee.prune.prune_data()
await cognee.prune.prune_system(metadata=True)
清零準備就緒後,我們現在就可以加入資料集,並將其處理成知識圖表。
新增資料與認知
await cognee.add(data=text_lines, dataset_name="milvus_faq")
await cognee.cognify()
# [DocumentChunk(id=UUID('6889e7ef-3670-555c-bb16-3eb50d1d30b0'), updated_at=datetime.datetime(2024, 12, 4, 6, 29, 46, 472907, tzinfo=datetime.timezone.utc), text='Does the query perform in memory? What are incremental data and historical data?\n\nYes. When ...
# ...
add
方法會將資料集(Milvus FAQs)載入 Cognee,而cognify
方法則會處理資料,以抽取實體、關係和摘要,建構知識圖表。
查詢摘要
現在資料已經處理完成,讓我們來查詢知識圖表。
from cognee.api.v1.search import SearchType
query_text = "How is data stored in milvus?"
search_results = await cognee.search(SearchType.SUMMARIES, query_text=query_text)
print(search_results[0])
{'id': 'de5c6713-e079-5d0b-b11d-e9bacd1e0d73', 'text': 'Milvus stores two data types: inserted data and metadata.'}
此查詢在知識圖表中搜尋與查詢文字相關的摘要,並列印出最相關的候選摘要。
查詢大塊
摘要提供了高層次的洞察力,但若要瞭解更仔細的細節,我們可以直接從處理過的資料集中查詢特定的資料塊。這些資料塊來自於在建立知識圖表時新增和分析的原始資料。
from cognee.api.v1.search import SearchType
query_text = "How is data stored in milvus?"
search_results = await cognee.search(SearchType.CHUNKS, query_text=query_text)
讓我們將它格式化並顯示出來,以獲得更好的可讀性!
def format_and_print(data):
print("ID:", data["id"])
print("\nText:\n")
paragraphs = data["text"].split("\n\n")
for paragraph in paragraphs:
print(paragraph.strip())
print()
format_and_print(search_results[0])
ID: 4be01c4b-9ee5-541c-9b85-297883934ab3
Text:
Where does Milvus store data?
Milvus deals with two types of data, inserted data and metadata.
Inserted data, including vector data, scalar data, and collection-specific schema, are stored in persistent storage as incremental log. Milvus supports multiple object storage backends, including [MinIO](https://min.io/), [AWS S3](https://aws.amazon.com/s3/?nc1=h_ls), [Google Cloud Storage](https://cloud.google.com/storage?hl=en#object-storage-for-companies-of-all-sizes) (GCS), [Azure Blob Storage](https://azure.microsoft.com/en-us/products/storage/blobs), [Alibaba Cloud OSS](https://www.alibabacloud.com/product/object-storage-service), and [Tencent Cloud Object Storage](https://www.tencentcloud.com/products/cos) (COS).
Metadata are generated within Milvus. Each Milvus module has its own metadata that are stored in etcd.
###
在之前的步驟中,我們查詢了 Milvus FAQ 資料集的摘要和特定資料塊。雖然這提供了詳盡的洞察力和細粒度資訊,但資料集相當龐大,因此要清楚可視化知識圖表內的依賴關係是一大挑戰。
為了解決這個問題,我們將重設 Cognee 環境,並使用更小、更集中的資料集。這將使我們能夠更好地展示在 Cognify 過程中提取的關係和依賴關係。通過簡化資料,我們可以清楚地看到 Cognee 如何組織和結構知識圖表中的資訊。
重置 Cognee
await cognee.prune.prune_data()
await cognee.prune.prune_system(metadata=True)
新增焦點資料集
在這裡,我們添加並處理了一個只有一行文字的較小數據集,以確保知識圖表聚焦且易於詮釋。
# We only use one line of text as the dataset, which simplifies the output later
text = """
Natural language processing (NLP) is an interdisciplinary
subfield of computer science and information retrieval.
"""
await cognee.add(text)
await cognee.cognify()
查詢洞察力
透過聚焦於這個較小的資料集,我們現在可以清楚地分析知識圖形中的關係和結構。
query_text = "Tell me about NLP"
search_results = await cognee.search(SearchType.INSIGHTS, query_text=query_text)
for result_text in search_results:
print(result_text)
# Example output:
# ({'id': UUID('bc338a39-64d6-549a-acec-da60846dd90d'), 'updated_at': datetime.datetime(2024, 11, 21, 12, 23, 1, 211808, tzinfo=datetime.timezone.utc), 'name': 'natural language processing', 'description': 'An interdisciplinary subfield of computer science and information retrieval.'}, {'relationship_name': 'is_a_subfield_of', 'source_node_id': UUID('bc338a39-64d6-549a-acec-da60846dd90d'), 'target_node_id': UUID('6218dbab-eb6a-5759-a864-b3419755ffe0'), 'updated_at': datetime.datetime(2024, 11, 21, 12, 23, 15, 473137, tzinfo=datetime.timezone.utc)}, {'id': UUID('6218dbab-eb6a-5759-a864-b3419755ffe0'), 'updated_at': datetime.datetime(2024, 11, 21, 12, 23, 1, 211808, tzinfo=datetime.timezone.utc), 'name': 'computer science', 'description': 'The study of computation and information processing.'})
# (...)
#
# It represents nodes and relationships in the knowledge graph:
# - The first element is the source node (e.g., 'natural language processing').
# - The second element is the relationship between nodes (e.g., 'is_a_subfield_of').
# - The third element is the target node (e.g., 'computer science').
此輸出代表知識圖表查詢的結果,展示了從已處理資料集中萃取的實體 (節點) 及其關係 (邊)。每個元元組包括來源實體、關係類型和目標實體,以及獨特 ID、描述和時間戳等元資料。圖形會強調關鍵概念及其語義連結,提供對資料集的結構化理解。
恭喜您,您已經學會了使用 Milvus 的 cognee 的基本用法。如果您想了解更多關於 cognee 的進階用法,請參閱其官方頁面。