利用維基百科API擷取資料,建構Deep Lake向量儲存函式庫,並使用LlamaIndex建立知識圖譜索引,實作高效能的RAG問答系統。系統流程包含資料收集、向量儲存、知識圖譜索引建構、查詢與生成,以及效能評估。透過Python程式碼示範如何使用wikipedia套件收集維基百科資料,並將其嵌入至Deep Lake向量儲存函式庫中。接著,利用LlamaIndex的KnowledgeGraphIndex建立知識圖譜索引,並執行查詢。最後,使用餘弦相似度和人工回饋評估系統效能,提供一個可擴充套件的知識圖譜RAG系統構建方案。

知識圖譜索引為基礎的RAG技術實作與解析

在前一章節中,我們成功建立並填充了Deep Lake向量儲存函式庫。本章節將著重於建立根據知識圖譜索引的RAG(檢索增強生成)管線,並與之互動。

管線3:知識圖譜索引為基礎的RAG

本章節將會建立知識圖譜索引、顯示圖譜、定義使用者提示、設定LlamaIndex內建LLM模型的超引數、安裝相似度評分套件、定義相似度函式、執行範例相似度比較、重新排序LLM回應的輸出向量、執行評估範例並套用指標和人為回饋評分,以及執行指標計算並顯示結果。

建立知識圖譜索引

首先,我們需要使用llama_index.core模組中的KnowledgeGraphIndex類別來建立知識圖譜索引。我們也會計算索引建立的時間,以評估效能。

from llama_index.core import KnowledgeGraphIndex
import time

# 開始計時
start_time = time.time()

# 建立知識圖譜索引
graph_index = KnowledgeIndex.from_documents(
    documents,
    max_triplets_per_chunk=2,
    include_embeddings=True,
)

# 結束計時
end_time = time.time()
elapsed_time = end_time - start_time
print(f"索引建立時間:{elapsed_time:.4f}秒")
print(type(graph_index))

輸出結果顯示了索引建立的時間和圖譜的型別:

索引建立時間:371.9844秒
<class 'llama_index.core.indices.knowledge_graph.base.KnowledgeGraphIndex'>

設定查詢引擎

接下來,我們需要設定查詢引擎,以管理相似度、回應溫度和輸出長度等引數:

# 設定相似度前k個結果
k = 3
# 設定溫度引數
temp = 0.1
# 設定輸出最大token數
mt = 1024

# 建立查詢引擎
graph_query_engine = graph_index.as_query_engine(
    similarity_top_k=k,
    temperature=temp,
    response_mode="compact",
    max_tokens=mt
)

這些引數將決定查詢引擎的行為:

  • k=3:設定要考慮的相似度前k個結果。
  • temp=0.1:設定溫度引數,控制查詢引擎回應生成的隨機性。越低的值越精確,越高的值越具創意。
  • mt=1024:設定輸出最大token數,定義生成的回應長度。

顯示圖譜

為了視覺化知識圖譜,我們將使用pyvis.network函式庫來建立互動式網路視覺化:

from pyvis.network import Network

# 建立圖譜
g = graph_index.get_networkx_graph()
net = Network(notebook=True, cdn_resources="in_line", directed=True)
net.from_nx(g)

# 設定節點和邊的屬性:顏色和大小
for node in net.nodes:
    node['color'] = 'lightgray'
    node['size'] = 10
for edge in net.edges:
    edge['color'] = 'black'
    edge['width'] = 1

# 將圖譜儲存為HTML檔案
fgraph = "Knowledge_graph_" + graph_name + ".html"
net.write_html(fgraph)
print(fgraph)

顯示圖譜於Notebook

from IPython.display import HTML

# 載入HTML內容並顯示
with open(fgraph, 'r') as file:
    html_content = file.read()

# 在Notebook中顯示HTML
display(HTML(html_content))

現在,您可以下載該檔案並在瀏覽器中顯示它,以與圖譜互動。您也可以在Notebook中視覺化它,如下圖所示:

