使用 Gemini Pro 建構含有多模型 RAG 的問答應用程式

1. 簡介

什麼是 RAG

「檢索增強生成 (RAG)」是一種技術,結合大型語言模型 (LLM) 的強大功能,以及從外部知識來源擷取相關資訊的能力。這表示 LLM 不只是仰賴內部訓練資料,還能在生成回覆時存取及整合最新的特定資訊。

936b7eedba773cac.png

RAG 人氣上升的原因如下:

  • 提高準確度和關聯性:RAG 能根據從外部來源擷取的事實資訊,為 LLM 提供關聯性更高的回覆,提供更準確且相關的回覆。以掌握最新資訊時特別實用,例如回答時事相關問題或提供特定主題相關資訊等。
  • 減少幻覺:LLM 有時可能會生成看似合理,但實際上不正確或無意義的回覆。RAG 會驗證根據外部來源產生的資訊,協助緩解這個問題。
  • 適應性較高:RAG 能根據不同的領域和任務,調整 LLM。藉助不同的知識來源,您可以輕鬆自訂 LLM,提供涵蓋各種主題的資訊。
  • 改善使用者體驗:RAG 可透過提供更豐富、可靠且相關的回應,改善整體使用者體驗。

多模態的理由

當今資料充足的時代,文件通常會結合文字和圖片,提供最完整的資訊。不過,大多數檢索增強生成 (RAG) 系統忽略了影像中鎖定的寶貴洞察。多模態大型語言模型 (LLM) 越來越引人注目,因此請務必探索如何運用視覺內容搭配 RAG 的文字,深入瞭解資訊環境。

多模態 RAG 的兩種選項

  • 多模態嵌入:多模態嵌入模型會根據您提供的輸入內容產生 1408 維度向量*,包括圖片、文字和影片資料的組合。圖片嵌入向量和文字嵌入向量位於相同的語意空間,但具有相同維度。因此,這些向量可以交替用於各種用途,例如按文字搜尋圖片或是以圖片搜尋影片。請觀看這個示範
  1. 使用多模態嵌入功能嵌入文字和圖片
  2. 使用相似度搜尋擷取兩者
  3. 將擷取的原始圖片和文字區塊傳遞至多模態 LLM 來生成合成內容
  • 文字嵌入 -
  1. 使用多模態大型語言模型,生成圖片的文字摘要
  2. 嵌入及擷取文字
  3. 將文字 Bucks 傳遞至 LLM 來合成答案

什麼是 Multi-Vector Retriever

多媒介擷取會運用文件區段的摘要來擷取原創內容,以便進行合成。能提升 RAG 的品質,尤其是在需要處理大量工作的資料表、圖形、圖表等內容時。詳情請參閱 Langchain 的網誌.

建構項目

用途:使用 Gemini Pro 開發問題回答系統

假設您有文件內含複雜的圖形或圖表,而且上面有各種資訊。您想擷取這項資料來回答問題或查詢。

在本程式碼研究室中,您將執行以下操作:

  • 使用 LangChain document_loaders 載入資料
  • 使用 Google 的 gemini-pro 模型產生文字摘要
  • 使用 Google 的 gemini-pro-vision 模型產生圖片摘要
  • 使用 Google 的 textembedding-gecko 模型搭配 Croma DBM 做為向量儲存庫,建立多向量擷取內容
  • 開發多模態 RAG 鏈結以便回答問題

2. 事前準備

  1. Google Cloud 控制台的專案選取器頁面中,選取或建立 Google Cloud 專案
  2. 確認 Google Cloud 專案已啟用計費功能。瞭解如何檢查專案是否已啟用帳單功能
  3. 在 Vertex AI 資訊主頁中啟用所有建議的 API
  4. 開啟 Colab 筆記本,然後登入目前使用的 Google Cloud 帳戶。

3. Building Multi-Modal RAG (建構多模態 RAG)

本程式碼研究室會使用 Python 適用的 Vertex AI SDKLangchain 來示範如何使用 Google Cloud 實作「選項 2」。

您可以從參照的存放區中參閱「Multi-modal RAG with Google Cloud」檔案中的完整程式碼。

4. 步驟 1:安裝及匯入依附元件

