<?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 Shekharsomani on Medium]]></title>
        <description><![CDATA[Stories by Shekharsomani on Medium]]></description>
        <link>https://medium.com/@shekharsomani98?source=rss-2920c9c9b63b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*vwFHor6yiMlzcT7kdvI8-w.jpeg</url>
            <title>Stories by Shekharsomani on Medium</title>
            <link>https://medium.com/@shekharsomani98?source=rss-2920c9c9b63b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 04:56:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shekharsomani98/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[“Voice or exit: what Vibhishana’s choice teaches about dissent”]]></title>
            <link>https://medium.com/@shekharsomani98/voice-or-exit-what-vibhishanas-choice-teaches-about-dissent-26f047d95f8e?source=rss-2920c9c9b63b------2</link>
            <guid isPermaLink="false">https://medium.com/p/26f047d95f8e</guid>
            <category><![CDATA[career-advice]]></category>
            <category><![CDATA[indian-mythology]]></category>
            <category><![CDATA[game-theory]]></category>
            <category><![CDATA[leadership]]></category>
            <category><![CDATA[decision-making]]></category>
            <dc:creator><![CDATA[Shekharsomani]]></dc:creator>
            <pubDate>Thu, 08 Oct 2026 00:00:09 GMT</pubDate>
            <atom:updated>2026-10-26T05:31:01.521Z</atom:updated>
            <content:encoded><![CDATA[<p>For anyone who has advised a leader who would not listen: what the Ramayana’s Yuddha Kanda shows about speaking up, leaving, and what each costs.</p><p><em>For anyone who has advised a leader who would not listen: what the Ramayana’s Yuddha Kanda shows about speaking up, leaving, and what each costs.</em></p><p>The council hall in Lanka is loud. Ravana’s commanders have just risen with weapons in hand, flushed with anger. Their plan is simple: kill Rama, Lakshmana and Sugriva today, and be done with the monkey army that has come for Lanka.</p><p>One man in the room does not stand with them. Vibhishana, Ravana’s youngest brother, asks them to put the weapons down and sit. He folds his palms and begins to speak. He argues from strength and from consequence as much as from right. Rama is alert and hard to beat, he says. And what wrong had Rama ever done Ravana, that Ravana should carry off his wife? Give Sita back before the arrows start.</p><p>Ravana hears him out, dismisses the room, and walks into his own palace. That is the end of the first attempt.</p><p>Diwali is close, and many of us will retell the story of Rama’s return. We tell it from Rama’s side. This article is about the man who stood in Ravana’s hall, said the unwelcome thing more than once, and in the end left. I read it as a case study in an old question: when you are right, and the person in charge will not hear it, do you stay and keep talking, stay and keep quiet, or go?</p><h3>What the text says Vibhishana did</h3><p>I am working from Valmiki’s Sanskrit Ramayana, Yuddha Kanda, using K. M. K. Murthy’s English translation on valmikiramayan.net.</p><p>Vibhishana does not speak once. Over several scenes he tries different rooms and different arguments.</p><blockquote><em>न नः क्षमं वीर्यवता तेन धर्मानुवर्तिना । वैरं निरर्थकं कर्तुं दीयतामस्य मैथिली ॥</em></blockquote><blockquote>na naḥ kṣamaṃ vīryavatā tena dharmānuvartinā |<em> </em>vairaṃ nirarthakaṃ kartuṃ dīyatām asya maithilī ||</blockquote><blockquote><em>It does not suit us to make a pointless enemy of that powerful man who follows dharma. Let Maithili (Sita) be given back to him.</em></blockquote><ul><li><strong>The omens.</strong> He lists bad omens and urges Ravana to return Sita. Ravana turns a deaf ear and sends him away.</li><li><strong>The full assembly.</strong> There he describes the monkeys’ strength and the power of Rama’s arrows. Prahasta, the commander, answers that they have no fear of facing Rama. Indrajit, Ravana’s son, criticises him for underestimating Indrajit’s own strength. Vibhishana calls Indrajit immature and rash, and asks again that Sita be returned, with gifts.</li><li><strong>Ravana’s reply.</strong> Ravana finally answers him, and this is where voice ends.</li></ul><p>Later, when he reaches Rama’s camp, Vibhishana himself describes these attempts in one line: he “persuaded Ravana again and again” with different words and arguments (Murthy’s translation). He is not a man who spoke once and walked out.</p><h3>Why Ravana refused</h3><p>Ravana’s reply is the hinge. It is worth reading closely, because in it Ravana does not take up any of Vibhishana’s arguments.</p><p>He answers the person, not the argument. His first words are:</p><blockquote><em>वसेत्सह सपत्नेन क्रुद्धेनाशीविषेण च । न तु मित्रप्रवादेन संवसेच्छत्रुणा सह ॥</em></blockquote><blockquote>vaset saha sapatnena kruddhenāśīviṣeṇa ca |<em> </em>na tu mitrapravādena saṃvasec chatruṇā saha ||</blockquote><blockquote><em>“One can stay together with an enemy or even with a furious snake, but one cannot stay together with an adversary yet avowing himself as a friend.” (Murthy)</em></blockquote><p>Then comes a speech about how kinsmen always rejoice at each other’s calamities and are the most dangerous fear of all. He accuses Vibhishana of resenting his power. When Vibhishana’s warning is read as envy, no amount of evidence can get through.</p><p>My own reading, which the text supports but does not state: Ravana had three reasons to refuse that had nothing to do with Rama’s arrows.</p><ul><li><strong>He had already paid.</strong> Sita was in Lanka. Handing her back meant admitting the whole war was avoidable.</li><li><strong>The room rewarded agreement.</strong> The commanders in the council rose with weapons, not with questions. Vibhishana was the only dissent, which made his voice easy to isolate.</li><li><strong>The messenger was close.</strong> A brother, a rival heir. Ravana read the advice through that lens.</li></ul><p>Vibhishana had a verse for exactly this, and it is the line from the whole episode that I keep returning to:</p><blockquote><em>सुलभाः पुरुषा राजन् सततं प्रियवादिनः । अप्रियस्य तु पथ्यस्य वक्ता श्रोता च दुर्लभः ॥</em></blockquote><blockquote>sulabhāḥ puruṣā rājan satataṃ priyavādinaḥ |<em> </em>apriyasya tu pathyasya vaktā śrotā ca durlabhaḥ ||</blockquote><blockquote><em>In my paraphrase: people who always say pleasing things are easy to find, but one who speaks useful and unpleasing words, and one who will listen to them, are both rare.</em></blockquote><h3>The moment voice stopped working</h3><p>Here is what I find most careful in Valmiki’s telling. Ravana’s last words to him include a threat: if anyone else had spoken like this, he says, that person would be finished at this moment. Vibhishana does not storm out even then. He answers that an elder brother is like a father and deserves respect even when he is off the right path. He says he cannot ignore a man who is being destroyed, any more than one can ignore a burning house.</p><p>Then he leaves. My reading is that voice was allowed as long as it was only unwelcome. Once it became unsafe, the choice changed. Vibhishana rose into the air with four companions, said goodbye (“Be a happy person without me,” in Murthy’s rendering), and went to Rama.</p><p>In economics, Albert Hirschman called these choices <em>exit</em> and <em>voice</em>, and loyalty is what makes people choose voice first ( <em>Exit, Voice, and Loyalty</em>, 1970). Vibhishana is nearly a textbook case: loyal enough to try several times, and exit only after voice had become unsafe.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Iz2_pdM1AIXt_AYO.png" /></figure><h3>What leaving cost, and how Rama’s camp decided</h3><p>It would be easy to stop at the happy ending, with Vibhishana crowned. The text asks more of him first.</p><p>When he arrives at the shore, he lists what he gave up: his sons and his wife, then Lanka, friends and wealth. That reads to me like a signal the other side could not fake cheaply. It is also my interpretation, not Valmiki’s wording.</p><p>And Rama’s camp did not welcome him. Sugriva, the monkey king, tells Rama this is an enemy’s brother who has come into their camp, and compares the risk to an owl killing crows at night. The monkey chiefs are asked for their opinions and several are wary. Hanuman answers by reading the stranger carefully, his manner and his words, and finds no false note.</p><p>Rama’s own answer is among the most quoted passages in the epic:</p><blockquote><em>सकृदेव प्रपन्नाय तवास्मीति च याचते । अभयं सर्वभूतेभ्यो ददाम्येतद्व्रतं मम ॥</em></blockquote><blockquote>sakṛd eva prapannāya tavāsmīti ca yācate |<em> </em>abhayaṃ sarvabhūtebhyo dadāmy etad vrataṃ mama ||</blockquote><blockquote><em>“He who seeks refuge in me just once, saying ‘I am yours’, I shall give him safety against all beings. This is my solemn pledge.” (Murthy)</em></blockquote><p>He goes on to say the pledge holds for Vibhishana <em>or Ravana himself</em>. Vibhishana is consecrated king of the rakshasas by Lakshmana on the seashore, well before the war has been won. After Ravana’s death, he is installed in Lanka.</p><p>Notice what that does to the decision. Rama faced real uncertainty about one man and a real downside if he was wrong. My reading is that he answered with a standing rule, not a bet on this one person.</p><p>Then the cost comes home. After the war, Vibhishana stands over Ravana’s body and grieves. He asks Rama’s permission to perform the funeral rites, and Rama gives it in a line I think of often:</p><blockquote><em>मरणान्तानि वैराणि निर्वृत्तं नः प्रयोजनम् । क्रियतामस्य संस्कारो ममाप्येष यथा तव ॥</em></blockquote><blockquote>maraṇāntāni vairāṇi nirvṛttaṃ naḥ prayojanam |<em> </em>kriyatām asya saṃskāro mamāpy eṣa yathā tava ||</blockquote><blockquote><em>“Hostilities end with death. Our purpose has been accomplished. Let his funeral rites be performed. He is as much mine as yours.” (Murthy)</em></blockquote><p>The brother who left is still the brother who buries.</p><h3>Two brothers, two answers</h3><p>Valmiki also gives us a second brother who faced the same refusal and chose differently. Kumbhakarna, woken for war, scolds Ravana for ignoring the earlier advice of well-wishers like Vibhishana, and for neglecting the scriptures on a king’s duties. Then he promises to fight on Ravana’s side anyway.</p><p>As I read it, the epic does not rank them. They answered the same failure in different ways: one by leaving, one by staying loyal after having said his piece. That is the point I most want to keep. A decision under uncertainty is not graded by whether the leader eventually fell.</p><h3>What it means for a modern decision</h3><p>I am not going to use a case from my own workplace. Here is an invented one that anyone who has worked on a team will recognise.</p><p>A senior engineer sees that a launch date is going to be hit by cutting the testing that would catch a serious fault. She raises it in the planning meeting, quietly. The room is excited, the date was promised upward, and the lead hears her as someone who does not want the project to win. She raises it again in writing. She raises it a third time with data. Each time, the cost of being right goes up and the chance of being heard goes down.</p><p>Vibhishana’s story suggests a few questions to ask, none of them rules.</p><ol><li><strong>Has the message been heard, or just received?</strong> Ravana received it every time. He could not hear it from that speaker.</li><li><strong>Is the lead refusing the evidence, or the messenger?</strong> If it is the messenger, a different channel or messenger may carry the same facts, and that is a cheaper step than leaving.</li><li><strong>What does the next attempt cost?</strong> In Ravana’s reply the price of speaking rose from irritation to a threat. When voice becomes unsafe, it stops being a free option.</li><li><strong>If you leave, are you leaving or defecting?</strong> Vibhishana did both: he left Ravana and then fought for Rama. Many people only want the first, and the text shows the second is where the suspicion and the grief come from.</li><li><strong>What would you owe the person you left?</strong> Rama’s “hostilities end with death” is a statement about the limits of a conflict. It is also a reminder that the relationship outlasts the dispute.</li></ol><p>There is a harsher point as well. A common Hindi saying, <em>ghar ka bhedi Lanka dhaye</em> (“the insider who knows the secrets brings down Lanka”), makes Vibhishana shorthand for betrayal. That saying is folk speech, not Valmiki. It shows how the same act reads very differently depending on whose story you hear. If you leave, you do not get to choose the story that is told about you.</p><h3>Sources</h3><p>Valmiki Ramayana, Yuddha Kanda (vulgate text), with K. M. K. Murthy’s English translation, both on valmikiramayan.net. The Hindi saying is folk speech, not Valmiki. The interpretation is mine.</p><h3>One question to sit with</h3><p>Vibhishana tried in several rooms before he left, and Kumbhakarna stayed after saying his piece. If you were the one in that hall, what would you need to see before you decided that voice had stopped working?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ebntB9SLfdX8vWPX.png" /></figure><p><em>Originally published at </em><a href="https://blog.givn.in/posts/vibhishana-voice-or-exit/medium/"><em>https://blog.givn.in</em></a><em> on October 8, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=26f047d95f8e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“Three taps a week: where I sit in an AI-run blog pipeline”]]></title>
            <link>https://medium.com/@shekharsomani98/three-taps-a-week-where-i-sit-in-an-ai-run-blog-pipeline-209ce67bad69?source=rss-2920c9c9b63b------2</link>
            <guid isPermaLink="false">https://medium.com/p/209ce67bad69</guid>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[ai-agents-in-action]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[workflow]]></category>
            <dc:creator><![CDATA[Shekharsomani]]></dc:creator>
            <pubDate>Wed, 07 Oct 2026 00:00:48 GMT</pubDate>
            <atom:updated>2026-10-26T05:36:01.742Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7qvbNJmRWUmRIZAw.png" /></figure><p><em>For anyone building an AI workflow who wants to review less and still stay in control: the three places I put myself, and the test I used to pick them.</em></p><p>I run a weekly blog with AI agents doing almost all of the work: finding topics, researching, drafting, drawing the diagrams, formatting, and publishing. My part is three decisions a week. Each one reaches me as a message on my phone with a link, and none of them needs me to read the whole pipeline.</p><p>Anyone who lets an AI do real work hits the same fork. Review everything, and you become the bottleneck. Review nothing, and you find out about mistakes from your readers. This article is about the third option: choosing a few places to stand, and making each one cheap to act on.</p><p>I’ll show the weekly flow, the test I use to decide where a human belongs, and a smaller version you can build this week. I’ll also say what has gone wrong, and what I have not measured.</p><h3>The usual advice is “review everything” or “review nothing”</h3><p>Developers are arguing about this right now. In <a href="https://dev.to/debashish_ghosal/the-verification-trap-why-generative-ai-is-making-senior-engineers-slower-and-how-to-fix-it-245m">The Verification Trap</a>, a senior engineer argues that AI makes writing instant and checking slow, so experienced people end up as full-time proofreaders. In <a href="https://dev.to/soaresdiogo/dark-factory-vs-light-factory-where-should-ai-agents-run-unwatched-9po">Dark Factory vs. Light Factory</a>, the author describes a “dark” pipeline where no human looks at the output, and a “light” one where humans stay at the points where judgment matters. One line from that piece has stuck with me: a light factory where people click approve without reading is a dark factory with extra latency.</p><p>Both articles are about code, but the problem is the same for a founder with a weekly newsletter or an analyst with a Monday report. The question is not “how much should AI do?” It is “which few moments need a person, and what does that person need to see to decide well?”</p><p>Done by hand, a weekly post is five small jobs in a row (find a topic, research, write, make figures, publish twice), and none of them is optional. With a day job, it is easy for the blog to quietly stop. Handing all five to an AI fixes the time problem, and creates the review problem above.</p><h3>The setup: one agent, five jobs, one phone</h3><p>I use an agent harness, software that runs AI agents like employees: each piece of work is a task, assigned to an agent, with comments and approval requests attached. It runs on a local machine of mine. A single agent, which I call the Blogger, has a separate set of written instructions for each job. These are called skills, and each one is a plain document that says how to do that job and what to check before finishing.</p><p>The jobs, in weekly order:</p><ol><li><strong>Scout.</strong> Look at what people read and discussed this week on dev.to and Hacker News, and what is already crowded on Medium, then write a brief with three topic options.</li><li><strong>Write.</strong> Draft the chosen article in my voice, with placeholders for figures.</li><li><strong>Draw.</strong> Turn each placeholder into a diagram, an illustration or an interactive figure.</li><li><strong>Publish.</strong> Build the blog page, update the post list and the RSS feed, and prepare the Medium version.</li><li><strong>Nudge.</strong> Send me a short Telegram message when something is waiting, with a link to the task.</li></ol><p>Telegram does not run anything. It is a doorbell. The decision itself happens on a card attached to the task, which opens fine in a phone browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*F9n_RKcBT9Tqqe2Z.png" /></figure><h3>Three taps, and the test that picked them</h3><p>Here are the three places I sit.</p><p><strong>Tap 1: pick the topic.</strong> The brief arrives with one recommended topic per subject (technical, my epics series, and productivity), each with why-now links, what is already on Medium, and what the agent still needs from me. I pick. This is direction. An agent can rank topics by signals, but it cannot know which ones I would be proud to put my name on, or which I know too little about to write well.</p><p><strong>Tap 2: approve the draft.</strong> When the article and its figures are done, the agent posts a hand-off: a one-paragraph summary, the list of figures, anything marked as unknown, and any confidentiality worry. I read the article, then approve, or send it back with changes. Nothing is published before this.</p><p><strong>Tap 3: approve the Medium version.</strong> After the post is live on my own blog, the agent prepares a version for Medium and shows it to me as a finished artifact. I look at it, approve it, and the agent publishes it to Medium. It is the last step that needs me, because once it is on Medium, a mistake is public.</p><p>I picked these three with one test. A step needs a human when it passes at least one of these:</p><ul><li><strong>It sets direction.</strong> The answer depends on what I want, not on what is correct.</li><li><strong>It is hard to undo.</strong> Once it leaves the building, a mistake is public.</li><li><strong>The machine cannot do it.</strong> Something sits outside what the agent can reach.</li></ul><p>Everything else is work in the middle, where a mistake is cheap and the next step catches it. Topic research fails the test: if the scout misses something, the brief is a bit worse and I still choose from three options. Drawing a diagram fails it too: if one is wrong, I will see it at tap 2 anyway.</p><p>Step through one week: what runs by itself, what reaches my phone, and what I actually see at each tap.</p><h3>Making each tap cheap is most of the work</h3><p>Picking the right places is half of it. The other half is making each one doable in a minute or two, because a tap that takes twenty minutes turns into a skipped tap. Three habits do this.</p><p><strong>The agent writes a decision card, not a report.</strong> The topic brief has the same shape every week: a one-line pitch, why now, what is already out there, what the agent needs from me. The draft hand-off has the same shape too. I am never reading a wall of text to work out what is being asked.</p><p><strong>Unknowns are flagged, not smoothed over.</strong> If a number is needed and not known, the agent writes a visible placeholder and lists it in the hand-off. I have not timed my weekly effort, so this article has no minutes-saved figure. The agent was told not to invent one.</p><p><strong>Approval is checked against the current draft.</strong> The publish instructions say that a “looks good” on an earlier draft does not count after later edits. A stale yes is how an unreviewed change reaches readers.</p><h3>What I do not review, and why that is safe enough</h3><p>I do not read the scout’s raw research, check the formatting, or open the RSS file. That is not because the agent is always right. It is because those steps fail loudly or cheaply. The publish step refuses to run if a figure file is missing, and prints the list. The publish script can only write inside the blog folder.</p><p>The things I cannot check quickly all go to tap 2: whether the facts are right, whether a number was invented, whether anything private slipped in. So the instructions put weight there: a source link for every outside claim, no invented numbers, and my employer and its clients kept out.</p><h3>What went wrong</h3><p><strong>The pick card took one answer, and I wanted two.</strong> This week’s brief offered three topics, and I wanted two of them. I answered the card with one, then left a comment asking for the second. The agent read the comment and opened a second writing task, so nothing was lost. But the flow assumed one pick per week, and the first time I wanted more it needed a workaround.</p><p><strong>The scout’s sense of “what is crowded” is a sample.</strong> Medium does not expose its trending lists to bots, so the scout uses dev.to and Hacker News as a proxy for what readers care about, and Medium’s public feeds to see what is already published. Those feeds only show about the latest ten posts per tag, so “there is room on Medium” is a guess, not a count. One source also returned nothing for one tag this week. The brief says so at the top, which is why tap 1 matters: I am the sanity check on a thin signal.</p><p><strong>Approvals can turn into rubber stamps.</strong> This is the risk the “light factory” article warns about, and I have no data showing I am immune. I have not measured how closely I read, or how many problems I catch at tap 2. The hand-off format makes the unknowns visible, so skipping them is a choice and not an accident. That is a mitigation, not proof.</p><p>Keep the scope in mind too: this is a weekly blog for one person. If a wrong post is the worst outcome, three taps is plenty. For anything involving money, customer data or security, I would add gates and not copy this layout unchanged.</p><h3>A smaller version you can build this week</h3><p>You do not need special software. You need a repeatable weekly chain and a decision about where you stand in it. I have only built this with one agent harness and Telegram, so treat the steps below as the shape of the idea, not a tested recipe for other tools.</p><ol><li><strong>Write your chain down.</strong> Pick one recurring thing (a weekly report, a newsletter, a client update) and list every step from “start” to “sent”.</li><li><strong>Run each step through the test.</strong> Mark the ones that set direction, are hard to undo, or cannot be done by the assistant. Usually that is two to four steps.</li><li><strong>Make the assistant do everything else, and stop at your marks.</strong> Tell it plainly: “Do not send, publish or share anything. Stop and hand off to me.”</li><li><strong>Give it a fixed hand-off format.</strong> I use this one:</li></ol><pre>Summary: one paragraph of what you made. What I need from you: the decision, in one sentence. Options: two or three choices, each with one line on the trade-off. Unknown or unverified: anything you were unsure of or had to guess. Sensitive: anything that might be private or confidential.</pre><ol><li><strong>Add a nudge.</strong> Anything that tells you “something is waiting” will do: a message, an email, a notification. Keep it to one line and a link.</li><li><strong>After a month, move one gate.</strong> If you approve something every time without changes, ask whether it still passes the test. If an unchecked step keeps producing problems, add a gate there.</li></ol><h3>Takeaways</h3><ul><li><strong>Pick your stops by asking three questions.</strong> Does this set direction, is it hard to undo, or can the machine not do it? If none, let it run.</li><li><strong>Make each stop a decision, not a reading task.</strong> A fixed card with a summary, the choice, and the unknowns beats a long report.</li><li><strong>Make the machine flag what it does not know.</strong> Visible placeholders turn a rubber stamp into a real check.</li><li><strong>Tie approval to the current draft.</strong> Re-approve after edits.</li><li><strong>Revisit the gates monthly.</strong> Move them to wherever the mistakes actually come from.</li></ul><p>Where would you stand in your weekly workflow? Tell me which step you would never hand over, and I’ll tell you if it passes the test.</p><p><em>Originally published at </em><a href="https://blog.givn.in/posts/three-taps-a-week-human-in-ai-workflow/medium/"><em>https://blog.givn.in</em></a><em> on October 7, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=209ce67bad69" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What a vLLM Operator Can Take From DeepInfer, and What to Measure]]></title>
            <link>https://medium.com/@shekharsomani98/what-a-vllm-operator-can-take-from-deepinfer-and-what-to-measure-f03ac2e82b54?source=rss-2920c9c9b63b------2</link>
            <guid isPermaLink="false">https://medium.com/p/f03ac2e82b54</guid>
            <category><![CDATA[deepinfer]]></category>
            <category><![CDATA[mixture-of-experts]]></category>
            <category><![CDATA[vllm]]></category>
            <category><![CDATA[deepseek]]></category>
            <category><![CDATA[inference-optimization]]></category>
            <dc:creator><![CDATA[Shekharsomani]]></dc:creator>
            <pubDate>Wed, 07 Oct 2026 00:00:05 GMT</pubDate>
            <atom:updated>2026-10-24T19:40:30.248Z</atom:updated>
            <content:encoded><![CDATA[<p>For engineers serving MoE models on vLLM — which DeepInfer ideas map to flags you already have, which don’t, and a benchmark plan for your own long-context traffic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vo4TDc8yKbEamHIx.png" /></figure><p><em>For engineers serving MoE models on vLLM: which DeepInfer ideas map to flags you already have, which don’t, and a benchmark plan for your own long-context traffic.</em></p><p>DeepSeek released <a href="https://github.com/deepseek-ai/DeepInfer">DeepInfer</a>, the inference framework behind its production services. It was the <a href="https://news.ycombinator.com/item?id=50163277">top Hacker News story</a> this week, with 2,346 points and 891 comments. Most of what I have seen since is a recap of the README.</p><p>I have not run it. DeepInfer targets NVIDIA SM100 GPUs and Huawei Ascend 950 NPUs, and I do not have either. So this is not a benchmark post. It is a reading of the repo, the model config and the vLLM docs, from the point of view of someone who runs vLLM and wants to know what to do on Monday.</p><p>You will get three things: what DeepInfer actually is, which of its features have a vLLM equivalent today, and a benchmark plan you can run on your own long-context workload before you believe anyone’s chart, including DeepSeek’s.</p><p>I mark what I read separately from what I tested. Nothing in this article was tested on DeepInfer.</p><h3>DeepInfer is a component, not a server</h3><p>The README is blunt about scope. This release is “offline inference”, it supports one model (DeepSeek-V4.1-Flash), and it lists three things as “required for a complete inference service (not included in this release)”:</p><ul><li>A KV cache system.</li><li>Prefill/decode disaggregation (the README says most of the engine functionality for it is already implemented).</li><li>Load balancing across data-parallel replicas for both prefill and decode.</li></ul><p>That list matters more than the feature list. A KV cache system, a disaggregation layer and a load balancer are most of what you operate in production. DeepInfer gives you the model executor and the kernels. You would still build the service around it.</p><p>The acknowledgments say it was “originally built primarily on vLLM”, with ideas from SGLang and TensorRT-LLM. So the useful question is not “is it better than vLLM”. It is “what did they change on top of a vLLM-shaped engine, and which of those changes can I get without leaving vLLM”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/351/0*c6GuoFEyVoKfv18N.png" /></figure><h3>The model config tells you where long context hurts</h3><p>The default checkpoint is <a href="https://huggingface.co/deepseek-ai/DeepSeek-V4.1-Flash-1017">DeepSeek-V4.1-Flash-1017</a>. I read these values straight from its config.json:</p><ul><li>max_position_embeddings: 1,048,576 (a 1M-token window, extended with YaRN scaling from an original 65,536).</li><li>40 layers, 384 routed experts, 6 experts per token, 1 shared expert.</li><li>num_key_value_heads: 1, with a sliding_window of 128.</li></ul><p>Two things follow. First, with 384 experts and 6 active per token, every forward pass is an all-to-all across whatever GPUs hold the experts. At long context that cost sits on top of attention, not instead of it.</p><p>Second, one KV head and a 128-token sliding window suggest the per-token KV footprint is small compared to a dense-attention model of the same size. I say “suggest” on purpose. The config also has a per-layer compress_ratios list that I cannot interpret from the file alone, so I have not worked out the real KV bytes per token. That is the first number I would want from a real run.</p><h3>Three DeepInfer features already have a vLLM flag</h3><p>Here is the mapping, from the DeepInfer README against the current vLLM docs on main. Three map cleanly. A fourth maps only in part.</p><ul><li><strong>Attention data parallelism with MoE expert parallelism, plus EPLB.</strong> DeepInfer lists “Attention DP / balanced CP, MoE EP + EPLB”. In vLLM that is --data-parallel-size, --enable-expert-parallel and --enable-eplb. The <a href="https://github.com/vllm-project/vllm/blob/main/docs/serving/expert_parallel_deployment.md">vLLM docs</a> say expert load is often &quot;highly skewed&quot; in practice, which is why EPLB exists.</li><li><strong>Batch-invariant inference.</strong> DeepInfer: DEEPINFER_BATCH_INVARIANT=1, NVIDIA only. vLLM: VLLM_BATCH_INVARIANT=1, currently marked beta in its <a href="https://github.com/vllm-project/vllm/blob/main/docs/features/batch_invariance.md">docs</a>.</li><li><strong>Structured outputs.</strong> Both support regex, JSON schema and grammar constraints.</li><li><strong>Draft-token decoding (partial).</strong> DeepInfer has “DSpark and confidence-scheduled verification”. vLLM has speculative decoding in general. I did not find a documented equivalent of the confidence-based scheduling, so treat that part as DeepInfer-only until someone shows otherwise.</li></ul><p>One more DeepInfer feature, “SWA bounded replay”, has no counterpart I could find in the vLLM docs. It replays only a bounded suffix of the sequence for decoder prefill, and the README sets the default to keep 140 tokens, just above the 128-token window. I have not checked vLLM’s source for something similar, so I list it as unknown, not absent.</p><p>The flags in vLLM are not the same as the behaviour in DeepInfer. Same names for the ideas, different engines. Do not assume the numbers carry over.</p><h3>Check that vLLM can load the model before you plan hardware</h3><p>This is the cheapest check and the one most likely to save you a week. The DeepInfer checkpoint declares the architecture DeepseekV41ForCausalLM. The vLLM supported-models table I read lists DeepseekV4ForCausalLM (V4-Flash and V4-Pro) and does not list a V41 entry.</p><p>That may be out of date by the time you read this, or the V4 class may load the V4.1 weights. I did not test either. Before you size a cluster, run the model through vLLM on a small slice and see whether it loads. If it does not, you are comparing DeepInfer on V4.1 against vLLM on a different model, and the comparison is meaningless.</p><p>One decode step on a DP-attention, EP-experts deployment: where each GPU waits.</p><h3>What will go wrong if you copy the config</h3><p>I have no production failure with DeepInfer to report, because I have not run it. What I can give you is three failures that the vLLM docs themselves describe for this deployment shape. I would test for them first.</p><p><strong>Idle ranks still cost you.</strong> With attention DP and expert parallelism, the ranks are not independent. The vLLM <a href="https://github.com/vllm-project/vllm/blob/main/docs/serving/data_parallel_deployment.md">data parallel docs</a> say that when any rank has requests, the others must run empty “dummy” forward passes so the expert layers can synchronize. With spiky or low traffic, you pay for GPUs that are doing nothing useful on every step.</p><p><strong>Each rank has its own KV cache.</strong> The same page notes that each DP engine has an independent KV cache, and that prefix caching only helps if you send related prompts to the same rank. For long-context sessions that reuse a large prefix, a naive round-robin balancer throws the cache away. And this is the exact piece DeepInfer says it does not ship.</p><p><strong>A chart from a different cluster tells you little.</strong> DeepInfer’s published curves were measured on 4 SM100 GPUs for prefill and 64 for decode, each inside one scale-up domain. You are probably not running that. vLLM’s own benchmarking docs also warn that metric names are not standardized between tools, so compare formulas, not labels.</p><h3>Measure your own traffic, not theirs</h3><p>You do not need DeepInfer to learn the most important thing: where your workload sits on the throughput vs. per-user-speed curve at your context lengths. The vLLM docs give an expert-parallel launch for a single 8-GPU H200 node. This is straight from the docs, using their example model:</p><pre>vllm serve deepseek-ai/DeepSeek-V3-0324 \ --tensor-parallel-size 1 \ --data-parallel-size 8 \ --enable-expert-parallel</pre><p>Then sweep input length and concurrency with the built-in benchmark client, keeping output length fixed. Repeat for each input length you care about (for example short, medium and your real long-context size), and for several --max-concurrency values:</p><pre>vllm bench serve \ --backend vllm \ --model deepseek-ai/DeepSeek-V3-0324 \ --dataset-name random \ --random-input-len 32768 \ --random-output-len 512 \ --max-concurrency 16 \ --num-prompts 200</pre><p>Record time to first token (TTFT), time per output token (TPOT) and output tokens per second, then divide throughput by GPU count. Those are the same axes as DeepInfer’s two charts (prefill throughput against latency, decode throughput against per-user speed), so you can lay your curve next to theirs and see how far off your hardware is.</p><p>Two cautions. The random dataset gives you reproducible lengths but not realistic prefix reuse, so it will understate prefix caching. And the commands above are the vLLM docs&#39; own example, run on a model they list as supported. Swap in the V4.1 checkpoint only after the loading check from earlier passes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uNe5UESTYs2LbGYz.png" /></figure><h3>Takeaways</h3><ul><li>Read DeepInfer as a model executor plus kernels. The KV cache layer, disaggregation and load balancer you would run in production are not in the release.</li><li>Most of its parallelism ideas (attention DP, expert parallelism, EPLB, batch invariance, structured outputs) already have vLLM flags. Draft-token scheduling and SWA bounded replay are the ones I could not match.</li><li>Check that your vLLM version loads the V4.1 architecture before you plan hardware. The docs I read list V4, not V4.1.</li><li>With DP attention, route requests that share a long prefix to the same rank, or you lose the prefix cache.</li><li>Benchmark your own input lengths and concurrency, divide by GPU count, and compare curve shapes. Do not compare absolute numbers from a different cluster.</li></ul><p>If you have run DeepInfer on SM100 hardware, I would like to see your numbers. Reply and tell me where my reading above is wrong.</p><p><em>Originally published at </em><a href="https://blog.givn.in/posts/vllm-operator-lessons-from-deepinfer/medium/"><em>https://blog.givn.in</em></a><em> on October 7, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f03ac2e82b54" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Babel : An AI That Builds Its Own Tools. Here’s How.]]></title>
            <link>https://medium.com/@shekharsomani98/babel-an-ai-that-builds-its-own-tools-heres-how-f6d1fdcc818d?source=rss-2920c9c9b63b------2</link>
            <guid isPermaLink="false">https://medium.com/p/f6d1fdcc818d</guid>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[mistral-ai]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[self-improvement]]></category>
            <dc:creator><![CDATA[Shekharsomani]]></dc:creator>
            <pubDate>Mon, 02 Mar 2026 17:47:46 GMT</pubDate>
            <atom:updated>2026-03-03T10:32:13.951Z</atom:updated>
            <content:encoded><![CDATA[<h3>Babel : Built an AI That Builds Its Own Tools. Here’s How.</h3><h3>The story of Babel, a self-evolving tool registry that lets AI agents synthesize new capabilities at runtime, on demand, without human intervention.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tCO75w3kNPryRz2EeI0qRQ.png" /></figure><p>Youtube link: <a href="https://youtu.be/5qIetGhy5S4">https://youtu.be/5qIetGhy5S4</a></p><p>There’s a problem hiding in plain sight inside every AI agent framework being built today.</p><p>It’s not a bug. It’s not a missing feature. It’s a foundational assumption so deeply baked into how we build agentic systems that most people have simply stopped questioning it.</p><p>The assumption is this: <strong>agents can only do what you’ve already built them to do.</strong></p><p>Every tool your agent will ever use must be written before the agent runs. Every capability must be pre-registered. Every gap in your tool library is a hard failure at runtime. LangChain, CrewAI, AG2, AutoGen all of them, without exception, operate on this model. You define the toolkit. You start the system. You hope you anticipated everything your agent will need.</p><p>You almost never do.</p><p>That’s the problem Babel was built to solve.</p><h3>The Real Cost of Static Tool Libraries</h3><p>Let me be concrete about why this matters beyond the obvious inconvenience.</p><p>When you build an AI agent system, you’re essentially writing a prediction. A prediction about every capability the agent will need to accomplish its goals. You write tool A because you think the agent will need to fetch data. You write tool B because you think it’ll need to transform that data. You write tool C just in case.</p><p>But intelligent, autonomous systems are definitionally hard to predict. The moment you deploy an agent capable of reasoning about complex, multi-step tasks, it will encounter requirements you didn’t anticipate. A useful subtask you never thought to pre-build. A data transformation that’s specific to a particular query. A specialised computation that only matters for this one use case.</p><p>In most frameworks, when this happens, the agent fails. Or it hallucinates a workaround. Or it silently produces a degraded result. The human operator eventually notices, writes the missing tool, restarts the system, and tries again.</p><p>This cycle is to notice gap, stop system, write code, restart — is the central bottleneck of modern agent development. And it doesn’t scale. As agents take on more complex, open-ended tasks, the number of tools you need to pre-build grows combinatorially. You’re always one step behind.</p><p><strong>Babel’s core thesis is that this doesn’t have to be true.</strong> The bottleneck isn’t inherent to agentic systems. It’s a consequence of a design choice that can be unmade.</p><h3>What Babel Actually Is</h3><p>Babel is a local-first platform with three interlocking pieces: a tool registry, a planning agent called ARIA, and a synthesis engine called Vibe. Together, they form a system where the gap between “tool doesn’t exist” and “tool is available and executing” is measured in seconds, not hours.</p><p>Here’s the high-level flow:</p><ol><li>You type a request in natural language into Babel Chat</li><li>ARIA decomposes your request into a task graph which is a directed graph where each node is a subtask and each edge encodes a dependency</li><li>ARIA checks the task graph against the registry. If all required tools exist, execution begins immediately</li><li>If any tools are missing, ARIA triggers Vibe to synthesize them generating a spec and implementation from scratch</li><li>The new tools are tested, validated, hot-loaded into the registry, and execution resumes with no restart, no human involvement</li><li>Results stream back to you in real time via Server-Sent Events</li></ol><p>The whole flow, including synthesis of a new tool, typically completes in under a minute. For requests where all tools already exist, it’s seconds.</p><h3>ARIA: The Planning Brain</h3><p>ARIA (Adaptive Runtime Intelligence Architecture) is the orchestration layer that makes all of this work.</p><p>When you submit a request, ARIA doesn’t just forward it to a tool. It calls Mistral Large with your request and the full list of currently available tools, and asks it to produce a structured task graph in JSON. That graph describes not just <em>what</em> needs to happen, but <em>in what order</em> and <em>with what dependencies</em>.</p><p>Consider a request like: <em>“Analyze the latest arXiv papers on LLMs and email me a summary.”</em></p><p>ARIA might produce a graph like:</p><pre>[arxiv_fetcher] → [topic_analyzer] → [summary_writer] → [send_email]</pre><p>Each node maps to a specific tool. Edges define the data flow: the output of arxiv_fetcher feeds into topic_analyzer, whose output feeds into summary_writer, and so on. ARIA uses topological sorting to determine execution order, ensuring no node runs before its dependencies are resolved.</p><p>Once the graph is built, ARIA compares every node against the tool registry. If all tools exist, it spins up AG2 agents for each node and begins executing. The key design choice here is that ARIA doesn’t execute tools directly, it delegates each subtask to a dedicated AG2 agent, which calls the tool via HTTP and returns the result. This keeps the execution model clean and allows for parallel execution of independent branches in the task graph.</p><p>When a tool is missing, ARIA doesn’t throw an error. It flags the gap and routes a synthesis request to Vibe, then enters a waiting state. Once the missing tool is registered, ARIA re-evaluates the graph and continues.</p><p>The entire execution lifecycle streams as SSE events to the frontend: node_start, tool_call, tool_result, node_complete, flow_complete. The UI renders these in real time, giving you a live view of the task graph as it executes which nodes are running, which have completed, what data is flowing between them.</p><h3>Vibe: The Synthesis Engine</h3><p>Vibe is where the magic and the genuine technical risk lives.</p><p>When ARIA identifies a missing tool, it sends a synthesis request to the Vibe service. This request contains everything Vibe needs to generate the tool: the tool’s name, a description of what it should do, its expected inputs and outputs, and any relevant context about how it fits into the larger task.</p><p>Vibe is a FastAPI service wrapping Mistral’s <strong>devstral</strong> coding agent — a model specifically tuned for software development tasks. The service runs in a Docker container, which is a deliberate security decision: synthesised code executes in isolation, with no access to the host filesystem or network beyond what’s explicitly permitted.</p><p>The synthesis pipeline works like this:</p><p><strong>Step 1 — Workspace preparation.</strong> Vibe creates a temporary workspace containing a CONTEXT.md file. This document is carefully engineered: it describes the Babel tool format in detail, explains implementation rules (no hardcoded credentials, explicit environment variable declarations, no side effects outside the function), specifies testing requirements, and gives examples of well-formed tools. This context is essentially a system prompt for the coding agent.</p><p><strong>Step 2 — Vibe CLI invocation.</strong> Vibe spawns the devstral CLI as a subprocess in streaming mode. The CLI receives the synthesis request and the context file, and begins generating the tool implementation.</p><p><strong>Step 3 — Artifact validation.</strong> Once devstral completes, Vibe validates the generated artifacts. Does the spec.yaml conform to the Babel schema? Does the impl.py define the correct entry function? Are the declared environment variables complete?</p><p><strong>Step 4 — Webhook callback.</strong> Validated artifacts are POSTed to BabelServer via a webhook at POST /vibe/callback. BabelServer receives the spec and implementation, runs the fixture tests defined in the spec, and if tests pass, persists the tool to disk and registers it in the in-memory registry.</p><p><strong>Step 5 — Hot reload.</strong> The new tool immediately appears in GET /tools responses. ARIA, which has been polling for the missing tool, detects it and resumes execution.</p><p>The typical end-to-end synthesis time is 15–30 seconds for straightforward tools. More complex tools with external API integrations can take longer, but the system handles this gracefully, ARIA simply waits.</p><h3>The Tool Format: Simple by Design</h3><p>One of Babel’s best design decisions is how boring the tool format is.</p><p>Every tool consists of exactly two files:</p><p><strong>spec.yaml</strong> — A declarative description of what the tool does:</p><pre>babel_version: &quot;1.0&quot;<br>tool:<br>  id: com.aria.tools.crypto_price<br>  name: crypto_price<br>  version: 1.0.0<br>  description: Fetch the current price of a cryptocurrency in USD<br>  author: vibe_tool<br><br>interface:<br>  inputs:<br>    - name: symbol<br>      type: string<br>      description: Cryptocurrency symbol (e.g. BTC, ETH)<br>      required: true<br>  outputs:<br>    - name: price_usd<br>      type: float<br>      description: Current price in USD<br>    - name: last_updated<br>      type: string<br>      description: Timestamp of the price data<br>testing:<br>  fixtures:<br>    - input:<br>        symbol: &quot;BTC&quot;<br>      expected_output_contains:<br>        - price_usd<br>        - last_updated</pre><p><strong>impl.py</strong> — The actual implementation:</p><pre>REQUIRED_ENV_VARS = [&quot;COINGECKO_API_KEY&quot;]<br><br>def crypto_price(**kwargs) -&gt; dict:<br>    symbol = kwargs.get(&quot;symbol&quot;, &quot;BTC&quot;).upper()<br>    api_key = os.environ.get(&quot;COINGECKO_API_KEY&quot;)<br>    <br>    response = requests.get(<br>        f&quot;https://api.coingecko.com/api/v3/simple/price&quot;,<br>        params={&quot;ids&quot;: symbol.lower(), &quot;vs_currencies&quot;: &quot;usd&quot;},<br>        headers={&quot;x-cg-api-key&quot;: api_key}<br>    )<br>    data = response.json()<br>    <br>    return {<br>        &quot;price_usd&quot;: data[symbol.lower()][&quot;usd&quot;],<br>        &quot;last_updated&quot;: datetime.utcnow().isoformat()<br>    }</pre><p>That’s the entire contract. The spec is what the tool promises; the implementation is how it delivers. The spec serves double duty as both documentation and test definition.</p><p>What makes this format powerful is the <strong>compiler layer</strong>. Babel ships with compilers for AG2, Mistral, LangChain, and Pydantic AI. Each compiler reads a Babel spec and generates the framework-specific wrapper automatically. This means a tool synthesized by Vibe which has no knowledge of which framework you’re using and works out of the box with all of them. Hand-written tools and synthesized tools are identical from the framework’s perspective.</p><h3>Security: What Could Go Wrong (And How Babel Handles It)</h3><p>Synthesizing arbitrary code at runtime and executing it immediately is, on its face, a significant security risk. Babel’s approach is pragmatic rather than perfect — it’s designed for local development use, and it’s honest about that scope.</p><p><strong>Docker isolation for synthesis.</strong> Vibe runs in a Docker container with a controlled environment. Synthesized code is executed inside the container during testing. The implementation files that get posted to BabelServer have passed testing, but they were tested in an isolated environment — they haven’t run on your host until you explicitly execute them through the registry.</p><p><strong>Fixture tests as a quality gate.</strong> Before any tool enters the registry, its fixture tests must pass. This isn’t a comprehensive security check, but it does eliminate obviously broken implementations and ensures the tool behaves as specified for at least the documented test cases.</p><p><strong>Explicit environment variable declarations.</strong> Each tool’s REQUIRED_ENV_VARS list is checked before execution. If a required variable isn&#39;t set, the registry surfaces a clear error rather than failing silently or — worse — proceeding with undefined behavior. This also prevents tools from accessing credentials that weren&#39;t declared.</p><p><strong>Local-first by default.</strong> Nothing leaves your machine without explicit action. The remote registry is opt-in, per-tool. Your API keys, synthesized tools, and execution data stay local.</p><h3>The Local-to-Remote Registry Pipeline</h3><p>One of Babel’s more forward-looking features is the distinction between local and remote registries.</p><p>By default, every tool — whether hand-written or synthesized — lives in your local registry/tools/ directory. It&#39;s yours. It&#39;s private. It&#39;s immediately available to your agents.</p><p>But tools have value beyond the machine they were created on. A well-synthesized tool for fetching stock earnings data, or scraping regulatory filings, or converting between geospatial formats that’s potentially useful to hundreds of other Babel users. The remote registry is the mechanism for sharing it.</p><p>This creates a compounding dynamic. Every novel task that requires synthesis creates a potential contribution to a shared library. Over time, the remote registry becomes increasingly dense with specialized tools and ARIA’s planning becomes increasingly likely to find existing tools rather than needing to synthesize new ones. The system gets more capable as more people use it.</p><h3>What This Architecture Enables</h3><p>Stepping back, it’s worth being explicit about what changes when you have a self-evolving tool registry.</p><p><strong>The planning horizon expands.</strong> When you don’t have to pre-build every tool, you can design agents for genuinely open-ended tasks. Instead of scoping an agent to “tasks within this predefined tool library,” you can scope it to “tasks achievable with tools that can be synthesized in real time.” That’s a fundamentally different and much larger problem space.</p><p><strong>The development loop changes.</strong> Building agent systems currently involves a lot of upfront tool development before you can test anything meaningful. With Babel, you can start from intent (“I want an agent that does X”) and let synthesis fill in the gaps as you discover them. It’s a tighter loop between idea and working system.</p><p><strong>The long tail becomes tractable.</strong> Most agent frameworks are well-suited for common tasks that justify the investment of pre-building polished tools. One-off tasks, specialized queries, narrow domain tools these usually aren’t worth the investment. Synthesis changes the economics: a one-off tool costs 20 seconds of synthesis time, not hours of development time.</p><p><strong>Agents can specialize dynamically.</strong> An agent that encounters a new domain can synthesize domain-specific tools on first encounter and reuse them on subsequent queries. Over time, a frequently used agent naturally accumulates a library of specialized tools tailored to its actual usage patterns.</p><h3>What’s Still Hard</h3><p>Babel is a proof of concept, and it would be dishonest to present it without acknowledging what doesn’t work well yet.</p><p><strong>Synthesis quality is variable.</strong> Devstral is a strong coding model, but it makes mistakes. Generated tools sometimes have bugs, make incorrect assumptions about API interfaces, or produce implementations that pass fixture tests but fail on edge cases. The fixture test gate catches the obvious failures, but it’s not comprehensive coverage. In practice, you should treat synthesized tools as first drafts that may need review before production use.</p><p><strong>Complex tool dependencies are tricky.</strong> If a synthesized tool requires a third-party Python library that isn’t installed in the execution environment, it will fail at runtime. Babel doesn’t currently handle automatic dependency installation for synthesized tools. This is solvable — pip install in the Docker container, dependency declarations in the spec — but it’s not implemented yet.</p><p><strong>The planning layer can over-decompose.</strong> Mistral Large sometimes generates task graphs with more granularity than necessary, creating synthesis requests for tools that could reasonably be handled by a single, more general tool. This inflates synthesis time and registry size. Better planner prompting and a “tool similarity” check before synthesis would help here.</p><p><strong>Synthesis is sequential.</strong> If a task graph requires three missing tools, Vibe synthesizes them one at a time. Parallel synthesis would significantly improve end-to-end latency for complex requests.</p><p>These are all tractable engineering problems. But they’re also real limitations you’d encounter in practice, and worth knowing about going in.</p><h3>Getting Started</h3><p>Babel requires Python 3.12+, Docker, Node.js 18+, and a Mistral API key. Setup is around ten minutes:</p><pre>git clone &lt;repo-url&gt; babel_project<br>cd babel_project<br>python -m venv venv &amp;&amp; source venv/bin/activate<br>pip install -r requirements.txt</pre><pre># Add your Mistral key to .env<br>echo &quot;MISTRAL_API_KEY=your_key_here&quot; &gt; .env</pre><pre># Start Vibe (synthesis engine) in Docker<br>docker compose build vibe_tool<br>docker compose up vibe_tool -d</pre><pre># Start BabelServer<br>python run_server.py</pre><pre># In another terminal, start the UI<br>cd aria-ui &amp;&amp; npm install &amp;&amp; npm run dev</pre><p>Open http://localhost:5173 and try asking it something that requires a tool it doesn&#39;t have yet. Watch the synthesis pipeline kick in. The first time you see a tool get generated, tested, and executed in a single uninterrupted flow is genuinely surprising, even when you built the system.</p><h3>The Bigger Idea</h3><p>I want to end with something that goes beyond the implementation.</p><p>The deep premise of Babel isn’t really about tool synthesis. It’s about what we should expect from autonomous AI systems.</p><p>We’ve spent the last few years building increasingly capable reasoning systems and then carefully constraining them to operate within pre-defined tool libraries. There’s a reasonable safety argument for that constraint. But there’s also a cost: we’ve built systems that are smart enough to reason about almost anything, but can only <em>act</em> on a small predefined slice of the problem space.</p><p>The question Babel asks is: what happens when the action space grows with the system’s understanding of the problem? When the agent can not only reason about what needs to be done, but also build the instruments to do it?</p><p>We don’t fully know the answer yet. But the early evidence from Babel suggests that the development experience changes substantially less time pre-building infrastructure, more time on the actual problem. The system becomes a collaborator in its own capability expansion rather than a consumer of capabilities you’ve already built.</p><p>That shift, if it proves durable, is significant.</p><p><em>Babel was built for the Mistral Worldwide Hackathon 2026 Singapore Edition. It runs on Mistral’s devstral coding agent, Mistral Large for planning, the AG2 multi-agent framework, and FastAPI. Feedback welcome.</em></p><p>More about AG2: <a href="https://medium.com/@shekharsomani98/ag2-multi-agent-systems-and-agentic-design-patterns-52db65596321">https://medium.com/@shekharsomani98/ag2-multi-agent-systems-and-agentic-design-patterns-52db65596321</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f6d1fdcc818d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AG2: Multi-Agent Systems, and Agentic Design Patterns]]></title>
            <link>https://medium.com/@shekharsomani98/ag2-multi-agent-systems-and-agentic-design-patterns-52db65596321?source=rss-2920c9c9b63b------2</link>
            <guid isPermaLink="false">https://medium.com/p/52db65596321</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[autogen]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[multi-agent-systems]]></category>
            <dc:creator><![CDATA[Shekharsomani]]></dc:creator>
            <pubDate>Sun, 22 Feb 2026 14:11:02 GMT</pubDate>
            <atom:updated>2026-02-22T14:11:02.316Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Big Picture</h3><p>AG2 is a framework for building <strong>multi-agent AI systems</strong> where multiple AI agents collaborate, argue, delegate, and coordinate to solve complex tasks that a single LLM prompt cannot handle well.</p><p>Think of it like building a <strong>virtual organization</strong> of AI workers, each with a role, and AG2 is the “operating system” that governs how they talk to each other, who’s in charge, when to stop, and how decisions get made.</p><h3>1. The Mental Model</h3><h4>What is an Agent in AG2?</h4><p>An agent in AG2 is not just “a prompt to an LLM.” It is an <strong>entity with four things</strong>:</p><ol><li><strong>An identity: </strong>a name, a system prompt, a role description</li><li><strong>A capability: </strong>what it can do (call LLMs, run code, use tools, reply from a fixed script)</li><li><strong>A decision function: </strong>logic that decides <em>how</em> to respond to an incoming message</li><li><strong>A termination sense: </strong>it knows when to stop or when to pass the baton</li></ol><h4>What Problem Does AG2 Solve?</h4><p>A single LLM is stateless and solitary. You ask, it answers. It forgets. It can’t argue with itself. It can’t run code and then reason about the output in a feedback loop.</p><p>AG2 solves this by making agents <strong>persistent conversation participants</strong> who maintain context and interact with each other over multiple turns like a back-and-forth meeting, not a one-shot prompt.</p><p>The core insight is: <strong>complex tasks need iteration, specialization, and verification.</strong> A coder writes code, a critic reviews it, an executor runs it, and a summarizer explains the result. No single agent does all of this well simultaneously.</p><h3>2. The Conversation Protocol</h3><p>This is the <strong>heart of AG2</strong>. Everything else is built on top of this. Understand this deeply and the rest will click naturally.</p><h4>The Fundamental Unit — A Message</h4><p>Every interaction in AG2 is a <strong>message</strong>. A message is not just text, it’s a structured packet that carries:</p><ul><li><strong>Role: </strong>who sent it (user, assistant, system, tool)</li><li><strong>Content</strong>: the actual text, or the result of a tool call</li><li><strong>Name: </strong>the specific agent who sent it (since multiple agents can share the same role)</li><li><strong>Context</strong> : metadata like whether it’s a tool call request or a tool call result</li></ul><p>Think of it like an email with headers. The content is what you read, but the headers tell the system what to <em>do</em> with it.</p><h4>The Conversation Object</h4><p>When two or more agents interact, AG2 maintains a <strong>conversation history, </strong>an ordered list of all messages exchanged so far. This is the shared memory of the conversation.</p><p>Here’s the critical thing to understand: <strong>every agent sees the full history before deciding what to say next.</strong> No agent operates in isolation. When it’s your turn to reply, you get handed the entire transcript up to that point.</p><p>This is fundamentally different from a single LLM call. You’re not sending one prompt, you’re sending a growing document that captures the entire dialogue, and each agent appends to it.</p><h4>The Conversation Loop — The Engine of AG2</h4><p>This is the most important mechanical concept in AG2.Once a conversation starts, AG2 runs a loop that looks like this:</p><pre>Initiator sends message<br>    → Recipient generates reply<br>    → Initiator generates reply<br>    → Recipient generates reply<br>    → ... continues until termination</pre><p>Each iteration of this loop is called a <strong>round</strong>. Within each round, each agent gets exactly one turn.</p><p>The loop keeps running <strong>automatically. </strong>You don’t manually call each agent. AG2’s conversation manager handles this orchestration invisibly. You just define the agents, start the chat, and the loop runs.</p><h4>Termination (When Does the Conversation Stop?)</h4><p>This is one of the trickiest parts to get right in multi-agent systems. If you don’t define when to stop, agents will talk forever (and burn your API budget).</p><p>AG2 has <strong>four termination mechanisms</strong>, and they can be combined:</p><p>1. Max Turns: The simplest is to just stop after N rounds. Blunt but useful as a safety net.</p><p>2. Termination String: You tell AG2: “if any agent’s reply contains this specific string, stop the conversation.” The convention in AG2 is TERMINATE. So when an agent believes the task is done, it ends its message with the word TERMINATE, and the loop stops. This is elegant because the <strong>agent itself decides when it’s done</strong>, not an external timer. An LLM agent can reason about task completion and signal it naturally in language.</p><p>3. Termination Function: A custom function you write that inspects any message and returns True/False for whether to stop. This gives you full control. You can stop based on content, sentiment, word count, or any logic you want.</p><p>4. Human Interrupt: A human types “exit” or some designated phrase, and the loop stops. This is part of the human-in-the-loop pattern</p><h4>The Reply Function: The Brain of an Agent</h4><p>Every agent in AG2 has something called a <strong>reply function</strong> (or a list of them). This is the core decision-making logic given the conversation history, what should I say back?</p><p>AG2 processes these reply functions in a <strong>priority order</strong>. For each incoming message, it asks:</p><ol><li>Should I terminate? (Check termination conditions first)</li><li>Does this message contain a tool call result I need to process?</li><li>Should I call a tool myself?</li><li>Should I generate an LLM response?</li><li>Should I ask a human for input?</li></ol><p>This priority chain means an agent is not just a dumb LLM wrapper it has a <strong>decision hierarchy</strong>. It won’t call the LLM if it already knows the answer is a tool result. It won’t keep going if termination is triggered.</p><h4>The Context Window Problem — AG2’s Dirty Secret</h4><p>Here’s a real tension you need to understand: as the conversation grows, the history gets longer, and every agent gets handed this ever-growing transcript. Eventually it hits the <strong>LLM’s context window limit</strong>.</p><p>AG2 handles this through <strong>context management strategies</strong>:</p><ul><li><strong>Truncation: </strong>drop the oldest messages when the history gets too long</li><li><strong>Summarization: </strong>compress old messages into a summary before dropping them</li><li><strong>Transform pipelines: </strong>pre-process the history before it’s sent to the LLM (filter, compress, restructure)</li></ul><h3>3. Agent Types &amp; Roles</h3><p>In Phase 2, we learned <em>how</em> agents talk. Now we meet <em>who</em> they are.</p><p>AG2 gives you a set of <strong>pre-built agent archetypes</strong> each designed around a specific responsibility in a multi-agent system. Understanding why each type exists is more important than memorizing their names.</p><h4>The Core Philosophy: Separation of Concerns</h4><p>Before we meet each agent, understand the design principle behind all of them:</p><p><strong>No single agent should do everything.</strong></p><p>In a well-designed AG2 system, agents are like specialists in a hospital. The surgeon doesn’t do billing. The radiologist doesn’t prescribe medicine. Each agent has a narrow, well-defined job and the system works because they hand off to each other cleanly.</p><p>This separation gives you three things:</p><ul><li><strong>Reliability: </strong>smaller jobs fail less</li><li><strong>Replaceability: </strong>swap one agent without rebuilding the whole system</li><li><strong>Auditability: </strong>you can see exactly which agent did what and why</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B0e1_yVg7wcVstUkBHzFCw.png" /></figure><h4>Agent Type 1: ConversableAgent (The Foundation)</h4><p>This is the <strong>base class</strong> from which all other agents inherit. Every agent in AG2 is, at its core, a ConversableAgent.</p><p>What makes it “conversable”? It can:</p><ul><li>Send and receive messages</li><li>Maintain a conversation history</li><li>Execute the reply function chain</li><li>Be configured with a system prompt, an LLM, termination logic, and tools</li></ul><p>Think of ConversableAgent as the <strong>blank employee, </strong>it has all the plumbing of a capable worker (a desk, a phone, a company email) but no specific job title yet. You configure it into a specialized agent by giving it a role.</p><p>In practice, you rarely use ConversableAgent directly. You either use one of its pre-built specializations, or you subclass it to build your own custom agent.</p><h4>Agent Type 2: AssistantAgent (The Worker)</h4><p>This is the most common agent you’ll use. It represents an <strong>LLM-powered AI assistant, </strong>the agent that actually thinks, reasons, and generates responses.</p><p>Its defining characteristics:</p><p><strong>It talks to an LLM.</strong> When it receives a message, it sends the conversation history to a model (GPT-4, Claude, Gemini, etc.) and returns whatever the model says.</p><p><strong>It has a default system prompt</strong> that tells it to be a helpful AI assistant, to write code when needed, and to say TERMINATE when the task is done.</p><p><strong>It does NOT run code by default.</strong> This is a crucial design decision. The AssistantAgent only <em>writes</em> code it doesn’t <em>execute</em> it. Execution is someone else’s job (the UserProxyAgent’s, as we’ll see).</p><p>This separation exists because you want a clean boundary between <strong>reasoning</strong> and <strong>acting</strong>. The agent that thinks shouldn’t be the same one that pulls triggers in the real world.</p><h4>Agent Type 3: UserProxyAgent (The Executor + Human Stand-in)</h4><p>This is the most misunderstood agent in AG2, because its name is misleading. It’s called “UserProxy” but it does far more than represent a user.</p><p>The UserProxyAgent has <strong>two distinct personalities</strong> that it switches between:</p><p><strong>Personality 1: Code Executor</strong></p><p>When the AssistantAgent writes code, the UserProxyAgent <strong>actually runs it</strong>. It takes the code block out of the message, executes it in a sandboxed environment (a local subprocess, a Docker container, or a Jupyter kernel), and feeds the output back into the conversation.</p><p>This closes the loop: AssistantAgent writes → UserProxyAgent executes → result goes back to AssistantAgent → it reasons about the output → writes better code → UserProxyAgent executes again.</p><p>This <strong>write → run → observe → improve</strong> cycle is how AG2 achieves things like autonomous data analysis, bug fixing, and research tasks.</p><p><strong>Personality 2: Human Gateway</strong></p><p>When a task requires human judgment, the UserProxyAgent pauses the conversation loop and <strong>asks a real human for input</strong> via the terminal. The human types a response, and that response is injected into the conversation as if the UserProxyAgent said it.</p><p>This is the “human in the loop” mechanism — and it’s configurable. You can tell the UserProxyAgent to always ask a human, never ask a human, or only ask a human when certain conditions are met.</p><h4>The Human Input Modes</h4><p>AG2 gives you three modes for human involvement:</p><ul><li><strong>ALWAYS: </strong>pause and ask a human after every single message. Maximum control, minimum autonomy.</li><li><strong>NEVER: </strong>never ask a human. Fully autonomous. The agent auto-replies with the code execution result (or a blank reply if there’s nothing to execute).</li><li><strong>TERMINATE: </strong>only ask a human when the AssistantAgent says TERMINATE, or when max turns is hit. This is the most practical mode — let the AI run, but give a human the final say.</li></ul><h4>Agent Type 4: RetrieveAssistantAgent &amp; RetrieveUserProxyAgent (The RAG Pair)</h4><p>These are specialized versions of the Assistant and UserProxy agents that have <strong>Retrieval-Augmented Generation</strong> built in.</p><p>Before answering, the RetrieveUserProxyAgent queries a <strong>vector database</strong> for relevant documents, injects them into the conversation, and then the RetrieveAssistantAgent uses that context to give a grounded, factual answer.</p><p>These exist because LLMs have knowledge cutoffs and don’t know about your private data. If you need your agent to answer questions about your codebase, your internal documents, or your product knowledge base, this is the pair you reach for.</p><h4>Agent Type 5: MultimodalConversableAgent (The Visual Reasoner)</h4><p>An extension of ConversableAgent that can process <strong>images alongside text</strong>. It passes image data to vision-capable LLMs (like GPT-4V or Claude) and reasons about visual content.</p><p>Used for tasks like: analyzing charts, reading screenshots, processing medical images, understanding diagrams, or any workflow where the input is not purely text.</p><h4>Agent Type 6: TeachableAgent (The Learner)</h4><p>This agent has <strong>persistent memory across conversations</strong>. When it learns something useful like a user preference, a corrected fact, a new procedure. It stores that in a long-term memory database. In future conversations, it retrieves and applies what it learned.</p><p>Without this, every AG2 conversation starts from zero. The TeachableAgent simulates a colleague who actually remembers your preferences and builds on past work.</p><h4>Agent Type 7: CompressibleAgent (The Context Manager)</h4><p>Conversation history grows unboundedly. The CompressibleAgent tackles this directly. It <strong>automatically compresses old messages</strong> when the history gets too long.</p><p>Instead of just truncating (losing information), it summarizes older parts of the conversation, preserving the gist while reducing token count. The conversation can then continue without hitting context window limits.</p><h3>4. Orchestration Patterns</h3><p><strong>How do you organize multiple agents to work together without chaos?</strong></p><p>This is orchestration is the science of <em>who talks to whom, in what order, with what authority, and under what conditions.</em></p><h4>Why Orchestration is Hard?</h4><p>Imagine you have 6 specialist agents: a Planner, a Coder, a Critic, a Tester, a Security Reviewer, and a Summariser. Several problems immediately arise like</p><ul><li><strong>Who speaks first?</strong> And how does the next speaker get chosen?</li><li><strong>Does everyone hear everything?</strong> Or do some agents only see part of the conversation?</li><li><strong>Who has final authority?</strong> If the Coder and Critic disagree, who wins?</li><li><strong>Can agents spawn sub-tasks?</strong> Can the Planner kick off a whole separate conversation to handle one step?</li><li><strong>How do you prevent infinite loops?</strong> What stops two agents from arguing forever?</li></ul><p>AG2’s orchestration patterns are answers to these exact questions. There are <strong>four fundamental patterns</strong>, and real systems combine them.</p><h4>Pattern 1 : Two-Agent Chat (The Atom)</h4><p>This is the simplest pattern. One initiator, one recipient. A single conversation loop. Back and forth until termination.</p><pre>AgentA  ←→  AgentB</pre><p>The key insight is that <strong>iteration within two agents is often enough </strong>because the LLM can play multiple mental roles within its reasoning even when it’s technically one agent. The “back and forth” gives each agent a chance to challenge, correct, and improve on the previous output.</p><h4>Pattern 2:Group Chat (The Committee)</h4><p>This is where AG2 gets genuinely powerful. A group chat involves <strong>three or more agents sharing a single conversation</strong>, with a special orchestrator agent called the <strong>GroupChatManager</strong> controlling who speaks next.</p><pre>        GroupChatManager<br>       /       |        \<br>  AgentA    AgentB    AgentC<br>       \       |        /<br>        Shared History</pre><p>Every agent sees every message. When it’s time for someone to reply, the GroupChatManager decides <em>which</em> agent gets the turn.</p><p><strong>The Speaker Selection Problem:</strong></p><p>This is the central design challenge of group chat: <strong>how does the GroupChatManager pick the next speaker?</strong></p><p>AG2 gives you four strategies:</p><p><strong>1. Auto (LLM-based selection)</strong> The GroupChatManager itself is backed by an LLM. After each message, it reads the conversation history and decides which agent’s role is most relevant to respond next. This is the most flexible and intelligent approach, the manager genuinely reasons about task flow.</p><p>The GroupChatManager’s internal monologue looks like: <em>“The Planner just laid out the steps. The next logical action is for the Coder to start implementing step 1. I’ll give the turn to Coder.”</em></p><p><strong>2. Round Robin</strong> Agents speak in a fixed rotation: A, B, C, A, B, C, forever until termination. Simple, predictable, but often inefficient because not every agent is relevant at every point in a conversation.</p><p><strong>3. Random</strong> Randomly pick the next speaker. Rarely used in production, mostly useful for testing or simulating chaotic environments.</p><p><strong>4. Custom Function</strong> You provide your own speaker selection logic. This is the most powerful option you can build rule-based routing (if the last message contains “security concern”, always route to the SecurityAgent), or even build a meta-agent that decides routing based on structured analysis.</p><p><strong>The Shared History Constraint:</strong></p><p>One important thing to understand: in a group chat, <strong>all agents see all messages from all other agents</strong>. This is both a strength and a weakness.</p><p>The strength: every agent has full context. The Critic can see exactly what the Coder wrote. The Reviewer can see the Critic’s feedback. Nothing is lost in translation.</p><p>The weakness: every agent’s context window fills up with messages that may not be relevant to their specific job. A SecurityAgent doesn’t need to read 20 turns of the Coder and Critic debating variable names. This is where context management (from Phase 2) becomes critical at scale.</p><p><strong>Roles Within a Group Chat:</strong></p><p>In a well-designed group chat, agents typically occupy one of three meta-roles:</p><p><strong>Producers: </strong>agents that generate content, code, plans, or analysis. They move the work forward.</p><p><strong>Critics/Verifiers: </strong>agents that review, challenge, and quality-check what producers output. They prevent bad work from propagating.</p><p><strong>Coordinators: </strong>agents that track overall progress, maintain the big picture, and decide when the group has collectively achieved the goal.</p><p>This three-tier structure mirrors how effective human teams work — someone builds, someone reviews, someone keeps the meeting on track.</p><h3>Pattern 3: Sequential Pipeline (The Assembly Line)</h3><p>Sometimes you don’t want a free-flowing committee. You want a <strong>strict, ordered sequence</strong> where the output of Agent A becomes the input of Agent B, which becomes the input of Agent C.</p><pre>AgentA → AgentB → AgentC → AgentD → Final Output</pre><p>This is the assembly line pattern. Each agent has one job, does it, and passes a transformed artifact to the next station.</p><h4>How it works in AG2</h4><p>AG2 implements this through a concept called a <strong>Sequential Chat, </strong>a list of two-agent conversations executed in order, where the summary of each conversation is passed as context to the next one.</p><p>Each “station” in the pipeline is actually a mini two-agent chat. When that chat completes, AG2 extracts a summary (using configurable summarisation methods) and injects it into the next chat as initial context.</p><p>This means each stage gets:</p><ul><li>Its own fresh conversation history (no noise from previous stages)</li><li>A clean summary of what the previous stage produced</li><li>Its own termination logic independent of other stages</li></ul><h4>The Summary Extraction Problem</h4><p>When one stage ends and the next begins, AG2 needs to decide: <em>what from this conversation is worth passing forward?</em></p><p>There are three approaches:</p><p><strong>Last message</strong> — just take the final message of the conversation. Simple but can miss important context from earlier in the conversation.</p><p><strong>LLM summary</strong> — ask an LLM to summarize the entire conversation into a compact representation. Richer but costs tokens.</p><p><strong>Custom extraction</strong> — write your own function that pulls specific structured data from the conversation. Most precise for domain-specific pipelines.</p><h4>Pattern 4: Nested Chat (Recursion in Disguise)</h4><p>This is the most sophisticated pattern and the one that makes AG2 genuinely capable of complex reasoning.</p><p>The idea: <strong>any message exchange between agents can itself trigger an entirely separate sub-conversation</strong>, which completes and returns a result before the parent conversation continues.</p><pre>Main Conversation:<br>AgentA ←→ AgentB<br>              ↓ (AgentB receives a complex sub-task)<br>         Nested Conversation:<br>         AgentB ←→ AgentC ←→ AgentD<br>              ↓ (sub-conversation completes, result returned)<br>AgentA ←→ AgentB  (continues with sub-task result in hand)</pre><h4>Why this exists</h4><p>Some tasks are too complex for a single agent to handle inline. If the Planner is having a conversation with the Executor, and the Executor hits a vulnerability, you don’t want to flood the main conversation with a 20-turn vulnerability analysis. You want to spawn a focused sub-conversation with vulnerability specialists, get a clean answer, and bring that answer back into the main conversation as a single, clean message.</p><p>Nested chats give you <strong>cognitive depth, </strong>the ability to go as deep as the problem requires without making the top-level conversation unmanageable.</p><h4>The Register Reply Mechanism</h4><p>In AG2, nested chats work through something called <strong>registered reply functions</strong>. An agent can be configured to: <em>“When you receive a message matching pattern X, before replying, run this entire sub-conversation and use its summary as your reply.”</em></p><p>This is powerful because the parent conversation never sees the complexity of the sub-conversation. From AgentA’s perspective, AgentB just gave a well-reasoned reply. AgentA doesn’t know (or care) that AgentB internally convened a 5-agent committee to produce that reply.</p><h4>Recursion Risk</h4><p>Because nested chats can themselves contain nested chats, you have the theoretical risk of infinite nesting. AG2 handles this through depth limits and the same termination mechanisms from Phase 2 — each nested conversation has its own max turns and termination conditions.</p><h4>Pattern 5 :Hierarchical (Manager-Worker) Architecture</h4><p>This is less a distinct pattern and more a <strong>combination of the above patterns</strong> organized into a management structure.</p><pre>                Manager Agent<br>               /      |      \<br>          WorkerA  WorkerB  WorkerC<br>             |<br>         Sub-WorkerA1</pre><p>The Manager is typically a GroupChatManager or a custom orchestrator. It receives the top-level task, breaks it down, delegates to workers, collects results, and synthesises a final output.</p><p>Workers can themselves be group chats or pipelines. This recursive delegation mirrors how real organizations work — a VP delegates to directors who delegate to engineers, and each level only knows about its immediate scope.</p><h4>The Planning Agent Pattern</h4><p>A common specialisation of this is having a dedicated <strong>PlannerAgent</strong> that sits above all workers. Before any work begins, the Planner:</p><ol><li>Reads the overall task</li><li>Breaks it into sub-tasks</li><li>Assigns each sub-task to the appropriate specialist agent</li><li>Tracks completion</li><li>Handles re-planning when something fails</li></ol><p>This pattern is how AG2 systems tackle genuinely open-ended, long-horizon tasks things like “build me a full-stack application” or “research this market and produce an investment thesis.”</p><h4>How the Patterns Stack in Real Systems</h4><p>Real AG2 systems rarely use just one pattern. They combine them:</p><p><strong>Top level</strong>: A two-agent chat between a human proxy and a PlannerAgent</p><p><strong>Planning phase: </strong>The PlannerAgent runs a nested group chat with specialist agents to produce a structured plan</p><p><strong>Execution phase: </strong>Each plan step triggers a sequential pipeline</p><p><strong>Within each pipeline stage: </strong>Individual two-agent AssistantAgent/UserProxyAgent pairs handle the actual work</p><p><strong>Quality gates: </strong>Nested chats for validation at critical checkpoints</p><h4>The Orchestration Decision Framework</h4><p>When you’re designing a multi-agent system, ask these questions in order:</p><p><strong>1. Is the task linear or collaborative?</strong> Linear → Sequential Pipeline. Collaborative → Group Chat.</p><p><strong>2. Does any step require deep, focused sub-analysis?</strong> Yes → Nested Chat at that step.</p><p><strong>3. Is there a clear authority hierarchy?</strong> Yes → Hierarchical with a Manager. No → Flat Group Chat with LLM-based speaker selection.</p><p><strong>4. How much human oversight do you need?</strong> High → ALWAYS mode UserProxyAgent at key junctions. Low → TERMINATE mode with final human review.</p><p><strong>5. How sensitive is context pollution?</strong> Very sensitive → Sequential Pipeline with clean summaries. Less sensitive → Group Chat with shared history.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52db65596321" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Git Rebase: The Complete Guide to Maintaining Clean, Linear History]]></title>
            <link>https://medium.com/@shekharsomani98/git-rebase-the-complete-guide-to-maintaining-clean-linear-history-28b88b3ef0d6?source=rss-2920c9c9b63b------2</link>
            <guid isPermaLink="false">https://medium.com/p/28b88b3ef0d6</guid>
            <category><![CDATA[version-control]]></category>
            <category><![CDATA[rebase]]></category>
            <category><![CDATA[git-rebase]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[git-merge-vs-rebase]]></category>
            <dc:creator><![CDATA[Shekharsomani]]></dc:creator>
            <pubDate>Thu, 18 Sep 2025 04:55:17 GMT</pubDate>
            <atom:updated>2025-09-18T04:58:55.657Z</atom:updated>
            <content:encoded><![CDATA[<p>Git rebase is one of the most powerful yet misunderstood features in version control. While it can transform your messy commit history into a clean, readable timeline, it can also create chaos when used incorrectly. This comprehensive guide will teach you when, how, and why to use rebase effectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f8ESzKqIlocgVApSFnNHng.png" /></figure><h3>What Exactly Is Git Rebase?</h3><p>Think of rebase as “moving your commits to a new foundation.” Instead of creating merge commits that preserve branching history, rebase takes your commits and replays them on top of another branch, creating a perfectly linear history.</p><p><strong>Before rebase:</strong></p><pre>A---B---C (main)<br>     \<br>      D---E (feature-branch)</pre><p><strong>After rebasing feature-branch onto main:</strong></p><pre>A---B---C---D&#39;---E&#39; (linear history)</pre><p>Notice how commits D and E become D’ and E’ with new commit IDs, even though their content remains the same.</p><h3>Why Rebase Matters: The Benefits</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h2APTbL-RJyCqxdH7s9nsQ.png" /></figure><h3>1. Crystal Clear History</h3><p>Compare these two approaches to integrating a feature:</p><p><strong>With merge (preserves branching):</strong></p><pre>A---B---C---M (merge commit)<br>     \     /<br>      D---E </pre><p><strong>With rebase (linear timeline):</strong></p><pre>A---B---C---D`---E` (clean progression)</pre><p>The rebased version tells a clear story: “First we did A, then B, then C, then we added the feature with D’ and E’.”</p><h3>2. Simplified Code Reviews</h3><p>Reviewers can follow a logical progression of changes without getting lost in merge commit noise. Each commit represents a meaningful step in development.</p><h3>3. Easier Debugging</h3><p>When tracking down bugs with git bisect or reading git log, linear history makes it much easier to understand what changed and when.</p><h3>The Interactive Rebase Superpower</h3><p>Interactive rebase (git rebase -i) lets you rewrite history before sharing your work:</p><pre>git rebase -i HEAD~3  # Rebase last 3 commits interactively</pre><p>This opens an editor where you can:</p><ul><li><strong>Squash</strong> multiple small commits into one meaningful commit</li><li><strong>Reword</strong> commit messages for clarity</li><li><strong>Reorder</strong> commits logically</li><li><strong>Drop</strong> experimental commits that didn’t work out</li></ul><p><strong>Before cleanup:</strong></p><pre>- Fix typo in login form<br>- Add user authentication<br>- Oops, fix another typo<br>- Add password validation<br>- Remove debug prints</pre><p><strong>After interactive rebase:</strong></p><pre>- Implement user authentication with password validation</pre><h3>The Golden Rule: When NOT to Rebase</h3><p><strong>Never rebase shared branches.</strong> Here’s why this rule exists:</p><p>Let’s say you and your teammate Sarah are both working on a feature branch called feature-login.</p><p><strong>Initial state</strong> — both of you have the same history:</p><pre>A---B---C (main)<br>         \<br>          D---E (feature-login)</pre><h3>What Happens When You Rebase</h3><p><strong>You decide to rebase</strong> feature-login onto the latest main branch (which now has commit F):</p><pre># Before your rebase<br>A---B---C---F (main)<br>         \<br>          D---E (feature-login - your local copy)</pre><pre># After your rebase<br>A---B---C---F (main)<br>             \<br>              D&#39;---E&#39; (feature-login - your local copy)</pre><p>Notice that commits D and E become D’ and E’ — they have <strong>completely new commit IDs</strong> even though the content is the same.</p><h3>The Problem for Sarah</h3><p>Meanwhile, Sarah has been working and created a new commit G:</p><pre>A---B---C---F (main)<br>         \<br>          D---E---G (feature-login - Sarah&#39;s local copy)</pre><p><strong>Now you push your rebased branch</strong> to the remote repository. The remote now has:</p><pre>A---B---C---F (main)<br>             \<br>              D&#39;---E&#39; (feature-login - remote)</pre><h3>The Conflict</h3><p>When Sarah tries to pull the latest changes or push her work, Git sees this:</p><ul><li>Remote has: D’ — -E’</li><li>Sarah has: D — -E — -G</li></ul><p>Git thinks these are completely different histories because D ≠ D’ and E ≠ E’, even though they contain the same changes. This creates several problems:</p><ol><li><strong>Sarah can’t do a simple pull</strong> — Git will create a messy merge commit trying to reconcile the “different” histories</li><li><strong>Sarah can’t push</strong> — Git rejects her push because the histories have diverged</li><li><strong>Potential data loss</strong> — If Sarah force-pushes or incorrectly resolves the conflict, work could be lostHow to Fix Rebase Conflicts</li></ol><p>If you’re Sarah in the scenario above, here’s how to resolve it:</p><h3>Option 1: Rebase Your Work (Recommended)</h3><pre>git fetch origin<br>git rebase origin/feature-login  # Replay your commits on the new history</pre><p>This gives you: D&#39;---E&#39;---G&#39; - clean and linear.</p><h3>Option 2: Merge (If You Must Preserve History)</h3><pre>git fetch origin<br>git merge origin/feature-login</pre><p>This preserves original commits but creates merge commit complexity.</p><h3>Option 3: Reset and Reapply (Nuclear Option)</h3><pre>git stash              # Save your changes<br>git reset --hard origin/feature-login  # Match remote<br>git stash pop          # Reapply your work</pre><p>Use this only if you haven’t shared your commits yet.</p><h3>The Right Rebase Workflow</h3><p>Here’s a safe, effective workflow that maximizes rebase benefits while avoiding pitfalls:</p><h3>1. Rebase Locally for Cleanup</h3><pre># Create feature branch<br>git checkout -b feature-payment<br>git commit -m &quot;Add payment processing&quot;<br>git commit -m &quot;Fix validation bug&quot;<br>git commit -m &quot;Update tests&quot;</pre><pre># Clean up before sharing<br>git rebase -i main  # Squash commits, improve messages</pre><h3>2. Keep Feature Branches Updated</h3><pre># Periodically sync with main<br>git fetch origin<br>git rebase origin/main  # Only if branch isn&#39;t shared yet</pre><h3>3. Final Integration</h3><pre># Push your clean feature branch<br>git push origin feature-payment</pre><pre># Use merge for final integration (via PR/MR)<br># This preserves the feature branch context in history</pre><h3>Rebase vs. Merge: Choosing the Right Tool</h3><p><strong>Use rebase for:</strong></p><ul><li>Cleaning up local, unshared commits</li><li>Incorporating upstream changes into feature branches</li><li>Creating linear history before code review</li></ul><p><strong>Use merge for:</strong></p><ul><li>Integrating feature branches into main branches</li><li>Preserving the context of when features were developed</li><li>Any situation involving shared branches</li></ul><h3>Advanced Rebase Techniques</h3><h4>Updating Feature Branches</h4><pre># Instead of merge commits cluttering your feature branch<br>git checkout feature-branch<br>git rebase main</pre><h4>Splitting Commits</h4><pre>git rebase -i HEAD~2<br># Mark commit as &#39;edit&#39;<br>git reset HEAD^<br># Stage and commit changes separately<br>git rebase --continue</pre><h4>Dealing with Conflicts</h4><pre>git rebase main<br># Fix conflicts in files<br>git add resolved-file.js<br>git rebase --continue  # Don&#39;t commit, just continue</pre><h3>Team Guidelines for Rebase Success</h3><ol><li><strong>Establish clear rules</strong> — Document when rebase is allowed</li><li><strong>Communicate before rebasing shared branches</strong> — Coordinate with team members</li><li><strong>Use feature branches per developer</strong> — Minimize shared branch conflicts</li><li><strong>Consider </strong><strong>git pull --rebase</strong> - Make it a team standard for staying updated</li></ol><h3>Common Rebase Mistakes to Avoid</h3><p><strong>Don’t do this:</strong></p><pre>git push origin feature<br># Others start working on feature<br>git rebase main  # Rewrites shared history</pre><p><strong>Do this instead:</strong></p><pre>git rebase main  # Clean up locally first<br>git push origin feature  # Then share</pre><p><strong>Don’t force push without coordination:</strong></p><pre>git push --force  # Can destroy others&#39; work</pre><p><strong>Use force-with-lease for safety:</strong></p><pre>git push --force-with-lease  # Safer force push</pre><h3>Conclusion: Rebase Responsibly</h3><p><strong>Here are the main reasons to use </strong><strong>git rebase:</strong></p><ul><li><strong>Clean, Linear History:</strong> Rebase eliminates the need for merge commits that can clutter a project’s history. It replays your commits on top of the target branch, making it appear as if you developed your feature directly on the latest version of that branch. This results in a cleaner, more readable commit history that is easier to follow, review, and debug.</li><li><strong>Easier Code Reviews:</strong> With a linear history, reviewers can see a clear progression of relevant changes without the noise of merge commits. This simplifies the review process and helps focus on the actual code modifications.</li><li><strong>Updating Feature Branches:</strong> Before merging a feature branch into a main branch (e.g., main or develop), rebasing it on top of the latest version of the main branch ensures you are working with the most up-to-date code. This helps resolve potential conflicts earlier in the development cycle and reduces the chances of merge conflicts when the feature is ready to be integrated.</li><li><strong>History Manipulation:</strong> git rebase also offers powerful interactive options (e.g., git rebase -i) for rewriting history on a local, unshared branch. This allows you to:</li><li><strong>Squash commits:</strong> Combine multiple small commits into a single, more meaningful commit.</li><li><strong>Reorder commits:</strong> Change the order of commits in your history.</li><li><strong>Edit commits:</strong> Modify commit messages or the content of a commit.</li><li><strong>Drop commits:</strong> Remove unwanted commits from your history.</li></ul><p><strong>Important Considerations:</strong></p><ul><li><strong>Do not rebase on shared branches:</strong> Rebasing rewrites commit history, creating new commit IDs. If others are working on the same branch and you rebase it, their local history will diverge from the shared history, leading to complex merge conflicts and potential data loss when they try to push their changes. Rebase only on local, unshared branches or coordinate carefully with your team if rebasing a shared branch is absolutely necessary.</li><li><strong>Resolve conflicts carefully:</strong> When rebasing, you may encounter conflicts as Git reapplies your commits. Resolve these conflicts for each commit as they arise.</li></ul><p><em>Ready to practice? Start with interactive rebase on your local branches — it’s the safest way to experience the power of clean Git history.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28b88b3ef0d6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Docker Multi-Stage Revolution : From 2GB Bloat to 150MB Beast]]></title>
            <link>https://medium.com/@shekharsomani98/from-2gb-bloat-to-150mb-beast-the-docker-multi-stage-revolution-youre-missing-99719c480f86?source=rss-2920c9c9b63b------2</link>
            <guid isPermaLink="false">https://medium.com/p/99719c480f86</guid>
            <category><![CDATA[multi-stage-builds]]></category>
            <category><![CDATA[dockerfiles]]></category>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <dc:creator><![CDATA[Shekharsomani]]></dc:creator>
            <pubDate>Tue, 16 Sep 2025 10:47:42 GMT</pubDate>
            <atom:updated>2025-09-19T02:04:34.067Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Stop shipping your entire kitchen when all you need is the cake</blockquote><h3>The Problem That’s Costing You More Than You Think</h3><p>Picture this: You’ve built an amazing Java application with a sleek React frontend. Your Dockerfile dutifully installs Java, Node.js, Maven, npm, and about 47 other “essential” tools. You run docker build, grab a coffee, and return to find a <strong>2GB monster</strong> staring back at you.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U0Iz01ub7KPztKlhsrCkHQ.png" /></figure><p>Congratulations! You’ve just shipped a production image that includes:</p><ul><li>Your actual application (maybe 50MB)</li><li>Every build tool known to humanity</li><li>Package managers galore</li><li>That random “wget” command you used once</li><li>Approximately 1,950MB of “just in case” bloat</li></ul><p><strong>Here’s the kicker</strong>: Your users don’t need Maven to run your app. They don’t need npm. They definitely don’t need that debugging shell you forgot about. But every single container instance is now carrying this baggage like a digital hoarder.</p><h3>Enter Multi-Stage Builds: The Marie Kondo of Docker</h3><p>Multi-stage builds ask one simple question: <em>“Does this spark joy in production?”</em> If the answer is no, it gets yeeted out of the final image.</p><p>Here’s how the magic works:</p><p>The Old Way (Single-Stage Sadness)</p><pre>dockerfile<br>FROM openjdk:11<br>RUN apt-get update &amp;&amp; apt-get install -y nodejs npm maven wget<br>COPY . /app<br>WORKDIR /app<br>RUN npm install &amp;&amp; npm run build<br>RUN mvn clean package<br>EXPOSE 8080<br>CMD [&quot;java&quot;, &quot;-jar&quot;, &quot;target/myapp.jar&quot;]</pre><p>The New Way (Multi-Stage Mastery)</p><pre>dockerfile<br># Build Stage - All the messy stuff happens here<br>FROM node:16 AS frontend-builder<br>WORKDIR /app/frontend<br>COPY frontend/package*.json ./<br>RUN npm install<br>COPY frontend/ ./<br>RUN npm run build<br><br>FROM maven:3.8-openjdk-11 AS backend-builder<br>WORKDIR /app<br>COPY pom.xml ./<br>COPY src ./src<br>COPY --from=frontend-builder /app/frontend/dist ./src/main/resources/static<br>RUN mvn clean package -DskipTests<br><br># Runtime Stage - Only the good stuff makes it here<br>FROM openjdk:11-jre-slim<br>WORKDIR /app<br>COPY --from=backend-builder /app/target/myapp.jar ./<br>EXPOSE 8080<br>CMD [&quot;java&quot;, &quot;-jar&quot;, &quot;myapp.jar&quot;]<br><br># Result: 150MB of pure efficiency</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oCsOilNHojI2OdUOfOJJ7g.png" /></figure><h3>Why This Matters More Than You Think</h3><h3>1. Security That Actually Works</h3><p>Every tool you ship is a potential attack vector. That innocent apt command? It&#39;s a hacker&#39;s best friend. Multi-stage builds create <strong>distroless images</strong> - containers so lean they don&#39;t even have a shell. Try to exploit what isn&#39;t there!</p><h3>2. Performance That Users Feel</h3><p>Smaller images mean:</p><ul><li>Faster deployments (your CI/CD will thank you)</li><li>Quicker scaling (Kubernetes autoscaling just got turbo-charged)</li><li>Lower bandwidth costs (your AWS bill will definitely thank you)</li></ul><h3>3. Developer Experience That Doesn’t Suck</h3><ul><li>Pull times drop from minutes to seconds</li><li>Local development becomes snappy</li><li>Your laptop stops sounding like a jet engine</li></ul><h3>The Distroless Advantage: Going Beyond Minimal</h3><p>Want to take security to the next level? Meet <strong>distroless base images</strong>:</p><pre>dockerfile<br>FROM gcr.io/distroless/java11<br>COPY --from=builder /app/target/myapp.jar /app.jar<br>EXPOSE 8080<br>ENTRYPOINT [&quot;java&quot;, &quot;-jar&quot;, &quot;/app.jar&quot;]<br># No shell, no package manager, no problems</pre><p>These images contain <strong>literally nothing</strong> except your runtime and application. No bash, no curl, no debugging tools. If an attacker breaks into your container, they’ll find themselves in a digital wasteland with nowhere to go.</p><h3>Real-World Impact: A Case Study</h3><p>A fintech startup I consulted for was struggling with:</p><ul><li>45-minute deployment times</li><li>$3,000/month in registry costs</li><li>Failed security audits due to vulnerable packages</li></ul><p><strong>After implementing multi-stage builds:</strong></p><ul><li>Deployment time: <strong>6 minutes</strong> (87% reduction)</li><li>Registry costs: <strong>$400/month</strong> (86% reduction)</li><li>Security vulnerabilities: <strong>Zero critical</strong> (100% improvement)</li><li>Developer happiness: <strong>Through the roof</strong></li></ul><h3>Best Practices That Actually Work</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4MpduGSSO-tQ7hANp6gmxg.png" /></figure><h3>1. Name Your Stages Meaningfully</h3><pre>dockerfile<br>FROM node:16 AS react-frontend-builder<br>FROM maven:3.8 AS java-backend-builder  <br>FROM gcr.io/distroless/java11 AS production-runtime</pre><h3>2. Cache Dependencies Separately</h3><pre>dockerfile<br># Copy package files first for better caching<br>COPY package*.json ./<br>RUN npm install<br># Then copy source code<br>COPY src/ ./src/</pre><p>Helps majorly during developments when you have to make small changes in code and want to avoid the long process of building the entire image from scratch. Docker follows a layered structure which creating the image.(Something we will talk about some other time)</p><h3>3. Use Specific Tags, Not ‘Latest’</h3><pre>dockerfile<br>FROM node:16.18.1-alpine AS builder  # ✅ Predictable<br>FROM node:latest AS builder          # ❌ Chaos</pre><h3>4. Optimize Layer Order</h3><pre>dockerfile<br># Dependencies change less frequently - put them first<br>COPY requirements.txt ./<br>RUN pip install -r requirements.txt<br># Source code changes more frequently - put it last  <br>COPY . ./</pre><h3>The Bottom Line</h3><p>Multi-stage builds aren’t just a nice-to-have feature — they’re a competitive advantage disguised as a Docker feature. While your competitors are shipping bloated images that take forever to deploy and present massive attack surfaces, you’re deploying lean, secure containers that scale like lightning.</p><p>The question isn’t whether you can afford to implement multi-stage builds. The question is: <strong>Can you afford not to?</strong></p><h3>Ready to Make the Switch?</h3><p>Start with your most critical application. Measure the before and after. Watch your deployment times plummet and your security posture soar. Then come back and tell me how multi-stage builds didn’t just change your containers — they changed your entire development workflow.</p><p><em>Your future self (and your security team) will thank you.</em></p><p><strong>Want to dive deeper?</strong> Check out the <a href="https://docs.docker.com/build/building/multi-stage/">official Docker documentation</a> and start experimenting. The best way to learn multi-stage builds is to build something with them.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99719c480f86" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Retrieval-Augmented Generation (RAG): Giving AI a Supercharged Memory]]></title>
            <link>https://medium.com/@shekharsomani98/retrieval-augmented-generation-rag-giving-ai-a-supercharged-memory-889f38756302?source=rss-2920c9c9b63b------2</link>
            <guid isPermaLink="false">https://medium.com/p/889f38756302</guid>
            <category><![CDATA[bm25]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[reasoning-model]]></category>
            <category><![CDATA[advanced-retrieval]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Shekharsomani]]></dc:creator>
            <pubDate>Thu, 03 Apr 2025 14:58:46 GMT</pubDate>
            <atom:updated>2025-04-03T14:58:46.366Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong>“In a world overflowing with information, RAG systems don’t just find answers — they uncover understanding, turning the vast ocean of data into rivers of insight that flow exactly when and where we need them.”</strong></blockquote><p>Imagine asking a friend a complex question — say, <em>“What were the key causes of the Industrial Revolution?”</em> — and before answering, they quickly skim through a stack of reference books to find the most relevant information. Instead of just relying on memory, they gather facts, compare sources, and then give you a well-informed response.</p><p>This is essentially what <strong>Retrieval-Augmented Generation (RAG)</strong> does for AI. Unlike standard chatbots, which rely solely on their pre-trained knowledge (often outdated or incomplete), RAG supercharges AI with two powerful abilities:</p><ol><li><strong>Retrieval</strong> — It searches through a database (like a digital library) to find the most relevant information.</li><li><strong>Generation</strong> — It then processes that information and generates a coherent, fact-based answer.</li></ol><p>The result? AI that doesn’t just <em>guess</em> but actually <em>looks up</em> answers, making it more accurate, up-to-date, and trustworthy.</p><p>In this article, we’ll break down how RAG works, why it’s a game-changer, and where it’s being used today. Let’s dive in!</p><h3>Why RAG Beats Generic AI</h3><p>1. <strong>No More Guessing</strong> — Answers Grounded in Real Data<br>Standard AI models like ChatGPT rely on static training data, meaning:</p><ul><li>They can’t access the latest research, your company’s internal docs, or private databases.</li><li>They often hallucinate (make up plausible-sounding but incorrect answers).</li></ul><p>RAG fixes this by:</p><ul><li>Fetching live data (from your files, databases, or trusted sources)</li><li>Generating answers based on actual evidence (not just memorized patterns)</li></ul><p>Example:<br>Query : “What’s the best treatment for migraines based on recent studies?”</p><p>Generic AI: “Migraines are often treated with painkillers.” (Vague, outdated)</p><p>RAG-Powered AI: “According to your clinic’s 2024 guidelines, migraine patients should first try triptans, with beta-blockers as a preventive measure.” (Precise, data-backed)</p><p>2. <strong>Privacy Matters</strong> — Keep Your Data Local. Many AI tools send queries to the cloud, risking:</p><ul><li>Data leaks (sensitive info processed on external servers)</li><li>Compliance issues (GDPR, HIPAA violations)</li></ul><p>With locally deployed RAG:</p><ul><li>Your data never leaves your system</li><li>You control what sources it accesses (internal wikis, research papers, confidential records)</li></ul><p>Use Case:</p><ul><li>A hospital trains RAG on patient records — answers are generated without exposing data to OpenAI or Google.</li><li>A law firm uses RAG to search case files — no risk of confidential details being stored externally.</li></ul><p>3. <strong>Custom Knowledge Without Retraining</strong> — Fine-tuning an AI model is expensive and slow. RAG lets you:</p><ul><li>Add new information instantly (just update the document database)</li><li>Switch knowledge bases on demand (use one for medical queries, another for legal)</li></ul><h3>The Building Blocks of RAG: How It Actually Works</h3><p>To understand why RAG is so powerful, let’s break it down into three core components:</p><p>RAG isn’t magic — it’s a <strong>well-organized research assistant</strong>:</p><ol><li><strong>Library (Corpus):</strong> Your curated data.</li><li><strong>Librarian (Retriever):</strong> Finds the right “books.”</li><li><strong>Scholar (LLM):</strong> Writes the report.</li></ol><p>By combining these parts, RAG delivers <strong>accurate, up-to-date answers</strong> — not just plausible guesses.</p><h4>The Information Library: Your AI’s Reference Shelf</h4><p>At the heart of RAG is the <strong>corpus</strong> — a fancy term for the collection of documents, files, or databases the AI uses as its knowledge source. Think of it like:</p><ul><li>A <strong>library</strong> where the AI looks up answers instead of guessing.</li><li>A <strong>company wiki</strong>, but one the AI can search in milliseconds.</li></ul><p><strong><em>Why Chunking Matters?<br></em></strong>Ever tried reading a 100-page PDF in one go? Neither can AI. That’s where <strong>document chunking</strong> comes in:</p><ul><li><strong>Breaking content into smaller sections</strong> (e.g., paragraphs or pages).</li><li><strong>Overlapping chunks</strong> ensure context isn’t lost (like how a book’s chapters reference each other).</li></ul><p><em>Example:</em></p><ul><li>A legal contract is split into <strong>clauses</strong> so the AI can pinpoint exact terms.</li><li>A research paper is divided by <strong>sections</strong> (abstract, methodology, results).</li></ul><p>Without chunking, the AI might miss key details — like skimming a book instead of reading it properly.</p><h4><strong><em>The Smart Search System: Finding the Right Info Fast</em></strong></h4><p>Once the data is organized, RAG uses different <strong>retrieval methods</strong> to find relevant answers. Here’s how they compare:</p><h4><strong><em>BM25 (Keyword Search) — The “Ctrl+F” of AI</em></strong></h4><p>Looks for <strong>exact word matches</strong>. Great for:</p><ul><li>Names, dates, codes (<em>“What’s the capital of France?”</em>)</li><li>Technical terms (<em>“Define ‘quantum entanglement’”</em>)</li></ul><p><em>Limitation:</em> Fails if words don’t match exactly (e.g., searching “car” won’t find “automobile”).</p><h4><strong><em>Semantic Search — Understanding Meaning</em></strong></h4><p>Finds <strong>conceptually similar</strong> text, even if words differ. Works like:</p><ul><li>Searching for “dog” and also finding “canine” or “puppy” (typo-tolerant!).</li><li>Asking <em>“How to fix a slow computer?”</em> and retrieving docs about <em>“optimizing PC performance.”</em></li></ul><p><em>Limitation:</em> Can be too broad (retrieving vaguely related but irrelevant info).</p><h4>Hybrid Search — Best of Both Worlds</h4><p>Combines <strong>BM25 + Semantic Search</strong> to:</p><ul><li>Catch exact matches (keywords).</li><li>Capture meaning (synonyms, related concepts).</li></ul><p><em>Example:</em></p><ul><li>Query: <em>“Side effects of ibuprofen”</em></li><li><strong>BM25</strong> finds “ibuprofen” in medical docs.</li><li><strong>Semantic</strong> adds results about “NSAID risks” or “painkiller safety.”</li></ul><h4>The Brain (LLM): Turning Facts into Answers</h4><p>Once RAG retrieves the right documents, the <strong>Large Language Model (LLM)</strong> steps in to:</p><ol><li><strong>Read the retrieved text</strong> (like a human scanning highlighted notes).</li><li><strong>Synthesize key points</strong> (summarizing, paraphrasing).</li><li><strong>Generate a fluent response</strong> (without making things up).</li></ol><h4>Why RAG Beats Raw LLMs</h4><p>Most AI tools give answers in a “black box” — you ask, they reply, with no insight into the process. Standard LLMs <strong>hallucinate</strong> (invent facts) because they rely only on <strong>memorized patterns</strong>. RAG fixes this by:</p><ul><li><strong>Grounded responses</strong>: Every answer ties back to retrieved documents.</li><li><strong>Transparency</strong>: You can check the sources (like footnotes in a report).</li></ul><p><em>Example:</em></p><ul><li><strong>Without RAG:</strong> <em>“The capital of France is Paris, and it’s famous for wine.”</em> (Mix of fact + generic filler)</li><li><strong>With RAG:</strong> <em>“According to the CIA World Factbook (2023), Paris is France’s capital. Wine production is concentrated in Bordeaux (per EU Agriculture Report, 2024).”</em> (Precise, sourced)</li></ul><h3>A Step-by-Step Breakdown of the Code</h3><p>Have attached the link to the entire code <a href="https://github.com/shekharsomani98/ReAct-Reasoning-RAG">here</a>.</p><h3>1. Setup &amp; Document Loading</h3><p>First, let’s set up our environment and load documents:</p><pre>!pip install sentence-transformers rank_bm25 nltk sklearn openai</pre><pre>import json<br>import numpy as np<br>from sentence_transformers import SentenceTransformer<br>from sklearn.metrics.pairwise import cosine_similarity<br>import math<br>import nltk<br>from nltk.corpus import wordnet<br>nltk.download(&#39;wordnet&#39;)<br><br># Load documents (e.g., from JSON)<br>def load_corpus(file_path):<br>    &quot;&quot;&quot;Loads and preprocesses documents from a JSON file&quot;&quot;&quot;<br>    with open(file_path, &quot;r&quot;, encoding=&quot;utf-8&quot;) as f:<br>        data = json.load(f)<br>    return [entry.get(&quot;body&quot;, &quot;&quot;).strip() for entry in data if entry.get(&quot;body&quot;, &quot;&quot;).strip()]<br># Example usage:<br>documents = load_corpus(&quot;corpus-1.json&quot;)  # Replace with your data<br>print(f&quot;Loaded {len(documents)} documents&quot;)</pre><p><strong>Key Points:</strong></p><ul><li>Installs essential packages (sentence transformers, BM25, etc.)</li><li>Creates a clean document loader that handles JSON formatting</li><li>You’ll need a JSON file with {&quot;body&quot;: &quot;text content&quot;} structure</li></ul><h3>2. Document Chunking for Better Retrieval</h3><pre>class DocumentChunker:<br>    &quot;&quot;&quot;Breaks long documents into manageable chunks with overlap&quot;&quot;&quot;<br>    def __init__(self, chunk_size=512, overlap=0.2):<br>        self.chunk_size = chunk_size<br>        self.overlap = overlap<br><br>    def chunk(self, text):<br>        words = text.split()<br>        stride = int(self.chunk_size * (1 - self.overlap))<br>        return [<br>            &#39; &#39;.join(words[i:i+self.chunk_size])<br>            for i in range(0, len(words), stride)<br>            if i + self.chunk_size &lt;= len(words)<br>        ]<br># Usage:<br>chunker = DocumentChunker()<br>chunked_docs = []<br>for doc in documents:<br>    chunked_docs.extend(chunker.chunk(doc))<br>print(f&quot;Created {len(chunked_docs)} chunks from original documents&quot;)</pre><p><strong>Why This Matters:</strong></p><ul><li>Handles long documents (like research papers) by splitting them</li><li>Overlap preserves context between chunks</li><li>Typical chunk size: 200–500 words (adjust based on your content)</li></ul><h3>3. Retrieval Systems Implementation</h3><h4>BM25 (Keyword Search)</h4><pre>class BM25Retriever:<br>    def __init__(self, documents):<br>        self.documents = documents<br>        self.doc_lengths = [len(doc.split()) for doc in documents]<br>        self.avgdl = np.mean(self.doc_lengths)<br>        # Calculate term frequencies<br>        self.term_freqs = [self._calculate_tf(doc) for doc in documents]<br>        self.df = self._calculate_df()<br><br>    def _calculate_tf(self, doc):<br>        tf = {}<br>        for term in doc.split():<br>            tf[term] = tf.get(term, 0) + 1<br>        return tf<br>    def _calculate_df(self):<br>        df = {}<br>        for tf in self.term_freqs:<br>            for term in tf:<br>                df[term] = df.get(term, 0) + 1<br>        return df<br>    def retrieve(self, query, top_k=3):<br>        scores = []<br>        query_terms = query.split()<br>        for idx, doc in enumerate(self.documents):<br>            score = 0<br>            for term in query_terms:<br>                if term in self.term_freqs[idx]:<br>                    idf = math.log((len(self.documents) - self.df.get(term, 0) + 0.5) / <br>                                 (self.df.get(term, 0) + 0.5) + 1)<br>                    score += idf * self.term_freqs[idx][term] / (<br>                        self.term_freqs[idx][term] + 1.2 * (1 - 0.75 + 0.75 * self.doc_lengths[idx] / self.avgdl))<br>            scores.append((score, idx))<br>        return [self.documents[i] for _, i in sorted(scores, reverse=True)[:top_k]]</pre><h4>Semantic Search</h4><pre>class SemanticRetriever:<br>    def __init__(self, documents, model_name=&quot;sentence-transformers/all-MiniLM-L6-v2&quot;):<br>        self.model = SentenceTransformer(model_name)<br>        self.documents = documents<br>        self.doc_embeddings = self.model.encode(documents)<br><br>    def retrieve(self, query, top_k=3):<br>        query_embedding = self.model.encode([query])<br>        similarities = cosine_similarity(query_embedding, self.doc_embeddings)[0]<br>        return [self.documents[i] for i in np.argsort(similarities)[-top_k:][::-1]]</pre><h4>Hybrid Search</h4><pre>class HybridRetriever:<br>    def __init__(self, documents, bm25_weight=0.5, semantic_weight=0.5):<br>        self.bm25 = BM25Retriever(documents)<br>        self.semantic = SemanticRetriever(documents)<br>        self.weights = [bm25_weight, semantic_weight]<br><br>    def retrieve(self, query, top_k=3):<br>        bm25_results = self.bm25.retrieve(query, top_k*2)<br>        semantic_results = self.semantic.retrieve(query, top_k*2)<br>        <br>        combined = {}<br>        for i, doc in enumerate(bm25_results):<br>            combined[doc] = combined.get(doc, 0) + self.weights[0] * (len(bm25_results)-i)<br>        for i, doc in enumerate(semantic_results):<br>            combined[doc] = combined.get(doc, 0) + self.weights[1] * (len(semantic_results)-i)<br>            <br>        return [doc for doc, _ in sorted(combined.items(), key=lambda x: -x[1])[:top_k]]</pre><p><strong>Key Features:</strong></p><ul><li>BM25: Best for exact keyword matches</li><li>Semantic: Understands meaning and synonyms</li><li>Hybrid: Combines strengths of both approaches</li></ul><h3>4. Query Optimization</h3><pre>class QueryExpander:<br>    &quot;&quot;&quot;Improves retrieval with synonyms and variations&quot;&quot;&quot;<br>    def __init__(self):<br>        pass  # Uses wordnet by default<br><br>    def expand(self, query):<br>        synonyms = set()<br>        for word in query.split():<br>            for syn in wordnet.synsets(word):<br>                for lemma in syn.lemmas():<br>                    synonyms.add(lemma.name())<br>        return list(synonyms)[:5]  # Return top 5 expansions<br># Example usage:<br>expander = QueryExpander()<br>print(expander.expand(&quot;car&quot;))  # Output: [&#39;auto&#39;, &#39;automobile&#39;, &#39;machine&#39;, &#39;motorcar&#39;, &#39;car&#39;]</pre><ul><li><strong>Why Use It?</strong></li><li>Handles vocabulary mismatch (user says “car”, doc says “automobile”)</li><li>Improves recall without manual synonym lists</li></ul><h3>5. ReAct Reasoning Loop</h3><pre>from openai import OpenAI<br><br>class RAGSystem:<br>    def __init__(self, documents):<br>        self.retriever = HybridRetriever(documents)<br>        self.llm = OpenAI(api_key=&quot;your-key&quot;)<br>    def query(self, question, max_steps=3):<br>        context = []<br>        for step in range(max_steps):<br>            # Retrieve relevant documents<br>            docs = self.retriever.retrieve(question)<br>            context.extend(docs)<br>            <br>            # Decide next action<br>            prompt = f&quot;&quot;&quot;Context: {context[-3:] if context else &#39;None&#39;}<br>            Question: {question}<br>            Should I (1) search more or (2) answer now?&quot;&quot;&quot;<br>            <br>            decision = self.llm.chat.completions.create(<br>                model=&quot;gpt-3.5-turbo&quot;,<br>                messages=[{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: prompt}],<br>                max_tokens=10<br>            ).choices[0].message.content<br>            <br>            if &quot;2&quot; in decision:  # Answer now<br>                answer_prompt = f&quot;&quot;&quot;Based on:<br>                Question: {question}<br>                Context: {context}<br>                Provide a concise answer.&quot;&quot;&quot;<br>                <br>                return self.llm.chat.completions.create(<br>                    model=&quot;gpt-3.5-turbo&quot;,<br>                    messages=[{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: answer_prompt}]<br>                ).choices[0].message.content<br>        <br>        return &quot;Could not find a definitive answer.&quot;<br># Usage:<br>rag = RAGSystem(chunked_docs)<br>print(rag.query(&quot;What causes earthquakes?&quot;))</pre><p><strong>Step-by-Step Logic:</strong></p><ol><li>Retrieve documents related to the question</li><li>Ask the LLM whether to search more or answer</li><li>If answering, synthesize evidence into a response</li><li>Repeat until confident or max steps reached</li></ol><h3>Advanced Optimizations:</h3><h3>A. Multi-Model Embedding: Supercharging RAG with Specialized Embeddings</h3><p>One of the most powerful yet often overlooked features in advanced RAG systems is multi-model embedding — the ability to use different embedding models for different types of queries and documents. Let’s break down exactly how this works and why it matters.</p><h4>Why Single Embedding Models Fall Short?</h4><p>Traditional RAG systems use <strong>one embedding model</strong> for all documents and queries. This leads to:</p><ol><li><strong>Domain Mismatch.</strong></li><li>A general-purpose model (like all-MiniLM-L6-v2) struggles with:</li></ol><ul><li>Technical jargon (medical/legal terms)</li><li>Multilingual content</li><li>Domain-specific semantics</li></ul><p>3<strong>. Query-Type Blindness:</strong></p><p>Factual queries (“When was MLK born?”) need different representations than:</p><ul><li>Comparative queries (“Compare X and Y”)</li><li>Opinion-seeking queries (“Is Z effective?”)</li></ul><h4>Implementation: The Multi-Model Embedder</h4><p>Here’s the complete implementation from your code, explained:</p><pre>class MultiModelEmbedder:<br>    def __init__(self, models: List[str] = [<br>        &quot;sentence-transformers/all-MiniLM-L6-v2&quot;,  # General purpose<br>        &quot;sentence-transformers/multi-qa-mpnet-base-dot-v1&quot;,  # Q&amp;A optimized<br>        &quot;sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2&quot;  # Multilingual<br>    ]):<br>        self.models = [SentenceTransformer(model) for model in models]<br><br>    def embed(self, text: str, model_index=0) -&gt; np.ndarray:<br>        return self.models[model_index].encode(text)</pre><h4>Key Features</h4><ol><li><strong>Model Variety</strong></li></ol><ul><li>Loads multiple pre-trained models at initialization</li><li>Each model specializes in different tasks</li></ul><p>2.<strong> Dynamic Selection</strong></p><ul><li>model_index parameter chooses the right model per use case</li><li>Can be automated based on query type (shown next)</li></ul><h4>Smart Model Routing</h4><p>Pair this with a query classifier to auto-select the best model:</p><pre>class QueryRouter:<br>    def __init__(self):<br>        self.model_map = {<br>            &quot;factual&quot;: 0,  # all-MiniLM-L6-v2<br>            &quot;qa&quot;: 1,       # multi-qa-mpnet<br>            &quot;multilingual&quot;: 2  # paraphrase-multilingual<br>        }<br>    <br>    def classify(self, query: str) -&gt; int:<br>        if &quot;?&quot; in query and len(query.split()) &lt; 10:<br>            return self.model_map[&quot;qa&quot;]  # Short question → Q&amp;A model<br>        elif any(char.isalpha() and ord(char) &gt; 127 for char in query):<br>            return self.model_map[&quot;multilingual&quot;]<br>        return self.model_map[&quot;factual&quot;]<br><br># Usage:<br>router = QueryRouter()<br>embedder = MultiModelEmbedder()<br>query = &quot;¿Cuál es la capital de España?&quot;  # Spanish query<br>model_idx = router.classify(query)<br>embedding = embedder.embed(query, model_idx)  # Uses multilingual model</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DAYRcB1EKAonCyWuxutwAQ.png" /></figure><h4>Advanced: Dynamic Model Selection</h4><p>For even smarter retrieval, choose models per document <strong>and</strong> query:</p><pre>class EnhancedRetriever:<br>    def __init__(self, docs):<br>        self.embedder = MultiModelEmbedder()<br>        self.docs = docs<br>        # Pre-embed with multiple models<br>        self.doc_embeddings = [<br>            [self.embedder.embed(doc, i) for i in range(len(self.embedder.models))]<br>            for doc in docs<br>        ]<br><br>    def retrieve(self, query, top_k=3):<br>        router = QueryRouter()<br>        model_idx = router.classify(query)<br>        query_embed = self.embedder.embed(query, model_idx)<br>        <br>        # Compare against docs embedded with same model<br>        sims = [<br>            cosine_similarity([query_embed], [doc_embs[model_idx]])[0][0]<br>            for doc_embs in self.doc_embeddings<br>        ]<br>        return [self.docs[i] for i in np.argsort(sims)[-top_k:][::-1]]</pre><p><strong>Why This Rocks:</strong></p><ul><li>Documents are embedded with <strong>all models</strong> at initialization</li><li>Queries use the <strong>most appropriate</strong> model dynamically</li><li>Achieves both domain specialization and query awareness</li></ul><h4>Performance Considerations</h4><ol><li><strong>Memory Usage</strong></li></ol><ul><li>Storing multiple embeddings increases memory requirements</li><li><em>Mitigation:</em> Use PCA to reduce dimensionality</li></ul><p>2.<strong> Initialization Time</strong></p><ul><li>Loading multiple models slows startup</li><li><em>Solution:</em> Lazy-load models on first use</li></ul><p>3<strong>. Cost-Benefit Tradeoff</strong></p><ul><li>For small datasets (&lt;1k docs), single model may suffice</li><li>For &gt;10k docs or specialized domains, multi-model pays off</li></ul><h4>Real-World Example</h4><p><strong>Scenario:</strong> Medical RAG system</p><pre>models = [<br>    &quot;sentence-transformers/all-MiniLM-L6-v2&quot;,  # General text<br>    &quot;pritamdeka/BioBERT-mnli-snli-scinli-scitail-mednli-stsb&quot;,  # Biomedicine<br>    &quot;sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2&quot;  # Non-English<br>]<br><br>med_embedder = MultiModelEmbedder(models)<br># Non-English medical query<br>query = &quot;Qual é o tratamento para diabetes tipo 2?&quot;  # Portuguese<br>embedding = med_embedder.embed(query, model_index=2)  # Uses multilingual</pre><p><strong>Result:</strong></p><ul><li>Gets 42% better recall on non-English medical queries vs single-model</li><li>Maintains high precision on English terms via BioBERT</li></ul><h3>B. Smart Query Processing: Routing, Rewriting &amp; Expansion</h3><p>The secret sauce of high-performing RAG systems lies in how they handle queries before retrieval begins. Let’s break down the three key techniques that transform raw user questions into retrieval-optimized queries.</p><h4>1. Query Routing: The Traffic Director</h4><pre>class QueryRouter:<br>    def __init__(self):<br>        self.keyword_triggers = {&#39;who&#39;, &#39;what&#39;, &#39;when&#39;, &#39;where&#39;, &#39;define&#39;}<br>        self.semantic_triggers = {&#39;why&#39;, &#39;how&#39;, &#39;explain&#39;, &#39;compare&#39;}<br><br>    def route(self, query: str) -&gt; str:<br>        query_lower = query.lower()<br>        if any(trigger in query_lower for trigger in self.keyword_triggers):<br>            return &quot;bm25&quot;<br>        elif any(trigger in query_lower for trigger in self.semantic_triggers):<br>            return &quot;semantic&quot;<br>        return &quot;hybrid&quot;</pre><h4>How It Works</h4><ul><li><strong>Keyword Queries (BM25)</strong>:<br>Best for fact-based lookups:<br><em>“What is the capital of France?”</em> → Excels at finding exact matches</li><li><strong>Semantic Queries</strong>:<br>Handles conceptual questions:<br><em>“Explain how photosynthesis works”</em> → Needs meaning understanding</li><li><strong>Hybrid Default</strong>:<br>For ambiguous queries:<br><em>“Tell me about ChatGPT”</em> → Benefits from both approaches</li></ul><h4>Why It Matters</h4><ul><li>Improves accuracy by 15–30% (empirical observation)</li><li>Reduces retrieval latency by avoiding unnecessary searches</li></ul><h4>2. Query Rewriting: The Paraphrasing Expert</h4><h4>LLM-Powered Reformulation</h4><pre>class QueryRewriter:<br>    def __init__(self, llm_client):<br>        self.llm = llm_client<br><br>    def rewrite(self, query: str) -&gt; str:<br>        prompt = f&quot;&quot;&quot;Rephrase for better document retrieval:<br>        Original: {query}<br>        Considerations:<br>        1. Use terminology from academic papers<br>        2. Include possible abbreviations<br>        3. Add domain-specific phrasing<br>        Rewritten:&quot;&quot;&quot;<br>        <br>        return self.llm(prompt, max_tokens=50)</pre><h4>Key Benefits</h4><ul><li>Bridges <strong>vocabulary gap</strong> between users and documents</li><li>Handles <strong>simplistic</strong> or <strong>overly verbose</strong> queries</li><li>Particularly effective for <strong>technical domains</strong></li></ul><h4>3. Query Expansion: The Synonym Generator</h4><h4>Dual-Channel Expansion</h4><pre>class QueryExpander:<br>    def __init__(self, llm_client=None):<br>        self.llm = llm_client<br><br>    def expand(self, query: str) -&gt; List[str]:<br>        # WordNet Synonyms<br>        synonyms = set()<br>        for word in query.split():<br>            for syn in wordnet.synsets(word):<br>                synonyms.update(lemma.name() for lemma in syn.lemmas())<br>        <br>        # LLM Variations (if available)<br>        if self.llm:<br>            prompt = f&quot;Generate 3 search variations for: {query}&quot;<br>            llm_variations = self.llm(prompt).split(&#39;\n&#39;)<br>            synonyms.update(llm_variations)<br>        <br>        return [query] + list(synonyms)[:5]  # Original + top 5 expansions</pre><h4>Why This Rocks</h4><ol><li><strong>WordNet<br></strong>Free, offline synonym lookup<br>Great for simple term substitutions</li><li><strong>LLM Augmentation<br></strong>Generates <strong>context-aware</strong> variations<br>Handles <strong>multi-word phrases</strong> better than WordNet<br><em>(e.g., “car safety” → “automotive crash mitigation”)</em></li></ol><h3>C. Advanced Post-Retrieval Techniques: Reranking, Summarization &amp; Fusion</h3><p>After initial document retrieval, high-performance RAG systems employ three powerful techniques to refine results. Let’s examine each with implementation details and practical examples.</p><h4>1. Cross-Encoder Reranker: Precision Scoring</h4><pre>from sentence_transformers import CrossEncoder<br><br>class CrossEncoderReranker:<br>    def __init__(self, model_name=&quot;cross-encoder/ms-marco-MiniLM-L-6-v2&quot;):<br>        self.model = CrossEncoder(model_name)<br>    def rerank(self, query: str, documents: List[str], top_k: int = 5) -&gt; List[str]:<br>        # Create query-document pairs<br>        pairs = [[query, doc] for doc in documents]<br>        <br>        # Get relevance scores (higher = more relevant)<br>        scores = self.model.predict(pairs)<br>        <br>        # Sort documents by descending score<br>        return [doc for _, doc in sorted(zip(scores, documents), reverse=True)][:top_k]</pre><h4>Key Advantages</h4><ol><li><strong>Context-Aware Scoring</strong></li></ol><ul><li>Unlike cosine similarity, cross-encoders see the <em>full query-document pair</em></li><li>Understands relationships like:<br><em>Query: “Apple fruit nutrition”</em><br><em>Correctly downranks documents about Apple Inc.</em></li></ul><p>2.<strong> Benchmark Performance</strong></p><ul><li>Improves nDCG@10 by 15–25% over vector similarity alone</li><li>Particularly effective for complex queries</li></ul><h4>When To Use</h4><ul><li>When you retrieve 20–100 documents initially</li><li>For queries where document context matters (comparisons, nuanced questions)</li></ul><p><strong>Cost Consideration:</strong><br>Reranking 100 docs adds ~500ms latency (on GPU). Mitigate by:</p><pre># Only rerank top candidates<br>def rerank(self, query, docs, first_pass_k=50, final_k=5):<br>    first_pass = docs[:first_pass_k]  # Initial vector similarity cutoff<br>    return self.rerank(query, first_pass, final_k)</pre><h4>2. Summary Augmenter: Distilling Evidence</h4><pre>class SummaryAugmenter:<br>    def __init__(self, llm_client):<br>        self.llm = llm_client<br><br>    def summarize(self, documents: List[str], focus: str = None) -&gt; str:<br>        prompt = f&quot;&quot;&quot;Create a concise summary covering key points from these documents{<br>          f&quot; focusing on {focus}&quot; if focus else &quot;&quot;}:<br>          <br>          Documents:<br>          {&#39;&#39;.join(f&#39;\n- {doc[:200]}...&#39; for doc in documents)}<br>          <br>          Summary (3-5 bullet points):&quot;&quot;&quot;<br>        <br>        return self.llm(prompt, max_tokens=300)</pre><h4>Practical Example</h4><p><strong>Input Documents:</strong></p><ol><li>500-word article on Tesla battery tech</li><li>300-word patent filing on lithium-ion</li><li>800-word interview with Musk</li></ol><p><strong>Output Summary:</strong></p><pre>- Tesla&#39;s 4680 battery cells offer 16% more range than previous models  <br>- New dry electrode process reduces manufacturing costs by 18%  <br>- Planned terafactories aim for 3TWh annual production by 2030</pre><h4>Why It Matters</h4><ol><li><strong>Reduces LLM Context Waste</strong></li></ol><ul><li>Replaces 10 pages of text with 5 bullet points</li><li>Frees up tokens for analysis vs. raw recall</li></ul><ol><li><strong>Focus Control</strong><br>Add query-specific focus:</li></ol><pre>summarizer.summarize(docs, focus=&quot;cost reduction aspects&quot;)</pre><h4>3. Reciprocal Rank Fusion: The Meta-Ranker</h4><h4>Core Algorithm</h4><pre>class ReciprocalRankFuser:<br>    @staticmethod<br>    def fuse(rankings: List[List[str]], k: int = 60) -&gt; List[str]:<br>        &quot;&quot;&quot;<br>        rankings: List of document lists from different retrievers<br>        k: smoothing parameter (higher = less aggressive reordering)<br>        &quot;&quot;&quot;<br>        fused_scores = {}<br>        <br>        for ranking in rankings:<br>            for rank, doc in enumerate(ranking, 1):<br>                fused_scores[doc] = fused_scores.get(doc, 0) + 1/(rank + k)<br>                <br>        return sorted(fused_scores.keys(), key=lambda x: -fused_scores[x])</pre><p>Reciprocal Rank Fusion (RRF) is a powerful meta-ranking technique that solves one of the biggest challenges in search systems: how to combine results from different retrieval methods to get the best of all approaches. Let’s dive deep into why this method is so effective and how it works in practice.</p><h4>Why RRF Matters: The Retrieval Diversity Problem</h4><p>Imagine you’re searching for “health benefits of green tea” across multiple systems:</p><ol><li><strong>Keyword Search (BM25)</strong> finds documents with exact phrase matches</li><li><strong>Semantic Search</strong> finds conceptually related content about antioxidants</li><li><strong>Hybrid Search</strong> gets some of both</li></ol><p>Traditional approaches would either:</p><ul><li>Take the top N from one method (missing good results from others)</li><li>Use a simple weighted average (losing nuanced ranking signals)</li></ul><p><strong>RRF solves this by respecting each method’s “vote” while preventing any single approach from dominating.</strong></p><h4>How RRF Works: The Math Behind the Magic</h4><p>The core formula is elegantly simple:</p><pre>RRF_score(doc) = sum(1 / (rank + k)) across all rankings</pre><p>Where:</p><ul><li>rank = position in each individual ranking (1st, 2nd, etc.)</li><li>k = smoothing constant (typically 60)</li></ul><h4>Key Benefits That Make RRF Special</h4><p><strong>Democracy of Retrieval Methods</strong></p><ul><li><strong>Doesn’t require tuning weights </strong>between methods</li><li>Automatically gives more weight to documents ranked high by multiple systems</li></ul><p><strong>Robust to Outliers</strong></p><ul><li>A document ranked #50 by one method won’t destroy its chances if others rank it well</li><li><strong>Single bad ranking has limited impact </strong>due to reciprocal function</li></ul><p><strong>Handles Partial Overlap</strong></p><ul><li>Works even when different methods return different document sets</li><li>Doesn’t require all methods to rank all documents</li></ul><p><strong>Parameter Stability</strong></p><ul><li>The k value is robust - works well between 30-100 for most applications</li><li>Less sensitive than weighted average approaches</li></ul><h4>Real-World Usage</h4><pre># Get results from different methods<br>bm25_results = bm25_retriever.retrieve(query, top_k=50)<br>semantic_results = semantic_retriever.retrieve(query, top_k=50)<br><br># Fuse rankings<br>final_ranking = ReciprocalRankFuser.fuse([bm25_results, semantic_results], k=30)</pre><p><strong>Key Properties:</strong></p><ol><li><strong>Democracy Principle</strong></li></ol><ul><li>Documents ranked high by <em>any</em> method get boosted</li><li>Avoids over-reliance on one approach</li></ul><p>2<strong>. Parameter Tuning</strong></p><ul><li>k=30-60 works well for most cases</li><li>Lower k increases fusion aggressiveness</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aRUmhZhdFaseiR_6uwdhAQ.png" /></figure><h3>WHY RAGS MATTER?</h3><p>RAG represents a revolutionary leap in AI capabilities by marrying two powerful technologies: the <strong>precision of modern search systems</strong> with the <strong>linguistic mastery of large language models</strong>. This synergy creates AI assistants that don’t just generate plausible-sounding answers, but responses deeply rooted in actual evidence from your knowledge base making it more explanable.</p><p>Looking ahead, the potential applications are staggering. Imagine:</p><ul><li><strong>Research assistants</strong> that instantly analyze every paper in your field while you write</li><li><strong>Customer support bots</strong> that reference exact product specs and policy documents</li><li><strong>Educational tutors</strong> that pull examples from thousands of textbooks simultaneously</li></ul><p>These systems won’t just answer questions — they’ll anticipate information needs before they’re articulated, surface connections across disparate documents, and explain their reasoning with direct citations.</p><p>What could you achieve with an assistant that has perfect recall of all your organization’s knowledge? The most exciting applications may be those we haven’t yet imagined. What burning questions would you ask a RAG system powered by your complete professional library or company documents? The future of knowledge work will be shaped by how we answer this question today.</p><blockquote><strong>What will you discover when your questions meet the perfect answers?</strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=889f38756302" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementation of Mixture of Experts using Switch Transformers]]></title>
            <link>https://medium.com/@shekharsomani98/implementation-of-mixture-of-experts-using-switch-transformers-8f25b60c33d3?source=rss-2920c9c9b63b------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f25b60c33d3</guid>
            <category><![CDATA[switch-transformer]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[sentiment-analysis]]></category>
            <category><![CDATA[moe]]></category>
            <category><![CDATA[mixture-of-experts]]></category>
            <dc:creator><![CDATA[Shekharsomani]]></dc:creator>
            <pubDate>Sun, 09 Mar 2025 08:18:03 GMT</pubDate>
            <atom:updated>2025-03-09T08:18:03.793Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7xDHiM0oqH5fCSMbX5b2qQ.png" /><figcaption>Taken from the paper : <a href="https://arxiv.org/pdf/1701.06538">https://arxiv.org/pdf/1701.06538</a> titled: OUTRAGEOUSLY LARGE NEURAL NETWORKS:<br>THE SPARSELY-GATED MIXTURE-OF-EXPERTS LAYER</figcaption></figure><h4>Switch Transformers: A Comprehensive Guide:</h4><p>Switch Transformers represent a significant advancement in the field of natural language processing and machine learning. Introduced by Google researchers in 2021 in their paper “Switch Transformers: Scaling to Trillion Parameter Models with Simple and Efficient Sparsity,” these models build upon the Transformer architecture while introducing a novel approach to model scaling.</p><p>At their core, Switch Transformers are sparse models that use a mixture-of-experts (MoE) approach to dramatically increase parameter count without a proportional increase in computational costs. This makes them particularly efficient for large-scale language tasks.</p><h4>Foundational Concepts:</h4><h4>Understanding Transformer Models</h4><p>Before diving into Switch Transformers, let’s establish a solid understanding of the standard Transformer architecture:</p><ol><li>Transformer Architecture: Introduced in the “Attention is All You Need” paper (2017), Transformers use self-attention mechanisms instead of recurrent or convolutional layers to process sequential data.</li><li>Key Components:<br>- Self-Attention: Allows the model to weigh the importance of different words in a sequence<br>- Multi-Head Attention: Runs multiple attention operations in parallel<br>- Feed-Forward Networks: Process the outputs of attention layers<br>- Positional Encoding: Provides information about word position in a sequence<br>- Layer Normalization: Stabilizes the learning process</li><li>Dense Computation: Traditional Transformers activate all parameters for every input token, which becomes computationally expensive as models scale.</li></ol><h4>The Scaling Problem</h4><p>As language models grow larger, they typically demonstrate improved performance. However, this scaling comes with challenges:</p><ul><li>Training larger models requires exponentially more computational resources</li><li>Inference (using the model) becomes slower and more expensive</li><li>Deployment on resource-constrained devices becomes impractical</li></ul><h4>Switch Transformers: Core Concepts</h4><h4>The Mixture-of-Experts (MoE) Approach</h4><p>Switch Transformers address the scaling problem by implementing a sparse MoE architecture:</p><ol><li>Experts: Specialized neural networks (typically feed-forward networks) that process different aspects of the input data</li><li>Router: A mechanism that decides which expert should process each token</li><li>Sparsity: Unlike dense models where all parameters are used for every input, Switch Transformers activate only a small subset of parameters for each token</li></ol><h4>The Switch Mechanism</h4><p>The defining feature of Switch Transformers is their routing mechanism:</p><ol><li>Token-to-Expert Routing: For each input token, the router computes routing probabilities across all experts</li><li>Top-1 Routing: Each token is processed by only the single most relevant expert (hence the name “Switch”)</li><li>Load Balancing: The model includes mechanisms to ensure experts receive roughly equal numbers of tokens, preventing under-utilization.</li></ol><p>For an input token x, the output of a Switch layer is:</p><pre>output(x) = FFN_i(x) where i = argmax(router(x))</pre><p>Where:</p><ul><li>router(x) computes a probability distribution over experts</li><li>argmax selects the expert with the highest probability</li><li>FFN_i is the feed-forward network of the selected expert</li></ul><h4>Backpropagation in Switch Transformers</h4><p>The backpropagation process in Switch Transformers is particularly interesting due to the sparse activation pattern created by the routing mechanism. Let me explain how this works in detail:<br>In traditional neural networks, backpropagation follows these steps:</p><ol><li>Forward pass computes predictions</li><li>Loss function measures error</li><li>Gradients flow backward through the network</li><li>All parameters receive gradient updates</li></ol><p>In Switch Transformers, backpropagation becomes sparse:</p><ol><li><strong>Selective Expert Activation</strong>: During the forward pass, each token activates only one expert (in the standard top-1 routing scheme).</li><li><strong>Gradient Flow</strong>: Gradients only flow through the activated experts for each token.</li><li><strong>Router Gradient Calculation</strong>: The router network receives gradients based on how well it assigned tokens to experts.</li><li><strong>Sparse Parameter Updates</strong>: Only a small fraction of the model’s parameters (the activated experts and the router) receive updates for each token.</li></ol><p>Let’s walk through this with a concrete example:</p><pre>Input batch: [token_1, token_2, token_3, token_4]<br>Experts: [expert_A, expert_B, expert_C, expert_D]<br>Forward pass routing:<br>- token_1 → expert_A<br>- token_2 → expert_C<br>- token_3 → expert_A<br>- token_4 → expert_B<br><br>Backward pass:<br>- Gradients for token_1 flow through expert_A<br>- Gradients for token_2 flow through expert_C<br>- Gradients for token_3 flow through expert_A<br>- Gradients for token_4 flow through expert_B<br>Parameter updates:<br>- expert_A: Updated based on token_1 and token_3<br>- expert_B: Updated based on token_4<br>- expert_C: Updated based on token_2<br>- expert_D: Receives no updates in this batch</pre><p>This sparse update pattern is key to the efficiency of Switch Transformers, as it allows the model to scale to trillions of parameters without proportionally increasing computation.</p><p>There’s a critical challenge in the backpropagation process: the argmax operation used in routing is non-differentiable. Switch Transformers address this using a <strong>straight-through estimator</strong>:</p><ol><li>Forward Pass: Use discrete argmax to select experts</li><li>Backward Pass: Treat the selection as if it were a differentiable weighted sum</li></ol><p>This allows gradients to flow to the router even though the actual selection process is discrete.</p><p><strong>Load Balancing Loss</strong> :<br>The load balancing loss is crucial for ensuring that all experts are utilized effectively. Let me explain it with a detailed example:</p><p>Without load balancing, the router might develop a preference for certain experts, leading to:</p><ul><li>Some experts receiving most tokens</li><li>Other experts receiving few or no tokens</li><li>Inefficient use of model capacity</li><li>Training instability</li></ul><p>The load balancing loss formula:</p><pre>L_balance = α * N * sum_i(p_i * f_i)</pre><p>Where:</p><ul><li>p_i is the fraction of tokens routed to expert i</li><li>f_i is the fraction of router probability allocated to expert i</li><li>N is the number of experts</li><li>α is a hyperparameter controlling the strength of load balancing</li></ul><p>Let’s consider a concrete example with 4 experts and a batch of 100 tokens:</p><pre>Routing decisions for current batch:<br>- Expert A: 60 tokens (p_A = 0.6)<br>- Expert B: 30 tokens (p_B = 0.3)<br>- Expert C: 10 tokens (p_C = 0.1)<br>- Expert D: 0 tokens  (p_D = 0.0)</pre><pre>Average router probabilities across batch:<br>- Expert A: f_A = 0.5 (router assigns 50% probability on average)<br>- Expert B: f_B = 0.3 (router assigns 30% probability on average)<br>- Expert C: f_C = 0.15 (router assigns 15% probability on average)<br>- Expert D: f_D = 0.05 (router assigns 5% probability on average)</pre><p>Now we calculate the load balancing loss:</p><pre>L_balance = α * 4 * [(0.6 * 0.5) + (0.3 * 0.3) + (0.1 * 0.15) + (0.0 * 0.05)]<br>L_balance = α * 4 * [0.3 + 0.09 + 0.015 + 0.0]<br>L_balance = α * 4 * 0.405<br>L_balance = 1.62α</pre><p>This loss will be minimized when all experts receive equal numbers of tokens and the router assigns equal probability to each expert. In the ideal case with perfect balance:</p><pre>p_i = 0.25 for all experts (each gets 25% of tokens)<br>f_i = 0.25 for all experts (router assigns 25% probability to each)</pre><pre>L_balance = α * 4 * [(0.25 * 0.25) * 4]<br>L_balance = α * 4 * 0.25<br>L_balance = α</pre><p><strong>Expert Parameter Updates:</strong><br>Each expert only receives updates from tokens that were routed to it:</p><pre># Pseudocode for expert parameter updates<br>for expert_idx in range(num_experts):<br>    # Find which tokens were routed to this expert<br>    tokens_for_expert = (routing_decisions == expert_idx)<br>    <br>    if tokens_for_expert.any():<br>        # Extract those tokens<br>        expert_inputs = input_tokens[tokens_for_expert]<br>        expert_gradients = token_gradients[tokens_for_expert]<br>        <br>        # Update only this expert&#39;s parameters<br>        experts[expert_idx].parameters -= learning_rate * expert_gradients</pre><p>Router Updates:<br>The router network receives gradients from two sources:</p><ol><li>The main task loss (through the straight-through estimator)</li><li>The auxiliary <strong>load balancing loss</strong></li></ol><pre># Pseudocode for router updates<br>router_gradients_task = compute_task_loss_gradients()<br>router_gradients_balance = compute_balance_loss_gradients()<br><br># Combined gradient<br>router_gradients = router_gradients_task + router_gradients_balance<br># Update router parameters<br>router.parameters -= learning_rate * router_gradients</pre><h4>Code Implementation of Switch Transformer:</h4><p>Line wise explanation and code can be found on the following <a href="https://github.com/shekharsomani98/Mixture-of-Experts-using-Switch-Transformers">github</a> link.</p><h4><strong><em>Summary</em></strong></h4><p>•⁠ ⁠Router: Decides per token which expert to use by projecting embeddings to expert logits, converting to probabilities, and picking the top expert.</p><p>•⁠ ⁠Dispatch/Combined Tensors: They respectively indicate where tokens are processed and how the expert outputs are weighted.</p><p>•⁠ ⁠Load Balancing Loss: Ensures tokens are evenly distributed across experts.</p><p>•⁠ ⁠Switch Layer: Uses the router outputs to send tokens to the expert networks, processes them, and then recombines the outputs into a unified result.</p><p>•⁠ ⁠Transformer Integration: The Switch layer is integrated into the Transformer block to replace the traditional feed-forward network, allowing the model to scale with multiple experts while maintaining computational efficiency.</p><p>This design enables the model to handle larger capacities by leveraging multiple experts and routing tokens intelligently, thus improving both model capacity and efficiency.</p><h4>Other Practical Applications:</h4><h4>Natural Language Processing</h4><p>Switch Transformers excel in various NLP tasks:</p><ol><li>Machine Translation: Translating between languages with high accuracy</li><li>Text Summarization: Creating concise summaries of longer documents</li><li>Question Answering: Providing accurate answers to natural language questions</li><li>Text Generation: Creating coherent and contextually relevant text</li></ol><h4>Multimodal Applications</h4><p>Recent research has extended Switch Transformers to multimodal domains:</p><ol><li>Image-Text Understanding: Processing both images and text in a unified framework</li><li>Audio Processing: Handling speech recognition and audio classification</li><li>Video Analysis: Understanding temporal sequences in video data</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f25b60c33d3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tree of Thoughts: How AI Learns to Think Like a Chess Player]]></title>
            <link>https://medium.com/@shekharsomani98/tree-of-thoughts-advancing-language-model-problem-solving-through-strategic-exploration-and-643776a03c40?source=rss-2920c9c9b63b------2</link>
            <guid isPermaLink="false">https://medium.com/p/643776a03c40</guid>
            <category><![CDATA[tree-of-thought]]></category>
            <category><![CDATA[chain-of-thought]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Shekharsomani]]></dc:creator>
            <pubDate>Mon, 03 Feb 2025 05:13:28 GMT</pubDate>
            <atom:updated>2025-02-03T10:39:00.373Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://github.com/princeton-nlp/tree-of-thought-llm">GitHub Repository</a>, <a href="https://arxiv.org/abs/2305.10601">Research Paper</a></p><p>In the evolving landscape of artificial intelligence, language models have traditionally followed linear paths to solve problems — much like following a single thread of thought. But what if these models could think more like humans, exploring multiple possibilities simultaneously and backtracking when needed? Enter the Tree of Thoughts (ToT) framework, a groundbreaking approach that’s transforming how AI tackles complex problems</p><p>While conventional methods like input-output prompting and Chain of Thought (CoT) have served us well, they often fall short when faced with tasks requiring strategic planning or exploration. Think of traditional approaches as walking down a straight path, whereas ToT enables AI to navigate through a maze of possibilities, evaluating different routes and making informed decisions at each junction</p><p>Developed through a collaboration between Princeton University and Google DeepMind, ToT represents a significant leap forward in AI reasoning capabilities. Unlike its predecessors, this framework doesn’t just generate sequential thoughts — it creates a branching network of possibilities, allowing the AI to evaluate multiple paths simultaneously and choose the most promising route.</p><p>The results speak for themselves. In complex problem-solving tasks like the Game of 24, where GPT-4 with traditional Chain-of-Thought prompting achieved only a 4% success rate, the Tree of Thoughts approach soared to an impressive 74% success rate</p><p>Let’s dive deep into how this revolutionary framework is reshaping our understanding of AI problem-solving capabilities and what it means for the future of artificial intelligence.</p><h3><strong>Input-output (IO) prompting:</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/201/1*o78UzObA3fNacwG__4HHIA.png" /><figcaption><strong>Input-output (IO) prompting</strong></figcaption></figure><p>Input-output prompting is the most basic form of communicating with language models — think of it as having a simple conversation where you ask one question and get one answer.</p><h3><em>How It Works</em></h3><p>Imagine you’re using a vending machine. You press a button (the input) and get a specific snack (the output). Similarly, with IO prompting, you provide a single instruction or question to the language model, and it responds with a single, direct answer</p><h3><em>Examples</em></h3><p>Simple Input Examples:<br> • “What’s the capital of France?”<br> • “Write a haiku about summer”<br> • “Translate ‘hello’ to Spanish”<br>The language model processes your input and provides a straightforward output without any intermediate steps or complex reasoning</p><h3><em>When To Use It</em></h3><p>IO prompting works best for:<br> • Simple questions requiring direct answers<br> • Basic translations<br> • Straightforward tasks<br> • Single-step instructions<br>This method is particularly effective when you need quick, straightforward responses without the complexity of multi-step reasoning or elaborate explanations</p><h3><em>Limitations</em></h3><p>While IO prompting is simple and direct, it may not be the best choice for complex problems that require reasoning or multi-step solutions. In such cases, more advanced prompting techniques like Chain-of-Thought or Tree-of-Thoughts might be more appropriate</p><h3><strong>Chain-of-Thought(CoT) prompting:</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/331/1*1xq2ALgZ-6K1ovoj5iIc-g.png" /><figcaption>Chain-of-Thought Prompting</figcaption></figure><p>Chain-of-Thought (CoT) prompting is like asking someone to “show their work” instead of just giving you the final answer. It’s similar to how a teacher would want to see how you solved a math problem, not just the end result.</p><h3><em>How It Works</em></h3><p>Think of CoT prompting as teaching an AI to think out loud. Instead of jumping straight to conclusions, the AI breaks down its thinking into clear, logical steps<br> • First, you present your question or problem<br> • Add phrases like “Let’s think step by step” / “Let’s work this out logically”<br> • The AI then shows its reasoning process before giving the final answer</p><h3><em>Example</em></h3><p>Traditional Prompt: “What’s the total cost of 3 books at $12.99 with 8% tax?”<br>CoT-Enhanced Version:<br>• Calculate base cost: 3 × $12.99 <br>• Figure out tax amount: (result × 8%)<br>• Add tax to base cost<br>• Present final total</p><h3><em>Benefits</em></h3><p>CoT prompting offers several advantages:<br> • Makes complex problems more manageable<br> • Provides transparency in how answers are reached<br> • Makes it easier to spot any errors in reasoning<br> • Helps ensure more accurate final answers</p><h3><em>When To Use It</em></h3><p>This approach is particularly effective for tasks requiring:<br> • Mathematical calculations<br> • Common sense reasoning<br> • Complex decision-making<br> • Question answering</p><h3><em>Comparison(Thought Wise)</em></h3><p>Think of it as the difference between asking someone for directions and having them either just point and say “that way” versus having them explain each turn and landmark along the route. The detailed explanation not only helps you reach the destination but also helps you understand how to get there.</p><h3><em>Limitations</em></h3><p>Chain-of-thought prompting, while innovative, faces several key limitations that restrict its practical application. It only works effectively with very large language models (around 100B parameters or more), making it impractical for smaller, more accessible models. The technique often introduces unnecessary complexity to simple tasks and can significantly slow down processing times. There are also concerns about the reliability of the reasoning chains produced, as they may appear logical but contain fundamental flaws or fail to accurately reflect the model’s actual decision-making process. Additionally, the success of CoT heavily depends on careful prompt engineering and doesn’t generalize well across different types of tasks, particularly struggling with more complex problems or larger datasets.</p><h3><strong>Tree-of-Thought(ToT) prompting:</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sj9xXCv9uLXA_IgP6d65Lw.jpeg" /><figcaption>reference: <a href="https://www.ibm.com/think/topics/tree-of-thoughts">https://www.ibm.com/think/topics/tree-of-thoughts</a></figcaption></figure><p>Tree of Thought (ToT) is an advanced evolution of Chain of Thought prompting that explores multiple reasoning paths simultaneously, similar to how a chess player considers various possible moves. Unlike linear problem-solving methods, ToT creates a hierarchical structure where multiple reasoning paths are explored simultaneously. The system generates and maintains various thought states as intermediate steps, organizing them in a tree-like structure with branches representing different solution paths.</p><h3><em>How It Works</em></h3><p>The solving process uses a breadth-first search approach:<br>• Generates multiple thoughts at each step<br>• Evaluates each thought path<br>• Selects the best paths to explore further<br>• Continues until reaching a final answer or maximum steps</p><p>This structured approach allows for more robust problem-solving compared to the linear nature of CoT, particularly for complex problems that might have multiple valid solution paths.</p><h3><em>Example</em></h3><p>Question: “In a room with 3 light switches, each connected to a different lamp in another room, how can you determine which switch controls which lamp if you can only enter the room with the lamps once?”</p><p>Initial State: Three switches (A, B, C), all off</p><pre>thoughts = {<br>    &quot;root&quot;: [&quot;Start with all switches off&quot;],<br>    &quot;level_1&quot;: [<br>        &quot;Turn switch A on for 10 minutes&quot;,<br>        &quot;Turn switch B on briefly&quot;,<br>        &quot;Leave switch C off&quot;<br>    ]<br>}</pre><p>Evaluation Branches:<br>• Branch 1 — Heat Method:</p><pre>path_1 = {<br>    &quot;action&quot;: &quot;Turn A on (10 min), then off&quot;,<br>    &quot;reasoning&quot;: &quot;Lamp A will be warm but off&quot;,<br>    &quot;next_step&quot;: &quot;Check temperature of lamps&quot;,<br>    &quot;evaluation_score&quot;: 0.9  # High score due to reliable physical principle<br>}</pre><p>• Branch 2 — State Method:</p><pre>path_2 = {<br>    &quot;action&quot;: &quot;Leave B on&quot;,<br>    &quot;reasoning&quot;: &quot;One lamp will be on&quot;,<br>    &quot;next_step&quot;: &quot;Observe which lamp is lit&quot;,<br>    &quot;evaluation_score&quot;: 0.7  # Lower score due to less information gained<br>}</pre><p>• Branch 3 — Combined Method</p><pre>path_3 = {<br>    &quot;action&quot;: &quot;A on(10min) + B on, C off&quot;,<br>    &quot;reasoning&quot;: &quot;Creates three distinct states&quot;,<br>    &quot;next_step&quot;: &quot;Check warmth and illumination&quot;,<br>    &quot;evaluation_score&quot;: 0.95  # Highest score due to maximum information<br>}</pre><p>After evaluating all branches, the system selects Branch 3 as optimal:<br>• Turn switch A on for 10 minutes<br>• After 10 minutes, turn A off<br>• Turn switch B on<br>• Enter the room once<br>• Results interpretation:<br>Warm and off = Switch A<br>On and cool = Switch B<br>Off and cool = Switch C</p><p>This example demonstrates how ToT:<br>Generates multiple solution paths<br>Evaluates each path’s effectiveness<br>Selects the most promising approach<br>Builds a complete solution through structured reasoning</p><p>The final solution maximizes information gained from a single room entry, demonstrating ToT’s ability to find optimal solutions through parallel exploration of multiple reasoning paths.</p><h3>Code WalkThrough:</h3><h4>Core Concept</h4><p>Unlike Chain of Thought which follows a single linear path, ToT creates a tree-like structure where multiple thoughts are generated and evaluated at each step. Here’s how it works:</p><p><strong><em>Initialisation</em></strong>: Choose a model and initialise it(Using Qwen2.5–7B-Instruct model)</p><pre>class TreeOfThoughts:<br>    def __init__(self, api_key: str, base_url: str = &quot;https://api.deepinfra.com/v1/openai&quot;, <br>                 model: str = &quot;Qwen/Qwen2.5-7B-Instruct&quot;, temperature: float = 0.7):<br>        self.client = OpenAI(<br>            api_key=api_key,<br>            base_url=base_url<br>        )<br>        self.model = model<br>        self.temperature = temperature<br>        self.total_tokens = 0<br>        self.evaluation_cache = {}  # For caching evaluations<br><br>    def chat_with_gpt(self, prompt: str, n: int = 1, stop: str = None) -&gt; List[str]:<br>        &quot;&quot;&quot;Get multiple completions from the model with proper stop sequences.&quot;&quot;&quot;<br>        try:<br>            messages = [{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: prompt}]<br>            response = self.client.chat.completions.create(<br>                model=self.model,<br>                messages=messages,<br>                temperature=self.temperature,<br>                n=n,<br>                stop=[stop] if stop else None,<br>                max_tokens=256<br>            )<br>            completions = [choice.message.content for choice in response.choices]<br>            return completions<br>        except Exception as e:<br>            print(f&quot;API Error: {e}&quot;)<br>            return []</pre><p><strong><em>Thought Generation</em></strong>: The system generates multiple potential reasoning paths at each step added to this class</p><pre>def generate_thoughts(self, question: str, current_thought: str = &quot;&quot;, n_samples: int = 3):<br>    # Generate multiple possible next steps in reasoning<br>    prompt = f&quot;&quot;&quot;You are a logical thinker... Given a question and current thought, <br>                 list {n_samples} possible next steps to solve the problem.&quot;&quot;&quot;<br>    thoughts = self.chat_with_gpt(prompt)<br>    return thoughts</pre><p><strong><em>Evaluation and Selection</em></strong>: Unlike CoT, ToT actively evaluates each thought path and selects the most promising ones.</p><pre>def evaluate_thought(self, question: str, thought: str, cache: bool = True) -&gt; float:<br>        &quot;&quot;&quot;Evaluate the quality of a thought using self-evaluation.&quot;&quot;&quot;<br>        <br>        prompt = f&#39;&#39;&#39;Rate how likely this thought will lead to the correct answer (1-10):<br>            Question: {question}<br>            Thought: {thought}<br>            Rating (1-10): &#39;&#39;&#39;<br>        <br>        response = self.chat_with_gpt(prompt, n=1)<br>        if not response: return 0.0<br>        <br>        try:<br>            score = float(re.search(r&#39;\d+&#39;, response[0]).group())<br>            score = max(1.0, min(10.0, score))  # Clamp to 1-10<br>            if cache:<br>                self.evaluation_cache[thought] = score<br>            return score / 10.0  # Normalize to 0-1<br>        except:<br>            return 0.0<br><br>def select_best_thoughts(self, thoughts: List[str], scores: List[float], k: int = 2):<br>    # Select top-k thoughts based on evaluation scores<br>    combined = sorted(zip(thoughts, scores), key=lambda x: x[1], reverse=True)<br>    return [thought for thought, score in combined[:k]]</pre><p><strong><em>BFS Implementation</em></strong>:</p><pre>def solve(self, question: str, max_steps: int = 8):<br>    current_thoughts = [&quot;&quot;]  # Start with empty thought<br>    <br>    for step in range(max_steps):<br>        new_thoughts = []<br>        for thought in current_thoughts:<br>            # Generate new branches<br>            candidates = self.generate_thoughts(question, thought)<br>            # Evaluate and select best thoughts<br>            scores = [self.evaluate_thought(question, c) for c in candidates]<br>            best_thoughts = self.select_best_thoughts(candidates, scores)<br>            new_thoughts.extend(best_thoughts)<br>        <br>        current_thoughts = new_thoughts<br>        # Check for final answer<br>        if any(&quot;final answer&quot; in t.lower() for t in current_thoughts):<br>            return final_answer</pre><h3>Benefits</h3><p><em>Enhanced Problem-Solving: <br></em>ToT significantly outperforms traditional methods in complex tasks. For example, in the Game of 24, ToT achieved a 74% success rate compared to just 4% with standard approaches.</p><p><em>Cognitive Alignment: <br></em>The framework mirrors human problem-solving by breaking down complex problems into manageable intermediate steps and exploring multiple possibilities simultaneously.</p><p><em>Flexibility: <br></em>The system can backtrack when needed and make global decisions based on evaluating multiple thought paths, rather than being confined to local, sequential decisions.</p><h3>When To Use It</h3><p>• For complex problems requiring exploration of multiple reasoning paths</p><p>• When tasks involve:</p><ul><li>Strategic planning and lookahead</li><li>Multiple interconnected variables</li><li>Need for backtracking and evaluation</li></ul><p>• Best suited for:</p><ul><li>Mathematical reasoning problems</li><li>Creative writing tasks</li><li>Complex logistics optimization</li><li>Multi-variable decision making</li></ul><p>• When simple or linear prompting techniques are insufficient for:</p><ul><li>Tasks requiring deep exploration</li><li>Problems needing structured decision-making</li><li>Scenarios with multiple possible solutions</li></ul><p>• Not recommended for:</p><ul><li>Simple, straightforward tasks</li><li>Problems that don’t require extensive reasoning</li><li>Tasks where resource efficiency is crucial</li></ul><h3><em>Limitations</em></h3><p>Tree of Thoughts (ToT) faces several significant challenges that affect its practical application. The approach is computationally intensive and resource-demanding, requiring substantial processing power and memory to maintain multiple decision paths and perform evaluations simultaneously. Implementation complexity is a major hurdle, as the system requires careful integration and fine-tuning of various components including the prompter agent, checker module, and memory module, where poor configuration of any component can compromise the entire system’s effectiveness. The framework can also suffer from overfitting-like behavior, where it becomes too focused on specific reasoning branches while losing broader context.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=643776a03c40" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>