Posted on

LlamaIndex介紹

主要功能

LlamaIndex 專注於將非結構化數據(如文本文件、PDF、網頁內容等)轉換為可以用於查詢和分析的結構化索引。它為用戶提供了一種簡單的方法來構建和查詢這些索引,從而更好地利用大型語言模型進行數據處理和檢索。

LlamaIndex 提供了以下功能來幫忙構建上下文增強 LLM 應用程式:

  • 數據索引和向量化:LlamaIndex 可以將非結構化數據轉換為向量表示,這對於 LLM 來說更易於處理。可以輕鬆地將自己的數據添加到 LlamaIndex 中,並讓 LLM 從中學習。
  • 數據檢索:LlamaIndex 可以根據用戶查詢快速準確地檢索相關數據。這意味著 LLM 應用程式將能夠快速找到其所需的信息,以提供準確的響應。
  • LLM 集成:LlamaIndex 可以與各種 LLM 集成,例如 GPT-3 和 Jurassic-1 Jumbo。這意味著可以選擇最適合的應用程式的 LLM。

使用教學(使用OpenAI的功能)

官方教學: https://docs.llamaindex.ai/en/latest/getting_started/starter_example/

LlamaIndex預設會使用OpenAI的Indexing功能去做文字的索引,以下為一個官方的範例,使用之前需要先安裝llama-index套件

pip install llama-index
pip install python-dotenv

接著下載數據並且放到data資料夾內,然後設定環境變數

設定環境變數的方法為到專案內新增.env檔案,並在其中設定OPENAI_API_KEY(可以到這邊申請)

OPENAI_API_KEY=xxxxxxxxxxxxxxxxxxxxxxx

接著新增一個檔案名為starter.py,內容如下:

from llama_index.core import VectorStoreIndex, SimpleDirectoryReader
import logging
import sys
import os.path
from llama_index.core import (
    VectorStoreIndex,
    SimpleDirectoryReader,
    StorageContext,
    load_index_from_storage,
)
# 載入環境變數
from dotenv import load_dotenv 
load_dotenv()

logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
logging.getLogger().addHandler(logging.StreamHandler(stream=sys.stdout))

# 假如已經有索引了,就不用再重新建立索引
PERSIST_DIR = "./storage"
if not os.path.exists(PERSIST_DIR):
    # 載入文件並建立索引
    documents = SimpleDirectoryReader("data").load_data()
    index = VectorStoreIndex.from_documents(documents)
    # 儲存索引
    index.storage_context.persist(persist_dir=PERSIST_DIR)
else:
    # 載入已存在的索引
    storage_context = StorageContext.from_defaults(persist_dir=PERSIST_DIR)
    index = load_index_from_storage(storage_context)

# 使用索引的資料詢問問題
query_engine = index.as_query_engine()
response = query_engine.query("What did the author do growing up?")
print(response)

此時文件結構應該像下面這樣子

執行之後,可以看到程式載入了data內的資料,呼叫https://api.openai.com/v1/embeddings來做詞嵌入的動作

以下是訊息中的一些重要部分:

  • connect_tcp.startedconnect_tcp.complete:表示開始和完成 TCP 連接。在這裡,連接成功建立到了 api.openai.com 的 443 端口。
  • start_tls.startedstart_tls.complete:表示開始和完成 TLS 握手過程,確保通信的安全性。
  • send_request_headers.startedsend_request_headers.complete:表示開始和完成發送請求頭的過程。
  • send_request_body.startedsend_request_body.complete:表示開始和完成發送請求主體的過程。
  • receive_response_headers.startedreceive_response_headers.complete:表示開始和完成接收響應頭的過程。響應頭中包含了一些重要的信息,如響應的 HTTP 狀態碼、內容類型、限速等。
  • INFO:httpx:HTTP Request: POST https://api.openai.com/v1/embeddings "HTTP/1.1 200 OK":表示成功發送了 HTTP POST 請求到 https://api.openai.com/v1/embeddings 並收到了 200 OK 的響應。

上面這些訊息則代表已經生成了storage資料夾,儲存詞嵌入的結果

使用索引的資料詢問問題

下面這樣簡短的程式碼可自動載入"./storage"內的嵌入檔案,並且將嵌入的檔案和詢問的問題傳送給OpenAI API的https://api.openai.com/v1/chat/completions文字生成機器人

# 載入已存在的索引
storage_context = StorageContext.from_defaults(persist_dir=PERSIST_DIR)
index = load_index_from_storage(storage_context)

# 使用索引的資料詢問問題
query_engine = index.as_query_engine()
response = query_engine.query("What did the author do growing up?")
print(response)

則可看到得到的回應如下:

The author worked on writing short stories and programming, starting with the IBM 1401 in 9th grade, using an early version of Fortran. Later, the author transitioned to microcomputers, particularly a TRS-80, where they wrote simple games, a rocket prediction program, and a word processor.

檢索增強生成 (RAG)

RAG(檢索增強生成)是一種用於構建大型語言模型 (LLM) 應用程式的架構。它由以下五個關鍵階段組成:

  1. 載入:此階段涉及將數據從其原始位置導入到您的管道中。數據可以來自各種來源,包括文檔、數據庫、API 等。Node 是 LlamaIndex 中數據的原子單位,表示文件中的“chunk”。節點具有將它們與它們所在的文件以及其他節點相關聯的元數據。連接器:資料連接器(通常稱為讀取器),可以從各種數據源和格式,例如資料庫、檔案、網路 API 等,將資料讀取到 LlamaIndex 的文件 (Documents) 和節點 (Nodes) 中。
  2. 索引:取得資料後,LlamaIndex 可以協助您將資料建立索引,變成易於檢索的結構。這通常會包含生成向量嵌入 (vector embeddings),並將它們儲存在稱為向量儲存庫 (vector store) 的特殊數據庫中。索引也可以儲存各種關於資料的元數據(metadata)。
    大型語言模型 (LLMs) 會產生稱為嵌入的資料數值表示。當您根據相關性過濾資料時,LlamaIndex 會將查詢轉換成嵌入,您的向量儲存庫會找到與查詢嵌入數值上相似的資料。
  3. 儲存:此階段涉及將索引數據存儲在持久存儲器中。這使您可以稍後查詢數據,而無需再次重新索引。LlamaIndex 提供了各種存儲選項,可幫助您選擇最適合您的需求的選項。
  4. 查詢:此階段涉及使用 LLM 對索引數據進行查詢。LlamaIndex 提供了各種查詢方法,包括子查詢、多步驟查詢和混合策略。常使用的術語包括RetrieversRoutersNode PostprocessorsResponse Synthesizers
  5. 評估:此階段涉及評估您的管道的性能。這包括測量查詢的準確性、相關性和速度。LlamaIndex 提供了各種評估工具,可幫助您微調您的管道以獲得最佳結果。

官方釋出的範例專案

https://github.com/run-llama/chat-llamaindex