!pip install -U --quiet langchain langchain_community chromadb  langchain-google-vertexai
!pip install --quiet "unstructured[all-docs]" pypdf pillow pydantic lxml pillow matplotlib chromadb tiktoken

輸入專案 ID 並完成驗證程序

#TODO : ENter project and location
PROJECT_ID = ""
REGION = "us-central1"

from google.colab import auth
auth.authenticate_user()

初始化 Vertex AI 平台

import vertexai
vertexai.init(project = PROJECT_ID , location = REGION)

5. 步驟 2:準備及載入資料

請參閱這篇文章,使用 ZIP 檔案,其中含有擷取的圖片和 PDF 檔子集。如果您想按照完整流程操作,請使用原本的範例

先下載資料

import logging
import zipfile
import requests

logging.basicConfig(level=logging.INFO)

data_url = "https://storage.googleapis.com/benchmarks-artifacts/langchain-docs-benchmarking/cj.zip"
result = requests.get(data_url)
filename = "cj.zip"
with open(filename, "wb") as file:
   file.write(result.content)

with zipfile.ZipFile(filename, "r") as zip_ref:
   zip_ref.extractall()

載入文件中的文字內容

from langchain_community.document_loaders import PyPDFLoader

loader = PyPDFLoader("./cj/cj.pdf")
docs = loader.load()
tables = []
texts = [d.page_content for d in docs]

檢查第一頁的內容

texts[0]

您應該會看到輸出內容

2c5c257779c0f52a.png

文件中的頁數

len(texts)

預期的輸出內容為

b5700c0c1376abc2.png

6. 步驟 3:產生文字摘要

請先匯入必要的程式庫

from langchain_google_vertexai import VertexAI , ChatVertexAI , VertexAIEmbeddings
from langchain.prompts import PromptTemplate
from langchain_core.messages import AIMessage
from langchain_core.output_parsers import StrOutputParser
from langchain_core.runnables import RunnableLambda

取得文字摘要

# Generate summaries of text elements
def generate_text_summaries(texts, tables, summarize_texts=False):
   """
   Summarize text elements
   texts: List of str
   tables: List of str
   summarize_texts: Bool to summarize texts
   """

   # Prompt
   prompt_text = """You are an assistant tasked with summarizing tables and text for retrieval. \
   These summaries will be embedded and used to retrieve the raw text or table elements. \
   Give a concise summary of the table or text that is well optimized for retrieval. Table or text: {element} """
   prompt = PromptTemplate.from_template(prompt_text)
   empty_response = RunnableLambda(
       lambda x: AIMessage(content="Error processing document")
   )
   # Text summary chain
   model = VertexAI(
       temperature=0, model_name="gemini-pro", max_output_tokens=1024
   ).with_fallbacks([empty_response])
   summarize_chain = {"element": lambda x: x} | prompt | model | StrOutputParser()

   # Initialize empty summaries
   text_summaries = []
   table_summaries = []

   # Apply to text if texts are provided and summarization is requested
   if texts and summarize_texts:
       text_summaries = summarize_chain.batch(texts, {"max_concurrency": 1})
   elif texts:
       text_summaries = texts

   # Apply to tables if tables are provided
   if tables:
       table_summaries = summarize_chain.batch(tables, {"max_concurrency": 1})

   return text_summaries, table_summaries


# Get text summaries
text_summaries, table_summaries = generate_text_summaries(
   texts, tables, summarize_texts=True
)

text_summaries[0]

預期的輸出內容為

aa76e4b523d8a958.png

7. 步驟 4:產生圖片摘要

請先匯入必要的程式庫

import base64
import os

from langchain_core.messages import HumanMessage

產生圖片摘要

def encode_image(image_path):
   """Getting the base64 string"""
   with open(image_path, "rb") as image_file:
       return base64.b64encode(image_file.read()).decode("utf-8")


def image_summarize(img_base64, prompt):
   """Make image summary"""
   model = ChatVertexAI(model_name="gemini-pro-vision", max_output_tokens=1024)

   msg = model(
       [
           HumanMessage(
               content=[
                   {"type": "text", "text": prompt},
                   {
                       "type": "image_url",
                       "image_url": {"url": f"data:image/jpeg;base64,{img_base64}"},
                   },
               ]
           )
       ]
   )
   return msg.content