此圖顯示了知識圖譜的視覺化結果。

與知識圖譜索引互動

現在,我們已經建立了知識圖譜索引並設定了查詢引擎,可以開始與它互動了。

#### 內容解密:

上述程式碼建立了一個知識圖譜索引並設定了查詢引擎。KnowledgeGraphIndex類別用於建立索引,而as_query_engine方法用於建立查詢引擎。查詢引擎的引數(如相似度前k個結果、溫度和輸出最大token數)被設定為控制查詢引擎的行為。圖譜使用pyvis.network函式庫進行視覺化,並儲存為HTML檔案以供互動式檢視。

與知識圖譜互動的下一步

在接下來的章節中,我們將探討如何與知識圖譜索引互動,包括執行查詢、評估結果和分析回應。這將有助於我們更好地理解知識圖譜索引的功能和應用。

查詢執行與相似度計算功能的實作

在前面的章節中,我們已經定義了執行查詢所需的函式,接下來我們將詳細闡述其實作細節。查詢功能的實作類別似於第三章中Pipeline3:根據索引的RAG部分。

執行查詢功能的實作

execute_query 是我們建立的用於執行查詢的函式。它不僅執行查詢,還測量查詢執行所需的時間。

user_query = "What is the primary goal of marketing for the consumer market?"
response = execute_query(user_query)

上述程式碼執行查詢並顯示回應結果。輸出結果提供了由Wikipedia資料建立的最佳向量,並附帶時間測量結果:

Query execution time: 2.4789 seconds
The primary goal of marketing for the consumer market is to effectively...

安裝相似度評分包並定義相似度計算函式

首先,我們需要從Google Colab的Secrets標籤中檢索Hugging Face令牌,該令牌在筆記本的設定中被儲存:

from google.colab import userdata
userdata.get('HF_TOKEN')

截至2024年8月,Hugging Face的sentence-transformers令牌是可選的。因此,我們可以忽略相關提示並註解掉該程式碼。接下來,我們安裝sentence-transformers

!pip install sentence-transformers==3.0.1

然後,我們使用嵌入向量建立一個餘弦相似度函式:

from sklearn.metrics.pairwise import cosine_similarity
from sentence_transformers import SentenceTransformer

model = SentenceTransformer('all-MiniLM-L6-v2')

def calculate_cosine_similarity_with_embeddings(text1, text2):
    embeddings1 = model.encode(text1)
    embeddings2 = model.encode(text2)
    similarity = cosine_similarity([embeddings1], [embeddings2])
    return similarity[0][0]

內容解密:

  • SentenceTransformer 模型用於將文字轉換為嵌入向量。
  • cosine_similarity 函式計算兩個嵌入向量之間的餘弦相似度。
  • calculate_cosine_similarity_with_embeddings 函式封裝了上述過程,用於計算兩個文字之間的相似度。

匯入必要的函式庫

import time
import textwrap
import sys
import io

這些函式庫用於時間測量、文字處理等。

重新排序(Re-ranking)

在本文中,程式透過重新排序查詢結果來選擇可能更好的結果:

user_query = "Which experts are often associated with marketing theory?"
start_time = time.time()
response = execute_query(user_query)
end_time = time.time()

遍歷查詢結果中的所有節點,並計算使用者查詢與節點文字之間的相似度評分:

for idx, node_with_score in enumerate(response.source_nodes):
    similarity_score3 = calculate_cosine_similarity_with_embeddings(text1, text2)
    # 顯示所有比較結果
    best_score = similarity_score3
    print(textwrap.fill(str(best_text), 100))  # 顯示最佳重新排序結果

內容解密:

  • response.source_nodes 包含查詢結果中的所有節點。
  • calculate_cosine_similarity_with_embeddings 用於計算相似度評分。
  • textwrap.fill 用於格式化輸出文字。

初始查詢結果可能如下:

Psychologists, cultural anthropologists, and market researchers are often associated with marketing theory.

