1. Giới thiệu
RAG là gì
Thế hệ tăng cường truy xuất (RAG) là một kỹ thuật kết hợp sức mạnh của các mô hình ngôn ngữ lớn (LLM) với khả năng truy xuất thông tin có liên quan từ các nguồn kiến thức bên ngoài. Điều này nghĩa là một LLM không chỉ dựa vào dữ liệu đào tạo nội bộ mà còn có thể truy cập và kết hợp thông tin cụ thể, mới nhất khi tạo câu trả lời.
RAG ngày càng trở nên phổ biến vì một số lý do:
- Tăng độ chính xác và mức độ liên quan: RAG cho phép các LLM cung cấp câu trả lời chính xác và phù hợp hơn bằng cách dựa vào thông tin thực tế được lấy từ các nguồn bên ngoài. Điều này đặc biệt hữu ích trong những tình huống yêu cầu phải cập nhật kiến thức mới nhất, chẳng hạn như trả lời câu hỏi về các sự kiện hiện tại hoặc cung cấp thông tin về các chủ đề cụ thể.
- Giảm sự ảo tưởng: Đôi khi, các LLM có thể tạo ra những câu trả lời có vẻ hợp lý nhưng thực ra lại không chính xác hoặc vô nghĩa. RAG giúp giảm thiểu vấn đề này bằng cách xác minh thông tin được tạo dựa trên các nguồn bên ngoài.
- Khả năng thích ứng cao hơn: RAG giúp các LLM thích ứng nhiều hơn với nhiều miền và nhiệm vụ. Bằng cách sử dụng nhiều nguồn kiến thức, bạn có thể dễ dàng tuỳ chỉnh một LLM (mô hình ngôn ngữ lớn) để cung cấp thông tin về nhiều chủ đề.
- Nâng cao trải nghiệm người dùng: RAG có thể cải thiện trải nghiệm tổng thể của người dùng bằng cách cung cấp các câu trả lời phù hợp, đáng tin cậy và chứa nhiều thông tin hơn.
Lý do nên tạo nhiều mô-đun
Trong thế giới phong phú dữ liệu ngày nay, các tài liệu thường kết hợp văn bản và hình ảnh để truyền đạt thông tin một cách toàn diện. Tuy nhiên, hầu hết các hệ thống Thế hệ tăng cường truy xuất (RAG) đều bỏ qua những thông tin chi tiết có giá trị nằm trong hình ảnh. Khi các Mô hình ngôn ngữ lớn đa phương thức (LLM) trở nên nổi bật, việc khám phá cách chúng ta có thể tận dụng nội dung hình ảnh cùng với văn bản trong RAG là rất quan trọng để hiểu rõ hơn về bối cảnh thông tin.
Hai lựa chọn cho RAG đa phương thức
- Nhúng đa phương thức – Mô hình nhúng đa phương thức tạo ra 1408 vectơ chiều* dựa trên dữ liệu đầu vào mà bạn cung cấp, vectơ này có thể bao gồm tổ hợp dữ liệu hình ảnh, văn bản và video. Vectơ nhúng ảnh và vectơ nhúng văn bản nằm trong cùng không gian ngữ nghĩa có cùng chiều. Do đó, các vectơ này có thể được dùng thay thế cho nhau cho các trường hợp sử dụng như tìm kiếm theo hình ảnh hoặc tìm kiếm trong video theo hình ảnh. Xem Bản minh hoạ này.
- Dùng tính năng nhúng nhiều phương thức để nhúng văn bản và hình ảnh
- Truy xuất cả hai bằng cách sử dụng tính năng tìm kiếm điểm tương đồng
- Truyền cả hình ảnh thô và các đoạn văn bản được truy xuất tới LLM đa phương thức để tổng hợp câu trả lời
- Nhúng văn bản -
- Sử dụng LLM đa phương thức để tạo bản tóm tắt hình ảnh bằng văn bản
- Đã nhúng và truy xuất văn bản
- Truyền đoạn văn bản tới LLM để tổng hợp câu trả lời
Multi-Vector Retriever là gì
Việc truy xuất nhiều vectơ sử dụng thông tin tóm tắt của các phần tài liệu để truy xuất nội dung gốc nhằm tổng hợp câu trả lời. Cải thiện chất lượng của RAG, đặc biệt đối với bảng, đồ thị, biểu đồ, v.v. cho các công việc chuyên sâu. Tìm hiểu thêm thông tin chi tiết tại blog của Langchain.
Sản phẩm bạn sẽ tạo ra
Trường hợp sử dụng: Phát triển hệ thống trả lời câu hỏi bằng Gemini Pro
Hãy tưởng tượng bạn có các tài liệu chứa đựng đồ thị hoặc sơ đồ phức tạp chứa đựng thông tin. Bạn muốn trích xuất dữ liệu này để trả lời câu hỏi hoặc truy vấn.
Trong lớp học lập trình này, bạn sẽ thực hiện các nội dung sau:
- Tải dữ liệu bằng LangChain
document_loaders
- Tạo bản tóm tắt bằng văn bản bằng mô hình
gemini-pro
của Google - Tạo bản tóm tắt hình ảnh bằng mô hình
gemini-pro-vision
của Google - Tạo truy xuất nhiều vectơ bằng cách sử dụng mô hình
textembedding-gecko
của Google với Croma Db làm kho lưu trữ vectơ - Phát triển chuỗi RAG đa phương thức để trả lời câu hỏi
2. Trước khi bắt đầu
- Trong Google Cloud Console, trên trang bộ chọn dự án, hãy chọn hoặc tạo một dự án trên Google Cloud.
- Nhớ bật tính năng thanh toán cho dự án Google Cloud của bạn. Tìm hiểu cách kiểm tra xem tính năng thanh toán có được bật trên một dự án hay không.
- Bật tất cả API được đề xuất trên trang tổng quan Vertex AI
- Mở Colab Notebook rồi đăng nhập vào cùng một tài khoản Google Cloud đang hoạt động.
3. Xây dựng RAG nhiều mô-đun
Lớp học lập trình này sử dụng Vertex AI SDK cho Python và Langchain để minh hoạ cách triển khai "Option 2" (Lựa chọn 2) được mô tả tại đây bằng Google Cloud.
Bạn có thể tham khảo mã đầy đủ trong tệp RAG đa phương thức trên Google Cloud trên kho lưu trữ được tham chiếu.
4. Bước 1: Cài đặt và nhập phần phụ thuộc
!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
Nhập mã dự án và hoàn tất quy trình xác thực
#TODO : ENter project and location
PROJECT_ID = ""
REGION = "us-central1"
from google.colab import auth
auth.authenticate_user()
Khởi chạy nền tảng Vertex AI
import vertexai
vertexai.init(project = PROJECT_ID , location = REGION)
5. Bước 2: Chuẩn bị và tải dữ liệu
Chúng tôi sử dụng tệp zip có tập hợp con gồm các hình ảnh và tệp pdf được trích xuất từ bài đăng này trên blog. Nếu bạn muốn theo dõi toàn bộ quy trình, vui lòng sử dụng ví dụ gốc.
Trước tiên, hãy tải dữ liệu xuống
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()
Tải nội dung văn bản từ tài liệu
from langchain_community.document_loaders import PyPDFLoader
loader = PyPDFLoader("./cj/cj.pdf")
docs = loader.load()
tables = []
texts = [d.page_content for d in docs]
Kiểm tra nội dung từ trang đầu tiên
texts[0]
Bạn sẽ thấy kết quả
Tổng số trang trong tài liệu
len(texts)
Kết quả đầu ra dự kiến là
6. Bước 3: Tạo nội dung tóm tắt bằng văn bản
Trước tiên, hãy nhập các thư viện cần thiết
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
Nhận nội dung tóm tắt bằng văn bản
# 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]
Kết quả đầu ra dự kiến là
7. Bước 4: Tạo bản tóm tắt hình ảnh
Trước tiên, hãy nhập các thư viện cần thiết
import base64
import os
from langchain_core.messages import HumanMessage
Tạo bản tóm tắt bằng hình ảnh
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]
Bạn sẽ thấy kết quả như sau
8. Bước 5: Tạo truy xuất nhiều vectơ
Hãy tạo bản tóm tắt dạng văn bản và hình ảnh rồi lưu vào kho vectơ ChromaDB.
Nhập cần có thư viện
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
Tạo truy xuất nhiều vectơ
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. Bước 6: Xây dựng RAG nhiều mô-đun
- Xác định các hàm hiệu dụng
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}
- Xác định lời nhắc bằng hình ảnh theo miền cụ thể
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)]
- Xác định chuỗi RAG nhiều mô-đun
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. Bước 7: Kiểm tra truy vấn
- Truy xuất tài liệu liên quan
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
plt_img_base64(docs[3])
- Chạy RAG của chúng tôi trên cùng một truy vấn
result = chain_multimodal_rag.invoke(query)
from IPython.display import Markdown as md
md(result)
Kết quả mẫu (có thể thay đổi khi bạn thực thi mã)
11. Dọn dẹp
Để tránh bị tính phí vào tài khoản Google Cloud cho những tài nguyên sử dụng trong lớp học lập trình này, hãy làm theo các bước sau:
- Trong bảng điều khiển Google Cloud, hãy chuyển đến trang Quản lý tài nguyên.
- Trong danh sách dự án, hãy chọn dự án mà bạn muốn xoá, sau đó nhấp vào Delete (Xoá).
- Trong hộp thoại, hãy nhập mã dự án rồi nhấp vào Tắt để xoá dự án.
12. Xin chúc mừng
Xin chúc mừng! Bạn đã phát triển thành công RAG nhiều mô-đun bằng Gemini.