def generate_img_summaries(path):
   """
   Generate summaries and base64 encoded strings for images
   path: Path to list of .jpg files extracted by Unstructured
   """

   # Store base64 encoded images
   img_base64_list = []

   # Store image summaries
   image_summaries = []

   # Prompt
   prompt = """You are an assistant tasked with summarizing images for retrieval. \
   These summaries will be embedded and used to retrieve the raw image. \
   Give a concise summary of the image that is well optimized for retrieval."""

   # Apply to images
   for img_file in sorted(os.listdir(path)):
       if img_file.endswith(".jpg"):
           img_path = os.path.join(path, img_file)
           base64_image = encode_image(img_path)
           img_base64_list.append(base64_image)
           image_summaries.append(image_summarize(base64_image, prompt))

   return img_base64_list, image_summaries


# Image summaries
img_base64_list, image_summaries = generate_img_summaries("./cj")

len(img_base64_list)

len(image_summaries)

image_summaries[0]

您應該會看到類似 fad6d479dd46cb37.png 的輸出內容

8. 步驟 5:建構多媒介擷取

我們要產生文字和圖片摘要,並將其儲存至 ChromaDB 向量商店。

匯入作業需要使用程式庫

import uuid
from langchain.retrievers.multi_vector import MultiVectorRetriever
from langchain.storage import InMemoryStore
from langchain_community.vectorstores import Chroma
from langchain_core.documents import Document

建立多媒介擷取

def create_multi_vector_retriever(
   vectorstore, text_summaries, texts, table_summaries, tables, image_summaries, images
):
   """
   Create retriever that indexes summaries, but returns raw images or texts
   """

   # Initialize the storage layer
   store = InMemoryStore()
   id_key = "doc_id"

   # Create the multi-vector retriever
   retriever = MultiVectorRetriever(
       vectorstore=vectorstore,
       docstore=store,
       id_key=id_key,
   )

   # Helper function to add documents to the vectorstore and docstore
   def add_documents(retriever, doc_summaries, doc_contents):
       doc_ids = [str(uuid.uuid4()) for _ in doc_contents]
       summary_docs = [
           Document(page_content=s, metadata={id_key: doc_ids[i]})
           for i, s in enumerate(doc_summaries)
       ]
       retriever.vectorstore.add_documents(summary_docs)
       retriever.docstore.mset(list(zip(doc_ids, doc_contents)))

   # Add texts, tables, and images
   # Check that text_summaries is not empty before adding
   if text_summaries:
       add_documents(retriever, text_summaries, texts)
   # Check that table_summaries is not empty before adding
   if table_summaries:
       add_documents(retriever, table_summaries, tables)
   # Check that image_summaries is not empty before adding
   if image_summaries:
       add_documents(retriever, image_summaries, images)

   return retriever


# The vectorstore to use to index the summaries
vectorstore = Chroma(
   collection_name="mm_rag_cj_blog",
   embedding_function=VertexAIEmbeddings(model_name="textembedding-gecko@latest"),
)

# Create retriever
retriever_multi_vector_img = create_multi_vector_retriever(
   vectorstore,
   text_summaries,
   texts,
   table_summaries,
   tables,
   image_summaries,
   img_base64_list,
)
 

9. 步驟 6:建構多模型 RAG

  1. 定義公用程式函式
import io
import re

from IPython.display import HTML, display
from langchain_core.runnables import RunnableLambda, RunnablePassthrough
from PIL import Image


def plt_img_base64(img_base64):
   """Disply base64 encoded string as image"""
   # Create an HTML img tag with the base64 string as the source
   image_html = f'<img src="data:image/jpeg;base64,{img_base64}" />'
   # Display the image by rendering the HTML
   display(HTML(image_html))


def looks_like_base64(sb):
   """Check if the string looks like base64"""
   return re.match("^[A-Za-z0-9+/]+[=]{0,2}$", sb) is not None


def is_image_data(b64data):
   """
   Check if the base64 data is an image by looking at the start of the data
   """
   image_signatures = {
       b"\xFF\xD8\xFF": "jpg",
       b"\x89\x50\x4E\x47\x0D\x0A\x1A\x0A": "png",
       b"\x47\x49\x46\x38": "gif",
       b"\x52\x49\x46\x46": "webp",
   }
   try:
       header = base64.b64decode(b64data)[:8]  # Decode and get the first 8 bytes
       for sig, format in image_signatures.items():
           if header.startswith(sig):
               return True
       return False
   except Exception:
       return False