經過重新排序後,結果可能包含更多具體的專家名稱:

Best Rank: 2
Best Score: 0.5217772722244263
[...In 1380 the German textile manufacturer Johann Fugger...]

內容解密:

  • 重新排序後的結果可能包含更詳細的內容,但也可能包含原始檔案的原始內容,而非摘要。
  • 原始查詢引擎的結果可能更簡潔,但重新排序後的結果可能提供更多上下文資訊。

示例指標(Example Metrics)

為了評估知識圖譜索引的查詢引擎,我們將執行十個示例並跟蹤評分結果。rscores 用於跟蹤人類反饋評分,而 scores 用於跟蹤相似度函式評分:

rscores = []
scores = []

每個示例的結構相同:執行查詢、測量時間、計算相似度評分並取得人類反饋評分:

user_query = "Which experts are often associated with marketing theory?"
elapsed_time = time.time() - start_time
response = execute_query(user_query)
text1 = str(response)
text2 = user_query
similarity_score3 = calculate_cosine_similarity_with_embeddings(text1, text2)
scores.append(similarity_score3)
human_feedback = 0.75
rscores.append(human_feedback)

內容解密:

  • text1 是查詢引擎的回應結果。
  • text2 是使用者查詢。
  • similarity_score3 是計算出的餘弦相似度評分。
  • human_feedback 是人類評估的相似度評分,可以替換為檔案或人類文字回應。

輸出結果示例:

Example 1:
User query: Which experts are often associated with marketing theory?
Response: Psychologists, cultural anthropologists, and other experts in behavioral sciences are often associated with marketing theory.
Cosine similarity score: 0.809
Human feedback: 0.75
Comment: The response is acceptable, but it could be more specific and mention the names of experts.

內容解密:

  • 評分結果可能因LLM的隨機性而有所不同。
  • 人類反饋評分可以用於調整模型的效能。

圖表翻譯:

此圖示描述了查詢執行與相似度計算的流程,包括查詢執行、相似度計算和重新排序等步驟。 圖表翻譯:

  • 查詢執行:使用 execute_query 函式執行使用者查詢。
  • 相似度計算:使用 calculate_cosine_similarity_with_embeddings 函式計算查詢結果與使用者查詢之間的相似度。
  • 重新排序:根據相似度評分對查詢結果進行重新排序,以選擇最佳結果。

透過這個流程,我們可以有效地評估和最佳化查詢引擎的效能。

利用維基百科API與LlamaIndex建構可擴充套件的知識圖譜RAG系統

前言

隨著資料量的爆炸性增長,如何有效地收集、整理和查詢大規模資料成為一個重要的課題。本篇文章將介紹如何利用維基百科API和LlamaIndex建構一個可擴充套件的知識圖譜RAG(Retrieval-Augmented Generation)系統,用於高效地檢索和生成相關資訊。

管道1:資料收集

在管道1中,我們將重點放在自動化檢索維基百科內容上。利用維基百科API,我們開發了一個程式來收集與特定主題相關的後設資料和URL。以下是資料收集的程式碼範例:

import wikipedia

def collect_wikipedia_data(topic):
    wikipedia.set_lang("en")
    search_results = wikipedia.search(topic)
    pages = []
    for result in search_results:
        try:
            page = wikipedia.page(result)
            pages.append({
                'title': page.title,
                'url': page.url,
                'content': page.content
            })
        except wikipedia.exceptions.DisambiguationError:
            continue
    return pages

# 收集與行銷相關的維基百科資料
marketing_data = collect_wikipedia_data("Marketing")

內容解密:

這段程式碼首先匯入了wikipedia函式庫,並定義了一個函式collect_wikipedia_data來收集與特定主題相關的維基百科頁面資料。它使用wikipedia.search方法來搜尋相關主題的頁面,並提取每個頁面的標題、URL和內容。

管道2:建立Deep Lake向量儲存

