Gemini Pro की मदद से, मल्टी-मोडल RAG की मदद से सवाल-जवाब वाला ऐप्लिकेशन बनाएं

1. शुरुआती जानकारी

RAG क्या है

रिकवरील ऑगमेंटेड जनरेशन (आरएजी) एक ऐसी तकनीक है जिसमें लार्ज लैंग्वेज मॉडल (एलएलएम) की क्षमता और बाहरी नॉलेज सोर्स से काम की जानकारी हासिल करने की सुविधा है. इसका मतलब है कि एलएलएम, सिर्फ़ इंटरनल ट्रेनिंग के डेटा पर निर्भर नहीं रहता. इसके अलावा, यह जवाब जनरेट करते समय, अप-टू-डेट और खास जानकारी को ऐक्सेस और शामिल भी कर सकता है.

936b7eedba773cac.png

RAG कई वजहों से लोकप्रिय हो रहा है:

  • ज़्यादा सटीक और काम का कॉन्टेंट: आरएजी की मदद से, एलएलएम को बाहरी सोर्स से तथ्यों पर आधारित जानकारी मिलती है. इससे एलएलएम को ज़्यादा सटीक और काम के जवाब मिलते हैं. यह सुविधा उन मामलों में खास तौर पर मददगार होती है जहां अप-टू-डेट जानकारी होना ज़रूरी है. जैसे, मौजूदा घटनाओं से जुड़े सवालों के जवाब देना या चुनिंदा विषयों के बारे में जानकारी देना.
  • गलत जानकारी कम करना: एलएलएम कभी-कभी ऐसे जवाब जनरेट कर सकते हैं जो भरोसेमंद लगते हैं, लेकिन असल में वे ग़लत या बेतुके होते हैं. आरएजी की मदद से बाहरी सोर्स के बारे में जनरेट हुई जानकारी की पुष्टि करके, इस समस्या को कम किया जा सकता है.
  • बेहतर तरीके से काम करने की क्षमता: आरएजी की मदद से एलएलएम, अलग-अलग डोमेन और टास्क के हिसाब से अपनाए जा सकते हैं. नॉलेज सोर्स का इस्तेमाल करके, कई तरह के विषयों पर जानकारी देने के लिए, एलएलएम को आसानी से पसंद के मुताबिक बनाया जा सकता है.
  • बेहतर उपयोगकर्ता अनुभव: RAG इस तरह के जवाब देता है जो ज़्यादा जानकारी वाले, भरोसेमंद, और काम के होते हैं. इससे उपयोगकर्ता अनुभव को बेहतर बनाया जा सकता है.

मल्टी-मोडल ही क्यों

आज-कल डेटा से भरी दुनिया में, दस्तावेज़ों में टेक्स्ट और इमेज का मिला-जुला रूप इस्तेमाल किया जाता है, ताकि उसकी पूरी जानकारी दी जा सके. हालांकि, ज़्यादातर रिकवरी ऑगमेंटेड जनरेशन (आरएजी) सिस्टम, इमेज में लॉक की गई अहम जानकारी को नज़रअंदाज़ कर देते हैं. अब मल्टी-मोडल लार्ज लैंग्वेज मॉडल (एलएलएम) को काफ़ी अहमियत मिल रही है. इसलिए, यह जानना बेहद ज़रूरी है कि आरएजी में टेक्स्ट के साथ-साथ विज़ुअल कॉन्टेंट का इस्तेमाल कैसे किया जा सकता है. इससे जानकारी को बेहतर तरीके से समझने में मदद मिलेगी.

मल्टी-मॉडल आरएजी के दो विकल्प

  • मल्टीमॉडल एम्बेडिंग - मल्टीमोडल एम्बेडिंग मॉडल, आपके दिए गए इनपुट के आधार पर 1408-डाइमेंशन वेक्टर* जनरेट करता है. इसमें इमेज, टेक्स्ट, और वीडियो डेटा का कॉम्बिनेशन शामिल हो सकता है. इमेज एम्बेड करने वाले वेक्टर और टेक्स्ट एम्बेड करने वाले वेक्टर, एक ही सिमैंटिक स्पेस में हैं और उनकी डाइमेंशन क्वालिटी एक जैसी है. ऐसे में, इन वेक्टर को टेक्स्ट के ज़रिए इमेज खोजने या इमेज के हिसाब से वीडियो खोजने जैसे मामलों में एक-दूसरे की जगह पर इस्तेमाल किया जा सकता है. इस डेमो पर एक नज़र डालें.
  1. टेक्स्ट और इमेज एम्बेड करने के लिए, मल्टी-मॉडल एम्बेडिंग का इस्तेमाल करना
  2. समानता खोजने की सुविधा का इस्तेमाल करके दोनों को वापस लाएं
  3. जवाब तैयार करने के लिए, वापस लाई गई रॉ इमेज और टेक्स्ट वाले हिस्सों को मल्टी-मॉडल एलएलएम पर पास करें
  • टेक्स्ट एम्बेड करना -
  1. इमेज के बारे में खास जानकारी वाला टेक्स्ट जनरेट करने के लिए, मल्टी-मोडल एलएलएम का इस्तेमाल करना
  2. टेक्स्ट एम्बेड करना और वापस पाना
  3. जवाब देने के लिए, टेक्स्ट चक को एलएलएम पर पास करें

