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

使用 Gemini Pro 建構採用多模態 RAG 的問答應用程式

程式碼研究室簡介

subject上次更新時間:6月 27, 2024
account_circle作者:Bhushan Garware, Aditya Rane, Leonid Kuligin

1. 簡介

什麼是 RAG

檢索增強生成 (RAG) 技術結合了大型語言模型 (LLM) 的強大功能,以及從外部知識來源擷取相關資訊的能力。也就是說,LLM 不只會依賴內部訓練資料,還能存取最新的特定資訊,並在產生回覆時納入這些資訊。

936b7eedba773cac.png

RAG 越來越受歡迎,原因如下:

  • 提升準確度和相關性:RAG 可讓 LLM 以從外部來源擷取的事實資訊為依據,提供更準確且相關的回覆。這項功能特別適合用於需要最新知識的情況,例如回答有關時事的問題,或提供特定主題的資訊。
  • 減少幻覺:大型語言模型有時會產生看似合理,但實際上不正確或毫無意義的回覆。RAG 會驗證與外部來源產生的資訊,以減輕這項問題。
  • 更高的適應性:RAG 可讓 LLM 更能適應不同的領域和工作。只要善用不同的知識來源,就能輕鬆自訂 LLM,提供各式各樣的主題資訊。
  • 提升使用者體驗:RAG 可提供更有參考價值、可靠且相關的回覆,進而改善整體使用者體驗。

為何採用多模態

在現今資料豐富的世界中,文件通常會結合文字和圖片,以全面的方式傳達資訊。不過,大多數的檢索增強生成 (RAG) 系統都忽略了圖片中隱藏的寶貴洞察資料。隨著多模態大型語言模型 (LLM) 越來越受重視,我們必須探索如何在 RAG 中運用視覺內容和文字,進一步瞭解資訊環境。

多模態 RAG 的兩種選項

  • 多模態嵌入 -多模態嵌入模型會根據您提供的輸入內容生成 1408 維向量*,其中可包含圖片、文字和影片資料的組合。圖片嵌入向量和文字嵌入向量位於相同的語意空間,且維度相同。因此,這些向量可用於以文字搜尋圖片或以圖片搜尋影片等用途。請參閱這部示範影片
  1. 使用多模態嵌入功能嵌入文字和圖片
  2. 使用相似度搜尋功能擷取兩者
  3. 將擷取的原始圖片和文字區塊傳遞至多模式 LLM,以便合成答案
  • 文字嵌入
  1. 使用多模態 LLM 產生圖像的文字摘要
  2. 嵌入及擷取文字
  3. 將文字片段傳送至 LLM 以合成答案

什麼是多媒介擷取器

多向量檢索會使用文件部分摘要,擷取原始內容來整合答案。這項功能可提升 RAG 的品質,特別適用於需要大量使用表格、圖表等的任務。詳情請參閱 Langchain 的網誌

建構項目

用例:使用 Gemini Pro 開發問答系統

假設您有包含複雜圖表或包含大量資訊的圖表的文件。您想要擷取這些資料來回答問題或查詢。

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

  • 使用 LangChain 載入資料 document_loaders
  • 使用 Google 的 gemini-pro 模型產生文字摘要
  • 使用 Google 的 gemini-pro-vision 模型產生圖片摘要
  • 使用 Google 的 textembedding-gecko 模型,並以 Croma Db 做為向量儲存空間,建立多向量擷取
  • 開發用於回答問題的多模態 RAG 鏈

2. 事前準備

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

3. 建構多模態 RAG

本程式碼實驗室使用 Vertex AI SDK for PythonLangchain,示範如何使用 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. 在專案清單中選取要刪除的專案,然後點按「刪除」。
  3. 在對話方塊中輸入專案 ID,然後按一下「Shut down」(關閉) 即可刪除專案。

12. 恭喜

恭喜!您已成功使用 Gemini 開發多模態 RAG。