<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Sarthak Arora on Medium]]></title>
        <description><![CDATA[Stories by Sarthak Arora on Medium]]></description>
        <link>https://medium.com/@iasarthak?source=rss-36c6f05bdc37------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*kG_7ayhnx7rnb1SPp7oD8A@2x.jpeg</url>
            <title>Stories by Sarthak Arora on Medium</title>
            <link>https://medium.com/@iasarthak?source=rss-36c6f05bdc37------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 07:02:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@iasarthak/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Harnessing Data Science Interns: A Game-Changer for Your Lean Startup]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://iasarthak.medium.com/harnessing-data-science-interns-a-game-changer-for-your-lean-startup-cc39fa84a93d?source=rss-36c6f05bdc37------2"><img src="https://cdn-images-1.medium.com/max/1792/1*7QYWe6g5G50wPMnAO_mORw.png" width="1792"></a></p><p class="medium-feed-link"><a href="https://iasarthak.medium.com/harnessing-data-science-interns-a-game-changer-for-your-lean-startup-cc39fa84a93d?source=rss-36c6f05bdc37------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://iasarthak.medium.com/harnessing-data-science-interns-a-game-changer-for-your-lean-startup-cc39fa84a93d?source=rss-36c6f05bdc37------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc39fa84a93d</guid>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[internships]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[jobs]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Sarthak Arora]]></dc:creator>
            <pubDate>Thu, 21 Nov 2024 10:48:00 GMT</pubDate>
            <atom:updated>2024-11-21T10:48:00.318Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Create Powerful Affirmations to Manifest Your Dream Life: A Step-by-Step Guide]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://iasarthak.medium.com/create-powerful-affirmations-to-manifest-your-dream-life-a-step-by-step-guide-48bb05765551?source=rss-36c6f05bdc37------2"><img src="https://cdn-images-1.medium.com/max/1792/1*Ne1k6jZ2zqZuYYV3_lJ8aQ.png" width="1792"></a></p><p class="medium-feed-snippet">Unlock the Power of Positive Affirmations: Step-by-Step Guide to Manifesting Health, Wealth, and Success in All Areas of Life</p><p class="medium-feed-link"><a href="https://iasarthak.medium.com/create-powerful-affirmations-to-manifest-your-dream-life-a-step-by-step-guide-48bb05765551?source=rss-36c6f05bdc37------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://iasarthak.medium.com/create-powerful-affirmations-to-manifest-your-dream-life-a-step-by-step-guide-48bb05765551?source=rss-36c6f05bdc37------2</link>
            <guid isPermaLink="false">https://medium.com/p/48bb05765551</guid>
            <category><![CDATA[affirmations]]></category>
            <category><![CDATA[self-improvement]]></category>
            <category><![CDATA[law-of-attraction]]></category>
            <category><![CDATA[life-lessons]]></category>
            <category><![CDATA[manifestation]]></category>
            <dc:creator><![CDATA[Sarthak Arora]]></dc:creator>
            <pubDate>Mon, 11 Nov 2024 15:32:24 GMT</pubDate>
            <atom:updated>2024-11-11T15:32:24.602Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Building Multimodal AI in Healthcare Using GPT and Qdrant]]></title>
            <link>https://medium.com/analytics-vidhya/building-multimodal-ai-in-healthcare-using-gpt-and-qdrant-ae56a99d23d6?source=rss-36c6f05bdc37------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae56a99d23d6</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[retrieval-augmented]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[healthcare-technology]]></category>
            <category><![CDATA[qdrant]]></category>
            <dc:creator><![CDATA[Sarthak Arora]]></dc:creator>
            <pubDate>Wed, 02 Oct 2024 07:47:03 GMT</pubDate>
            <atom:updated>2024-10-02T07:47:03.552Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sjq6czL4KO-7hJqF87xTdQ.png" /><figcaption>Image by AI about AI. Heh.</figcaption></figure><p><em>The accompanying code for this blog/project is </em><a href="https://github.com/iasarthak/healthcare_multimodal_ai"><em>here</em></a><em>.</em></p><p><strong>AI is transforming everything — and fast.</strong> New tools and APIs drop almost daily, and staying updated is no easy feat. Luckily, many great wrappers (not rappers!) simplify the process, making it easier than ever to build AI-powered tools for any use case.</p><p>Recently, <a href="https://www.linkedin.com/in/abhishekor/">Abhishek</a> and <a href="https://www.linkedin.com/in/iasarthak/">I</a> attempted a project to do just that. And trust me — it was easier than you’d think! Our goal was to help radiologists by creating a tool that not only analyzes medical reports and images but also suggests possible next steps to provide the best care for their patients.</p><p>In technical terms, it’s a <strong>RAG (Retrieval-Augmented Generation)</strong> system. But for us, it’s more like a “RAG-to-riches” story, where “riches” means productivity. And who wouldn’t want that, especially when doctors are already putting in long hours? This project aims to give them an extra helping hand.</p><p>So, let’s dive into how we built it!</p><h3>So, what is Multimodal AI and how are we implementing it?</h3><p>Multimodal AI involves the integration of different types of data — such as text, images, and audio — into a single model capable of processing complex information in a way that mimics human cognition.<br> <br>This approach allows the AI system to leverage multiple sources of information to gain a comprehensive understanding of a subject. For instance, in the healthcare domain, a multimodal model can analyze both medical images and textual patient records to deliver more accurate diagnostic insights.</p><p>The future of AI is inherently multimodal, as it aligns with how humans interpret and process information through various senses. This capability enables more robust, context-aware models that can excel in diverse applications such as healthcare, autonomous driving, and content generation.</p><p>In this project, we aim to demonstrate how to build a multimodal AI system using GPT-4o for natural language understanding and Qdrant for managing and querying vector embeddings. This system will combine text and image data to provide a powerful diagnostic tool for healthcare applications.</p><h3>Pre-requisites</h3><p>Before you begin, ensure that you have the following:<br>- Python 3.8+ installed.<br>- API Keys for GPT-4o and Qdrant.<br>- Installed dependencies like fastembed, qdrant-client, openai, gradio. (Don’t worry, these are mentioned in requirements.txt file as well, link to the repo is mentioned in the end.)<br>- Dataset: Medical scans and corresponding patient records in text format. (Explained below.)<br>- Patience (This is the most important, you know!)</p><h3>Dataset</h3><p>For this project, we are using the Radiology Objects in Context (ROCO) dataset, a large-scale medical imaging dataset that includes thousands of anonymized captions and corresponding medical scans.</p><p>The ROCO dataset is specifically tailored for radiological contexts, making it ideal for developing multimodal models that analyze both medical images and associated textual information.</p><p>In the repository, I’ve prepared a subset of the ROCO dataset in the <em>data</em> folder, which contains a variety of medical scans and related text descriptions. This sample includes a few images representing different medical conditions, sufficient for demonstrating the project’s capabilities.</p><p>You can access the full dataset <a href="https://github.com/razorx89/roco-dataset">here</a>. There is a script that you can run after forking the repository which will download the dataset on your local machine.</p><p>Ensure you review the dataset’s licensing and accessibility guidelines for research purposes.</p><h3>Architecture</h3><p>Here’s a pretty intuitive architecture that talks about how our project is structured</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/0*Yer9tUhRVFQM5nps" /></figure><h3>Steps to Implement Multimodal AI</h3><h4>1. Sign up for GPT-4o and Qdrant:</h4><p><strong>- GPT-4o:</strong> Create an account on the OpenAI platform and obtain an API key to access GPT-4o’s natural language processing capabilities. Refer to this guide to get the API key. <a href="https://www.merge.dev/blog/chatgpt-api-key">https://www.merge.dev/blog/chatgpt-api-key<strong><br></strong></a><strong>- Qdrant:</strong> Register on the <a href="https://qdrant.tech/">Qdrant website</a> to manage and query your vector embeddings efficiently. We are going to store our vector embeddings locally for the purpose of this project. The Qdrant Python wrappers are elaborate enough to help us do this with a few commands.</p><h4>2. Data Preparation and Embedding Creation:</h4><p><strong>Text Embeddings - </strong>To convert patient records into vector embeddings, we use the FastEmbed library. Each record is transformed into a vector representation, with metadata such as patient ID, diagnosis, and symptoms included in the payload.</p><p><strong>Image Embeddings - </strong>To convert medical images into vector embeddings, we use the CLIP model. Each image is processed into a vector, and metadata such as scan type and diagnosis is stored along with it.</p><p><em>File: src/embeddings_utils.py</em></p><pre><br>from typing import List<br>from fastembed import TextEmbedding, ImageEmbedding<br><br>TEXT_MODEL_NAME = &quot;Qdrant/clip-ViT-B-32-text&quot;<br>IMAGE_MODEL_NAME = &quot;Qdrant/clip-ViT-B-32-vision&quot;<br><br>def convert_text_to_embeddings(documents: List[str], embedding_model: str = TEXT_MODEL_NAME) -&gt; List:<br>    text_embedding_model = TextEmbedding(model_name=embedding_model)<br>    text_embeddings = list(text_embedding_model.embed(documents))  # Returns a generator of embeddings<br>    return text_embeddings<br><br>def convert_image_to_embeddings(images: List[str], embedding_model: str = IMAGE_MODEL_NAME) -&gt; List:<br>    image_model = ImageEmbedding(model_name=embedding_model)<br>    images_embedded = list(image_model.embed(images))<br>    return images_embedded</pre><h4><strong>3. Storing Embeddings in Qdrant:</strong></h4><p>We store the text and image embeddings in the Qdrant vector database. The metadata associated with each embedding helps in performing accurate similarity searches later.</p><p>Named vectors like ‘<strong>text</strong>’ and ‘<strong>image</strong>’ refer to structured embeddings of each input modality. By naming them, we can easily distinguish between text and image data during processing. This ensures that the model handles each input appropriately and combines them effectively in tasks like retrieval or content generation, improving the system’s accuracy and coherence.</p><p><em>File: src/create_data_embeddings.py</em></p><pre>import os<br>import uuid<br><br>import pandas as pd<br>from fastembed import TextEmbedding, ImageEmbedding<br>from qdrant_client import QdrantClient, models<br><br>from src.embeddings_utils import convert_text_to_embeddings, convert_image_to_embeddings, TEXT_MODEL_NAME, \<br>   IMAGE_MODEL_NAME<br><br>DATA_PATH = &#39;/Users/sarthak/Documents/Work/Personal_Projects/healthcare_multimodal_ai/data/&#39;<br><br>def create_uuid_from_image_id(image_id):<br>   NAMESPACE_UUID = uuid.UUID(&#39;12345678-1234-5678-1234-567812345678&#39;)<br>   return str(uuid.uuid5(NAMESPACE_UUID, image_id))<br><br>def create_embeddings(collection_name):<br>   # Read captions txt data<br>   path = DATA_PATH + &#39;captions.txt&#39;<br>   caption_df = pd.read_csv(path, sep=&#39;\t&#39;, header=None, names=[&#39;image_id&#39;, &#39;caption&#39;])<br><br><br>   # Read images<br>   image_directory = os.listdir(DATA_PATH + &#39;images&#39;)<br><br><br>   # Filter out images that are not in the captions<br>   images = []<br>   for image in image_directory:<br>       if image.split(&#39;.&#39;)[0] in caption_df[&#39;image_id&#39;].values:<br>           images.append(image)<br><br><br>   # Create image_id, caption, image_path list of dictionaries<br>   image_docs = []<br>   for image in images:<br>       image_id = image.split(&#39;.&#39;)[0]<br>       caption = caption_df[caption_df[&#39;image_id&#39;] == image_id][&#39;caption&#39;].values[0]<br>       image_path = DATA_PATH + &#39;images/&#39; + image<br>       image_docs.append({&#39;image_id&#39;: image_id, &#39;caption&#39;: caption, &#39;image_path&#39;: image_path})<br><br><br>   # Convert text to embeddings using Fastembed and images to embeddings using CLIP<br>   captions = [doc[&#39;caption&#39;] for doc in image_docs]<br>   embeddings = convert_text_to_embeddings(captions)<br>   for idx, embedding in enumerate(embeddings):<br>       image_docs[idx][&#39;caption_embedding&#39;] = embedding<br><br><br>   # Convert image to embeddings using CLIP<br>   image_embeddings = convert_image_to_embeddings([doc[&#39;image_path&#39;] for doc in image_docs])<br><br><br>   for idx, embedding in enumerate(image_embeddings):<br>       image_docs[idx][&#39;image_embedding&#39;] = embedding<br><br><br>   # Save the embeddings to vector database<br>   client = QdrantClient(&quot;:memory:&quot;)<br><br><br>   text_model = TextEmbedding(model_name=TEXT_MODEL_NAME)<br>   text_embeddings_size = text_model._get_model_description(TEXT_MODEL_NAME)[&quot;dim&quot;]<br><br><br>   image_model = ImageEmbedding(model_name=IMAGE_MODEL_NAME)<br>   image_embeddings_size = image_model._get_model_description(IMAGE_MODEL_NAME)[&quot;dim&quot;]<br><br><br>   if not client.collection_exists(collection_name):<br>       client.create_collection(<br>           collection_name=collection_name,<br>           vectors_config={<br>               &quot;image&quot;: models.VectorParams(size=image_embeddings_size, distance=models.Distance.COSINE),<br>               &quot;text&quot;: models.VectorParams(size=text_embeddings_size, distance=models.Distance.COSINE),<br>           }<br>       )<br>   client.upload_points(<br>       collection_name=collection_name,<br>       points=[<br>           models.PointStruct(<br>               # Convert image_id to UUID<br>               id=create_uuid_from_image_id(doc[&#39;image_id&#39;]),<br>               vector={<br>                   &quot;text&quot;: doc[&#39;caption_embedding&#39;],<br>                   &quot;image&quot;: doc[&#39;image_embedding&#39;],<br>               },<br>               payload={<br>                   &quot;image_id&quot;: doc[&#39;image_id&#39;],<br>                   &quot;caption&quot;: doc[&#39;caption&#39;],<br>                   &quot;image_path&quot;: doc[&#39;image_path&#39;]<br>               }<br>           )<br>           for doc in image_docs<br>       ]<br>   )<br>   return client</pre><h4><strong>4. Query Conversion and Similarity Search:</strong></h4><p>We convert the user’s query (either text or image) into a vector embedding and perform a similarity search in the Qdrant database to find the most relevant text or images. This allows for both ‘query by text’ and ‘query by image,’ improving retrieval accuracy across modalities.</p><p><em>File: src/embeddings_utils.py</em></p><pre># Search for similar text and get corresponding images as well<br>def search_similar_text(collection_name, client, query, limit=3):<br>   text_model = TextEmbedding(model_name=TEXT_MODEL_NAME)<br>   search_query = text_model.embed([query])<br>   search_results = client.search(<br>       collection_name=collection_name,<br>       query_vector=(&#39;text&#39;, list(search_query)[0]),<br>       with_payload=[&#39;image_path&#39;, &#39;caption&#39;],<br>       limit=limit,<br>   )<br>   return search_results<br><br># Search for similar images and get corresponding text as well<br>def search_similar_image(collection_name, client, query_image_path, limit=3):<br>   # Convert the query image into an embedding using the same model used for image embeddings<br>   image_embedding_model = ImageEmbedding(model_name=IMAGE_MODEL_NAME)<br><br><br>   # Embed the provided query image (assumed to be a file path)<br>   query_image_embedding = list(image_embedding_model.embed([query_image_path]))[0]  # Embedding for the query image<br><br><br>   # Perform the similarity search in the Qdrant collection for image embeddings<br>   search_results = client.search(<br>       collection_name=collection_name,<br>       query_vector=(&#39;image&#39;, query_image_embedding),<br>       with_payload=[&#39;image_path&#39;, &#39;caption&#39;],  # Fetch image paths and captions as metadata<br>       limit=limit,<br>   )<br>   return search_results<br><br>def merge_results(text_results, image_results):<br>   # Combine based on some metadata, or simply concatenate<br>   combined_results = text_results + image_results<br>   return combined_results<br></pre><h4><strong>5. Response Generation with GPT-4o:</strong></h4><p>We use the retrieved data to prompt the GPT-4o model, generating a detailed response based on the relevant context.</p><p>Make sure you give a detailed intuitive role to the model. That’ll help you give more appropriate results.</p><p><em>File: src/gpt_utils.py</em></p><pre>import base64<br>import json<br>import requests<br><br>from config import Config<br><br>class GPTClient:<br>   def __init__(self):<br>       self.api_key = Config.OPENAI_API_KEY<br>       self.api_url = &quot;https://api.openai.com/v1/chat/completions&quot;<br><br>   def query(self, prompt, retrieved_contexts, user_image=None):<br>       headers = {<br>           &quot;Content-Type&quot;: &quot;application/json&quot;,<br>           &quot;Authorization&quot;: f&quot;Bearer {self.api_key}&quot;<br>       }<br><br>       chatbot_role = &quot;&quot;&quot;<br>       You are a radiologist with an experience of 30 years.<br>       You analyse medical scans and text, and help diagnose underlying issues.<br>       &quot;&quot;&quot;<br><br>       # Initialize message structure with the system prompt<br>       messages = [<br>           {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: chatbot_role},<br>           {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: [<br>               {&quot;type&quot;: &quot;text&quot;, &quot;text&quot;: prompt}<br>           ]}<br>       ]<br><br><br>       # Add the user-uploaded image (if any)<br>       if user_image:<br>           with open(user_image, &quot;rb&quot;) as image_file:<br>               base64_image = base64.b64encode(image_file.read()).decode(&#39;utf-8&#39;)<br>               messages[1][&quot;content&quot;].append({<br>                   &quot;type&quot;: &quot;image_url&quot;,<br>                   &quot;image_url&quot;: {<br>                       &quot;url&quot;: f&quot;data:image/jpeg;base64,{base64_image}&quot;<br>                   }<br>               })<br><br><br>       messages[1][&quot;content&quot;].append({<br>           &quot;type&quot;: &quot;text&quot;,<br>           &quot;text&quot;: &quot;Additional context that you may use as a reference. Use them if you feel they are relevant to &quot;<br>                   &quot;the case.&quot;<br>                   &quot;NOTE: They are not the patient&#39;s images. They are of other patients which can be used as a &quot;<br>                   &quot;reference, if required.&quot;<br>       })<br><br><br>       # Add the retrieved contexts, which should include both captions and corresponding images<br>       for context in retrieved_contexts:<br>           caption = context.payload[&#39;caption&#39;]<br>           image_path = context.payload[&#39;image_path&#39;]<br><br>           # Add the caption to the message<br>           messages[1][&quot;content&quot;].append({<br>               &quot;type&quot;: &quot;text&quot;,<br>               &quot;text&quot;: f&quot;Caption: {caption}&quot;<br>           })<br><br>           # Add the corresponding image to the message<br>           with open(image_path, &quot;rb&quot;) as image_file:<br>               base64_image = base64.b64encode(image_file.read()).decode(&#39;utf-8&#39;)<br>               messages[1][&quot;content&quot;].append({<br>                   &quot;type&quot;: &quot;image_url&quot;,<br>                   &quot;image_url&quot;: {<br>                       &quot;url&quot;: f&quot;data:image/jpeg;base64,{base64_image}&quot;<br>                   }<br>               })<br><br>       # Prepare the payload for the GPT API<br>       data = {<br>           &quot;model&quot;: &quot;gpt-4o&quot;,<br>           &quot;messages&quot;: messages,<br>           &quot;max_tokens&quot;: 600<br>       }<br><br>       # Send the request to the API<br>       response = requests.post(self.api_url, headers=headers, data=json.dumps(data))<br>       return response.json()<br><br>   def process_response(self, response):<br>       if &#39;choices&#39; in response and len(response[&#39;choices&#39;]) &gt; 0:<br>           return response[&#39;choices&#39;][0][&#39;message&#39;][&#39;content&#39;]</pre><h4><strong>6. Tying All the Pieces Together:</strong></h4><p>Here, we are setting up the multimodal RAG system class. The method process_query will orchestrate the retrieval and pass the query to ChatGPT.</p><p><em>File: src/multimodal_rag_system.py</em></p><pre>from src.create_data_embeddings import create_embeddings<br>from src.embeddings_utils import search_similar_text, search_similar_image, merge_results<br>from src.gpt_utils import GPTClient<br><br>COLLECTION_NAME = &quot;medical_images_text&quot;<br><br>class MultimodalRAGSystem:<br>   collection_name: str<br><br>   def __init__(self):<br>       self.gpt_client = GPTClient()<br>       self.qdrant_client = create_embeddings(COLLECTION_NAME)<br>       self.collection_name = COLLECTION_NAME<br><br>   def process_query(self, query, query_image_path=None, top_k=3):<br>       # 1. Text-based search if query is textual<br>       search_results_text = search_similar_text(self.collection_name, self.qdrant_client, query, limit=top_k)<br><br>       # 2. Image-based search if a query image is provided<br>       search_results_image = []<br>       if query_image_path:  # Only perform image retrieval if an image path is provided<br>           search_results_image = search_similar_image(self.collection_name, self.qdrant_client, query_image_path, limit=top_k)<br><br>       # 3. Combine both results - merging text and image results<br>       combined_results = merge_results(search_results_text, search_results_image)<br><br>       # 4. Query GPT with the context and images<br>       gpt_response = self.gpt_client.query(query, combined_results, query_image_path)<br><br>       # 5. Process and return the response<br>       return self.gpt_client.process_response(gpt_response)</pre><h4>7. Showcasing Results Using Gradio:</h4><p>We use Gradio to create an interactive user interface where users can input text queries and upload medical images. The system will then provide a detailed response based on the multimodal data.</p><p><em>File: src/main.py</em></p><pre>import gradio as gr<br>from PIL import Image<br>from multimodal_rag_system import MultimodalRAGSystem<br><br># Initialize the MultimodalRAGSystem<br>system = MultimodalRAGSystem()<br><br># Define the Gradio function that will process the user input and image<br>def chatbot_interface(user_query, user_image=None):<br>   if user_image is not None:<br>       # Convert numpy array to a PIL Image and save it temporarily<br>       user_image = Image.fromarray(user_image)<br>       user_image_path = (&quot;/Users/sarthak/Documents/Work/Personal_Projects/healthcare_multimodal_ai/data&quot;<br>                          &quot;/user_input_image.jpg&quot;)<br>       user_image.save(user_image_path)<br>   else:<br>       user_image_path = None<br><br>   # Get the response from the Multimodal AI system<br>   response = system.process_query(user_query, query_image_path=user_image_path)<br>   return response<br><br># Create the Gradio interface with text input and image input<br>interface = gr.Interface(<br>   fn=chatbot_interface,<br>   inputs=[gr.components.Textbox(lines=5, label=&quot;User Query&quot;), gr.components.Image(label=&quot;Upload Medical Image&quot;)],<br>   outputs=gr.components.Textbox(),<br>   title=&quot;Multimodal Medical Assistant&quot;,<br>   description=&quot;Ask medical-related questions and upload relevant medical images for analysis.&quot;<br>)<br><br># Launch the Gradio interface<br>if __name__ == &quot;__main__&quot;:<br>   interface.launch()</pre><h3>Output</h3><p>Voila! The attached screenshots show our first attempt at uploading scans and getting a relevant analysis related to the scan. In the background, it augments the knowledge by retrieving relevant case studies.</p><p>If there is no relevant image found, it would do a preliminary diagnosis and suggest potential next steps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nU-fsbvke6a1StoJ" /><figcaption>Neck Scan: Using Gradio interface for querying, uploading and getting responses related to the images/query</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UCm4NAlPyndRuTYd" /><figcaption>Chest Scan: Using Gradio interface for querying, uploading and getting responses related to the images/query</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*j_pKcRosENYwgeuI" /><figcaption>Knee Scan: Using Gradio interface for querying, uploading and getting responses related to the images/query</figcaption></figure><h3>Next Steps</h3><p>We can improve this further by providing as many historical cases as possible in the form of images and captions. For example: a diagnostic/imaging centre which has handled thousands of cases would have a lot of data which can be augmented to our query to make informed decisions about the cases.</p><p>There is a lot of tweaking that can be done to the prompt as well, which would depend on the use-case of the application.</p><p>If applied right, this could prove to be a fantastic tool for radiologists and has the potential to increase the turn-around-time for cases by 2x.</p><h3>References and Resources</h3><p>Github Repo: <a href="https://github.com/iasarthak/healthcare_multimodal_ai">https://github.com/iasarthak/healthcare_multimodal_ai</a></p><p>GPT-4 Documentation: <a href="https://www.openai.com/research">https://www.openai.com/research</a></p><p>Qdrant Documentation: <a href="https://qdrant.tech/documentation/">https://qdrant.tech/documentation/</a></p><p>FastEmbed Library: <a href="https://github.com/fastembed">https://github.com/fastembed</a></p><p>CLIP Paper: <a href="https://arxiv.org/abs/2103.00020">https://arxiv.org/abs/2103.00020</a></p><p>A big shoutout to <a href="https://www.linkedin.com/in/abhishekor/">Abhishek Maurya</a> for being a huge help here. He’s worked with me as an intern at Jupiter and I’ve had the most wonderful experience mentoring him.</p><p>If you’re here, do give me a <a href="https://medium.com/@iasarthak">follow on Medium</a> and connect with me on <a href="https://medium.com/@iasarthak">Linkedin</a> to chat more about Data Science!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae56a99d23d6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/building-multimodal-ai-in-healthcare-using-gpt-and-qdrant-ae56a99d23d6">Building Multimodal AI in Healthcare Using GPT and Qdrant</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing a Full Stack Production RAG with Docker, Ray, Qdrant and LM Studio]]></title>
            <link>https://iasarthak.medium.com/implementing-a-full-stack-production-rag-with-docker-ray-qdrant-and-lm-studio-b0441ef52420?source=rss-36c6f05bdc37------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0441ef52420</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[qdrant]]></category>
            <dc:creator><![CDATA[Sarthak Arora]]></dc:creator>
            <pubDate>Tue, 14 May 2024 06:24:22 GMT</pubDate>
            <atom:updated>2024-05-14T06:24:22.763Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OQpWYoYUz20l0XeiD9kg6A.png" /><figcaption>Image about an AI, created by an AI</figcaption></figure><h3>Introduction</h3><p>In this tutorial, I will deploy a full stack Retrieval Augmented Generation (RAG) AI application using Docker, which can help developers understand how to deploy applications in production. My use case is text extraction and processing from PDF documents. To serve LLMs locally, I will use LM Studio.</p><h3>System Architecture</h3><ul><li><strong>Qdrant:</strong> Vector Store for storing and retrieving text embeddings.</li><li><strong>Ray: </strong>Handles parallel processing for generating embeddings, the part of the application that often is most computationally intensive.</li><li><strong>Gradio:</strong> Helps create user interfaces quickly.</li><li><strong>Langchain:</strong> Orchestration framework that helps bring together various AI components, such as LLMs, vector stores, knowledge graphs and more.</li></ul><h3><strong>Python Implementation</strong></h3><h4><strong>STEP 0: Pre-requisites</strong></h4><p>The 10 essential packages along with their uses that are required to replicate the project based on the provided descriptions.</p><ol><li><strong>ray </strong>— For distributed and parallel computation, crucial for handling intensive tasks like text embedding generation.</li><li><strong>qdrant-client — </strong>To interact with the Qdrant vector database for storing and querying embeddings.</li><li><strong>gradio</strong> — To build interactive web interfaces that allow users to interact with your machine learning model.</li><li><strong>transformers</strong> — Provides pre-trained models and utilities for natural language processing tasks.</li><li><strong>PyPDF2</strong> — Enables the extraction of text from PDF files, which is necessary for processing document data.</li><li><strong>nltk </strong>— Useful for text processing tasks such as tokenization, stemming, and removing stopwords.</li><li><strong>torch </strong>— PyTorch library, essential for building and running deep learning models.</li><li><strong>numpy </strong>— A fundamental package for scientific computing with Python, often used for data manipulation and analysis.</li><li><strong>sentence-transformers — </strong>A library for computing dense vector representations for sentences and paragraphs, based on transformer models.</li><li><strong>docker </strong>— For creating and managing application containers.</li></ol><h4>STEP 1: <strong>Import the necessary libraries</strong></h4><pre>import os<br>import pandas as pd<br>from langchain.embeddings import HuggingFaceBgeEmbeddings<br>from langchain.vectorstores import Qdrant<br>from langchain_openai import ChatOpenAI<br>from langchain_core.prompts import ChatPromptTemplate<br>from langchain.chains.combine_documents import create_stuff_documents_chain<br>from langchain.text_splitter import RecursiveCharacterTextSplitter<br>from langchain_openai import OpenAIEmbeddings<br>from langchain.chains import create_retrieval_chain<br>from langchain_core.prompts import MessagesPlaceholder<br>from langchain_core.messages import HumanMessage, AIMessage<br>from langchain.chains.history_aware_retriever import create_history_aware_retriever<br>import PyPDF2<br>import nltk<br>import re<br>import io<br>import gradio as gr<br>from nltk.corpus import stopwords<br>from nltk.stem import PorterStemmer, WordNetLemmatizer<br><br><br>import ray<br>from nltk.corpus import stopwords<br>from transformers import AutoModel, AutoTokenizer<br>import torch</pre><h4>STEP 2: <strong>Utilizing Ray for Parallel Processing</strong></h4><p>Ray is used here to parallelize the generation of text embeddings. Tasks are distributed across multiple processors to speed up the computation, crucial for handling large datasets efficiently. If initialized twice, it will give an error.</p><pre>ray.init()<br><br><br>@ray.remote<br>def compute_embeddings(doc, model_name):<br>    tokenizer = AutoTokenizer.from_pretrained(model_name)<br>    model = AutoModel.from_pretrained(model_name)<br>   <br>    # Check if CUDA is available and set the device accordingly<br>    device = torch.device(&quot;cuda&quot; if torch.cuda.is_available() else &quot;cpu&quot;)<br>    model.to(device)  # Move the model to the specified device<br><br><br>    inputs = tokenizer(doc, return_tensors=&#39;pt&#39;, padding=True, truncation=True)<br>    inputs = {k: v.to(device) for k, v in inputs.items()}<br><br><br>    with torch.no_grad():<br>        outputs = model(**inputs)<br><br><br>    embeddings = outputs.last_hidden_state[:, 0, :].squeeze()<br>    return embeddings.cpu().numpy()  # Move embeddings back to CPU if needed and convert to numpy array<br><br><br>def create_db(docs):<br>    print(&#39;Ray has been initiated&#39;)<br>    model_name = &quot;BAAI/bge-large-en&quot;  <br><br><br>    # Dispatch the embedding computation tasks<br>    embedding_futures = [compute_embeddings.remote(doc, model_name) for doc in docs]<br><br><br>    # Retrieve results from Ray&#39;s object store<br>    embeddings = ray.get(embedding_futures)<br><br>    # Create a list of dictionaries containing text and embeddings<br>    documents_with_embeddings = [{&quot;text&quot;: doc, &quot;embeddings&quot;: emb} for doc, emb in zip(docs, embeddings)]<br>    url = &quot;http://localhost:6333&quot;<br><br>    # Pass the list of preprocessed text strings directly to from_documents<br>    vectorStore = Qdrant.from_documents(docs, embeddings, url=url, prefer_grpc=False, collection_name=&quot;vector_db_2&quot;)<br>    print(&quot;Vector DB Created successfully&quot;)<br>   <br>    ray.shutdown()<br>    print(&#39;Ray has been shut down&#39;)<br>    return vectorStore</pre><h4>STEP 3: <strong>PDF Text Extraction</strong></h4><p>Let’s extract text from PDF documents using <strong>PyPDF2.</strong> This function iterates through PDF pages and combines them to create text data.</p><pre>def extract_text_from_pdf(pdf_content):<br>    &quot;&quot;&quot;Extract text from a PDF file content.&quot;&quot;&quot;<br>    pdf_reader = PyPDF2.PdfReader(io.BytesIO(pdf_content))<br>    pdf_text = &quot;&quot;<br>    for page in pdf_reader.pages:<br>        pdf_text += page.extract_text() if page.extract_text() else &quot;&quot;<br>    return pdf_text</pre><p><strong>Ray Logs:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/0*dpZ5HoZgykaJl4pj" /></figure><h4>STEP 4: <strong>Text Preprocessing</strong></h4><p>Now let’s remove figures, tables, and in-text citations. After that, we will apply tokenization, lemmatization, and stopword removal.</p><pre>def preprocess_text(text):<br>    &quot;&quot;&quot;Preprocess the text by removing stop words, stemming, and lemmatizing.&quot;&quot;&quot;<br>    stop_words = set(stopwords.words(&#39;english&#39;))<br>    stemmer = PorterStemmer()<br>    lemmatizer = WordNetLemmatizer()<br><br><br>    tokens = nltk.word_tokenize(text)<br>    tokens = [word for word in tokens if word.lower() not in stop_words]<br>    lemmatized_tokens = [lemmatizer.lemmatize(stemmer.stem(word)) for word in tokens]<br>    return &#39; &#39;.join(lemmatized_tokens)<br><br><br>def final_result(pdf_file, query):<br>    # Extract text from the PDF file content<br>    pdf_text = extract_text_from_pdf(pdf_file)<br><br>    # Clean and preprocess the extracted text<br>    cleaned_text = remove_figures_tables_citations(pdf_text)<br>    preprocessed_text = preprocess_text(cleaned_text)<br><br>    # Create a list of documents (currently just one document)<br>    docs = [preprocessed_text]<br><br>    # Create the vector database<br>    vectorStore = create_db(docs)<br><br>    return &quot;Processed and created the vector database successfully!&quot;</pre><h4>STEP 5: <strong>Deploying Mistral-7b on LM Studio</strong></h4><p>- <strong>Install LM Studio:</strong> Begin by downloading the installer from [https://lmstudio.ai](https://lmstudio.ai).</p><p>- <strong>Download an LLM:</strong> Open LM Studio, search for and download an LLM, such as “TheBloke/Mistral-7B-Instruct-v0.2-GGUF” (approximately 4GB in size). It only accepts models in the GGUF format as that is the format needed by LlamaCpp, which is the underlying library used for model deployment in Open LM Studio.</p><p>- <strong>Navigate to the Local Server:</strong> Click on the Local Server tab (icon with &lt;-&gt;) on the left.</p><p>- <strong>Load the LLM:</strong> Select the downloaded LLM from the dropdown menu.</p><p>- <strong>Start the Server:</strong> Click on the green ‘Start Server’ button to initiate the server. This will launch the model instance on “<a href="http://localhost:6333/">http://localhost:6333</a>&quot;.</p><p>- <strong>Minimize LM Studio:</strong> Once the server is running, you can minimize the app. The server will continue to operate and handle API requests.</p><h4>STEP 6: <strong>Gradio Web Interface</strong></h4><p>Implements an interface for uploading PDFs and entering queries. Displays processing results on a webpage.</p><pre># Gradio Interface Setup<br>interface = gr.Interface(<br>    fn=final_result,<br>    inputs=[<br>        gr.File(type=&quot;binary&quot;, label=&quot;Upload a PDF&quot;),<br>        gr.Textbox(lines=2, label=&quot;Enter your query&quot;)<br>    ],<br>    outputs=&quot;text&quot;,<br>    title=&quot;Process PDF and Query&quot;,<br>    description=&quot;Upload a PDF file and enter a query The app will process the PDF and perform some operations based on the query.&quot;<br>)<br><br><br># Launch the interface<br>if __name__ == &quot;__main__&quot;:<br>    interface.launch()</pre><h3><strong>Docker Deployment</strong></h3><p>The Dockerfile configures the environment for the web application, as illustrated below:</p><pre># Start with the Python 3.9 image<br>FROM python:3.10<br><br><br># Set the working directory to /Chatbot<br>WORKDIR /webapp<br><br><br># running requirements- requirements file provide all necessary library with version that could enable building up the docker<br>COPY requirements.txt .<br><br><br>RUN pip install -r requirements.txt <br><br><br># Copy the Python script generated from your notebook<br>COPY webapp.py .<br><br><br># Expose the port Gradio will run on, assuming 7860 (default Gradio port)<br>EXPOSE 7860<br>EXPOSE 6333<br>EXPOSE 1234<br># Command to run your Gradio app<br>CMD [&quot;python&quot;, &quot;webapp.py&quot;]</pre><p>Make sure the above is saved as Dockerfile without any file extension in your project directory. Also, ensure you have a requirements.txt file in the same directory, listing all the Python packages your application needs.</p><p>Open your terminal or command prompt and navigate to the directory containing your Dockerfile and requirements.txt. Use the following command to build the Docker image:</p><pre>docker build -t webapp-image .</pre><p>Here, -t webapp-image tags the image with the name webapp-image, and the . at the end tells Docker to use the Dockerfile in the current directory.</p><p>Once the image is built, you can run a container from it. Since you expose multiple ports (7860, 6333, and 1234) in your Dockerfile, you should map these ports to ports on your host machine.</p><pre>docker run -p 7860:7860 -p 6333:6333 -p 1234:1234 webapp-image</pre><h3><strong>Local Deployment with LM Studio</strong></h3><p>Manual configuration in LM Studio involves setting up Docker containers and ensuring that all services can communicate effectively in a local deployment environment. This setup allows developers to manage resources effectively and tweak the system as needed for optimal performances.</p><h3><strong>Output after Deployment</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wKiDiMFc6bIDcJHG" /></figure><h3>Conclusion</h3><p>This deployment strategy using Docker and Ray provides a scalable, efficient solution for document processing applications. The use of Ray for parallel processing significantly enhances the system’s ability to handle large volumes of data, making it an ideal choice for enterprise-level applications.</p><h3><strong>Additional Resources and References</strong></h3><p>For those interested in further exploring or building upon the concepts discussed in this article, the following resources are recommended:</p><ul><li><strong>Docker Documentation</strong>: <a href="https://docs.docker.com/">https://docs.docker.com/</a></li><li><strong>Ray Project</strong>: <a href="https://github.com/ray-project/ray">Ray GitHub Repository</a></li><li><strong>Gradio Web Interface</strong>: <a href="https://www.gradio.app/docs">https://www.gradio.app/docs</a></li><li><strong>Langchain GitHub Repository</strong>: <a href="https://python.langchain.com/docs/get_started/introduction">https://python.langchain.com/docs/get_started/introduction</a></li><li><strong>Qdrant Vector Search Engine</strong>: <a href="https://qdrant.tech/">Qdrant Documentation</a></li></ul><p>A big shoutout to <a href="https://www.linkedin.com/in/abhishekor/">Abhishek Maurya</a> for practically doing everything here! He’s worked with me as an intern at Jupiter and I’ve had the most wonderful experience mentoring him.</p><p>If you’re here, do give me a <a href="https://medium.com/@iasarthak">follow on Medium</a> and connect with me on <a href="https://medium.com/@iasarthak">Linkedin</a> to chat more about Data Science!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0441ef52420" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Step-by-Step Guide to Build a Competition Analysis AI]]></title>
            <link>https://iasarthak.medium.com/step-by-step-guide-to-build-a-competition-analysis-ai-4be006980d1d?source=rss-36c6f05bdc37------2</link>
            <guid isPermaLink="false">https://medium.com/p/4be006980d1d</guid>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[qdrant]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[mistral]]></category>
            <dc:creator><![CDATA[Sarthak Arora]]></dc:creator>
            <pubDate>Tue, 02 Apr 2024 06:04:36 GMT</pubDate>
            <atom:updated>2024-04-02T06:05:04.804Z</atom:updated>
            <content:encoded><![CDATA[<p>Traditional competition analysis, while valuable, has limitations. A business might consider a competition analysis AI tool for speed and efficiency, for real-time insights, for making better data-driven decisions, or for an AI’s predictive capabilities.</p><p>In this blog, I’ll walk you through the building of a Competition Analysis AI using a powerful combination of tools: Mistral 7B, Python, Qdrant, and LangChain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Q79o8-y7oXdB8kFpaiMdw.png" /><figcaption>Image generated using AI, about an AI</figcaption></figure><h3>Laying the Groundwork</h3><p>To begin our journey, we start with the backbone of any good analysis: data. Using Python, I scripted a process that compiles a comprehensive list of competitor websites and their URLs, ensuring a broad and representative sample of the competitive space and downloading necessary libraries for the same.</p><h4>Python Script for Importing Necessary Libraries and Data Collection</h4><pre>from dotenv import load_dotenv<br>load_dotenv()<br><br>import os<br>from langchain.embeddings import HuggingFaceBgeEmbeddings<br>from langchain.vectorstores import Qdrant<br>from langchain_openai import ChatOpenAI<br>from langchain_core.prompts import ChatPromptTemplate<br>from langchain.chains.combine_documents import create_stuff_documents_chain<br>from langchain_community.document_loaders import WebBaseLoader<br>from langchain.text_splitter import RecursiveCharacterTextSplitter<br>from langchain_openai import OpenAIEmbeddings<br>from langchain_community.vectorstores.faiss import FAISS<br>from langchain.chains import create_retrieval_chain<br><br># Conversation imports<br>from langchain_core.prompts import MessagesPlaceholder<br>from langchain_core.messages import HumanMessage, AIMessage<br>from langchain.chains.history_aware_retriever import create_history_aware_retriever</pre><pre>import pandas as pd<br>from langchain_community.document_loaders import WebBaseLoader<br>from langchain.text_splitter import RecursiveCharacterTextSplitter<br><br><br># Reading Webpages of our competitors<br>def get_documents_from_web(df):<br>    lst = []<br>    for i in range(len(df)):<br>        url = df[&quot;URL&#39;s&quot;][i]<br>        loader = WebBaseLoader(url)<br>        docs = loader.load()<br>        lst.append(docs)<br><br><br>    splitter = RecursiveCharacterTextSplitter(<br>        chunk_size=400,<br>        chunk_overlap=20<br>    )<br>    splitDocs = splitter.split_documents(docs)<br>    return splitDocs<br><br>df = pd.read_csv(&#39;Others.csv&#39;)<br>docs =  get_documents_from_web(df)</pre><h3>The Tech Marvels: Qdrant and LangChain</h3><p>Next, it’s onto the powerhouse duo — Qdrant and LangChain. With Python at the helm, these tools work in tandem to sift through the compiled URLs. They index the content into <a href="https://qdrant.tech/">Qdrant</a>, a potent vector database, readying it for sophisticated natural language processing. LangChain’s linguistic prowess is invaluable here, transforming the raw website content into structured, analyzable data.</p><h4>Indexing with Qdrant and LangChain</h4><pre>def create_db(docs):<br>    model_name = &quot;BAAI/bge-large-en&quot;<br>    model_kwargs = {&#39;device&#39;: &#39;cpu&#39;}<br>    encode_kwargs = {&#39;normalize_embeddings&#39;: False}<br>    embeddings = HuggingFaceBgeEmbeddings(model_name=model_name,model_kwargs=model_kwargs,encode_kwargs=encode_kwargs)<br><br><br>    url = &quot;http://localhost:6333&quot;<br>    vectorStore = Qdrant.from_documents(docs,embedding= embeddings,url=url,prefer_grpc=False,collection_name=&quot;vector_db&quot;)<br>    print(&quot;Vector DB Created successfully&quot;)<br>    return vectorStore<br><br><br>vectorStore = create_db(docs)</pre><h4>Building the RAG Pipeline</h4><p>The heart of our AI is the RAG (Retrieval Augmented Generation) pipeline, fueled by Mistral 7B. This pipeline is our query processing unit, designed to handle complex questions like “What does XYZ company do?” It retrieves the most relevant information, shaped by the contextual understanding courtesy LangChain and Qdrant’s indexing prowess.</p><p>I have used LLM Studio here.</p><p>LM Studio is a desktop application designed to make experimenting with large language models (LLMs) accessible. LM Studio caters to users who want to run LLMs directly on their own computers, rather than relying on cloud-based services. This can be advantageous for privacy reasons or for working with open-source models that may not be available as cloud services.</p><p>LM Studio also simplifies the process of downloading, running, and interacting with LLMs. It provides a graphical user interface (UI) that doesn’t require extensive coding knowledge. LM Studio works on both Windows and Mac operating systems, making it accessible to a wider range of users.</p><pre>def create_chain(vectorStore):<br>    os.environ[&quot;OPENAI_API_KEY&quot;] = &quot;not-needed&quot;<br>    model = ChatOpenAI(base_url=&quot;http://localhost:1234/v1&quot;) <br>    <br>    #LM Studio was used here, for downloading mestral-7B and <br>    #for connectivity here!, it&#39;s a go to app for playing with open source LLM<br><br>    prompt = ChatPromptTemplate.from_messages([<br>        (&quot;system&quot;, &quot;Answer the user&#39;s questions based on the context: {context}&quot;),<br>        MessagesPlaceholder(variable_name=&quot;chat_history&quot;),<br>        (&quot;user&quot;, &quot;{input}&quot;)<br>    ])<br><br><br>    # chain = prompt | model<br>    chain = create_stuff_documents_chain(<br>        llm=model,<br>        prompt=prompt<br>    )<br><br><br>    # Replace retriever with history aware retriever<br>    retriever = vectorStore.as_retriever(search_kwargs={&quot;k&quot;: 3})<br><br><br>    retriever_prompt = ChatPromptTemplate.from_messages([<br>        MessagesPlaceholder(variable_name=&quot;chat_history&quot;),<br>        (&quot;user&quot;, &quot;{input}&quot;),<br>        (&quot;user&quot;, &quot;Given the above conversation, generate a search query to look up in order to get information relevant to the conversation&quot;)<br>    ])<br>    history_aware_retriever = create_history_aware_retriever(<br>        llm=model,<br>        retriever=retriever,<br>        prompt=retriever_prompt<br>    )<br><br><br>    retrieval_chain = create_retrieval_chain(<br>        # retriever, Replace with History Aware Retriever<br>        history_aware_retriever,<br>        chain<br>    )<br><br><br>    return retrieval_chain<br><br><br><br><br>def process_chat(chain, question, chat_history):<br>    response = chain.invoke({<br>        &quot;chat_history&quot;: chat_history,<br>        &quot;input&quot;: question,<br>    })<br>    return response[&quot;answer&quot;]<br><br><br>chain = create_chain(vectorStore)<br><br><br># Initialize chat history<br>chat_history = []<br><br>while True:<br>    user_input = input(&quot;You: &quot;)<br>    if user_input.lower() == &#39;exit&#39;:<br>        break<br>    response = process_chat(chain, user_input, chat_history)<br>    chat_history.append(HumanMessage(content=user_input))<br>    chat_history.append(AIMessage(content=response))<br>    print(&quot;Assistant:&quot;, response)</pre><h4>Gradio UI: Your Analysis, Simplified</h4><p>No AI is complete without an interface. Here’s a peek at how we used Gradio to create a user-friendly front-end:</p><pre>import gradio as gr<br><br><br>chat_history = []<br><br><br># Define a function that takes input and returns output<br>def greet(query):<br>    global chat_history  # Ensure chat_history is accessible and modified globally<br><br><br>    user_input = query<br>    response = process_chat(chain, user_input, chat_history)<br><br><br>    # Update chat history with the current interaction before returning the response<br>    chat_history.append(HumanMessage(content=user_input))<br>    chat_history.append(AIMessage(content=response))<br><br><br>    return response<br><br><br># Create an interface<br>iface = gr.Interface(<br>    fn=greet,<br>    inputs=&quot;text&quot;,<br>    outputs=&quot;text&quot;,<br>    title=&quot;Company Info Application&quot;,<br>    description=&quot;Write your queries about the company&quot;<br>)<br><br><br># Launch the interface<br>iface.launch()</pre><h4><strong>Output:</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*F3nNKK7Idbm7tuwa" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oQb1DZ87J4GXWE58" /></figure><h3>Conclusion</h3><p>This Competition Analysis AI stands as a testament to the transformative power of AI in business strategy.</p><p>It encapsulates the ability to turn vast arrays of data into actionable insights, offering businesses a competitive edge in understanding their market position.</p><p>If you’re here, do give me a <a href="https://medium.com/@iasarthak">follow on Medium</a> and connect with me on <a href="https://medium.com/@iasarthak">Linkedin</a> to chat more about Data Science!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4be006980d1d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Machine Learning for Classification: Quadratic Discriminant Analysis vs Logistic Regression]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/analytics-vidhya/machine-learning-for-classification-quadratic-discriminant-analysis-vs-logistic-regression-582dd748fe03?source=rss-36c6f05bdc37------2"><img src="https://cdn-images-1.medium.com/max/1280/1*fBAT5ZK8ncq8MFsdT2LXjw.jpeg" width="1280"></a></p><p class="medium-feed-snippet">Unmasking Quadratic Discriminant Analysis (QDA), its Assumptions and its Viability in today&#x2019;s Data Science Toolkit</p><p class="medium-feed-link"><a href="https://medium.com/analytics-vidhya/machine-learning-for-classification-quadratic-discriminant-analysis-vs-logistic-regression-582dd748fe03?source=rss-36c6f05bdc37------2">Continue reading on Analytics Vidhya »</a></p></div>]]></description>
            <link>https://medium.com/analytics-vidhya/machine-learning-for-classification-quadratic-discriminant-analysis-vs-logistic-regression-582dd748fe03?source=rss-36c6f05bdc37------2</link>
            <guid isPermaLink="false">https://medium.com/p/582dd748fe03</guid>
            <category><![CDATA[logistic-regression]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[classification-algorithms]]></category>
            <category><![CDATA[supervised-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Sarthak Arora]]></dc:creator>
            <pubDate>Sat, 08 Jul 2023 23:01:44 GMT</pubDate>
            <atom:updated>2023-07-25T08:06:00.313Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[What ‘not’ to do when you’re starting to learn Data Science]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/swlh/what-not-to-do-when-you-re-starting-to-learn-data-science-9f69385d9aa1?source=rss-36c6f05bdc37------2"><img src="https://cdn-images-1.medium.com/max/2600/1*EZQJDQx33irsLfb8Tqemjg.jpeg" width="12402"></a></p><p class="medium-feed-snippet">Richard Feynman, the great Physicist, has said that in order to understand a subject, understand its fundamentals to a level that you can&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/swlh/what-not-to-do-when-you-re-starting-to-learn-data-science-9f69385d9aa1?source=rss-36c6f05bdc37------2">Continue reading on The Startup »</a></p></div>]]></description>
            <link>https://medium.com/swlh/what-not-to-do-when-you-re-starting-to-learn-data-science-9f69385d9aa1?source=rss-36c6f05bdc37------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f69385d9aa1</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[jobs]]></category>
            <category><![CDATA[freshers]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Sarthak Arora]]></dc:creator>
            <pubDate>Thu, 13 May 2021 07:59:20 GMT</pubDate>
            <atom:updated>2022-03-15T15:00:27.097Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[The Lazy Learning Algorithm-KNN]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://iasarthak.medium.com/the-lazy-learning-algorithm-knn-8faab9e13c94?source=rss-36c6f05bdc37------2"><img src="https://cdn-images-1.medium.com/max/2600/1*EVQV7R8Ur4ZH9OvSE__N5Q.png" width="3969"></a></p><p class="medium-feed-snippet">You must be aware why are we being advised to stay at least 6 ft. away from other people whenever we go out? It&#x2019;s being said that the&#x2026;</p><p class="medium-feed-link"><a href="https://iasarthak.medium.com/the-lazy-learning-algorithm-knn-8faab9e13c94?source=rss-36c6f05bdc37------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://iasarthak.medium.com/the-lazy-learning-algorithm-knn-8faab9e13c94?source=rss-36c6f05bdc37------2</link>
            <guid isPermaLink="false">https://medium.com/p/8faab9e13c94</guid>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Sarthak Arora]]></dc:creator>
            <pubDate>Wed, 06 Jan 2021 04:12:39 GMT</pubDate>
            <atom:updated>2023-07-24T03:41:54.527Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[An Efficient way of performing EDA- Hypothesis Generation]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://iasarthak.medium.com/an-efficient-way-of-performing-eda-hypothesis-generation-7054a60dbd0c?source=rss-36c6f05bdc37------2"><img src="https://cdn-images-1.medium.com/max/1050/1*CLBcrQh3ecVo9b5BZ63J0w.jpeg" width="1050"></a></p><p class="medium-feed-snippet">How Hypothesis generation can help you understand your data in a quicker manner and speed up your modelling process?</p><p class="medium-feed-link"><a href="https://iasarthak.medium.com/an-efficient-way-of-performing-eda-hypothesis-generation-7054a60dbd0c?source=rss-36c6f05bdc37------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://iasarthak.medium.com/an-efficient-way-of-performing-eda-hypothesis-generation-7054a60dbd0c?source=rss-36c6f05bdc37------2</link>
            <guid isPermaLink="false">https://medium.com/p/7054a60dbd0c</guid>
            <category><![CDATA[data]]></category>
            <category><![CDATA[exploratory-data-analysis]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[thinking]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Sarthak Arora]]></dc:creator>
            <pubDate>Fri, 06 Nov 2020 14:50:13 GMT</pubDate>
            <atom:updated>2022-03-15T15:00:58.874Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Data Science Is for Everyone]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/swlh/data-science-is-for-everyone-ad712ae22e5f?source=rss-36c6f05bdc37------2"><img src="https://cdn-images-1.medium.com/max/1050/1*amNwyl4S1oWStws9aqc4kg.jpeg" width="1050"></a></p><p class="medium-feed-snippet">How learning Data Science techniques can help you improve your daily life even if you don&#x2019;t want to pursue it as a career?</p><p class="medium-feed-link"><a href="https://medium.com/swlh/data-science-is-for-everyone-ad712ae22e5f?source=rss-36c6f05bdc37------2">Continue reading on The Startup »</a></p></div>]]></description>
            <link>https://medium.com/swlh/data-science-is-for-everyone-ad712ae22e5f?source=rss-36c6f05bdc37------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad712ae22e5f</guid>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[visualization]]></category>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Sarthak Arora]]></dc:creator>
            <pubDate>Wed, 30 Sep 2020 07:21:36 GMT</pubDate>
            <atom:updated>2022-03-15T14:59:49.423Z</atom:updated>
        </item>
    </channel>
</rss>