在管道2中,我們建立並填充了Deep Lake向量儲存。從管道1檢索到的資料被嵌入並上傳到Deep Lake向量儲存中。以下是建立Deep Lake向量儲存的程式碼範例:

import numpy as np
from deeplake import VectorStore

def create_deep_lake_vector_store(data):
    vector_store = VectorStore("marketing_data")
    embeddings = []
    for item in data:
        # 假設我們使用某種方法將文字轉換為嵌入向量
        embedding = np.random.rand(128)  # 示例嵌入向量
        embeddings.append(embedding)
    vector_store.add(embeddings, data)
    return vector_store

# 使用收集到的行銷資料建立Deep Lake向量儲存
deep_lake_store = create_deep_lake_vector_store(marketing_data)

內容解密:

這段程式碼定義了一個函式create_deep_lake_vector_store,用於將資料嵌入並儲存到Deep Lake向量儲存中。為了簡化範例,我們使用了隨機生成的嵌入向量。在實際應用中,您需要使用適當的嵌入模型來生成文字的嵌入表示。

管道3:根據知識圖譜索引的RAG

在管道3中,我們引入了根據知識圖譜索引的RAG系統。利用LlamaIndex,我們自動建立了知識圖譜索引,並使用內建的語言模型來查詢和生成最優回應。以下是建立知識圖譜索引和查詢的程式碼範例:

from llama_index import KnowledgeGraphIndex

def create_knowledge_graph_index(data):
    index = KnowledgeGraphIndex(data)
    return index

def query_knowledge_graph(index, query):
    response = index.query(query)
    return response

# 使用收集到的行銷資料建立知識圖譜索引
knowledge_graph_index = create_knowledge_graph_index(marketing_data)

# 查詢知識圖譜
query_result = query_knowledge_graph(knowledge_graph_index, "What is the difference between B2B and B2C?")

內容解密:

這段程式碼展示瞭如何使用LlamaIndex建立知識圖譜索引並進行查詢。create_knowledge_graph_index函式建立了知識圖譜索引,而query_knowledge_graph函式則用於查詢索引以獲得相關資訊。

效能評估

為了評估系統的效能,我們使用了餘弦相似度分數和人工反饋分數來衡量查詢結果的準確性和相關性。以下是評估指標的計算範例:

import numpy as np

# 假設scores和rscores分別為餘弦相似度分數和人工反饋分數
scores = [0.808918, 0.720165, 0.7599532, 0.8513956, 0.5457667, 0.696391]
rscores = [0.75, 0.5, 0.8, 0.9, 0.65, 0.8]

mean_score = np.mean(scores)
median_score = np.median(scores)
std_deviation = np.std(scores)

print("Mean Score:", mean_score)
print("Median Score:", median_score)
print("Standard Deviation:", std_deviation)

內容解密:

這段程式碼計算了餘弦相似度分數的平均值、中位數和標準差,以評估系統的效能。這些指標有助於瞭解系統的整體表現和查詢結果的一致性。

隨著人工智慧和大資料技術的不斷進步,知識圖譜RAG系統將在資訊檢索、自然語言處理和智慧推薦等領域發揮越來越重要的作用。未來,我們可以探索將該系統與其他技術(如圖神經網路和強化學習)相結合,以進一步提升其效能和應用範圍。

附錄:Mermaid圖表示例

  graph LR
    A[資料收集] --> B[建立向量儲存]
    B --> C[建立知識圖譜索引]
    C --> D[查詢和生成]
    D --> E[效能評估]

圖表翻譯: 此圖示展示了建構知識圖譜RAG系統的主要流程,包括資料收集、建立向量儲存、建立知識圖譜索引、查詢和生成以及效能評估等步驟。

結語

透過本篇文章的介紹,我們瞭解瞭如何利用維基百科API和LlamaIndex建構一個可擴充套件的知識圖譜RAG系統。該系統具有廣泛的應用前景,能夠為各個領域提供高效、準確的資訊檢索和生成服務。希望本篇文章能夠為相關領域的研究人員和開發者提供有價值的參考和啟發。