मल्टी-वेक्टर रिट्रीवर क्या है

मल्टी-वेक्टर रिकवरिंग, दस्तावेज़ के सेक्शन की खास जानकारी का इस्तेमाल करके, जवाब देने के लिए ओरिजनल कॉन्टेंट का इस्तेमाल करती है. यह खास तौर पर टेबल, ग्राफ़, चार्ट वगैरह में ज़्यादा मुश्किल टास्क पूरे करने के लिए, RAG की क्वालिटी को बेहतर बनाता है. ज़्यादा जानकारी के लिए, Langchain के ब्लॉग पर जाएं.

आपको क्या बनाना होगा

इस्तेमाल का उदाहरण: Gemini Pro की मदद से सवाल-जवाब का सिस्टम डेवलप करना

मान लें कि आपके पास ऐसे दस्तावेज़ हैं जिनमें जानकारी से भरे जटिल ग्राफ़ या डायग्राम हैं. आपको सवालों या क्वेरी का जवाब देने के लिए, इस डेटा को एक्सट्रैक्ट करना है.

इस कोडलैब में, आपको ये काम करने होंगे:

  • LangChain document_loaders का इस्तेमाल करके डेटा लोड करना
  • Google के gemini-pro मॉडल का इस्तेमाल करके, टेक्स्ट की खास जानकारी जनरेट करें
  • Google के gemini-pro-vision मॉडल का इस्तेमाल करके, इमेज की खास जानकारी जनरेट करें
  • वेक्टर स्टोर के तौर पर, Croma Db की मदद से Google के textembedding-gecko मॉडल का इस्तेमाल करके, मल्टी-वेक्टर डेटा का कलेक्शन बनाएं
  • सवालों के जवाब देने के लिए, मल्टी-मोडल आरएजी चेन डेवलप करें

2. वेब कंटेनर इंस्टॉल करने से पहले

  1. Google Cloud Console में, प्रोजेक्ट सिलेक्टर पेज पर, Google Cloud प्रोजेक्ट चुनें या बनाएं.
  2. पक्का करें कि आपके Google Cloud प्रोजेक्ट के लिए बिलिंग की सुविधा चालू हो. किसी प्रोजेक्ट के लिए बिलिंग की सुविधा चालू है या नहीं, यह देखने का तरीका जानें.
  3. Vertex AI डैशबोर्ड से, सुझाए गए सभी एपीआई चालू करें
  4. Colab Notebook खोलें और उसी खाते में लॉगिन करें जिससे आपने मौजूदा Google Cloud खाते में साइन इन किया है.

3. मल्टी-मोडल आरएजी बनाना

यह कोडलैब Python के लिए Vertex AI SDK और Langchain का इस्तेमाल करके, यहां बताए गए ‘विकल्प 2’ को Google Cloud के साथ लागू करने का तरीका बताता है.

रेफ़र की गई डेटा स्टोर करने की जगह से, Google Cloud के साथ मल्टी-मॉडल RAG फ़ाइल में पूरा कोड देखा जा सकता है.

4. पहला चरण: डिपेंडेंसी इंस्टॉल और इंपोर्ट करना

!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

अपना प्रोजेक्ट आईडी डालें और पुष्टि करने की प्रक्रिया पूरी करें

#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. दूसरा चरण: डेटा तैयार करना और लोड करना

हम इस ब्लॉग पोस्ट से निकाली गई इमेज और 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. तीसरा चरण: टेक्स्ट की खास जानकारी जनरेट करना

पहले ज़रूरी लाइब्रेरी इंपोर्ट करें

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. चौथा चरण: इमेज की खास जानकारी जनरेट करना

पहले ज़रूरी लाइब्रेरी इंपोर्ट करें

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. पांचवां चरण: मल्टी-वेक्टर रिकवरी

आइए, टेक्स्ट और इमेज की खास जानकारी जनरेट करें और उन्हें 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. छठा चरण: मल्टी-मोडल आरएजी बनाना

  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. मल्टी-मोडल आरएजी चेन को परिभाषित करें
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. सातवां चरण: अपनी क्वेरी की जांच करना

  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 Console में, संसाधन मैनेज करें पेज पर जाएं.
  2. प्रोजेक्ट की सूची में, वह प्रोजेक्ट चुनें जिसे मिटाना है. इसके बाद, मिटाएं पर क्लिक करें.
  3. डायलॉग बॉक्स में, प्रोजेक्ट आईडी टाइप करें. इसके बाद, प्रोजेक्ट मिटाने के लिए, शट डाउन करें पर क्लिक करें.

12. बधाई

बधाई हो! आपने Gemini की मदद से मल्टी-मोडल आरएजी तैयार कर लिया है.