<?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 Neelamyadav on Medium]]></title>
        <description><![CDATA[Stories by Neelamyadav on Medium]]></description>
        <link>https://medium.com/@neelamyadav10053?source=rss-8ea043d1bf12------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*SzvhRvRe8_GGVRWyYhu_eg.png</url>
            <title>Stories by Neelamyadav on Medium</title>
            <link>https://medium.com/@neelamyadav10053?source=rss-8ea043d1bf12------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 23:23:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@neelamyadav10053/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[Attention Is All You Need Explained Simply: The Paper That Changed Modern AI]]></title>
            <link>https://medium.com/@neelamyadav10053/attention-is-all-you-need-explained-simply-the-paper-that-changed-modern-ai-dc693d52679f?source=rss-8ea043d1bf12------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc693d52679f</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Neelamyadav]]></dc:creator>
            <pubDate>Fri, 17 Jul 2026 06:42:00 GMT</pubDate>
            <atom:updated>2026-07-17T06:47:05.699Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BHO60xqHbJAPsgHvcLvXYg.png" /></figure><p><strong>How Transformers moved AI beyond RNNs, why self-attention matters, and how this idea became the foundation of GPT, BERT, ChatGPT, and modern Large Language Models.</strong></p><p>Watch the full video here:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FcwGDHruw20I%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DcwGDHruw20I&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FcwGDHruw20I%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/e6e7c4b2d0f448949d8886133ed919ae/href">https://medium.com/media/e6e7c4b2d0f448949d8886133ed919ae/href</a></iframe><p>A few years ago, if you wanted to understand Natural Language Processing, you had to learn about RNNs, LSTMs, GRUs, and encoder-decoder models.</p><p>Today, almost every serious discussion around modern AI eventually reaches one word which is: <strong>Transformers</strong></p><p>Transformers power many of the systems we now associate with Generative AI: GPT, ChatGPT, BERT, T5, Claude-style models, Gemini-style models, and many other Large Language Models.</p><p>But the Transformer did not appear out of nowhere. It came from a 2017 research paper with a bold title:</p><h4>Attention Is All You Need</h4><p>At first, the title sounds almost too simple.</p><p>But behind that title was a major shift in how machines process language.</p><p>This blog explains that shift in a beginner-friendly way. We will move from RNNs to attention, then to self-attention, and finally to Transformers.</p><p>No heavy mathematics.<br>No unnecessary jargon.<br>Just the core idea explained clearly.</p><h3>Why This Paper Matters</h3><p>Before Transformers became popular, sequence-based AI tasks were mostly handled by models such as:</p><ul><li>RNNs</li><li>LSTMs</li><li>GRUs</li></ul><p>These models were widely used for:</p><ul><li>Machine translation</li><li>Speech recognition</li><li>Text generation</li><li>Sentiment analysis</li><li>Time-series prediction</li></ul><p>They worked, but they had limitations.</p><p>Then attention was introduced. Attention helped models focus on the most relevant parts of the input instead of treating every word equally.</p><p>The Transformer took that idea much further.</p><p>The journey looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8FGD6FFx_FQ3d569MAfb-g.png" /></figure><p>That is why this paper matters.</p><p>It was not just another model architecture. It changed the direction of modern AI.</p><h3>Start with the Basics: What Is a Sequence?</h3><p>A sequence is data where order matters.</p><p>For example:</p><pre>I → love → machine → learning</pre><p>This sentence is not just a bag of words. The order creates meaning. If we randomly rearrange the words, the meaning becomes unclear.</p><p>Language is a sequence because each word depends on the words around it.</p><p>But sequences are not limited to text.</p><p>Examples include:</p><ul><li>Speech as a sequence of sounds</li><li>Music as a sequence of notes</li><li>Video as a sequence of frames</li><li>Stock prices as a sequence over time</li><li>Sensor readings as a sequence of measurements</li></ul><p>Because order matters, early neural networks for language needed a way to remember previous information while reading new information.</p><p>That is where RNNs came in.</p><h3>What an RNN Tries to Do</h3><p>RNN stands for <strong>Recurrent Neural Network</strong>.</p><p>The basic idea is simple:</p><p>An RNN reads data one step at a time.</p><p>For a sentence, it reads one word at a time:</p><pre>The → cat → sat → on → the → mat</pre><p>When the RNN reads the word <strong>“cat,”</strong> it also carries some memory from the previous word <strong>“The.” </strong>This memory is called the <strong>hidden state</strong>.</p><p>A simple way to think about it is:</p><pre>Current word + Previous memory = New memory</pre><p>That new memory is passed forward to the next word.</p><p>So an RNN is like a reader moving through a sentence step by step while carrying a small memory of what it has already seen.</p><h3>Where RNNs Struggle</h3><p>RNNs were important, but they had major limitations.</p><h4>1. They Process Sequentially</h4><p>An RNN must process word 1 before word 2, word 2 before word 3, and so on.</p><p>This makes sense for reading, but it creates a computational problem.</p><h4>2. They Are Harder to Train Efficiently</h4><p>Modern GPUs are powerful because they can run many calculations in parallel.</p><p>But RNNs are naturally step-by-step. Because every step depends on the previous step, training can become slow.</p><h4>3. They Struggle with Long-Term Dependencies</h4><p>Information from the beginning of a long sentence may become weak by the time the model reaches the end.</p><p>This is called the <strong>long-term dependency problem</strong>.</p><h3>Long-Term Dependency Problem</h3><p>Look at this sentence:</p><pre>The animal crossed the road, walked through the field, and entered the house because it was tired.</pre><p>The word <strong>“it”</strong> refers to <strong>“the animal.” </strong>But “animal” appears much earlier in the sentence.</p><p>For an RNN, information about “animal” has to travel through many intermediate words before reaching “it.”</p><p>The longer the sentence becomes, the harder it is to preserve that earlier information.</p><p>LSTMs and GRUs improved this problem, but they still followed the same step-by-step processing pattern.</p><p>So the AI community needed a better way to connect related words, even when they were far apart.</p><h3>The Encoder-Decoder Bottleneck</h3><p>Older translation systems often used an <strong>encoder-decoder</strong> architecture.</p><p>The encoder read the input sentence and compressed its meaning into one fixed-size representation called a <strong>context vector</strong>.</p><p>The decoder then used that context vector to generate the output sentence.</p><p>For short sentences, this approach worked reasonably well.</p><p>But for long sentences, it created a bottleneck.</p><p>Imagine reading an entire book and trying to write every important point on one sticky note. Something will be lost.</p><p>That was the problem.</p><p>The model needed a way to directly access the important parts of the input instead of depending only on one compressed vector.</p><p>This need led to attention.</p><h3>What Attention Means</h3><p>Attention means focusing on what matters most.</p><p>Suppose someone asks:</p><pre>What is the capital of France?</pre><p>You do not give equal importance to every word.</p><p>You focus mainly on:</p><pre>capital + France</pre><p>That is enough to answer:</p><pre>Paris</pre><p>Attention gives a neural network a similar ability.</p><p>Instead of treating every word equally, the model learns which words are more important for the current task.</p><p>In practical terms, attention helps the model answer:</p><pre>Which part of the input should I focus on right now?</pre><h3>Attention Before Transformers</h3><p>Attention was first used as an improvement to RNN-based encoder-decoder models.</p><p>The encoder and decoder were still recurrent.</p><p>But now the decoder could look back at all encoder hidden states instead of depending only on one final context vector.</p><p>While generating one translated word, the decoder could focus on one part of the input sentence.</p><p>While generating the next word, it could focus somewhere else.</p><p>Attention reduced the bottleneck.</p><p>But one major limitation remained:</p><p>The model was still built around recurrence.</p><h3>The Big Transformer Idea</h3><p>The Transformer paper proposed a simple but powerful shift:</p><pre>Remove recurrence.<br>Make attention the main mechanism.</pre><p>Instead of passing information word by word, the Transformer allows tokens to directly connect with other relevant tokens.</p><p>This has two major benefits:</p><ul><li>Training becomes more parallel.</li><li>Distant words can connect more directly.</li></ul><p>That is the core idea behind the title:</p><h4>Attention Is All You Need</h4><p>The Transformer still has other important parts like embeddings, feed-forward networks, normalization, and positional encoding.</p><p>But attention became the main mechanism for sharing information across the sequence.</p><h3>What Is Self-Attention?</h3><p>Self-attention means that each word looks at other words in the same sentence to understand its own meaning.</p><p>For example, take the word <strong>“bank” </strong>in below sentences:</p><p>In this sentence:</p><pre>The bank approved my loan.</pre><p>“Bank” means a financial institution.</p><p>But in this sentence:</p><pre>I sat near the bank of the river.</pre><p>“Bank” means the side of a river.</p><p>The same word changes meaning because the surrounding context changes.</p><p>Self-attention helps the model understand this context.</p><p>Self-attention uses three important vectors:</p><ul><li>Query</li><li>Key</li><li>Value</li></ul><p>The <strong>Query</strong> represents:</p><pre>What am I looking for?</pre><p>The <strong>Key</strong> represents:</p><pre>What information do I contain?</pre><p>The <strong>Value</strong> represents:</p><pre>What information should I provide if I am relevant?</pre><p>A simple analogy is search.</p><p>When you search on Google, your search text is the Query.</p><p>Each result has information that helps decide whether it matches your search. That is like the Key.</p><p>The actual page content is the Value.</p><p>Every token in a Transformer creates its own Query, Key, and Value.</p><h3>How Attention Works</h3><p>At a high level, attention works in four steps:</p><ol><li>Compare Query with Keys.</li><li>Calculate attention scores.</li><li>Apply Softmax.</li><li>Combine Values.</li></ol><p>A higher attention score means that word is more relevant.</p><p>The formula looks like this:</p><pre>Attention(Q,K,V) = Softmax(QKᵀ / √dₖ)V</pre><p>For beginners, the formula can be understood as:</p><pre>Compare words.<br>Find important words.<br>Use more information from those words.</pre><h3>Multi-Head Attention</h3><p>One attention head may learn one kind of relationship.</p><p>For example:</p><ul><li>One head may focus on grammar.</li><li>One head may focus on meaning.</li><li>One head may connect pronouns to nouns.</li><li>One head may capture subject-object relationships.</li></ul><p>Language contains many relationships at the same time.</p><p>So the Transformer uses multiple attention heads.</p><p>This is called <strong>multi-head attention</strong>.</p><p>A simple analogy is a group of experts reading the same sentence.</p><p>One expert checks grammar.<br>Another checks meaning.<br>Another checks references.<br>Another checks actions and objects.</p><p>When their observations are combined, the understanding becomes richer.</p><h3>How the Transformer Understands Word Order</h3><p>An RNN naturally knows word order because it reads words one by one.</p><p>A Transformer processes tokens largely in parallel.</p><p>So it needs another way to know position.</p><p>Consider:</p><pre>Dog bites man.</pre><p>and:</p><pre>Man bites dog.</pre><p>The words are almost the same, but the meaning is different.</p><p>The Transformer solves this using <strong>positional encoding</strong>.</p><p>Each token receives:</p><pre>Token Embedding + Position Information</pre><p>The embedding tells the model what the word means.</p><p>The position information tells the model where the word appears.</p><h3>Transformer Architecture: Encoder and Decoder</h3><p>The original Transformer was designed mainly for translation.</p><p>It has two major parts:</p><ul><li>Encoder</li><li>Decoder</li></ul><p>The <strong>encoder</strong> reads and understands the input.</p><p>The <strong>decoder</strong> generates the output.</p><p>For example:</p><pre>English sentence → Encoder → Decoder → French sentence</pre><p>This encoder-decoder structure was especially useful for tasks where one sequence is converted into another sequence.</p><h3>Transformer Encoder Explained</h3><p>The encoder’s job is to understand the input sentence.</p><p>It is made of multiple layers stacked on top of each other.</p><p>Inside each encoder layer, two main things happen.</p><h4>1. Multi-Head Self-Attention</h4><p>Each word looks at other words and collects useful information.</p><h4>2. Feed-Forward Network</h4><p>The model processes and improves the information collected through attention.</p><p>The encoder also uses <strong>Add and Normalize</strong> steps.</p><p>For beginners, remember:</p><pre>Add and Normalize helps the model stay stable and preserve useful information.</pre><p>The simple encoder flow is:</p><pre>Self-Attention → Add &amp; Normalize → Feed-Forward → Add &amp; Normalize</pre><p>After several layers, the encoder creates a rich understanding of the input.</p><h3>Transformer Decoder Explained</h3><p>The decoder’s job is to generate the output.</p><p>The decoder generates text step by step.</p><p>For example:</p><pre>Artificial intelligence<br>Artificial intelligence is<br>Artificial intelligence is changing<br>Artificial intelligence is changing the<br>Artificial intelligence is changing the world</pre><p>Inside the decoder, three main things happen:</p><h4>1. Masked Self-Attention</h4><p>The decoder can look only at words it has already generated.</p><h4>2. Encoder-Decoder Attention</h4><p>The decoder looks at the encoder’s understanding of the input.</p><h4>3. Feed-Forward Processing</h4><p>The decoder further processes the information before producing output.</p><p>The most important point is:</p><pre>The decoder cannot look into the future while predicting the next word.</pre><p>That is why masking is important.</p><h3>What Masking Means</h3><p>Suppose the model must complete this sentence:</p><pre>Artificial intelligence is changing the ___</pre><p>During training, the correct future word may already exist in the data.</p><p>Without masking, the model could look ahead and copy the answer.</p><p>That would not be learning.</p><p>Masked self-attention blocks future words.</p><p>The model can only use previous words to predict the next word.</p><p>This idea is central to GPT-style text generation.</p><h3>RNN vs Transformer</h3><p>Here is the difference in simple terms:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xBCj9Gtu2HnBU2Doo-YNxQ.png" /></figure><p>A simple way to remember it:</p><pre>RNN = step-by-step memory<br>Transformer = direct relationship finding</pre><h3>Is the Transformer Perfect?</h3><p>No.</p><p>Transformers are powerful, but they have limitations.</p><p>Some important ones are:</p><ul><li>Standard self-attention can use a lot of memory.</li><li>Longer sequences require more computation.</li><li>Large Transformers need huge amounts of data.</li><li>Training large models can be expensive.</li><li>Models can still produce incorrect answers.</li></ul><p>Attention helps the model find relationships. It does not guarantee truth. That distinction is important.</p><h3>How This Led to BERT, GPT, and Modern LLMs</h3><p>The original Transformer had both an encoder and a decoder.</p><p>Later models used different parts of that architecture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wGrwrXvGBzec2sZWohZYsA.png" /></figure><h3>How GPT Generates Text</h3><p>GPT generates text one token at a time.</p><p>Suppose the input is:</p><pre>Artificial intelligence is</pre><p>The model may predict:</p><pre>changing</pre><p>Now the sequence becomes:</p><pre>Artificial intelligence is changing</pre><p>Then it predicts the next token again.</p><p>This process continues repeatedly. This is called <strong>autoregressive generation</strong>.</p><h3>The Complete Transformer Flow</h3><p>The full flow looks like this:</p><pre>Raw Text<br>↓<br>Tokens<br>↓<br>Embeddings + Positions<br>↓<br>Self-Attention<br>↓<br>Feed-Forward Layers<br>↓<br>Prediction</pre><p>Raw text becomes tokens.</p><p>Tokens become embeddings. Position information is added.</p><p>Self-attention helps tokens collect useful context.</p><p>Feed-forward networks process the information.</p><p>Finally, the model produces a prediction.</p><h3>Final Summary</h3><p>Let us quickly revise the journey.</p><p>We started with <strong>sequences</strong>, where order matters.</p><p>Then we saw how <strong>RNNs</strong> processed sequences step by step.</p><p>We understood their limitations:</p><ul><li>Sequential processing</li><li>Slow training</li><li>Difficulty with long-term dependencies</li></ul><p>Then we saw how <strong>attention</strong> helped models focus on relevant information.</p><p>The <strong>Transformer</strong> removed recurrence and made self-attention the main mechanism.</p><p>Its key ideas include:</p><ul><li>Query, Key, and Value</li><li>Multi-head attention</li><li>Positional encoding</li><li>Encoder and decoder architecture</li><li>Masking for next-token prediction</li></ul><p>This architecture became the foundation of:</p><ul><li>BERT</li><li>GPT</li><li>T5</li><li>ChatGPT</li><li>Modern Large Language Models</li></ul><h3>Watch the Full Video</h3><p>I have also explained this complete topic in a beginner-friendly YouTube video with slides and examples.</p><p>👉 <strong>Watch here:</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FcwGDHruw20I%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DcwGDHruw20I&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FcwGDHruw20I%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/e6e7c4b2d0f448949d8886133ed919ae/href">https://medium.com/media/e6e7c4b2d0f448949d8886133ed919ae/href</a></iframe><p>If you are learning <strong>AI, ML, Generative AI, LLMs, or Transformers</strong>, this is one of the most important concepts to understand.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc693d52679f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Agentic AI Design Patterns that 90% of Teams Use]]></title>
            <link>https://pub.towardsai.net/agentic-ai-design-patterns-that-90-of-teams-use-03b3bb481d62?source=rss-8ea043d1bf12------2</link>
            <guid isPermaLink="false">https://medium.com/p/03b3bb481d62</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Neelamyadav]]></dc:creator>
            <pubDate>Wed, 08 Oct 2025 12:01:59 GMT</pubDate>
            <atom:updated>2026-08-04T13:36:31.435Z</atom:updated>
            <content:encoded><![CDATA[<p>No more guesswork with LLMs. This guide walks you through the small set of agentic patterns that actually work in practice — what they mean, when to pick them, and how they look in clear architecture diagrams.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VsXVerbH6M7RC0JwtBce2g.png" /></figure><p>🎥 Don’t want to read, go here:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FtJdWWWdj254%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DtJdWWWdj254&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FtJdWWWdj254%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/86bba461e1d4baa5130e6220a23d5c19/href">https://medium.com/media/86bba461e1d4baa5130e6220a23d5c19/href</a></iframe><h3>Introduction</h3><p>Most LLM apps are like smart autocomplete — you ask, they reply. <strong>Agentic AI</strong> goes further — it:</p><ol><li>plans steps,</li><li>uses tools/APIs,</li><li>checks its work, and</li><li>asks a human before doing anything risky.</li></ol><p>In this blog, we’ll cover the patterns you’ll see in about <strong>90% of production systems</strong>.</p><blockquote>Rule of thumb: <strong>start simple</strong>. If one LLM call is enough, use it. Add more structure only when it boosts reliability, safety, or scale.</blockquote><h3>What is Agentic AI</h3><p><strong>Agentic AI</strong> is an LLM that can make small decisions, take actions, and learn as it goes. Think of it as a careful helper that works in steps:</p><p><strong>Observe → Think → Plan → Act → Verify → Learn</strong></p><ul><li><strong>Observe:</strong> read the request and any needed docs or logs.</li><li><strong>Think:</strong> decide the next best move.</li><li><strong>Plan (optional):</strong> outline a few steps if the task is bigger.</li><li><strong>Act:</strong> call a tool/API, run a query, or write a file.</li><li><strong>Verify:</strong> check quality/safety; ask a human if it’s risky.</li><li><strong>Learn:</strong> save useful notes so the next run is better.</li></ul><h3>Agentic AI Design Patterns ( Core 4 )</h3><p>The four patterns you’ll use most — again and again.</p><h3>1) Tool Use (Function Calling)</h3><h4>What it is?</h4><p>Tool Use pattern<strong> </strong>lets an agent go beyond what it “knows” by calling external tools — APIs, databases, or custom functions.<br>With this pattern the agent can:</p><ul><li>fetch real-time data,</li><li>run calculations, and</li><li>perform actions in other systems.</li></ul><p>The key is that the agent decides when a tool is needed, picks the right tool, and then uses the tool’s result to finish the task.</p><h4>When to use</h4><ul><li><strong>Look up a record</strong><br>“What’s the order status for ID 4829?” → call get_order(id=4829) and return status/ETA.</li><li><strong>Transform or convert</strong><br>“Turn this CSV into JSON.” → call convert_csv_to_json(file=...).</li><li><strong>Light analytics</strong><br>“What’s the 95th percentile of these numbers?” → call stats.percentile(values, 95).</li><li><strong>Trigger one action</strong><br>“Create a short URL for this link.” → call shorten_url(https://medium.com/url=...).</li><li><strong>Send a notification</strong><br>“Email the report to finance.” → call send_email(to=..., attachment=...) (often behind approval).</li></ul><h4>Cons</h4><ul><li>If the request isn’t clear, the model may call a tool with the wrong fields. Use <strong>schema validation</strong> and show <strong>friendly error messages</strong>.</li><li>Calls can time out or fail. Add <strong>timeouts</strong>, <strong>retries with backoff</strong>, and sensible <strong>error handling</strong>.</li><li>Some tools change real systems. <strong>Allow-list</strong> approved tools only and keep <strong>audit logs</strong> of every call.</li></ul><h4>Architecture Diagram</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UqLNz_DUM7EgRSTOwVObHA.png" /></figure><h3>2) Planning (Plan-then-Execute)</h3><h4>What it is?</h4><p>The agent <strong>creates a short plan first</strong>, then executes each step with a <strong>quick verify</strong>. If a step fails, it <strong>repairs or replans</strong> and continues. If you’ve seen “ReAct,” think of it as interleaving reasoning and actions. Planning is the more explicit, step-by-step version.</p><h4>When to use</h4><ul><li><strong>Data pipeline / report</strong><br><em>“Ingest → clean → join → validate → export dashboard.”</em><br> Each stage runs only after the previous one passes a quick check.</li><li><strong>Research brief</strong><br><em>“Find 5 sources → extract key facts → draft → fact-check → finalize with citations.”</em></li><li><strong>Ops weekly update</strong><br><em>“Pull metrics → summarize risks → draft email → tone check → send (with approval).”</em></li><li><strong>Content production</strong><br><em>“Outline → draft → style check → fix → publish.”</em></li></ul><h4>Cons</h4><ul><li>Over-planning wastes tokens and time (keep plans to 3–8 steps).1</li><li><strong>More steps can slow things down.</strong> Add <strong>time limits per step</strong> to control latency.</li><li>Needs <strong>checkpoints</strong> and <strong>idempotency</strong> to survive retries/crashes.</li></ul><h4>Architecture Diagram</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s4_ESM9oDoW_hMAfrXO6ww.png" /></figure><h3>3) Reflection</h3><h4>What it is?</h4><p>The agent gets better by reviewing its own work. It first creates an output, then — either the same model in a second step or a separate critic model — checks for mistakes and unclear parts, gives feedback, and the agent revises the answer. This loop boosts accuracy, reliability, and autonomy, so the system needs less constant human oversight.</p><h4>When to use</h4><ul><li><strong>Customer emails / chat replies</strong><br>Keep messages <strong>accurate, polite, and within policy;</strong> flag or remove risky phrases.</li><li><strong>Code patches</strong><br>Ensure the change <strong>compiles</strong>, <strong>tests pass</strong>, and suggest a <strong>safer alternative</strong> if needed.</li><li><strong>Regulated text</strong><br>Enforce <strong>approved wording</strong>, avoid <strong>medical/financial claims</strong>, and <strong>require citations</strong>.</li><li><strong>Summaries</strong><br>Demand <strong>sources and relevance </strong>so as to cut down on hallucinations and fluff.</li></ul><h4>Cons</h4><ul><li>Adds cost and time. Limit to no more than 2 passes.</li><li>Vague checklists cause over-editing. Keep checks specific and concrete.</li><li>Avoid infinite fix loops. Set a clear stop condition (e.g., “stop after 2 tries or if no new issues found”).</li></ul><h4>Architecture Diagram</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BHVwBhOd2bCdo_NhhyxwkQ.png" /></figure><h3>4) Multi-Agent Collaboration (Supervisor / Worker)</h3><h4>What it is?</h4><p>Use several small, specialized AI agents that work together on one goal. The big task is split into subtasks and delegated to different agents (e.g., a planner, an executor, a reviewer). They communicate, coordinate, and share progress so the team delivers a single, better result than a lone agent.</p><h4>When to use</h4><ul><li><strong>Parallel research</strong><br><em>“Agent A finds sources, Agent B extracts numbers, Agent C writes the draft; Supervisor merges and checks.”</em></li><li><strong>Complex operations</strong><br><em>“Security triage: one agent scans logs, another checks indicators of compromise, a third proposes actions; Supervisor coordinates and escalates.”</em></li><li><strong>Data quality ops</strong><br><em>“Worker A fixes schema, Worker B flags anomalies, Worker C writes the report; Supervisor tracks status to ‘done.’”</em></li></ul><h4>Cons</h4><ul><li><strong>Coordination overhead:</strong> Multiple agents can trip over each other. Use locks/leases (simple “check-out” rules) to avoid race conditions and duplicate work.</li><li><strong>Harder to observe/debug:</strong> Add traces, task IDs, and a shared state/blackboard so you can see who did what and why.</li><li><strong>Cost and latency can climb:</strong> Start small — often two agents (doer + checker) are enough. Scale up only when you see a clear benefit.</li></ul><h4>Architecture Diagram (image prompt)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rOeOSkd4onwAwBDc-fo0pA.png" /></figure><h3>Quick chooser (at a glance)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Px1NS8k0RTlQjCcaNARItw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=03b3bb481d62" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/agentic-ai-design-patterns-that-90-of-teams-use-03b3bb481d62">Agentic AI Design Patterns that 90% of Teams Use</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enterprise RAG on AWS: From Scattered Docs to Trusted Answers at TB-Scale]]></title>
            <link>https://pub.towardsai.net/enterprise-rag-on-aws-from-scattered-docs-to-trusted-answers-at-tb-scale-30e5a4c6be94?source=rss-8ea043d1bf12------2</link>
            <guid isPermaLink="false">https://medium.com/p/30e5a4c6be94</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Neelamyadav]]></dc:creator>
            <pubDate>Wed, 10 Sep 2025 10:53:04 GMT</pubDate>
            <atom:updated>2026-08-10T04:46:47.506Z</atom:updated>
            <content:encoded><![CDATA[<h4>If your AI can’t prove where its answers come from, it isn’t enterprise — yet.</h4><h3>Overview</h3><p>We built a <strong>product-ready RAG system</strong> on AWS that turns thousands of PDFs, pages, and internal documents into <strong>accurate, current, citable</strong> answers. At terabyte scale, the wins are simple:</p><ul><li><strong>Speed:</strong> answers in seconds instead of hours of hunting</li><li><strong>Confidence:</strong> citations and validation stop costly mistakes</li><li><strong>Cost control:</strong> re-embed only what changed</li><li><strong>Adoption:</strong> people trust and reuse results</li></ul><h3>Why We Built This</h3><p><strong>8:00 a.m.</strong>: The official <em>Returns &amp; Refunds</em> policy updates from <strong>30 days → 14 days</strong> in a signed PDF.<br><strong>2:00 p.m.</strong>: A support agent replies using an <strong>old internal note</strong> that still promises <strong>30 days</strong>.<br><strong>Day 20:</strong> The customer returns the product. The warehouse rejects the item (new policy), the customer shows the agent’s message (old policy), and we — rightly — <strong>compensate</strong> to protect the relationship (shipping, fees, goodwill coupon).</p><p>This wasn’t “bad search.” It was a <strong>confidence</strong> failure: the answer wasn’t <strong>correct</strong> (approved source), <strong>current</strong> (latest version), or <strong>citable</strong> (provable in the moment).</p><blockquote>We didn’t need another chatbot. We needed a <strong>trusted answer engine</strong>.</blockquote><h3>What “Trusted” Means (Design Principles)</h3><ol><li><strong>Store cleanly</strong> — single source of truth with versions.</li><li><strong>Automate updates</strong> — no manual refresh paths.</li><li><strong>Validate before serving</strong> — a quality gate.</li><li><strong>Retrieve by meaning</strong> — semantic search, not keyword guesses.</li><li><strong>Explain with citations</strong> — every answer can show its sources.</li><li><strong>Observe &amp; improve</strong> — drift detection, feedback, and monitoring.</li></ol><p>Everything in the architecture maps 1:1 to these controls.</p><h3>The Architecture</h3><blockquote>Read Left → Right</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cq7eroUSZqpJ-2XaYroSbQ.png" /><figcaption>Enterprise RAG Architecture</figcaption></figure><p><strong>Left:</strong> <strong>Ingestion &amp; Indexing (Data Plane)</strong> — makes knowledge <strong>clean, validated, searchable</strong><br><strong>Right:</strong> <strong>Serving &amp; Retrieval (Application Plane)</strong> — returns <strong>grounded answers with citations</strong></p><h3>Stack at a Glance</h3><ul><li><strong>S3 + Delta Lake</strong> — data lakehouse (raw docs, processed chunks, embeddings)</li><li><strong>Amazon MWAA (Airflow)</strong> — <em>ingest → preprocess → embed → index</em> (automation)</li><li><strong>AWS Glue + Amazon Athena</strong> — validation gate before production</li><li><strong>Qdrant on ECS</strong> — vector database for low-latency semantic retrieval</li><li><strong>FastAPI on ECS + ALB</strong> — API entry point &amp; orchestration</li><li><strong>Amazon Bedrock</strong> — LLM that writes grounded answers (with citations)</li><li><strong>Amazon DynamoDB</strong> — governance ledger (doc versions, drift, feedback)</li><li><strong>Amazon CloudWatch</strong> — logs, metrics, dashboards, and alerts</li></ul><h3>Ingestion &amp; Indexing (Data Plane)</h3><h4>1) S3 + Delta Lake — Where Trust Begins</h4><p>Delta Lake turns S3 into a <strong>lakehouse</strong> with ACID transactions, schema evolution, and time-travel. We keep three Delta areas:</p><ul><li><strong>Raw Documents</strong> (as they arrive)</li><li><strong>Processed Chunks</strong> (cleaned and split text, Delta table)</li><li><strong>Embeddings</strong> (vector fingerprints per chunk, Delta table)</li></ul><p><strong>Why Delta instead of “just S3”?</strong><br> At TB-scale, you need <strong>ACID</strong>, <strong>schema evolution</strong>, <strong>compaction</strong>, <strong>partitioning</strong>, and SQL access (Athena/Spark) to validate and audit safely.</p><p><em>Delta write example (PySpark):</em></p><pre># pyspark --packages io.delta:delta-spark_2.12:3.2.0<br>from pyspark.sql import SparkSession<br>from pyspark.sql.functions import current_date, lit<br>spark = SparkSession.builder \<br>    .appName(&quot;rag-embeddings-write&quot;) \<br>    .config(&quot;spark.sql.extensions&quot;, &quot;io.delta.sql.DeltaSparkSessionExtension&quot;) \<br>    .config(&quot;spark.sql.catalog.spark_catalog&quot;, &quot;org.apache.spark.sql.delta.catalog.DeltaCatalog&quot;) \<br>    .getOrCreate()<br><br># df_chunks: doc_id, chunk_id, chunk_text, dataset<br># df_embeds: doc_id, chunk_id, embedding (array&lt;float&gt;), model_id<br>dt = &quot;2025-09-01&quot;<br><br>(df_chunks<br> .withColumn(&quot;dt&quot;, lit(dt))<br> .write.format(&quot;delta&quot;)<br> .mode(&quot;append&quot;)<br> .partitionBy(&quot;dt&quot;)<br> .save(&quot;s3://&lt;lake-bucket&gt;/delta/processed/&quot;))<br><br>(df_embeds<br> .withColumn(&quot;dt&quot;, lit(dt))<br> .write.format(&quot;delta&quot;)<br> .mode(&quot;append&quot;)<br> .partitionBy(&quot;dt&quot;)<br> .save(&quot;s3://&lt;lake-bucket&gt;/delta/embeddings/&quot;))</pre><blockquote><strong>Tip:</strong> Compact tiny files regularly (OPTIMIZE / compaction jobs) and partition by dt / dataset.</blockquote><p><strong>Minimal schemas that work:</strong></p><p><em>Processed chunks (Delta):</em></p><pre>doc_id STRING,<br>chunk_id STRING,<br>dataset STRING,<br>dt DATE,<br>version STRING,<br>chunk_text STRING,<br>metadata MAP&lt;STRING,STRING&gt;</pre><p><em>Embeddings (Delta):</em></p><pre>doc_id STRING,<br>chunk_id STRING,<br>model_id STRING,<br>embedding ARRAY&lt;FLOAT&gt;,  -- size = dim<br>dt DATE,<br>version STRING,<br>metadata MAP&lt;STRING,STRING&gt;</pre><h4>2) Amazon MWAA (Airflow) — Change That Runs Itself</h4><p>Airflow is the <strong>single conductor.</strong> It:</p><ul><li><strong>Reads</strong> Raw from Delta</li><li><strong>Writes</strong> Processed &amp; Embeddings back to Delta</li><li><strong>Triggers</strong> Glue crawlers / Spark jobs</li><li><strong>Runs</strong> Athena validations (gate)</li><li><strong>Upserts</strong> validated vectors to Qdrant</li><li><strong>Updates</strong> DynamoDB with doc_id → version/hash for drift detection</li></ul><p><strong>Pipeline:</strong> <em>Ingest → Preprocess → Embed → Index</em><br><em>Properties</em>: <strong>idempotent </strong>(safe to rerun) , <strong>retries</strong>, <strong>full logs</strong>; fans out heavy work to Glue/Spark.</p><p><em>Pseudo-DAG:</em></p><pre># rag_ingest_and_index (skeleton)<br>ingest_raw      -&gt; preprocess -&gt; embed -&gt; write_delta<br>write_delta     -&gt; glue_crawl -&gt; athena_validate<br>athena_validate -&gt; [index_qdrant if PASS, stop if FAIL]<br>index_qdrant    -&gt; update_dynamodb_versions</pre><p><em>DAG skeleton (Airflow + boto3 for reliability):</em></p><pre>from datetime import datetime, timedelta<br>import time, json, hashlib, boto3<br>from airflow import DAG<br>from airflow.operators.python import PythonOperator<br><br>ATHENA_DB = &quot;rag_prod&quot;<br>ATHENA_OUTPUT = &quot;s3://&lt;lake-bucket&gt;/athena-results/&quot;<br>GLUE_CRAWLER_NAME = &quot;rag-delta-crawler&quot;<br><br>session = boto3.Session()<br>glue = session.client(&quot;glue&quot;)<br>athena = session.client(&quot;athena&quot;)<br>dynamodb = session.client(&quot;dynamodb&quot;)<br><br>def run_glue_crawler(**_):<br>    glue.start_crawler(Name=GLUE_CRAWLER_NAME)<br><br>def run_athena(query):<br>    exec_id = athena.start_query_execution(<br>        QueryString=query,<br>        QueryExecutionContext={&quot;Database&quot;: ATHENA_DB},<br>        ResultConfiguration={&quot;OutputLocation&quot;: ATHENA_OUTPUT},<br>    )[&quot;QueryExecutionId&quot;]<br>    while True:<br>        q = athena.get_query_execution(QueryExecutionId=exec_id)<br>        state = q[&quot;QueryExecution&quot;][&quot;Status&quot;][&quot;State&quot;]<br>        if state in (&quot;SUCCEEDED&quot;, &quot;FAILED&quot;, &quot;CANCELLED&quot;):<br>            if state != &quot;SUCCEEDED&quot;:<br>                raise RuntimeError(f&quot;Athena failed: {state}&quot;)<br>            return exec_id<br>        time.sleep(2)<br><br>def athena_validate(**_):<br>    checks = [<br>        &quot;SELECT COUNT(*) AS c FROM processed_chunks WHERE chunk_text IS NULL&quot;,<br>        &quot;SELECT COUNT(*) AS c FROM embeddings WHERE cardinality(embedding) &lt;&gt; 1024&quot;,<br>        &quot;SELECT CAST(MAX(dt) AS VARCHAR) AS latest_dt FROM processed_chunks&quot;,<br>    ]<br>    for q in checks:<br>        run_athena(q)<br><br>def index_qdrant(**_):<br>    # Pull validated rows (e.g., via Athena CTAS or Spark job), then upsert to Qdrant<br>    # Leave implementation to a batch indexer (see Qdrant section)<br>    pass<br><br>with DAG(<br>    &quot;rag_ingest_and_index&quot;,<br>    start_date=datetime(2025, 1, 1),<br>    schedule_interval=&quot;@daily&quot;,<br>    catchup=False,<br>    max_active_runs=1,<br>    default_args={<br>        &quot;retries&quot;: 2,<br>        &quot;retry_delay&quot;: timedelta(minutes=5),<br>        &quot;owner&quot;: &quot;rag-platform&quot;,<br>    },<br>) as dag:<br><br>    # (You’d add: ingest_raw, preprocess, embed, write_delta as PythonOperators)<br>    glue_crawl = PythonOperator(task_id=&quot;glue_crawl&quot;, python_callable=run_glue_crawler)<br>    validate = PythonOperator(task_id=&quot;athena_validate&quot;, python_callable=athena_validate)<br>    index = PythonOperator(task_id=&quot;index_qdrant&quot;, python_callable=index_qdrant)<br><br>    glue_crawl &gt;&gt; validate &gt;&gt; index</pre><blockquote>Why boto3 instead of a provider operator? It’s portable and explicit. If you prefer Airflow’s Glue/Athena operators, keep their params aligned with your environment (workgroups, connections).</blockquote><h4>3) AWS Glue + Amazon Athena — The Quality Gate</h4><p>Glue <strong>discovers</strong> your Delta tables. Athena (or Spark SQL) <strong>verifies</strong>:</p><ol><li><strong>Row counts</strong> aren’t off</li><li><strong>No null text</strong> in chunks</li><li><strong>Embedding dimension</strong> matches the model (e.g., 1024)</li><li><strong>Freshness</strong> — today’s partitions exist</li></ol><p><strong>Fail fast:</strong> If a check fails, Airflow stops the indexing step and raises an alert (CloudWatch/SNS). Bad data never reaches production.</p><p><em>Example Athena checks:</em></p><pre>-- Null text check<br>SELECT COUNT(*) AS null_chunks<br>FROM processed_chunks<br>WHERE chunk_text IS NULL;<br><br>-- Embedding dimension<br>SELECT COUNT(*) AS bad_dim<br>FROM embeddings<br>WHERE CARDINALITY(embedding) &lt;&gt; 1024;<br><br>-- Freshness (expect today&#39;s partition)<br>SELECT MAX(dt) AS latest_dt FROM processed_chunks;</pre><h4>4) Qdrant on ECS — The Fast Semantic Index</h4><p>After validation, Airflow <strong>upserts</strong> embeddings into Qdrant on ECS.</p><p><strong>Operational notes</strong></p><ul><li><strong>Bulk index</strong> from Delta (batch points; avoid single-point HTTP loops).</li><li><strong>Shards</strong> per dataset; <strong>replicas</strong> for HA; place behind an internal NLB.</li><li>Tune <strong>HNSW</strong>: m, ef_construct; for queries tune ef_search.</li></ul><p><em>Why Qdrant?</em> Low-latency semantic search with straightforward horizontal scaling.</p><p><em>Bulk upsert (Python):</em></p><pre>from qdrant_client import QdrantClient, models<br><br>def bulk_upsert(qdrant_host, collection, rows):<br>    client = QdrantClient(host=qdrant_host, port=6333, https=False, timeout=60)<br>    client.recreate_collection(<br>        collection_name=collection,<br>        vectors_config=models.VectorParams(size=len(rows[0][&quot;embedding&quot;]), distance=models.Distance.COSINE),<br>        replication_factor=2, shards=4 # adjust for your scale<br>    )<br>    points = [<br>        models.PointStruct(<br>            id=r[&quot;chunk_id&quot;],<br>            vector=r[&quot;embedding&quot;],<br>            payload={<br>                &quot;doc_id&quot;: r[&quot;doc_id&quot;],<br>                &quot;dataset&quot;: r[&quot;dataset&quot;],<br>                &quot;source&quot;: r[&quot;source&quot;],<br>                &quot;dt&quot;: r[&quot;dt&quot;],<br>                &quot;version&quot;: r[&quot;version&quot;]<br>            }<br>        ) for r in rows<br>    ]<br>    client.upsert(collection_name=collection, points=points)</pre><blockquote>In production, stream batches (10k–100k points), and handle retries/back-pressure.</blockquote><p><em>Qdrant payload (serving copy):</em></p><pre>{<br>  &quot;id&quot;: &quot;chunk_id&quot;,<br>  &quot;vector&quot;: [ ... dim floats ... ],<br>  &quot;payload&quot;: {<br>    &quot;doc_id&quot;: &quot;...&quot;,<br>    &quot;source&quot;: &quot;s3://.../doc.pdf#page=5&quot;,<br>    &quot;dt&quot;: &quot;2025-09-01&quot;,<br>    &quot;version&quot;: &quot;v42&quot;<br>  }<br>}</pre><h3>Serving &amp; Retrieval (Application Plane)</h3><h4>5) ALB + FastAPI on ECS — The Front Door &amp; Conductor</h4><p>Requests flow <strong>User → ALB → FastAPI</strong>. FastAPI:</p><ul><li><strong>Embeds</strong> the query (same model family as the index)</li><li><strong>Retrieves</strong> top-K chunks from Qdrant</li><li><strong>Assembles</strong> a grounded prompt with citations</li><li><strong>Calls</strong> Bedrock to compose the answer</li><li><strong>Writes</strong> user feedback (rating, helpful/not) to DynamoDB</li></ul><blockquote>Note<em>:</em> There’s <strong>no direct Qdrant → Bedrock</strong> call. FastAPI mediates and enforces policy (rate limits, redaction, etc.).</blockquote><p><em>FastAPI outline:</em></p><pre># FastAPI flow (concept)<br>emb = embed_query(user_query)                 # same family as index<br>hits = qdrant.search(emb, top_k=8)            # ids + payload<br>ctx  = dedupe_and_trim(hits, max_tokens=1200) # fit model limits<br>prompt = build_prompt(user_query, ctx)        # include citation tags<br>answer = bedrock.generate(prompt)             # model call<br>return answer_with_sources(answer, ctx)</pre><p><em>Search endpoint (FastAPI):</em></p><pre>from fastapi import FastAPI<br>from pydantic import BaseModel<br>from qdrant_client import QdrantClient, models<br>import boto3, json<br><br>app = FastAPI()<br>qdrant = QdrantClient(host=&quot;qdrant.internal&quot;, port=6333)<br>bedrock = boto3.client(&quot;bedrock-runtime&quot;, region_name=&quot;us-east-1&quot;)<br><br>class QueryIn(BaseModel):<br>    question: str<br>    top_k: int = 6<br><br>def embed_query(text: str) -&gt; list[float]:<br>    # Use your embedder (e.g., E5/Mistral embeddings or Titan Embeddings on Bedrock)<br>    # Return a normalized vector of the same dim used in Qdrant<br>    ...<br><br>def build_prompt(q: str, passages: list[dict]) -&gt; str:<br>    context = &quot;\n\n&quot;.join(f&quot;[{i+1}] {p[&#39;text&#39;]}\nSource: {p[&#39;source&#39;]}&quot;<br>                          for i, p in enumerate(passages))<br>    return f&quot;&quot;&quot;You are a helpful assistant. Use ONLY the context to answer.<br>If the context is insufficient, say you don&#39;t know and ask for clarification.<br>Question: {q}<br>Context:<br>{context}<br>Include citations like [1], [2] after the sentences they support.&quot;&quot;&quot;<br><br>@app.post(&quot;/ask&quot;)<br>def ask(q: QueryIn):<br>    v = embed_query(q.question)<br>    hits = qdrant.search(<br>        collection_name=&quot;policies_1024&quot;,<br>        query_vector=v,<br>        limit=q.top_k,<br>        with_payload=True<br>    )<br>    passages = [{&quot;text&quot;: h.payload.get(&quot;chunk_text&quot;, &quot;&quot;),<br>                 &quot;source&quot;: h.payload.get(&quot;source&quot;, &quot;&quot;),<br>                 &quot;score&quot;: h.score} for h in hits]<br><br>    prompt = build_prompt(q.question, passages)<br><br>    body = json.dumps({<br>        &quot;inputText&quot;: prompt,<br>        &quot;textGenerationConfig&quot;: {&quot;temperature&quot;: 0.2, &quot;maxTokenCount&quot;: 512}<br>    })<br>    resp = bedrock.invoke_model(modelId=&quot;&lt;your-model-id&gt;&quot;, body=body)<br>    answer = json.loads(resp[&quot;body&quot;].read().decode(&quot;utf-8&quot;))[&quot;results&quot;][0][&quot;outputText&quot;]<br>    return {&quot;answer&quot;: answer, &quot;sources&quot;: [p[&quot;source&quot;] for p in passages]}</pre><blockquote>Adjust the Bedrock payload shape for your chosen model (e.g., Cohere, Claude, or Llama via Bedrock). The pattern above (JSON body, invoke_model, read body) is correct; only field names vary per model.</blockquote><h4>6) Amazon Bedrock — The Writer That Sticks to the Facts</h4><p>Bedrock generates the answer <strong>from the passages we provide</strong>. We require <strong>citations</strong> in the output; if context is weak, the model should say so. This is how we “earn trust” at scale.</p><p><strong>Prompting tips</strong></p><ul><li>Keep context under model token limits (trim/merge similar passages).</li><li>Ask for inline citations [1] matching the context list.</li><li>For regulated content, add policy guardrails and PII filters in FastAPI before LLM calls.</li></ul><h4>7) Amazon DynamoDB — Governance &amp; Learning</h4><p>DynamoDB stores:</p><ul><li><strong>Document versions &amp; hashes</strong> (from Airflow) for <strong>drift detection</strong></li><li><strong>User feedback</strong> (from FastAPI) for retrieval/prompt improvement</li></ul><p><em>Drift detection (hash &amp; re-embed only what changed):</em></p><pre>import hashlib, boto3<br><br>ddb = boto3.resource(&quot;dynamodb&quot;).Table(&quot;rag_governance&quot;)<br><br>def content_hash(text: str) -&gt; str:<br>    return hashlib.sha256(text.encode(&quot;utf-8&quot;)).hexdigest()<br><br>def upsert_doc_version(doc_id: str, hash_: str, version: str):<br>    ddb.put_item(Item={&quot;doc_id&quot;: doc_id, &quot;hash&quot;: hash_, &quot;version&quot;: version})<br><br>def needs_reembed(doc_id: str, new_hash: str) -&gt; bool:<br>    old = ddb.get_item(Key={&quot;doc_id&quot;: doc_id}).get(&quot;Item&quot;)<br>    return (old is None) or (old[&quot;hash&quot;] != new_hash)</pre><blockquote>On each ingest run, compute the new hash; if different → re-embed those chunks, re-validate via Athena, then upsert to Qdrant.</blockquote><p><strong>Minimal DynamoDB schema that work:</strong></p><pre>PK: doc_id <br>Attr: version, hash, last_seen, drift_flag, last_run_id, optional feedback_stats</pre><h4>8) Amazon CloudWatch — End-to-End Observability</h4><ul><li><strong>Dashboards:</strong> success rate, latency (p95/p99), error counts, Qdrant query time, Bedrock token usage, Athena scan GB, ECS health.</li><li><strong>Alarms:</strong> validation failure, Qdrant p99 &gt; threshold, FastAPI 5xx rate, Bedrock timeout, DynamoDB throttling.</li><li><strong>Tracing/logs:</strong> Airflow task logs, FastAPI request traces, ECS/ALB access logs.</li></ul><p>This is what turns “we hope it works” into “we know it works.”</p><h3>How One Request Flows (At User Level)</h3><ol><li>A user asks a question.</li><li><strong>FastAPI</strong> embeds it and asks <strong>Qdrant</strong> for the best matching chunks.</li><li>FastAPI builds a short, clear prompt with <strong>the exact passages</strong> and <strong>their sources</strong>.</li><li><strong>Bedrock</strong> writes an answer that sticks to those passages and includes <strong>citations</strong>.</li><li>The user sees <strong>answer + sources.</strong> They can verify instantly.</li><li>Feedback flows into <strong>DynamoDB</strong> to improve retrieval and prompts over time.</li></ol><h3>Scaling patterns that matter at TB-scale</h3><ul><li><strong>Partition</strong> Delta tables (by dt, dataset) and <strong>compact</strong> small Parquet files</li><li><strong>Bulk index</strong> Qdrant from Delta</li><li><strong>Selective re-embedding</strong> (DynamoDB versions/hashes)</li><li><strong>Cache</strong> popular queries (short TTL) to offload spikes</li><li>Align <strong>embed model</strong> and <strong>search model</strong> (or use a mapping layer)</li><li>Track end-to-end latency, not just averages</li></ul><h3>Security, Reliability, and Cost</h3><h4><strong>Security</strong></h4><ul><li>ECS/Qdrant in private subnets</li><li>ALB in public with WAF</li><li>KMS-encrypted S3/Delta</li><li>EBS/EFS, and DynamoDB</li><li>IAM least-privilege for each service</li><li>PII redaction before embedding</li></ul><h4><strong>Reliability</strong></h4><ul><li>Multi-AZ replicas for Qdrant</li><li>Health checks on ECS tasks</li><li>Airflow retries</li><li>Validation gate prevents bad data from going live.</li></ul><h4><strong>Cost</strong></h4><ul><li>Compaction &amp; partition pruning in Delta</li><li>Bulk indexing to Qdrant</li><li>Selective re-embedding (only changed docs)</li><li>Prompt trimming and caching to reduce LLM costs</li></ul><h3>What to measure</h3><ul><li><strong>Time-to-answer</strong> (p95)</li><li><strong>Citation coverage</strong> (% of answers with sources)</li><li><strong>Validation failure rate</strong> (prevents bad data reaching users)</li><li><strong>Re-embedding efficiency</strong> (% changed docs vs full set)</li><li><strong>Adoption</strong> (weekly active users, repeat queries)</li><li><strong>Incidents avoided</strong> (version drift caught by gate)</li></ul><h3>Conclusion</h3><p>This isn’t a chatbot. It’s a <strong>trusted knowledge engine</strong>. We <strong>store cleanly</strong>, <strong>automate responsibly</strong>, <strong>validate quality</strong>, <strong>retrieve by meaning</strong>, <strong>explain with citations</strong>, and <strong>keep improving</strong> — at <strong>terabyte scale</strong>.</p><p>🎥 If you want the full walkthrough with visuals, watch the video:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fy7H5iJ4q0hs%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dy7H5iJ4q0hs&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fy7H5iJ4q0hs%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c474b82021a2689116a57287c64748e/href">https://medium.com/media/0c474b82021a2689116a57287c64748e/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30e5a4c6be94" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/enterprise-rag-on-aws-from-scattered-docs-to-trusted-answers-at-tb-scale-30e5a4c6be94">Enterprise RAG on AWS: From Scattered Docs to Trusted Answers at TB-Scale</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Don’t Default to RAG: Think Before You Choose]]></title>
            <link>https://medium.com/@neelamyadav10053/dont-default-to-rag-think-before-you-choose-f6b1476a8b91?source=rss-8ea043d1bf12------2</link>
            <guid isPermaLink="false">https://medium.com/p/f6b1476a8b91</guid>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Neelamyadav]]></dc:creator>
            <pubDate>Sun, 07 Sep 2025 07:48:08 GMT</pubDate>
            <atom:updated>2025-09-07T07:48:08.490Z</atom:updated>
            <content:encoded><![CDATA[<p>RAG is powerful, but not a magic button. Even with guardrails and temperature = 0, you still face security risks, extra latency/cost, and audit headaches. Use RAG when it clearly helps. Use <strong>deterministic systems</strong> (rules, APIs, SQL/graph, workflows) when you need exact answers and tight control.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o_fi2CHiHSSbOs2q8x1wMQ.png" /></figure><h3>Why this matters</h3><p>AI is trendy. RAG is everywhere. But shipping RAG “because everyone is doing it” can give you slower apps, higher bills, and new security risks. The goal here: <strong>choose RAG on purpose</strong>, not by hype.</p><h3>Quick refresher: when RAG is actually good</h3><ul><li>Your knowledge base is large and fairly trustworthy.</li><li>People ask open questions and want <strong>citations</strong>.</li><li>You don’t need perfect precision every time.</li></ul><p>If that sounds like you, RAG can shine. If not, keep reading.</p><h3>When not to use RAG</h3><p>Say <strong>“not now”</strong> to RAG if several of these are true:</p><ul><li><strong>You need exact, auditable answers.</strong><br>If someone could audit this later — price, tax, eligibility, dosing — don’t use RAG. Call the rules or the API. Let the model explain, not decide.</li><li><strong>You already have a system of truth.</strong><br>If the answer lives in your database, rules engine, or graph, hit that directly. No need to ask a model to guess.</li><li><strong>You owe fast responses or low cost.</strong><br>RAG adds steps — retrieve, re-rank, generate — which can slow worst-case responses and raise per-answer cost unless you over-engineer. Keep the path short.</li><li><strong>You need strict access control across tenants.</strong><br>If permissions change by tenant, field, or paragraph, default RAG isn’t enough. You need hard isolation and filters — do authorization in code first.</li><li><strong>Your documents are messy or change a lot.</strong><br>If content is noisy or churns daily, you’ll be re-ingesting and re-indexing nonstop. Clean the source first or stay deterministic.</li><li><strong>A wrong answer would really hurt.</strong><br>If mistakes mean legal trouble, safety risk, or real money, keep decisions deterministic and fully auditable.</li></ul><h3>Common pushbacks (and the reality)</h3><p><strong>Pushback A — “We have guardrails; prompt injection is handled.”</strong><br><em>Reality:</em> Guardrails reduce risk but they don’t remove it — especially indirect prompt injection hidden in retrieved content (the default risk in RAG). This is listed as the top risk in OWASP’s LLM Top-10, and Microsoft’s security guidance recommends layered defenses (isolation, allow-lists, provenance, scoped tools, monitoring). Recent demos show these attacks remain practical across text and other modalities.</p><p><strong>Pushback B — “Set temperature = 0; it will be deterministic and correct.”</strong><br><em>Reality:</em> Temperature-0 reduces randomness, not errors. Hallucinations can still appear, and the same prompt can behave differently across systems. Repeatable doesn’t equal right.</p><p><strong>Pushback C — “We’ll force citations; that makes it safe.”</strong><br><em>Reality:</em> A citation can still be<strong> </strong>wrong or only partially supporting. Recent studies show that measuring citation faithfulness is hard; models often include sources that don’t fully support the claim. Treat citations as hints, not proof, unless you validate support.</p><p><strong>Pushback D — “Better embeddings/chunking will fix it.”</strong><br><em>Reality:</em> Tuning helps, but it’s not magic. You still need to <strong>measure</strong>: Are the right docs showing up ? Is the final answer faithful to those docs? Don’t tune in the dark.</p><p><strong>Pushback E — “RAG 2.0 (Self-RAG, GraphRAG, etc.) solves the risks.”</strong><br><em>Reality:</em> New flavors can improve recall and structure, but <strong>poisoned or adversarial docs still work</strong>. Keep the same safety basics: isolation, provenance, scoped tools, monitoring.</p><p><strong>Pushback F — “We can sanitize any untrusted document.”</strong><br><em>Reality:</em> Sanitization helps, but indirect injection keeps showing up in surprising places (titles, calendar invites, images). Keep permissions tight and isolate by tenant.</p><p><strong>Pushback G — “We’ll just scale infra to fix latency and cost.”</strong><br><em>Reality:</em> RAG is a pipeline. Vector search, reranking, and LLM calls add hops and tail latency. You need smart caching, placement, and evaluation — not just bigger clusters.</p><h3>Myths that make teams overuse RAG</h3><ul><li><strong>Myth:</strong> “Guardrails stop prompt injection.”<br><strong>Reality:</strong> Guardrails help, but attackers can hide instructions inside the documents you retrieve. Keep tenants isolated, keep tools tightly scoped, and monitor everything.</li><li><strong>Myth:</strong> “Temperature zero means safe and correct.”<br><strong>Reality:</strong> Setting temperature to zero makes the model less random, not automatically right. Hallucinations can still happen, and results may differ across systems.</li><li><strong>Myth:</strong> “RAG is multi-tenant secure by default.”<br><strong>Reality:</strong> It isn’t. You must design it: separate indexes per tenant or hard metadata filters, and route every request with identity end-to-end.</li><li><strong>Myth:</strong> “RAG won’t hurt our SLOs.”<br><strong>Reality:</strong> It can. Retrieval + re-ranking + generation add hops and cost. Measure P95/P99 latency and dollars per accepted answer — don’t guess.</li></ul><h3>A simple decision checklist</h3><p>Ask yourself these quick questions. If you say <strong>“yes” to five or more</strong>, skip RAG for now — build a <strong>deterministic core</strong> (rules/APIs/workflows) and let the LLM help only with wording.</p><ul><li><strong>Do you need exact, checkable answers?</strong><br>(Something you could audit later — like price, tax, eligibility, dosing.)</li><li><strong>Do you already have a single source of truth?</strong><br>(A database, rules engine, or graph you trust.)</li><li><strong>Do you have strict speed or cost targets?</strong><br>(Those worst-case P99 latencies or tight budgets.)</li><li><strong>Do you need very strict access control across tenants?</strong><br>(Down to fields or paragraphs, with zero leaks.)</li><li><strong>Is your content messy or changing a lot?</strong><br>(You’d be re-ingesting and re-indexing all the time.)</li><li><strong>Would a wrong answer be expensive or unsafe?</strong><br>(Legal exposure, safety risk, or money on the line.)</li><li><strong>Do you lack a solid test set to measure quality?</strong><br>(For both retrieval hit-rate and answer faithfulness.)</li><li><strong>Could simple search + templates/rules answer most questions?</strong><br>(If yes, do that first — it’s faster, cheaper, safer.)</li></ul><blockquote><strong>Rule of thumb:</strong> Five or more “yes” → go deterministic first. Fewer than five → consider RAG, but run it in <strong>Safe Mode</strong>.</blockquote><h3>What to build instead</h3><ul><li><strong>Rules / Policy Engine + API (the deterministic core)</strong><br>Put the decision in code, not in the model. Write your rules once, keep versions, and expose a simple API that returns the answer (and the reason). Let the LLM only <strong>explain</strong> that result in clear language.</li><li><strong>Search-and-Cite portal</strong><br>Use solid keyword search with filters (by author, date, source). Show the <strong>exact clause</strong> from the document with its source and date so people can trust it. If you want, let the LLM <strong>summarize after</strong> the user has seen the sources.</li><li><strong>Workflow orchestration for actions</strong><br>When something changes state (updates a record, sends money, creates a ticket), run it through a workflow with steps, approvals, and an audit trail. Tools like Step Functions/Temporal/BPMN make who-did-what-when crystal clear.</li><li><strong>Structured generation (LLM-lite)</strong><br>Ask the model <strong>once</strong> to fill a strict JSON shape (no free-form guessing), then render that JSON into a template (email/report/page). All <strong>facts</strong> come from your trusted APIs — <strong>not</strong> from retrieved text. The LLM helps with wording, not decisions.</li></ul><h3>If you truly need RAG, run it in Safe Mode</h3><ul><li><strong>Keep each customer’s data separate.</strong><br>Give every request a tenant/user ID and carry it through every step. Only fetch what that person is allowed to see.</li><li><strong>Track where the info came from.</strong><br>Save the <strong>source</strong> and its <strong>version</strong> for every snippet. Prefer content you trust (reviewed, approved, up-to-date).</li><li><strong>Clean what you retrieve — then still be cautious.</strong><br>Strip out any hidden instructions or active content before sending text to the model. Even after cleaning, treat it as untrusted.</li><li><strong>Give the AI the least power possible.</strong><br>Only enable the tools it truly needs, set rate limits, and keep audit logs so you can see who did what, when.</li><li><strong>Watch what it fetches and what it answers.</strong><br>Log the retrieved chunks and the final reply. Regularly check two things:</li></ul><ol><li>How often the right documents show up near the top, and</li><li>Whether the answer actually sticks to those sources.</li></ol><ul><li><strong>Keep it fast and affordable.</strong><br>Cache results using a key that includes the question, the user/tenant, and the document version. Monitor both average and tail response times (the slow ones) and track <strong>cost per accepted answer</strong>.</li><li><strong>Have a safe fallback.</strong><br>If confidence is low, switch to a simple <strong>search-and-cite</strong> view (show the sources) or ask a human to approve before sending.</li></ul><h3>Final takeaway</h3><p><strong>Think before choosing.</strong> If the job needs truth, speed, and audits, keep the decision in code and let LLMs help at the edges (tone, summaries, intent). Use RAG <strong>when the trade-off is worth it</strong>, and only with solid safety, isolation, and measurement in place.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f6b1476a8b91" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Zero to RAG Chatbot in 10 Minutes (LangChain + Qdrant + Mistral + FastAPI + Airflow)]]></title>
            <link>https://pub.towardsai.net/from-zero-to-rag-chatbot-in-10-minutes-langchain-qdrant-mistral-fastapi-airflow-f99c16dad91e?source=rss-8ea043d1bf12------2</link>
            <guid isPermaLink="false">https://medium.com/p/f99c16dad91e</guid>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[langchain]]></category>
            <dc:creator><![CDATA[Neelamyadav]]></dc:creator>
            <pubDate>Sun, 24 Aug 2025 13:06:19 GMT</pubDate>
            <atom:updated>2026-08-10T04:46:30.998Z</atom:updated>
            <content:encoded><![CDATA[<h4>Ever wished you could build your own ChatGPT-style bot that answers from <em>your own data</em>? Welcome to the world of <strong>Retrieval-Augmented Generation (RAG)</strong>.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HIzdXGDIeUDAHFcMwk8UVg.png" /></figure><p>Retrieval-Augmented Generation (RAG) is the <strong>secret sauce</strong> behind today’s most reliable AI chatbots. Instead of letting an LLM “hallucinate,” RAG pulls in the <strong>right knowledge at the right time</strong> from your own data.</p><p>In this article, I’ll show you how I built a <strong>RAG chatbot from scratch</strong> using <strong>LangChain, Qdrant, Mistral, FastAPI, and Airflow</strong>.<br>This isn’t theory — it’s a full <strong>hands-on PoC</strong> you can clone, run locally, and extend.</p><p>👉 <strong>GitHub Repo (Code Ready to Clone):</strong> <a href="https://github.com/neelam-yadav/rag-poc">github.com/neelam-yadav/rag-poc</a></p><h3>🏗️ Architecture</h3><p>Before diving into code, here’s the flow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1odTEr00NTuXpmiCpkDIjQ.png" /></figure><p>This flow shows the entire journey:</p><ul><li><strong>Data sources</strong> are scraped, cleaned, and chunked with semantic overlap.</li><li><strong>E5 embeddings</strong> turn chunks into vectors, stored in <strong>Qdrant</strong>.</li><li>A <strong>retriever</strong> fetches relevant chunks for each query.</li><li>Finally, <strong>Mistral 7B</strong> assembles an answer with proper context.</li></ul><h3>🧩 Tech Stack</h3><ul><li><strong>LangChain</strong> → to orchestrate scraping, chunking, embeddings, and retrieval</li><li><strong>Qdrant</strong> → vector database to store embeddings</li><li><strong>E5 embeddings</strong> → high-quality retrieval embeddings</li><li><strong>Mistral 7B</strong> (via <strong>Ollama</strong>) → the LLM for answering</li><li><strong>FastAPI</strong> → lightweight API layer for chatbot endpoints</li><li><strong>Airflow</strong> → to automate ingestion and re-ingestion</li></ul><h3>📂 Project Layout</h3><p>Here’s how the repo is structured:</p><pre>rag-poc/<br>  .env<br>  requirements.txt               # pinned versions for poc<br>  dags/<br>    rag_ingest_dag.py            # Airflow DAG (manual trigger)<br>  pipeline/<br>    scrape.py                    # fetch + clean HTML<br>    build_index.py               # chunk → embed → upsert to Qdrant<br>  app/<br>    embeddings_e5.py             # E5 wrapper (query/passages + normalize)<br>    rag_chain.py                 # retriever + prompt assembler + LLM<br>    main.py                      # FastAPI endpoints</pre><p>This makes it modular — ingestion and RAG logic are separate, and you can extend each block independently.</p><h3>⚙️ Setup</h3><p>Clone the repo:</p><pre>git clone https://github.com/neelam-yadav/rag-poc<br>cd rag-poc</pre><p>Create a Python environment:</p><pre>python -m venv .venv<br>.venv\Scripts\activate   # Windows<br># source .venv/bin/activate  # macOS/Linux</pre><p>Install dependencies:</p><pre>pip install --upgrade pip<br>pip install -r requirements.txt</pre><h3>🗄️ Start Qdrant (Vector Database)</h3><pre>docker run -p 6333:6333 -p 6334:6334 -v qdrant_storage:/qdrant/storage --name qdrant -d qdrant/qdrant:latest</pre><p>Check the Qdrant UI at: <a href="http://localhost:6333/dashboard">http://localhost:6333/dashboard</a></p><h3>🤖 Install Ollama + Pull Mistral Model</h3><pre>ollama pull mistral:7b-instruct-q4_K_M</pre><p>If your system runs low on RAM, use a smaller quantized variant and reduce context:</p><pre>export OLLAMA_NUM_CTX=1024</pre><h3>🔍 Code Walkthrough</h3><p>Let’s quickly walk through the key files:</p><ol><li><strong>pipeline/scrape.py</strong> → Uses requests + BeautifulSoup to fetch docs/HTML and clean text.</li></ol><pre>def fetch_and_clean(url: str) -&gt; str:<br>    r = requests.get(url, timeout=30)<br>    r.raise_for_status()<br>    soup = BeautifulSoup(r.text, &quot;html.parser&quot;)<br><br>    # Remove nav/aside/script/style<br>    for bad in soup([&quot;nav&quot;,&quot;aside&quot;,&quot;script&quot;,&quot;style&quot;,&quot;footer&quot;,&quot;header&quot;]):<br>        bad.decompose()<br><br>    text = soup.get_text(separator=&quot;\n&quot;)<br>    text = re.sub(r&quot;\n{2,}&quot;, &quot;\n\n&quot;, text)<br>    text = re.sub(r&quot;[ \t]+&quot;, &quot; &quot;, text)<br>    return text.strip()</pre><p>2. <strong>pipeline/build_index.py</strong> → It does below tasks:</p><ul><li>Splits text into semantic chunks</li><li>Converts chunks to embeddings</li><li>Upserts embeddings into <strong>Qdrant</strong>.</li></ul><pre>def semantic_chunk(text: str, embedder: E5Embeddings,<br>                   window_words: int = 300, overlap_ratio: float = 0.2) -&gt; List[Document]:<br>    # Use semantic splitter to find natural boundaries<br>    splitter = SemanticChunker(embedder, breakpoint_threshold_type=&quot;percentile&quot;)<br>    docs = splitter.create_documents([text])  # list[Document] of big, semantically-coherent chunks<br><br>    # Now apply 20% overlap within each semantic segment for retrieval robustness<br>    final_docs: List[Document] = []<br>    for d in docs:<br>        windows = overlap_windows(d.page_content, target_words=window_words, overlap_ratio=overlap_ratio)<br>        for w in windows:<br>            final_docs.append(<br>                Document(<br>                    page_content=w,<br>                    metadata={**(d.metadata or {}), &quot;source&quot;: &quot;web_corpus&quot;}<br>                )<br>            )<br>    return final_docs<br><br>def ensure_collection(client: QdrantClient, collection: str, vector_size: int = 768):<br>    # Safer: try/except around get_collection<br>    try:<br>        client.get_collection(collection)<br>    except Exception:<br>        client.create_collection(<br>            collection_name=collection,<br>            vectors_config=VectorParams(size=vector_size, distance=Distance.COSINE),<br>        )<br><br>def run_build_index():<br>    # 1) Build corpus &amp; chunks as you already do<br>    corpus = fetch_corpus(DOC_URLS)<br>    embeddings = E5Embeddings()<br>    docs = semantic_chunk(corpus, embeddings, window_words=300, overlap_ratio=0.2)<br>    print(f&quot;[INGEST] Created {len(docs)} chunks&quot;)<br><br>    # 2) Create client &amp; ensure collection<br>    client = QdrantClient(url=QDRANT_URL, api_key=QDRANT_API_KEY or None)<br>    ensure_collection(client, COLLECTION, vector_size=768)<br><br>    # 3) Use an instance + add_documents (avoid from_documents path)<br>    vs = QdrantVectorStore(client=client, collection_name=COLLECTION, embedding=embeddings)<br>    vs.add_documents(docs)<br><br>    print(&quot;[INGEST] Upsert complete.&quot;)</pre><p>3. <strong>app/embeddings_e5.py</strong> → Wraps the E5 embedding model for both queries &amp; passages (normalization included).</p><pre>def embed_documents(self, texts: List[str]) -&gt; List[List[float]]:<br>        prefixed = [f&quot;passage: {t}&quot; for t in texts]<br>        vecs = self.model.encode(prefixed, normalize_embeddings=True, batch_size=32)<br>        return vecs.tolist()<br><br>    def embed_query(self, text: str) -&gt; List[float]:<br>        vec = self.model.encode(f&quot;query: {text}&quot;, normalize_embeddings=True)<br>        return vec.tolist()</pre><p>4. <strong>app/rag_chain.py</strong> → Orchestrates the Retriever + LLM (Mistral) pipeline using LangChain’s RetrievalQA.</p><pre>def build_retriever(k: int = 4):<br>    embeddings = E5Embeddings()<br>    client = QdrantClient(url=QDRANT_URL, api_key=QDRANT_API_KEY or None)<br>    vs = QdrantVectorStore(client=client, collection_name=COLLECTION, embedding=embeddings)<br>    return vs.as_retriever(search_type=&quot;mmr&quot;,<br>                           search_kwargs={&quot;k&quot;: k, &quot;fetch_k&quot;: 20, &quot;lambda_mult&quot;: 0.5})<br><br>def build_qa_chain():<br>    llm = build_llm()<br>    retriever = build_retriever(k=4)<br><br>    TEMPLATE = &quot;&quot;&quot;You are a precise assistant. Use the following context to answer the question.<br>Cite sources as [source] if helpful. If unsure, say you don&#39;t know.<br><br>Question: {question}<br><br>Context:<br>{context}<br><br>Answer:&quot;&quot;&quot;<br>    prompt = PromptTemplate.from_template(TEMPLATE)<br><br>    chain = RetrievalQA.from_chain_type(<br>        llm=llm,<br>        retriever=retriever,<br>        chain_type=&quot;stuff&quot;,<br>        chain_type_kwargs={&quot;prompt&quot;: prompt},<br>        return_source_documents=True,<br>    )<br>    return chain</pre><p>5. <strong>app/main.py</strong> → FastAPI app with /chat endpoint. This is where the UI/Streamlit (or Postman) hits for responses.</p><pre>@app.post(&quot;/chat&quot;)<br>def chat(q: Query):<br>    # RetrievalQA handles calling the retriever + LLM<br>    res = qa_chain({&quot;query&quot;: q.query})<br>    answer = res[&quot;result&quot;]<br>    sources = [<br>        {<br>            &quot;source&quot;: d.metadata.get(&quot;source&quot;, &quot;unknown&quot;),<br>            &quot;snippet&quot;: d.page_content[:300] + (&quot;...&quot; if len(d.page_content) &gt; 300 else &quot;&quot;)<br>        }<br>        for d in res.get(&quot;source_documents&quot;, [])<br>    ]<br>    return {&quot;answer&quot;: answer, &quot;sources&quot;: sources}</pre><p>6. <strong>streamlit_app/chat_ui.py</strong> → Streamlit UI for Chatbot where user can ask queries and get the answers.</p><pre>API_URL = &quot;http://localhost:8000/chat&quot;<br><br>st.set_page_config(page_title=&quot;RAG Chatbot&quot;, page_icon=&quot;🤖&quot;, layout=&quot;wide&quot;)<br>st.title(&quot;💬 RAG Chatbot&quot;)<br><br># Keep chat history<br>if &quot;messages&quot; not in st.session_state:<br>    st.session_state[&quot;messages&quot;] = []<br><br># Input box<br>user_query = st.chat_input(&quot;Type your question...&quot;)<br><br>if user_query:<br>    # Add user message<br>    st.session_state[&quot;messages&quot;].append({&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: user_query})<br>    # Add assistant placeholder (None = waiting)<br>    st.session_state[&quot;messages&quot;].append({&quot;role&quot;: &quot;assistant&quot;, &quot;content&quot;: None})<br>    st.rerun()<br><br># Render conversation<br>for i, msg in enumerate(st.session_state[&quot;messages&quot;]):<br>    if msg[&quot;role&quot;] == &quot;user&quot;:<br>        st.chat_message(&quot;user&quot;).write(msg[&quot;content&quot;])<br>    else:<br>        if msg[&quot;content&quot;] is None:<br>            with st.chat_message(&quot;assistant&quot;):<br>                placeholder = st.empty()<br>                placeholder.markdown(&quot;🤖 *Bot is thinking...*&quot;)<br>        else:<br>            st.chat_message(&quot;assistant&quot;).write(msg[&quot;content&quot;])<br><br># If last assistant is still None → fetch answer<br>if st.session_state[&quot;messages&quot;]:<br>    last_msg = st.session_state[&quot;messages&quot;][-1]<br>    if last_msg[&quot;role&quot;] == &quot;assistant&quot; and last_msg[&quot;content&quot;] is None:<br>        query_text = st.session_state[&quot;messages&quot;][-2][&quot;content&quot;]<br>        try:<br>            payload = {&quot;query&quot;: query_text, &quot;user_email&quot;: &quot;demo@lilly.com&quot;, &quot;product_id&quot;: 1}<br>            response = requests.post(API_URL, json=payload, timeout=None)<br><br>            if response.status_code == 200:<br>                answer = response.json().get(&quot;answer&quot;, &quot;⚠️ No response&quot;)<br>            else:<br>                answer = &quot;❌ Backend error&quot;<br>        except Exception as e:<br>            answer = f&quot;❌ Request failed: {str(e)}&quot;<br><br>        # Update last assistant message<br>        st.session_state[&quot;messages&quot;][-1][&quot;content&quot;] = answer<br>        st.rerun()</pre><p>7. <strong>dags/rag_ingest_dag.py</strong> → Defines an Airflow DAG that runs build_index.py whenever ingestion is needed.</p><pre>with DAG(<br>    dag_id=&quot;rag_ingest_dag&quot;,<br>    start_date=datetime(2025, 8, 1),<br>    schedule_interval=None,   # trigger manually for the PoC<br>    catchup=False,<br>    default_args=default_args,<br>    tags=[&quot;rag&quot;,&quot;qdrant&quot;,&quot;e5&quot;],<br>) as dag:<br><br>    build_index = PythonOperator(<br>        task_id=&quot;build_index&quot;,<br>        python_callable=run_build_index,<br>    )<br><br>    build_index</pre><p>👉 If you follow along with my <a href="https://youtu.be/DHjk5Un0Kxs">YouTube video</a>, I walk through these modules step by step, showing how data flows from <em>scrape → embed → store → retrieve → answer</em>.</p><h3>🌱 Quickstart (Basic RAG, No Airflow)</h3><p>Create a .env file at the repo root:</p><pre>QDRANT_URL=http://localhost:6333<br>QDRANT_COLLECTION=rag_poc<br>DOC_URLS=https://qdrant.tech/documentation/overview/,https://docs.mistral.ai/getting-started/models/<br>OLLAMA_MODEL=mistral:7b-instruct-q4_K_M<br>CHUNK_WORDS=300<br>CHUNK_OVERLAP=0.2</pre><h3>Step 1 — Ingest Data</h3><pre>python -m pipeline.build_index</pre><p>Expected logs:</p><pre>[INGEST] Created 14 chunks<br>[INGEST] Upsert complete.</pre><p>Once ingestion is complete, Qdrant shows inserted points in the dashboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HnhCHQUJiJCGPJY-zRnfNg.png" /></figure><p>Each point here has embedding vectors + payload (source, chunk ID, snippet).</p><h3>Step 2 — Run the Chat API</h3><pre>uvicorn app.main:app --reload --port 8000</pre><p>If you want to test the API, then query the API:</p><pre>curl -X POST http://localhost:8000/chat \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -d &#39;{&quot;query&quot;:&quot;What is Qdrant and how does it store vectors?&quot;}&#39;</pre><p>Response will include both the <strong>answer</strong> and <strong>sources</strong> (snippets + URLs) like this:</p><pre>{<br>    &quot;answer&quot;: &quot;Qdrant is a vector similarity search engine that provides a production-ready service with an API to store, search, and manage vectors (i.e., embeddings) with additional payloads. The payloads can help hone in on the search results and provide useful information to users. Qdrant supports the Euclidean Distance, Cosine Similarity, and Dot Product distance metrics for measuring the similarity between vectors.&quot;,<br>    &quot;sources&quot;: [<br>        {<br>            &quot;source&quot;: &quot;web_corpus&quot;,<br>            &quot;snippet&quot;: &quot;### Source: https://qdrant.tech/documentation/overview/ What is Qdrant? - Qdrant Documentation What is Qdrant? Introduction Vector databases are a relatively new way for interacting with abstract data representations derived from opaque machine learning models such as deep learning architectures. Th...&quot;<br>        },<br>        {<br>            &quot;source&quot;: &quot;web_corpus&quot;,<br>            &quot;snippet&quot;: &quot;Yes No Thank you for your feedback! 🙏 We are sorry to hear that.&quot;<br>        },<br>        {<br>            &quot;source&quot;: &quot;web_corpus&quot;,<br>            &quot;snippet&quot;: &quot;Learn more in our blog post 128k ministral-8b-2410 24.10 Mistral Medium 3 ✔️ Our frontier-class multimodal model released May 2025. Learn more in our blog post 128k mistral-medium-2505 25.05 Codestral 2501 ✔️ Our cutting-edge language model for coding with the second version released January 2025, C...&quot;<br>        },<br>        {<br>            &quot;source&quot;: &quot;web_corpus&quot;,<br>            &quot;snippet&quot;: &quot;among others. These databases enable fast similarity and semantic search while allowing users to find vectors that are the closest to a given query vector based on some distance metric. The most commonly used distance metrics are Euclidean Distance, Cosine Similarity, and Dot Product, and these thre...&quot;<br>        }<br>    ]<br>}</pre><h3>Step 3 — Run Streamlit UI</h3><pre>streamlit run streamlit_app/chat_ui.py</pre><h3>Step 4 — Query Your Chatbot</h3><p>Ask your queries in the chatbot and get the response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*hZCxEz7zy6lVfgH1b75B_w.gif" /></figure><h3>🔄 One-Click Re-ingestion with Airflow</h3><p>Manually rerunning ingestion is fine for PoC, but what if you want automation? That’s where <strong>Airflow</strong> comes in.</p><ul><li><strong>rag_ingest_dag.py</strong> defines a DAG that runs pipeline.build_index.</li><li>Create DockerFile for Airflow:</li></ul><pre>FROM apache/airflow:2.9.2-python3.12<br>USER airflow<br>COPY requirements.txt /tmp/requirements.txt<br>RUN pip install --no-cache-dir -r /tmp/requirements.txt</pre><ul><li>Create requirments.txt:</li></ul><pre>langchain<br>langchain-qdrant<br>qdrant-client<br>langchain-ollama<br>langchain-experimental<br>sentence-transformers<br>beautifulsoup4<br>requests<br>python-dotenv</pre><ul><li>Build and Mounts in docker-compose.yaml:</li></ul><pre>build:<br>      context: D:\projects\poc\airflow<br>      dockerfile: Dockerfile<br>volumes:<br>  - &quot;D:/projects/poc/rag-poc/dags:/opt/airflow/dags&quot;<br>  - &quot;D:/projects/poc/rag-poc:/opt/airflow/repo&quot;<br>  - &quot;D:/projects/poc/rag-poc/.env:/opt/airflow/.env:ro&quot;<br>  - &quot;D:/projects/poc/airflow/logs:/opt/airflow/logs&quot;</pre><p>Here ,</p><p><em>D:\projects\poc\airflow</em> is the directory where I have created custom image for airflow having the requirements file needed to import my dag in airflow.</p><p><em>D:\projects\poc\rag-poc</em> is my project directory.</p><ul><li>Configure Qdrant in docker-compose.yaml:</li></ul><pre>  environment:<br>    &amp;airflow-common-env<br>    QDRANT_URL: &quot;http://host.docker.internal:6333&quot;<br>    QDRANT_COLLECTION: &quot;rag_poc&quot;<br>    DOC_URLS: &quot;https://qdrant.tech/documentation/overview/,https://docs.mistral.ai/getting-started/models/&quot;<br>    CHUNK_WORDS: &quot;300&quot;<br>    CHUNK_OVERLAP: &quot;0.2&quot;</pre><ul><li>You can trigger it in the <strong>Airflow UI (</strong><a href="http://localhost:8080/"><strong>http://localhost:8080</strong></a><strong>)</strong> with a single click.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8b2u3U3HTJIgeu_5rVAvvA.png" /></figure><ul><li>Logs will show chunking + upserts into Qdrant.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XQKRedaXIqgmYaBTA4vo_w.png" /></figure><h3>💡 Why This Matters</h3><p>This project shows that you can build an <strong>end-to-end RAG system</strong> with:</p><ul><li>✅ Real-time retrieval (Qdrant)</li><li>✅ Context-aware embeddings (E5)</li><li>✅ Lightweight open-source LLM (Mistral)</li><li>✅ Modern orchestration (Airflow)</li></ul><p>And you don’t need a massive GPU cluster to do it.</p><h3>🎥 Bonus: Watch the Demo</h3><p>If you prefer <strong>watching the demo</strong>, I’ve recorded a step-by-step walkthrough with explanations.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FDHjk5Un0Kxs%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DDHjk5Un0Kxs&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FDHjk5Un0Kxs%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/2eeffb5ea8a52da84d9cd7feb02c096d/href">https://medium.com/media/2eeffb5ea8a52da84d9cd7feb02c096d/href</a></iframe><h3>📌 Final Words</h3><p>If you’re just getting into <strong>RAG systems</strong>, this repo is the perfect starting point.<br> Clone it, run it locally, and start experimenting.</p><p>👉 GitHub Repo: <a href="https://github.com/neelam-yadav/rag-poc">github.com/neelam-yadav/rag-poc</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f99c16dad91e" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/from-zero-to-rag-chatbot-in-10-minutes-langchain-qdrant-mistral-fastapi-airflow-f99c16dad91e">From Zero to RAG Chatbot in 10 Minutes (LangChain + Qdrant + Mistral + FastAPI + Airflow)</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Agentic AI Explained: How It Works and Real-World Uses]]></title>
            <link>https://medium.com/@neelamyadav10053/agentic-ai-explained-how-it-works-and-real-world-uses-b9beafa7db8a?source=rss-8ea043d1bf12------2</link>
            <guid isPermaLink="false">https://medium.com/p/b9beafa7db8a</guid>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[agentic-ai-explained]]></category>
            <category><![CDATA[agentic-ai-for-beginners]]></category>
            <category><![CDATA[ai-autonomous-agents]]></category>
            <category><![CDATA[agentic-ai-tutorial]]></category>
            <dc:creator><![CDATA[Neelamyadav]]></dc:creator>
            <pubDate>Wed, 13 Aug 2025 12:15:16 GMT</pubDate>
            <atom:updated>2025-08-13T12:15:16.299Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5E5mSEQybNu9z1sVuM5L8A.png" /></figure><p>AI is everywhere — answering questions, generating content, and powering smart assistants.<br> But most AI today is <strong>reactive</strong> — it waits for your input and gives you a single output.</p><p><strong>Agentic AI</strong> is different.<br>It’s AI that can <strong>plan, take actions, use tools, and make decisions — all by itself</strong> to achieve a goal.</p><h3>What is Agentic AI</h3><p>Agentic AI is <strong>AI that acts</strong>.<br>Instead of simply responding to prompts, it works toward a goal through multiple steps — planning, acting, checking results, and refining until the task is done.</p><p>Example:</p><ul><li><strong>Traditional AI:</strong> “What’s the capital of France?” → <em>Paris</em></li><li><strong>Agentic AI:</strong> “Plan my weekend trip to Goa” → Plans the trip, finds hotels, checks transport, compares options, refines results, and gives you a final itinerary.</li></ul><h3>Traditional AI vs Agentic AI</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/953/1*v5V76JoPdCYKB5wqW3uxkA.png" /></figure><p><strong>In short:</strong></p><ul><li><strong>Passive vs Proactive:</strong> Traditional AI waits for prompts; Agentic AI takes initiative.</li><li><strong>Tool Use:</strong> Can connect to APIs, apps, and databases to get real data.</li><li><strong>Multi-Step Planning:</strong> Breaks a goal into smaller, actionable steps.</li><li><strong>Self-Refining:</strong> Learns from each attempt to improve results.</li></ul><h3>Agentic AI Workflow</h3><p>Let’s see Agentic AI in action with the goal: <strong>“Find me the cheapest flight to Delhi.”</strong></p><ol><li><strong>Plan</strong> — Search travel APIs, filter by date, compare prices.</li><li><strong>Use Tools</strong> — Query flight databases.</li><li><strong>Get Results</strong> — Return multiple options.</li><li><strong>Evaluate</strong> — Check timing, layovers, airline preference.</li><li><strong>Refine</strong> — Re-check for better options.</li><li><strong>Done</strong> — Book and confirm.</li></ol><p>This loop —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rf6q8tohbkSmO4FrmPVMsQ.png" /></figure><p>— is what makes Agentic AI different from reactive systems.</p><h3>How It’s Built</h3><p>Agentic AI is powered by four key components:</p><p><strong>🧠 LLM Core</strong> — The “brain” that understands instructions and reasons (e.g., GPT, Claude, Mistral).</p><p><strong>🔗 Tool Connectors</strong> — Bridges to external systems like APIs, databases, and software tools.</p><p><strong>🗺️ Planning &amp; Memory</strong> — Ability to plan steps and remember past actions or context.</p><p><strong>♻️ Feedback Loop</strong> — Evaluates results and refines them for improvement.</p><h3>Real-World Examples</h3><p>Here’s how Agentic AI can be applied:</p><p><strong>📅 Personal Assistant Agent</strong> — Books meetings, manages travel, sends reminders.</p><p><strong>💼 Timesheet Filler</strong> — Logs work hours automatically from your calendar.</p><p><strong>🔍 Research Agent</strong> — Gathers and summarizes industry trends.</p><p><strong>📦 E-Commerce Product Sourcer</strong> — Finds suppliers, compares prices, and recommends the best deal.</p><h3>Benefits &amp; Why It Matters</h3><p>Agentic AI can:</p><p>👉 <strong>Boost efficiency</strong> by reducing manual work.</p><p>🤝 <strong>Collaborate</strong> with humans and systems seamlessly.</p><p>⚙️ <strong>Automate</strong> multi-step workflows.</p><p>📈 <strong>Scale</strong> operations without increasing manpower.</p><blockquote>Agentic AI isn’t just a smarter chatbot — it’s a <strong>new category of AI</strong> that works <strong><em>with you</em> </strong>and <strong><em>for you</em></strong>, turning goals into completed actions.</blockquote><h3>🎥 Watch the Full Video</h3><p>For visuals, diagrams, and a beginner-friendly explanation, watch the full YouTube video here:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FaOUHGUAWCak%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DaOUHGUAWCak&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FaOUHGUAWCak%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/d48be43c68e8804b62f2b985084da12e/href">https://medium.com/media/d48be43c68e8804b62f2b985084da12e/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9beafa7db8a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started with MLOps: A Practical Guide]]></title>
            <link>https://medium.com/@neelamyadav10053/getting-started-with-mlops-a-practical-guide-f5bf4af20774?source=rss-8ea043d1bf12------2</link>
            <guid isPermaLink="false">https://medium.com/p/f5bf4af20774</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Neelamyadav]]></dc:creator>
            <pubDate>Tue, 04 Feb 2025 06:19:40 GMT</pubDate>
            <atom:updated>2025-02-04T06:19:40.266Z</atom:updated>
            <content:encoded><![CDATA[<p>As machine learning is growing tremendously, so is the need to automate the whole process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/959/1*ur51ukhdw0jfDSokPZ52iQ.jpeg" /></figure><h3>Introduction</h3><p>Machine Learning Operations (MLOps) is basically an engineering discipline that aims to bridge the gap between machine learning development and operations. It involves the collaboration of data scientists, machine learning engineers and operations professionals to streamline the process of building, deploying, monitoring and maintaining machine learning models in a production environment. The purpose of MLOps is to ensure the successful deployment of ML models, minimising the gap between experimental models and models in production, and to manage the lifecycle of the ML models effectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NdtEbZrKj00YyfyQyszKIg.png" /></figure><h3>Why is MLOps Important?</h3><p>As machine learning becomes increasingly critical to business success, organisations need to ensure their models are accurate, reliable and up to date. MLOps addresses this need by :</p><ul><li>Reducing the time it takes to deploy models into production</li><li>Ensuring consistency, reproducibility and traceability in model development</li><li>Monitoring model performance and managing updates</li><li>Facilitating collaboration between data scientists, engineers and operations teams</li><li>Complying with regulatory and ethical requirements</li></ul><h3>ML Project Life Cycle</h3><p>ML Life Cycle has many steps and all the steps involved in the ML Life Cycle are required for the successful development and implementation of ML models. It is a cyclical process because the process is actually continuous and repetitive.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y_Qfve6YJV29EVsg2_lVtA.png" /></figure><h4>Business Objective</h4><p>Like any other good business lifecycle, the data science lifecycle also starts with ‘why we need it?’</p><p>If business requirements are not clear, it will be futile to go for further steps. understanding business needs and knowing The customers is essential to build an accurate model</p><h4>Data Gathering</h4><p>This is the next stage in the data science lifecycle. Data is like a fuel for a machine learning algorithm. It may be collected from different sources, but we need to make sure that we collect data which is relevant to the business need. The data captured can be either in structured or unstructured form. Data sources can be — logs from websites, social media data, data from online repositories, and even data streamed from online sources via APIs, web scraping or data that could be present in excel or any other source.</p><h4>Data Preparation</h4><p>Once the data is collected, it is very essential to clean and pre-process the data to get accurate results from our model. Converting raw data into a usable format is the basis of this step. It involves:</p><p>1. Missing value treatment.</p><p>2. Checking out improper data type or invalid data.</p><p>3. Examining null values.</p><p>4. Eliminating duplicate records.</p><h4>Exploratory Data Analysis (EDA)</h4><p>In this step, we explore the data deeper for better understanding of the data. It is a critical step in gaining some ideas about the solution and factors affecting the data science lifecycle. The key aspect to remember here is that your input determines your output.</p><p>In this section, the data prepared from the previous stage will be explored further to examine the various features and their relationships, aiding in better feature selection required for applying it to the model.</p><h4>Model Building</h4><p>This is one of the major phases of data processes<strong> </strong>and is often mentioned as the heart of data analysis. A model should use prepared and analysed data to provide the desired output. In this phase, the team works together to develop datasets for training and testing the model for production purposes. It also involves various tasks such as choosing the appropriate mode type and learning whether the problem is a classification, regression, or clustering problem. It has to be done carefully since extracting necessary insights from the prepared data is extremely important.</p><h4>Model Evaluation</h4><p>Once the model is trained, it is important to analyze the performance and accuracy of the model. The main goal of any machine learning project is to achieve maximum model accuracy.</p><p>There are various evaluation criteria ( like Accuracy Score, Precision, Recall, F1 Score, ROC Curve, etc.) based on which the best model is selected. Moreover, overfitting and underfitting problems are addressed so that the model performs well with the new data.</p><h4>Model Deployment</h4><p>This is the final stage of the lifecycle of data science which is model deployment. After a rigorous evaluation process, the model is finally prepared to be deployed in the desired format and preferred channel. We all know there is no value for the machine learning model or any software until it’s deployed to production. In general, these models are integrated and coupled with products and applications.</p><h3>DevOps vs. MLOps: Key Differences</h3><p>While MLOps is inspired by DevOps, it introduces additional complexities due to the dynamic nature of ML models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X9TB8A58xfM-AUs3zF6hMA.png" /><figcaption>DevOps vs MLOps</figcaption></figure><h3>MLOps Tools and Frameworks</h3><p>Several tools support the MLOps workflow, enabling automation, tracking, and model management:</p><h4>1. Kubeflow</h4><p>An open-source MLOps platform for orchestrating ML workflows on Kubernetes. Ideal for scalable deployments.</p><h4>2. MLflow</h4><p>A platform that simplifies ML lifecycle tracking, model versioning, and experiment management.</p><h4>3. TensorFlow Extended (TFX)</h4><p>A production-ready ML pipeline tool designed for TensorFlow models but adaptable to other frameworks.</p><h4>4. Cloud MLOps Solutions</h4><p>Cloud platforms provide managed MLOps services, reducing infrastructure overhead:</p><ul><li><strong>Azure Machine Learning</strong> (Microsoft)</li><li><strong>AWS SageMaker</strong> (Amazon)</li><li><strong>Google Cloud AI Platform</strong> (Google)</li></ul><h3>Challenges in MLOps &amp; How to Overcome Them</h3><h4>1. Managing Model Drift</h4><p>Models degrade over time due to evolving data patterns. Implement:</p><ul><li>Regular monitoring with automated alerts.</li><li>Periodic model retraining with fresh data.</li></ul><h4>2. Complexity in Data Management</h4><p>Handling vast amounts of data requires:</p><ul><li>Versioning datasets with tools like <strong>DVC</strong>.</li><li>Automating data preprocessing and transformation.</li></ul><h4>3. Infrastructure Scalability &amp; Cost</h4><p>ML workloads require significant compute resources. Solutions include:</p><ul><li>Using <strong>cloud-based auto-scaling</strong> services.</li><li>Optimising models for <strong>efficient inference (quantisation, pruning)</strong>.</li></ul><h4>4. Ensuring Compliance &amp; Security</h4><p>ML models must adhere to industry regulations (<strong>GDPR, HIPAA</strong>). Key practices:</p><ul><li>Implementing access controls and encryption.</li><li>Ensuring explainability and fairness in AI models.</li></ul><h3>Conclusion</h3><p>MLOps is revolutionising how machine learning models are developed, deployed, and maintained in production. By implementing best practices and leveraging the right tools, organisations can build scalable and reliable AI solutions. As AI adoption continues to grow, mastering MLOps will be essential for businesses looking to stay competitive.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f5bf4af20774" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RAG vs. CAG: Choosing the Right AI Approach]]></title>
            <link>https://medium.com/kpmg-uk-engineering/rag-vs-cag-choosing-the-right-ai-approach-a9e9f0517bf1?source=rss-8ea043d1bf12------2</link>
            <guid isPermaLink="false">https://medium.com/p/a9e9f0517bf1</guid>
            <category><![CDATA[ai-technique]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <dc:creator><![CDATA[Neelamyadav]]></dc:creator>
            <pubDate>Mon, 03 Feb 2025 09:40:15 GMT</pubDate>
            <atom:updated>2025-02-03T10:27:54.064Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*OfcHJa-zfUWC1QI-jbsgPQ.png" /></figure><p>In the rapidly evolving landscape of artificial intelligence, particularly within large language models (LLMs), the methods by which these systems access and integrate external knowledge are crucial. Two prominent approaches have emerged: Retrieval-Augmented Generation (RAG) and the more recent Cache-Augmented Generation (CAG). This article delves into the intricacies of both methodologies, examining their architectures, advantages, limitations, and suitable application scenarios.</p><h3><strong>What is Retrieval-Augmented Generation (RAG)?</strong></h3><p>RAG is a technique that enhances the capabilities of LLMs by dynamically retrieving relevant information from external sources during inference. This approach addresses the inherent limitation of LLMs, which, despite their vast training data, may lack up-to-date or domain-specific knowledge.</p><p><em>How RAG Works:</em></p><ol><li><strong>Query Processing:</strong> Upon receiving a user query, the system employs a retriever to search external databases or documents to find pertinent information.</li><li><strong>Information Retrieval:</strong> The retriever identifies and selects documents or data segments relevant to the query.</li><li><strong>Response Generation:</strong> The LLM integrates the retrieved information with its internal knowledge to generate a coherent and contextually accurate response.</li></ol><p><em>Advantages of RAG:</em></p><ul><li><strong>Access to Dynamic Data:</strong> RAG excels in scenarios where information is frequently updated, such as news or real-time data feeds.</li><li><strong>Scalability:</strong> It can handle extensive and diverse datasets, retrieving only the most relevant pieces as needed.</li></ul><p><em>Limitations of RAG:</em></p><ul><li><strong>Latency:</strong> The retrieval process can introduce delays, especially with large datasets.</li><li><strong>System Complexity:</strong> Implementing RAG requires maintaining a retrieval pipeline, including search engines and indexing mechanisms, which can increase system complexity and maintenance efforts.</li><li><strong>Potential for Retrieval Errors:</strong> Incorrect or irrelevant documents may be retrieved, affecting the accuracy of the generated responses.</li></ul><h3><strong>What is Cache-Augmented Generation (CAG)?</strong></h3><p>CAG emerges as an alternative by leveraging the expanded context windows of modern LLMs. Instead of retrieving information in real-time, CAG preloads all necessary data into the model’s context and utilizes a precomputed Key-Value (KV) cache to streamline the generation process.</p><p><em>How CAG Works:</em></p><ol><li><strong>Data Preloading:</strong> Relevant documents are preprocessed and loaded into the model’s context window, fitting within its token capacity.</li><li><strong>KV Cache Utilization:</strong> The model precomputes a KV cache that encapsulates the inference state of the preloaded data.</li><li><strong>Inference:</strong> During inference, the model accesses the precomputed KV cache to generate responses, eliminating the need for real-time retrieval.</li></ol><p><em>Advantages of CAG:</em></p><ul><li><strong>Reduced Latency:</strong> By eliminating the retrieval step, CAG offers faster response times.</li><li><strong>Simplified Architecture:</strong> Without the need for a separate retrieval pipeline, the system becomes less complex and easier to maintain.</li><li><strong>Enhanced Consistency:</strong> Preloading data ensures that the model has a unified view of the information, which can improve response consistency.</li></ul><p><em>Limitations of CAG:</em></p><ul><li><strong>Context Window Constraints:</strong> The approach is limited by the model’s context window size, which may not accommodate very large datasets.</li><li><strong>Static Data Requirement:</strong> CAG is best suited for scenarios where the knowledge base is relatively stable and does not require frequent updates.</li><li><strong>Initial Setup Overhead:</strong> Preloading and precomputing the KV cache can be resource-intensive, especially for large datasets.</li></ul><h3><strong>Comparative Analysis: RAG vs. CAG</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rJdswR5uJXcNi1b7HEiUKg.png" /><figcaption>RAG vs CAG</figcaption></figure><h3><strong>Choosing Between RAG and CAG</strong></h3><p>The decision between RAG and CAG hinges on specific application requirements:</p><h4><strong>Opt for RAG when:</strong></h4><ul><li>The application demands access to real-time or frequently updated information.</li><li>The knowledge base is extensive, dynamic, and cannot fit within the model’s context window.</li><li>Flexibility and scalability are prioritized over response latency.</li></ul><h4><strong>Opt for CAG when:</strong></h4><ul><li>The knowledge base is stable, well-defined, and can fit within the model’s context window.</li><li>Fast response times are critical, and any retrieval latency is unacceptable.</li><li>A simpler system architecture is desired, with reduced maintenance overhead.</li></ul><h3><strong>Conclusion</strong></h3><p>Both RAG and CAG offer unique advantages in integrating external knowledge into LLMs. RAG provides dynamic access to up-to-date information, making it suitable for applications dealing with constantly changing data. In contrast, CAG offers speed and simplicity by preloading stable information into the model’s context. Understanding the strengths and limitations of each approach is essential for selecting the most appropriate method for a given application, ensuring optimal performance and accuracy in AI-driven solutions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a9e9f0517bf1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/kpmg-uk-engineering/rag-vs-cag-choosing-the-right-ai-approach-a9e9f0517bf1">RAG vs. CAG: Choosing the Right AI Approach</a> was originally published in <a href="https://medium.com/kpmg-uk-engineering">KPMG UK Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an Intelligent Chatbot with Langchain and Vector Databases]]></title>
            <link>https://medium.com/@neelamyadav10053/building-an-intelligent-chatbot-with-langchain-and-vector-databases-0014a454376c?source=rss-8ea043d1bf12------2</link>
            <guid isPermaLink="false">https://medium.com/p/0014a454376c</guid>
            <category><![CDATA[vector-database]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[langchain]]></category>
            <dc:creator><![CDATA[Neelamyadav]]></dc:creator>
            <pubDate>Sun, 21 Jan 2024 09:37:19 GMT</pubDate>
            <atom:updated>2024-01-21T09:37:19.840Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Welcome to the world of interactive chatbots, where artificial intelligence meets user-friendly interfaces.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FSNlUVj8HGzb5La03FSJ9w.png" /></figure><p>We’re diving into a practical session to build a chatbot that not only converses but understands and processes complex queries. Our tools of choice?</p><ol><li>Langchain framework for its AI prowess, and</li><li>FAISS for its vector database efficiency</li></ol><p>Let’s unravel these tools and their roles in our chatbot’s development.</p><h3>Langchain: Breathing Life into Chatbots</h3><p>Imagine having a digital assistant that learns from various documents and interacts with you as if it knows everything in them. That’s what Langchain brings to the table. It’s a Python-based toolkit that empowers language models to become data-aware. This means our chatbot won’t be restricted by what the model has been traditionally trained on; it can ingest new information and respond intelligently.</p><h3>Vector Databases: The Backbone of Data Retrieval</h3><p>Vector databases are at the forefront of managing and retrieving complex data types, such as text, images, and embeddings. They store information in vector format, which is ideal for handling unstructured data that traditional databases might struggle with. FAISS, or Facebook AI Similarity Search, is one such open-source library we use to store and manage these high-dimensional vector embeddings. With FAISS, our chatbot can perform high-speed searches, cluster, sort, and classify data points with ease.</p><h3>Chainlit (UI): Streamlining User Interactions</h3><p>Chainlit is the user interface magic that glues everything together. It’s a Python package that lets us swiftly build chat interfaces akin to the likes of ChatGPT. With Chainlit, integrating complex backend logic into a user-friendly front end becomes a breeze, making our chatbot not only smart but also accessible.</p><h3>Crafting an Intelligent Chatbot</h3><blockquote>Don’t worry about the code explained here. Its readily available. Just scroll down for it :)</blockquote><h4>Step 1: Data Loading and Text Splitting</h4><p>First, we load our documents:</p><pre>loader = DirectoryLoader(directory)<br>documents = loader.load()</pre><p>Then, we split the text into manageable pieces:</p><pre>text_splitter = RecursiveCharacterTextSplitter(chunk_size, chunk_overlap)<br>chunks = text_splitter.split_documents(documents)</pre><h4>Step 2: Embeddings and Vector DB Storage</h4><p>We generate embeddings and save them:</p><pre>embeddings = HuggingFaceEmbeddings(&#39;model_name&#39;, model_kwargs={&#39;device&#39;: &#39;cpu&#39;})<br>db = FAISS.from_documents(chunks, embeddings)<br>db.save_local(&#39;db_path&#39;)</pre><p>This step transforms text into a format that our AI can understand.</p><h4>Step 3: User Interactions and Chainlit Integration</h4><p>Here’s how we listen for user queries:</p><pre>@cl.on_message<br>async def main(message: cl.Message):<br>    response = await chain.acall(message.content)<br>    await cl.Message(content=response).send()</pre><p>And find related information:</p><pre>qa_result = RetrievalQA.from_chain_type(...)<br>response = qa_result({&#39;query&#39;: query})</pre><h3>Step 4: Running the Chatbot</h3><p>Launch the chatbot with:</p><pre>chainlit run chatbot.py</pre><p>And access it via:</p><pre>http://localhost:8000</pre><h3>Engaging with the Code</h3><p>For those eager to dive deeper and tweak the chatbot, the code is readily available here:</p><p><a href="https://github.com/neelam-yadav/DSAChatbot.git">https://github.com/neelam-yadav/DSAChatbot.git</a></p><p>This is how our DSA Chatbot looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GnklCKze6iTD4p8nenoLKQ.png" /></figure><h3>Conclusion</h3><p>By harnessing the strengths of Langchain and FAISS, we’ve developed a chatbot that not only understands complex queries but also provides accurate and insightful responses. Chainlit ensures that the user interface is as intuitive as the AI behind it, offering a seamless interaction experience. The fusion of these tools translates into a chatbot that’s not just a digital entity but a knowledgeable companion ready to converse on a multitude of topics.</p><p>Try out the chatbot and witness how it revolutionizes the way we interact with AI, bridging the gap between human queries and machine understanding.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0014a454376c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Decoding the AI Evolution: Langchain and Vector Databases]]></title>
            <link>https://medium.com/@neelamyadav10053/decoding-the-ai-evolution-langchain-and-vector-databases-24b87d5fb6b2?source=rss-8ea043d1bf12------2</link>
            <guid isPermaLink="false">https://medium.com/p/24b87d5fb6b2</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[vector-database]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Neelamyadav]]></dc:creator>
            <pubDate>Sat, 20 Jan 2024 09:13:37 GMT</pubDate>
            <atom:updated>2024-01-20T09:13:37.217Z</atom:updated>
            <content:encoded><![CDATA[<p>Welcome to the cutting edge of AI and machine learning, where the complexity of data meets the sophistication of modern algorithms. I’m here to present to you the marvels of Langchain and Vector Databases in an easily digestible format. Let’s embark on a journey to explore these transformative technologies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SUaVZpUhnPF9hdB1AAtSxA.png" /></figure><h3>Langchain: The AI Conversationalist</h3><p>Imagine having a conversation with AI that understands every piece of new information you present. That’s the vision behind Langchain, an open-source tool that endows Large Language Models (LLMs) like GPT-3.5 and GPT-4 with a remarkable capability — to be data aware and act with agency.</p><h4>The Challenge with LLMs</h4><p>LLMs are trained on vast datasets, but they’re traditionally limited to the knowledge cut-off at the time of their last training update. Take ChatGPT, for example; it can only comprehend and converse about information up to April 2023. What happens when the world moves on, and new data emerges? Enter Langchain.</p><h4>The Langchain Advantage</h4><p>Langchain is designed to feed LLMs with real-time data, whether it’s a Word document, a PDF, or any other format. This ability to process fresh data allows the AI to respond with an understanding of the latest information, providing a dynamic, human-like interaction.</p><h4>Building AI Agents with Langchain</h4><p>Langchain goes beyond simple conversations. It allows us to construct autonomous LLM agents that can perform a multitude of tasks. These range from data analysis and SQL querying to crafting basic code — effectively outsourcing routine cognitive tasks to AI, thus freeing up human intellect for complex problem-solving.</p><h3>Vector Databases: A Multidimensional Solution</h3><p>As we delve deeper into AI capabilities, we encounter the need for a system that can handle the vast and complex nature of unstructured data. This is where Vector Databases come into play.</p><h4>Unstructured Data and AI</h4><p>Most of the world’s data is unstructured. It’s the images we capture, the audio we record, and the text we write. Traditional databases struggle with this type of data due to its lack of clear organization.</p><h4>The Power of Vector Embeddings</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xc1E-NDZGha8Axc4E6b7aw.gif" /></figure><p>Vector Databases store information as vector embeddings — a mathematical representation in multi-dimensional space. These embeddings translate complex data into a language that AI can understand, capturing not just the data but its underlying semantic meaning.</p><h4>Open-source Pioneers</h4><p>The market offers various open-source vector databases like Chroma, Milvus, Weaviate, and FAISS, each contributing to the ecosystem with unique capabilities to store, search, and manage high-dimensional data.</p><h3>A Match Made in AI Heaven</h3><p>The synergy between Langchain and Vector Databases is where the magic happens. Langchain uses Vector Databases to manage the data it feeds to LLMs, ensuring that the AI is always conversing with the most current and relevant information.</p><h3>The Workflow</h3><p>A typical Langchain workflow begins with loading and processing documents, breaking them down into manageable chunks that fit within the LLM’s processing window.</p><ol><li>Loading and Processing Documents: Langchain tackles large text datasets by breaking them down into chunks, making data manageable and preserving context.</li><li>Creating and Using Vector Embeddings: It then translates text into vector embeddings, helping AI to grasp the semantic essence of the data.</li><li>Setting Up FAISS for Vector Database Management: With tools like FAISS, Langchain efficiently manages these embeddings for quick retrieval and similarity searches.</li><li>Configuring the Prompt and Model: A crucial step where the AI’s behavior is tailored through structured prompts and sophisticated models.</li><li>Assembling the LangChain: This involves combining various components into a modular workflow, allowing the AI to perform tasks like document retrieval, input formatting, response generation, and output parsing.</li><li>Querying the Chain and Analyzing Results: Finally, the AI is put to the test with specific queries to evaluate performance and fine-tune for accuracy.</li></ol><h3>Conclusion</h3><p>Langchain and Vector Databases are revolutionizing AI’s approach to data comprehension and interaction. By unifying these tools, we can create AI applications that are not only responsive but also truly understand the data they’re working with — propelling AI from mere machines to intelligent partners in our digital journey. As we continue to innovate and integrate these technologies, the potential for AI to enhance every facet of our lives becomes increasingly tangible.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=24b87d5fb6b2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>