<?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 Ratnesh Dagli on Medium]]></title>
        <description><![CDATA[Stories by Ratnesh Dagli on Medium]]></description>
        <link>https://medium.com/@dagliratnesh02?source=rss-1cc539547207------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*o1OxKnE8uQ5ipuDH</url>
            <title>Stories by Ratnesh Dagli on Medium</title>
            <link>https://medium.com/@dagliratnesh02?source=rss-1cc539547207------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 15:54:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dagliratnesh02/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[How to Improve Your Research Paper RAG Chatbot: Code Snippets for Smarter Retrieval]]></title>
            <link>https://medium.com/@dagliratnesh02/how-to-improve-your-research-paper-rag-chatbot-code-snippets-for-smarter-retrieval-d5a72fb3642e?source=rss-1cc539547207------2</link>
            <guid isPermaLink="false">https://medium.com/p/d5a72fb3642e</guid>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Ratnesh Dagli]]></dc:creator>
            <pubDate>Sun, 12 Oct 2025 14:31:12 GMT</pubDate>
            <atom:updated>2025-10-12T14:31:12.097Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>So, you’ve built a basic Retrieval-Augmented Generation (RAG) chatbot. It’s a powerful tool, but when you start feeding it dense, technical documents like research papers, you quickly hit its limits.</p><p>Maybe you’re seeing some of these common issues:</p><ul><li>It pulls up text chunks that are only vaguely related to the query.</li><li>It can’t connect the dots between different papers.</li><li>You find yourself correcting the same mistakes over and over.</li><li>The answers feel generic, or worse, completely made up.</li></ul><p>If that sounds familiar, you’re in the right place. This guide is a hands-on, code-focused walkthrough to fix these problems.</p><p>We’ll go through incremental, easy-to-implement code snippets to sharpen your bot’s retrieval accuracy. By the end, you’ll have clear “Before vs. After” comparisons that show the real-world impact of each improvement, turning your simple chatbot into a much smarter research assistant.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*tddAibUPdsAQa16KIDAkRA.png" /></figure><h3>Prerequisites</h3><p>Before we dive in, let’s get our environment set up. You should have a working Python environment with the following libraries installed. We’re using LangChain, Streamlit, and Groq for fast inference, but the principles here are transferable to other stacks.</p><pre>pip install streamlit langchain langchain-groq langchain-community pypdf faiss-cpu rank-bm25 sentence-transformers chromadb</pre><p>You’ll also need an API key from Groq to get this running.</p><h3>Baseline: A Simple Streamlit Research Paper Chatbot</h3><p>Let’s start with a standard, functional Streamlit application. This is our foundation. It lets a user plug in their API key, upload a PDF, and then it chunks, embeds, and stores the text in a FAISS vector store for retrieval.</p><p><strong>Here’s the rundown of its parts:</strong></p><ul><li><strong>API Key Management:</strong> A simple input in the Streamlit sidebar.</li><li><strong>Load:</strong> PyPDFLoader to read the uploaded PDF.</li><li><strong>Split:</strong> RecursiveCharacterTextSplitter to break the document into manageable chunks.</li><li><strong>Embed:</strong> HuggingFaceEmbeddings to create vector representations locally.</li><li><strong>Store:</strong> FAISS for a local, in-memory vector database.</li><li><strong>Memory:</strong> ConversationBufferMemory to remember chat history for follow-up questions.</li><li><strong>Chain:</strong> ConversationalRetrievalChain to manage the whole Q&amp;A process. The <strong>retriever</strong> inside this chain is what we’ll be upgrading.</li><li><strong>LLM:</strong> ChatGroq for fast language model inference with Llama 3</li></ul><p>Chatbot code-<a href="https://github.com/ratneshdagli/DocQna_CHATBOT">https://github.com/ratneshdagli/DocQna_CHATBOT</a></p><p><strong>Baseline Output Example:</strong></p><ul><li><strong>Query:</strong> “What is the core idea of the RAG paper?”</li><li><strong>Basic Answer:</strong> “Retrieval-Augmented Generation (RAG) is a model that combines a retriever with a generator to answer questions. The retriever finds relevant documents, and the generator uses them to create an answer.”</li></ul><p>It’s not wrong, but it’s pretty shallow. We can do much better.</p><h3>Improvement 1: Hybrid Retrieval (Keyword + Semantic Search)</h3><p><strong>Method:</strong> At the heart of a RAG system is retrieval, and there are two main ways to tackle it. Each has its own blind spots.</p><ol><li><strong>Semantic Search (The Concept Librarian):</strong> This is the modern RAG workhorse. It uses embeddings to understand the <em>meaning</em> of your text. You ask a conceptual question, and it finds text that means the same thing, even with different words. It’s powerful, but sometimes it’s too fuzzy and can glide right past a critical, specific formula or term.</li><li><strong>Keyword Search (The ‘Ctrl+F’ Assistant):</strong> This is old-school, literal search. It finds the exact characters you typed. It’s perfect for pulling up a specific function name or a person’s name. The downside? It has zero understanding of context.</li></ol><p>Research papers are a mix of complex ideas and precise, literal terms. Relying on just one of these methods is a losing game. The fix is <strong>Hybrid Retrieval</strong> — using both at the same time to get the best of both worlds.</p><p><strong>Purpose:</strong> This technique drastically improves the retrieval of exact phrases and terminology that pure semantic search often misses, without losing the ability to understand broader concepts.</p><p>Code Snippet:</p><pre># 1. Initialize BM25 (keyword) retriever from your documents<br>bm25_retriever = BM2Retriever.from_documents(splits)<br><br># 2. Initialize your standard vector store retriever (e.g., from FAISS)<br># faiss_retriever = ...<br><br># 3. Initialize Ensemble Retriever to combine them<br>ensemble_retriever = EnsembleRetriever(<br>    retrievers=[bm25_retriever, faiss_retriever],<br>    weights=[0.5, 0.5]<br>)</pre><p>Chatbot_link-<a href="https://github.com/ratneshdagli/DocQna_CHATBOT">https://github.com/ratneshdagli/DocQna_CHATBOT</a></p><p><strong>Before vs. After:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*DldGZUOmo9iaPABlruE9Nw.png" /></figure><h3>Improvement 2: HyDE for Better Query Understanding</h3><p><strong>Method:</strong> Here’s a classic RAG problem: the “vocabulary mismatch.” A user asks a simple question like, “why do GANs fail?”, but the answer is buried in a dense paragraph using technical language like “generator sample diversity reduction.” The chatbot looks for the user’s simple phrase and comes up empty.</p><p><strong>HyDE (Hypothetical Document Embeddings)</strong> is a clever workaround. Instead of searching with the user’s short query, it flips the script:</p><ol><li><strong>Generate a Fake Answer:</strong> It first sends the user’s query to an LLM with a prompt like: “Generate a perfect, textbook-style answer to this question, even if you have to make something up.”</li><li><strong>Use the Fake Answer to Search:</strong> The LLM produces a detailed paragraph packed with the kind of keywords and technical phrases you’d expect to find in the real document. The chatbot then uses this <em>hypothetical</em> answer to do the semantic search.</li><li><strong>Find the Real Answer:</strong> This hypothetical answer is a much better “lure” for finding the actual, relevant paragraphs in the source document because it speaks the same language.</li></ol><p>It’s like asking a librarian for a book you only vaguely remember. The librarian imagines what the book’s full summary <em>might</em> be, uses that to search the catalog, and it leads them right to the real thing.</p><h3>Making HyDE Safer</h3><p>A word of caution, though. This technique can backfire if the LLM’s hypothetical answer is plausible but wrong. To use it safely:</p><ul><li><strong>Set low temperature:</strong> Use temperature=0 in your LLM call to keep the output factual and less creative.</li><li><strong>Limit output tokens:</strong> Keep the hypothetical document short and to the point.</li><li><strong>Never show the HyDE document:</strong> This is a tool for retrieval, not a source of truth. It should never be shown to the user.</li></ul><p><strong>Purpose:</strong> HyDE transforms a short user query into a rich, hypothetical document that’s more likely to match the style and content of the source material, leading to better search results</p><p><strong>Code Snippet:</strong></p><pre>from langchain_core.prompts import ChatPromptTemplate<br>from langchain_core.output_parsers import StrOutputParser<br>from langchain_groq import ChatGroq<br><br># 1. Initialize a &quot;safer&quot; LLM for HyDE generation<br>hyde_llm = ChatGroq(temperature=0, model_name=&quot;llama3-8b-8192&quot;)<br><br># 2. Create a prompt to generate a hypothetical answer<br>hyde_template = &quot;&quot;&quot;Even if you do not know the answer, please generate a plausible answer to the following question.<br>Question: {question}<br>Answer:&quot;&quot;&quot;<br>hyde_prompt = ChatPromptTemplate.from_template(hyde_template)<br><br># 3. Create a chain to generate the hypothetical document<br>hyde_chain = hyde_prompt | hyde_llm | StrOutputParser()<br><br># 4. Use the output of hyde_chain to retrieve documents<br># retrieved_docs = retriever.get_relevant_documents(hyde_chain.invoke(query))</pre><p>Chatbot_link-<a href="https://github.com/ratneshdagli/DocQna_CHATBOT">https://github.com/ratneshdagli/DocQna_CHATBOT</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*_u1EfnVu_fU0wtSGC41tzw.png" /></figure><h3>Improvement 3: Metadata Filtering</h3><p><strong>Method:</strong> This next technique is less about a fancy algorithm and more about good old-fashioned organization. Think of it this way: imagine a library where none of the books have labels on their spines. To find a book from after 2020, you’d have to pull every single one off the shelf. That’s what a basic RAG system does.</p><p><strong>Metadata</strong> is the solution — it’s the label on the spine that gives you the title, author, and publication year. By attaching these labels to every chunk of text we process, we can perform <strong>pre-filtering</strong>. When a user asks, “What are the latest developments… since 2022?”, the system can instantly ignore every chunk from a document with a publication_year before 2022.</p><p><strong>Important Note:</strong> Here’s the catch, though: your standard FAISS vector store can’t do this. You need a vector database that does. A great, lightweight option to start with is ChromaDB. The code below shows how to use it.</p><p><strong>Purpose:</strong> This allows the chatbot to narrow its search to only the most relevant documents <em>before</em> doing the expensive vector search, making it faster and far more accurate.</p><p>Code Snippet:</p><p>First, you add metadata when creating documents. Then, you use a vector store like Chroma that can use it in a filter</p><pre>from langchain.docstore.document import Document<br>from langchain_community.vectorstores import Chroma<br># 1. First, add metadata when you create your documents<br>docs_with_metadata = []<br>for split in splits:<br>    new_doc = Document(<br>        page_content=split.page_content,<br>        metadata={<br>            &quot;publication_year&quot;: 2023,<br>            &quot;author&quot;: &quot;Vaswani et al.&quot;<br>        }<br>    )<br>    docs_with_metadata.append(new_doc)<br># 2. Create a Chroma vector store with the new documents<br>vectorstore = Chroma.from_documents(docs_with_metadata, embeddings)<br># 3. Then, use the filter directly in the retriever call<br>retriever = vectorstore.as_retriever(<br>    search_kwargs={&#39;filter&#39;: {&#39;publication_year&#39;: {&#39;$gte&#39;: 2022}}}<br>)</pre><p>Chatbot_link-<a href="https://github.com/ratneshdagli/DocQna_CHATBOT">https://github.com/ratneshdagli/DocQna_CHATBOT</a></p><p><strong>Before vs. After:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*FGqFX5vUDNG-NMgxxOeksQ.png" /></figure><h3>Improvement 4: Multi-Hop Reasoning (Comparing Papers)</h3><p><strong>Method:</strong> A basic RAG system has a one-track mind. If you ask a complex question like “Compare the pros of apples to the cons of oranges,” it’s likely to just search for “apples” and call it a day, completely ignoring the second half of your question.</p><p>This is where <strong>multi-hop reasoning</strong> comes in. It teaches the chatbot to think like a researcher. It breaks a big, complex question into smaller, manageable pieces, finds the answer to each one, and then combines that knowledge to form a complete, final answer. Here’s how it works:</p><ol><li><strong>Decompose (The Planner):</strong> The system first uses an LLM as a “planner.” It looks at the complex query (“Compare BERT vs. GPT-2”) and creates a to-do list of simple, standalone questions, like:</li></ol><ul><li>“What are the evaluation metrics for the BERT paper?”</li><li>“What are the evaluation metrics for the GPT-2 paper?”</li></ul><p><strong>2. Retrieve in Parallel (The Interns):</strong> It then sends out “interns” to find the info for each simple question at the same time. One intern looks for BERT’s metrics, another looks for GPT-2’s.</p><p><strong>3. Synthesize (The Lead Researcher):</strong> Finally, all the retrieved information is handed to a “lead researcher” (another LLM call). This final step takes all the separate pieces of context and writes a single, coherent answer that directly addresses the user’s original, complex query.</p><p>The code snippet below shows how to build the “Planner” (Step 1). A full implementation would then need to execute a retrieval for each of those questions and feed the combined results into a final prompt for synthesis.</p><p><strong>Purpose:</strong> This gives the chatbot the ability to answer complex, comparative questions that a single search pass could never handle.</p><p>Code Snippet:</p><pre>This snippet shows the first step of generating sub-questions. A full implementation requires chaining these steps together.<br>from langchain_core.output_parsers import JsonOutputParser<br>from langchain_core.prompts import ChatPromptTemplate<br><br># 1. Chain to generate sub-questions from the original query<br>sub_question_template = &quot;&quot;&quot;<br>You are a helpful assistant who generates stand-alone questions from a complex user query.<br>Generate a JSON object containing a list of 2-3 sub-questions...<br><br>User Query: {query}<br>&quot;&quot;&quot;<br>sub_question_prompt = ChatPromptTemplate.from_template(sub_question_template)<br>sub_question_chain = sub_question_prompt | llm | JsonOutputParser()<br><br># 2. Invoke chain to get sub-questions.<br># sub_questions = sub_question_chain.invoke({&quot;query&quot;: original_query})[&#39;questions&#39;]<br><br># 3. The next step is to create a more complex chain that:<br>#    a. Runs the sub_question_chain.<br>#    b. For each generated sub-question, runs your retriever.<br>#    c. Gathers all retrieved documents.<br>#    d. Passes the original query and all documents to a final prompt for synthesis.</pre><p>Chatbot_link-<a href="https://github.com/ratneshdagli/DocQna_CHATBOT">https://github.com/ratneshdagli/DocQna_CHATBOT</a></p><p><strong>Before vs. After:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*hqKfOSvq2N8hTkrW_WGohQ.png" /></figure><h3>Conclusion</h3><p>So there you have it. We’ve walked through a series of upgrades to take our baseline RAG bot from a simple retriever to a much more sophisticated research assistant.</p><p>We’ve combined keyword and semantic search for precision, used HyDE to bridge the vocabulary gap between user and document, filtered results with metadata for relevance, and enabled multi-hop reasoning to tackle complex questions.</p><h3>Next Steps:</h3><p>Where do you go from here? The real fun is in experimenting.</p><ul><li>Try adding different kinds of metadata, like section titles or figure captions.</li><li>Play with the weights in the EnsembleRetriever to see what works best for your documents.</li><li>Build out a more permanent solution for a failure-memory loop.</li></ul><h3>Future Directions:</h3><p>And if you want to push things even further, you could explore automated table extraction, linking citations between documents, or generating structured JSON summaries instead of plain text. The possibilities are wide open.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5a72fb3642e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>