<?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 stefanoz on Medium]]></title>
        <description><![CDATA[Stories by stefanoz on Medium]]></description>
        <link>https://medium.com/@stefanoz?source=rss-60f0eba3a328------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*oY-5dtrLyt5qB87rQmDJoQ.jpeg</url>
            <title>Stories by stefanoz on Medium</title>
            <link>https://medium.com/@stefanoz?source=rss-60f0eba3a328------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 12:14:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@stefanoz/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[Beyond Naive RAG: How an Iterative Self-Correction Loop Turns Retrieval into a Thinking Process]]></title>
            <link>https://medium.com/@stefanoz/beyond-naive-rag-how-an-iterative-self-correction-loop-turns-retrieval-into-a-thinking-process-f759fe213bd6?source=rss-60f0eba3a328------2</link>
            <guid isPermaLink="false">https://medium.com/p/f759fe213bd6</guid>
            <category><![CDATA[agentic-rag]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[stefanoz]]></dc:creator>
            <pubDate>Sun, 07 Jun 2026 14:31:45 GMT</pubDate>
            <atom:updated>2026-06-07T14:31:45.170Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Most RAG implementations are a one-shot bet.</strong> You embed a query, pull the top-K chunks from a vector store, stuff them into an LLM prompt, and hope the context was good enough. Sometimes it is. Often it isn’t — and the LLM either hallucinates to fill the gaps or politely admits it doesn’t know. Neither is acceptable in a production system where the quality of the retrieved context is the foundation of every answer.</p><blockquote>The Agentic RAG pattern I’ll describe here solves this with a surprisingly elegant idea: treat retrieval as a feedback loop, not a one-shot operation. The system retrieves, evaluates what it got, decides if it’s enough, and — if not — refines the query and tries again. Up to three times. And it never throws away what it already found.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/1*2mw1Lof4kY4geK6XOCIgFw.png" /></figure><h3>The Problem with Standard RAG</h3><p>Standard RAG has two fundamental weaknesses that compound each other.</p><p>The first is <strong>query brittleness</strong>. A user rarely phrases their question in the exact vocabulary used in your knowledge base. “What are the security obligations for data processors?” and “Which technical measures must a data processor implement?” mean the same thing, but a cosine similarity search may rank them very differently against the same corpus. You’re one rephrasing away from a completely different result set.</p><p>The second is silent failure. Standard RAG has no mechanism to know whether the retrieved context is actually useful. It retrieves blindly, passes whatever it finds to the LLM, and lets the model figure it out. There’s no checkpoint, no validation, no second chance.</p><blockquote><strong>Agentic RAG addresses both.</strong></blockquote><h3>The Architecture: Four Cooperating Agents</h3><p>The system is built from four small, focused components that pass control to each other in a loop.</p><h3>1. The Query Expansion Agent</h3><p>Before any retrieval happens, the original user query is handed to a lightweight LLM agent whose only job is to think about the question from multiple angles. It produces three to five semantic variants of the query, plus a set of extracted keywords. These aren’t random paraphrases — they’re strategically different reformulations designed to hit different parts of the embedding space.</p><p>For example, a query like <em>“What logging requirements apply to critical infrastructure operators?”</em> might expand into:</p><ul><li><em>“Audit trail obligations for essential service providers”</em></li><li><em>“Event logging and monitoring requirements under security frameworks”</em></li><li><em>“Record-keeping duties for operators of critical systems”</em></li><li>Keywords: logging, audit trail, monitoring, critical infrastructure, obligations</li></ul><p>Each variant represents a different angle of the same information need. The retrieval step runs all of them.</p><h3>2. The Hybrid Retriever</h3><p>For each query variant, retrieval is performed twice in parallel: once with dense vectors (semantic similarity via embeddings) and once with sparse vectors (keyword matching, similar to BM25). The results from both methods, across all query variants, are merged and deduplicated by ID.</p><p>This hybrid approach is important. Dense retrieval finds conceptually related content even when phrasing differs. Sparse retrieval catches exact terminology that embeddings might underweight. Together they cover the spectrum between meaning and vocabulary. The merged set becomes the accumulated context for the evaluation step.</p><h3>3. The Context Evaluation Agent</h3><p>This is the heart of the self-correction loop. After retrieval, a dedicated evaluator agent reads the accumulated results and asks a structured question: <em>“Is this context actually sufficient to answer the original query?”</em></p><p>It produces a typed output with four fields:</p><ul><li>is_sufficient: a boolean decision</li><li>relevance_score: a float between 0 and 1</li><li>missing_aspects: a list of specific things the context doesn’t cover</li><li>suggestions: concrete hints for improving the next retrieval attempt</li></ul><p>The critical detail: the evaluator looks at the original query alongside the retrieved content. It’s not just scoring individual chunks in isolation — it’s reasoning about the gap between what the user asked and what the system found.</p><h3>4. The Query Refinement Step</h3><p>If the evaluator says the context isn’t sufficient, the system doesn’t restart from scratch. It takes the missing_aspects from the evaluation and generates a refined query that specifically targets what’s still missing. The new retrieval adds to the accumulated results — it never replaces them.</p><blockquote>This accumulation strategy is deliberate. If iteration 1 retrieved good content about topic <strong>A</strong> but missed topic <strong>B</strong>, iteration 2 targets topic <strong>B</strong> while keeping topic <strong>A</strong> as results. By the time the loop ends, the context is the union of the best results across all iterations.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/647/1*c3xPqfRa_4Ji2Gb9rxdjXw.png" /><figcaption>four step</figcaption></figure><p>The loop runs a maximum of three times. If three iterations aren’t enough to reach a satisfactory relevance score, the system answers on the best available context rather than returning an error. Degrading gracefully is better than failing loudly.</p><h3>Why Accumulation Matters More Than You’d Think</h3><p>The choice to accumulate rather than replace results across iterations is subtle but important. Consider this scenario:</p><ul><li>Iteration 1: retrieves excellent coverage of the legal framework but nothing about technical implementation details</li><li>Iteration 2 (refined query targeting implementation): retrieves good technical content but redundant legal content</li></ul><p>A naive system would discard iteration 1’s results and answer only from iteration 2. The accumulating system keeps both, deduplicates by ID, and presents the LLM with the full picture.</p><p>This transforms the retrieval loop from <em>“try again and hope for better”</em> into <em>“progressively build a more complete context”</em>.</p><h3>The Role of Chat History</h3><p>The final answer generation isn’t stateless either. The Answer Generator agent carries conversation history across turns — the last several exchanges are included in every prompt. This means the system can answer follow-up questions coherently without the user needing to repeat context.</p><p>The session is identified by a unique ID, stored in a local SQLite database, and the history is loaded automatically at answer generation time. From the user’s perspective, it feels like talking to someone who remembers what was said five messages ago. Technically, it’s just structured prompt construction — but the experience difference is significant.</p><h3>The Deeper Principle</h3><p>Standard RAG asks: <em>“What is most similar to this query?”</em></p><p>Agentic RAG asks: <em>“Do I have enough to answer this question well — and if not, what specifically am I missing?”</em></p><p>That shift — from similarity matching to sufficiency reasoning — is what makes retrieval feel less like a database lookup and more like a research process. The system doesn’t just find; it evaluates, refines, and persists until it has what it needs.</p><p>If you’re building anything where retrieval quality determines answer quality, this loop is worth the extra complexity. The infrastructure to implement it is small: one evaluator agent, one accumulating result set, and a loop counter. The payoff in answer reliability is substantial.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f759fe213bd6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Paying Twice for the Same Document: A Four-Gate Semantic Deduplication Pattern for LLM…]]></title>
            <link>https://medium.com/@stefanoz/stop-paying-twice-for-the-same-document-a-four-gate-semantic-deduplication-pattern-for-llm-2e8883be3d8a?source=rss-60f0eba3a328------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e8883be3d8a</guid>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[clustering-algorithm]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[data-deduplication]]></category>
            <category><![CDATA[cosine-similarity]]></category>
            <dc:creator><![CDATA[stefanoz]]></dc:creator>
            <pubDate>Sun, 07 Jun 2026 14:19:02 GMT</pubDate>
            <atom:updated>2026-06-07T14:19:02.783Z</atom:updated>
            <content:encoded><![CDATA[<h3>Stop Paying Twice for the Same Document: A Four-Gate Semantic Deduplication Pattern for LLM Pipelines</h3><blockquote>If you’re building a document processing system powered by LLMs, you’re going to run into this problem sooner or later. Your users will upload the same document twice. Or an updated version of it. Or two documents that describe the same thing in slightly different words. And every time that happens, your pipeline will happily re-analyse it — burning tokens, adding latency, and polluting your vector store with near-identical entries.</blockquote><p>I ran into this exact problem while building an AI-powered compliance analysis system that processes company documents (contracts, policies, privacy notices) and runs deep gap analysis against regulatory frameworks. The pipeline is expensive per document — it involves multiple LLM calls, vector retrieval, and structured output generation. Letting duplicates slip through wasn’t just wasteful; it was progressively breaking the quality of the results stored in the database.</p><p>Here’s how I solved it. :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*F-iuUhqF38CYoRgr" /><figcaption>deduplication data</figcaption></figure><h3>The Problem in Concrete Terms</h3><p>Imagine a pipeline that processes a company’s documents and extracts structured <em>items</em> from them — things like “payroll data processing activity” or “data retention policy for HR files”. For each item, the system runs a full LLM-powered analysis and stores the results in a vector database (Qdrant in my case).</p><p>Now imagine the same company uploads documents every month. Or uploads both their privacy policy and their internal governance charter, which both mention the same data processing activities. Without deduplication, you end up with:</p><ul><li>Multiple identical analyses for the same real-world concept</li><li>Inflated costs, since every duplicate triggers another round of retrieval + LLM inference</li><li>Inconsistent results in your database, because the same item analyzed twice may get slightly different findings</li><li>A growing noise problem: future RAG queries start pulling duplicates instead of the best available answer</li></ul><p>The naive fix — checking for exact string matches — doesn’t work here. The same concept rarely appears with identical wording across different documents. You need <em>semantic</em> deduplication.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/461/1*7k8AxRBjbC1aEwzvn7A81Q.png" /><figcaption>naive approach</figcaption></figure><h3>The Solution: Four Gates, Ordered by Cost</h3><p>The key insight is that deduplication should be layered, and each layer should be cheaper than the one it precedes. You want to eliminate duplicates as early as possible, before you spend compute on them.</p><p>Here’s the architecture I landed on:</p><p><strong>Gate 1: SHA-256 File Hash (Cost: ~zero)</strong></p><p>The first check is purely byte-level: if the exact same file has been uploaded before (same hash), skip it entirely. No ML inference, no DB query , just a hash comparison against stored metadata. This handles the most obvious case: someone uploads the same PDF twice.</p><p><strong>Gate 2: In-Batch Cosine Similarity (Cost: one embedding pass, no API calls)</strong></p><p>When multiple files arrive in the same upload batch, they all get processed through a local embedding model first (<a href="https://huggingface.co/Alibaba-NLP/gte-multilingual-base">gte-multilingual-base</a> in my case, running entirely local via sentence-transformers). For every extracted item across all files, I compute an identity text — a short string combining the item&#39;s name and description — and embed it. Then I run pairwise cosine similarity across all items.</p><p>If two items from <em>different files</em> score above a threshold (0.88 in my setup), they’re considered duplicates. Only one survives — specifically, the one from the most recently uploaded file. The intuition: you don’t have gap analysis results yet, so recency is the best proxy for quality.</p><p>The clustering uses a Union-Find (disjoint-set) algorithm, which handles transitive duplicates efficiently: if A ≈ B and B ≈ C, all three collapse into one cluster.</p><p><strong>Gate 3: Qdrant Resolve (Cost: one embedding pass + one DB scan, no API calls)</strong></p><p>Before triggering any LLM work on the batch survivors, we check whether any of them already exist in the vector store from a <em>previous</em> upload. This is where it gets interesting.</p><p>The naive approach would be to compare new item vectors against stored vectors. But this doesn’t work cleanly — stored vectors were computed from the full item context including the gap analysis text, which is verbose and dominated by regulatory vocabulary. Two completely different items could have high vector similarity simply because they both mention GDPR Articles 5 and 32.</p><p>The solution: <strong>re-embed only the identity text</strong> (name + description) for both new and existing items, creating a fresh, minimal embedding in a consistent space. Then compare those. This is a <strong>dual-embedding strategy</strong>: one vector for retrieval quality (stored, full-context), one vector for identity comparison (computed on demand, minimal-context).</p><p>Any existing Qdrant point that matches above threshold gets its ID marked for deletion — <em>after</em> the new analysis is saved.</p><p><strong>Gate 4: Cross-Document LLM Merge (Cost: one LLM call per cluster)</strong></p><p>Even after all three previous gates, you can end up with semantically equivalent items that survived because they come from genuinely different documents with complementary analysis. Gate 4 runs <em>after</em> saving new analyses. It scans the collection for cross-document duplicate clusters and consolidates them.</p><p>For each cluster, an LLM agent receives all the findings from all source documents and merges them into a single enriched report. The merge rules are explicit and strict: never downgrade a gap (worst-case status always wins), keep all unique logical areas, combine complementary evidence into richer findings.</p><p>If the LLM call fails, a <strong>deterministic fallback</strong> kicks in: a pure Python function that unions all findings and applies worst-case selection by status and severity rank. The system degrades predictably, not silently.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/998/1*s24kcZjS2lgQD0AgfKY2tw.png" /><figcaption>The four gate</figcaption></figure><h3>The “Save First, Delete After” Protocol</h3><p>One pattern worth calling out explicitly: the pipeline always <strong>saves the new analysis before deleting the old one.</strong> The IDs of superseded points are carried forward in a lightweight wrapper object throughout the pipeline and only acted on after the new point is confirmed in the database.</p><p>This might seem obvious, but it’s easy to get wrong under time pressure. A reversed order — delete first, then save — creates a window where no valid analysis exists for an item. In a compliance context (or any context where data integrity matters), that’s unacceptable.</p><h3>Why This Matters Beyond Compliance</h3><p>The problem this solves is completely general. Any pipeline that:</p><ul><li>Processes documents repeatedly over time</li><li>Extracts structured entities from unstructured text</li><li>Stores those entities in a vector database</li><li>Uses LLMs for expensive per-entity analysis</li></ul><p>…will eventually face the same challenge. Think: invoice processing, contract analysis, knowledge base ingestion, customer support ticket deduplication, or any RAG system fed by a continuously updated corpus.</p><p>The four-gate pattern works because it respects the cost hierarchy: eliminate the cheap duplicates first, pay for the expensive analysis only on genuinely new content. The dual-embedding strategy for identity comparison is reusable anywhere you have full-context vectors that you don’t want to use for identity matching.</p><h3>Technologies at a Glance</h3><ul><li>Qdrant — vector store with payload filtering and scroll API for full-collection scans</li><li>sentence-transformers — local embedding model for identity vectors (no API dependency)</li><li>scikit-learn — cosine similarity matrix computation</li><li>Union-Find — classic graph algorithm for transitive cluster detection</li><li>Pydantic — typed wrapper objects that carry dedup metadata through the pipeline</li><li>instructor — structured LLM output for the merge step, with Agno as primary path</li></ul><h3>The Takeaway</h3><p>The most important engineering decision in this system wasn’t choosing the right LLM or the right vector database. It was deciding <em>when not to call them at all</em>.</p><p>Good deduplication is a form of caching with semantic awareness and building it in layers, ordered by cost, is the pattern that makes it practical at scale. If you’re building a document processing pipeline today, design your dedup gates before you design your analysis pipeline. You’ll thank yourself on the first re-upload.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e8883be3d8a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MOST POPULARS IMPLEMENTATIONS OF RAG]]></title>
            <link>https://medium.com/@stefanoz/most-populars-implementations-of-rag-8596924bc421?source=rss-60f0eba3a328------2</link>
            <guid isPermaLink="false">https://medium.com/p/8596924bc421</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[stefanoz]]></dc:creator>
            <pubDate>Mon, 11 Nov 2024 17:48:00 GMT</pubDate>
            <atom:updated>2024-11-11T17:48:00.107Z</atom:updated>
            <content:encoded><![CDATA[<p>In this post, we’ll delve into the most populars RAG (Retrieval-Augmented Generation) implementations of used today.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eLbo2DOZUPUGrtDoMwxqkA.png" /><figcaption>RAG</figcaption></figure><p>Large Language Models (LLMs) showcase impressive capabilities but encounter challenges like hallucination, outdated knowledge, and non-transparent, untraceable reasoning processes. Retrieval-Augmented Generation (RAG) has emerged as a promising solution by incorporating knowledge from external databases. This enhances the accuracy and credibility of the generation, particularly for knowledge-intensive tasks, and allows for continuous knowledge updates and integration of domain-specific information. RAG merges LLMs’ intrinsic knowledge with the vast, dynamic repositories of external databases. This comprehensive review paper offers a detailed examination of the progression of RAG paradigms, encompassing the <strong>Standard RAG, the Corrective RAG, the Speculative RAG, the Fusion RAG, the Self RAG and MEMO RAG.</strong></p><h3><strong>1. STANDARD RAG</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*z-4aKMcVGeXafqdj6-hU7w.png" /><figcaption>STANDARD RAG</figcaption></figure><blockquote>Naive Retrieval-Augmented Generation (RAG) is the foundational architecture within the broader RAG framework, designed to enhance the capabilities of large language models (LLMs) by integrating external knowledge sources. Here’s a detailed overview of its workings and significance.</blockquote><h4>How Naive RAG Works</h4><p>Naive RAG operates through a straightforward three-step process:</p><ol><li><strong>Indexing</strong>:</li></ol><ul><li>The system collects information from various sources, including internal documents and online content, which may come in different formats such as PDFs or text files.</li><li>This information is then segmented into smaller chunks, encoded into vector representations, and stored in a vector database for efficient retrieval.</li></ul><p><strong>2. Retrieving</strong>:</p><ul><li>When a user submits a query, the system encodes this question into a vector using the same embedding model that was used for indexing.</li><li>It performs a similarity search against the vector database to find the most relevant chunks that align with the query.</li></ul><p><strong>3. Generating</strong>:</p><ul><li>The retrieved chunks are combined with the original user query and fed into an LLM to generate a coherent response.</li><li>This process may also consider conversation history in interactive settings to maintain context continuity.</li></ul><h4>Strengths of Naive RAG</h4><ul><li><strong>Simplicity</strong>: The architecture is easy to implement and understand, making it accessible for various applications.</li><li><strong>Real-Time Updates</strong>: By pulling in fresh information from external sources, Naive RAG can provide responses based on current data rather than relying solely on pre-trained knowledge.</li></ul><h4>Limitations of Naive RAG</h4><p>Despite its advantages, Naive RAG also faces several challenges:</p><ul><li><strong>Retrieval Challenges</strong>: Issues with precision and recall can lead to irrelevant or misaligned chunks being retrieved, resulting in incomplete or incorrect answers.</li><li><strong>Generation Challenges</strong>: The model may produce “hallucinations,” where it generates information not present in the retrieved documents.</li><li><strong>Complex Queries</strong>: Naive RAG struggles with complex queries that require nuanced understanding since it relies on a single retrieval step, which may not capture all necessary context.</li></ul><h3>2. CORRECTIVE RAG</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/587/1*3OAzFvFxwPs9wdH_X9iRhA.png" /><figcaption>CORRECTIVE RAG</figcaption></figure><blockquote>Corrective Retrieval-Augmented Generation (CRAG) is an advanced architecture within the RAG framework that enhances the accuracy and reliability of responses generated by large language models (LLMs). This approach integrates a self-reflection mechanism that critically evaluates the relevance and quality of retrieved information before it is used in generating responses.</blockquote><h4>How CRAG Works</h4><p>The CRAG process typically follows these steps:</p><ul><li><strong>Query Input</strong>: The user submits a query.</li><li><strong>Document Retrieval</strong>: Relevant documents are fetched from a knowledge base.</li><li><strong>Knowledge Stripping and Grading</strong>: Retrieved documents are divided into knowledge strips, which are then graded for relevance.</li><li><strong>Knowledge Refinement</strong>: Irrelevant strips are filtered out; if no strips meet the relevance threshold, supplementary retrieval occurs.</li><li><strong>Generation</strong>: A final response is generated based on the most relevant and accurate knowledge strips</li></ul><h4>Strengths of CRAG</h4><ul><li><strong>Improved Accuracy</strong>: By incorporating a systematic evaluation of retrieved content, CRAG minimizes hallucinations — instances where models generate incorrect or fabricated information.</li><li><strong>Contextual Relevance</strong>: The ability to refine knowledge through iterative retrieval ensures that responses are not only accurate but also contextually appropriate.</li><li><strong>Dynamic Adaptation</strong>: CRAG can adapt to varying levels of information quality by seeking additional data sources when necessary, enhancing its robustness in real-time applications.</li></ul><h3>3. SPECULATIVE RAG</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/563/1*FMxoo6tYSP9CsG23hf9_ig.png" /><figcaption>SPECULATIVE RAG</figcaption></figure><blockquote>Speculative RAG leverages two types of language models (LMs): a smaller, specialized model for drafting and a larger, generalist model for verification. Here’s a comprehensive overview of how Speculative RAG operates and its advantages.</blockquote><h4>How Speculative RAG Works</h4><ol><li><strong>Drafting with Specialist LMs</strong>:</li></ol><ul><li>In Speculative RAG, the initial drafting of responses is handled by a smaller, distilled specialist LM. This model generates multiple drafts in parallel based on distinct subsets of retrieved documents. By clustering these documents by content similarity and sampling from each cluster, the system minimizes redundancy and maximizes diversity in the drafts produced</li></ul><p><strong>2. Verification with Generalist LMs</strong>:</p><ul><li>Once the drafts are generated, a larger generalist LM evaluates these outputs. This verification step involves assessing the quality and relevance of each draft, allowing the generalist model to select the best response based on its reasoning capabilities.</li><li>This two-step process effectively offloads the computational burden from the generalist LM while still ensuring high-quality output.</li></ul><h4>Strengths of Speculative RAG</h4><ul><li><strong>Improved Accuracy</strong>: By providing diverse perspectives from multiple drafts.</li><li><strong>Reduced Latency</strong>: By delegating the drafting task to a smaller model, Speculative RAG can produce responses more quickly than traditional methods that may struggle with longer contexts or extensive document inputs.</li></ul><h3>4. FUSION RAG</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TlYHJeVaWQt26_fsrcXNgA.png" /><figcaption>FUSION RAG</figcaption></figure><blockquote>Fusion RAG generates multiple queries based on the original user input. This allows for a broader search across various data sources, increasing the likelihood of retrieving relevant information.</blockquote><h4>How Fusion RAG works:</h4><ol><li><strong>User Query Input</strong>: A user submits a query that requires information retrieval and generation.</li><li><strong>Multiple Query Generation</strong>: The system generates several variations of the original query to capture different aspects of the request.</li><li><strong>Information Retrieval</strong>: Each generated query is used to search a knowledge base or document repository, retrieving relevant documents for each variation.</li><li><strong>Reranking with RRF</strong>: The retrieved documents are scored and reranked using reciprocal rank fusion, which considers the ranks from different queries to optimize the selection of documents.</li><li><strong>Document Fusion</strong>: The top-ranked documents are fused together, consolidating information from various sources into a coherent set of data.</li><li><strong>Response Generation</strong>: The fused information is then passed to a large language model, which generates a comprehensive response based on the enriched context provided by the retrieved documents.</li></ol><h4>Strengths of Fusion RAG</h4><ul><li><strong>Improved Accuracy</strong>: By leveraging multiple queries and reranking techniques, Fusion RAG significantly enhances the accuracy of responses.</li><li><strong>Comprehensive Responses</strong>: The fusion process allows for a more systematic view of the information available.</li><li><strong>Dynamic Adaptability</strong>: Fusion RAG can adapt to different types of queries by generating tailored queries that reflect various angles or nuances in user requests.</li></ul><h3>5. SELF RAG</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5ixvI4sk36UWESI0Ci9LFQ.png" /><figcaption>SELF RAG</figcaption></figure><blockquote>Self-RAG employs a self-reflective mechanism where the system evaluates the relevance of retrieved documents against the user’s query. This involves assessing whether the retrieved passages provide useful information for answering the question.</blockquote><h4>How Self RAG works?</h4><p>The Self-RAG process generally follows these steps:</p><ol><li><strong>User Query Input</strong>: A user submits a query that requires information retrieval.</li><li><strong>Initial Document Retrieval</strong>: The system retrieves relevant documents from a knowledge base based on the user’s query.</li><li><strong>Relevance Assessment</strong>: Each retrieved document is evaluated for its relevance to the query. If documents are judge irrelevant, they are filtered out.</li><li><strong>Self-Grading of Responses</strong>: The generated responses from an LLM (Large Language Model) are also assessed for quality and relevance. This includes checking for hallucinations — instances where the model generates incorrect or fabricated information.</li><li><strong>Query Rewriting</strong>: If necessary, the original query is rewritten based on insights gained from the self-assessment process to improve future retrieval accuracy.</li><li><strong>Re-execution of Retrieval</strong>: The refined query is used to perform another round of document retrieval, repeating the evaluation and grading steps until satisfactory results are achieved.</li><li><strong>Final Response Generation</strong>: Once relevant documents are identified and graded positively, a final response is generated using an LLM based on this enriched context.</li></ol><h4>Strengths of Self RAG</h4><ul><li><strong>Enhanced Accuracy</strong>: By incorporating self-reflection and grading mechanisms, Self-RAG significantly improves the accuracy of generated responses, reducing instances of irrelevant or incorrect information.</li><li><strong>Dynamic Adaptability</strong>: The iterative nature allows the system to adapt to ambiguous or complex queries effectively, refining its approach based on feedback from previous iterations.</li></ul><h3>6. MEMO RAG</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yi9K0E7COiu84VG4PlyQqw.png" /><figcaption>MEMO RAG</figcaption></figure><blockquote>MemoRAG is an innovative framework that enhances traditional Retrieval-Augmented Generation (RAG) systems by integrating long-term memory capabilities, allowing for deeper contextual understanding and more accurate information retrieval. This methodology addresses the limitations of standard RAG, which often struggles with complex or ambiguous queries.</blockquote><h4>How MEMO RAG Works?</h4><ol><li><strong>Input Handling</strong>: When a user submits a query, MemoRAG first utilizes its memory model to generate clues based on its retained knowledge.</li><li><strong>Evidence Retrieval</strong>: The retrieval-generation model then uses these clues to fetch relevant documents from the database.</li><li><strong>Response Generation</strong>: Finally, the system synthesizes the retrieved evidence into a coherent response that is contextually rich and accurate.</li></ol><h4>Strengths of MEMO RAG</h4><ul><li><strong>Improved Handling of Ambiguous Queries</strong>: The memory system allows MemoRAG to infer user intent even when queries are implicit or incomplete.</li><li><strong>Complex Summarization Capabilities</strong>: MemoRAG can condense large datasets into coherent summaries by generating key points and retrieving supporting evidence.</li></ul><h3>FINAL CONSIDERATIONS</h3><p>That’s all you need to know to start implementing these RAG frameworks. There is a lot more that I didn’t cover yet, and the usage of each one depends on your requirements, so feel free to choose and experiment!</p><p>If you have enjoyed this lecture, please read my others topics, Thanks and see you soon with others topics!</p><ul><li><a href="https://medium.com/@stefanoz/rag-llm-llama-3-1-70b-in-python-5c77a1785277">RAG + LLM (Llama-3.1–70B) in Python</a></li><li><a href="https://medium.com/@stefanoz/building-a-talking-ai-with-llama-rag-8684dc0dd67a">Building a talking AI with LLAMA + RAG</a></li></ul><h3>REFERENCES OF THIS POST</h3><ul><li><a href="https://www.promptingguide.ai/research/rag">Retrieval Augmented Generation (RAG) for LLMs | Prompt Engineering Guide</a></li><li><a href="https://humanloop.com/blog/rag-architectures">8 Retrieval Augmented Generation (RAG) Architectures You Should Know in 2025</a></li><li><a href="https://www.turingpost.com/p/speculativerag">What is Speculative RAG?</a></li><li><a href="https://github.com/qhjqhj00/MemoRAG">GitHub - qhjqhj00/MemoRAG: Empowering RAG with a memory-based data interface for all-purpose applications!</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8596924bc421" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a talking AI with LLAMA + RAG]]></title>
            <link>https://medium.com/@stefanoz/building-a-talking-ai-with-llama-rag-8684dc0dd67a?source=rss-60f0eba3a328------2</link>
            <guid isPermaLink="false">https://medium.com/p/8684dc0dd67a</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[conversational-ai]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[llama-3]]></category>
            <dc:creator><![CDATA[stefanoz]]></dc:creator>
            <pubDate>Wed, 23 Oct 2024 07:48:20 GMT</pubDate>
            <atom:updated>2024-10-23T07:48:20.593Z</atom:updated>
            <content:encoded><![CDATA[<p>In this post, I’ll demonstrate how to create an interactive conversation between a user (you) and an AI using only Python, the LLM (Llama-3.1–70b), and RAG, along with some necessary dependencies, without spending any money!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oQ93W79RiAKgn98ig7Y91g.jpeg" /></figure><p>The goal of this project is to create a base template using Python GUI to initiate a conversation with an AI, focusing solely on the context you’ve previously uploaded, leveraging the principle of RAG.</p><p>Before to proceed, the prerequisites of the following lectures are:</p><ul><li>Know what RAG is (you can take a look at one of my post: <a href="https://medium.com/@stefanoz/rag-llm-llama-3-1-70b-in-python-5c77a1785277">https://medium.com/@stefanoz/rag-llm-llama-3-1-70b-in-python-5c77a1785277</a>)</li><li>Know how to configure and use python environment</li></ul><p>If you’re already familiar with these concepts, let’s move on!</p><h3>A glimpse to results</h3><p>In this caption, as the image illustrates, It’s shown the goal to achieve. A user talks to a AI and after processing the speech, the AI respond to user relating only to the context provided before. The context affers to a file pdf that is processed on startup of application. I attacched only the image because I cannot embed the video with audio in Medium, although you’re welcome to copy and run my code to experience this powerful functionality.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/989/1*-lFT5nldMEhiJcoUY0YbuQ.png" /><figcaption>FINAL RESULT</figcaption></figure><p>The document retrieved from the PDF was related to this part:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fGLUWoWFIyWr4eI0A1fsJw.png" /><figcaption>DOCUMENT RETRIEVED FOR THE FIRST QUESTION</figcaption></figure><p>To summarize all the process in a diagram workflow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UQpqiCCBEYX53gfrFDjL6w.png" /><figcaption>SYSTEM WORKFLOW</figcaption></figure><p>Let’s explain this system workflow proceeding for steps:</p><h4>Setup</h4><ul><li>The user copies to a default directory the files pdf or text. These files might contain information that the user wants to query later.</li><li>Upon detecting a new file in the upload directory, the system once launched initiates a processing routine.</li><li>The system reads the file and divides its content into manageable chunks. These chunks could be paragraphs, pages, or sections, depending on the file type and the system’s configuration.</li><li>Simultaneously, the system computes a unique hash of the PDF file. A hash is a fixed-size string that uniquely identifies the content of the file. This hash is stored in a text file, which acts as a registry of all uploaded PDFs.</li><li>When the user uploads another PDF, the system checks the hash of this new PDF against the hashes in the text file.</li><li>If the hash is not found, it means the PDF is new, and the system proceeds to process it as described above.</li><li>If the hash matches an existing entry, it indicates that the PDF has been uploaded before. In this case, the system skips processing the file, as it already has its content stored in the database.</li></ul><h4><strong>User Interaction with AI</strong>:</h4><ul><li>After uploading one or more files, the user can interact with the AI system by asking questions or seeking information related to the content of these files.</li><li>The AI system employs a Retrieval-Augmented Generation (RAG) approach. RAG is a technique where a system first tries to retrieve relevant information from a knowledge base (in this case, the database of file chunks) before generating a response.</li><li>The AI first analyzes the user’s question to understand the context and the information being requested.</li><li>It then searches the database for chunks of information that might be relevant to the query. This search could be based on keywords, topics, or other semantic relationships.</li><li>If relevant chunks are found, the AI retrieves this information.</li><li>The AI then uses a Large Language Model (LLM) to generate a response. LLMs like LLMana are trained to produce human-like text based on the input they receive. The LLM will use the retrieved information to formulate a response to the user’s question.</li><li>The generated response is then presented to the user, either on a screen and through an audio interface.</li><li>The user can continue the conversation replying to the last message.</li></ul><h4><strong>Benefits and Advantages</strong>:</h4><ul><li>By storing hashes of uploaded PDFs, the system ensures that duplicate content is not processed, saving computational resources and storage space.</li><li>The RAG process enables the AI to provide more accurate and contextually relevant responses by first retrieving specific information from the uploaded files.</li><li>The use of LLMs ensures that the responses generated are coherent, contextually appropriate, and in a natural language format that users can easily understand.</li></ul><h3>CODING SECTION</h3><p>Before to move on to the code, I would emphasize the main libraries used for this project and give you a resume for each of them:</p><ul><li><strong>langchain</strong>: framework to build with LLMs by chaining interoperable components.</li><li><strong>elevenlabs</strong>: Service that convert Text to Speech using AI. You have some free credits that will reset every months to use the functionalities of this service.</li><li><strong>pyaudio library </strong>used for playing and recording audio, <strong>wave library </strong>for working with WAV audio files, <strong>pydub library</strong> for manipulating audio:</li><li><strong>tkinter</strong>: create easy and fast UI with python</li></ul><p>Now let’s start… here is the structure of project:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/283/1*eRejC5OP2pgiKgMgiUY0Ng.png" /><figcaption>PROJECT STRUCTURE</figcaption></figure><p>The first class to implement is <strong>Config </strong>inside config.py. This class includes all the properties configuration with keys. <em>Only for the purpose of this project to keep all minimal and simpler possible, the Config class stores credentials, but in real project they only must be written inside a properties file.</em></p><pre>from dataclasses import dataclass, field<br><br>@dataclass<br>class Config:<br>    PDF_FOLDER_PATH: str = &quot;pdf_folder&quot;<br>    DATABASE_DIRECTORY: str = &quot;chromadb&quot;<br>    HF_TOKEN: str = &quot;gsk_xx&quot;<br>    EMBEDDING_MODEL: str = &quot;sentence-transformers/all-MiniLM-L6-v2&quot;<br>    LLM_MODEL: str = &quot;llama-3.1-70b-versatile&quot;<br>    CHUNK_SIZE: int = 1024<br>    CHUNK_OVERLAP: int = 500<br>    ELEVENLABS_API_KEY: str = &quot;sk_xx&quot;<br>    API_URL: str = &quot;https://api-inference.huggingface.co/models/jonatasgrosman/wav2vec2-large-xlsr-53-english&quot;<br>    HEADERS: dict = field(default_factory=lambda: {&quot;Authorization&quot;: &quot;Bearer hf_xx&quot;})<br>    SAMPLE_RATE: int = 44100<br>    CHANNELS: int = 1<br>    RECORD_SECONDS: int = 15<br>    MIN_RECORD_SECONDS: int = 15<br>    OUTPUT_FILENAME: str = &quot;output.flac&quot;</pre><p>The second class to implement is <strong>SetupRag</strong>. It’s goal is the setup process that we’ve already seen in the previous image. Here is the class:</p><pre>import os<br>import hashlib<br>from typing import List, Set<br>import requests<br>import langchain<br>from langchain_text_splitters import RecursiveCharacterTextSplitter<br>from langchain_community.embeddings import HuggingFaceEmbeddings<br>from langchain_community.vectorstores import Chroma<br>from langchain_community.document_loaders import PyPDFLoader<br>from langchain_core.output_parsers import StrOutputParser<br>from langchain_core.runnables import RunnablePassthrough<br>from langchain.prompts import ChatPromptTemplate<br>from langchain_groq import ChatGroq<br>from elevenlabs import play, ElevenLabs<br>from queue import Queue<br><br>from config import Config<br><br>class SetupRag:<br>    def __init__(self):<br>        self.config = Config()<br>        # Initialize clients<br>        self.elevenlabs_client = ElevenLabs(api_key=self.config.ELEVENLABS_API_KEY)<br>        self.transcript_queue = Queue()<br>        self.llm = ChatGroq(<br>            model_name=self.config.LLM_MODEL,<br>            api_key=self.config.HF_TOKEN,<br>            verbose=True,<br>            max_retries=2,<br>            temperature=0.02,<br>            max_tokens=500<br>        )<br><br>    def query(self, filename):<br>        with open(filename, &quot;rb&quot;) as f:<br>            data = f.read()<br>        response = requests.post(<br>            self.config.API_URL, headers=self.config.HEADERS, data=data)<br>        return response.json()<br><br>    def handle_conversation(self, rag_chain, text: str) -&gt; None:<br>        response = rag_chain.invoke(text)<br>        audio = self.elevenlabs_client.generate(text=response, voice=&quot;Rachel&quot;)<br>        print(f&quot;\nAI: {response}&quot;)<br>        play(audio)<br><br>    def setup_embedding_function(self) -&gt; HuggingFaceEmbeddings:<br>        return HuggingFaceEmbeddings(model_name=self.config.EMBEDDING_MODEL)<br><br>    def generate_pdf_hash(self, pdf_path: str) -&gt; str:<br>        with open(pdf_path, &quot;rb&quot;) as f:<br>            return hashlib.md5(f.read()).hexdigest()<br><br>    def load_existing_hashes(self, database_directory: str) -&gt; Set[str]:<br>        hash_file = os.path.join(database_directory, &quot;tabella_pdfhash.txt&quot;)<br>        try:<br>            with open(hash_file, &quot;r&quot;, encoding=&quot;utf-8&quot;) as file:<br>                return set(file.read().splitlines())<br>        except FileNotFoundError:<br>            return set()<br><br>    def save_hash(self, hash_value: str, database_directory: str) -&gt; bool:<br>        hash_file = os.path.join(database_directory, &quot;tabella_pdfhash.txt&quot;)<br>        existing_hashes = self.load_existing_hashes(database_directory)<br><br>        if hash_value not in existing_hashes:<br>            with open(hash_file, &quot;a&quot;, encoding=&quot;utf-8&quot;) as file:<br>                file.write(f&quot;{hash_value}\n&quot;)<br>            return True<br>        return False<br><br>    def process_pdf(self, pdf_path: str, pdf_hash: str, vectordb: Chroma) -&gt; None:<br>        loader = PyPDFLoader(pdf_path)<br>        documents = loader.load()<br>        text_splitter = RecursiveCharacterTextSplitter(<br>            chunk_size=self.config.CHUNK_SIZE, chunk_overlap=self.config.CHUNK_OVERLAP<br>        )<br>        chunked_documents = text_splitter.split_documents(documents)<br>        ids = [f&quot;{pdf_hash}_{i}&quot; for i in range(1, len(chunked_documents) + 1)]<br><br>        vectordb.add_documents(documents=chunked_documents, ids=ids)<br><br>    def process_pdf_folder(self, folder_path: str, database_directory: str, embedding_function: HuggingFaceEmbeddings) -&gt; Chroma:<br>        vectordb = Chroma(persist_directory=database_directory,<br>                          embedding_function=embedding_function)<br><br>        for root, _, filenames in os.walk(folder_path):<br>            for filename in filenames:<br>                if filename.endswith(&quot;.pdf&quot;):<br>                    pdf_path = os.path.join(root, filename)<br>                    pdf_hash = self.generate_pdf_hash(pdf_path)<br><br>                    if self.save_hash(pdf_hash, database_directory):<br>                        self.process_pdf(pdf_path, pdf_hash, vectordb)<br>                    else:<br>                        print(<br>                            f&quot;The PDF {filename} is already in the hash list.&quot;)<br><br>        return vectordb<br><br>    def setup_rag_chain(self, vectordb: Chroma) -&gt; RunnablePassthrough:<br>        langchain.debug = True<br>        retriever = vectordb.as_retriever(search_kwargs={&quot;k&quot;: 2})<br><br>        template = &quot;&quot;&quot;Answer only with one brief sentence to the question based only on the following context:<br>        {context}<br><br>        Question: {question}<br>        &quot;&quot;&quot;<br>        prompt = ChatPromptTemplate.from_template(template)<br><br>        return (<br>            {&quot;context&quot;: retriever | self.format_docs,<br>                &quot;question&quot;: RunnablePassthrough()}<br>            | prompt<br>            | self.llm<br>            | StrOutputParser()<br>        )<br><br>    def format_docs(self, docs: List[str]) -&gt; str:<br>        return &quot;\n\n&quot;.join(doc.page_content for doc in docs)</pre><p>The class is designed to set up and manage a Retrieval-Augmented Generation (RAG) system that can process and respond to queries based on information from uploaded PDFs. Here&#39;s a summary of what the class does:</p><p><strong>Initialization</strong>:</p><ul><li>The class constructor initializes various clients and configurations required for the RAG system. This includes setting up an ElevenLabs client for text-to-speech, a queue for transcripts, and an LLM model for generating responses.</li></ul><p><strong>Querying API</strong>:</p><ul><li>The query method sends a POST request to a specified API with the content of a file and returns the JSON response.</li></ul><p><strong>Handling Conversations</strong>:</p><ul><li>The handle_conversation method manages the interaction between the user and the RAG system. It takes a rag_chain (which is a chain of operations in the LangChain library) and a user&#39;s text input.</li><li>It then uses the ElevenLabs client to convert the response into audio using a specific voice and plays it using the play function.</li></ul><p><strong>Embedding Function Setup</strong>:</p><ul><li>The setup_embedding_function method initializes and returns a HuggingFaceEmbeddings object, which is used for creating vector representations of text data.</li></ul><p><strong>PDF Hashing</strong>:</p><ul><li>The generate_pdf_hash method calculates the MD5 hash of a PDF file given its path. This hash is used to uniquely identify the PDF.</li><li>The load_existing_hashes method reads a text file containing previously saved PDF hashes from a specified directory and returns them as a set.</li><li>The save_hash method checks if a given hash value is already present in the set of existing hashes. If not, it appends the hash to a text file, indicating a new PDF has been processed.</li></ul><p><strong>Processing PDFs</strong>:</p><ul><li>The process_pdf method takes a PDF path, its hash, and a Chroma vector database (vectordb).</li><li>It loads the PDF using PyPDFLoader, splits it into smaller chunks using RecursiveCharacterTextSplitter, and then adds these chunks to the vectordb with unique IDs.</li><li>The process_pdf_folder method processes all PDFs in a given folder.</li><li>It initializes a Chroma vector database with the provided embedding function and directory for persistence.</li><li>For each PDF in the folder, it calculates the hash and checks if it’s a new PDF. If new, it processes the PDF and adds its content to the vectordb.</li></ul><p><strong>Setting Up RAG Chain</strong>:</p><ul><li>The setup_rag_chain method configures the LangChain pipeline for the RAG system.</li><li>It sets up a retriever based on the vectordb, which retrieves relevant chunks of text based on a query.</li><li>It defines a prompt template that includes the retrieved context and the user’s question.</li><li>The method then constructs a LangChain pipeline that combines the retriever, prompt, LLM, and output parser to generate a response.</li><li>The format_docs method formats a list of documents (retrieved from the database) into a single string by concatenating their content with newlines.</li></ul><p>The RealtimeSpeech class is designed for capturing and saving audio input in real-time. It provides a way to record audio from a microphone or other input device and then process and save that audio in a specific format.:</p><pre>import time<br>import os<br>import threading<br>import pyaudio<br>import wave<br>from elevenlabs import play<br>from pydub import AudioSegment<br><br>class RealtimeSpeech:<br>    def __init__(self, config):<br>        self.config = config<br>        self.format = pyaudio.paInt16<br>        self.frames = []<br>        self.is_recording = False<br>        self.start_time = 0<br>        self.recording_completed = threading.Event()<br><br>    def callback(self, in_data, frame_count, time_info, status):<br>        self.frames.append(in_data)<br>        return (in_data, pyaudio.paContinue)<br><br>    def record_audio(self):<br>        p = pyaudio.PyAudio()<br>        stream = p.open(format=self.format,<br>                        channels=self.config.CHANNELS,<br>                        rate=self.config.SAMPLE_RATE,<br>                        input=True,<br>                        frames_per_buffer=self.config.CHUNK_SIZE,<br>                        stream_callback=self.callback)<br>        print(&quot;* Recording&quot;)<br>        stream.start_stream()<br>        self.start_time = time.time()<br>        self.is_recording = True<br>        while self.is_recording and (time.time() - self.start_time &lt; self.config.MIN_RECORD_SECONDS):<br>            time.sleep(0.1)<br>        stream.stop_stream()<br>        stream.close()<br>        p.terminate()<br>        print(&quot;* Done recording&quot;)<br>        self.save_audio()<br>        self.recording_completed.set()<br><br>    def save_audio(self):<br>        # Save as WAV first<br>        wf = wave.open(&quot;temp.wav&quot;, &#39;wb&#39;)<br>        wf.setnchannels(self.config.CHANNELS)<br>        wf.setsampwidth(pyaudio.get_sample_size(self.format))<br>        wf.setframerate(self.config.SAMPLE_RATE)<br>        wf.writeframes(b&#39;&#39;.join(self.frames))<br>        wf.close()<br>        # Convert WAV to FLAC<br>        audio = AudioSegment.from_wav(&quot;temp.wav&quot;)<br>        audio.export(self.config.OUTPUT_FILENAME, format=&quot;flac&quot;)<br>        # Remove temporary WAV file<br>        os.remove(&quot;temp.wav&quot;)<br><br>    def start_recording(self):<br>        self.is_recording = True<br>        self.frames = []<br>        self.recording_completed.clear()<br>        threading.Thread(target=self.record_audio).start()<br><br>    def stop_recording(self):<br>        self.is_recording = False<br>        self.recording_completed.wait()  # Wait for recording to complete</pre><p>The class utilizes the PyAudio library, which allows for low-level manipulation of audio streams, to set up the audio recording parameters such as the format, channels, sample rate, and chunk size. The record_audio method starts the recording process, which runs in a separate thread to ensure the recording is not blocked by other operations. It keeps recording until a minimum time has passed or the recording is manually stopped.</p><p>Once the recording is complete, the captured audio data is saved as a WAV file. This temporary WAV file is then converted to a FLAC format using the pydub library, which offers more efficient storage and better quality for voice data. The temporary WAV file is deleted after the conversion.</p><p>The class also provides methods to start and stop the recording process, ensuring that the recording is not abruptly terminated, and that there’s a minimum recording duration. The start_recording method initializes the recording process, while stop_recording gracefully ends it, ensuring that the recording thread completes its operation.</p><p>The <strong>RAGConversationGUI </strong>class builds a graphical interface for a real-time conversation system. It enables users to chat with an AI model by typing or recording voice messages. The AI responds with text and audio. The class manages recording, displays conversations, and integrates with an external RAG system for AI responses. It ensures a smooth user experience by handling recording, displaying messages, and generating AI replies concurrently.</p><pre>import os<br>import tkinter as tk<br>from tkinter import ttk, scrolledtext, font<br>import threading<br>import time<br>from elevenlabs import play<br>from config import Config<br>from realtime_speech import RealtimeSpeech<br>from setup_rag import SetupRag<br><br>class RAGConversationGUI:<br>    def __init__(self, master):<br>        self.config = Config()<br>        self.master = master<br>        master.title(&quot;RAG Conversation System&quot;)<br>        master.geometry(&quot;800x600&quot;)<br>        self.rag_system = SetupRag()<br>        self.create_widgets()<br>        self.setup_rag_system()<br>        self.is_recording = False<br>        self.recorder = RealtimeSpeech(self.config)<br>        self.recording_start_time = 0<br>        self.timer_id = None<br><br>    def create_widgets(self):<br>        style = ttk.Style()<br>        style.theme_use(&quot;yaru&quot;)<br>        self.main_frame = ttk.Frame(self.master, padding=&quot;10&quot;)<br>        self.main_frame.pack(fill=tk.BOTH, expand=True)<br>        custom_font = font.nametofont(&quot;TkTextFont&quot;)<br>        custom_font.configure(family=&quot;Helvetica&quot;, size=12)<br>        self.conversation_area = scrolledtext.ScrolledText(<br>            self.main_frame, <br>            wrap=tk.WORD, <br>            height=20, <br>            font=custom_font,<br>        )<br>        self.conversation_area.pack(fill=tk.BOTH, expand=True, pady=(0, 10))<br>        self.conversation_area.tag_configure(&quot;user&quot;, foreground=&quot;#4CAF50&quot;)<br>        self.conversation_area.tag_configure(&quot;ai&quot;, foreground=&quot;#2196F3&quot;)<br>        self.input_frame = ttk.Frame(self.main_frame)<br>        self.input_frame.pack(fill=tk.X)<br>        self.input_entry = ttk.Entry(self.input_frame, font=custom_font)<br>        self.input_entry.pack(side=tk.LEFT, fill=tk.X, expand=True)<br>        self.send_button = ttk.Button(self.input_frame, text=&quot;Send&quot;, command=self.send_message)<br>        self.send_button.pack(side=tk.RIGHT)<br>        self.record_button = ttk.Button(self.main_frame, text=&quot;Start Recording&quot;, command=self.toggle_recording)<br>        self.record_button.pack(pady=(10, 0))<br>        self.status_label = ttk.Label(self.main_frame, text=&quot;&quot;)<br>        self.status_label.pack(pady=(10, 0))<br>        self.master.bind(&#39;&lt;Return&gt;&#39;, lambda event: self.send_message())<br><br>    def setup_rag_system(self):<br>        self.embedding_function = self.rag_system.setup_embedding_function()<br>        self.vectordb = self.rag_system.process_pdf_folder(self.config.PDF_FOLDER_PATH, self.config.DATABASE_DIRECTORY, self.embedding_function)<br>        self.rag_chain = self.rag_system.setup_rag_chain(self.vectordb)<br><br>    def send_message(self):<br>        user_input = self.input_entry.get()<br>        if user_input:<br>            self.add_message_to_conversation(&quot;You&quot;, user_input)<br>            self.input_entry.delete(0, tk.END)<br>            self.get_ai_response(user_input)<br><br>    def get_ai_response(self, user_input):<br>        def ai_response_thread():<br>            response = self.rag_chain.invoke(user_input)<br>            self.master.after(0, self.add_message_to_conversation, &quot;AI&quot;, response)<br>            audio = self.rag_system.elevenlabs_client.generate(text=response, voice=&quot;Rachel&quot;)<br>            play(audio)<br>        threading.Thread(target=ai_response_thread).start()<br><br>    def add_message_to_conversation(self, speaker, message):<br>        self.conversation_area.insert(tk.END, f&quot;{speaker}: &quot;, speaker.lower())<br>        self.conversation_area.insert(tk.END, f&quot;{message}\n\n&quot;)<br>        self.conversation_area.see(tk.END)<br><br>    def toggle_recording(self):<br>        if not self.is_recording:<br>            self.start_recording()<br>        else:<br>            self.stop_recording()<br><br>    def start_recording(self):<br>        self.is_recording = True<br>        self.record_button.config(text=&quot;Stop Recording&quot;)<br>        self.status_label.config(text=&quot;Recording...&quot;)<br>        self.recording_start_time = time.time()<br>        self.recorder.start_recording()<br>        self.update_recording_timer()<br><br>    def stop_recording(self):<br>        self.is_recording = False<br>        self.recorder.stop_recording()<br>        self.record_button.config(text=&quot;Start Recording&quot;)<br>        self.status_label.config(text=&quot;Processing...&quot;)<br>        if self.timer_id:<br>            self.master.after_cancel(self.timer_id)<br>        self.master.after(3000, self.wait_for_recording_completion)<br><br>    def wait_for_recording_completion(self):<br>        if self.recorder.recording_completed.is_set():<br>            self.master.after(1000, self.process_recording)<br>        else:<br>            self.master.after(100, self.wait_for_recording_completion)<br><br>    def update_recording_timer(self):<br>        if self.is_recording:<br>            elapsed_time = time.time() - self.recording_start_time<br>            remaining_time = max(self.config.MIN_RECORD_SECONDS - elapsed_time, 0)<br>            if remaining_time &gt; 0:<br>                self.status_label.config(text=f&quot;Recording... {remaining_time:.1f}s remaining&quot;)<br>                self.timer_id = self.master.after(100, self.update_recording_timer)<br>            else:<br>                self.stop_recording()<br>        else:<br>            self.status_label.config(text=&quot;Recording complete. Processing...&quot;)<br><br>    def process_recording(self):<br>        if os.path.exists(self.config.OUTPUT_FILENAME) and os.path.getsize(self.config.OUTPUT_FILENAME) &gt; 0:<br>            text_query = self.rag_system.query(self.config.OUTPUT_FILENAME)<br>            transcribed_text = text_query[&#39;text&#39;]<br>            self.add_message_to_conversation(&quot;You (voice)&quot;, transcribed_text)<br>            self.get_ai_response(transcribed_text)<br>        else:<br>            self.status_label.config(text=&quot;Error: Recording failed&quot;)<br>        self.status_label.config(text=&quot;&quot;)</pre><p>The GUI is designed using the Tkinter library with the Equilux theme for styling. There is a Start/Stop Recording” button to initiate voice recording and a status label to show recording or processing status.</p><p>Here is the main class which you’ll use to launch the scripts:</p><pre>from ttkthemes import ThemedTk<br><br>from rag_conversional_gui import RAGConversationGUI<br><br>def main():<br>    root = ThemedTk(theme=&quot;equilux&quot;)<br>    app = RAGConversationGUI(root)<br>    root.mainloop()<br><br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><h3>CONCLUSION</h3><p>That’s all you need to know to launch a powerful application that can simulate a realistic conversation between you and AI, leveraging RAG (Retrieval-Augmented Generation) tools to provide perteining information from your uploaded files.</p><p>If you like this content <em>Feel free to check out my other articles 📚</em></p><p><a href="https://link.medium.com/FRwjjPUDyNb">RAG + LLM (Llama-3.1-70B) in Python</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8684dc0dd67a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RAG + LLM (Llama-3.1–70B) in Python]]></title>
            <link>https://medium.com/@stefanoz/rag-llm-llama-3-1-70b-in-python-5c77a1785277?source=rss-60f0eba3a328------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c77a1785277</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[langchain]]></category>
            <dc:creator><![CDATA[stefanoz]]></dc:creator>
            <pubDate>Wed, 09 Oct 2024 15:06:19 GMT</pubDate>
            <atom:updated>2024-10-12T10:03:58.589Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/923/1*xWV9jHbJzUp8PGvHq3FQ1A.png" /></figure><p>In this post, I’ll explain what RAG is and how to use in combination with LLM (Large Language Model) as Llama-3.1–70B and how to configure all the environment in python 3.11 to use this powerful technology.</p><h3>WHAT IS RAG?</h3><p>Retrieval-Augmented Generation (RAG) is a AI technology that enhances the performance of Large Language Models (LLMs) by combining their generative capabilities with external information retrieval systems. <strong>The concept of RAG is based on the idea of ​​using a retrieval model to search for relevant information in a database or external knowledge, and then using a generation model to create text conditioned by this information.</strong> Here’s a more detailed breakdown of how the RAG process works and why is useful. I’ll explain as easily as possible.</p><h4>WHY RAG?</h4><p>Large Language Models like GPT, BERT, and others are trained on massive datasets, which allow them to learn patterns, relationships, and structures within language. They are capable of generating human-like text and performing a wide range of tasks, including answering questions, summarizing, and even engaging in conversation. However, LLMs have inherent limitations:</p><ul><li><strong>Training data cut-off</strong>: LLMs are trained on static datasets that may become outdated over time, leading to responses that do not reflect the latest information or developments.</li><li><strong>Knowledge boundaries</strong>: Even with vast training data, LLMs cannot have comprehensive knowledge of specialized or proprietary domains (e.g., a specific company’s internal documentation, scientific research, or legal databases).</li><li><strong>Inaccuracy or hallucination</strong>: LLMs can sometimes generate responses that seem plausible but are factually incorrect or misleading. This happens because they base their output on statistical patterns rather than an external, verifiable source.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/345/1*YVTBKLiA5pb7B0Bt-ifntA.png" /><figcaption>PROMPT VS RAG</figcaption></figure><p>At this point, you could ask “Why I can’t pre-trained the LLM with a specific context to overcome the gap attaching the information in the prompt?” The answer is straightforward: you can’t train a LLM using the prompt, you can’t attach a large context or massive data in the prompt and moreover you’ve to be very precise because the result is often not deterministic. And how about cost of token?!</p><blockquote>Don’t be afraid, the RAG is you friend in this case!</blockquote><h4>HOW RAG WORKS</h4><p>RAG addresses these limitations by incorporating external knowledge retrieval into the generation process. Here’s how the RAG pipeline works:</p><p><strong>1: Query Understanding</strong>: When a user inputs a question or request, the LLM interprets the query based on its inherent language understanding capabilities. It may recognize the topic, identify key terms, and so on... <em>So far nothing new!!!</em></p><p><strong>2: Knowledge Retrieval</strong>: Now the situation changes!!! <em>Instead of relying solely on its pre-trained knowledge, the RAG model connects to an external knowledge base.</em> This knowledge base could be:</p><ul><li>Public or private databases</li><li>Search engines that retrieve real-time or domain-specific information</li><li>Structured or unstructured data from knowledge repositories</li></ul><p><strong>!!!PLEASE NOTE!!!</strong></p><blockquote>The model sends the query to a retrieval system that performs a search over the external data (database…), returning the most relevant data or documents.</blockquote><p>So it retrieves only the most relevant information based on user request in all data saved in database or others external sources.</p><p><strong>3: Fusion of Retrieved Data</strong>: The retrieved information is then <strong>combined</strong> with the LLM’s internal knowledge adding automatically the information retrieved in LLM prompt. This technique is called Prompt Engeenering. This can happen in several ways:</p><ul><li>The retrieved data serves as a <strong>context</strong> that the LLM uses to refine and guide its generative process.</li><li>The LLM integrates the external knowledge into its answer, directly quoting or paraphrasing the most relevant portions of the retrieved documents.</li></ul><p><strong>4: Response Generation</strong>: Using both its trained parameters and the externally retrieved data, the LLM generates a response. Because it now references up-to-date and specialized information, the output is more accurate, relevant, and contextualized than if the LLM relied solely on its training data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*eGn2-t13xawtbfEKahSCtw.jpeg" /><figcaption>RAG FLOW</figcaption></figure><h3>HOW TO IMPLEMENT IN PYTHON?</h3><p>Now the cool part, I’ll show you how to integrate all this stuff in python code and show the result of RAG in action.</p><p>First of all, as said before the technologies I’ll use are python for code, Groq Provider to use the API of LLM Llama 3.1–70B that are free until certain number of requests and as external source knowledge data where the RAG will retrieve the context is a vector database called ChromaDB. Now you’ll understand all this stuffs!!!</p><h4>Step 1:</h4><p>Import and install all libraries needed:</p><pre>from langchain_chroma import Chroma<br>from langchain.chains import RetrievalQA<br>from langchain.schema import Document<br>from langchain_community.embeddings import HuggingFaceEmbeddings<br>from langchain.prompts import PromptTemplate<br>import chromadb<br>import random</pre><p>I use <strong>langchain </strong>for leverage the lifecycle of every stage of the LLM application lifecycle and <strong>chromadb that is a vector database </strong>where we’ll store all our data.</p><h4>Step 2:</h4><p>We have to populate the data inside the database to provide a context that Llama will use later.</p><pre>client = chromadb.PersistentClient(path=&quot;chromadb&quot;)<br>collection = client.get_or_create_collection(name=&quot;my_collection&quot;)<br>documents = [<br>  &quot;Retrieval-augmented generation (RAG) is a technique for enhancing the accuracy and reliability of generative AI models with facts fetched from external sources... and much more...&quot;,<br>  &quot;VectorDB is a simple, lightweight, fully local, end-to-end solution, open-source for using embeddings-based text retrieval and much more ...&quot;<br>  ]<br>collection.add(<br>                documents=documents,<br>                ids=ids=[str(random.getrandbits(64)), str(random.getrandbits(64))]<br>            )</pre><p>Let me explain what I’ve done in the code above.</p><pre>client = chromadb.PersistentClient(path=&quot;chromadb&quot;)</pre><p>Initializes a persistent client for <strong>ChromaDB</strong>, a SQLite database for managing and retrieving embeddings (I’ll explain after). The data will be stored at the specified path, &quot;chromadb&quot;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/395/1*FC8y-_HWbRUVFLyJqjCDfw.png" /><figcaption>CHROMADB TABLES</figcaption></figure><pre>collection = client.get_or_create_collection(name=&quot;my_collection&quot;)</pre><p>Either retrieves an existing collection named &quot;my_collection&quot; from the database or creates it if it doesn&#39;t exist. A <strong>collection</strong> in ChromaDB typically stores related documents belonging to a specific domain. A <strong>document </strong>is your effective data, that can be plain text (like in this example), pdf and so on. Image collection as grouping of related documents and there can be a lot of collections in your database with his own specific documents.</p><pre>documents = [<br>  &quot;Retrieval-augmented generation (RAG) is a technique for enhancing the accuracy and reliability of generative AI models with facts fetched from external sources... and much more...&quot;,<br>  &quot;VectorDB is a simple, lightweight, fully local, end-to-end solution, open-source for using embeddings-based text retrieval and much more ...&quot;<br>  ]<br>collection.add(<br>                documents=documents,<br>                ids=ids=[str(random.getrandbits(64)), str(random.getrandbits(64))]<br>            )</pre><p>A list of documents to be added to the collection. In this case, the list contains two documents, which are a brief description of what is RAG and vectorDB. Imagine that Llama has not idea of what is RAG, and now we are feeding it with this new information (in real scenario you provide a file with a large context of this treat domain). The collection has a unique identifier. The ID is generated using a random 64-bit number to ensure it is unique, converted to a string.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*irOKVXYL9PaipH_GjxzURw.png" /></figure><h4>INVOKE LLM + RAG</h4><pre>embeddings = HuggingFaceEmbeddings(model_name=&quot;sentence-transformers/all-MiniLM-L6-v2&quot;)<br># initialize the chroma database<br>vectordb = Chroma(<br>  persist_directory=&quot;chromadb&quot;,<br>  embedding_function=embeddings,<br>  collection_name=&quot;my_collection&quot;<br>  )<br># build prompt<br>template = &quot;&quot;&quot;%s\nContext: {context}\nUser Question: {question}\nAnswer:&quot;&quot;&quot;<br>prompt = PromptTemplate(<br>  template=template % (&quot;Please answer using only five simple words&quot;),<br>  input_variables=[&quot;context&quot;, &quot;question&quot;]<br>)<br># attacch LLM with vectordb<br>qa_chain = RetrievalQA.from_chain_type(<br>  llm=ChatGroq(<br>            model_name=&quot;llama-3.1-70b-versatile&quot;,<br>            api_key=hf_token # insert your token<br>        ),<br>  chain_type=&quot;stuff&quot;,<br>  retriever=vectordb.as_retriever(search_kwargs={&quot;k&quot;:1}),<br>  verbose=True,<br>  return_source_documents=True,<br>  chain_type_kwargs={&quot;prompt&quot;: prompt, &quot;verbose&quot;: True}<br>)<br>return qa_chain.invoke({&quot;query&quot;: &quot;What is RAG?&quot;})[&#39;result&#39;]</pre><p>Don’t be afraid of this code, now I’ll cover all:</p><pre>embeddings = HuggingFaceEmbeddings(model_name=&quot;sentence-transformers/all-MiniLM-L6-v2&quot;)</pre><p>Initializes an embedding model from the Hugging Face library. This model converts text (like documents or queries) into vector representations (embeddings), which will be used for <strong>similarity searches</strong>.</p><pre>vectordb = Chroma(persist_directory=&quot;chromadb&quot;, embedding_function=embeddings, collection_name=&quot;my_collection&quot;)</pre><p>Loads a <strong>Chroma</strong> vector database from the specified directory &quot;chromadb&quot;. Then uses the embedding model (HuggingFaceEmbeddings) to convert text into vectors. Brief note that I’ll cover in a future article: vectorDB and embedding model serves to semantic research to retrieve most pertinent data from your catalog of data. And finally specifies the collection &quot;my_collection&quot; within the vector database, where documents will be retrieved from.</p><pre>template = &quot;&quot;&quot;%s\nContext: {context}\nUser Question: {question}\nAnswer:&quot;&quot;&quot;<br>prompt = PromptTemplate(template=template % (&quot;Please answer using only five simple words&quot;), input_variables=[&quot;context&quot;, &quot;question&quot;])</pre><p>Defines a template for structuring the prompt that will be sent to the model. The template includes placeholders for a context ({context}) and a user question ({question}), followed by the expected answer. These markers are valorized by LLM, you cannot do nothing. You can only act on <strong><em>%s</em> </strong>for adding your customize prompt, in my case: <em>Please answer using only a simple few words</em></p><pre>qa_chain = RetrievalQA.from_chain_type(<br>  llm=ChatGroq(model_name=&quot;llama-3.1-70b-versatile&quot;, api_key=hf_token),<br>  chain_type=&quot;stuff&quot;,<br>  retriever=vectordb.as_retriever(search_kwargs={&quot;k&quot;:1}),<br>  verbose=True, return_source_documents=True,<br>  chain_type_kwargs={&quot;prompt&quot;: prompt, &quot;verbose&quot;: True})</pre><ul><li>Initializes a <strong>RetrievalQA</strong> chain using a large language model (LLM) named &quot;llama-3.1-70b-versatile&quot; accessed via the <strong>ChatGroq</strong> interface, authenticated with the variable hf_token.</li><li>The chain_type=&quot;stuff&quot; specifies the method used to combine retrieved documents and the generated response. Use it by default.</li><li>Uses the vector database vectordb to retrieve relevant documents, with search_kwargs={&quot;k&quot;:1} specifying that the top 1 most relevant document will be retrieved.</li><li>verbose=True enables detailed logging of the process.</li><li>return_source_documents=True ensures that the retrieved source documents are returned with the result.</li><li>chain_type_kwargs={&quot;prompt&quot;: prompt, &quot;verbose&quot;: True} passes the custom prompt template to the chain and enables verbosity for this part of the process.</li></ul><pre>return qa_chain.invoke({&quot;query&quot;: &quot;What is RAG?&quot;})[&#39;result&#39;]</pre><p>Executes the question-answering chain by passing a query (&quot;What is RAG?&quot;) to the model via the invoke method and retrieves and returns the result of the query, which is extracted from the response using [&#39;result&#39;]</p><h3>REPORT RESULTS</h3><p>This is a custom prompt made up using RAG that will be used as input to a LLM to generate a response:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T7bJJPvjr9WFy8_T_d15JQ.png" /><figcaption>CONSOLE REPORT</figcaption></figure><p>In the console log, and the end of lines, the result of user request at question “What is RAG?” is the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/1*u2SU5wUnKjPuzNT8JfEflw.png" /><figcaption>CONSOLE RESULT</figcaption></figure><p>The context has been retrieved using the retrieval system that performs a search over the external data (database), returning the most relevant data or documents, in this case the context relative to RAG.</p><h3>CONCLUSION</h3><p>That’s all for now!!!</p><p>The code is a brief demonstration of what you can do with RAG + LLM. Note that is a powerful technology that you can use to enhance the reliability and accuracy of LLM answer, but much more! Please read the references to expand your knowledge if you’re curious.</p><p>If you like reading this post, follow also my linkedIn profile: <a href="http://www.linkedin.com/in/stefano-zogno-63716b18b">click here</a></p><p>Thanks for reading so far.</p><h4>REFERENCES</h4><ul><li><a href="https://docs.trychroma.com/">Chroma</a></li><li><a href="https://cookbook.chromadb.dev/">ChromaDB Cookbook | The Unofficial Guide to ChromaDB</a></li><li><a href="https://console.groq.com/docs/quickstart">GroqCloud</a></li><li><a href="https://python.langchain.com/v0.1/docs/get_started/quickstart/">Tutorials | 🦜️🔗 LangChain</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c77a1785277" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>