<?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 Sai Sampath Ghantasala on Medium]]></title>
        <description><![CDATA[Stories by Sai Sampath Ghantasala on Medium]]></description>
        <link>https://medium.com/@psisampath1703?source=rss-b79b7d181d71------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*vVH0pYJsYpoTvrPy</url>
            <title>Stories by Sai Sampath Ghantasala on Medium</title>
            <link>https://medium.com/@psisampath1703?source=rss-b79b7d181d71------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 11:54:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@psisampath1703/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[Why Your AI Gives Different Answers: Explained with Sambar, Dosa and a Kirana Scale]]></title>
            <link>https://medium.com/@psisampath1703/why-your-ai-gives-different-answers-explained-with-sambar-dosa-and-a-kirana-scale-4df8de74ced3?source=rss-b79b7d181d71------2</link>
            <guid isPermaLink="false">https://medium.com/p/4df8de74ced3</guid>
            <category><![CDATA[nondeterminism]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Sai Sampath Ghantasala]]></dc:creator>
            <pubDate>Sun, 27 Sep 2026 04:55:45 GMT</pubDate>
            <atom:updated>2026-09-27T04:55:45.738Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Ask an AI the same question twice, with every randomness setting turned off, and you can still get two different answers. The reason has nothing to do with the AI being “creative.” It has everything to do with how busy the kitchen is.</em></p><h3>The mystery of the changing sambar</h3><p>Walk into your favourite Bengaluru darshini and order idli-vada with sambar. Tell the master: follow the recipe exactly, no experimenting. On Monday the sambar is a little tangier. On Tuesday it is a little sweeter. Same master, same recipe, same vessel. Someone blames the tamarind. Someone blames the weather. Nobody can prove anything.</p><p>Large language models like ChatGPT, Claude and Gemini have the same argument going on inside them.</p><p>When an AI writes an answer, it picks one word at a time. For each spot, it scores every possible next word and then chooses one. There is a setting called <strong>temperature</strong> that controls how adventurous that choice is. Set temperature to zero and the model should always pick the single highest-scoring word. No dice rolls. No creativity. Just the “best” word, every time. Think of it as the chef’s freedom to improvise. Turn temperature up and he might toss extra podi or a handful of cashews into the upma. Set it to zero and he must follow the standard recipe, bite for bite.</p><p>So with temperature at zero, the same question should give the same answer, word for word. Like a perfectly written recipe followed perfectly.</p><p>It doesn’t. Engineers have complained about this for years. In September 2025, Horace He and the team at Thinking Machines Lab published a research post called <a href="https://thinkingmachines.ai/blog/defeating-nondeterminism-in-llm-inference/">Defeating Nondeterminism in LLM Inference</a> that finally named the real culprit and showed how to fix it.</p><p>This article walks through their findings using things every Indian eatery and kirana store already has: a weighing scale, a restaurant pass, a busy darshini, a meals plate and a ball of atta. No computer science degree needed.</p><p>Prefer to watch? Here is the whole idea as a 15 minute animated explainer.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FcMAB5TVmOfU%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DcMAB5TVmOfU&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FcMAB5TVmOfU%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/c2d926ae7371e1ed2658822e35091acb/href">https://medium.com/media/c2d926ae7371e1ed2658822e35091acb/href</a></iframe><h3>Ingredient one: the kirana store scale that rounds</h3><p>Computers store decimal numbers in a format called <strong>floating point</strong>. The simplest way to picture it is the big weighing scale at your local kirana store.</p><p>That scale can weigh a 50 kg sack of rice. It can also weigh 100 grams of jeera. But it only shows a few digits at a time. Weigh something heavy and it shows kilograms; the grams quietly disappear. It keeps a fixed number of <em>significant digits</em>, and the scale slides up or down depending on how big the thing is.</p><p>Now imagine the shopkeeper keeps his ledger using only what the scale shows.</p><p><strong>Order A:</strong> He puts a 50 kg sack of basmati on the scale. It reads 50 kg. He drops in one elaichi pod, about 0.2 grams. The scale still reads 50 kg, because it cannot notice something that small next to something that big. He takes the rice sack off. The scale reads 0. The elaichi has vanished from the ledger.</p><p><strong>Order B:</strong> He puts the rice on, then takes it off. The scale reads 0. Then he adds the elaichi. The scale, now weighing something tiny, happily shows 0.2 grams.</p><p>Same ingredients. Different order. Different answer.</p><p>This is not a thought experiment. Open Python and type this:</p><pre>(0.1 + 10**20) - 10**20   # gives 0<br>0.1 + (10**20 - 10**20)   # gives 0.1</pre><p>In school maths, (a + b) + c always equals a + (b + c). With floating point, it doesn’t:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*KQpI3tQHfXwl3DVa_9GEsQ.png" /></figure><p>That’s because every step rounds off whatever doesn’t fit on the display. The Thinking Machines team showed how extreme this gets: take just eight numbers, add them up in 10,000 shuffled orders, and you get 102 different totals. Their code is short enough to run yourself, and it prints exactly 102.</p><p>Here is a worked example. Picture a shop scale that is precise for small weights but, for anything around a kilo, <strong>only reads to the nearest 10 g</strong>. That is exactly how floating point behaves: the bigger the number, the bigger the steps it can show. You are weighing 1000 g of rice plus two 4 g spoons of salt.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*ZHnM5HOQji_YwC95GCdu8A.png" /></figure><p>The true answer is 1008 g. Add the salt one spoon at a time and each spoon is too small for the scale to notice, so both vanish. Combine the two spoons first and together they are big enough to nudge the reading up. Same three ingredients, two different answers, only because of the grouping.</p><p>The 102-totals experiment works the same way. The eight numbers were 0.0000000001, 0.00001, 0.01 and 1, plus the negative of each, so the true total is exactly zero. Depending on the order, the tiny numbers get swallowed at different moments, and the computer reports 102 different almost-zero totals.</p><p>Here is the experiment, adapted from the research post, so you can run it yourself:</p><pre>import random<br>vals = [1e-10, 1e-5, 1e-2, 1]<br>vals = vals + [-v for v in vals]   # true total is exactly 0<br>results = []<br>random.seed(42)<br>for _ in range(10000):<br>    random.shuffle(vals)<br>    results.append(sum(vals))<br>unique = sorted(set(results))<br>print(f&quot;There are {len(unique)} unique results&quot;)<br>print(&quot;Smallest:&quot;, unique[:3])<br>print(&quot;Largest:&quot;, unique[-3:])</pre><p>And here is what it prints:</p><pre>There are 102 unique results<br>Smallest: [-8.326672684688674e-17, -7.45931094670027e-17, -7.419330991589868e-17]<br>Largest: [7.419330991589868e-17, 7.45931094670027e-17, 8.326672684688674e-17]</pre><p>Only 1,369 of the 10,000 shuffles landed on the true answer, 0. The rest scattered across 101 slightly wrong totals, as far off as about 8.3 × 10⁻¹⁷, which is 0.000000000000000083. Tiny, but not zero, and different depending on nothing more than the order of adding.</p><p>So the <em>order</em> in which a computer adds numbers changes the result. An AI model does billions of additions for every word it writes. If that order ever changes, the final scores for each word change slightly too.</p><p>The real question is: why would the order ever change?</p><h3>The red herring: too many cooks</h3><p>The popular explanation goes like this. A GPU, the chip that runs AI, is like a busy restaurant kitchen with a few dozen cooks. An order ticket comes in for a table: dal makhani, paneer tikka, butter naan and jeera rice. The head chef splits the ticket across cooks, and each one sends their dish to the pass, the counter where the waiter collects the order. Whichever dish reaches the pass first goes on the tray first. Cooks finish in an unpredictable order, so the order gets assembled differently every time, and the result wobbles.</p><p>It sounds right. It is also mostly wrong.</p><p>Kitchens <em>can</em> work that way. In GPU language, dishes landing on the tray in whatever order they reach the pass is called an <strong>atomic add</strong>, and it really does make results unpredictable. But the Thinking Machines team pointed out that the part of an AI model that writes answers, called the <em>forward pass</em>, uses no atomic adds at all.</p><h3>What an atomic add actually is</h3><p>Picture one billing counter where every cook must add the price of their dish to the table’s running bill. If two cooks scribble on the bill at the same instant, one amount could get lost. So the counter has a rule: one cook at a time, and each addition happens completely or not at all. <em>Atomic</em> means exactly that: an addition that can’t be interrupted halfway.</p><p>The rule guarantees that every cook’s amount gets added. It does <strong>not</strong> guarantee the order. Whoever reaches the counter first goes first.</p><p>Now bring back the same scale, which reads heavy loads only to the nearest 10 g. Three cooks arrive with 1000, 4 and 4:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*auyvpRdEnouVibr_Bqo7IQ.png" /></figure><p>Same dishes, same prices, different arrival order, different bill. Run the kitchen twice with identical orders and you can get two different totals. Engineers call this <em>run-to-run nondeterminism</em>, and atomic adds are its classic cause.</p><p>GPUs use atomic adds because they are the laziest way to let thousands of cores contribute to one sum without waiting on each other.</p><h3>Why the answer-writing step doesn’t need them</h3><p>The <em>forward pass</em> is the model’s trip from your question to its next word, one pass through all its layers, like an order going from ticket to tray. The researchers found it uses no atomic adds, for two reasons:</p><ol><li><strong>There is usually plenty of separate work.</strong> With many orders on the rail, each cook can take a whole dish alone. Nobody shares a counter, so nobody races.</li><li><strong>When a sum must be shared, kitchens use slips instead of a counter.</strong> Each cook writes their subtotal on their own slip, and the head chef adds the slips in a fixed sequence: cook 1, cook 2, cook 3. This is called a <em>split reduction</em>, and it costs almost no extra time.</li></ol><p>The common exception is during <em>training</em>, in a step that runs backwards through the attention layers. That step isn’t involved when the model writes answers for you.</p><p>In a well-run restaurant, the pass follows the ticket, not the stopwatch. The waiter loads the tray in the same sequence every time, dal, then paneer, then naan, then rice, no matter which cook finished first. The researchers proved this with a simple test. They ran the same big multiplication on the same GPU 1,000 times and got results that were identical down to the last bit, every single time.</p><p>So the cooks are innocent. The recipe steps themselves are perfectly repeatable. Something else must be changing between Monday and Tuesday.</p><h3>The real culprit: the lunch rush</h3><p>Here is the twist. When you send a question to ChatGPT, you are not the only customer. Thousands of people are asking questions at the same moment, and the server cooks all of them together in one go. This group of orders is called a <strong>batch</strong>.</p><p>Think of a busy Bengaluru darshini with ten cooks.</p><p><strong>At 1:30 pm, the lunch rush.</strong> Forty orders of South Indian meals are waiting, with rice, sambar, rasam, palya and curd on every plate. The easiest plan: each cook takes one complete plate and makes the whole thing, start to finish. Your meals plate is made by one cook, in one sequence.</p><p><strong>At 4 pm, the dead hour.</strong> Only your order comes in. Nine cooks standing idle is a waste, so the master splits your single plate. One cook ladles the sambar, another the rasam, a third makes the palya, all at the same time, and someone assembles the plate at the end.</p><p>That split is smart. It gets your food out faster. But notice what happened: <em>your</em> plate was put together in a different sequence, by a different grouping of hands, only because of how many other customers were in the darshini.</p><p>This is exactly what GPU code does. Engineers write their code to keep every part of the chip busy. With a big batch, each part of the chip computes one person’s full sum on its own. With a small batch, there isn’t enough work to go around, so the code splits <em>one person’s</em> sum into pieces across many parts of the chip and combines the pieces at the end.</p><p>Splitting changes the grouping of the additions. And from the kirana scale, you already know what a different grouping does: the rounding lands differently. Maybe your number comes out as 0.48171234 at lunchtime and 0.48171238 at 4 pm.</p><p>Now the final piece. You cannot see how busy the darshini is from your table. The batch size depends on how many strangers happen to be using the AI at the exact second you hit enter. From your point of view, that is pure chance.</p><p>Put those together and you get the answer to the whole mystery:</p><blockquote><em>The AI gives different answers because its maths depends on the batch size, and the batch size depends on how busy the server is, which you can’t control or see.</em></blockquote><p>The researchers call the missing property <strong>batch invariance</strong>: your result should not depend on how many other orders are cooking alongside yours. Most AI serving software today does not have it. And notably, this isn’t a GPU quirk; servers running on other chips would have the same problem.</p><h3>The evidence: ghee roast or benne dosa?</h3><p>A difference in the eighth decimal place sounds harmless. Can it really change what the AI says?</p><p>The researchers tested it. They took a large open model, Qwen3–235B, and sent it the same prompt, <em>“Tell me about Richard Feynman,”</em> 1,000 times at temperature zero. In theory, that should produce one answer, copied 1,000 times.</p><p>They got <strong>80 different answers</strong>.</p><p>Every single one matched for the first 102 tokens (a token is a word or a piece of a word). Then, at token 103, the answers split:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*19QUJApppe7xbZ0ZKSt_8g.png" /></figure><p>Picture the master choosing between a ghee roast and a benne dosa when both would be perfect. His scores are nearly tied: ghee roast 0.50000001, benne dosa 0.49999999. A rounding wobble from the crowd in the kitchen is enough to flip the winner. At lunchtime you get a ghee roast; at 4 pm, a benne dosa. That is exactly what happened at token 103.</p><p>And once one word changes, every word after it is written on top of a different sentence, so the two answers drift further and further apart. Order a ghee roast, and the chutney, the sambar and the filter coffee that follow are all chosen to go with it.</p><h3>The fix: same-size rotis, every time</h3><p>The fix follows directly from the diagnosis. If the problem is that the kitchen changes its method depending on the crowd, then the kitchen must use one method, no matter the crowd. Your meals plate gets assembled the same way at 1:30 pm and at 4 pm.</p><p>The cleverest part of the fix is best explained with roti dough.</p><p>Say you have a lump of atta and need to divide it among cooks. There are two ways to give instructions:</p><ol><li><strong>“Always make 4 rotis.”</strong> With 1 kg of atta, each roti is 250 g. With 800 g, each roti is 200 g. The cut points move every time the lump changes size.</li><li><strong>“Always make 256 g rotis.”</strong> With 1 kg, you get three 256 g rotis and one smaller leftover. With 800 g, you get three 256 g rotis and a tiny one. The cut points stay in exactly the same places.</li></ol><p>The second rule is what the researchers did. Inside the AI, the dough is the model’s memory of the conversation so far, and its length keeps changing as the answer grows and as requests get chopped into chunks. By always cutting that work into fixed-size pieces instead of a fixed number of pieces, the additions always happen in the same groups, so the rounding always lands the same way.</p><p>They applied this discipline to the three steps inside the model that add long lists of numbers, which you can think of as three items on the meals plate:</p><ul><li><strong>Normalisation</strong> (evening out the numbers): each customer’s row stays with one cook, start to finish, never split.</li><li><strong>Matrix multiplication</strong> (the main course, where most of the work happens): one fixed kitchen setup for every order size, even when a different setup would be faster for small orders.</li><li><strong>Attention</strong> (where the model looks back at earlier words): the fixed-size-roti trick above, plus making sure old and new ingredients are always laid out the same way before cooking starts.</li></ul><p>The result? They sent the Feynman prompt(Tell me about Richard Feynman) 1,000 times again, now with these batch invariant kernels. All 1,000 answers were <strong>identical</strong>.</p><h3>The price, and why it’s worth paying</h3><p>A kitchen that refuses to adapt to the crowd is a little slower. The researchers measured it on a server running the Qwen3–8B model, generating 1,000 answers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*Q9y9uvC_W6Lxx7MBdiQEbA.png" /></figure><p>Slower, but not a disaster, and they note they have barely started optimising it.</p><p>Why bother? Three reasons.</p><p><strong>Science needs repeatable results.</strong> If a lab can’t get the same output twice, it can’t tell whether a change it made helped, hurt, or did nothing. Debugging becomes guesswork.</p><p><strong>Testing gets honest.</strong> Engineers often loosen their tests (“close enough is fine”) because AI outputs wobble. With repeatable outputs, a test can demand an exact match, and any difference means a real bug.</p><p><strong>AI training gets smoother.</strong> This is the most surprising benefit. Modern AI models improve through a kind of practice called <em>reinforcement learning</em>. One part of the system cooks the answers (the sampler), and another part tastes them and adjusts the recipe (the trainer). Today, those two usually do their maths slightly differently, so the taster is judging a dish that isn’t quite the one that was served. The researchers showed this mismatch can make training collapse partway through. With batch invariant kernels, the cook and the taster work from exactly the same numbers. The gap between them dropped to zero, and training stayed smooth without any extra correction tricks.</p><h3>The takeaway</h3><p>When AI behaves unpredictably, it is tempting to shrug, “It’s AI, it’s probabilistic, what do you expect?” The Thinking Machines team rejected that shrug. They traced a mysterious wobble through rounding, parallel chips and server traffic, found a concrete cause, and fixed it.</p><p>So the next time the darshini’s sambar tastes different on Tuesday, don’t blame the master. Ask how busy the kitchen was.</p><h3>Credits</h3><p>This article explains the research post <a href="https://thinkingmachines.ai/blog/defeating-nondeterminism-in-llm-inference/">Defeating Nondeterminism in LLM Inference</a> by Horace He and Thinking Machines Lab (September 2025). All numbers and experiments come from that post; the kitchen analogies are mine. Their batch invariant kernels are open source on <a href="https://github.com/thinking-machines-lab/batch_invariant_ops">GitHub</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4df8de74ced3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI Concepts Explained Through a Plate of Hot Biryani]]></title>
            <link>https://medium.com/@psisampath1703/ai-101-explained-through-a-plate-of-hot-biryani-50536883851d?source=rss-b79b7d181d71------2</link>
            <guid isPermaLink="false">https://medium.com/p/50536883851d</guid>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[ai-education]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Sai Sampath Ghantasala]]></dc:creator>
            <pubDate>Sat, 30 May 2026 06:57:16 GMT</pubDate>
            <atom:updated>2026-05-30T07:12:21.663Z</atom:updated>
            <content:encoded><![CDATA[<p>A beginner-friendly guide to ChatGPT, LLMs, tokens, embeddings, prompt engineering, and AI agents — explained using Indian food.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*soaUVd6TN5Cz322lkEB33w.png" /></figure><p>Every time you read about AI, you get hit with a wall of words that feel designed to make you feel stupid. <em>Tokens, Context Windows, Embeddings, Agents.</em> It feels like you need a computer science PhD just to use a chatbot.</p><p>But underneath the marketing fluff, the core mechanics of AI are actually very simple. We can explain almost all of it using something we deal with every day: food.</p><h3>What is an LLM?</h3><p>Before looking at the individual terminologies, we need to understand the engine. What actually is a Large Language Model (LLM) like GPT-4 or Claude?</p><p>Think of an LLM as a chef who has read every cookbook, recipe blog, and restaurant review on the internet.</p><p>The chef hasn’t memorized every single sentence word-for-word. Instead, through years of reading, they have figured out the <em>patterns</em> of food:</p><ul><li>Which ingredients usually go together (like tomatoes and basil).</li><li>Which dishes typically follow others in a multi-course meal.</li><li>Which flavors complement one another.</li></ul><p>When you ask an AI a question, it isn’t searching a database of pre-written answers. Instead, the chef is predicting the next best ingredient (or word) one step at a time, based on those learned patterns.</p><h3>1. Tokens</h3><p>Imagine you went to Meghana Foods and ordered a Biryani. You don’t gulp whole plate of biryani in one go. You eat it spoon by spoon, chewing and digesting it bit by bite.</p><p>AI does the exact same thing. A language model cannot read your entire prompt as one single block of text. Instead, it chops your sentences down into tiny, bite-sized pieces called <strong>tokens</strong>.</p><ul><li>A token isn’t always a full word. It can be a single word, a prefix, punctuation, or even just a fragment of a word.</li><li>For example, the sentence <em>“I love masala dosa”</em> gets chopped up into five distinct “spoonfuls” by the AI: [&quot;I&quot;] [&quot;love&quot;] [&quot;mas&quot;] [&quot;ala&quot;] [&quot;dosa&quot;].</li></ul><pre>How the AI Reads Your Query:<br>┌─────────┐     ┌─────────┐     ┌─────────┐     ┌─────────┐     ┌─────────┐<br>│   &quot;I&quot;   │ ──► │ &quot;love&quot;  │ ──► │  &quot;mas&quot;  │ ──► │  &quot;ala&quot;  │ ──► │ &quot;dosa&quot;  │<br>└─────────┘     └─────────┘     └─────────┘     └─────────┘     └─────────┘<br>Spoonful 1      Spoonful 2      Spoonful 3      Spoonful 4      Spoonful 5</pre><p>When you type a query, the AI sits down and processes your input spoon by spoon to understand the overall flavor of what you are asking.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8moo-TwrqFVpwYgh7iHsQg.png" /></figure><h3>2. Context Window</h3><p>Imagine sitting down for a heavy lunch. Your body has a hard physical limit on how much rice it can handle in one sitting. That capacity limit is the <strong>Context Window</strong>.</p><p>In AI terms, the context window is the maximum number of tokens (spoonfuls) the model can hold in its active memory at any given moment.</p><ul><li>Older or smaller models can only handle a conversation the size of a single <em>dosa</em>.</li><li>Modern models have massive stomach capacities, meaning they can ingest hundreds of pages of text in a single prompt.</li></ul><h3>3. Hallucinations</h3><p>what happens when you try to eat way past your capacity? Your stomach gets overloaded, leading directly to indigestion, severe acidity, and physical rejection.</p><p>An LLM behaves the exact same way. If you force-feed it more text than its context window can handle, it experiences severe “technical indigestion” because it simply cannot digest the excess. This brings us to the most infamous issue with AI: <strong>Hallucinations</strong>.</p><p>When you stuff too much text into a model, or ask it to process a massive, cluttered document, it gets technical acidity. In computer science, this is known as the <em>“</em><strong><em>Lost in the Middle</em></strong><em>”</em> effect. The AI’s memory gets so clogged that it completely loses track of the details buried in the middle of your prompt.</p><pre>The &quot;Lost in the Middle&quot; Indigestion:<br>┌────────────────────────────────────────────────────────┐<br>│  [Top of Prompt]   - Recalled Well                     │<br>├────────────────────────────────────────────────────────┤<br>│  [Middle of Prompt]- ACIDITY / LOST IN INDIGESTION!    │◄── Hallucinations<br>├────────────────────────────────────────────────────────┤  ◄── happen here!<br>│  [End of Prompt]   - Recalled Well                     │<br>└────────────────────────────────────────────────────────┘</pre><p>Because these models are designed to always give you an answer no matter what, they won’t stop and tell you their stomach hurts. Instead, they do the digital equivalent of <strong>vomiting</strong>.</p><p>The model throws up a messy, chaotic mixture of half-remembered facts, incorrect guesses, and completely made-up nonsense, presenting it to you as if it were a perfectly cooked dish.</p><p>Imagine a chef who has absolutely no idea how to make <em>Rasmalai</em>. Instead of admitting it, his system glitches under pressure. He randomly throws curd, sugar, salt, and milk into a bowl, presents this messy throw-up beautifully, and says with absolute confidence:</p><blockquote>“Here is your authentic, wood-smoked, deconstructed fusion Rasmalai, sir. Chef’s special.”</blockquote><p>Because the AI is just predicting patterns, it will serve you this “vomited” nonsense wrapped in highly authoritative, convincing language. This is why you can never blindly trust a model’s output.</p><p><em>(If you want to see how software engineers actually cure this technical indigestion in production systems, check out my deep-dive article on building a real-world solution to this exact problem: </em><a href="https://medium.com/@psisampath1703/beyond-the-toy-apps-building-a-full-stack-production-grade-agentic-rag-pipeline-in-net-841b61232ae6"><em>Beyond the Toy Apps: Building a Full-Stack, Production-Grade Agentic RAG Pipeline in .NET.</em></a><em>)</em></p><h3>4. Prompt Engineering: Ordering at Subway</h3><p>Have you ever ordered a sandwich at Subway?</p><p>If you just walk up to the counter and say, <em>“Give me food,”</em> the person behind the glass is going to stare at you. If you get anything at all, it’ll probably be a weird, disappointing mess.</p><p>To get a great sandwich, you have to be specific about the components:</p><ul><li>The bread (Multigrain Honey Oat)</li><li>The protein (Paneer Tikka or Roasted Chicken)</li><li>The cheese (Mozzarella)</li><li>The specific veggies (lots of olives, no onions)</li><li>The exact sauces (Sweet Onion and Mint Mayo)</li></ul><p><strong>Prompt Engineering</strong> is exactly like ordering your sandwich.</p><p>The quality of the AI’s response depends entirely on the specific “toppings” you choose for your prompt. If you write a lazy, blank prompt, you get a bland, useless answer.</p><ul><li><strong>The lazy order:</strong> <em>“Write an email about cloud computing.”</em> (This gets you dry, generic bread).</li><li><strong>The Subway-style order:</strong> <em>“Write a 3-paragraph email explaining cloud computing to a non-technical sales team. Use a simple, real-world analogy, keep the tone casual, and format it with clear bullet points.”</em> (Now you’ve chosen your bread, veggies, and sauces — and the final output actually tastes good).</li></ul><h3>5. Temperature: The Chef’s Mood</h3><p>Some home cooks follow a recipe down to the exact gram. Others throw random ingredients into a pan just to see what happens. This level of randomness is what we call <strong>Temperature</strong> (usually scaled from 0 to 1).</p><ul><li><strong>Low Temperature (</strong>0.1–0.3<strong>):</strong> The strict, traditional chef. They follow the recipe book perfectly. The output is highly predictable, factual, and repetitive. This is what you want for writing code, doing math, or summarizing legal documents.</li><li><strong>High Temperature (</strong>0.7–1.0<strong>):</strong> The experimental fusion chef. They might put chocolate inside a <em>samosa</em> or cheese on <em>panipuri</em>. The output is highly creative, unexpected, and varied. This is the setting you want for brainstorming story ideas, writing poetry, or naming a startup.</li></ul><p><strong>The Intelligence Trap:</strong> A common mistake beginners make is thinking that a higher temperature makes the AI “smarter” because it gets more creative. It doesn’t. Higher temperature increases <em>randomness</em>, not intelligence. A chef running on high temperature is like a cook who has had way too much espresso — they will throw wild ideas at you, but they are also much more likely to make a complete mess of the kitchen.</p><h3>6. Embeddings</h3><p>How does a computer actually understand that a <em>samosa</em> and a <em>kachori</em> are practically cousins, but a <em>samosa</em> and a <em>smartphone</em> have absolutely nothing in common? It uses <strong>Embeddings</strong>.</p><p>Imagine every food item in the world is placed on a massive, invisible 3D map based on its flavor profile. Let’s map them using three coordinates: $(Sweetness, Spiciness, Crunchiness)$.</p><pre>The Great Flavor Coordinate Map:<br>          [Spiciness]<br>               ▲<br>               │      *(Chilli Paneer) [1, 8, 4]<br>               │<br>               │<br>               │           *(Samosa) [1, 6, 8]<br>               │<br>               └────────────────────────► [Sweetness]<br>              /  *(Gulab Jamun) [9, 0, 1]<br>             /   *(Jalebi)      [9, 0, 6]<br>            ▼<br>     [Crunchiness]</pre><ul><li><em>Gulab Jamun</em> sits at coordinate $(9, 0, 1)$—high sweet, no spice, low crunch.</li><li><em>Jalebi</em> sits right next to it at $(9, 0, 6)$—high sweet, no spice, but very crunchy.</li><li><em>Chilli Paneer</em> is way over at $(1, 8, 4)$.</li><li>A <em>smartphone</em> would be placed on a completely different map, miles away.</li></ul><p>Embeddings are mathematical coordinates that place words and sentences on a “meaning map” just like this flavor map. By converting words into these numbers, the AI instantly understands how “close” two ideas are, allowing it to make smart recommendations, search for related topics, and understand context.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CZ10AmSvBTvXwK0Nob97gQ.png" /></figure><h3>7. AI Agents</h3><p>Using basic AI is like dealing with a single, overworked solo chef in a roadside food stalls. They have to take your order, prep the vegetables, cook the food, wash the dishes, and handle the billing all by themselves.</p><p>The future of technology belongs to <strong>AI Agents</strong>, which operate like a highly coordinated restaurant kitchen.</p><p>Instead of one giant AI trying to do everything, you have a team of specialized agents working together:</p><ul><li><strong>The Waiter (Manager Agent):</strong> Takes your request, breaks it down into a plan, and assigns tasks.</li><li><strong>The Prep Cook (Search Agent):</strong> Scours the internet to gather fresh, real-time data.</li><li><strong>The Line Cook (Writing Agent):</strong> Takes the data and drafts a clean response.</li><li><strong>The Head Chef (Critic Agent):</strong> Reviews the draft, checks for errors, and only serves it when it’s ready.</li></ul><p>By collaborating and passing tasks back and forth, AI agents can handle complex workflows — like writing a full research paper or building a software application — entirely on their own.</p><h3>Final Thoughts</h3><p>At the end of the day, AI is not a conscious, thinking mind trapped inside a computer. It is not magic.</p><p>It is a complex kitchen. It takes in ingredients (data), chops them into spoonfuls (tokens), uses specific tools (embeddings), and operates under strict rules (temperature, prompt constraints, and context limits) to serve you a plate of text that mimics human language.</p><p>Once you stop looking at AI as a mysterious sci-fi robot and start seeing it as a structured system of patterns, the entire landscape becomes incredibly easy to navigate.</p><p>The next time someone tries to intimidate you with AI buzzwords, just smile, think of your customized Subway order, and remember: it’s all just cooking.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50536883851d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beyond the Toy Apps: Building a Full-Stack, Production-Grade Agentic RAG Pipeline in .NET]]></title>
            <link>https://medium.com/@psisampath1703/beyond-the-toy-apps-building-a-full-stack-production-grade-agentic-rag-pipeline-in-net-841b61232ae6?source=rss-b79b7d181d71------2</link>
            <guid isPermaLink="false">https://medium.com/p/841b61232ae6</guid>
            <category><![CDATA[microsoft-agent-framework]]></category>
            <category><![CDATA[agentic-rag]]></category>
            <category><![CDATA[rags]]></category>
            <dc:creator><![CDATA[Sai Sampath Ghantasala]]></dc:creator>
            <pubDate>Thu, 21 May 2026 05:54:00 GMT</pubDate>
            <atom:updated>2026-05-21T09:12:06.737Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you ever tried asking an AI model to answer questions about your company’s internal PDFs, only for it to confidently make up completely false information?</p><p>In the AI world, we call this <strong>hallucination</strong>. In the corporate world, we call it an executive liability.</p><p>To solve this, developers use a pattern called <strong>RAG (Retrieval-Augmented Generation)</strong>. But if you search for “How to build RAG in .NET,” 95% of the tutorials show you a basic console app that reads a local text file, generates an embedding, and prints a console output. That is a “toy app.”</p><p>When you deploy a RAG pipeline to production, you face a completely different class of engineering challenges:</p><ul><li>How do you scale document ingestion globally without choking your web server threads?</li><li>How do you manage multi-turn conversational history when the LLM itself is stateless?</li><li>How do you avoid annoying CORS configuration bottlenecks during local development?</li><li>How do you build a flexible agent that knows <em>when</em> to search your database, rather than blindly fetching data for a simple query like <em>“Hi, how are you?”</em></li></ul><p>In this deep-dive guide, we are going to move past the superficial tutorials. First, we will demystify the core mathematical concepts of RAG using simple, everyday analogies that anyone can understand. Second, we will map out and build a production-ready, full-stack architecture using <strong>React</strong>, <strong>.NET Minimal APIs</strong>, <strong>AWS S3</strong>, <strong>Amazon EventBridge</strong>, <strong>Quartz.NET</strong> deployed on decoupled containers (<strong>AWS ECS/EC2</strong>), <strong>Pinecone</strong> for vector search, and the unified <strong>Microsoft Agent Framework (MAF)</strong>.</p><h3>RAG Demystified</h3><p>Before we write a single line of C# or React, we must understand the mechanics under the hood. Let’s break down the math and engineering concepts using some familiar Indian analogies.</p><h3>1. Why Do LLMs Hallucinate?</h3><p>Imagine you hire a world-class, Michelin-starred chef (the Large Language Model, or LLM) to cater an intimate family dinner. This chef has read every cookbook in existence. They know how to prepare French soufflés, Italian risottos, and generic street-style curries perfectly.</p><p>However, during the dinner, you ask the chef: <em>“Can you cook my grandmother’s secret, authentic Amritsari Dal Makhani?”</em></p><p>The chef has a major problem. They are incredibly skilled, but they do not know your grandmother’s secret spice ratios. Because the chef is eager to please, they will not say “I don’t know.” Instead, they will use their general knowledge to improvise and create a recipe that <em>looks</em> right, but lacks the secret ingredients.</p><p>In AI terms, this creative improvisation is a <strong>hallucination</strong>. The chef’s brain was pre-trained on generic data, but they lack your specific, private grounding data.</p><h3>2. What is RAG? (Retrieval-Augmented Generation)</h3><p>To solve the chef’s dilemma, you do something simple: you walk into your kitchen, grab your grandmother’s handwritten recipe diary, and hand it to the chef.</p><pre>+------------------+     1. Query      +---------------------------+<br>|   Dinner Guest   |------------------&gt;|         The Chef          |<br>| (&quot;Make Granny&#39;s  |                   |    (Pre-trained weights)  |<br>|   Dal Makhani&quot;)  |                   +-------------+-------------+<br>+------------------+                                 |<br>         ^                                           | 2. Retrieves secret<br>         |                                           |    recipe notebook<br>         | 4. Serves perfect,                        v<br>         |    grounded dish            +---------------------------+<br>         +-----------------------------|   Granny&#39;s Recipe Book    |<br>                                       |      (Grounding Data)     |<br>                                       +---------------------------+</pre><p>Now, the chef’s execution changes:</p><ol><li><strong>Retrieval:</strong> The chef searches through the diary (the database) to find the page detailing the “Amritsari Dal Makhani.”</li><li><strong>Augmentation:</strong> The chef reads those specific secret notes and appends them to their world-class cooking skills.</li><li><strong>Generation:</strong> The chef cooks a perfectly grounded, authentic dish.</li></ol><p><strong>Retrieval-Augmented Generation (RAG)</strong> is simply the process of feeding the LLM a highly relevant “cheat sheet” (grounding context) right before it generates a response.</p><h3>3. What are Embeddings and Vectors?</h3><p>To feed our “cheat sheet” to a computer, we need a way to translate human language into numbers. This is where <strong>embeddings</strong> and <strong>vectors</strong> come in.</p><p>Suppose you want to describe where the Taj Mahal is to an international tourist. You could describe nearby landmarks, or you could give them its exact GPS coordinates: [27.1751, 78.0421]. These two numbers represent a precise location in a two-dimensional physical space.</p><p>An <strong>embedding</strong> is the exact same concept, but instead of mapping physical locations on Earth, it maps the <em>meaning of words or sentences</em> in a high-dimensional mathematical space. This list of numbers is called a <strong>vector</strong>.</p><h4>The Spice Grid Example (Visualizing Vector Space)</h4><p>Let’s map some popular Indian street foods on a simple 2-dimensional grid based on two attributes: <strong>Spiciness</strong> (X-axis) and <strong>Sweetness</strong> (Y-axis), scaling both from 0 to 10.</p><pre>Sweetness (Y)<br>  ^<br>  |  [Gulab Jamun] (0, 10)<br>  |<br>  |  [Jalebi] (0.5, 9.5)<br>  |<br>  |                               [Samosa] (8, 1)<br>  |                               [Chilli Bajji] (10, 0)<br>  +----------------------------------------------------&gt; Spiciness (X)</pre><ul><li><strong>Chilli Bajji</strong> is incredibly spicy and not sweet at all. Its vector is [10, 0].</li><li><strong>Samosa</strong> is moderately spicy and slightly sweet (from sweet tamarind chutney). Its vector is [8, 1].</li><li><strong>Gulab Jamun</strong> is pure sweet syrup. Its vector is [0, 10].</li><li><strong>Jalebi</strong> is also incredibly sweet with a tiny hint of sour/spice. Its vector is [0.5, 9.5].</li></ul><p>Because the vectors for <strong>Gulab Jamun</strong> [0, 10] and <strong>Jalebi</strong> [0.5, 9.5] are numerically very close in this vector space, a computer can instantly calculate that they have a highly similar flavor profile, even if the computer has absolutely no concept of what &quot;sweet&quot; actually tastes like.</p><h3>4. What is Dimensionality and the “Upsert Mismatch” Trap?</h3><p>In our simple street food example, we only looked at two dimensions: <em>Spiciness</em> and <em>Sweetness</em>.</p><p>However, real food is much more complex. To map its profile accurately, we need dimensions for <em>Sourness, Saltiness, Crunchiness, Serving Temperature, Oiliness, and Pungency</em>. If we use 8 attributes, our food vector expands to 8 dimensions (e.g., Samosa = [8, 1, 3, 7, 9, 8, 8, 4]).</p><p>In enterprise AI, OpenAI’s text-embedding-3-small model typically uses <strong>512</strong> or <strong>1536</strong> dimensions. It maps sentences across thousands of complex semantic, grammatical, and conceptual axes to capture the exact nuances of human language.</p><h4>The Upsert Mismatch Error 🚨</h4><p>Imagine your kitchen has a custom spice rack built specifically to hold <strong>3-slot spice jars</strong> (3 dimensions). One day, you buy a premium <strong>5-slot spice jar</strong> (5 dimensions) from the local market and try to force it onto the rack. It physically won’t fit, and you might drop and break it.</p><pre>Expected Index Dimension: [X, Y, Z] (Dim: 3)<br>Incoming Vector:          [A, B, C, D, E] (Dim: 5) ---&gt; ERROR: Dimension Mismatch!</pre><p>This is the exact root cause of the infamous <strong>Upsert Dimension Mismatch Error</strong> in vector databases like Pinecone.</p><ul><li>If you set up your Pinecone index to expect <strong>512 dimensions</strong> (the space you configured for your database)…</li><li>But in your C# code, you call the embedding generator with a default configuration that outputs <strong>1536 dimensions</strong>…</li><li>The database will aggressively reject the request. The dimensionality of your incoming embeddings <em>must</em> perfectly match the declared schema of your vector index.</li></ul><h3>5. What is Similarity Search and how does it work?</h3><p>When a user asks our RAG chatbot a question, we convert their query into a vector and look for the closest matching document vectors in our database. How do we mathematically measure “closeness”?</p><p>There are three primary distance metrics used in production vector databases:</p><h4>A. Euclidean Distance (L2)</h4><ul><li><strong>How it works:</strong> It measures the straight-line distance between two points (like measuring with a physical ruler).</li><li><strong>Analogy:</strong> Finding the closest auto-rickshaw stand near you. You look at a map, draw a straight line from your location to the nearest stand, and walk. It doesn’t care about what direction the stand is facing; it only cares about physical closeness.</li><li><strong>Use Case:</strong> Best when the absolute magnitude of your values is highly critical.</li></ul><h4>B. Cosine Similarity</h4><ul><li><strong>How it works:</strong> It measures the <em>angle</em> between two vectors, ignoring their scale or length. It focuses purely on the “ratio” of the attributes.</li><li><strong>Analogy:</strong> Think of a perfect cup of <strong>Masala Chai</strong> (which is a precise ratio of ginger, cardamom, tea leaves, milk, and sugar).</li></ul><pre>  Massive 10-Liter Kettle Vector<br>               ^<br>              /<br>             /   (Angle is 0° - Exact same flavor ratio!)<br>            / <br>           /____ Small 150ml Cup Vector<br>          +----------------------------&gt;</pre><p>Whether you pour a tiny <strong>150ml cup</strong> of tea at a roadside stall or brew a massive <strong>10-liter kettle</strong> of tea, the <em>flavor profile ratio</em> remains identical. Cosine similarity recognizes them as the exact same beverage because the angle between their profiles is zero, even though their volumes (magnitudes) are completely different.</p><ul><li><strong>Use Case:</strong> Standard for text retrieval. A short paragraph and a long article on the exact same topic will have highly similar angles, despite different word counts.</li></ul><h4>C. Dot Product (Inner Product)</h4><ul><li><strong>How it works:</strong> It multiplies both the angle (direction) and the length (magnitude) of the vectors.</li><li><strong>Analogy:</strong> Think of how movie recommendations work. If you and a friend both have strong, passionate alignments on Bollywood action movies, your combined score is massive. If one of you is indifferent (low magnitude) or you have opposite tastes (pointing in different directions), the score drops to zero or goes negative.</li><li><strong>Use Case:</strong> Highly optimized search when vectors are already normalized (scaled to a length of exactly 1).</li></ul><h3>6. Chunking, Token Limits, and Context Windows</h3><p>Why can’t we just feed an entire 500-page operational manual directly to the LLM every time a user asks a question? To understand why, we have to look at the physical limitations of Large Language Models.</p><h4>A. The Context Window and Token Limits (The Banana Leaf Feast)</h4><p>LLMs don’t read words like humans; they break sentences down into small fragments of characters called <strong>tokens</strong>. For example, the Hindi phrase “Shaktimaan” might be parsed by an AI as three distinct tokens: [&quot;Shak&quot;, &quot;ti&quot;, &quot;maan&quot;].</p><p>Every LLM has a strict <strong>Context Window</strong> — a maximum threshold of tokens it can hold in its active working memory at any single moment.</p><pre>+------------------------------------------------------------+<br>|                  The Banana Leaf Surface                   |<br>|  [Rice]   [Sambar]   [Avial]   [Thoran]   [Rasam]  [Papad] |<br>|                                                            |<br>|  &lt;--- Overfilled Leaf = Spills, Mix-ups, Messy Disaster---&gt;|<br>+------------------------------------------------------------+</pre><ul><li><strong>The Analogy:</strong> Imagine you are sitting down for a traditional South Indian <em>Sadya</em> or <em>Thali</em> served on a beautiful green banana leaf. This leaf has a physical, fixed surface area (the Context Window). If the server places rice, sambar, papad, and three side curries on the leaf, you have plenty of space to enjoy your meal systematically.</li><li>But imagine a hyper-generous relative rushes over and dumps 40 different curries, 10 types of parathas, 5 styles of biryani, and 8 bowls of payasam / Kheer all at once onto your single leaf. The food will slide off the edges, mix into a strange unappetizing mush, ruin the flavors, and make an absolute mess.</li><li><strong>The Reality:</strong> When you try to stuff an entire directory of documents into a single prompt, you exceed the model’s physical “leaf capacity.” The API will either reject your request with an out-of-memory error, or the model will get confused by the cluttered context and return broken, nonsensical responses.</li></ul><h4>B. The “Lost in the Middle” Phenomenon (The Grand Wedding Buffet Line)</h4><p>Even if an LLM has a massive context window (like Gemini’s 1-million+ tokens), it suffers from a cognitive bias called primacy and recency effects. It pays deep attention to information at the very beginning and the very end of its prompt, but glosses over the middle.</p><ul><li><strong>The Analogy:</strong> Think of walking through a massive, 150-dish Indian wedding buffet line.</li><li>At the very start of the table, you are excited and hungry. You pay deep attention to the appetizers — piling your plate with hot Paneer Tikka, Crispy Samosas, and Golgappas. You remember exactly how crisp and perfect each one tasted.</li><li>In the chaotic, long middle section of the counter, your attention wanders. You breeze past 25 similar-looking curries, rice dishes, and dals, scooping up random items without really looking at or tasting them.</li><li>At the very end of the line, you perk up again because you’ve reached the live dessert counter. You focus entirely on getting a hot, fresh Jalebi with Rabri.</li><li>If someone asks you the next morning: <em>“How was the taste of the third vegetable curry in the middle section of the counter?”</em> you won’t have a clue. Your brain completely “lost it in the middle.”</li><li><strong>The Reality:</strong> If you stuff a 500-page document into your prompt, the LLM will pay strict attention to the setup instructions at the beginning of the prompt and the summary at the end, but completely overlook the critical technical instruction hidden on page 243.</li></ul><h4>C. Cost and Speed (The Luxury Live Tandoor Counter)</h4><p>Every token you send to an LLM provider (input tokens) and every token it writes back (output tokens) costs real money. Furthermore, processing millions of words takes time, drastically increasing API response latency.</p><ul><li><strong>The Analogy:</strong> Imagine you are sitting at home at 5 PM and feel like eating a single piece of Samosa as an evening snack.</li><li>Instead of walking to the local sweet shop, you call a high-end luxury catering company and request them to set up a full, live tandoor kitchen in your backyard with five professional chefs, 20kg of premium coal, and massive crates of raw ingredients. You will wait four hours for them to fire up the tandoor (high latency), and you will be handed a massive invoice for Rs. 25,000 (exorbitant cost) just to eat a single Rs. 15 samosa.</li><li><strong>The Reality:</strong> Passing an entire 300,000-word document repository to an LLM just to answer a simple, single question like <em>“What is our company’s late-mark policy?”</em> is exactly like hiring that luxury catering crew. You end up paying massive processing fees and waiting several seconds for a response when you only needed to send the model a single paragraph of relevant context.</li></ul><h4>The Solution: Chunking (Bite-Sized Portion Control)</h4><p>Instead of serving your wedding guests a giant, raw 10kg sack of flour and a whole block of paneer, you cut the paneer into small cubes, roll the flour into fresh rotis, and serve bite-sized <strong>Paneer Tikka</strong>.</p><p>In RAG, we slice our massive documents into smaller, coherent text blocks called <strong>chunks</strong> (e.g., 500 characters with a 100-character overlap to preserve semantic continuity). We generate embeddings for these individual chunks, upload them to Pinecone, and retrieve <em>only</em> the top-3 or top-5 most relevant slices (e.g., the exact paragraphs detailing the late-mark policy) to feed into the prompt context.</p><h3>7. Metadata Filtering (The Veg/Non-Veg Filter)</h3><p>Imagine you are at an Indian wedding buffet. You want to eat paneer, so you start scanning the dishes. However, to save time and ensure you don’t accidentally look at a chicken dish, you only scan the section of the buffet table marked with the <strong>green vegetarian dot</strong> (the metadata tag).</p><p>If your RAG database contains documents from 10 different clients, you don’t want a user from <em>Client A</em> accidentally retrieving sensitive data from <em>Client B</em>.</p><p>To solve this, we tag every vector with <strong>metadata</strong> (e.g., clientId: &quot;A&quot;, department: &quot;HR&quot;). Before we run a similarity search, we apply a hard metadata filter. The database instantly ignores all vectors that do not match the filter, saving computational power and guaranteeing absolute data isolation.</p><h3>Part 2: The Complete RAG Lifecycle</h3><p>Now let’s trace exactly how a query travels through these concepts in a single, continuous journey before we examine our .NET architecture:</p><pre>[ User Input: &quot;How is appraisal evaluated?&quot; ]<br>                  |<br>                  v<br>       +--------------------+<br>       | 1. Metadata Filter | ---&gt; &quot;Filter for department = HR&quot;<br>       +--------------------+<br>                  |<br>                  v<br>       +--------------------+<br>       | 2. Vectorization   | ---&gt; Call text-embedding-3-small to get 512-dim vector<br>       +--------------------+<br>                  |<br>                  v<br>       +--------------------+<br>       | 3. Query DB        | ---&gt; Perform Cosine Similarity in Pinecone<br>       +--------------------+<br>                  |<br>                  v<br>       +--------------------+<br>       | 4. Fetch Chunks    | ---&gt; Pull top-K text chunks with citations<br>       +--------------------+<br>                  |<br>                  v<br>       +--------------------+<br>       | 5. Context Stuffing| ---&gt; Inject chunks into Agent Prompt<br>       +--------------------+<br>                  |<br>                  v<br>       +--------------------+<br>       | 6. Generation      | ---&gt; gpt-4o-mini generates the grounded answer<br>       +--------------------+</pre><h3>Part 3: The Production-Grade .NET Architecture</h3><p>To build a real-world, enterprise-ready application, we must map this logical flow to high-performance, resilient software engineering patterns. Here is the blueprint of our proof-of-concept (POC) stack:</p><pre>       +---------------------------------------------+<br>       |           1. React Frontend (Vite)          |<br>       |             [React UI View (App.jsx)]       |<br>       +----------------------|----------------------+<br>                              | Relative Fetch Queries<br>                              v<br>       +---------------------------------------------+<br>       |           2. Development Gateway            |<br>       |      [Vite Dev Server Reverse Proxy (/api)] |<br>       +----------------------|----------------------+<br>                              | Proxy Redirect (Port 61622)<br>                              v<br> +-------------------------------------------------------------------+<br> |                    3. Dedicated C# Web API Backend                |<br> |                                                                   |<br> |  +-----------------------+              +----------------------+  |<br> |  |    Minimal Endpoints  |-------------&gt;|  AWS S3 Bucket       |  |<br> |  |      (Program.cs)     |              | (Stateless Storage)  |  |<br> |  +-----------|-----------+              +-----------|----------+  |<br> |              |                                      |             |<br> |              |                                      | S3 Event<br> |              v                                      v             |<br> |  +-----------------------+              +----------------------+  |<br> |  |    Microsoft Agent    |              |  Amazon EventBridge  |  |<br> |  |   Runtime (AIAgent)   |              +-----------|----------+  |<br> |  +-----------|-----------+                          |             |<br> |              |                                      | Trigger     |<br> |              v                                      v             |<br> |  +-----------------------+              +----------------------+  |<br> |  |   In-Memory Stores    |              | AWS ECS Task (Quartz)|  |<br> |  |      (Stores.cs)      |              | (FileIngestionJob.cs)|  |<br> |  +-----------------------+              +-----------|----------+  |<br> +-----------------------------------------------------|-------------+<br>                                                       |<br>        +----------------------------------------------+------+<br>        |                                                     |<br>        v                                                     v<br>+-----------------------------+                 +-----------------------------+<br>|    4. Data &amp; Vector Storage |                 |  5. OpenAI Cognitive Serv.  |<br>|                             |                 |                             |<br>|  [Pinecone Vector Database] |                 |   [gpt-4o-mini]             |<br>|  [AWS S3 Document Storage]  |                 |   [text-embedding-3-small]  |<br>+-----------------------------+                 +-----------------------------+</pre><h3>File Walkthrough: Implementation Code of the POC</h3><p>Rather than talking about abstract components, let’s open the hood and look at the exact files running this architecture.</p><h3>Layer 1: Asynchronous Ingestion &amp; Document Processing</h3><p>The ingestion pipeline handles reading files (PDFs, Word files, text docs), chunking them, calling the OpenAI embeddings client, and upserting the multidimensional floating points directly to Pinecone.</p><h4>FileReader.cs (Chunking and Parsing)</h4><p>First, we need a service to read files and divide them into clean chunks while tracking metadata like page numbers.</p><pre>using UglyToad.PdfPig;<br>using System.Text;<br>using System.IO.Compression;<br>using System.Xml.Linq;<br><br>public class FileChunkingService<br>{<br>    public List&lt;TextChunk&gt; ReadAndChunkFile(<br>        string filePath,<br>        int chunkSize = 1000,<br>        int overlap = 200)<br>    {<br>        var extension = Path.GetExtension(filePath).ToLowerInvariant();<br>        if (extension == &quot;.pdf&quot;)<br>        {<br>            return ReadAndChunkPdf(filePath, chunkSize, overlap);<br>        }<br>        else if (extension == &quot;.docx&quot;)<br>        {<br>            return ReadAndChunkDocx(filePath, chunkSize, overlap);<br>        }<br>        else<br>        {<br>            return ReadAndChunkPlainText(filePath, chunkSize, overlap);<br>        }<br>    }<br>    private List&lt;TextChunk&gt; ReadAndChunkPdf(string filePath, int chunkSize, int overlap)<br>    {<br>        var chunks = new List&lt;TextChunk&gt;();<br>        using var document = PdfDocument.Open(filePath);<br>        int globalChunkIndex = 0;<br>        foreach (var page in document.GetPages())<br>        {<br>            string pageText = page.Text;<br>            var pageChunks = ChunkText(pageText, chunkSize, overlap, page.Number, ref globalChunkIndex);<br>            chunks.AddRange(pageChunks);<br>        }<br>        return chunks;<br>    }<br>    private List&lt;TextChunk&gt; ReadAndChunkDocx(string filePath, int chunkSize, int overlap)<br>    {<br>        string text = ExtractTextFromDocx(filePath);<br>        int globalChunkIndex = 0;<br>        return ChunkText(text, chunkSize, overlap, 1, ref globalChunkIndex);<br>    }<br>    private List&lt;TextChunk&gt; ReadAndChunkPlainText(string filePath, int chunkSize, int overlap)<br>    {<br>        string text = File.ReadAllText(filePath);<br>        int globalChunkIndex = 0;<br>        return ChunkText(text, chunkSize, overlap, 1, ref globalChunkIndex);<br>    }<br>    private string ExtractTextFromDocx(string filePath)<br>    {<br>        try<br>        {<br>            using var fileStream = File.OpenRead(filePath);<br>            using var archive = new ZipArchive(fileStream);<br>            var entry = archive.GetEntry(&quot;word/document.xml&quot;);<br>            if (entry == null) return string.Empty;<br>            using var entryStream = entry.Open();<br>            var doc = XDocument.Load(entryStream);<br>            XNamespace w = &quot;[http://schemas.openxmlformats.org/wordprocessingml/2006/main](http://schemas.openxmlformats.org/wordprocessingml/2006/main)&quot;;<br>            <br>            var sb = new StringBuilder();<br>            foreach (var paragraph in doc.Descendants(w + &quot;p&quot;))<br>            {<br>                var textElements = paragraph.Descendants(w + &quot;t&quot;);<br>                foreach (var text in textElements)<br>                {<br>                    sb.Append(text.Value);<br>                }<br>                sb.AppendLine();<br>            }<br>            return sb.ToString();<br>        }<br>        catch (Exception ex)<br>        {<br>            Console.WriteLine($&quot;Error reading docx: {ex.Message}&quot;);<br>            return string.Empty;<br>        }<br>    }<br>    private List&lt;TextChunk&gt; ChunkText(string text, int chunkSize, int overlap, int pageNumber, ref int chunkIndex)<br>    {<br>        var chunks = new List&lt;TextChunk&gt;();<br>        if (string.IsNullOrWhiteSpace(text)) return chunks;<br>        int index = 0;<br>        while (index &lt; text.Length)<br>        {<br>            int length = Math.Min(chunkSize, text.Length - index);<br>            string chunkContent = text.Substring(index, length);<br>            chunks.Add(new TextChunk<br>            {<br>                ChunkIndex = chunkIndex++,<br>                Content = chunkContent,<br>                PageNumber = pageNumber,<br>                Metadata = new Dictionary&lt;string, string&gt; { { &quot;PageNumber&quot;, pageNumber.ToString() } }<br>            });<br>            index += chunkSize - overlap;<br>        }<br>        return chunks;<br>    }<br>}</pre><h4>Embeddings.cs (Using the OpenAI Embedding Client)</h4><p>This helper takes raw text strings and converts them to floating-point vectors using OpenAI’s text-embedding-3-small model.</p><pre>using System;<br>using System.Collections.Generic;<br>using System.Linq;<br>using OpenAI.Embeddings;<br>using Pinecone;<br><br>namespace MSAgentFrameworkRAG<br>{<br>    public static class EmbeddingsHelper<br>    {<br>        public static List&lt;(string Id, float[] Values, Pinecone.Metadata Metadata)&gt; CreateVectors&lt;T&gt;(<br>            using System.Collections.Generic.IEnumerable&lt;T&gt; items,<br>            Func&lt;T, string&gt; idSelector,<br>            Func&lt;T, string&gt; contentSelector,<br>            string apiKey,<br>            EmbeddingGenerationOptions? options = null,<br>            string model = &quot;text-embedding-3-small&quot;,<br>            Func&lt;T, Pinecone.Metadata&gt;? metadataBuilder = null)<br>        {<br>            var list = items.ToList();<br>            var embeddingClient = new EmbeddingClient(model, apiKey);<br>            var contents = list.Select(contentSelector).ToList();<br>            // Calling official OpenAI SDK client to get the float embeddings<br>            OpenAIEmbeddingCollection embeddings = embeddingClient.GenerateEmbeddings(contents, options).Value;<br>            var vectors = new List&lt;(string Id, float[] Values, Pinecone.Metadata Metadata)&gt;();<br>            foreach (var embedding in embeddings)<br>            {<br>                var idx = embedding.Index;<br>                var item = list[idx];<br>                float[] values = embedding.ToFloats().ToArray();<br>                Pinecone.Metadata metadata;<br>                if (metadataBuilder != null)<br>                {<br>                    metadata = metadataBuilder(item);<br>                }<br>                else<br>                {<br>                    metadata = new Pinecone.Metadata();<br>                    metadata[&quot;id&quot;] = new Pinecone.MetadataValue(idSelector(item));<br>                    metadata[&quot;content&quot;] = new Pinecone.MetadataValue(contentSelector(item));<br>                }<br>                vectors.Add((idSelector(item), values, metadata));<br>            }<br>            return vectors;<br>        }<br>    }<br>}</pre><h4>FileIngestionJob.cs (Quartz.NET Background Worker Task)</h4><p>When triggered, this background job processes documents asynchronously. It protects your web server’s ThreadPool from locking up during CPU-bound vector calculations.</p><pre>using System;<br>using System.IO;<br>using System.Linq;<br>using System.Threading.Tasks;<br>using OpenAI.Embeddings;<br>using Pinecone;<br>using Quartz;<br><br>namespace MSAgentFrameworkRAG<br>{<br>    [DisallowConcurrentExecution]<br>    public class FileIngestionJob : IJob<br>    {<br>        private readonly DocumentStore _documentStore;<br>        private readonly FileChunkingService _chunkingService = new();<br>        public FileIngestionJob(DocumentStore documentStore)<br>        {<br>            _documentStore = documentStore ?? throw new ArgumentNullException(nameof(documentStore));<br>        }<br>        public async Task Execute(IJobExecutionContext context)<br>        {<br>            var dataMap = context.MergedJobDataMap;<br>            var documentId = dataMap.GetString(&quot;documentId&quot;) ?? string.Empty;<br>            var filePath = dataMap.GetString(&quot;filePath&quot;) ?? string.Empty;<br>            var fileName = dataMap.GetString(&quot;fileName&quot;) ?? string.Empty;<br>            var openAIApiKey = dataMap.GetString(&quot;openAIApiKey&quot;) ?? string.Empty;<br>            var pineconeApiKey = dataMap.GetString(&quot;pineconeApiKey&quot;) ?? string.Empty;<br>            var indexName = dataMap.GetString(&quot;indexName&quot;) ?? &quot;financialknowledgerepo&quot;;<br>            var embeddingModel = dataMap.GetString(&quot;embeddingModel&quot;) ?? &quot;text-embedding-3-small&quot;;<br>            Console.WriteLine($&quot;[Quartz Ingestion] Processing document &#39;{fileName}&#39; ({documentId}) from &#39;{filePath}&#39;...&quot;);<br>            var doc = _documentStore.Get(documentId);<br>            if (doc == null)<br>            {<br>                Console.WriteLine($&quot;[Quartz Ingestion] Document {documentId} not found in store.&quot;);<br>                return;<br>            }<br>            try<br>            {<br>                doc.Status = &quot;Processing&quot;;<br>                _documentStore.AddOrUpdate(doc);<br>                // 1. Chunk the file<br>                var chunks = _chunkingService.ReadAndChunkFile(filePath, chunkSize: 3000, overlap: 500);<br>                Console.WriteLine($&quot;[Quartz Ingestion] Split file into {chunks.Count} chunks.&quot;);<br>                if (chunks.Count &gt; 0)<br>                {<br>                    // 2. Generate embeddings via our helper using text-embedding-3-small (512 dimensions)<br>                    var embeddingOptions = new EmbeddingGenerationOptions { Dimensions = 512 };<br>                    var vectorsToUpsert = EmbeddingsHelper.CreateVectors(<br>                        chunks,<br>                        idSelector: c =&gt; $&quot;{documentId}_chunk_{c.ChunkIndex}&quot;,<br>                        contentSelector: c =&gt; c.Content,<br>                        apiKey: openAIApiKey,<br>                        options: embeddingOptions,<br>                        model: embeddingModel,<br>                        metadataBuilder: c =&gt;<br>                        {<br>                            var md = new Metadata();<br>                            md[&quot;chunkIndex&quot;] = new MetadataValue(c.ChunkIndex.ToString());<br>                            md[&quot;pageNumber&quot;] = new MetadataValue(c.PageNumber.ToString());<br>                            md[&quot;Content&quot;] = new MetadataValue(c.Content);<br>                            md[&quot;documentId&quot;] = new MetadataValue(documentId);<br>                            md[&quot;sourceName&quot;] = new MetadataValue(fileName);<br>                            md[&quot;sourceLink&quot;] = new MetadataValue(filePath);<br>                            return md;<br>                        });<br>                    var vectorsForUpsert = vectorsToUpsert.Select(v =&gt; new Vector<br>                    {<br>                        Id = v.Id,<br>                        Values = new ReadOnlyMemory&lt;float&gt;(v.Values),<br>                        Metadata = v.Metadata<br>                    }).ToList();<br>                    // 3. Connect to Pinecone and upsert vectors<br>                    var pinecone = new PineconeClient(pineconeApiKey);<br>                    var index = pinecone.Index(indexName);<br>                    var upsertRequest = new UpsertRequest { Vectors = vectorsForUpsert };<br>                    Console.WriteLine($&quot;[Quartz Ingestion] Upserting vectors to Pinecone index &#39;{indexName}&#39;...&quot;);<br>                    await index.UpsertAsync(upsertRequest).ConfigureAwait(false);<br>                }<br>                // 4. Mark as indexed<br>                doc.Status = &quot;Indexed&quot;;<br>                _documentStore.AddOrUpdate(doc);<br>                Console.WriteLine($&quot;[Quartz Ingestion] Ingestion complete for &#39;{fileName}&#39; ({documentId}).&quot;);<br>            }<br>            catch (Exception ex)<br>            {<br>                Console.WriteLine($&quot;[Quartz Ingestion] Error indexing document: {ex}&quot;);<br>                doc.Status = &quot;Failed&quot;;<br>                doc.ErrorMessage = ex.Message;<br>                _documentStore.AddOrUpdate(doc);<br>            }<br>        }<br>    }<br>}</pre><h3>Layer 2: Retrieval &amp; Chat Pipeline</h3><p>The chat pipeline needs to receive a user query, convert it into an embedding vector, look for the most similar chunks in Pinecone (applying metadata filters if necessary), and feed those context blocks to our Agent.</p><h4>SearchAdapter.cs (Vector Search to Microsoft Agent Provider Bridge)</h4><p>This adapter is a crucial bridge. It handles the vector similarity search in Pinecone and adapts the results into TextSearchProvider.TextSearchResult format, which the Microsoft Agent Framework uses to construct grounding prompts.</p><pre>using Microsoft.Agents.AI;<br>using OpenAI.Embeddings;<br>using Pinecone;<br><br>namespace MSAgentFrameworkRAG;<br>public sealed class PineconeTextSearchAdapter<br>{<br>    private readonly PineconeClient _pinecone;<br>    private readonly string _indexName;<br>    private readonly string _openAIApiKey;<br>    private readonly string _embeddingModel;<br>    private readonly EmbeddingGenerationOptions? _embeddingOptions;<br>    private readonly Metadata? _filter;<br>    private readonly int _topK;<br>    public PineconeTextSearchAdapter(<br>        PineconeClient pinecone,<br>        string indexName,<br>        string openAIApiKey,<br>        EmbeddingGenerationOptions? embeddingOptions = null,<br>        Metadata? filter = null,<br>        string embeddingModel = &quot;text-embedding-3-small&quot;,<br>        int topK = 5)<br>    {<br>        _pinecone = pinecone ?? throw new ArgumentNullException(nameof(pinecone));<br>        _indexName = string.IsNullOrWhiteSpace(indexName) ? throw new ArgumentException(&quot;Index name is required.&quot;, nameof(indexName)) : indexName;<br>        _openAIApiKey = string.IsNullOrWhiteSpace(openAIApiKey) ? throw new ArgumentException(&quot;OpenAI API key is required.&quot;, nameof(openAIApiKey)) : openAIApiKey;<br>        _embeddingOptions = embeddingOptions;<br>        _filter = filter;<br>        _embeddingModel = embeddingModel;<br>        _topK = topK;<br>    }<br>    public async Task&lt;IEnumerable&lt;TextSearchProvider.TextSearchResult&gt;&gt; SearchAsync(<br>        string query,<br>        CancellationToken cancellationToken)<br>    {<br>        if (string.IsNullOrWhiteSpace(query)) return [];<br>        // Vectorize incoming natural query string<br>        var vectors = EmbeddingsHelper.CreateVectors(<br>            [query],<br>            idSelector: _ =&gt; &quot;query&quot;,<br>            contentSelector: q =&gt; q,<br>            apiKey: _openAIApiKey,<br>            options: _embeddingOptions,<br>            model: _embeddingModel);<br>        if (vectors.Count == 0) return [];<br>        // Query Pinecone Index using the query&#39;s vector embeddings<br>        var queryResponse = await _pinecone.Index(_indexName).QueryAsync(<br>            new QueryRequest<br>            {<br>                Vector = vectors[0].Values,<br>                TopK = (uint)_topK,<br>                IncludeMetadata = true,<br>                Filter = _filter<br>            }).ConfigureAwait(false);<br>        cancellationToken.ThrowIfCancellationRequested();<br>        return (queryResponse.Matches ?? []).Select(match =&gt;<br>        {<br>            var metadata = match.Metadata ?? [];<br>            var text = GetMetadataValue(metadata, &quot;Content&quot;)<br>                ?? GetMetadataValue(metadata, &quot;content&quot;)<br>                ?? string.Empty;<br>            var chunkIndex = GetMetadataValue(metadata, &quot;chunkIndex&quot;);<br>            var pageNumber = GetMetadataValue(metadata, &quot;pageNumber&quot;);<br>            var sourceName = GetMetadataValue(metadata, &quot;sourceName&quot;)<br>                ?? BuildSourceName(match.Id, chunkIndex, pageNumber);<br>            var sourceLink = GetMetadataValue(metadata, &quot;sourceLink&quot;);<br>            return new TextSearchProvider.TextSearchResult<br>            {<br>                SourceName = sourceName,<br>                SourceLink = sourceLink,<br>                Text = text,<br>                RawRepresentation = match<br>            };<br>        });<br>    }<br>    private static string BuildSourceName(string id, string? chunkIndex, string? pageNumber)<br>    {<br>        var sourceName = string.IsNullOrWhiteSpace(id) ? &quot;Pinecone search result&quot; : $&quot;Pinecone chunk {id}&quot;;<br>        if (!string.IsNullOrWhiteSpace(pageNumber)) sourceName += $&quot; page {pageNumber}&quot;;<br>        else if (!string.IsNullOrWhiteSpace(chunkIndex)) sourceName += $&quot; chunk {chunkIndex}&quot;;<br>        return sourceName;<br>    }<br>    private static string? GetMetadataValue(Metadata metadata, string key)<br>    {<br>        return metadata.TryGetValue(key, out var value) ? value?.ToString() : null;<br>    }<br>}</pre><h4>Stores.cs (Thread-Safe In-Memory State &amp; Conversation Storage)</h4><p>Since HTTP endpoints are stateless, we use thread-safe dictionaries to track conversation metadata and manage the active stateful AgentSession.</p><pre>using System;<br>using System.Collections.Concurrent;<br>using System.Collections.Generic;<br>using System.Linq;<br>using System.Threading.Tasks;<br>using Microsoft.Agents.AI;<br><br>namespace MSAgentFrameworkRAG<br>{<br>    public class DocumentStore<br>    {<br>        private readonly ConcurrentDictionary&lt;string, UploadedDocument&gt; _documents = new();<br>        public void AddOrUpdate(UploadedDocument doc)<br>        {<br>            _documents[doc.Id] = doc;<br>        }<br>        public UploadedDocument? Get(string id)<br>        {<br>            return _documents.TryGetValue(id, out var doc) ? doc : null;<br>        }<br>        public List&lt;UploadedDocument&gt; GetAll()<br>        {<br>            return _documents.Values.OrderByDescending(d =&gt; d.UploadedAt).ToList();<br>        }<br>    }<br>    public class ConversationManager<br>    {<br>        private readonly ConcurrentDictionary&lt;string, Conversation&gt; _conversations = new();<br>        private readonly ConcurrentDictionary&lt;string, AgentSession&gt; _sessions = new();<br>        public List&lt;Conversation&gt; GetAll()<br>        {<br>            return _conversations.Values.OrderByDescending(c =&gt; c.CreatedAt).ToList();<br>        }<br>        public Conversation? Get(string id)<br>        {<br>            return _conversations.TryGetValue(id, out var conversation) ? conversation : null;<br>        }<br>        public Conversation Create(string? name = null)<br>        {<br>            var id = Guid.NewGuid().ToString(&quot;N&quot;);<br>            var conversation = new Conversation<br>            {<br>                Id = id,<br>                Name = string.IsNullOrWhiteSpace(name) ? $&quot;Conversation {DateTime.Now:HH:mm:ss}&quot; : name,<br>                CreatedAt = DateTime.UtcNow<br>            };<br>            _conversations[id] = conversation;<br>            return conversation;<br>        }<br>        public void AddMessage(string conversationId, ChatMessageInfo msg)<br>        {<br>            if (_conversations.TryGetValue(conversationId, out var conversation))<br>            {<br>                conversation.Messages.Add(msg);<br>            }<br>        }<br>        public async Task&lt;AgentSession&gt; GetOrCreateSessionAsync(string conversationId, AIAgent agent)<br>        {<br>            if (_sessions.TryGetValue(conversationId, out var session))<br>            {<br>                return session;<br>            }<br>            // Establish stateful session context using the Microsoft Agent Framework<br>            var newSession = await agent.CreateSessionAsync().ConfigureAwait(false);<br>            _sessions[conversationId] = newSession;<br>            if (!_conversations.ContainsKey(conversationId))<br>            {<br>                Create();<br>            }<br>            return newSession;<br>        }<br>    }<br>}</pre><h3>Layer 3: Orchestration API &amp; Coordination Loop</h3><p>Our API entry point exposes Minimal Endpoints. It handles file staging, coordinates Quartz background workers, manages chat memory, and invokes the intelligent agent runtime loop.</p><h4>Program.cs (Web API &amp; Orchestration Engine)</h4><p>This orchestrator ties everything together. It coordinates the initial file staging, schedules background processing with Quartz, and spins up stateful AIAgent instances using standard OpenAI clients.</p><pre>using Microsoft.Agents.AI;<br>using MSAgentFrameworkRAG;<br>using OpenAI.Chat;<br>using OpenAI.Embeddings;<br>using Pinecone;<br>using Quartz;<br>using System.Text.Json;<br><br>var builder = WebApplication.CreateBuilder(args);<br>// Config parameters (retained from configuration manager)<br>string pineconeApiKey = &quot;pcsk_your_pinecone_api_key_here&quot;;<br>string openAIApiKey = &quot;sk_your_openai_key_here&quot;;<br>string indexName = &quot;your_pinecone_index_name&quot;;<br>string chatModel = &quot;gpt-5-mini&quot;;<br>string embeddingModel = &quot;text-embedding-3-small&quot;;<br>// Register custom thread-safe DI stores<br>builder.Services.AddSingleton&lt;DocumentStore&gt;();<br>builder.Services.AddSingleton&lt;ConversationManager&gt;();<br>// Register Quartz.NET<br>builder.Services.AddQuartz(q =&gt;<br>{<br>    q.UseMicrosoftDependencyInjectionJobFactory();<br>});<br>builder.Services.AddQuartzHostedService(options =&gt; options.WaitForJobsToComplete = true);<br>// Configure CORS<br>builder.Services.AddCors(options =&gt;<br>{<br>    options.AddPolicy(&quot;AllowAll&quot;, p =&gt; p.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());<br>});<br>var app = builder.Build();<br>app.UseCors(&quot;AllowAll&quot;);<br>// Create uploads folder inside wwwroot<br>var uploadsDir = Path.Combine(app.Environment.WebRootPath ?? Path.Combine(Directory.GetCurrentDirectory(), &quot;wwwroot&quot;), &quot;uploads&quot;);<br>if (!Directory.Exists(uploadsDir))<br>{<br>    Directory.CreateDirectory(uploadsDir);<br>}<br>// ----------------- API ENDPOINTS -----------------<br>app.MapGet(&quot;/api/documents&quot;, (DocumentStore store) =&gt; Results.Ok(store.GetAll()));<br>app.MapGet(&quot;/api/conversations&quot;, (ConversationManager manager) =&gt; Results.Ok(manager.GetAll()));<br>app.MapPost(&quot;/api/conversations/new&quot;, (ConversationManager manager, JsonElement body) =&gt;<br>{<br>    string? name = null;<br>    if (body.ValueKind == JsonValueKind.Object &amp;&amp; body.TryGetProperty(&quot;name&quot;, out var prop))<br>    {<br>        name = prop.GetString();<br>    }<br>    var conversation = manager.Create(name);<br>    return Results.Ok(conversation);<br>});<br>app.MapGet(&quot;/api/conversations/{id}&quot;, (string id, ConversationManager manager) =&gt;<br>{<br>    var convo = manager.Get(id);<br>    return convo == null ? Results.NotFound() : Results.Ok(convo);<br>});<br>// Endpoint 1: File Upload Handler (Staging &amp; Quartz Trigger)<br>app.MapPost(&quot;/api/upload&quot;, async (IFormFile file, DocumentStore store, ISchedulerFactory schedulerFactory) =&gt;<br>{<br>    if (file == null || file.Length == 0) return Results.BadRequest(&quot;No file uploaded.&quot;);<br>    var documentId = Guid.NewGuid().ToString(&quot;N&quot;);<br>    var fileName = Path.GetFileName(file.FileName);<br>    var safeFileName = $&quot;{documentId}_{fileName}&quot;;<br>    var filePath = Path.Combine(uploadsDir, safeFileName);<br>    using (var stream = new FileStream(filePath, FileMode.Create))<br>    {<br>        await file.CopyToAsync(stream);<br>    }<br>    var doc = new UploadedDocument<br>    {<br>        Id = documentId,<br>        FileName = fileName,<br>        Status = &quot;Pending&quot;,<br>        UploadedAt = DateTime.UtcNow<br>    };<br>    store.AddOrUpdate(doc);<br>    // Schedule background processing off-thread via Quartz<br>    var scheduler = await schedulerFactory.GetScheduler();<br>    <br>    var job = JobBuilder.Create&lt;FileIngestionJob&gt;()<br>        .WithIdentity($&quot;Job_{documentId}&quot;, &quot;IngestionGroup&quot;)<br>        .UsingJobData(&quot;documentId&quot;, documentId)<br>        .UsingJobData(&quot;filePath&quot;, filePath)<br>        .UsingJobData(&quot;fileName&quot;, fileName)<br>        .UsingJobData(&quot;openAIApiKey&quot;, openAIApiKey)<br>        .UsingJobData(&quot;pineconeApiKey&quot;, pineconeApiKey)<br>        .UsingJobData(&quot;indexName&quot;, indexName)<br>        .UsingJobData(&quot;embeddingModel&quot;, embeddingModel)<br>        .Build();<br>    var trigger = TriggerBuilder.Create()<br>        .WithIdentity($&quot;Trigger_{documentId}&quot;, &quot;IngestionGroup&quot;)<br>        .StartNow()<br>        .Build();<br>    await scheduler.ScheduleJob(job, trigger);<br>    return Results.Ok(doc); // Returns 200 immediately back to UI<br>}).DisableAntiforgery();<br>// Endpoint 2: Conversational Agent Chat Route<br>app.MapPost(&quot;/api/chat&quot;, async (ChatRequest request, ConversationManager manager) =&gt;<br>{<br>    if (string.IsNullOrWhiteSpace(request.ConversationId)) return Results.BadRequest(&quot;ConversationId is required.&quot;);<br>    if (string.IsNullOrWhiteSpace(request.Message)) return Results.BadRequest(&quot;Message is required.&quot;);<br>    try<br>    {<br>        Console.WriteLine($&quot;[Chat API] Query: &#39;{request.Message}&#39; in Convo: &#39;{request.ConversationId}&#39;, Filter: &#39;{request.DocumentId}&#39;&quot;);<br>        var pinecone = new PineconeClient(pineconeApiKey);<br>        var embeddingOptions = new EmbeddingGenerationOptions { Dimensions = 512 };<br>        Metadata? filter = null;<br>        if (!string.IsNullOrEmpty(request.DocumentId))<br>        {<br>            filter = new Metadata { [&quot;documentId&quot;] = new MetadataValue(request.DocumentId) };<br>        }<br>        // Initialize our custom Search Adapter<br>        var searchAdapter = new PineconeTextSearchAdapter(<br>            pinecone,<br>            indexName,<br>            openAIApiKey,<br>            embeddingOptions: embeddingOptions,<br>            filter: filter,<br>            embeddingModel: embeddingModel,<br>            topK: 10);<br>        // Tell the framework&#39;s search provider to pull grounding context *before* invoking the LLM<br>        TextSearchProviderOptions textSearchOptions = new()<br>        {<br>            SearchTime = TextSearchProviderOptions.TextSearchBehavior.BeforeAIInvoke,<br>        };<br>        // Construct Chat Client and instantiate AIAgent<br>        ChatClient client = new(model: chatModel, apiKey: openAIApiKey);<br>        ChatClientAgentOptions chatClientAgentOptions = new()<br>        {<br>            ChatOptions = new()<br>            {<br>                Instructions = &quot;You are a helpful support specialist. Answer questions using the provided context and cite source documents.&quot;<br>            },<br>            Name = &quot;InsuranceSupportAgent&quot;,<br>            AIContextProviders = [new TextSearchProvider(searchAdapter.SearchAsync, textSearchOptions)]<br>        };<br>        AIAgent agent = client.AsAIAgent(chatClientAgentOptions);<br>        // Retrieve/Restore the stateful user session using the manager<br>        var session = await manager.GetOrCreateSessionAsync(request.ConversationId, agent).ConfigureAwait(false);<br>        // Run the agent statefully (short-term conversational memory handled automatically)<br>        var response = await agent.RunAsync(request.Message, session).ConfigureAwait(false);<br>        var responseText = response.Text;<br>        // Retrieve actual context hits for UI transparency<br>        var citationsList = new List&lt;SourceCitation&gt;();<br>        try<br>        {<br>            var searchResults = await searchAdapter.SearchAsync(request.Message, default).ConfigureAwait(false);<br>            foreach (var sr in searchResults)<br>            {<br>                citationsList.Add(new SourceCitation<br>                {<br>                    SourceName = sr.SourceName,<br>                    SourceLink = sr.SourceLink,<br>                    Text = sr.Text<br>                });<br>            }<br>        }<br>        catch (Exception ex)<br>        {<br>            Console.WriteLine($&quot;[Chat API] Error fetching citations: {ex.Message}&quot;);<br>        }<br>        var userMsg = new ChatMessageInfo { Sender = &quot;user&quot;, Text = request.Message, Timestamp = DateTime.UtcNow };<br>        var assistantMsg = new ChatMessageInfo<br>        {<br>            Sender = &quot;assistant&quot;,<br>            Text = responseText,<br>            Timestamp = DateTime.UtcNow,<br>            Citations = citationsList<br>        };<br>        manager.AddMessage(request.ConversationId, userMsg);<br>        manager.AddMessage(request.ConversationId, assistantMsg);<br>        return Results.Ok(new ChatResponse { ConversationId = request.ConversationId, Message = assistantMsg });<br>    }<br>    catch (Exception ex)<br>    {<br>        Console.WriteLine($&quot;[Chat API ERROR] Exception: {ex}&quot;);<br>        return Results.Json(new { error = ex.Message, details = ex.ToString() }, statusCode: 500);<br>    }<br>});<br>app.Run();</pre><h3>Part 4: Production Roadmap (Scaling from Local to Enterprise Cloud)</h3><p>While our POC is fully decoupled and ready for local workloads, production-scale enterprise architectures require a cloud-native scaling strategy. Let’s look at how to evolve this local setup into an enterprise AWS deployment.</p><pre>+------------------+         Upload          +---------------+<br>|    React App     |------------------------&gt;|   Amazon S3   |<br>+------------------+                         +-------+-------+<br>                                                     | S3 Event Notification<br>                                                     v<br>+------------------+      Poll Message       +---------------+<br>| Quartz Worker    |&lt;------------------------|  Amazon SQS   |<br>| (On ECS Fargate) |                         +---------------+<br>+--------+---------+<br>         |<br>         | Pull S3 stream, Chunk, Embed<br>         v<br>+--------+---------+<br>|  Pinecone DB     |<br>+------------------+</pre><h3>1. Moving from Local Staging (wwwroot/uploads) to Amazon S3</h3><p>In production, your API runs on multiple container instances behind an Application Load Balancer. Storing uploads on a local folder is a major bottleneck — if <em>Instance A</em> handles the file upload, <em>Instance B</em> won’t have access to it when processing.</p><ul><li><strong>The Production Fix:</strong> Upload document streams directly to an <strong>S3 Bucket</strong> rather than writing to disk. S3 provides a centralized, durable, and highly scalable storage solution.</li></ul><h3>2. Replacing In-Process Triggers with EventBridge and SQS</h3><p>Instead of calling the local Quartz scheduler directly from the API container, you can decouple ingestion workflows with an event-driven queue:</p><ol><li>When a file lands in <strong>Amazon S3</strong>, it fires an ObjectCreated event notification.</li><li><strong>Amazon EventBridge</strong> routes this event directly to an <strong>Amazon SQS Queue</strong>.</li><li>Containerized Quartz.NET workers deployed on <strong>AWS ECS Fargate</strong> poll the SQS queue, pulling down the file stream from S3 and executing the chunking/embedding pipeline in total isolation.</li></ol><p>This architecture guarantees that even if 10,000 files are uploaded at once, your chat API instances stay at 0% processing load, keeping the client conversation response fast and uninterrupted.</p><p>By organizing our application into this decoupled background-worker architecture, we move away from fragile console prototypes and enter the realm of resilient enterprise engineering. We’ve separated heavy ingestion tasks from the user-facing thread using Quartz.NET, resolved local CORS issues using Vite’s reverse proxying, and built an intelligent agentic conversational pipeline using Pinecone and the Microsoft Agent Framework.</p><p>Enjoyed this architectural breakdown? Let me know in the comments below if you have any questions about managing background schedulers in .NET or configuring Pinecone indices!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=841b61232ae6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>