def resize_base64_image(base64_string, size=(128, 128)):
   """
   Resize an image encoded as a Base64 string
   """
   # Decode the Base64 string
   img_data = base64.b64decode(base64_string)
   img = Image.open(io.BytesIO(img_data))

   # Resize the image
   resized_img = img.resize(size, Image.LANCZOS)

   # Save the resized image to a bytes buffer
   buffered = io.BytesIO()
   resized_img.save(buffered, format=img.format)

   # Encode the resized image to Base64
   return base64.b64encode(buffered.getvalue()).decode("utf-8")


def split_image_text_types(docs):
   """
   Split base64-encoded images and texts
   """
   b64_images = []
   texts = []
   for doc in docs:
       # Check if the document is of type Document and extract page_content if so
       if isinstance(doc, Document):
           doc = doc.page_content
       if looks_like_base64(doc) and is_image_data(doc):
           doc = resize_base64_image(doc, size=(1300, 600))
           b64_images.append(doc)
       else:
           texts.append(doc)
   if len(b64_images) > 0:
       return {"images": b64_images[:1], "texts": []}
   return {"images": b64_images, "texts": texts}
  1. 定義特定網域的圖片提示
def img_prompt_func(data_dict):
   """
   Join the context into a single string
   """
   formatted_texts = "\n".join(data_dict["context"]["texts"])
   messages = []

   # Adding the text for analysis
   text_message = {
       "type": "text",
       "text": (
           "You are financial analyst tasking with providing investment advice.\n"
           "You will be given a mixed of text, tables, and image(s) usually of charts or graphs.\n"
           "Use this information to provide investment advice related to the user question. \n"
           f"User-provided question: {data_dict['question']}\n\n"
           "Text and / or tables:\n"
           f"{formatted_texts}"
       ),
   }
   messages.append(text_message)
   # Adding image(s) to the messages if present
   if data_dict["context"]["images"]:
       for image in data_dict["context"]["images"]:
           image_message = {
               "type": "image_url",
               "image_url": {"url": f"data:image/jpeg;base64,{image}"},
           }
           messages.append(image_message)
   return [HumanMessage(content=messages)]

  1. 定義多模型 RAG 鏈
def multi_modal_rag_chain(retriever):
   """
   Multi-modal RAG chain
   """

   # Multi-modal LLM
   model = ChatVertexAI(
       temperature=0, model_name="gemini-pro-vision", max_output_tokens=1024
   )

   # RAG pipeline
   chain = (
       {
           "context": retriever | RunnableLambda(split_image_text_types),
           "question": RunnablePassthrough(),
       }
       | RunnableLambda(img_prompt_func)
       | model
       | StrOutputParser()
   )

   return chain


# Create RAG chain
chain_multimodal_rag = multi_modal_rag_chain(retriever_multi_vector_img)

10. 步驟 7:測試查詢

  1. 擷取相關文件
query = "What are the EV / NTM and NTM rev growth for MongoDB, Cloudflare, and Datadog?"
docs = retriever_multi_vector_img.get_relevant_documents(query, limit=1)

# We get relevant docs
len(docs)

docs
         You may get similar output 

(74ecaca749ae459a.png)

plt_img_base64(docs[3])

989ad388127f5d60.png

  1. 對相同查詢執行 RAG
result = chain_multimodal_rag.invoke(query)

from IPython.display import Markdown as md
md(result)

輸出內容範例 (執行程式碼時可能會改變)

e5e102eaf10289ab.png

11. 清除所用資源

如要避免系統向您的 Google Cloud 帳戶收取這個程式碼研究室所用資源的費用,請按照下列步驟操作:

  1. 在 Google Cloud 控制台中,前往「管理資源」頁面。
  2. 在專案清單中選取要刪除的專案,然後按一下「Delete」(刪除)
  3. 在對話方塊中輸入專案 ID,然後按一下「Shut down」(關閉) 即可刪除專案。

12. 恭喜

恭喜!你已成功使用 Gemini 開發多模型 RAG,