<?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 Anshul Kalbande on Medium]]></title>
        <description><![CDATA[Stories by Anshul Kalbande on Medium]]></description>
        <link>https://medium.com/@anshulkalbande?source=rss-3164f83e8b6a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*FFAXWqLqfWp7A07nFlVehQ.jpeg</url>
            <title>Stories by Anshul Kalbande on Medium</title>
            <link>https://medium.com/@anshulkalbande?source=rss-3164f83e8b6a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 02:49:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@anshulkalbande/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 inference engineering 101]]></title>
            <link>https://medium.com/@anshulkalbande/voice-inference-engineering-101-3afa2170af87?source=rss-3164f83e8b6a------2</link>
            <guid isPermaLink="false">https://medium.com/p/3afa2170af87</guid>
            <category><![CDATA[voice-ai]]></category>
            <category><![CDATA[inference-engineering]]></category>
            <dc:creator><![CDATA[Anshul Kalbande]]></dc:creator>
            <pubDate>Wed, 30 Sep 2026 18:11:03 GMT</pubDate>
            <atom:updated>2026-09-30T18:11:03.802Z</atom:updated>
            <content:encoded><![CDATA[<p><em>the 3 ways to self host a voice agent</em></p><p>you must’ve noticed that everyone is suddenly learning inference engineering, and i dont think it’s an ephemeral trend, i think people are realizing this field is a real discipline and it is far from being ‘solved’ (even with ai)</p><p>self-hosting is becoming more and more important. you want control over latency, over your data, over cost, over whether your agent still works when the api changes (or when you suddenly can’t afford it anymore).</p><p>i’ve had some experience applying these ideas while deploying real-time voice agents. here, i’ve tried to distill what i learned from that work and from more recent experiments. partly to share it, and partly to expose the gaps in my own understanding.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_kMTQWH7OSznrWeiYKQiqg.png" /></figure><h3>the three architectures</h3><p>most voice agents fall into one of <strong>3 main architectures.</strong></p><ol><li><strong>modular</strong> : something listens, something thinks, something speaks. three separate models in a row. you own the seams between them.</li><li><strong>full-duplex</strong> : one model, audio flowing in and out at the same time, like a phone call.</li><li><strong>omni</strong> : designed to process multiple modalities, such as text, audio, images and potentially video, within a unified model architecture.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZerNg8tnqw3dNIGhdoPjFw.png" /></figure><h3>the 80/20 of inference engineering</h3><p>although i wanna focus on what changes when we do inference for voice, we need a few basics first.</p><p>when we run a model, its <strong>weights</strong> need to live somewhere the gpu can access. the simplest estimate is:</p><blockquote>number of parameters × bytes per parameter = weight memory</blockquote><p>so a 12B parameter model in FP16, where each parameter takes 2 bytes, needs roughly:</p><blockquote>12 billion × 2 bytes ≈ 24 GB</blockquote><p><strong><em>just for the weights.</em></strong></p><p>this is where <strong>precision</strong> starts to matter. FP32 uses 4 bytes per value, FP16 and BF16 use 2, INT8 uses 1. lower precision means less memory to store the model and less data that needs to move around, although whether you can actually use a particular precision without hurting quality or performance depends on the model and hardware.</p><p>but weight memory is only the starting point.</p><p>during inference the gpu also needs memory for intermediate values produced while running the network, usually called <strong>activations</strong>, temporary workspaces used by kernels, the CUDA/runtime itself, and in autoregressive transformers, the <strong>KV cache</strong>.</p><p>the KV cache exists because when an LLM generates the next token, it shouldn’t recompute the attention state for every previous token from scratch. it stores the keys and values from earlier tokens and reuses them during later generation.</p><p>so the actual memory picture is actually more like:</p><pre>weights<br>+ KV cache<br>+ activations<br>+ temporary/runtime memory<br>+ some headroom</pre><p>this is why saying a model has <strong>“24 GB of weights”</strong> and putting it on a 24 GB gpu usually does not work.</p><p>memory capacity tells us whether the workload can fit. once it fits, we care about how quickly the gpu can actually execute it.</p><p>there are two useful hardware numbers here: <strong>compute throughput</strong> and <strong>memory bandwidth</strong>.</p><p><strong>compute throughput</strong> is roughly how much math the gpu can perform per second. this is where numbers like TFLOPs come from.</p><p><strong>memory bandwidth</strong> is how quickly data can be moved between the gpu’s memory and its compute units.</p><p>which one matters more depends on what the model is doing.</p><p>for an autoregressive LLM, inference is usually split into two phases.</p><p>say the prompt is:</p><blockquote>why is the sky blue?</blockquote><p>before generating anything, the model processes all of those input tokens. this is called <strong>prefill</strong>.</p><p>the nice thing about prefill is that the tokens are already known, so a lot of their computation can happen in <strong>parallel</strong>. with sufficiently large inputs or batches, this tends to make good use of the gpu’s compute.</p><p>then generation starts.</p><pre>the<br>the sky<br>the sky appears<br>the sky appears blue<br>...</pre><p>this is <strong>decode</strong>.</p><p>each new token depends on the tokens before it, so generation happens one step at a time. every step still has to read a large amount of model state and KV-cache state, but there isn’t necessarily enough arithmetic work in one token to fully use all of the gpu’s compute.</p><p>this is why LLM decode is often <strong>memory-bandwidth bound</strong>: the bottleneck is moving the required data quickly enough rather than doing the arithmetic itself.</p><p>this gives us two latency measurements that will show up throughout the article.</p><p><strong>time to first token (TTFT)</strong> is how long it takes before generation begins. model loading aside, <strong>prefill is a large part of this.</strong></p><p>after that, <strong>inter-token latency (ITL)</strong> tells us how quickly subsequent tokens arrive during decode.</p><p>voice systems add their own versions of these measurements later. instead of only caring about the first text token, we might care much more about <strong>time to first audio</strong>.</p><p>there’s one more thing we need before getting into the experiments: <strong>warmup</strong>.</p><p>loading model weights onto the gpu does not mean every part of the runtime is ready to execute at steady-state speed.</p><p>the first real inference can trigger work that <em>only</em> needs to happen once, depending on the runtime: CUDA kernels and libraries may initialize lazily, memory pools may grow, execution paths may be compiled or selected, and some runtimes capture CUDA graphs for later reuse.</p><p>so this can happen:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1cWWqyQcyCtehuDcPLwnaA.png" /></figure><p>we can deliberately trigger this work with a fake input before serving a real user. that’s <strong>warmup</strong>.</p><p>warmup doesn’t make that initialization work disappear. it changes <strong>who waits for it</strong>.</p><p>this distinction ended up mattering a lot more than i expected once i started measuring the voice models.</p><h3>the modular pipeline</h3><p>the chain is the most intuitive.</p><p>three models in a row: speech to text (stt), then a language model, then text to speech (tts)</p><p>i rented a gpu with 23.7 gb of usable VRAM and loaded the entire modular stack into one container:</p><ul><li>whisper-large-v3-turbo through faster-whisper for speech-to-text</li><li>Qwen2.5-3B-Instruct for language generation</li><li>Kokoro-82M for text-to-speech</li></ul><p>whisper-large-v3-turbo used about 2.4 gb, Kokoro-82M about 0.7 gb, and Qwen2.5-3B-Instruct, including its KV cache, a little over 9 gb. after loading everything, roughly 11 gb remained free. memory was never the problem; scheduling was.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NSvuy6LNbTY870NhfEb8hQ.png" /></figure><p>because each of the three models has a different idea of what “done” means. the stt works on a buffer, retranscribing a window of audio as it grows. the language model works in single tokens. the speaker works in whole sentences. three different <strong>units of progress</strong> in one pipeline.</p><p>and so the most important thing in a modular design is to figure out what the smallest useful unit of progress is, <strong>the smallest thing worth handing to the next stage.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rsEGmUbWTxIU56kMbn67RA.png" /></figure><h4>the sequential baseline</h4><p>i wanted the baseline to be as naive as possible: where you listen fully, then think fully, then speak, with nothing overlapping.</p><p>for input i used a fixed clip, “give me three practical tips for sleeping better, one short sentence each”, synthesised once and frozen, for reproducibility. <strong>it’s a scheduling experiment,</strong> how well the listener hears is a separate question. synthetic speech is cleaner than a human, so the listener does better on it than it would in production, fine for now.</p><p><strong>if you give tts the whole paragraph, it produces one chunk</strong>. the entire three-sentence reply comes back as a single unit, because there’s no incremental audio inside a chunk, it splits on newlines before its internal chunker ever sees the text, so one paragraph becomes one chunk.</p><p>so if i wanted the first sentence to start speaking while the model was still writing the third, the tts wasn’t going to hand it to me. i had to build that myself. that’s what the next experiment is.</p><h4>overlap</h4><p>the idea: feed the speaker <strong>one sentence at a time.</strong> the moment the language model finishes sentence one, start speaking it while sentence two is still being written.</p><p>my first attempt made it look like a regression: overlap was worse and time-to-first-audio went up.</p><p>the trace showed why: transcription was <strong>2.28× slower in the second container, and time-to-first-token 1.56× slower. </strong>those aren’t things the scheduling policy can touch. yet they moved, more than the effect i was trying to measure.</p><p>so the two containers weren’t comparable. one was just slower. comparing across them measured container variation, and the policy had nothing to do with it.</p><p>a benchmark can run correctly and<strong> still answer the wrong question.</strong></p><p>so i redid it. both versions in one container, alternating, models loaded once, startup costs paid before any measured turn. now scheduling is the only thing that differs. and the number that should’ve been identical was: transcription spread <strong>1.02× across six turns, against 2.28× in the broken comparison.</strong></p><h4>result:</h4><p>first audio came <strong>353 ms earlier under overlap, 42.4% earlier. total completion moved 13 ms, a 1.6% increase.</strong></p><p>no model got faster. the listener did the same work, the language model did the same work, the speaker did the same work. we just stopped waiting for work that could already begin.</p><p>and total time barely moved, because overlap can’t make synthesis faster. it moves work earlier, but the work still happens. audio starts sooner, the turn ends at the same time.</p><p>so i won’t call it “42% faster.” time-to-first-audio improved 42%. total completion stayed the same. which one matters depends on what “feeling fast” means to you and your use case.</p><h4>one thing i couldn’t resolve:</h4><p>under overlap, the language model’s generation took about 93 ms longer, 18.7%, reproducibly, across all three pairs. two explanations fit: the speaker’s gpu work genuinely slows the language model (contention), or my reader thread didn’t get scheduled while synthesis ran (client-side scheduling). both produce the same signature.</p><p>i don’t know which it is, and the data can’t separate them, so i’m leaving it as a measured difference with an unknown cause, because inventing a clean story is exactly the mistake this project was trying not to make.</p><h4>experimental design</h4><p>this is the part that matters more than any single number.</p><p>i almost believed the wrong result more than once, and it always came from the same place: not checking whether the experiment isolated the thing i thought it isolated. the two-container comparison above is one example, the code ran fine and the numbers were real, they just weren’t about scheduling. another: a metric that looked like it measured the model was really measuring the startup cost. the first request took 68 ms to first token, every later one 25 ms. if you don’t know which you’re looking at, your number is a coin flip.</p><p>and there’s a clock problem underneath all of it. a voice system has four clocks, audio, gpu, server, browser, on different machines with unknown offsets. subtract a browser timestamp from a server timestamp and you get a number that looks meaningful but means nothing. same with `torch.cuda.synchronize()`: it waits for all pending gpu work, so your timing includes the whole queue. that’s a choice with a purpose. mixing two clocks the same way and calling the result latency is a bug. i broke this rule, then rebuilt the harness around it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lSim0ilF1WzdxoSzaudfgw.png" /></figure><p>separate what you measured from the story you tell about it. a number tells you something happened. why it happened is a different question.</p><h3>the full-duplex stream</h3><p>the second architecture is the opposite of the chain.</p><p>one model, audio flowing in and out at the same time. no request, no response, just two streams on one clock.</p><p>it works in frames: 80 milliseconds of audio at a time, and it computes each frame in about 49 milliseconds. so the model is faster than the clock, it can process one chunk of the world before the world produces the next.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4NmyhC8de1BVJn6y46WaVw.png" /></figure><p>i proved the full-duplex part with three wav files on the same timeline: what the person said, what the model said, both summed. the model’s output lags its input by exactly one frame, and you can see it.</p><p>then warmup, where the first-call thing bites hardest. the first frame took 10.8 seconds. not 10.8 ms, ten point eight seconds, doing nothing useful, paying startup costs. then 987 ms, 476 ms, down to about 49 ms. once warm, the first real frame took about 46 ms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cYoheTY2YK0PpCaQzi_XbQ.png" /></figure><p>warmup moves work off the user’s critical path, but the work still happens. the 10.8 seconds still happened, you just made it happen before the user started talking.</p><p>and there are two different things people mean by warm. loading the weights into memory is one. having made the first real call is another.</p><p>then there’s state over time: i ran it for 3,400 frames, about four and a half minutes, crossing its context window. memory stayed flat before and after. compute stayed roughly flat too.</p><p>but be careful about what that proves. the system’s cost staying bounded over the period i tested, that’s measured. how much the model actually remembered across the wrap is an open question. flat memory means the system stayed bounded. it says nothing about what the model remembered.</p><p>finally, the real test: offline it ran at about 48–49 ms per frame, and live through a browser and a websocket it took 49.3 ms. the offline number survived contact with the actual serving path, the measurement was of the model. that’s the result you want.</p><h3>the omni model</h3><p>the third architecture is the one everyone’s excited about.</p><p>from the outside it’s perfect: audio in, audio out, one model, nothing to manage.</p><p>except when you go to serve it, the chain shows up again, just moved inside.</p><p>the runtime runs it as three stages, a thinker, a talker, and a codec, placed on two gpus. the config it loads by default says so: thinker on gpu 0, talker and codec on gpu 1, with memory fractions 0.9, 0.6, 0.1. “verified on 2x h100.”</p><p>so the question becomes: where did the chain move? answer: inside the runtime, owned by someone else. “single model” and “single-gpu deployment” are different claims. one black box from the outside is still three stages on two devices inside, just with someone else drawing the boundaries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IO8WgrElO74x33Hr-eKOxw.png" /></figure><p>i should be honest about how long it took to even get that far, because it wasn’t a total waste of time. it failed over and over, and every failure traced to something outside the model: a memory-accounting bug in the runtime, then the model name the api registered, then a file url.</p><p>in the end it served: two large gpus, about nine minutes of cold startup, the thinker alone holding 135 gb of the first device’s 150 gb. same input as the chain, three sleep tips out, a wav to match. the whole request, audio in to audio out, took 2.9 seconds. one request, cold, so i won’t call it a benchmark, but it’s a real artifact, the thing this section was missing for most of the project.</p><p><strong>“end-to-end” describes what the user sees. what the deployment looks like is a separate question.</strong></p><h3>side by side</h3><p>now compare by question.</p><p>who owns state? the stream keeps it in one model. the chain keeps it in three, and the seams are mine. the omni model keeps it in three stages the vendor placed.</p><p>smallest unit of progress? a sliver of audio in the stream, a token or a sentence in the chain, and whatever’s hidden behind the api in the omni model.</p><p>who owns scheduling? the model’s clock in the stream, me in the chain, and the runtime’s orchestrator in the omni model.</p><p>by the end, the stream and the chain feel like genuinely different machines. and the omni model makes you ask whether the complexity disappeared, or just moved behind the api where you can’t see it.</p><h3>some hypotheses from my side</h3><p>here are some concepts i thought about while writing, im not claiming them as original, they’re probably not.</p><h4><strong>speculative thinking</strong></h4><p>start the language model before the transcript is final. the listener retranscribes a growing window, so the transcript changes as more audio arrives. if you run the model on an early draft, who decides the work is still valid? reuse the parts that still apply, cancel the rest? it’s the obvious next lever, full of questions about wasted work.</p><h4>dynamic endpointing</h4><p>one fixed silence threshold is the wrong shape. a short simple question probably doesn’t need as much trailing silence as a long thoughtful request. i have a hunch the endpoint should adapt to the utterance. untested.</p><h4>interruption handling</h4><p>when the user starts speaking while the agent is talking, the agent needs to stop the old response and listen. this basic behavior is solved, but the implementation differs. a full-duplex model handles both streams together. in a modular chain, the application has to coordinate the speech recognizer, language model, audio generator, and playback queue itself. the interesting question is not whether interruption works, but who is responsible for making all those pieces stop together.</p><h3>the questions</h3><p>i think asking the right questions is the key to achieving a good design for your specific use case. here are my go-to questions when i need clarity:</p><p>- who owns the clock?</p><p>- who owns state?</p><p>- what is the smallest unit of progress?</p><p>- what work is actually happening?</p><p>- what are we waiting for?</p><p>- what can safely overlap?</p><p>- what did we measure, and what are we merely explaining?</p><p>- what changed between two experiments?</p><p>answer those about a voice system, or say honestly which ones you can’t, and you understand it better than any benchmark table.</p><h3>glossary</h3><p><strong>prefill: </strong>processing a whole prompt at once. fast per token.</p><p><strong>decode</strong>: generating one token at a time. slower per token, done many times.</p><p><strong>kv cache:</strong> running memory of generated tokens. grows with the conversation.</p><p><strong>ttft / time to first token:</strong> time until the first generated token.</p><p><strong>ttfa / time to first audio:</strong> time until the first audible output. not the same as ttft.</p><p><strong>stt / asr:</strong> speech to text. audio to words.</p><p><strong>tts:</strong> text to speech. words to audio.</p><p><strong>full duplex:</strong> audio both ways at once, like a phone call, not alternating turns.</p><p><strong>bf16 / fp16 / int4:</strong> precision formats. fewer bytes = less memory, faster, some quality loss.</p><p><strong>gpu memory utilization:</strong> the fraction of a gpu’s memory a serving engine may reserve.</p><h3>references</h3><p>the measurements are my own, from <a href="https://github.com/anshulLuhsna/voice-inference-lab">this project’s</a> traces. the exact models used, so the numbers can be checked:</p><p>- the speech-to-text model was [faster-whisper](https://github.com/SYSTRAN/faster-whisper), `whisper-large-v3-turbo`.</p><p>- the language model was [Qwen2.5–3B-Instruct](https://huggingface.co/Qwen/Qwen2.5-3B-Instruct).</p><p>- the text-to-speech model was [Kokoro-82M](https://huggingface.co/hexgrad/Kokoro-82M).</p><p>- the full-duplex stream was [Moshi](https://github.com/kyutai-labs/moshi).</p><p>- the omni model was [Qwen3-Omni-30B-A3B-Instruct](https://huggingface.co/Qwen/Qwen3-Omni-30B-A3B-Instruct).</p><p>- served with [vLLM](https://github.com/vllm-project/vllm) and [vLLM-Omni](https://github.com/vllm-project/vllm-omni), on [Modal](https://modal.com).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3afa2170af87" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[30 Ideas for Thinking Clearly About Recommendation Systems]]></title>
            <link>https://medium.com/@anshulkalbande/30-ideas-for-thinking-clearly-about-recommendation-systems-9987f74d6a14?source=rss-3164f83e8b6a------2</link>
            <guid isPermaLink="false">https://medium.com/p/9987f74d6a14</guid>
            <category><![CDATA[youtube]]></category>
            <category><![CDATA[recommendation-system]]></category>
            <category><![CDATA[netflix]]></category>
            <category><![CDATA[pinterest]]></category>
            <dc:creator><![CDATA[Anshul Kalbande]]></dc:creator>
            <pubDate>Sat, 19 Sep 2026 19:01:12 GMT</pubDate>
            <atom:updated>2026-09-19T19:01:12.601Z</atom:updated>
            <content:encoded><![CDATA[<p><em>What YouTube, Pinterest and Netflix taught me about retrieval, ranking, embeddings, and when not to use the fancy model</em></p><p>i was asked to design natural language search for a website that sells shoes.</p><p>this was an applied ai/agentic role, so i could use an agent. i straightaway felt like figuring out where the agent belonged and how to constrain it was the kind of thinking they were looking for.</p><p>since i had some experience designing recommendation systems, i could see that this search problem shared the same ‘<em>retrieve-then-rank’</em> intuition.</p><p>except in search, we also get explicit intent from the user in the form of a query.</p><p>i’ll get to my answer at the end, but first i want to walk through some patterns that helped me think about recommendation systems more clearly.</p><p>there are a lot of ideas here, so i’ve added <strong>mind maps as checkpoints</strong> after ideas 3, 8, 10, 18, 25 and 30. each one pulls together what we’ve covered so far. you don’t need to remember every model name as you go; use these to keep track of how the ideas connect.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9VqnnFAT6dzdg60eRRcOMw.png" /></figure><h3>1. Don’t start with the model</h3><p>this is the <em>single worst thing</em> you can do at the start: jump to a solution without knowing the requirements.</p><p>start with questions like:<br><em>what are we optimizing?<br>what signals do we have?<br>what scale are we operating at?<br>what latency constraints exist?<br>what are the hard business constraints?</em></p><p>in our shoe website example, this could look something like:<br>1. are we optimizing for the most relevant items to the query, or the products the user is most likely to actually buy?</p><p>2. do we have just the query, or do we also know the user’s previous purchases, clicks and preferences?</p><p>3. what information do we have about the products? titles, descriptions, brand, color, price, size, images?</p><p>4. are we searching through 10,000 shoes or 10 million?</p><p>5. does inventory change every few minutes?</p><p>6. if the user searches for “black running shoes under ₹5000”, is ₹5000 a strict constraint?</p><p>7. Should we show out-of-stock shoes?</p><p>8. and how much time do we have to do all of this?</p><p>these questions matter because they completely change what system we should build.</p><p>for this problem, the answers were roughly:</p><ul><li>the main objective was to return the products most relevant to the user’s query. personalization could help, but the explicit query should dominate.</li><li>we had the natural language query and product information like titles, descriptions, brand, category, color, price, size and images.</li><li>the catalog could contain millions of products.</li><li>the end-to-end p95 &lt; 3 seconds.</li><li>things like inventory, price and availability could change and needed to stay reasonably fresh.</li><li>explicit constraints like price, size and product type should generally be respected, and unavailable products should not be shown.</li><li>the final output was a ranked Top-K list of products.</li><li>since this was an applied AI role, we were allowed to use an agent or LLM, but clearly we couldn’t afford to run expensive reasoning over millions of products.</li></ul><p><strong>these answers immediately start ruling out certain designs.</strong></p><p>if i only had a few thousand products and no strict latency requirement, i could afford a <em>very</em> different solution than if i had millions of products and needed results in a few hundred milliseconds.</p><p>the model should come <strong>after</strong> understanding the problem.</p><p>once the requirements are clear, the next question becomes much easier:</p><p>how do we go from millions of possible items to the handful we actually want to show?</p><p>that leads to probably <strong>THE most useful idea in recommendation systems.</strong></p><h3>2. Separate retrieval and ranking</h3><p>we need to create a <em>funnel.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/1*OIN4FjDxyah-MjGqT8gi7Q.png" /></figure><p>but <em>why?</em></p><p>why not just run the most powerful model we have on the entire catalog?</p><p>well you can. but it would violate almost <strong>every </strong>non functional requirement we have.</p><p>the amount of computation we can afford per item depends on how many items we are looking at.</p><p>if we have 10 million products, we can’t afford to deeply reason about every single one of them for every search request.</p><p>imagine using an LLM or a heavy cross-encoder to compare the query against millions of products individually. even if each comparison was relatively fast, doing it millions of times for every user request would immediately destroy our latency and cost requirements.</p><p>so instead, we spend very little computation per item at the beginning of the funnel.</p><p>the retrieval stage tries to quickly find a few hundred or few thousand plausible candidates from millions of products.</p><p>so the basic idea is:</p><p><strong>the smaller the candidate set becomes, the more computation we can afford to spend per candidate.</strong></p><p>YouTube’s 2016 paper, <em>Deep Neural Networks for YouTube Recommendations</em>, describes this separation: one network generates candidates, and another ranks them.<a href="#fn-1">[1]</a></p><h3>3. Optimize retrieval for coverage, ranking for order</h3><h4>Retrieval</h4><p>first off: retrieval ≠ rough ranking<br>if the perfect item never enters the candidate set, nothing downstream can recover it.<br>for retrieval, you generally care a lot about <strong>recall</strong>.<br>but don’t say:</p><blockquote><em>retrieval should maximize recall.</em></blockquote><p>say:</p><blockquote><strong><em>retrieval should get high recall within a reasonable candidate budget.</em></strong></blockquote><p>we need constraints,<br>because:</p><p>return ENTIRE CATALOG -&gt; recall 100% (completely useless)</p><p>because a good retriever makes sure we don’t miss the good stuff, while also not making the downstream ranker’s job harder.</p><p>this is an <strong>optimization problem</strong>, not a maximisation problem.</p><h4>Ranking</h4><p>ranking is fundamentally an <strong>ordering problem</strong>.<br>for example:</p><pre>List A:<br>relevant<br>relevant<br>relevant<br>irrelevant<br>irrelevant</pre><p>is <em>much </em>better than:</p><pre>List B:<br>irrelevant<br>irrelevant<br>relevant<br>relevant<br>relevant</pre><p>even though both lists contain exactly three relevant items.</p><p>that’s why metrics like <strong>MAP and NDCG</strong> exist: they care about <em>where</em> relevant items appear, not only whether they appear.</p><p>the final ranking objective doesn’t have to literally be “relevance.”</p><p>a real system might rank for:</p><ul><li>probability of purchase,</li><li>watch time,</li><li>revenue,</li><li>satisfaction,</li><li>some combination of these.</li></ul><p>so ranking is ultimately:</p><blockquote><strong><em>order the candidates according to what the product actually cares about.</em></strong></blockquote><p>this is why Idea 1 is so important.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/1*v6lna6WclE6sb6ImMvopDg.png" /><figcaption>mindmap 1</figcaption></figure><h3>4. Where does relevance come from? Content vs Collaborative Filtering</h3><p>“relevance” isn’t one well-defined thing.</p><p>let’s say we are recommending “black running shoes” for a user “A”<br>relevance could be traced back to one of these:</p><ol><li>based on A’s own history, A tends to like attributes like black, running shoes, or a certain brand. <strong>content-based filtering</strong></li><li>based on interaction patterns across users, people who behave similarly to A tend to buy these shoes. <strong>collaborative filtering</strong></li></ol><p>the distinction is really about <em>what</em> the system is learning from.</p><p>content-based filtering learns <strong>attribute patterns</strong>.</p><p>maybe A tends to buy black products, running shoes, or Nike. we use what we know about the items to find more items with those properties.</p><p>collaborative filtering learns <strong>interaction patterns</strong>.</p><p>it doesn’t necessarily need to know why A might like a particular shoe. it might simply <em>learn</em> that people who bought the same things as A also tend to buy this shoe.</p><p>this also means using someone’s history doesn’t automatically make a system collaborative.</p><p>if i use A’s purchase history to learn that A likes black shoes, that’s <em>still</em> content-based.</p><p>the collaborative part begins when interactions across users and items start influencing what we recommend.</p><p>but how do we even represent these interaction patterns?</p><h3>5. Interaction patterns can be compressed into latent representations</h3><p>now we go deeper into collaborative filtering and how we actually use interaction patterns for recommendations.</p><p>Imagine an interaction matrix:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XO9oAHr3mCZwKGpJr9acnA.png" /></figure><p>most user-item pairs are empty. But the observed interactions contain structure.</p><p>in <em>Matrix Factorization Techniques for Recommender Systems</em>, Koren, Bell and Volinsky describe two broad approaches to collaborative filtering:<a href="#fn-2">[2]</a></p><ul><li><strong>neighborhood methods</strong></li><li><strong>latent factor models</strong></li></ul><h4>neighborhood methods</h4><p>this is the intuitive version of collaborative filtering.</p><p>say Joe likes:</p><ul><li>Star Wars</li><li>The Lord of the Rings</li><li>Gladiator</li></ul><p>you find people who liked similar movies, then see what else they liked.</p><p><em>or</em> you can do the item version:</p><blockquote><em>people who rated </em>Saving Private Ryan<em> similarly also tended to rate these other movies similarly.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/1*DFQmijArUCs4uhQuc2YOTQ.png" /><figcaption>Figure 1 from Koren, Bell and Volinsky, “Matrix Factorization Techniques for Recommender Systems” (2009).</figcaption></figure><p>this diagram illustrates this user-neighborhood idea.<a href="#fn-2">[2–1]</a></p><p>so neighborhood methods are basically:</p><blockquote><strong><em>look for similar users or similar items directly.</em></strong></blockquote><p>that’s collaborative filtering in a <strong>very literal sense.</strong></p><h4>latent factor models</h4><p>Koren, Bell and Volinsky explain the alternative: instead of explicitly finding neighbors, we can try to explain behavior using a smaller number of hidden factors inferred from ratings. <a href="#fn-2">[2–2]</a></p><p>for movies, imagine hidden dimensions like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j6-IhdcVdZuLhfNmOtU1Kg.png" /></figure><p>a movie gets a position along those <em>dimensions.</em></p><p>a user also gets a position based on what they tend to like.</p><p>if the user and movie line up well, we predict a high rating.</p><p>but lets get something clear: some factors may have an obvious meaning, but many can be completely uninterpretable.</p><p>we are <strong>not</strong> manually saying:</p><blockquote>dimension 1 = comedy</blockquote><blockquote>dimension 2 = action</blockquote><blockquote>dimension 3 = romance</blockquote><p>the model discovers whatever dimensions are useful for explaining the interactions. some may line up with concepts humans understand, many won’t.</p><p>that’s why they’re called <strong>latent</strong> factors.</p><p>to put it simply: matrix factorization takes the huge user-item matrix and represents it using two much smaller sets of vectors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s61-4g4kTZLHG7bE7OSy6w.png" /></figure><p>so instead of storing a separate relationship for every possible user-item pair, we can represent a user like:</p><pre>User A = [0.8, -0.2, 0.5, ...]</pre><p>and a shoe like:</p><pre>Shoe X = [0.7, -0.1, 0.6, ...]</pre><p>their dot product gives us a compatibility score.</p><p>if you take away only one thing from this idea, let it be this: With the help of matrix factorization, massive amount of interaction data can be compressed into small representations that still preserve useful behavioral patterns.</p><p>this is also why matrix factorization can recommend an item the user has never interacted with before: the model doesn’t need to have seen that exact user-item pair. it only needs their latent representations to be compatible.</p><p>but now we have another problem:</p><p><strong>where do these user and item vectors actually come from?</strong></p><h3>6. Matrix factorization is the model. ALS is one way to learn it.</h3><p>so where do these vectors actually come from?</p><p>we learn them from the interactions we already observed.</p><p>the goal is simple: choose user and item vectors such that their dot products are high for interactions that actually happened, and lower for ones that didn’t.</p><p>there are different ways to learn these vectors.</p><p>one is stochastic gradient descent: make a prediction, measure the error, slightly adjust the user and item vectors, repeat.</p><p>another is <strong>Alternating Least Squares (ALS)</strong>, also discussed by Koren, Bell and Volinsky.<a href="#fn-2">[2–3]</a></p><p>ALS works by alternating:</p><pre>fix all item vectors → solve for user vectors<br>fix all user vectors → solve for item vectors<br>repeat</pre><p><strong>matrix factorization is the model. ALS is just one way of fitting it.</strong></p><p>this also explains where the “collaborative” part comes from.</p><p>when we learn User A’s vector, we are not looking at A in isolation. the item vectors themselves were shaped by interactions from many other users, and those users were in turn shaped by many other items.</p><p>the final prediction may just be:</p><pre>user vector · item vector</pre><p>so if one just sees this final formula they might conclude there is no user-item collaborative learning happening but those two vectors carry information learned from the entire interaction matrix.</p><p><strong>the collaboration happens while learning the representations, not while computing the final score.</strong></p><h3>7. Two-tower models learn a recipe for representations</h3><p>ALS gives us a learned vector for every user and item it has seen.</p><p>this works well until a new item enters the catalog.</p><p>if nobody has interacted with that shoe yet, ALS has almost nothing to learn its vector from.<br>this is called <strong>item cold start.</strong></p><p>but we might already know a lot about the shoe:</p><pre>brand = Nike<br>type = running shoe<br>color = white<br>price = ₹7499</pre><p>a two-tower model lets us use that information directly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z5aCcNiOoNkeEwjKWKbmYw.png" /></figure><p>the two towers are trained so that users and items which interact end up compatible in the same embedding space.</p><p>the distinction from ALS is useful:</p><blockquote><strong><em>ALS learns a vector for an ID. A two-tower model learns a function for producing a vector from features.</em></strong></blockquote><p>so when a new shoe arrives, the item tower can generate a representation for it before that exact shoe has built up much interaction history.</p><p>another common misconception: a two-tower model using product metadata is not automatically “content-based”.</p><p>the inputs might be content features, while the model is still trained from collaborative signals like clicks or purchases across users.</p><p><strong>architecture, input features and training signal are three different things.</strong><br>so before we label an entire model as “content-based” or “collaborative-based”, its useful to separate these three things and look at them individually</p><h3>8. Cold start is two different problems</h3><p>there are two cold starts.</p><p><strong>item cold start:</strong> a new item has little or no interaction history.</p><p>ALS struggles here because it has no useful item vector yet. a two-tower can still build one from metadata like brand, category, text or image.</p><p><strong>user cold start:</strong> a new user has little or no history.</p><p>now both ALS and a history-based two-tower struggle because there is very little to represent the user with.</p><p>so we fall back to signals that don’t need much history: popularity, the current session, the query, context or onboarding preferences.</p><p>the main takeaway is:</p><blockquote><strong><em>cold start is not one problem. ask what information still exists when the history disappears.</em></strong></blockquote><p>before moving on, here’s how these ideas fit together. content and collaborative filtering describe where the evidence comes from. matrix factorization and two-tower describe ways to learn representations from that evidence. ALS is one way to fit a matrix factorization model.</p><p>these aren’t all competing alternatives. a two-tower can use product content while learning from user interactions.</p><figure><img alt="where ‘relevance’ comes from" src="https://cdn-images-1.medium.com/max/1024/1*sB2L_foiPq7a5RtyAJMAig.png" /><figcaption>mindmap 2</figcaption></figure><p>At this point I wanted to test these ideas instead of only reading about them. I used the H&amp;M Personalized Fashion Recommendations dataset on Kaggle and built a recommender that had to predict a customer’s next purchases from a catalog of over 100K products.<a href="#fn-3">[3]</a></p><p>the task was to rank 12 products a customer would buy in the next seven days, using only information available before the prediction cutoff. H&amp;M gives us purchases, not impressions or search logs.</p><p>the code and experiment notes are in <a href="https://github.com/anshulLuhsna/recsys-loom">RecSys Loom</a>. you can follow the implementations and see what worked, what didn’t, and how i evaluated it.</p><p>From here on, I’ll use that system whenever an experiment helped answer one of these questions. The project results come from my RecSys Loom experiment records, rather than the papers cited for the underlying methods.<a href="#fn-4">[4]</a></p><h3>9. Retrievers should complement each other</h3><p>if two-tower can handle things ALS struggles with, should we just replace ALS?</p><p>not necessarily.</p><p>ALS and two-tower learn different kinds of relevance.</p><p>ALS is very good at capturing specific behavioral patterns around known users and items.</p><p>a metadata two-tower is better at generalizing from what we know about the user or item.</p><p>standalone recall tells us how strong a retriever is by itself.</p><p>in a system with multiple retrievers, we also care about how many relevant items it adds that weren’t already being found.</p><p>in our H&amp;M system, the two-tower had very little overlap with ALS and added relevant products that weren’t already in the candidate pool.</p><p>even a weaker retriever can therefore be valuable if it finds different things.</p><p><strong>the value of a retriever depends on what it contributes to the combined candidate pool.</strong></p><h3>10. More retrieval is not free</h3><p>after idea 9, a reasonable question is:</p><blockquote>why not take hundreds or thousands of candidates from every retriever?</blockquote><p><strong>because the ranker still has to choose 12.</strong></p><p>adding candidates gives it more chances to find a future purchase, but also more items to score and more irrelevant items that might receive high scores.</p><p>retrieval recall asks whether the relevant products made it into the candidate pool. it doesn’t tell us whether they survived into the final list.</p><p>for that, we look at <strong>MAP@12</strong>, which measures how highly the relevant products appear in the final top 12, averaged across users.</p><p>suppose we increase the number of candidates we take from the two-tower, merge them with the other sources, and run the ranker each time.</p><p>these numbers are illustrative, not measurements from the H&amp;M run:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dIGFzuE8qwKZz4uiPABReA.png" /></figure><p>recall alone would tell us to take 200 candidates.</p><p>but in this example, taking 50 produces the best final list. beyond that, we pay to score more products and get worse ordering.</p><p>that is what a candidate budget controls: how many places each retriever gets in the merged pool.</p><p>in the H&amp;M project, i swept different two-tower budgets and saw the same tradeoff. higher recall did not consistently produce higher MAP, and we kept a two-tower budget of 50.</p><p>so when deciding how many candidates to take from a source, measure the list the user would actually receive, along with the cost of producing it.</p><p><strong>choose retrieval budgets by the final ranking result, within the system’s cost budget.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q-eEr--ggsFe4mYnKcEIsQ.png" /><figcaption>mindmap 3</figcaption></figure><h3>11. Repeat purchases are not a guarantee</h3><p>one easy retrieval strategy is to recommend things the user has bought before.</p><p>whether that makes sense depends heavily on the domain.</p><p>for groceries, repeat purchase is almost <em>obvious.</em></p><p>for fashion, i would have expected it to matter much less.</p><p>but in the H&amp;M data, exact repeats turned out to be one of the strongest signals we had. later-purchased items that were exact repeats reached the final Top-12 far more often than new items that were merely similar in product type.</p><p>so repeat purchase became its own retrieval source.</p><p><strong>every retrieval strategy is making an assumption about how users behave. test that assumption against the data before deciding how important it should be.</strong></p><h3>12. The negatives you choose define the problem the model learns</h3><p>training a recommender needs examples of what the user wanted and what they didn’t.</p><p>positives are easy enough.</p><p>if a user bought a shoe, we can treat that interaction as a positive.</p><p>negatives? not so easy to define.</p><p>if the user didn’t buy another shoe, that doesn’t necessarily mean they disliked it.</p><p>maybe they never saw it.</p><p>maybe it was out of stock.</p><p>maybe they liked it but bought something else.</p><p>so a negative often just means:</p><blockquote><strong><em>we did not observe a positive interaction.</em></strong></blockquote><p>now suppose the positive is a running shoe.</p><p>a random negative might be:</p><p>running shoe vs baby socks</p><p>an easy distinction.</p><p>a hard negative might be:</p><p>running shoe bought by the user</p><p>vs</p><p>another running shoe they didn’t but</p><p>a much finer distinction.</p><p>with enough data, hard negatives can be useful because random negatives eventually become too easy and stop teaching the model much.</p><p>but the negatives still need to represent the problem the model will actually face.</p><p>in the H&amp;M project, i tried replacing much of the full candidate set with hard negatives.</p><p>performance got <strong>worse.</strong></p><p>my hypothesis is that by focusing too heavily on difficult cases, we gave the model a narrower view of the candidate pool and threw away useful examples of easier distinctions.</p><p>the model has to rank all kinds of candidates, so it helps to train it on all kinds of candidates.</p><p><strong>the negatives you choose define the distinctions the model learns to make.</strong></p><h3>13. More supervision can matter more than a fancier model</h3><p>early on, our H&amp;M ranker had only around 446 positive examples.</p><p>after adding more temporal training weeks, that became roughly 7,177.</p><p>MAP@12 improved from about:</p><p>0.015<strong> -&gt; 0.0256</strong></p><p>without changing to a fundamentally more complicated model.</p><p>the bottleneck was not model capacity. it was lack of supervision.</p><p><strong>before adding complexity, check whether the model simply needs more examples of the problem.</strong></p><p>this might sound obvious but im just stating all the factors you should consider BEFORE adding more complexity to your models.</p><h3>14. Ranking can use richer signals than retrieval</h3><p>as the candidate funnel gets smaller, the feature funnel can get bigger.</p><p>retrieval starts with a huge catalog, so scoring each item has to be cheap at request time. the embeddings themselves can still contain rich information computed beforehand.</p><p>ranking sees a much smaller candidate set, so it can afford a richer view of each item.</p><pre>candidates:   millions       →  hundreds<br>scoring:      cheap matching →  richer comparisons</pre><p>in our H&amp;M ranker, this meant combining signals like ALS score, two-tower score, repeat purchase, recency, popularity and how many retrievers found the item.</p><p>two products can have similar ALS scores but very different evidence behind them.</p><p>was one bought recently? did three retrievers find it, or only one? does it match the customer’s usual categories?</p><p>the ranker can compare these signals together for each candidate. a retrieval score on its own doesn’t tell us all of that.</p><p>we can also include an LLM as an optional reranker once the candidate set is small enough.</p><p>the smaller the candidate set, the richer the feature set you can afford.</p><h3>15. Model complexity has to fit the data regime</h3><p>okay this one is a bit long but stay with me.</p><p>sometimes a feature isn’t very meaningful on its own. the useful signal is in how it <em>interacts </em>with another feature.</p><p>say:</p><pre>ALS score = high<br>two-tower score = high</pre><p>either score alone says the item looks promising.</p><p>both being high might be <strong>much stronger evidence</strong> because two very different retrieval methods independently agree on the item.</p><p>or take:</p><pre>repeat purchase = yes<br>days since last purchase = 5</pre><p>that might mean something very different from:</p><pre>repeat purchase = yes<br>days since last purchase = 300</pre><p>these interactions between features are usually called <strong>feature crosses</strong>.</p><p>you could manually create features for every combination you think might matter:</p><pre>ALS × two-tower<br>repeat × recency<br>popularity × source count<br>...</pre><p>but this gets out of hand quickly. once you have dozens or hundreds of features, there are far too many possible interactions to manually design all of them.</p><p>this is what made Wang and colleagues’ <strong>DCN V2, or Deep &amp; Cross Network V2</strong>, interesting.<a href="#fn-5">[5]</a></p><p>it has a cross network specifically designed to learn interactions between features, alongside a deep network that can learn more general patterns.</p><p>and our H&amp;M ranker seemed like a pretty reasonable place to try it.</p><p>we already had signals like:</p><pre>ALS score<br>two-tower score<br>source ranks<br>source count<br>repeat purchase<br>recency<br>popularity<br>category affinity</pre><p>there were clearly useful relationships between them.</p><p>so the thinking was reasonable:</p><blockquote><em>if feature interactions matter this much, maybe a model designed specifically to learn them should beat our tree-based ranker.</em></blockquote><p>it <strong>didn’t.</strong></p><p>in one of our controlled comparisons:</p><pre>MLP        ≈ 0.0119 MAP@12<br>DCN V2     ≈ 0.0134 MAP@12<br>LambdaRank ≈ 0.0256 MAP@12</pre><p>DCN V2 could fit the training data increasingly well while its validation performance got <em>worse.</em></p><p><strong>that was a pretty clear sign of overfitting.</strong></p><p>one possible explanation is the kind of data we were giving the ranker.</p><p>we weren’t asking it to learn directly from raw images, text or massive behavioral sequences.</p><p>a lot of the hard work had already happened before ranking.</p><p>ALS had already compressed collaborative behavior into a score.</p><p>the two-tower had already learned another representation of user-item compatibility.</p><p>we had already calculated recency, repeat behavior, popularity, source agreement and other useful signals.</p><p>by the time the ranker saw the data, it looked more like a structured table:</p><pre>candidate | ALS | TT | repeat | recency | popularity | source_count | ...</pre><p>tree models are known to work well with this kind of structured data, and they can naturally learn relationships like:</p><pre>if repeat = yes<br>and recency &lt; 30 days<br>→ score higher</pre><p>or:</p><pre>if ALS is high<br>and source_count &gt;= 3<br>→ score higher</pre><p>so one reasonable explanation is that the tree ranker was already a strong fit for the features and amount of supervision we had, while DCN V2’s extra flexibility made it easier to overfit.</p><p>but i didn’t isolate that explanation experimentally.</p><p>what i actually know for sure: DCN V2 overfit, and the tree ranker generalized much better on our validation data.</p><p>so the thing im taking away is, <strong>for the amount of supervision and the kind of features we had, the simpler tree ranker generalized much better.</strong></p><p><strong>model complexity has to be earned by the data.</strong></p><h3>16. Explicit feature crosses don’t automatically help</h3><p>after thinking so much about feature interactions, i tried creating some of them manually.</p><p>for example:</p><pre>ALS × two-tower<br>two-tower × source count<br>repeat purchase × recency<br>popularity × source count</pre><p>the idea was to expose useful combinations directly to the ranker.</p><p>it didn’t help.</p><pre>original ranker ≈ 0.02799 MAP@12<br>with explicit crosses ≈ 0.02606 MAP@12</pre><p>we can speculate that the tree model was already capturing enough of these interactions, but our experiment doesn’t prove that.</p><p>what it does show is:</p><p><strong>an interaction sounding useful does not mean explicitly adding it as a feature will improve the model.</strong></p><h3>17. Separate what the experiment showed from why you think it happened</h3><p>this one is a bit of a note to self.</p><p>later, CatBoost YetiRank beat our tuned LightGBM LambdaRank.</p><p>that part is easy to say.</p><pre>LightGBM MAP@12 ≈ 0.0280<br>CatBoost MAP@12 ≈ 0.0299</pre><p>CatBoost won on both development folds, so i kept it.</p><p>what is harder to say with confidence is <strong>why</strong>.</p><p>maybe CatBoost regularized better.</p><p>maybe YetiRank matched our ranking problem better.</p><p>maybe its tree structure worked better for our features.</p><p>all of these are plausible.</p><p><strong>none of them were isolated by the experiment.</strong></p><p>the experiment proved:</p><blockquote><em>CatBoost performed better in this setup.</em></blockquote><p><em>it did not prove:</em></p><blockquote><em>CatBoost performed better because of X.</em></blockquote><p>this sounds obvious, but it is very easy to look at a result and immediately invent a clean story around it.</p><p><strong>measurements tell you what happened. explanations need their own evidence.</strong><br>do not be tempted to explain away without evidence.</p><h3>18. Improving one component can make the whole system worse</h3><p>idea 10 was about how many candidates to take from a retriever.</p><p>now suppose we improve the retriever itself. surely that should help?</p><p>we tried adding richer product text to our two-tower. measured on its own, retrieval improved:</p><pre>two-tower Recall@500<br>0.0733 → 0.1479</pre><p>at the same cutoff of 500 candidates per user, recall had roughly <strong>doubled.</strong></p><p><strong>but after merging candidates and ranking them, MAP@12 went down.</strong></p><p>the thing to not miss was where the newly retrieved relevant products ended up. <strong>their median rank in the final ranking was about 501.</strong></p><p>retrieval got credit for finding them. the user, who only saw 12 products, <strong>would never reach most of them.</strong></p><p>this tells us that the extra recall wasn’t turning into useful top-12 placements. it doesn’t establish why, or explain the entire MAP drop. the ranking features, supervision and changed mix of candidates are things to investigate, not conclusions from this result alone.</p><p>so a retriever upgrade needs two checks:</p><ol><li>does it find more relevant products,</li><li>and does the full system put those products where the user can see them?</li></ol><p><strong>a better retrieval metric is a reason to test the full pipeline, not a reason to replace the retriever yet.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aK1LTywoLSmmZsD8ATwt6Q.png" /><figcaption>mindmap 4</figcaption></figure><h3>19. Recommendation and search share a funnel, but intent enters differently</h3><p>this brings us back to the search problem that started the article.<br> recommendation and search are different problems, but they share the same retrieve-then-rank intuition.</p><p>in recommendation, we are trying to infer what the user might want from their history, behavior and context.</p><p>in search, the user simly <em>tells</em> us.</p><pre>recommendation:<br>user + history → retrieve → rank</pre><pre>search:<br>query + user → retrieve → rank</pre><p>so the machinery can look very similar. what changes is the source of relevance.</p><p>a recommendation ranker might ask:</p><blockquote><em>how relevant is this item to this user?</em></blockquote><p>a search ranker asks:</p><blockquote><em>how relevant is this item to this query?</em></blockquote><p>and personalized search becomes:</p><blockquote><em>how relevant is this item to this query, for this user?</em></blockquote><p>that explicit query intent should usually dominate everything else.</p><h3>20. Hard constraints and soft preferences belong in different places</h3><p>consider:</p><blockquote><strong><em>black running shoes under ₹5000 for an office party</em></strong></blockquote><p>we first need a query-understanding layer to turn this into structured intent.</p><p>something like:</p><pre>product_type = running shoes<br>color = black<br>price_max = 5000<br>occasion = office party</pre><p>then we decide how strongly each piece should be enforced.</p><p>a useful rule is:</p><blockquote><em>if violating it would make the result obviously wrong, it is probably a hard constraint.</em></blockquote><p>under ₹5000 is a good example.</p><p>size 9 or in stock are even clearer.</p><p>something like good for an office party is <strong><em>subjective</em></strong>. there is no boundary as such where one shoe suddenly stops being suitable.</p><p>that belongs in <strong>ranking.</strong></p><p>so the system can look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E6z4Vixa84-IKtfBNiuMvw.png" /></figure><p>this policy can be simple code.</p><p>for example:</p><pre>price, size, availability → hard<br>occasion, style, vibe → soft</pre><p>with confidence and context for ambiguous cases.</p><p>black shoes may mean color = black.</p><p>black tie shoes should probably not.</p><p>an LLM or lightweight model can help interpret the language and propose the structure, while deterministic rules decide which constraints we are willing to enforce strongly.</p><p>hard constraints remove candidates.</p><p>soft preferences change their scores.</p><h3>21. Lexical and semantic retrieval solve different failures</h3><p>suppose someone searches:</p><blockquote><em>Nike Air Max 270</em></blockquote><p>the exact words matter.</p><p>BM25 is very good at this kind of query.</p><p>now consider:</p><blockquote><em>something light and comfortable for a summer office</em></blockquote><p>exact word overlap becomes much less useful.</p><p>semantic embeddings can connect that query with products whose descriptions use different words but mean roughly the same thing.</p><p>so a search system can retrieve from both.</p><pre>query<br>├── lexical retrieval<br>└── semantic retrieval<br>        ↓<br>   combined candidates</pre><p>one protects <strong>exact matches.</strong></p><p><strong>the other helps when the words change but the meaning <em>doesn’t.</em></strong></p><h3>22. Query intent should dominate personalization</h3><p>say a user normally buys black hoodies.</p><p>today they search:</p><blockquote><em>red formal dress</em></blockquote><p>their history can still help, but it shouldn’t pull black hoodies into the results.</p><p>the query already told us what they want right now.</p><p>personalization becomes useful after we have products that satisfy that intent.</p><pre>query relevance<br>→ then personalize among relevant products</pre><p>search gives us explicit information that recommendation usually has to infer.</p><p><strong>we HAVE to use it.</strong></p><h3>23. Evaluate image representations against the task</h3><p>fashion is <strong>visual</strong>, so using image embeddings for recommendations felt like an obvious idea.</p><p>i tried image retrieval using DINOv2, the visual representation model introduced by Oquab and colleagues.<a href="#fn-6">[6]</a></p><p><strong>it didn’t help much</strong>.</p><p>later, i used CLIP, Radford and colleagues’ model trained on image–text pairs, for queries describing visual properties of products.<a href="#fn-7">[7]</a></p><p>that worked <strong><em>much better.</em></strong></p><p>both the model and what i was asking it to do had changed.</p><blockquote>&quot;which visually similar product will this user buy next?&quot;</blockquote><p>is a much less direct question than:</p><blockquote>&quot;which product looks like what this query describes?&quot;</blockquote><p>so this wasn’t a controlled comparison. i can’t put the different results down to the task alone.</p><p><strong>a representation is only useful relative to the task you give it.</strong></p><h3>24. How you use the LLM matters</h3><p>Netflix’s GenRec is a useful example of an LLM-backed <strong>ranker</strong>, but its design needs a distinction here.<a href="#fn-8">[8]</a></p><p><strong>GenRec can score the full Netflix catalog in one forward pass.</strong> it can also rank a supplied candidate set; it doesn’t require a small retrieved set first.</p><p>Netflix turns user history and context into language. the LLM encodes that input, and a catalog-aware scoring head produces item scores.</p><p>roughly:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iA4JaU59zQFuh8KmIXG3vw.png" /></figure><p>they first adapt a foundation model to Netflix data, then post-train it for recommendation ranking. prefill-only inference avoids normal token-by-token generation when producing the ranking.</p><p>the thing i took away is that <strong>the scoring architecture and serving cost matter as much as the choice to use an LLM.</strong></p><p>for our shoe-search problem, i would still place an LLM <strong>near the end of the funnel </strong>as an optional reranker over retrieved products.</p><p>that’s my design choice for this problem, not a reproduction of GenRec’s full-catalog scoring architecture.</p><h3>25. Check the final results against the constraints</h3><p>once we’ve interpreted the query and validated its constraints, the final results still have to satisfy them.</p><p>that includes after an optional LLM reranker changes the list.</p><pre>price &lt;= ₹5000<br>inventory &gt; 0<br>size available<br>seller allowed</pre><p>a useful architecture is:</p><pre>ranked candidates<br>→ optional LLM reranker<br>→ validate returned product IDs<br>→ deterministic rules enforce the constraints<br>→ final results</pre><p>your job as the designer is to make sure everything is playing to its strengths.<br>the model helps with ambiguity.<br>the system still enforces the guarantees.</p><p>that guarantees the results satisfy the validated constraints. it doesn’t guarantee we understood every part of the query correctly.</p><p>here’s another mindmap. the search path (right side) is what we covered from Ideas 19–25.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E9F8DJxXQBe86hhzus4CZg.png" /><figcaption>mindmap-5</figcaption></figure><h3>26. Sequence models matter when order contains information</h3><p>so far, most of our user representations have compressed history without caring much about the order in which things happened.</p><p>PinnerFormer, described by Pancha and colleagues in <em>PinnerFormer: Sequence Modeling for User Representation at Pinterest</em>, takes a different approach.<a href="#fn-9">[9]</a></p><p>it looks at a sequence of a user’s recent actions on Pinterest and turns that sequence into a <strong>user embedding</strong> which is basically a compact representation of what that user is interested in.</p><p>roughly:</p><pre>Pin A<br>→ Pin B<br>→ Pin C<br>→ Pin D<br>       ↓<br> PinnerFormer<br>       ↓<br> user representation</pre><p>the important part is that:</p><pre>A → B → C</pre><p>can carry different information from:</p><pre>C → A → B</pre><p>because recent behavior can reveal how someone’s interests are evolving.</p><p>PinnerFormer also does something interesting with the training objective.</p><p>many sequence recommenders try to predict the user’s <strong>next action</strong>.</p><p>Pinterest instead trained PinnerFormer to predict a broader set of the user’s <strong>future actions over a longer window</strong> using what they call a dense all-action loss.</p><p>so the representation is trying to capture something more durable than:</p><blockquote><em>what will this user click next?</em></blockquote><p>it is more like:</p><blockquote><strong><em>what is this user’s current state of interest, such that it helps explain what they will engage with over the near future?</em></strong></blockquote><p>Pinterest then generates these user embeddings in batch, roughly once a day, and uses them downstream for personalization. The paper’s goal was to get much of the benefit of realtime sequence modeling without requiring the entire representation to be recomputed after every action.</p><p>this works especially well for Pinterest because they have rich sequences of behavior: views, saves, clicks and other actions.</p><p>unfortunately i couldn’t implement this myself because our H&amp;M data mostly had purchases.</p><p>a sequence of 200 mixed actions can tell you a lot about how a user’s intent is changing.</p><p>a sequence of a few purchases tells you much less.</p><p><strong>sequence models become useful when the order and evolution of behavior contain enough information to justify modeling them.</strong></p><h3>27. Evaluation design is part of the system</h3><p>recommendation happens over time.</p><p>the evaluation has to respect that.</p><p>if we use future information while building features or tuning models, the offline result can look better than anything we could have achieved in the real system.</p><p>during the H&amp;M project, i had already inspected the final calendar week during earlier experiments.</p><p>so it could no longer honestly be treated as a completely untouched future test set.</p><p>so i eventually froze the system and evaluated it once on a reserved set of customers.</p><blockquote><strong><em>when evaluating a prediction, only use information that would have existed when the prediction was made.</em></strong></blockquote><p><em>another note to self.</em></p><h3>28. dont treat offline metric as product success</h3><p>our final H&amp;M system reached around:</p><pre>MAP@12 = 0.0307</pre><p>on the customer holdout.</p><p>that tells us the system became better at putting products users later bought near the top of the list.</p><p>it does not tell us whether deploying those recommendations would:</p><pre>increase purchases<br>increase revenue<br>improve satisfaction<br>improve retention</pre><p>offline evaluation measures how well we reproduce observed behavior.</p><p>an online experiment tells us what changes because we deployed the system.</p><p><strong>those are different questions.</strong></p><h3>29. Competition systems and production systems solve different versions of the problem</h3><p>the H&amp;M dataset came from a Kaggle competition, so we can also look at what the strongest competitors actually did.</p><p>the first-place team’s solution write-up called candidate generation the key part of the competition. their pipeline generated candidates first, then used engineered user/item/interaction features and LightGBM models to score them. for final inference they generated around 400 candidates per customer and ranked them down to the final 12.<a href="#fn-10">[10]</a></p><p>the second-place team’s write-up was <strong>even more interesting.</strong><a href="#fn-11">[11]</a></p><p>the component described by <em>wht1996</em> started with roughly 600 popular products per user, used a LightGBM model to reduce that to around 130 candidates, added the user’s historical purchases, and then used another LightGBM model for the final ranking.</p><p>in the third-place write-up,<em> sirius </em>also described candidate generation followed by ranking. its candidates came from several sources: popular items, recent purchases, related items, demographic popularity and products sharing the same product name. the final ranking ensemble used features like matrix-factorization similarity, item-to-item similarity, popularity, recency and which retrieval strategy produced the candidate.<a href="#fn-12">[12]</a></p><p>so even among very different solutions, the same pattern kept appearing:</p><pre>multiple candidate sources<br>→ feature engineering<br>→ boosted-tree ranking<br>→ Top 12</pre><p>that is useful evidence for the ideas in this article.</p><p><strong>but Kaggle is still a different problem from production.</strong></p><p>the leaderboard only cares about the final offline metric.</p><p><strong>a production recommender also has to survive latency limits, changing inventory, new items, failures, feedback loops and users whose behavior changes after seeing the recommendations.</strong></p><p>competition solutions tell us a lot about what can work offline.</p><p>production adds another set of constraints on top.</p><h3>30. Architecture should follow the data regime</h3><p>after reading enough recommendation papers, it becomes very easy to collect architectures.</p><p>YouTube uses one thing.</p><p>Pinterest uses another.</p><p>Netflix uses something else.</p><p>but our H&amp;M experiments kept bringing us back to the same lesson.</p><p>two-tower helped, but only at a controlled candidate budget.</p><p>richer text improved retrieval and hurt the final ranking.</p><p>image retrieval didn’t help next-purchase recommendation.</p><p>DCN V2 overfit.</p><p>more supervision helped enormously.</p><p>CatBoost eventually became our best ranker.</p><p>the papers gave us useful ideas to test.</p><p>the data decided which ones survived.</p><blockquote><strong>choose the architecture for the problem and the data you actually have.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*oRlYZeTPgrPLSFvEfa_kkg.png" /><figcaption>mindmap 6</figcaption></figure><h3>Back to the shoe website</h3><p>so, what would i actually build for the question at the beginning?</p><p>take the query:</p><blockquote><em>black running shoes under ₹5000 for an office party</em></blockquote><p>first, turn it into <strong>structured intent.</strong></p><p>running shoes, black and the price limit are explicit requirements. suitability for an office party is a softer preference. an LLM can help interpret the language, but the extracted constraints still need validation.</p><p>then <strong>retrieve from the eligible catalog.</strong> lexical retrieval protects exact product and brand matches. semantic retrieval can help with descriptions like the occasion. keep the original query available to retrieval too.</p><p><strong>merge the candidates and rank them for the query. </strong>now we can use richer product details and, if we have useful user history, personalize among products that already satisfy the intent.</p><p><strong>if an LLM reranker earns its cost, let it reorder a small shortlist of actual product IDs.</strong> if it times out or returns something invalid, keep the existing ranking.</p><p>before returning the final list, <strong>check those IDs, the price limit and current availability again.</strong> if nothing satisfies the constraints, say so.</p><p>that’s where i’d put the agent: <strong>helping with interpretation and possibly the last ranking step. the system still owns candidate selection, validation and enforcement.</strong></p><p>this is the design i’d propose for the shoe website. the H&amp;M project helped me test the retrieval and ranking ideas; it doesn’t contain live price or inventory data to validate that entire design.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*q1ENt_godVGZG3k7QCS4bg.png" /></figure><p>this is the architecture i ended up drawing roughly in the actual interview.</p><p>i am fascinated by recommendation systems (especially the ones that operate at the scale of Youtube, Netflix, Pinterest) and i hope atleast some of these ideas clicked for you as well.</p><p>thanks for reading :)</p><h3>References</h3><ol><li>Paul Covington, Jay Adams and Emre Sargin. <a href="https://research.google/pubs/deep-neural-networks-for-youtube-recommendations/"><em>Deep Neural Networks for YouTube Recommendations</em></a>. RecSys, 2016.</li><li>Yehuda Koren, Robert Bell and Chris Volinsky. <a href="https://doi.org/10.1109/MC.2009.263"><em>Matrix Factorization Techniques for Recommender Systems</em></a>. IEEE Computer, 2009. Figure 1 illustrates user-neighborhood recommendation.</li><li>H&amp;M. <a href="https://www.kaggle.com/competitions/h-and-m-personalized-fashion-recommendations/data"><em>H&amp;M Personalized Fashion Recommendations</em></a>. Kaggle competition dataset, 2022.</li><li>Anshul Kalbande. <em>RecSys Loom</em>: <a href="https://github.com/anshulLuhsna/recsys-loom/blob/1cf26a445681af08b6d3fd734e24ef3718896f71/OVERNIGHT_RESULTS.md">experiment results</a>, <a href="https://github.com/anshulLuhsna/recsys-loom/blob/1cf26a445681af08b6d3fd734e24ef3718896f71/docs/evaluation_ledger.md">evaluation ledger</a> and <a href="https://github.com/anshulLuhsna/recsys-loom/blob/1cf26a445681af08b6d3fd734e24ef3718896f71/docs/experiment_ledger.md">experiment ledger</a>. Project records, 2026, linked to a fixed repository revision. These are the sources for my local experimental results, not independently published benchmarks.<a href="#fnref-4">︎</a></li><li>Ruoxi Wang, Rakesh Shivanna, Derek Z. Cheng, Sagar Jain, Dong Lin, Lichan Hong and Ed H. Chi. <a href="https://arxiv.org/abs/2008.13535"><em>DCN V2: Improved Deep &amp; Cross Network and Practical Lessons for Web-scale Learning to Rank Systems</em></a>. arXiv preprint, 2020; published at The Web Conference, 2021.</li><li>Maxime Oquab et al. <a href="https://arxiv.org/abs/2304.07193"><em>DINOv2: Learning Robust Visual Features without Supervision</em></a>. arXiv preprint, 2023.</li><li>Alec Radford et al. <a href="https://arxiv.org/abs/2103.00020"><em>Learning Transferable Visual Models From Natural Language Supervision</em></a>. ICML, 2021. Introduces CLIP.<a href="#fnref-7">︎</a></li><li>Ying Li, Shradha Sehgal, Arjun Rao, Rein Houthooft, Yaochen Zhu and Ashish Rastogi. <a href="https://arxiv.org/abs/2608.10257"><em>GenRec: An LLM-Backed Recommendation Ranker at Netflix</em></a>. arXiv preprint, 2026. See Sections 3 and 4 for full-catalog ranking, the scoring head and prefill-only inference. Related engineering article: Ying Li, Arjun Rao and Shradha Sehgal, <a href="https://netflixtechblog.com/genrec-towards-llm-native-recommendation-at-netflix-f20be6f643e3"><em>GenRec: Towards LLM-Native Recommendation at Netflix</em></a>, Netflix Technology Blog, 2026.</li><li>Nikil Pancha, Andrew Zhai, Jure Leskovec and Charles Rosenberg. <a href="https://arxiv.org/abs/2205.04507"><em>PinnerFormer: Sequence Modeling for User Representation at Pinterest</em></a>. KDD, 2022.<a href="#fnref-9">︎</a></li><li>senkin13 and team. <a href="https://www.kaggle.com/competitions/h-and-m-personalized-fashion-recommendations/discussion/324070"><em>1st place solution</em></a>. H&amp;M Personalized Fashion Recommendations, Kaggle, 2022.<a href="#fnref-10">︎</a></li><li>wht1996 and Paweł Jankiewicz. <a href="https://www.kaggle.com/competitions/h-and-m-personalized-fashion-recommendations/writeups/hello-world-2nd-place-solution"><em>2nd place solution</em></a>. H&amp;M Personalized Fashion Recommendations, Kaggle, 2022. The 600 → 130 candidate pipeline is wht1996’s component.<a href="#fnref-11">︎</a></li><li>sirius (sirius81). <a href="https://www.kaggle.com/competitions/h-and-m-personalized-fashion-recommendations/discussion/324129"><em>3rd place solution</em></a>. H&amp;M Personalized Fashion Recommendations, Kaggle, 2022.<a href="#fnref-12">︎</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9987f74d6a14" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[what telephone degradation does to hindi whisper models]]></title>
            <link>https://medium.com/@anshulkalbande/what-telephone-degradation-does-to-hindi-whisper-models-25ceff3e9d4b?source=rss-3164f83e8b6a------2</link>
            <guid isPermaLink="false">https://medium.com/p/25ceff3e9d4b</guid>
            <category><![CDATA[audio]]></category>
            <category><![CDATA[text-to-speech]]></category>
            <category><![CDATA[voice-assistant]]></category>
            <category><![CDATA[fine-tuning]]></category>
            <category><![CDATA[openai-whisper]]></category>
            <dc:creator><![CDATA[Anshul Kalbande]]></dc:creator>
            <pubDate>Sun, 02 Aug 2026 12:15:59 GMT</pubDate>
            <atom:updated>2026-08-02T12:15:59.340Z</atom:updated>
            <content:encoded><![CDATA[<p>18,000 recordings. 3,000 training steps. A 10-point WER improvement. And a model that failed the test that mattered.</p><p>let me define the terms in the title first:</p><p>telephone degradation -&gt; audio has a sampling rate, a bit like video has a frame rate. a higher sampling rate lets us capture a wider range of frequencies.</p><p>a traditional telephone channel samples audio at 8 kHz, which is quite low compared with other forms of recording. even at 8 kHz, the Nyquist-Shannon sampling theorem tells us that we can only represent frequencies up to 4 kHz.</p><p>the missing frequencies contain useful speech details, especially for consonant sounds. converting an 8 kHz recording into a 16 kHz file gives Whisper the correct input format, but it does not bring those details back. the model receives a valid audio file with less information inside it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*d6DEFXDjgEFapQJP" /><figcaption>upsampling the telephone version back to 16 kHz changes the file format. the missing frequencies remain missing.</figcaption></figure><p>so why do we still use 8 kHz in telephony?</p><p>because telephone networks were designed to transmit understandable speech efficiently, not to preserve the full quality of a human voice.</p><p>most of the frequency information required to understand a conversation lies within a relatively narrow range. traditional telephone systems preserve roughly 300 Hz to 3.4 kHz. an 8 kHz sampling rate is enough to carry this range while keeping the amount of transmitted data low.</p><p>this mattered when telephone infrastructure was being developed. lower bandwidth meant that more calls could travel through the same network, with lower transmission and storage costs. standards and codecs such as G.711 were built around these constraints, and 8 kHz remained common across traditional phone networks and call-centre recordings.</p><p>humans can usually understand this audio because we use context to fill in missing details. an ASR model works differently. it has learned relationships between acoustic patterns and words from its training data. but when the telephone channel removes frequency information or introduces codec distortion, those patterns change.</p><p>this leads to the question behind this experiment:</p><blockquote><em>do different Hindi Whisper models lose the same amount of accuracy when the exact same speech is passed through a telephone channel?</em></blockquote><h3>what are Hindi Whisper models?</h3><p>Whisper converts spoken audio into text and was trained on multilingual speech, including Hindi.</p><p>the original Whisper models can recognise Hindi, but they are general-purpose models. a model can be further trained on Hindi speech so that its weights become better adapted to Hindi pronunciation, vocabulary, and speaking patterns. the saved result of this additional training is often called a fine-tuned checkpoint.</p><p>i primarily compared two Hindi-tuned checkpoints: ARTPARK Whisper-medium and Adalat Whisper-small.</p><p>both are based on Whisper, but they differ in model size and training data. ARTPARK uses the larger Whisper-medium architecture, while Adalat uses Whisper-small and requires less computation during inference.</p><p>that gives us the comparison i care about.</p><p>the smaller model is faster, but does it also lose more accuracy when the same speech is passed through a telephone channel?</p><h3>how is speech recognition accuracy measured?</h3><p>it is dead simple. WER is based on the minimum number of edits needed to turn the model transcript into the reference:</p><p>WER = (substitutions + deletions + insertions) / reference words</p><p>where:</p><ul><li><strong>substitution:</strong> the model predicts the wrong word.</li><li><strong>deletion:</strong> the model misses a reference word.</li><li><strong>insertion:</strong> the model adds a word that was never spoken.</li></ul><p>a WER of 20% roughly means one word error for every five reference words. WER can exceed 100% if the model inserts many additional words.</p><p>WER is imperfect. it treats every word edit equally, even though confusing a person’s name may matter more than missing a filler word.</p><p>there’s also CER, which performs the same calculation at the character level and helps reveal smaller spelling differences. for the main comparisons, however, we use WER.</p><h3>GramVaani</h3><p>Gram Vaani is an Indian social technology company behind Mobile Vaani, a phone-based community platform. people can call from a basic phone, without internet, to record messages or listen to what others have posted. some of those calls were later transcribed and released as the GramVaani speech dataset.</p><p>that gives us real spontaneous Hindi telephone speech instead of sentences recorded in a studio. it also gives us regional accents, background noise, inconsistent recording quality and messy transcripts. exactly the kind of audio that makes ASR difficult.</p><p>i started with this dataset. the initial result appeared to confirm that 8 kHz audio was the main problem, but the comparison had an important flaw.</p><p>we first tested on 50 recordings, of which 32 were 8 kHz recordings. Whisper-small produced 92.39% WER on the native 8 kHz group and 70.03% on the higher-rate group. this looked like a telephone-channel penalty of more than 22 WER points… at first.</p><p>upon digging deeper though, i found that the two groups did not contain the same speech. they had different speakers, gender distributions, topics, noise levels, and recording conditions. any of these differences could have contributed to the higher WER.</p><p>to measure the effect of the channel itself, we needed to keep the speaker, utterance, and transcript fixed while changing only the audio condition.</p><h3>building a fair comparison</h3><p>so i did the obvious thing: take one recording and create several versions of it.</p><ul><li>the original recording</li><li>audio limited to an 8 kHz telephone channel</li><li>8 kHz audio passed through G.711 A-law</li><li>8 kHz audio passed through G.711 μ-law</li><li>8 kHz audio passed through GSM</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kYU912V-lD1qXYkIAMKz5w.png" /></figure><p>the codec versions were band-limited first because that is closer to what happens during a telephone call. all the final files were converted back to 16 kHz before being given to Whisper, since that is the input rate Whisper expects.</p><p>now the speaker, words, accent, microphone and background noise remain the same. only the audio channel changes. both models also receive the same files with the same transcription settings.</p><p>this gives us a paired comparison. instead of comparing two unrelated groups of recordings, we can measure how much each model gets worse on a degraded copy of the same speech.</p><p>we call this difference the <strong>channel penalty</strong>:</p><p><strong>channel penalty = WER on degraded audio − WER on original audio</strong></p><p>the larger the penalty, the more accuracy the model loses because of the telephone transformation.</p><h3>so what did we find?</h3><p>now we can return to the original question without mixing up different speakers and recordings: do both models lose the same amount of accuracy?</p><p>i first ran this paired comparison on Vaani, which is a different dataset from GramVaani. i selected one recording from each of 500 speakers and created all five versions of every recording.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iuvdse9MLdQjxOC1TfpT9A.png" /></figure><p>ARTPARK lost less than half a WER point. Adalat lost 2.80 points on the exact same speech transformations. the difference between their channel penalties was 2.32 points.</p><p>but how do we know that this was not caused by a few unusual speakers?</p><p>i used a bootstrap test, which basically repeats the calculation thousands of times with different samples of speakers. after 20,000 repetitions, the estimated gap remained between 1.66 and 3.00 WER points in 95% of the samples. since this range stayed above zero, the difference was unlikely to be random.</p><p>there was still another problem. ARTPARK had already been trained on Vaani data, so it might have been unusually comfortable with this dataset.</p><p>to check whether the result was specific to Vaani, i repeated the same experiment on LAHAJA using one recording from each of its 132 speakers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TYidW17iWUsgVCNZGPb_wg.png" /></figure><p>LAHAJA made the tradeoff easier to see. Adalat was slightly better on the original recordings, but became worse after telephone degradation. its channel penalty was 2.92 points larger than ARTPARK’s.</p><p>so the same pattern appeared on two different Hindi datasets. Adalat Whisper-small was faster, taking around 53% of ARTPARK’s inference time, but ARTPARK Whisper-medium was consistently less affected by the telephone channel.</p><p>these are the exact channel penalties across the two datasets:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*H3TjhV3t8S2YwcIN" /><figcaption>the smaller Adalat model suffered a much larger pooled channel penalty on both external datasets.</figcaption></figure><p>the smaller Adalat model suffered a much larger pooled channel penalty on both external datasets.</p><h3>can we train the smaller model to handle this better?</h3><p>Adalat was the obvious model to work on. it was almost twice as fast, and on the original LAHAJA recordings it was even slightly more accurate than ARTPARK. its weakness only became clear after the telephone transformations.</p><p>so the next question was: can we keep the speed and reduce the channel penalty?</p><p>for this, i used LoRA. instead of updating every weight in Whisper-small, LoRA freezes the original model and trains a much smaller set of additional parameters. this makes the experiment possible on a Colab T4 without training the whole model from scratch.</p><p>the adapter was trained on 18,000 GramVaani recordings. every selected source clip kept its released telephone version, while one-third received an extra 8 kHz, G.711 or GSM version. the final mix was roughly 75% released GramVaani audio and 25% added channel stress, giving about 65 hours of training views over 3,000 steps.</p><p>Vaani and LAHAJA were kept out of training. even the internal GramVaani split was separated by recording group, so the same recording could not appear on both sides.</p><p>and initially, it worked:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*encTEl0CZ5egWrpeZafX3Q.png" /></figure><p>that is a drop of more than ten WER points on both the released audio and the telephone conditions. on the internal test, the adapter looked clearly better.</p><p>but both the training data and this test still came from GramVaani. the model had learned something useful there. we still did not know whether it had learned general telephone robustness or simply become better at GramVaani.</p><h3>did the improvement survive outside GramVaani?</h3><p>short answer: no. the adapter had overfit to GramVaani.</p><ul><li>on <strong>Vaani</strong>, pooled telephone WER became worse: <strong>20.22% → 22.62%</strong>.</li><li>on <strong>LAHAJA</strong>, it barely changed: <strong>21.53% → 21.89%</strong>. so there was no improvement there either.</li><li>original-audio WER also became worse on both datasets.</li></ul><p>the adapter had learned something specific to GramVaani, such as its speaking style, vocabulary, recordings, or transcription patterns.</p><h3>why did the adapter fail?</h3><p>the adapter had seen 18,000 GramVaani recordings, but they still came from one dataset. the extra G.711 and GSM versions made the audio rougher. they did not add new accents, topics, microphones or transcription styles.</p><p>even the internal test came from GramVaani. separating recording groups prevented the same recording from appearing in both training and evaluation, but both sides still shared the same source and transcript conventions.</p><p>the problem was what the model was being rewarded for.</p><p>its job was to reduce transcription error on the GramVaani training mix. nothing explicitly forced it to produce the same transcript for an original recording and its degraded copy. it could lower the loss by becoming better at GramVaani without learning general telephone robustness.</p><p>that is the most likely explanation for the final result: a ten-point improvement inside GramVaani, worse performance on Vaani, and no improvement on LAHAJA.</p><p>a second attempt would need more variety. i would use Hindi and Hinglish speech from several datasets, mix clean and real telephone recordings, and train on matched original/degraded pairs. model selection would also need to use more than one domain.</p><p>Vaani and LAHAJA cannot be the final test again. we have already seen their results, so tuning against them would turn them into validation sets. a new attempt needs a new untouched benchmark.</p><h3>what this project shows</h3><p>once i tested the adapter on Vaani and LAHAJA, i could no longer call it an improvement.</p><p>i am publishing the training run as a failed adaptation case, along with its setup and evaluation results. the benchmark caught a problem that the internal GramVaani score hid.</p><p>the paired benchmark produced the result i trust most from this project. Adalat’s channel penalty was 2.32 WER points larger on Vaani and 2.92 points larger on LAHAJA. it also took around 53% of ARTPARK’s inference time.</p><p>Adalat is faster, but it lost more accuracy when the same speech was passed through the same telephone transformations. that pattern survived a second dataset.</p><h3>where this result stops</h3><p>the 8 kHz, G.711 and GSM conditions are controlled simulations. they isolate specific kinds of channel damage. real calls can also have packet loss, clipping, network jitter and device noise, none of which were covered here.</p><p>the absolute WER values across GramVaani, Vaani and LAHAJA should not be compared directly either. Vaani uses multiple human references, while GramVaani and LAHAJA use one. the useful comparisons happen inside each dataset.</p><p>ARTPARK had also seen Vaani during training. that could help its Vaani score, which is why repeating the result on LAHAJA mattered.</p><p>and this is still a comparison between two specific checkpoints. it does not mean every Whisper-small model will handle telephone audio worse than every Whisper-medium model.</p><p>the answer to the question in the title (atleast rn): these two Hindi Whisper models did not react to telephone degradation in the same way. the smaller model was faster, but more sensitive to the channel.</p><p>training reduced its error inside GramVaani, then failed to carry that improvement anywhere else.</p><p>I’ve published these experiments here:</p><p><a href="https://github.com/anshulLuhsna/CallWhisper-8k">https://github.com/anshulLuhsna/CallWhisper-8k</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25ceff3e9d4b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Last Argument Always Wins]]></title>
            <link>https://medium.com/@anshulkalbande/the-last-argument-always-wins-d4f43e0e23e1?source=rss-3164f83e8b6a------2</link>
            <guid isPermaLink="false">https://medium.com/p/d4f43e0e23e1</guid>
            <category><![CDATA[llm-council]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[ai-sycophancy]]></category>
            <category><![CDATA[protocol]]></category>
            <dc:creator><![CDATA[Anshul Kalbande]]></dc:creator>
            <pubDate>Sun, 10 May 2026 18:10:31 GMT</pubDate>
            <atom:updated>2026-05-10T18:10:31.135Z</atom:updated>
            <content:encoded><![CDATA[<p>So I built a <a href="https://github.com/anshulLuhsna/council.md">council.md</a>. A file-first LLM council to make models disagree before they persuade me.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zOt22UAbdsHjT9JZZPAplA.png" /></figure><p>I’ve been thinking about this Karpathy tweet for a while and it makes me think about something I’ve learned from <a href="https://www.youtube.com/@ChrisWillx">Chris Williamson.</a></p><p>Thanks to evolution, our brain has a <strong>stronger horsepower engine </strong>to see the glass as half <em>empty</em>, Charlie Munger found a way to harness this with his famous quote:</p><blockquote>invert, always invert.</blockquote><p>LLMs are dangerous because they are good at making whichever side you <em>asked for</em> feel <strong>reasonable.</strong></p><p>I noticed something annoying about myself. When a model argued well, I could feel my opinion moving. Not because the model was right. Because the argument was <em>clean</em>.</p><p>They can <em>invert</em> almost anything.</p><h3>The last answer has too much power</h3><p>That makes the <strong>user</strong> part of the system more important than we like to admit. If I ask a lazy question, I get a persuasive lazy answer.</p><p>If I ask for confidence, I often get something that sounds <em>like</em> confidence.</p><p>And if I ask the opposite, I may suddenly believe that too.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dxGwhq5LYLyOUJB0XoaWnQ.png" /></figure><h3>Most AI councils agree too beautifully</h3><p>The obvious answer is to use <strong>multiple models.</strong></p><p><strong>Get a strategist. A critic. A user advocate. A risk analyst. Let them argue. Then synthesize.</strong></p><p>This sounds rigorous. Sometimes it is.</p><p>But a lot of AI councils have a quiet failure mode: <strong>they agree too early.</strong></p><p>One agent frames the problem. The others react to that frame. The discussion starts leaning. <strong>Then the synthesizer arrives and turns that lean into a neat conclusion.</strong></p><p>Now the user is not looking at one chatbot answer. They are looking at <strong><em>“the council.”</em></strong></p><p>That sounds <em>stronger.</em></p><p>It may not be.</p><p>A bad council does not fail by arguing. It fails by agreeing too <em>beautifully.</em></p><h3>The real problem is who saw what</h3><p>This is the part I kept coming back to.</p><p>I believe we can reach useful disagreement with a few basic questions like:</p><ul><li><strong>Who saw the original context?</strong></li><li><strong>Who saw another agent’s answer?</strong></li><li><strong>Did the critic write independently, or did they react to the builder’s framing?</strong></li><li><strong>Did the synthesizer preserve the minority view?</strong></li><li><strong>Did the human decide, or did the summary gently decide for them?</strong></li></ul><p>That is why I built <a href="https://github.com/anshulLuhsna/council.md"><em>council.md</em></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_2TsE6ojHsqlMbOqTbJMQA.png" /></figure><p>It is a protocol for running AI councils using plain session files. The basic flow is simple:</p><ol><li>A coordinator helps define the question.</li><li>Agents write independent first drafts, ideally blind.</li><li>Their contributions are merged into a shared discussion.</li><li>A synthesizer maps agreement, disagreement, open questions, and candidate paths.</li><li>The human makes the decision.</li></ol><p>The important part is that the <strong>information flow is visible.</strong></p><p>For example, if the <strong>Builder</strong> says</p><blockquote>“this is mostly a UX problem”</blockquote><p>before the Critic writes, the Critic may spend its whole turn reacting to UX. But if the Critic writes blind, it may decide the real issue is distribution, pricing, or trust. That difference matters.</p><h3>I’m not against runtimes. I’m against hidden reasoning.</h3><p>The first version of this idea was easy to describe as <strong>“an LLM council without a runtime.”</strong></p><p>I still like that phrase. It has a nice <em>bluntness</em> to it.</p><p>But it is not quite the mature position.</p><p>The better position is:</p><blockquote><strong>file-first, invariant-first, runtime-optional.</strong></blockquote><p>A runtime is fine if it preserves the protocol. If it exports the session files, keeps blind rounds isolated, logs who saw what, and leaves the human in control of phase transitions, great.</p><p>What I do not want is <strong>hidden orchestration.</strong></p><p>I do not want a system where five agents <em>supposedly</em> deliberated, but I cannot reconstruct the prompts, the order, the memory, the handoffs, or the moment synthesis began.</p><p>I’m not religious about files.</p><p><strong>I’m religious about being able to reconstruct the argument.</strong></p><h3>Blind first, argue later</h3><p><strong>The blind first round is probably the most important design choice.</strong></p><p>Each agent gets the same context and its own role. It writes its first position before reading the other agents.</p><p><strong>It means the risk analyst is not anchored by the strategist</strong>. The user advocate is not politely reacting to the builder. The challenger has to actually challenge from its own lane, not just decorate someone else’s framing.</p><p>After that, you can run a second round. Let them respond. Let them clash.</p><p>But the first thoughts are preserved.</p><p>That matters because once a strong framing enters the room, everything after it starts bending around that framing.</p><h3>Files are boring in exactly the right way</h3><p><em>council.md</em> is file-first.</p><p>A session is just a folder:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*Uj15JJeNzSyLPdskhQcJaw.png" /></figure><p>This is not because markdown is magical.</p><p>It is because files are <strong>inspectable.</strong> They make the process harder to hide.</p><p>You can open the folder and see the actual record:</p><ul><li>this was the question</li><li>these were the roles</li><li>this is what each agent saw</li><li>this is what each agent said</li><li>this is where synthesis happened</li><li>this is where the human decision was recorded</li></ul><p>The files are not the interface.</p><p>The files are the audit trail.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bkfba-ncalcMDqOMkdvuoA.png" /><figcaption>The optional briefing is generated from the synthesis. It is not the decision.</figcaption></figure><h3>The synthesizer is not a judge</h3><p>The synthesizer has one job: <strong>map the territory.</strong></p><p>It should not turn disagreement into a soft consensus because that <em>reads better.</em></p><p>A good synthesis should say:</p><ul><li><strong>here is where agents independently converged</strong></li><li><strong>here is where they disagree</strong></li><li><strong>here is what is at stake in that disagreement</strong></li><li><strong>here is what evidence would resolve it</strong></li><li><strong>here are the candidate paths</strong></li><li><strong>here is what remains unknown</strong></li></ul><p>The synthesizer is not there to make me feel done.</p><p>It is there to make me <strong>harder to fool.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_9teRIbXFYFrU5_8w6u4DQ.png" /><figcaption>The useful part is often the conflict that remains unresolved.</figcaption></figure><h3>The UI is a briefing, not the source of truth</h3><p>I added an optional UI because reading raw markdown is not always pleasant.</p><p>The UI turns the synthesis into a staged briefing: overview, agents, agreements, conflicts, risks, candidate paths, open questions, and a final “before you decide” moment.</p><p>But the UI is deliberately <strong>non-authoritative.</strong></p><p>It is generated from JSON inside synthesizer.md. The model fills the JSON. The CLI renders the HTML. The HTML does not become the source of truth.</p><p>If the UI ever disagrees with the markdown, <strong>the markdown wins.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tbNEp1uu-e5gXDCF2o1wjA.png" /><figcaption>The final step is still human judgment.</figcaption></figure><h3>Subscription-native is not a compromise</h3><p>One thing I care about more than I expected: this should work with the AI access people <em>already have.</em></p><p><strong>Most people do not have a clean API setup across every model.</strong> They have subscriptions. Browser tabs. Claude. ChatGPT. Gemini. Perplexity. Grok. Maybe a local model. Maybe Cursor or Claude Code.</p><p><strong>So council.md treats copy-paste as a first-class workflow.</strong></p><p>That is slower than a runtime. It is more manual. It can be <em>annoying.</em></p><p>But it also means the protocol works without API keys, billing setup, provider lock-in, or a custom orchestration service.</p><p>For occasional hard decisions, that tradeoff feels right.</p><p>The point is not to automate everything.</p><p><strong>The point is to make the thinking process visible enough that I can trust the record.</strong></p><h3>The council now reviews itself</h3><p>There is a funny consequence of building a protocol like this.</p><p>At some point, the repo itself has to live by the rules.</p><p>So council.md now has a <strong>self-improvement profile.</strong> Meaningful changes to the project are supposed to go through a council before becoming a PR.</p><p>In fact the first version of this idea, the <strong>“an LLM council without a runtime.” </strong>did not survive the council!</p><p>So I scrapped it.</p><p>That sounds a little ridiculous.</p><p>I kind of like that.</p><p>Not because I think the project is now some self-improving AI <em>organism</em>. It is not. There is still a human deciding. There is still a maintainer judging the change.</p><p>But if the whole thesis is that meaningful changes should survive structured disagreement, then the <strong>protocol should be able to survive its own process.</strong></p><p>Especially when the change is about the protocol <em>itself.</em></p><h3>Where this might be wrong</h3><p>This is <strong>slower</strong> than asking one strong model.</p><p>Some people will hate the manual handoffs. Some decisions do not need this much structure. A bad prompt can still produce bad deliberation. A human can still ignore the uncomfortable part of the synthesis.</p><p>Files can become ceremony.</p><p>A checklist can become theater.</p><p>A council can become a more elaborate way to hear what you already wanted to hear.</p><p>I do not think council.md magically solves that.</p><p><strong>But I do think it makes the failure easier to see.</strong></p><p>And for me, that is the <strong><em>point.</em></strong></p><p>check out council.md at <a href="https://github.com/anshulLuhsna/council.md"><strong>https://github.com/anshulLuhsna/council.md</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d4f43e0e23e1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Chronology of Learning: Leveraging Spectral Bias for Better DNNs]]></title>
            <link>https://medium.com/@anshulkalbande/the-chronology-of-learning-leveraging-spectral-bias-for-better-dnns-8569c6c77c0c?source=rss-3164f83e8b6a------2</link>
            <guid isPermaLink="false">https://medium.com/p/8569c6c77c0c</guid>
            <category><![CDATA[training-dynamic]]></category>
            <category><![CDATA[generalization]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[neural-networks]]></category>
            <dc:creator><![CDATA[Anshul Kalbande]]></dc:creator>
            <pubDate>Sun, 23 Nov 2025 14:34:43 GMT</pubDate>
            <atom:updated>2025-11-23T14:41:32.948Z</atom:updated>
            <content:encoded><![CDATA[<h4>Turning the memorization effect from a bug into a feature in modern deep learning pipelines.</h4><p>Bad data<em> kills</em> performance, atleast that was the gospel every ML engineer lived by. If noisy labels slipped into training, accuracy <em>would</em> falter. That was until the models grew so large that the old rules simply stopped applying.</p><h4>The Generalization Paradox</h4><p>The 2017 paper by Zhang et al., titled “Understanding Deep Learning Requires Rethinking Generalization,” demonstrates that large deep neural networks have enough capacity to perfectly memorize training data, even when the labels are<strong> randomized.</strong></p><p>In other words, a DNN will do whatever it takes to drive training error to zero, even if it means behaving like a giant <em>hash map</em> instead of learning meaningful structure. It can brute-force its way to perfect accuracy with the same mindset as me solving every LeetCode problem using a hash map instead of actually learning the intended algorithm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xy09uySgEFrbwfUr.jpeg" /><figcaption>iconic</figcaption></figure><p>And here’s where the paradox hits:<br>If the model turns into a bloated look-up table during training… why doesn’t it collapse at test time? Isn’t this classic overfitting?<br>How does a network that memorizes garbage still manage to generalize cleanly on new, unseen data?</p><p>To unpack this paradox properly, we have to go back to what Zhang’s experiments actually revealed.</p><h3>Chronology of Learning — Patterns First, Noise Later</h3><p>Zhang et al. found that modern nets can memorize anything, even <em>random labels.</em><br>But that wasn’t the whole story. In the same year, <strong>Arpit et al.</strong> showed in the paper “<em>A Closer Look at Memorization in Deep Networks” </em>that <strong>learning ≠ memorization, </strong>they unfold on different timelines.</p><p>In simple terms: networks learn the easy, <strong>shared patterns first</strong>, and only later start absorbing the outliers and noisy labels. It’s the same as a student learning the core concepts early, and cramming the weird exceptions and random facts at the last minute.</p><p>And we can actually use this behavior to our advantage.<br>Chronology becomes a spotlight on <strong>data quality</strong>: clean patterns appear early, while noisy samples get pushed to the end of training.</p><p>If you train a network on <em>CIFAR-10</em> with partial label corruption, the loss curve shows this exact behavior.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/989/1*T-BQhqToXKDah9JOYWWhvA.png" /><figcaption>20% noise VS 0% noise at 40 epochs</figcaption></figure><p>This plot shows how training dynamics separate real structure from noise. With clean labels, the network <strong>quickly</strong> learns the shared low-frequency patterns and the loss plateaus early. But with 20% label noise, the curve develops a <strong>long, shallow tail</strong> — the model keeps optimizing NOT because it is discovering new structure, but because it is slowly memorizing <em>contradictions.</em></p><h4>Inject Partial Label Noise</h4><pre>def corrupt_labels(y, fraction, seed=0):<br>    rng = np.random.RandomState(seed)<br>    y_new = y.copy()<br>    n = len(y)<br>    k = int(fraction * n)<br><br>    idx = rng.choice(n, size=k, replace=False)<br>    random_labels = rng.randint(0, 10, size=k)<br><br>    # ensure corrupted labels differ from original<br>    same = random_labels == y_new[idx]<br>    while np.any(same):<br>        random_labels[same] = rng.randint(0, 10, size=np.sum(same))<br>        same = random_labels == y_new[idx]<br><br>    y_new[idx] = random_labels<br>    return y_new</pre><p>This tiny function turns <em>CIFAR-10</em> into a partially contradictory dataset, letting you <em>see</em> memorization unfold in the loss curve.</p><h4>Simple NumPy MLP Forward Pass</h4><pre>class MLP:<br>    def __init__(self, input_dim=3072, hidden=256, classes=10):<br>        rng = np.random.RandomState(0)<br>        self.W1 = 0.01 * rng.randn(input_dim, hidden).astype(np.float32)<br>        self.b1 = np.zeros(hidden)<br>        self.W2 = 0.01 * rng.randn(hidden, classes).astype(np.float32)<br>        self.b2 = np.zeros(classes)<br><br>    def forward(self, X):<br>        z1 = X @ self.W1 + self.b1<br>        h1 = np.maximum(0, z1)<br>        logits = h1 @ self.W2 + self.b2<br>        return logits, (X, z1, h1)</pre><p>The model is a simple two-layer MLP:</p><ul><li><strong>Input layer:</strong> 3072 features (32×32×3 flattened CIFAR image)</li><li><strong>Hidden layer:</strong> 256 ReLU units</li><li><strong>Output layer:</strong> 10 logits (one per class)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*R_mltx0AeSBPTnItTOXJ-w.png" /><figcaption>40% noise with 60 epochs VS 0% noise with 40 epochs</figcaption></figure><p>It’s apparent that these nets learn simple, smooth patterns first, and only later fit sharp, noisy details.<br>This behavior is called spectral bias, or the frequency principle.</p><p>A helpful way to think about it is through <strong>music</strong>: low-frequency signals are like the bassline — broad, repetitive, and shared across the entire track. High-frequency signals are like the static and crackle layered on top. The bassline comes through immediately; the static takes effort to notice.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UfQDGLTFl4gSGPE4CZaM3g.png" /></figure><p>Gradient descent behaves the same way. Smooth, low-frequency features have stronger, more coherent gradients across the dataset, so the network locks onto them early. Sharp, noisy patterns require many small, inconsistent adjustments, so they appear late in training. If you peek a little into the math, this maps cleanly to the fact that low-frequency functions have larger effective <em>eigenvalues</em> during optimization.</p><p>You can see this directly in our curves:<br>The <strong>fast drop</strong> in the 0%-noise run is the network capturing <em>low-frequency structure, </em>and the <strong>long, shallow tail</strong> in the 20%-noise run is the network slowly fitting <em>high-frequency</em> noise.</p><p>This is exactly what spectral bias predicts — and it’s why training dynamics reveal the difference between real structure and mislabeled data.</p><h4><strong>Forgetting Events — Using Training Dynamics as a Data Debugger</strong></h4><p>Let’s now get into the practical side and see how we can use training dynamics to our advantage.<br>Up to this point, we’ve seen that networks learn simple patterns first, fit noise later, and that this sequence naturally separates signal from garbage. But researchers found an even clearer signature — a pattern that shows you exactly which examples the model considers stable, and which ones it keeps fighting with.<br>Toneva et al. (2019) called this a <strong>forgetting event</strong>.</p><p>A forgetting event happens when the model gets a training example right at one epoch and wrong at the next.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YkybltLhG_vw-24da9K1bg.png" /><figcaption>The most-forgotten samples are almost always mislabeled.</figcaption></figure><p>This is surprisingly common early in training and almost nonexistent for clean samples later on. Clean examples produce gradients that all point in the same direction; once the model aligns with those signals, it rarely flips again. Noisy or mislabeled examples behave differently. Their gradients conflict with the dominant pattern in the dataset, so the model might memorize them for a moment, only to “drop” them as soon as cleaner structure pulls back.</p><p>This tug-of-war lines up perfectly with spectral bias:<br>low-frequency structure stabilizes early, while high-frequency, noisy points sit near the decision boundary and get knocked around by every update. Forgetting is simply the network rejecting patterns that contradict the underlying signal.</p><p>The nice part is how actionable this becomes.<br>If you count forgetting events per sample across training, the dataset almost annotates itself.</p><pre># Track correctness across epochs<br>correct_prev = np.zeros(len(y_train), dtype=bool)<br>forgetting_events = np.zeros(len(y_train), dtype=np.int32)<br><br>for epoch in range(epochs):<br>    ...<br>    y_pred = model.predict(X_train)<br>    correct_curr = (y_pred == y_train)<br><br>    # correct → incorrect = forgetting<br>    forgot = correct_prev &amp; (~correct_curr)<br>    forgetting_events[forgot] += 1<br><br>    correct_prev = correct_curr</pre><p>Unforgettable examples correspond to stable, meaningful structure. Highly forgotten examples are almost always mislabeled, ambiguous, or outliers. You don’t need heuristics, the dynamics themselves reveal what the model trusts and what it doesn’t.</p><p>Check out the entire notebook <a href="https://github.com/anshulLuhsna/articles/blob/main/1_spectral_bias.ipynb">here.</a></p><p>The big lesson across all these results is simple:<strong> the value isn’t just in the model you end up with, but in the timeline it took to get there</strong>. Zhang et al. showed that networks can memorize anything. Arpit et al. showed that learning and memorization follow different timelines. Spectral bias explained why simple structure appears early. Forgetting events revealed exactly which examples the model keeps resisting.</p><blockquote>The dynamics aren’t an afterthought — they’re a diagnostic instrument.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8569c6c77c0c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building HNSW from Scratch]]></title>
            <link>https://medium.com/@anshulkalbande/building-hnsw-from-scratch-03f1db8435fc?source=rss-3164f83e8b6a------2</link>
            <guid isPermaLink="false">https://medium.com/p/03f1db8435fc</guid>
            <category><![CDATA[hnsw]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[vector-database]]></category>
            <category><![CDATA[similarity-search]]></category>
            <dc:creator><![CDATA[Anshul Kalbande]]></dc:creator>
            <pubDate>Sat, 13 Sep 2025 06:54:01 GMT</pubDate>
            <atom:updated>2025-09-13T06:54:01.603Z</atom:updated>
            <content:encoded><![CDATA[<h4>How Qdrant and Pinecone Search Millions of Vectors in Milliseconds</h4><p>It’s so crazy to me how normalized millisecond responses from vector databases have become recently, when in truth we’re asking them to do the impossible — <em>pluck a needle out of a haystack</em>, again and again, without ever missing.</p><p>This article assumes some familiarity with concepts like vector embeddings, vector spaces, and RAG systems; if you’re new to RAG, I recommend starting with<em> </em><a href="https://medium.com/worqhat/retrieval-augmented-generation-rag-worqhat-aicon-langchain-46059c529f2d"><em>this article</em></a><em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EguPsbA5IV46mJS7_mIjig.png" /><figcaption>Query latency comparison. Sources: <a href="http://redis.io/blog/benchmarking-results-for-vector-databases">1</a> • <a href="http://research.aimultiple.com/vector-database-for-rag">2</a> • <a href="http://qdrant.tech/benchmarks">3</a></figcaption></figure><p>All of these databases —<strong> Redis, Milvus, Weaviate, Pinecone, and Qdrant</strong> — shine under different conditions: Redis for ultra-low latency, Milvus for massive scale, Weaviate for hybrid semantic search, Pinecone for managed reliability, and Qdrant for balanced open-source performance.</p><p>Yet despite their differences, they share a common foundation in graph-based ANN techniques like <strong><em>HNSW.</em></strong></p><h3>Hierarchical navigable small world (HNSW)</h3><p>That’s a mouthful I know, let’s break that down…</p><p><strong>Navigable small world (NSW)</strong> graphs are a type of graph structure designed for efficient search in high-dimensional spaces.</p><p>The <strong>“small world”</strong> property means that even in a very large graph, the average path length between any two nodes is short because the graph contains both:</p><ul><li><strong>Local connections</strong> (edges to nearby neighbors), and</li><li><strong>Long-range shortcuts</strong> (edges to more distant nodes).</li></ul><p>This balance makes it possible to navigate quickly across the graph: you can start anywhere and, by greedily moving to nodes that are closer to your target, reach your destination in only a handful of hops.</p><h4>The Highway Analogy</h4><p>Imagine a <strong>city map</strong>:</p><ul><li>At the street level, every house connects to nearby houses — you’ll reach your destination eventually, but it’s slow.</li><li>Add a few highways, and suddenly you can cross town in just a couple of jumps, then finish on local roads.</li></ul><p>That’s what a <strong>Navigable Small World (NSW) graph</strong> does: <strong>local edges</strong> are streets, <strong>long-range edges</strong> are highways, and greedy search gets you close in only a few hops.</p><p><strong><em>HNSW</em></strong> extends this idea by stacking <strong>multiple layers of highways.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UYR1QUM_Zkjsfgu2.png" /><figcaption>Hierarchical layers of an HNSW graph</figcaption></figure><h3>Basic intuition behind HNSW</h3><p>If speed is non-negotiable, and we have millions of possibilities, I think you’ll agree we shouldn’t wade through everything but leap over most of it first.</p><p>HNSW applies this exact same principle to vector search. Instead of comparing your query against every single vector (which would be like checking every address in the city), it creates multiple “zoom levels” of the data:</p><p><strong>Layer 2 (Highway)</strong>: A few well-connected vectors that can make big jumps across the vector space</p><p><strong>Layer 1 (Main roads)</strong>: More vectors with medium-range connections to get you closer</p><p><strong>Layer 0 (Local streets)</strong>: All vectors with precise, local connections for the final approach.</p><h4>Do vectors live on just one level?</h4><p>No — <strong>each vector exists at every level up to its maximum assigned level<em>.</em> </strong>And so the bottommost layer contains <em>ALL</em> the vectors. So if we were to perform similarity search, we should obviously start from the top layer.</p><h4>How does a vector get assigned a maximum level?</h4><p>You might think we need some complex algorithm to determine “importance,” but HNSW uses something much simpler: coin flips.</p><p>When you add a new vector:</p><ol><li>It always goes in <strong>Layer 0</strong> (<em>everyone goes here</em>)</li><li>Flip a coin — if <strong>heads</strong>, it also goes in <strong>Layer 1</strong></li><li>If it made Layer 1, flip again — if heads, it goes in<strong> Layer 2</strong></li><li>Continue until you get tails</li></ol><p>That’s it! No complex decisions. Less is more sometimes haha.</p><p><strong><em>Why this works:</em></strong> Over time, about 50% of vectors reach Layer 1, 25% reach Layer 2, 12.5% reach Layer 3, and so on. You naturally get a pyramid structure where higher layers have fewer vectors.</p><h4>How does insertion work?</h4><p>When a new vector needs to be inserted, HNSW uses its own search algorithm to find the perfect <em>“landing zone”</em> for it. The search starts from the top layer and navigates downward through existing connections, getting closer and closer to where the new vector belongs based on similarity. Read <em>Step 5</em> for more details.</p><h3>Building Our Vector Database</h3><h4>Step 1 — Basic Structure</h4><ol><li><strong>Vector embeddings</strong>: The actual numbers representing each document</li><li><strong>Documents</strong>: The original text we want to return to users</li><li><strong>Connections</strong>: Which vectors are connected to which other vectors in each layer</li></ol><pre>import random<br>import numpy as np<br><br>class HNSW:<br> def __init__(self, max_connections=16):<br>   self.max_connections = max_connections<br>    # Three core dictionaries<br>   self.vec2neighbors = {} # Which vectors connect to which<br>   self.vec2embeds = {} # The actual vector embeddings<br>   self.vec2docs = {} # The original documents<br>    # Bookkeeping<br>   self.highest_layer = 0 # Track the tallest vector<br>   self.currentID = 0 # Give each vector a unique ID</pre><p>The <em>vec2neighbors</em> structure is the most important. For vector ID 5 that exists in layers 0, 1, and 2, it might look like:</p><pre>vec2neighbors[5] = {<br>    0: [10, 15, 23, 8],     # connected to these vectors in layer 0<br>    1: [15, 23, 7],         # connected to these vectors in layer 1<br>    2: [23, 7]              # connected to these vectors in layer 2<br>}</pre><h4>Step 2 — Implementing the Coin Flip Layer Assignment</h4><p>Now let’s implement the probabilistic layer assignment we discussed:</p><pre>def _assign_layer(self):<br>    &quot;&quot;&quot;Determine which layers a new vector should exist in&quot;&quot;&quot;<br>    layer = 0<br>    while random.random() &gt; 0.5:  # 50% chance to continue<br>        layer += 1<br>    return layer</pre><h4>Step 3 — Inserting Vectors (The Simple Version)</h4><p>Let’s start with a basic insertion that stores vectors but doesn’t connect them yet:</p><pre>def insert(self, embedding, document):<br>    # Step 1: Decide which layers this vector goes in<br>    max_layer = self._assign_layer()<br>    self.highest_layer = max(self.highest_layer, max_layer)<br><br>    # Step 2: Store the vector data<br>    vector_id = self.currentID<br>    self.vec2embeds[vector_id] = embedding<br>    self.vec2docs[vector_id] = document<br><br>    # Step 3: Initialize empty neighbor lists for each layer<br>    self.vec2neighbors[vector_id] = {}<br>    for layer in range(max_layer + 1):  # 0, 1, 2, ..., max_layer<br>        self.vec2neighbors[vector_id][layer] = []<br><br>    # Step 4: Increment ID for next vector<br>    self.currentID += 1<br>    return vector_id</pre><p>Let’s test this basic version:</p><pre># Create our vector database<br>hnsw = HNSW(max_connections=16)<br><br># Insert two test vectors<br>embedding1 = np.array([1, 0, 0, 0])<br>doc1 = &quot;Hello, world!&quot;<br>hnsw.insert(embedding1, doc1)<br><br>embedding2 = np.array([0, 1, 0, 0])<br>doc2 = &quot;Goodbye, world!&quot;<br>hnsw.insert(embedding2, doc2)<br><br># See what happened<br>print(&quot;Vector 0 layers:&quot;, list(hnsw.vec2neighbors[0].keys()))<br>print(&quot;Vector 1 layers:&quot;, list(hnsw.vec2neighbors[1].keys()))<br>print(&quot;Highest layer:&quot;, hnsw.highest_layer)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/415/1*cVPz5Twgmbi8wPcG6qQQ1A.png" /><figcaption>A possible output</figcaption></figure><p>Vector 0 got lucky and made it to layer 3, while vector 1 only exists in layer 0 and 1. But notice — neither vector has any neighbors yet. They’re stored but not connected.</p><h4>Step 4 — Similarity Calculation</h4><p>Before we can connect vectors, we need a way to measure how similar they are. For vector embeddings, cosine similarity is the most common choice:</p><pre>def cosine_similarity(self, vec1, vec2):<br>    &quot;&quot;&quot;Calculate how similar two vectors are (0 = opposite, 1 = identical)&quot;&quot;&quot;<br>    dot_product = np.dot(vec1, vec2)<br>    magnitude1 = np.linalg.norm(vec1)<br>    magnitude2 = np.linalg.norm(vec2)<br>    return dot_product / (magnitude1 * magnitude2)</pre><p>What this does: Cosine similarity measures the angle between two vectors. If they point in the same direction (similar meaning), you get a high score. If they point in opposite directions (different meaning), you get a low score.</p><h4>Step 5 — The search strategy (finding good neighbors)</h4><p>As mentioned above, when we want to insert a new vector, we need to find which existing vectors should be its neighbors. We can’t just compare it to every vector (that would be slow), so we use the layer structure for efficient search.</p><p><strong>The strategy</strong>:</p><ol><li>Start at the highest layer with very few vectors</li><li>Find the best vector we can reach in that layer</li><li>Drop down to the next layer and continue from that vector</li><li>Repeat until we reach the bottom layer</li><li>Return the best candidates we found</li></ol><p>But there’s a problem with simple “greedy” search — what if we get stuck? What if the path leads us to a local optimum but misses better candidates nearby?</p><p>So maybe instead of following just one path, we should use “beam search” — we keep track of multiple promising candidates and explore from all of them.</p><pre>def search(self, query_embedding, num_candidates=50):<br>    &quot;&quot;&quot;Find the most similar vectors by searching through layers&quot;&quot;&quot;<br>    if len(self.vec2neighbors) == 0:<br>        return {}  # Empty database<br><br>    # Step 1: Find starting points in the top layer<br>    current_candidates = []<br>    for vector_id in self.vec2neighbors:<br>        if self.highest_layer in self.vec2neighbors[vector_id]:<br>            current_candidates.append(vector_id)<br><br>    layer_candidates = {}<br><br>    # Step 2: Search down through each layer<br>    for layer in range(self.highest_layer, -1, -1):  # 3, 2, 1, 0<br>        # Step 2a: Explore neighbors of current candidates<br>        all_neighbors = []<br>        for candidate in current_candidates:<br>            if layer in self.vec2neighbors[candidate]:<br>                neighbors = self.vec2neighbors[candidate][layer]<br>                all_neighbors.extend(neighbors)<br><br>        # Step 2b: Combine candidates + their neighbors<br>        all_candidates = current_candidates + all_neighbors<br>        unique_candidates = list(set(all_candidates))  # Remove duplicates<br><br>        if not unique_candidates:<br>            layer_candidates[layer] = []<br>            current_candidates = []<br>            continue<br><br>        # Step 2c: Score all candidates by similarity to our query<br>        scored_candidates = []<br>        for candidate in unique_candidates:<br>            similarity = self.cosine_similarity(query_embedding, self.vec2embeds[candidate])<br>            scored_candidates.append((similarity, candidate))<br><br>        # Step 2d: Keep the best candidates<br>        scored_candidates.sort(reverse=True)  # Highest similarity first<br>        top_candidates = scored_candidates[:num_candidates]<br><br>        # Step 2e: Store results and prepare for next layer<br>        layer_candidates[layer] = [vector_id for _, vector_id in top_candidates]<br><br>        # Pass fewer candidates down to next layer for efficiency<br>        next_layer_size = min(num_candidates // 2, len(top_candidates))<br>        current_candidates = [vector_id for _, vector_id in top_candidates[:next_layer_size]]<br><br>    return layer_candidates</pre><h3>Step 6 — Making Connections</h3><p>Now comes the <strong>most important part</strong>: actually connecting vectors to each other. This is what transforms our isolated vectors into a navigable graph.</p><p><strong>The challenge</strong>: Each vector can only have a limited number of connections (we set max_connections=16). So when we want to connect a new vector to an existing one, we might need to &quot;evict&quot; the existing vector&#39;s worst neighbor to make room.</p><p><strong>An interesting edge case</strong>: If we want to connect a new vector to an existing vector, but we find that the existing vector has already reached max_connections AND the new connection itself is worse than all the existing connections, the connection is <strong><em>rejected.</em></strong></p><blockquote>Yes even vectors get rejected :(</blockquote><p>Here’s the connection logic:</p><pre>def _make_connections(self, new_vector_id, candidates_by_layer, new_vector_layers):<br>    &quot;&quot;&quot;Create bidirectional connections between new vector and candidates&quot;&quot;&quot;<br><br>    for layer in new_vector_layers:<br>        if layer not in candidates_by_layer:<br>            continue  # No candidates in this layer<br><br>        candidates = candidates_by_layer[layer]<br><br>        # Connect to the best candidates (up to our limit)<br>        connections_to_make = min(len(candidates), self.max_connections)<br>        best_candidates = candidates[:connections_to_make]<br><br>        for candidate_id in best_candidates:<br>            # Step 1: Add candidate to new vector&#39;s neighbor list<br>            self.vec2neighbors[new_vector_id][layer].append(candidate_id)<br><br>            # Step 2: Add new vector to candidate&#39;s neighbor list (if there&#39;s room)<br>            if candidate_id in self.vec2neighbors and layer in self.vec2neighbors[candidate_id]:<br>                candidate_neighbors = self.vec2neighbors[candidate_id][layer]<br><br>                if len(candidate_neighbors) &lt; self.max_connections:<br>                    # There&#39;s room - just add the connection<br>                    candidate_neighbors.append(new_vector_id)<br>                else:<br>                    # No room - need to decide if new connection is better than worst existing<br>                    candidate_embedding = self.vec2embeds[candidate_id]<br>                    new_embedding = self.vec2embeds[new_vector_id]<br>                    new_similarity = self.cosine_similarity(candidate_embedding, new_embedding)<br><br>                    # Find the worst existing neighbor<br>                    worst_similarity = float(&#39;inf&#39;)<br>                    worst_neighbor = None<br><br>                    for neighbor_id in candidate_neighbors:<br>                        neighbor_embedding = self.vec2embeds[neighbor_id]<br>                        similarity = self.cosine_similarity(candidate_embedding, neighbor_embedding)<br>                        if similarity &lt; worst_similarity:<br>                            worst_similarity = similarity<br>                            worst_neighbor = neighbor_id<br><br>                    # Replace worst neighbor if new connection is better<br>                    if new_similarity &gt; worst_similarity:<br>                        candidate_neighbors.remove(worst_neighbor)<br>                        candidate_neighbors.append(new_vector_id)</pre><h4>Step 7 — Putting It All Together</h4><p>Now let’s update our insert method to use search and make connections:</p><pre>def insert(self, embedding, document):<br>    # Step 1: Determine layers<br>    max_layer = self._assign_layer()<br>    self.highest_layer = max(self.highest_layer, max_layer)<br>    vector_layers = list(range(max_layer + 1))<br><br>    # Step 2: Find neighbors (only if database isn&#39;t empty)<br>    candidates_by_layer = {}<br>    if self.currentID &gt; 0:  # There are existing vectors to search<br>        candidates_by_layer = self.search(embedding, num_candidates=50)<br><br>    # Step 3: Store the vector<br>    vector_id = self.currentID<br>    self.vec2embeds[vector_id] = embedding<br>    self.vec2docs[vector_id] = document<br><br>    # Step 4: Initialize neighbor lists<br>    self.vec2neighbors[vector_id] = {}<br>    for layer in vector_layers:<br>        self.vec2neighbors[vector_id][layer] = []<br><br>    # Step 5: Make connections<br>    if candidates_by_layer:<br>        self._make_connections(vector_id, candidates_by_layer, vector_layers)<br><br>    self.currentID += 1<br>    return vector_id</pre><h4>Step 8 — A Query Interface (Optional)</h4><p>Finally, let’s add a simple interface for users to search for documents:</p><pre>def query(self, query_embedding, k=5):<br>    &quot;&quot;&quot;Search for the k most similar documents&quot;&quot;&quot;<br>    if len(self.vec2neighbors) == 0:<br>        return []<br><br>    # Use our search algorithm to find candidates<br>    layer_candidates = self.search(query_embedding, num_candidates=k*2)<br><br>    if 0 not in layer_candidates:<br>        return []<br><br>    # Focus on layer 0 candidates (most complete set)<br>    candidates = layer_candidates[0]<br>    scored_results = []<br><br>    for candidate_id in candidates:<br>        similarity = self.cosine_similarity(query_embedding, self.vec2embeds[candidate_id])<br>        scored_results.append({<br>            &#39;document&#39;: self.vec2docs[candidate_id],<br>            &#39;similarity&#39;: similarity,<br>            &#39;vector_id&#39;: candidate_id<br>        })<br><br>    # Return top k results<br>    scored_results.sort(key=lambda x: x[&#39;similarity&#39;], reverse=True)<br>    return scored_results[:k]</pre><p><strong>Let’s run the whole thing now:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*jElONSYZvT9bwtNWsyvzBg.png" /></figure><h3>What We’ve Built</h3><p>We’ve built the same core algorithm that powers billion-dollar vector databases.</p><p><strong>Our implementation includes</strong>:</p><ul><li>✅ Probabilistic layer assignment (the coin-flipping magic)</li><li>✅ Multi-layer beam search (finding neighbors efficiently)</li><li>✅ Bidirectional connection management (building the navigable graph)</li><li>✅ Connection limits and eviction (maintaining graph quality)</li></ul><p>We’ve kept the code minimal on purpose. Real HNSW engines add a few powerful knobs — <strong>M/Mmax, </strong><strong>efConstruction, </strong><strong>efSearch</strong>, and heuristic neighbor selection—that trade memory for recall and latency. We’ll look at those next.</p><h3>HNSW in Practice: the simple knobs that make it fast and accurate</h3><p>We built a clean, minimal HNSW. In real systems, a few <strong>dials</strong> help you trade off <strong>speed</strong>, <strong>memory</strong>, and <strong>accuracy</strong>. Think of them like city-planning settings for your road network.</p><h4>1) How many roads per junction: M and Mmax</h4><ul><li><strong>What it means (plain):</strong> Cap the number of neighbors a node can keep.</li><li><strong>Why it helps:</strong> Fewer edges = less memory and faster updates; more edges = better coverage and easier routing.</li><li><strong>Typical setting:</strong> Upper layers stay <strong>sparse</strong>; the bottom layer (layer 0) is <strong>denser</strong>.</li><li>A common start: M = 16 on upper layers, Mmax0 = 32 on layer 0.</li></ul><p><strong>When to turn this knob:</strong></p><ul><li>Low memory / faster builds → <strong>decrease</strong> M.</li><li>Missing neighbors / recall too low → <strong>increase</strong> M (and Mmax0).</li></ul><h4>2) How wide your search party is: efConstruction and efSearch</h4><ul><li><strong>efConstruction (build time):</strong> How many candidates you consider while wiring a <strong>new</strong> node.</li><li>Higher = better graph quality (higher recall later), but <strong>slower</strong> and more RAM during build.</li><li><strong>efSearch (query time):</strong> How many candidates you keep while answering a <strong>query</strong>.</li><li>Higher = higher recall, but <strong>more latency</strong>.</li></ul><p><strong>Rules of thumb:</strong></p><ul><li>Start with efConstruction ≈ 200.</li><li>For k = 10, try efSearch in the <strong>50–200</strong> range and measure.</li></ul><p><strong>When to turn this knob:</strong></p><ul><li>Queries feel inaccurate → <strong>increase</strong> efSearch.</li><li>Latency is too high → <strong>decrease</strong> efSearch.</li><li>You want better recall without touching queries → <strong>increase</strong> efConstruction.</li></ul><h4>3) Don’t build five roads to the same suburb: diversified neighbors</h4><ul><li><strong>Problem:</strong> If you connect to the top-M nearest points blindly, you may pick neighbors that all sit in the <em>same direction</em>.</li><li><strong>Fix (diversification):</strong> While selecting neighbors, keep a candidate <strong>only if</strong> it adds a <em>new direction</em> (isn’t too similar to already-chosen neighbors)</li><li><strong>Why it helps:</strong> You cover space more evenly, so greedy search can hop across regions instead of getting stuck.</li></ul><h4>How This Compares to Production Systems</h4><p><strong>What Pinecone, Qdrant, and Weaviate add</strong>:</p><ul><li><strong>Memory optimization</strong>: Handle datasets larger than RAM</li><li><strong>Quantization</strong>: Use 8-bit floats instead of 32-bit to save memory</li><li><strong>SIMD instructions</strong>: Vectorized operations for faster similarity calculations</li><li><strong>Concurrent queries</strong>: Handle thousands of searches simultaneously</li><li><strong>Persistence</strong>: Save the index to disk and reload it</li><li><strong>Updates and deletes</strong>: Modify the graph after it’s built</li></ul><p>But the core algorithm? It’s exactly what we just built.</p><p>You can find the full code <a href="https://github.com/anshulLuhsna/HNSW-algorithm"><em>here</em></a></p><h3>What’s Next?</h3><p>Now that you understand HNSW, you can:</p><ol><li><strong>Try it with real embeddings</strong>: Use OpenAI’s API or Sentence Transformers to get actual vector representations of text</li><li><strong>Experiment with parameters</strong>: Try different values of max_connections and see how it affects performance</li><li><strong>Compare performance</strong>: Test this against brute force search to see the speed difference</li></ol><h3>Some history for nerds</h3><p>Now that you’ve built your own HNSW implementation, it’s worth knowing the remarkable story behind this algorithm.</p><p>HNSW was created by <strong>Yury Malkov and Dmitry Yashunin</strong>, two Russian physicists at the Institute of Applied Physics in Nizhny Novgorod. Both had earned PhDs in laser physics in 2015, but their interdisciplinary background proved crucial for solving a fundamental computer science problem.</p><p>In March 2016, they published their breakthrough paper <a href="https://arxiv.org/abs/1603.09320">“Efficient and robust approximate nearest neighbor search using Hierarchical Navigable Small World graphs”</a> on arXiv. Working in a laser physics lab, they brought fresh mathematical insights to the decades-old challenge of finding similar items in high-dimensional spaces.</p><p><strong>The timing was perfect.</strong> When HNSW was published in 2016, the AI boom was just beginning. By 2020–2021, transformer models and neural embeddings created massive demand for exactly what HNSW delivered: fast similarity search in high-dimensional spaces.</p><p><strong>The commercial explosion followed quickly.</strong> Edo Liberty founded Pinecone in 2019, recognizing that vector search would become critical infrastructure. When ChatGPT launched in late 2022 and created massive demand for RAG applications, companies built on HNSW were perfectly positioned. Pinecone went from $10M seed funding to a $750M valuation in just two years.</p><p>Soon, an entire ecosystem emerged: Weaviate (Amsterdam), Qdrant (Berlin), and dozens of other vector databases, all implementing the same core algorithm two Russian physicists had discovered in a laser physics lab.</p><p><strong>Today, HNSW powers the invisible infrastructure behind modern AI.</strong> Every time you ask ChatGPT a question that requires retrieving information, when Spotify recommends your next song, or when an AI assistant searches through millions of documents — HNSW is likely working behind the scenes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=03f1db8435fc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[Part 2] A2A+MCP: A Practical guide to the future of AI agent workflows]]></title>
            <link>https://medium.com/fossible/part-2-a2a-mcp-a-practical-guide-to-the-future-of-ai-agent-workflows-7ab38a013f02?source=rss-3164f83e8b6a------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ab38a013f02</guid>
            <category><![CDATA[multi-agent-systems]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[mcp-protocol]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[a2a-protocol]]></category>
            <dc:creator><![CDATA[Anshul Kalbande]]></dc:creator>
            <pubDate>Wed, 18 Jun 2025 04:38:21 GMT</pubDate>
            <atom:updated>2025-06-18T04:38:21.286Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Note: Both part 1 and part 2 of this series are the joint efforts of </em><a href="https://medium.com/u/5462300ec751?source=post_page---user_mention--f8052aa6e126---------------------------------------"><em>Anurag Mandke</em></a><em> and </em><a href="https://medium.com/u/3164f83e8b6a?source=post_page---user_mention--f8052aa6e126---------------------------------------"><em>Anshul Kalbande</em></a><em>.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/637b604b861976128be61b57a112622b/href">https://medium.com/media/637b604b861976128be61b57a112622b/href</a></iframe><p>In <strong>Part 1</strong>, we introduced two powerful, open-source protocols reshaping how AI agents communicate and collaborate: Google’s <strong>Agent-to-Agent (A2A)</strong> protocol and Anthropic’s <strong>Model Context Protocol (MCP)</strong>. <strong>A2A</strong> provides a standardized way for agents to delegate tasks and exchange information seamlessly, while <strong>MCP</strong> equips these agents with structured, real-time context by integrating external data and tools effortlessly.</p><p>Now, in <strong>Part 2</strong>, we’ll showcase a real-world implementation — a practical market research and financial analysis platform leveraging both protocols. By orchestrating specialized agents that fetch market data, gauge public sentiment, scrape web sources, and visualize insights, you’ll see firsthand how combining A2A and MCP results in a modular, scalable, and efficient AI-driven system.</p><h4>System at a glance</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WbZCpQ-M-iJmwzLpIEqYMQ.jpeg" /></figure><p>A <strong>user</strong> interacts directly with the <strong>UI orchestrator</strong>, which forwards the user request via the standardized <strong>Agent-to-Agent (A2A)</strong> protocol to a dedicated <strong>Remote Orchestrator</strong>. This Remote Orchestrator delegates specialized tasks to four distinct agents: <strong>Financial</strong>, <strong>Sentiment</strong>, <strong>Scraper</strong>, and <strong>Visualization</strong>. Each agent leverages context provided through the <strong>Model Context Protocol (MCP)</strong>. For example, the Financial agent queries local market data using a locally-hosted <strong>Postgres MCP server</strong>, while simultaneously accessing external crypto-price data through the <strong>CoinCap MCP</strong>. Similarly, the Sentiment agent gathers real-time market sentiment via the <strong>Reddit MCP server</strong>. This structured flow ensures efficient modularity, interoperability, and real-time data enrichment.</p><h4>Why two orchestrators?</h4><p>Well, David Wheeler has an excellent maxim for this question -</p><blockquote>“There’s no problem in Computer Science that can’t be solved by adding another layer of abstraction to it”</blockquote><p>The two orchestrators let the UI see an entire market-research cluster as one “agent,” hiding its five specialists so each domain can plug in as a self-contained module without bloating the frontend.</p><p>This design lets the UI orchestrator plug into any number of domain-specific clusters, each focused on its own area of expertise, and posing as a single agent with a dedicated orchestrator.</p><h3>A2A implementation</h3><h4>Route Discovery</h4><p>As we saw in Part 1, every A2A agent (whether an orchestrator or a specialist) exposes a machine-readable “Agent Card” at a standard endpoint (/.well-known/agent.json). This JSON file describes the agent’s identity, capabilities, and expected inputs/outputs, allowing other agents to discover how to talk to it. Here’s the remote orchestrator’s Agent Card:</p><pre>{<br>  &quot;name&quot;: &quot;Orchestrator Agent&quot;,<br>  &quot;description&quot;: &quot;Agent that breaks down user tasks and delegates them to specialized agents&quot;,<br>  &quot;url&quot;: &quot;http://localhost:8000/&quot;,<br>  &quot;version&quot;: &quot;1.0.0&quot;,<br>  &quot;capabilities&quot;: {<br>    &quot;streaming&quot;: true,<br>    &quot;pushNotifications&quot;: true,<br>    &quot;stateTransitionHistory&quot;: true<br>  },<br>  &quot;skills&quot;: [<br>    {<br>      &quot;id&quot;: &quot;task_decomposition&quot;,<br>      &quot;name&quot;: &quot;Task Decomposition&quot;,<br>      &quot;description&quot;: &quot;Ability to break down complex tasks into manageable subtasks&quot;<br>    },<br>    {<br>      &quot;id&quot;: &quot;agent_delegation&quot;,<br>      &quot;name&quot;: &quot;Agent Delegation&quot;,<br>      &quot;description&quot;: &quot;Ability to assign tasks to appropriate specialized agents&quot;<br>    },<br>    {<br>      &quot;id&quot;: &quot;workflow_management&quot;,<br>      &quot;name&quot;: &quot;Workflow Management&quot;,<br>      &quot;description&quot;: &quot;Ability to coordinate and track progress across multiple agents&quot;<br>    },<br>    {<br>      &quot;id&quot;: &quot;result_integration&quot;,<br>      &quot;name&quot;: &quot;Result Integration&quot;,<br>      &quot;description&quot;: &quot;Ability to compile and integrate results from multiple agents&quot;<br>    }<br>  ],<br>  &quot;defaultInputModes&quot;: [&quot;text&quot;],<br>  &quot;defaultOutputModes&quot;: [&quot;text&quot;],<br>  &quot;authentication&quot;: {<br>    &quot;schemes&quot;: [&quot;none&quot;]<br>  }<br>}</pre><h4>Sending a Task</h4><p>Once the UI Orchestrator knows where to send a request, it initiates a JSON-RPC call to the Remote Orchestrator’s task endpoint.</p><p>The <strong>UI Orchestrator</strong> constructs a JSON payload with the user’s prompt in a message part and a unique task ID, specifying the method as &quot;tasks/send&quot; (or &quot;tasks/sendSubscribe&quot; for streaming). For example, a request body might look like:</p><pre>{<br>  &quot;jsonrpc&quot;: &quot;2.0&quot;,<br>  &quot;id&quot;: 1,<br>  &quot;method&quot;: &quot;tasks/send&quot;,<br>  &quot;params&quot;: {<br>    &quot;id&quot;: &quot;de38c76d-d54c-436c-8b9f-4c2703648d64&quot;,<br>    &quot;message&quot;: {<br>      &quot;role&quot;: &quot;user&quot;,<br>      &quot;parts&quot;: [<br>        { &quot;type&quot;: &quot;text&quot;, &quot;text&quot;: &quot;Tell me a joke about stocks.&quot; }<br>      ]<br>    },<br>    &quot;metadata&quot;: {}<br>  }<br>}</pre><p>When this POST hits the Remote Orchestrator’s server, the framework parses it and recognizes the JSON-RPC method. In code, the payload is validated and routed: if the &quot;method&quot; is &quot;tasks/send&quot; or &quot;tasks/sendSubscribe&quot;, the server calls the appropriate handler in its. The <strong>Remote Orchestrator</strong>’s handler (e.g. on_send_task) then delegates work to a specialist agent. It uses the A2A protocol to forward the prompt as a new task to the appropriate agent – for example, sending a tasks/send request to the FinancialAgent’s URL for a finance query.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rbnoQiSpLpp-Zf68" /></figure><p>The code abstracts this step using Google’s A2A SDK: it creates an A2A client or request object and calls the remote agent’s endpoint with the user’s question. In essence, the orchestrator becomes an A2A <strong>client</strong> to the specialist agent. This kicks off the task on the Financial or Sentiment Agent in the same standardized way, without the orchestrator needing internal knowledge of those agents (it relies on the Agent Card and A2A interface). The Remote Orchestrator immediately returns an acknowledgement to the UI (for non-streaming calls) or begins preparing to stream results if in subscribe mode.</p><h4>Streaming Updates</h4><p>For long-running tasks or incremental results, the system uses <strong>Server-Sent Events (SSE)</strong> via the tasks/sendSubscribe mode. In this case, the UI Orchestrator’s initial request is a subscribe call, so the Remote Orchestrator keeps the HTTP connection open and streams updates as they arrive. Under the hood, the A2A server code checks if the task handler returned an asynchronous iterator (async generator). If so, it wraps it in an SSE response:</p><pre>def _create_response(self, result: Any) -&gt; JSONResponse | EventSourceResponse:<br>    if isinstance(result, AsyncIterable):<br>        async def event_generator(result) -&gt; AsyncIterable[dict[str, str]]:<br>            async for item in result:<br>                yield {&quot;data&quot;: item.model_dump_json(exclude_none=True)}<br>        return EventSourceResponse(event_generator(result))<br>    elif isinstance(result, JSONRPCResponse):<br>        return JSONResponse(result.model_dump(exclude_none=True))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WDG0FRckD_7lYc6qjkxajA.jpeg" /></figure><p>In our case, the <strong>Remote Orchestrator</strong>’s handler returns an async generator that yields partial results (e.g. intermediate analysis or data fetched from the specialist). The snippet above shows that the server detects this and uses EventSourceResponse to stream each yielded item as an SSE event. Each event might contain a JSON-RPC “TaskUpdate” (with new artifacts or status). Meanwhile, the Remote Orchestrator has also initiated a subscribe call to the specialist agent. The <strong>Financial Agent</strong> (for example) will likewise stream its progress back to the orchestrator. The orchestrator’s task manager listens on the specialist’s SSE channel (e.g. via an async HTTP client) and forwards those updates upstream. In this way, a chain of SSE connections propagates live updates: the specialist agent pushes events to the orchestrator’s tasks/get (subscribe) route, and the orchestrator pushes events to the UI’s subscribe connection. This continues until the specialist signals completion.</p><h4>Returning Artifacts</h4><p>When the specialist finishes the task, it sends a final JSON-RPC response (or final SSE event) marking the task as <strong>completed</strong> and including any resulting artifacts (e.g. the final answer text, or data compiled). The Remote Orchestrator may combine multiple agents’ outputs at this stage. For instance, it might wait for both the FinancialAgent and SentimentAgent to finish and then assemble a final report artifact. In the code, the arrival of a final event is flagged by the protocol — for example, event.is_final_response() returns true for the last update. The client-side logic (or orchestrator receiving from a specialist) checks for this to know the task is done:</p><pre>async for event in events_async:<br>    if event.is_final_response():<br>        if event.content and event.content.parts:<br>            final_response_text = event.content.parts[0].text<br>        elif event.actions and event.actions.escalate:<br>            final_response_text = f&quot;Agent escalated: {event.error_message or &#39;No message.&#39;}&quot;<br>        print(f&quot;Final Response: {final_response_text}&quot;)<br>        break</pre><p>Here the code looks at the final event’s content parts (the agent’s answer) and prints out the final result. In the backend, a similar step occurs: the <strong>Remote Orchestrator</strong> collects the final artifacts from the specialist and wraps them in its own JSON-RPC response to the UI. Any remaining state is updated to “completed”. If there were multiple partial artifacts streamed earlier, the final artifact might be a summary or collation of them. The use of A2A ensures that even these final pieces conform to a standard structure (each artifact composed of parts, like text), which the orchestrator and client can easily handle. Once the final artifact is delivered, the SSE stream closes and the task is complete.</p><h3>MCP Implementation</h3><h4>Servers at a glance</h4><p>In this repo three MCP servers are defined — for Postgres, CoinCap, and Reddit — each exposing domain-specific resources and tools. The <strong>Postgres server</strong> runs on the local Docker network and exposes database resources (schemas/tables) and SQL execution tools (e.g. “run_sql” or “list_tables”). The <strong>CoinCap server</strong> wraps the public CoinCap crypto API, so its manifest likely declares resources like <em>cryptocurrency price data</em> and tools such as get_price(coin) and get_historical_prices. The <strong>Reddit server</strong> provides Reddit content: its manifest lists resources (e.g. a subreddit or post stream) and tools to fetch recent posts or comments from r/Bitcoin or other communities.</p><h3>How Agents Invoke MCP Tools</h3><p>Agents use standard MCP clients or HTTP calls to consume these servers’ tools. For example, an A2A agent might call a URI like mcp://coincap/get_price?symbol=BTC or use a built-in MCP client adapter to invoke the CoinCap server’s get_price tool, retrieving real-time Bitcoin data. In the sentiment agent flow, an A2A task goes from the agent to the MCP server and then on to the external API. As the README’s architecture diagram shows, a task eventually flows “Agent → MCP Server → Reddit API”. Concretely, the agent’s task manager invokes an MCP client that looks up the Reddit server’s manifest (via .well-known/mcp.json), selects the right tool (e.g. “fetch subreddit posts”), calls it over HTTP, and then passes the JSON response back into the agent. In effect the agent does not need custom scraping code – it just “calls the tool by name” and the MCP server does the API work.</p><h3>Comparative Study</h3><p>Below is a quick comparison showing how adding MCP and A2A makes our AI system faster, more reliable, and easier to manage compared to the old way of connecting agents:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iBoTCmYCirGM9aeh79GH_w.png" /></figure><h3>Resilience &amp; Fault Tolerance</h3><p>Real-world systems need to handle failure gracefully. Here’s how this architecture ensures robustness:</p><ul><li><strong>MCP Tool Failures</strong>: MCP calls include timeouts and structured error responses. Agents validate responses and handle timeouts explicitly.</li><li><strong>Agent Errors &amp; Escalation</strong>: A2A agents emit TaskFailed events and standardized error payloads. Orchestrators can retry, escalate, or fallback.</li><li><strong>Retries &amp; Fallbacks</strong>: Orchestrators use exponential backoff, alternate tools, or partial result propagation to maintain workflow continuity.</li><li><strong>Best Practices</strong>: Agents are designed to be stateless, handle exceptions cleanly, and stream status updates even during errors.</li></ul><h3>Local vs Remote Context</h3><p>Because the Postgres MCP server runs in the local Docker environment, calls to it execute SQL directly on a containerized database (no external network). In contrast, the CoinCap and Reddit MCP servers are thin wrappers over public APIs. The agents don’t see this difference — they use the same tool invocation mechanism — but under the hood the CoinCap/Reddit servers make HTTP requests out to the web. This split means the Postgres context is local (fast, self-hosted), while CoinCap/Reddit use remote context. From the agent’s point of view it’s transparent, but in practice the remote servers may require dealing with API limits or tokens, whereas the Postgres server just needs DB credentials in its container.</p><h3>Putting It All Together</h3><p>At runtime, an agent receives an A2A request and may invoke multiple MCP services. For instance, a financial agent could retrieve a stock price by calling the CoinCap MCP tool, then store or compare it via the Postgres MCP tool. The sentiment agent takes Reddit query inputs (e.g. “current Bitcoin sentiment”), invokes the Reddit MCP tool to fetch posts, and then sends that text into a language model for analysis. All these calls follow the A2A task lifecycle (as shown in the sentiment README): <em>A2A Request → Task Manager → Agent → MCP Server → External API → processing → A2A Response</em>. The MCP manifests keep everything discoverable — the agent never hardcodes endpoints, it simply asks “give me Bitcoin price” or “give me r/Bitcoin posts” and the infrastructure routes the call to the right tool.</p><h3>A short demo</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F449P2SQCsjg%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D449P2SQCsjg&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F449P2SQCsjg%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/b1a493926d749eee6be3a561e74262c9/href">https://medium.com/media/b1a493926d749eee6be3a561e74262c9/href</a></iframe><blockquote>Check out the <a href="https://github.com/anshulLuhsna/a2a_with_mcp">repo</a> and refer the readme to run it yourself</blockquote><h3>How to make your agent A2A compliant</h3><h4>Step 1: Decide Your Agent’s Role</h4><p>Are you creating an agent to <strong>perform specialized tasks</strong> (like sentiment analysis or financial forecasting)? That makes you an <strong>A2A server</strong>, meaning you’ll publish your capabilities for others to use.<br> Or are you building an agent that <strong>coordinates and delegates tasks to other agents</strong>? That’s an <strong>A2A client</strong>, meaning you’ll consume the services published by others.</p><p>This choice is crucial — it determines if your agent will open connections (server) or make calls (client).</p><h4>Step 2: Create an Agent Card</h4><p>If you’re an A2A server, you’ll need an <strong>Agent Card</strong> (agent.json). This is like your agent’s LinkedIn profile—it describes who you are and what you can do.<br> Here&#39;s a simple example:</p><pre>{<br>  &quot;name&quot;: &quot;Financial Analyst Agent&quot;,<br>  &quot;description&quot;: &quot;Provides crypto market analysis and charts.&quot;,<br>  &quot;url&quot;: &quot;https://youragent.com&quot;,<br>  &quot;capabilities&quot;: {<br>    &quot;messages&quot;: true,<br>    &quot;artifacts&quot;: true<br>  },<br>  &quot;skills&quot;: [&quot;crypto-prices&quot;, &quot;chart-rendering&quot;]<br>}</pre><p>If you’re an A2A client, you’ll typically skip this, unless you also want to offer your own services.</p><h4>Step 3: Implement the Required Endpoints (Server)</h4><p>As a server, you’ll expose these three standard endpoints for A2A interactions:</p><ul><li>POST /tasks/send (receive new tasks)</li><li>POST /tasks/sendSubscribe (receive new tasks with real-time streaming)</li><li>GET /tasks/get?id=&lt;task_id&gt; (stream real-time task updates via SSE)</li></ul><p>This is how others call your agent to ask for work to be done.</p><h4>Step 4: Set Up Task Management (Server)</h4><p>When you receive a task request, you’ll need to track it carefully.<br> Implement or reuse a simple task manager to store tasks, track their statuses (SUBMITTED → WORKING → COMPLETED), and manage streaming updates back to clients.</p><h4>Step 5: Run Your Business Logic (Server)</h4><p>This is the core of your agent — where you actually perform your specialized task (like fetching crypto prices or analyzing sentiment).<br> While your agent does the heavy lifting, it should send back updates (TaskUpdate messages) in real time so users see live progress.</p><h4>Step 6: Deliver Your Results (Artifacts)</h4><p>Once you finish the task, package your results neatly into <strong>artifacts</strong> (charts, CSV, JSON responses, etc.). Include links to these artifacts in your final update message so your caller can easily retrieve and use them.</p><h4>Step 7: Secure Your Agent (Optional but Recommended)</h4><p>Consider adding basic security. Accept API keys, OAuth tokens, or JWTs through an Authorization header, and validate incoming calls. This ensures your agent stays protected and is used responsibly.</p><h4>Step 8: Validate Your Setup (Server and Client)</h4><p>Test your agent easily using the official A2A CLI from Google:</p><pre>pip install google-a2a</pre><pre># Check your agent card<br>a2a ping <a href="https://youragent.com/">https://youragent.com</a></pre><pre># Test sending a task<br>a2a send --card <a href="https://youragent.com/.well-known/agent.json">https://youragent.com/.well-known/agent.json</a> --prompt &quot;Test task&quot;</pre><p>By following these steps, you’ve made your agent fully A2A-compliant — ready to seamlessly integrate into a growing ecosystem of modular, interoperable AI services!</p><h3>How to Wrap Your Tools in an MCP Server</h3><h4>Step 1: Choose Your MCP Server Framework</h4><p>Pick an MCP-friendly server framework, such as <strong>FastMCP</strong> (built on FastAPI):</p><pre>pip install &quot;mcp[cli]&quot; fastapi uvicorn</pre><h4>Step 2: Define Your MCP Server and Tools</h4><p>Create a Python script (e.g., mcp_server.py). Here&#39;s an example where you&#39;ll substitute <strong>your</strong> existing tool:</p><pre>from mcp.server.fastmcp import FastMCP</pre><pre>mcp = FastMCP(&quot;YourToolMCP&quot;)  # &lt;- Change this to your server&#39;s name<br># Replace this example tool with YOUR actual function<br>@mcp.tool()<br>def your_custom_tool(your_input: str) -&gt; str:  # &lt;- Change function name and parameters<br>    # Your code goes here!<br>    return f&quot;Result of your tool with input: {your_input}&quot;<br>if __name__ == &quot;__main__&quot;:<br>    mcp.run()</pre><p><strong>Highlight:</strong></p><ul><li>Substitute your_custom_tool with the <strong>name of your existing function</strong>.</li><li>Replace your_input with your tool’s <strong>actual parameters</strong>.</li><li>Implement your existing logic within the function.</li></ul><h4>Step 3: Declare Your Resources and Prompts (Optional but Recommended)</h4><p>You can optionally add standardized resources (static data) and prompts (structured interactions):</p><pre>@mcp.resource()<br>def your_resource(identifier: str) -&gt; str:  # &lt;- Replace with your own data-fetching logic<br>    # Return static or cached data<br>    return f&quot;Static data related to {identifier}&quot;</pre><pre>@mcp.prompt()<br>def your_prompt(user_question: str):<br>    # Replace below with your own workflow or prompt<br>    return [<br>        {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: user_question},<br>        {&quot;role&quot;: &quot;assistant&quot;, &quot;content&quot;: &quot;Processing your request...&quot;},<br>        {&quot;role&quot;: &quot;function&quot;, &quot;name&quot;: &quot;your_custom_tool&quot;, &quot;arguments&quot;: {&quot;your_input&quot;: user_question}},<br>    ]</pre><p><strong>Highlight:</strong></p><ul><li>Replace your_resource with a function that returns <strong>your own static or dynamic data</strong>.</li><li>Modify your_prompt to represent <strong>your own conversational flow or tool invocation logic</strong>.</li></ul><h4>Step 4: Serve Your MCP Server</h4><p>Start your server locally to test your setup:</p><pre>uvicorn mcp_server:mcp.app --reload</pre><p>This runs your MCP server at <a href="http://localhost:8000.">http://localhost:8000.</a></p><h4>Step 5: Test Your MCP Server</h4><p>Verify your server and tools are exposed correctly:</p><pre>curl http://localhost:8000/.well-known/mcp/manifest.json</pre><p>Check that your tools and resources appear as expected.</p><h4>Step 6: Secure Your MCP Server (Recommended)</h4><p>If your tools handle sensitive information, integrate authentication such as API keys or OAuth within your server logic.</p><h4>Step 7: Document Your Server</h4><p>Provide simple, clear examples on how other developers or agents can use your MCP resources and tools.</p><h3>Final Thoughts</h3><p><a href="https://medium.com/u/5462300ec751">Anurag Mandke</a> and I have truly enjoyed collaborating on this project. As we release part two, it’s remarkable to note that not just one or two, but three new protocols have already been launched by major industry players: IBM’s <a href="https://www.ibm.com/think/topics/agent-communication-protocol">ACP</a> (Agent Communication Protocol), as well as AGNTCY’s <a href="https://github.com/agntcy/slim">AGP</a> (Agent Gateway Protocol) and <a href="https://agent-network-protocol.com/">ANP</a> (Agent Network Protocol).</p><blockquote>Not to be all existential but what. a. time. to. be. alive.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ab38a013f02" width="1" height="1" alt=""><hr><p><a href="https://medium.com/fossible/part-2-a2a-mcp-a-practical-guide-to-the-future-of-ai-agent-workflows-7ab38a013f02">[Part 2] A2A+MCP: A Practical guide to the future of AI agent workflows</a> was originally published in <a href="https://medium.com/fossible">FOSSible</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Retrieval Augmented Generation (RAG) — Worqhat AiCon + Langchain]]></title>
            <link>https://medium.com/worqhat/retrieval-augmented-generation-rag-worqhat-aicon-langchain-46059c529f2d?source=rss-3164f83e8b6a------2</link>
            <guid isPermaLink="false">https://medium.com/p/46059c529f2d</guid>
            <category><![CDATA[worqhat]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[langchain]]></category>
            <dc:creator><![CDATA[Anshul Kalbande]]></dc:creator>
            <pubDate>Mon, 15 Apr 2024 18:30:13 GMT</pubDate>
            <atom:updated>2024-04-15T18:30:13.616Z</atom:updated>
            <cc:license>http://creativecommons.org/publicdomain/zero/1.0/</cc:license>
            <content:encoded><![CDATA[<h3>Retrieval Augmented Generation (RAG) — WorqHat AiCon + Langchain</h3><p><strong>Who should read? </strong>— Anyone looking to build a chatbot/assistant on their custom data.</p><p><strong>What will be covered?</strong></p><ol><li>What is RAG?</li><li>LangChain overview</li><li>WorqHat LLMs overview</li><li>Project 1: Using PineCone VectorDB (cloud) and streamlit — Python</li><li>Project 2: Using a Local memory VectorDB and the Vercel AI SDK — Javascript/Typescript</li></ol><p><em>The only motive behind writing this article is to share my experience while exploring RAG for my personal projects. While I have done my best to provide accurate and up-to-date information, please keep in mind that my knowledge is limited to what I have personally researched and experienced. This article should not be considered an official or authoritative source on the topic of retrieval-augmented generation.</em></p><h3>What is RAG?</h3><p>Look, if you are reading this, I know you’ve probably played around with ChatGPT, Claude, Gemini, and all the other big AI chatbots out there. And you might be wondering, “What’s the point of yet another AI app?”</p><p>Fair question. But the thing is, most of those bots can only access the data they were trained on — which, let’s be real, can get pretty outdated pretty fast.</p><p>And none of them can tap into the actual files and information you’ve got stored on your own computer. That’s where this whole retrieval-augmented generation (RAG) thing comes in handy. RAG is a framework that lets AI models like large language models (LLMs) pull in relevant facts and data from external sources — including your own local files. So instead of just spitting out generic responses, the AI can ground its outputs in the most up-to-date and personalized information available.</p><p>Enough talk. Let’s visualize this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nYs8n1FkTxblk7YOskwCaQ.png" /><figcaption>An overview of the workflow</figcaption></figure><p>Let’s break it down:</p><h4><strong>1. Splitting &amp; Chunking:</strong></h4><p>Assuming you have a ship container worth of data, it only makes sense to chunk it up. These chunks can be made in a few different ways: by character, by tokens, by markdown, etc. Chunk sizes are also important and should be customized to the length of average context required to answer any question to optimize token usage and response accuracy.</p><h4><strong>2. Embeddings:</strong></h4><p>Text chunks are then converted into embeddings. Embeddings, in layman terms, are nothing but a numerical form of the text data.</p><p>How are embeddings made? Well, do you ever rate people you see on the street based on their looks, facial expressions, and <em>vibes?</em> I’m sure you do. We get an embedding model to do exactly this with our chunks of data.</p><p>The are key differences are:</p><ul><li>The model rates each chunk on a LOT more parameters than us (1536 dimensions in our case).</li><li>The model does not keep the ratings to itself (I don’t either sometimes) and returns a unique vector for each chunk. Essentially a data <em>fingerprint</em>.</li></ul><p>Here is an example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_IcVAAQ4tnzoQXtHUW6U5A.png" /></figure><p>So when all is said and done, we are able to perform sematic search on this data and get the most contextually similar embedding and it’s corresponding text chunk.</p><p>And we do just that once we also convert the user query to an embedding to make it an <em>apple-to-apple </em>comparison.</p><h4><strong>3. Large Language Model:</strong></h4><p>If everything goes to plan, we should end up with the answer to our query. But it’s not exactly in flow with the conversation and maybe it’s irrelevant because the user asked something out of the database.</p><p>Enter the engine of our system, the Large Language Model (LLM). As mentioned at the very beginning, an LLM is already trained on millions and millions of words and is able to answer generic questions with ease.</p><p>So, with a bit of prompt engineering, we are able to pass the user query, the relevant chunk with answer to that query, and custom instructions on how to reply, all in the context window of the LLM.</p><p><em>Surely now it’ll tell me the meaning of life.</em></p><h3>Langchain Overview:</h3><p><a href="https://www.langchain.com/">LangChain</a> is a framework for developing applications powered by large language models (LLMs).</p><p>Remember that flowchart we looked at earlier? Almost every step is made MUCH MUCH simpler by LangChain.</p><p>Not only the RAG workflow, LangChain simplifies every stage of the LLM application lifecycle:</p><ul><li>Development: Build your applications using LangChain’s open-source <a href="https://python.langchain.com/docs/expression_language/">building blocks</a> and <a href="https://python.langchain.com/docs/modules/">components</a>. Hit the ground running using <a href="https://python.langchain.com/docs/integrations/platforms/">third-party integrations</a> and <a href="https://python.langchain.com/docs/templates/">Templates</a>.</li><li>Productionization: Use <a href="https://python.langchain.com/docs/langsmith/">LangSmith</a> to inspect, monitor and evaluate your chains, so that you can continuously optimize and deploy with confidence.</li><li>Deployment: Turn any chain into an API with <a href="https://python.langchain.com/docs/langserve/">LangServe</a>.</li></ul><p>Note: While there are plenty of excellent Langchain tutorials available, in this article, we’ll only be exploring the tip of the iceberg of Langchain and its ecosystem. My aim is to encourage the use of other language models, such as WorqHat AiConV2/V3, which are not yet natively supported by Langchain, and demonstrate how they can be integrated using the customLLM class method.</p><h3>WorqHat LLMs overview:</h3><p>WorqHat is a no-code platform builder that utilizes the power of Generative AI to produce brandable Custom Apps. You can read more at https://worqhat.com</p><p>Here is the MT-bench scores of WorqHat’s AiCon LLMS compared against the likes of GPT, Claude and LLama 2. You can read more about these comparisons in this <a href="https://blog.worqhat.com/a-benchmark-excellence-of-aicon-ee6337d1e7eb">article</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*oWPoK-bvOdTcYXlx.png" /><figcaption>MT-bench score</figcaption></figure><p>To get started, you can start by forking their <a href="https://docs.worqhat.com/postman-reference">Postman Collection.</a> Then get your API key from the developer settings.</p><p>Here is an example of testing their APIs with Postman:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lNQ7aEPteLczogmR1-latg.png" /></figure><p>Note: It is <strong>VERY </strong>important to pass these different parameters correctly. For example, the conversation history is only saved as a record, fetched only if needed, else ignored. Training data is like a set of guidelines for the model to follow, it is kept on the highest priority. Here’s the full <a href="https://docs.worqhat.com/api-reference/ai-models/text-generation-ai/aicon-v2-textgen">API reference</a>.</p><h3>Project 1: Using PineCone VectorDB (cloud) and streamlit</h3><p>In this section, we are building a streamlit app which uses the RAG framework to retrieve data from a pdf titled “New features introduced with Next.js 13”. As you can probably tell, these new features are not known to the LLMs which makes them perfect for our little demo!</p><h4>PineCone and upserting to an index</h4><p>After signing up, go ahead and create an index with 1536 dimensions.</p><p>Now, we’ll split up the docs and store the chunks in the index after converting them to embeddings.</p><pre>pip install openai langchain pinecone-client pypdf langchain_experimental langchain_openai</pre><p>After installing the dependencies, place the pdf you want to upsert in the same directory as your upsert.py</p><p>upsert.py:</p><pre>from langchain.document_loaders import PyPDFLoader<br>from langchain.embeddings.openai import OpenAIEmbeddings<br>import uuid<br>from pinecone import Pinecone<br>from langchain_experimental.text_splitter import SemanticChunker<br>from langchain_openai.embeddings import OpenAIEmbeddings<br><br>loader = PyPDFLoader(&quot;nextjs-new-features.pdf&quot;) #Replace with your pdf name.<br>pages = loader.load_and_split()<br>text = &#39;&#39;.join([page.page_content for page in pages])<br>text_splitter = SemanticChunker(OpenAIEmbeddings(openai_api_key=&quot;YOUR OPENAI API KEY&quot;))<br>docs = text_splitter.create_documents([text])<br><br>embeddings = OpenAIEmbeddings(openai_api_key=&quot;YOUR OPENAI API KEY&quot;)<br>pc = Pinecone(api_key=&quot;YOUR PINECONE API KEY&quot;)<br>index = pc.Index(&quot;nextjs&quot;)<br><br>from openai import OpenAI<br>client = OpenAI(api_key=&quot;YOUR OPENAI API KEY&quot;)<br><br>for doc in docs:<br>  response = client.embeddings.create(<br>    input=doc.page_content,<br>    model=&quot;text-embedding-3-small&quot;<br>  )<br>  embedding = response.data[0].embedding<br>  index.upsert(<br>      vectors=[<br>          {<br>              &quot;id&quot;: str(uuid.uuid4()),<br>              &quot;values&quot;: embedding,<br>              &quot;metadata&quot;: {&quot;text&quot;: doc.page_content}<br>          }<br>      ]<br>  )</pre><p>Here, I’ve used the <strong>Semantic chunker</strong> taken from Greg Kamradt’s wonderful notebook:<em> </em><a href="https://github.com/FullStackRetrieval-com/RetrievalTutorials/blob/main/tutorials/LevelsOfTextSplitting/5_Levels_Of_Text_Splitting.ipynb"><em>5_Levels_Of_Text_Splitting</em></a><em>.</em> Check it out if you want to have more control over your splits.</p><p>I have opted for OpenAI’s <strong>text-embedding-3-small</strong> because it is their cheapest model to date with a staggering <em>62,500 pages/dollar. </em>You can, of course, switch out this embedding model with an open-source model from HuggingFace.</p><p>If everything went well, you should see some vectors on your dashboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*deRB9NrpliOdbCkg9fxooQ.png" /><figcaption>Pinecone index dashboard</figcaption></figure><h4>The CustomLLM class</h4><p>Here comes the main thing I wanted to share through this article. Since Langchain does not provide native support for AiCon, we need to define the class for ourselves:</p><pre>class CustomLLM(LLM):<br>    n: int <br><br>    @property<br>    def _llm_type(self) -&gt; str:<br>        return &quot;custom&quot;<br><br>    def _call(<br>        self,<br>        prompt,<br>        **kwargs: Any,<br>    ) -&gt; str:<br>        <br>        #Prompt parsing to extract the different variables will go here<br>        # This part will be different according to which prompt template you<br>        # use and how your variables are formatted<br><br>        url = &quot;https://api.worqhat.com/api/ai/content/v2&quot;<br><br>        payload = json.dumps({<br>            &quot;question&quot;: human_message,<br>            &quot;preserve_history&quot;: True,<br>            &quot;stream_data&quot;: False,<br>            &quot;conversation_history&quot;: conversation_history_obj,<br>            &quot;response_type&quot;: &quot;text&quot;,<br>            &quot;training_data&quot;: context_message<br>        })<br><br>        headers = {<br>            &#39;Content-Type&#39;: &#39;application/json&#39;,<br>            &#39;Accept&#39;: &#39;application/json&#39;,<br>            &#39;Authorization&#39;: &#39;Bearer YOUR_API_KEY&#39;<br>        }<br><br>        response = requests.post(url, headers=headers, data=payload)<br><br>        return response.text<br><br>    @property<br>    def _identifying_params(self) -&gt; Mapping[str, Any]:<br>        return {&quot;n&quot;: self.n}</pre><p>Unlike <a href="https://js.langchain.com/docs/modules/model_io/llms/custom_llm">Langchain.js</a>, the original <a href="https://python.langchain.com/docs/modules/model_io/llms/custom_llm/">langchain for python</a> does not seem to support <em>response streaming</em>. This is kind of the reason I’m covering both python and JavaScript versions, as no streaming support is a dealbreaker for some people (myself included).</p><h4>The full streamlit app.py</h4><pre>pip install streamlit requests langchain-core pinecone-client openai python-dotenv</pre><pre>import streamlit as st<br>import requests<br>import json<br>import re<br>from typing import Any<br>from langchain_core.language_models.llms import LLM<br>from typing import Any, Mapping<br>from langchain_core.output_parsers import StrOutputParser<br>from langchain_core.prompts import ChatPromptTemplate<br>from pinecone import Pinecone<br>from openai import OpenAI<br>from dotenv import load_dotenv<br><br>load_dotenv()<br><br>class CustomLLM(LLM):<br>    n: int <br><br>    @property<br>    def _llm_type(self) -&gt; str:<br>        return &quot;custom&quot;<br><br>    def _call(<br>        self,<br>        prompt,<br>        **kwargs: Any,<br>    ) -&gt; str:<br>        human_match = re.search(r&quot;Human: (.*?)(?=\n(?:Context|Topic|Training Data|Conversation History):|\Z)&quot;, prompt, re.DOTALL)<br>        message_match = re.search(r&quot;Context: (.*?)(?=\n(?:Topic|Training Data|Conversation History):|\Z)&quot;, prompt, re.DOTALL)<br>        conversation_history_match = re.search(r&quot;Conversation History:\n(.*?)(?=\n(?:Topic|Training Data):|\Z)&quot;, prompt, re.DOTALL)<br><br>        human_message = human_match.group(1).strip() if human_match else &quot;&quot;<br>        context_message = message_match.group(1).strip() if message_match else &quot;&quot;<br>        conversation_history_str = conversation_history_match.group(1).strip() if conversation_history_match else &quot;&quot;<br>     <br>        try:<br>            conversation_history_obj = json.loads(conversation_history_str)<br>        except json.JSONDecodeError:<br>            conversation_history_obj = []<br>            conversation_pairs = re.findall(r&quot;{\s*&#39;(.*?)&#39;\s*:\s*&#39;(.*?)&#39;\s*}&quot;, conversation_history_str)<br>            for conversation_pair in conversation_pairs:<br>                conversation_history_obj.append({conversation_pair[0]: conversation_pair[1]})<br><br>        # I recommend you get some AI to do this formatting for you.<br>        # They are pretty good at Regular Expressions<br><br>        url = &quot;https://api.worqhat.com/api/ai/content/v2&quot;<br><br>        payload = json.dumps({<br>            &quot;question&quot;: human_message,<br>            &quot;preserve_history&quot;: True,<br>            &quot;stream_data&quot;: False,<br>            &quot;conversation_history&quot;: conversation_history_obj,<br>            &quot;response_type&quot;: &quot;text&quot;,<br>            &quot;training_data&quot;: context_message<br>        })<br><br>        headers = {<br>            &#39;Content-Type&#39;: &#39;application/json&#39;,<br>            &#39;Accept&#39;: &#39;application/json&#39;,<br>            &#39;Authorization&#39;: &#39;Bearer YOUR_API_KEY&#39;<br>        }<br><br>        response = requests.post(url, headers=headers, data=payload)<br><br>        return response.text<br><br>    @property<br>    def _identifying_params(self) -&gt; Mapping[str, Any]:<br>        return {&quot;n&quot;: self.n}<br><br>llm = CustomLLM(n=10)<br><br>def generate_response(prompt, topic, conversation_history):<br>    client = OpenAI()<br>    pc = Pinecone(api_key=&quot;YOUR_API_KEY&quot;)<br>    index = pc.Index(&quot;nextjs&quot;)<br><br>    response = client.embeddings.create(<br>        input=topic,<br>        model=&quot;text-embedding-3-small&quot;<br>    )<br><br>    query_result = index.query(<br>        vector=response.data[0].embedding,<br>        top_k=1,<br>        include_metadata=True,<br>    )<br><br>    context = query_result[&#39;matches&#39;][0][&#39;metadata&#39;][&#39;text&#39;]<br><br>    prompt_template = ChatPromptTemplate.from_template(prompt + &quot;\n\nContext: {context}\n\nTopic: {topic}\n\nConversation History:\n{conversation_history}&quot;)<br><br>    output_parser = StrOutputParser()<br><br>    chain = prompt_template | llm | output_parser<br><br>    response_content = chain.invoke({&quot;context&quot;: context, &quot;topic&quot;: topic, &quot;conversation_history&quot;: conversation_history})<br><br>    return json.loads(response_content)[&quot;content&quot;]<br><br>def main():<br>    st.title(&quot;NextJS 13 new features bot&quot;)<br><br>    conversation_history = st.session_state.get(&quot;conversation_history&quot;, [])<br><br>    prompt = st.text_area(&quot;Enter your prompt&quot;)<br>    topic = st.text_input(&quot;Enter topic&quot;)<br><br>    if st.button(&quot;Generate Response&quot;):<br>        if prompt and topic:<br>            response = generate_response(prompt, topic, conversation_history)<br>            conversation_history.append({prompt: response})<br>            st.session_state[&quot;conversation_history&quot;] = conversation_history<br>            st.success(&quot;Generated Response:&quot;)<br>            st.write(response)<br>        else:<br>            st.warning(&quot;Please enter both prompt and topic.&quot;)<br><br><br>if __name__ == &#39;__main__&#39;:<br>    main()<br><br></pre><h4>Prompts with Langchain:</h4><p>Prompt templates are predefined recipes for generating prompts for language models.A template may include instructions, few-shot examples, and specific context and questions appropriate for a given task. LangChain provides tooling to create and work with prompt templates.</p><h4>Using Prompt Templates:</h4><p>Use PromptTemplate to create a template for a string prompt.</p><p>By default, PromptTemplate uses <a href="https://docs.python.org/3/library/stdtypes.html#str.format">Python’s str.format</a> syntax for templating. The template supports any number of variables, including no variables:</p><p>You can check out my deployed version here: <a href="https://rag-article-python.streamlit.app/">Streamlit (rag-article-python.streamlit.app)</a>. <em>It can even give you code right out of the pdf :)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lXvYjqIyyruGJpEOUuwN6g.png" /><figcaption>Note: Rememer that the semantic search happens on the <strong>topic</strong> not the prompt in this case.</figcaption></figure><p>If the deployed version doesn’t work for some reason, here is my <a href="https://github.com/anshulLuhsna/RAG-article/tree/main/Python">repo</a>.</p><h4>A few words on LangChain Expression Language:</h4><p>LCEL, is a declarative way to easily compose chains together.</p><p>Example:</p><pre>chain = prompt_template | llm | output_parser</pre><blockquote>LCEL was designed to support putting prototypes in production, with no code changes, from the simplest “prompt + LLM” chain to the most complex chains.</blockquote><p>And again, I encourage you to explore Langchain and it’s ecosystem on your own.</p><h3>Project 2: Using a Local memory VectorDB and the Vercel AI SDK — Javascript/Typescript</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wPBDOzTzeYLbpYbwE-OHLQ.png" /><figcaption>Image generated by WorqHat ImageCon.</figcaption></figure><p>First, I’d recommend you to check out my deployed version to know what we are building: <a href="https://rag-article.vercel.app/">PDF chatbot (rag-article.vercel.app)</a></p><p>Make sure you upload a pdf that has selectable text. Also, the vercel plan I have only allows upto 10 seconds of a backend serverless function so AiConV3 might stop responding mid-way because of this limit. In any case, if you run this project locally then you won’t face any issues. <a href="https://github.com/anshulLuhsna/RAG-article/tree/main/Javascript">Repo link</a>.</p><p>Following is the response after I uploaded the same NextJS new features pdf:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y0FaFZaq72bJIjOOy3sdPw.png" /></figure><p><strong>Web developers</strong>, listen up, I HIGHLY recommend using Next.js and especially the Vercel AI SDK to integrate any chatbot into your website. They have literally thought about everything one could need in this process.</p><p>For example,</p><pre>const { messages, input, append, handleInputChange, handleSubmit } = useChat({<br>    onFinish: handleFinish,<br>    onResponse: handleFirstResponse,<br>    body: { extractedText: extractedText, model:props.model },<br>    credentials: credentials,<br>    headers: headers<br>  });</pre><p>useChat is a utility to allow you to easily create a conversational user interface for your chatbot application. It enables the <strong>streaming</strong> of chat messages from your AI provider, manages the state for chat input, and updates the UI automatically as new messages are received. You can read more about it in the <a href="https://sdk.vercel.ai/docs">Vercel AI SDK Docs</a>.</p><p>By default, this useChat hits the /api/chat route. Let us explore that next.</p><h4>/api/chat/custom_llm.ts</h4><pre>import { LLM, type BaseLLMParams } from &quot;@langchain/core/language_models/llms&quot;;<br>import type { CallbackManagerForLLMRun } from &quot;langchain/callbacks&quot;;<br>import { GenerationChunk } from &quot;langchain/schema&quot;;<br><br><br>export interface CustomLLMInput extends BaseLLMParams {<br>    <br>    apiKey: string;<br>  }<br>  <br>  export class CustomLLMV2 extends LLM {<br>    apiKey: string;<br>  <br>    constructor(fields: CustomLLMInput) {<br>      super(fields);<br>      this.apiKey = fields.apiKey;<br>    }<br>  <br>    _llmType(): string {<br>      return &quot;custom_llm&quot;;<br>    }<br>  <br><br>  <br>    async *_streamResponseChunks(<br>      prompt: string,<br>      options: this[&quot;ParsedCallOptions&quot;],<br>      runManager?: CallbackManagerForLLMRun<br>    ): AsyncGenerator&lt;GenerationChunk&gt; {<br>   <br>      <br>      const stream = await this.streamWorqHatAPI(prompt, options, runManager);<br>      for await (const chunk of stream) {<br>        yield chunk;<br>      }<br>    }<br>  <br>    private async *streamWorqHatAPI(<br>        prompt: string,<br>        options: this[&quot;ParsedCallOptions&quot;],<br>        runManager?: CallbackManagerForLLMRun<br>      ): AsyncGenerator&lt;GenerationChunk&gt; {<br>       <br>      <br>        // Extract message, context, and history using regular expressions<br>        const messageRegex = /question\s*:\s*(.*)/i;<br>        const contextRegex = /context\s*:\s*([\s\S]*)/i;<br>        const historyRegex = /history\s*:\s*(\[[\s\S]*?\])/i;<br>      <br>        const messageMatch = prompt.match(messageRegex);<br>        const contextMatch = prompt.match(contextRegex);<br>        const historyMatch = prompt.match(historyRegex);<br>      <br>        const message = messageMatch ? messageMatch[1].trim() : &quot;&quot;;<br>        const context = contextMatch ? contextMatch[1].trim() : &quot;&quot;;<br>        const historyString = historyMatch ? historyMatch[1].trim() : &quot;[]&quot;;<br>       <br>        const history = JSON.parse(historyString);<br>        <br>        const response = await fetch(&quot;https://api.worqhat.com/api/ai/content/v2&quot;, {<br>          method: &quot;POST&quot;,<br>          headers: {<br>            &quot;Content-Type&quot;: &quot;application/json&quot;,<br>            &quot;Authorization&quot;: `Bearer ${this.apiKey}`,<br>          },<br>          body: JSON.stringify({<br>            &quot;question&quot;: message,<br>            &quot;training_data&quot;: context,<br>            &quot;preserve_history&quot;: true,<br>            &quot;conversation_history&quot;: history,<br>            &quot;stream_data&quot;: true<br>          }),<br>        });<br>      <br>        if (!response.ok) {<br>          throw new Error(`HTTP error ${response.status}`);<br>        }<br>      <br>        const reader = response.body.getReader();<br>        let result = await reader.read();<br>        while (!result.done) {<br>          yield new GenerationChunk({<br>            text: new TextDecoder().decode(result.value),<br>          });<br>          await runManager?.handleLLMNewToken(new TextDecoder().decode(result.value));<br>          result = await reader.read();<br>        }<br>      }<br>  }</pre><h4>/api/chat/route.ts</h4><pre>import { StreamingTextResponse } from &#39;ai&#39;;<br>import { OpenAIEmbeddings } from &#39;@langchain/openai&#39;;<br>import { MemoryVectorStore } from &#39;langchain/vectorstores/memory&#39;;<br>import { RecursiveCharacterTextSplitter } from &#39;langchain/text_splitter&#39;;<br>import { CustomLLMV2 } from &#39;./custom_llmV2&#39;; <br>import { CustomLLMV3 } from &#39;./custom_llmV3&#39;;<br>import { PromptTemplate } from &quot;@langchain/core/prompts&quot;;<br><br><br>const llmV2 = new CustomLLMV2({<br>  apiKey: &quot;YOUR_API_KEY&quot;,<br>});<br>const llmV3 = new CustomLLMV3({<br>  apiKey: &quot;YOUR_API_KEY&quot;,<br>});<br>let vectorStore;<br>let context = &quot;&quot;<br>const promptTemplate = PromptTemplate.fromTemplate(`question : {message} \n\ncontext: {context}\n\n history: {messages}`)<br><br>export async function POST(req: Request) {<br>  const { messages, extractedText, model } = await req.json();<br>  <br>  let chain = null<br><br>  if(model === &quot;v2&quot;){<br>   <br>    chain = promptTemplate.pipe(llmV2)<br>  }<br>  else{<br><br>    chain = promptTemplate.pipe(llmV3)<br>  }<br>  const hasAssistantMessages = messages.some(message =&gt; message.role === &#39;assistant&#39;);<br><br>  if (!vectorStore || !hasAssistantMessages) {<br>    <br>    const textSplitter = new RecursiveCharacterTextSplitter({<br>      chunkSize: 2000,<br>      chunkOverlap: 200,<br>    });<br><br>    if (extractedText) {<br>      const docs = await textSplitter.createDocuments([extractedText]);<br>      vectorStore = await MemoryVectorStore.fromDocuments(docs, new OpenAIEmbeddings());<br>    } else {<br>      console.log(&#39;Extracted text is empty or null&#39;);<br>     <br>    }<br>  }<br><br>  const fixAssistantContent = (assistantMessage) =&gt; {<br>    if (assistantMessage.content) {<br>      const contentStrings = assistantMessage.content.match(/&quot;content&quot;:&quot;(.*?)&quot;/g);<br>      if (contentStrings) {<br>        const contents = contentStrings.map((str) =&gt; {<br>          const match = str.match(/&quot;content&quot;:&quot;(.*?)&quot;/);<br>          return match ? match[1] : null;<br>        });<br>        assistantMessage.content = contents.join(&#39;&#39;);<br>      }<br>    } else {<br>      console.log(&#39;assistantMessage.content is undefined&#39;);<br>    }<br>  };<br><br>  messages.forEach((message) =&gt; {<br>    if (message.role === &#39;assistant&#39;) {<br>      fixAssistantContent(message);<br>    }<br>  });<br><br>  const getLastUserQuestion = (messages) =&gt; {<br>    for (let i = messages.length - 1; i &gt;= 0; i--) {<br>      if (messages[i].role === &#39;user&#39;) {<br>        return messages[i].content;<br>      }<br>    }<br>    return null;<br>  };<br><br>  const lastUserQuestion = getLastUserQuestion(messages);<br><br>  if (vectorStore) {<br>    const searchResults = await vectorStore.similaritySearch(lastUserQuestion, 1);<br>   <br>    context = searchResults[0].pageContent<br>  } else {<br>    console.log(&#39;Vector store is not initialized&#39;);<br>  <br>  }<br><br>  try {<br>    <br><br>    const stream = await chain.stream({<br>      message: lastUserQuestion,<br>      context: context,<br>      messages: JSON.stringify(messages)<br>    });<br>   <br>    return new StreamingTextResponse(stream);<br>  } catch (error) {<br>    console.error(&#39;Error:&#39;, error.message);<br>    return new Response(&#39;Internal Server Error&#39;, { status: 500 });<br>  }<br>}</pre><p>We create a custom LLM class and import it into our main api route. Since we are creating a vector DB in the memory itself, it’s important to understand this task is time consuming and should only be done ONCE after the pdf doc is uploaded. And so we create the vector store ONLY if one doesn’t exist already or if the chat is reset.</p><p>Note: The streaming response from AiCon comes in the following string format:</p><pre>data: {&quot;content&quot;:&quot;Hello&quot;,&quot;model&quot;:&quot;aicon-v2&quot;,&quot;timestamp&quot;:1712961144288,&quot;processing_id&quot;:&quot;ec197cbb-bb92–43f3-a783-b04a8de2869c&quot;}</pre><p>Which does need some formatting on the client side.</p><p>I’ve shared the main backend and customLLM codes in this article itself. For a closer look at the frontend, have a peek at the entire code. As I mentioned before, the <a href="https://github.com/anshulLuhsna/RAG-article">entire repo</a> is open and free-to-use.</p><p>Thank you so much for reading and I hope you found it useful!</p><p>Written with ❤ by Anshul</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=46059c529f2d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/worqhat/retrieval-augmented-generation-rag-worqhat-aicon-langchain-46059c529f2d">Retrieval Augmented Generation (RAG) — Worqhat AiCon + Langchain</a> was originally published in <a href="https://medium.com/worqhat">WorqHat</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>