<?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 Priyansh on Medium]]></title>
        <description><![CDATA[Stories by Priyansh on Medium]]></description>
        <link>https://medium.com/@priyansh1990_60788?source=rss-9277fb2fcf78------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*KNx92QhixbXXC61xomcMsA.jpeg</url>
            <title>Stories by Priyansh on Medium</title>
            <link>https://medium.com/@priyansh1990_60788?source=rss-9277fb2fcf78------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 16:54:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@priyansh1990_60788/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[How the map is learned]]></title>
            <link>https://medium.com/@priyansh1990_60788/how-the-map-is-learned-e984215e97c1?source=rss-9277fb2fcf78------2</link>
            <guid isPermaLink="false">https://medium.com/p/e984215e97c1</guid>
            <category><![CDATA[nlp-training]]></category>
            <dc:creator><![CDATA[Priyansh]]></dc:creator>
            <pubDate>Sun, 31 May 2026 05:38:41 GMT</pubDate>
            <atom:updated>2026-05-31T05:38:41.253Z</atom:updated>
            <content:encoded><![CDATA[<p><em>The chicken-and-egg problem at the heart of every embedding model — and the trick that solves it. A follow-up to </em><a href="https://markdownlivepreview.com/02-vectors-cosine-and-the-map-versioning-trap.md"><em>“Vectors, cosine, and the map-versioning trap.”</em></a></p><p>In the previous article I told you, fairly casually, that an embedding model is a neural network with millions of knobs that get tweaked during <em>training</em> until similar sentences end up with similar vectors. I said this in two sentences and moved on.</p><p>That description has a hole in it big enough to drive a truck through.</p><p>Think about it. To “tweak the knobs until similar sentences end up nearby,” somebody has to <em>know which sentences are similar</em>. But that’s the entire problem we’re trying to solve! If we already had a list of every pair of similar sentences in English, we wouldn’t need an embedding model — we’d just use the list. The whole point of training is to <em>learn</em> what similarity means.</p><p>So how does training actually work? You can’t directly tell the model <em>“make ‘cat’ close to ‘feline’”</em> — there are millions of words and effectively infinite sentences. You can’t hand-label every pair. And yet somehow this exact training process happens, every time someone releases a new embedding model, and it works.</p><p>The trick is one of the most beautiful ideas in machine learning. I want to walk you through it carefully, because once you see it, you’ll see it everywhere — including, when we get to it, inside ChatGPT.</p><h3>The chicken-and-egg problem</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*guWBQ5hJPCetve9hYuUbtQ.png" /></figure><p>Let’s get the constraint into sharp focus first. We want to train a model that takes text and produces a vector such that <em>similar meanings → similar vectors</em>. We have a giant pile of text — say, every Wikipedia article, every Reddit post, every news article scraped from the open internet. Billions of sentences. Nobody has labeled any of them.</p><p>We can’t tell the model what “similar” means. The whole problem is that “similar” is what we want it to figure out.</p><p>We have to find some signal that’s <em>already inside the data</em> — some pattern the text itself contains that, if the model learns to predict that pattern, it’ll <em>accidentally</em> learn what similar meaning looks like along the way.</p><p>This is the move. The whole field rests on this move. It’s called a proxy task.</p><h3>The proxy task</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_0sMy8pt4Y536_KLCCYBVw.png" /></figure><p>A proxy task is a fake objective you give the model. The fake objective doesn’t directly say “learn embeddings.” It says “predict this thing.” But the only way to do well at predicting <em>that</em> thing is to <em>understand the meaning</em> of the input — and the model’s internal representations of meaning, the vectors it computes along the way, become useful for everything else as a side effect.</p><p>Here’s the key insight: language has structure that gives away meaning for free.</p><p>Words that mean similar things tend to appear in similar contexts. <em>“The cat drank the milk”</em> and <em>“The kitten lapped at the milk”</em> are different sentences with different words, but the <em>roles the words play</em> and <em>what tends to come before and after them</em> overlap heavily. Every English speaker knows, without anyone telling them, that <em>cat</em> and <em>kitten</em> belong to roughly the same neighborhood of meaning — because we’ve all heard them in similar contexts thousands of times.</p><p>This is the signal. Distribute the words of your language by context, and you’ve discovered meaning, even though “meaning” was never explicitly labeled. The technical name for this principle is the distributional hypothesis — the idea that you can know a word “by the company it keeps” — but you don’t need the term. You just need the move.</p><p>So the proxy task that an embedding model gets trained on is some version of: <em>predict what’s missing from a piece of text using only the surrounding context.</em> If the model can do that well, it must have learned what each word <em>means</em>, because predicting requires understanding.</p><p>Let me make this concrete with the original example: word2vec.</p><h3>How word2vec actually does it</h3><p>Word2vec is the cleanest possible expression of this idea. Forget transformers and modern embedding models for a minute. Imagine the simplest neural network you can: an input layer, one hidden layer in the middle, and an output layer. It’s barely a “deep” network at all. The hidden layer has some chosen number of neurons — let’s say 300. Those 300 numbers will become the embedding.</p><p>Now we play the following game.</p><p>I’ll take a sentence from my training data:</p><blockquote>“The fluffy cat curled up on the warm windowsill.”</blockquote><p>I’ll pick one word — say, <em>“cat”</em> — and remove it. The model’s job is: given the surrounding words <em>“the fluffy ___ curled up on the warm windowsill,”</em> predict the missing word from the entire vocabulary of English (~50,000 candidates).</p><p>The model produces a probability for each candidate word. The right answer is <em>“cat,”</em> so we compare the model’s prediction to <em>“cat”</em> and measure how wrong it was. Then we do the math that says <em>“if you nudge each of these knobs slightly in this direction, you’d be slightly less wrong next time”</em> — that’s called backpropagation, the engine that makes neural networks learnable. We nudge the knobs. We move on to the next sentence.</p><p>We do this billions of times.</p><p>Here’s the magic trick, and it’s worth slowing down for. The model has <em>no idea</em> what cats or windowsills are. It’s just a lump of math trying to minimize a number. But to be good at this prediction game, it has no choice but to develop a particular kind of internal representation: words that appear in similar contexts have to produce similar internal patterns, because if they didn’t, the model would systematically fail on whichever one it had under-represented.</p><p>After billions of training examples, the network’s middle layer settles into a configuration where:</p><ul><li><em>cat</em>, <em>kitten</em>, <em>feline</em> — all appearing in similar contexts (curled up, purred, meowed) — get <em>similar 300-number patterns</em>.</li><li><em>cat</em>, <em>spreadsheet</em>, <em>photosynthesis</em> — appearing in wildly different contexts — get <em>very different 300-number patterns</em>.</li></ul><p>We never trained for that directly. We trained for “predict the missing word.” The geography of meaning emerged as a side effect.</p><p>Once training is done, we throw away the prediction part of the network entirely. We don’t care about it. What we want is the middle layer — the 300-number representations the network learned for each word along the way. <em>Those</em> are the embeddings. The model that predicts the missing word was just scaffolding to force the geometry into existence.</p><p>That’s the entire trick. That’s word2vec. (Footnote: there’s a complementary version, called <em>Skip-gram</em>, that flips the task — given the center word, predict the context words around it. Same idea in mirror image.)</p><h3>What’s still wrong with word2vec, and how the field fixed it</h3><p>The word2vec scheme works, but it has one obvious limitation that I touched on briefly in article 02. It produces <em>one vector per word</em>. That means <em>bat</em> in <em>“swing the bat”</em> and <em>bat</em> in <em>“the bat flew through the window”</em> get the exact same vector. The model has no way to use the surrounding context to disambiguate, because the embedding is a fixed lookup-table entry — not a function of the sentence.</p><p>Fixing this took five years and a different architecture. Starting with ELMo (2018) and especially BERT (2019), models started producing <em>context-sensitive</em> embeddings. Now when you embed <em>bat</em> inside <em>“swing the bat,”</em> the surrounding words flow through layers of math (the famous <em>transformer</em> layers, which we’ll meet properly in the next article) and pull the <em>bat</em> vector toward the “baseball equipment” neighborhood of the map. Embed <em>bat</em> inside <em>“the bat flew at night”</em> and the same model pulls the vector toward the “flying mammal” neighborhood instead.</p><p>But the underlying training trick — the proxy task — barely changed. BERT’s training task is essentially <em>“hide a random word in the sentence, predict it from the rest.”</em> It’s word2vec’s idea, scaled up to a more powerful architecture and applied across whole sentences instead of fixed-window contexts.</p><p>Modern <em>sentence</em> embedding models (the MiniLM, BGE, E5 family we keep mentioning) take it one step further. They’re typically built on a BERT-style backbone and then fine-tuned with a <em>different</em> proxy task, called contrastive learning.</p><h3>Contrastive learning, the modern version</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lP49zSX-or4STw-f88HFzg.png" /></figure><p>Once you have a backbone model that can produce vectors from text, and you want it to be good specifically at <em>retrieval</em> — making queries land near their answer documents — you train it with a more direct signal. You collect <em>triples</em>:</p><ul><li>An <em>anchor</em> — for example, a question.</li><li>A <em>positive</em> — a known correct answer, or a paraphrase of the anchor.</li><li>A <em>negative</em> — a random unrelated piece of text.</li></ul><p>You run all three through the model. You get three vectors. The training loss says: <em>“the anchor’s vector should be closer to the positive’s vector than to the negative’s vector.”</em> Then you nudge the knobs. Repeat over millions of triples.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xvxP8jBv5WiXxXl6fF5d7w.png" /></figure><p>Where do the triples come from? Cleverness. Stack Overflow titles paired with the accepted answer. Reddit titles paired with the body of the post. Wikipedia paragraphs paired with paraphrases. Search query logs paired with clicked results. Every clever data source ends up being someone-else’s-labels-without-anyone-having-to-label-anything, which is the recurring flavor of “self-supervised learning.” Same proxy-task move, applied at the sentence level instead of the word level.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-_C6CUSRpp0QS74gS0l0Mg.png" /></figure><p>This is why modern embedding models are <em>better</em> at retrieval than word2vec ever was: they were trained on a task much closer to the one you’re going to use them for. Word2vec was trained on “predict the missing word.” Modern retrieval embeddings are trained on “make queries closer to their answers.” The closer the proxy task is to the real task, the better the resulting geometry.</p><h3>Why this matters for everything else</h3><p>The proxy-task move isn’t just an embeddings trick. Once you internalize it, you start to recognize it as the engine driving most of modern AI.</p><ul><li>Image embeddings are trained on tasks like <em>“given a damaged version of this image, restore it”</em> — and the internal representations end up encoding what the image is <em>about</em>.</li><li>Speech embeddings are trained on <em>“given audio with a chunk masked out, predict the chunk.”</em> Same idea, audio domain.</li><li>Large language models like GPT-4 and Claude are trained on <em>one and exactly one</em> proxy task: <em>“given everything you’ve seen so far, predict the next token.”</em> That’s it. From that single objective, they learn grammar, facts, reasoning, style, code, math — all as side effects of getting good at next-word prediction.</li></ul><p>That last bullet is the punchline of this whole article, and it’s where we’ll pick up next time. The reason ChatGPT can answer your question, write code, summarize a document, and pretend to be a pirate is that it was trained on the same kind of proxy-task move that word2vec was — just with a different proxy and a thousand times more knobs.</p><p>The setup is identical. <em>Define a fake task that requires understanding to solve. Throw enough data and compute at it. The understanding shows up as a side effect.</em> Word2vec solved this for words. BERT solved it for words-in-context. Sentence-transformers solved it for sentences. GPT-style LLMs solved it for <em>everything</em>.</p><h3>Where this leaves you</h3><p>Three things to take away.</p><ol><li>Embedding models can’t be trained on “make these similar” directly. The whole field is built on a proxy task: predict the missing word, or distinguish related from unrelated pairs. Geometry emerges as a side effect of doing that task well.</li><li>Word2vec is the historical proof-of-concept; the modern equivalent is contrastive learning on top of transformer backbones. The scaffolding got more sophisticated, but the move is the same.</li><li>The same trick — proxy task → emergent capability — is what makes large language models possible. That’s our next article.</li></ol><p>If you understood this one, you understand the <em>creation</em> of the map, not just its shape and use. That’s the deepest of the three layers. Most working engineers in this field never sit down and ask themselves how the geography came to be in the first place. Now you have.</p><p>Next up: how that same idea, scaled to absurd sizes, becomes ChatGPT.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e984215e97c1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vectors, cosine, and the map-versioning trap]]></title>
            <link>https://medium.com/@priyansh1990_60788/vectors-cosine-and-the-map-versioning-trap-d27797f9705b?source=rss-9277fb2fcf78------2</link>
            <guid isPermaLink="false">https://medium.com/p/d27797f9705b</guid>
            <category><![CDATA[embedding]]></category>
            <category><![CDATA[word2vec]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Priyansh]]></dc:creator>
            <pubDate>Sun, 24 May 2026 19:45:20 GMT</pubDate>
            <atom:updated>2026-05-31T03:32:46.742Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Three things about embeddings that nobody explains until you trip over them — a follow-up to “</em><a href="https://medium.com/@priyansh1990_60788/what-an-embedding-is-and-why-it-might-be-the-most-important-idea-in-modern-ai-09d5bb3e12cb">What an embedding is, and why it might be the most important idea in modern AI</a><em>.”</em></p><p>In the first article, I told you that an embedding is a pin on a giant invisible map of meaning. Two pieces of text with similar meaning land near each other on the map. That’s the whole trick.</p><p>If that’s all you ever know about embeddings, you’ll do fine. You’ll understand why search feels smarter, why “people who liked this also liked…” works, and why every AI feature ships an embedding step somewhere.</p><p>But the moment you actually <em>build</em> something with embeddings — or even just have a deeper conversation with someone who has — three questions show up. They sound technical, but they’re not really. They’re the kind of “wait, but how does that actually work” questions that change your mental model from <em>cute analogy</em> to <em>thing I understand</em>.</p><p>These are the three.</p><ol><li>The “pin on a map” is actually a vector. What does that mean?</li><li>When we say two pins are “close,” we measure the angle between them, not the straight-line distance. Why?</li><li>Every embedding model draws its own map. Two maps from two models can’t be combined. Why not, and what does that ruin?</li></ol><h3>The pin is a vector — and that word matters less than you think</h3><p>A vector is just a list of numbers in a specific order. That’s it. Not a metaphor, not jargon, not a mathematical mystery. If I write [3, 1, 4], I&#39;ve written a 3-dimensional vector. If I write a list of 768 numbers, I&#39;ve written a 768-dimensional vector.</p><p>When you embed a sentence, the model gives you back a vector. For a typical embedding model that’s a list of somewhere between 384 and 1,536 numbers. Each number is one <em>coordinate</em> in the meaning map.</p><p>In our 2D map analogy, every pin had two coordinates: how far across (left-to-right) and how far up (down-to-up). To place a pin you needed two numbers. A real embedding pin needs <em>hundreds</em> of coordinates because the map isn’t 2D — it has hundreds of dimensions, one per number in the vector.</p><p>We can’t visualize a 768-dimensional space. Nobody can. But here’s the move that makes everything still work: we don’t need to visualize it. We only need to measure distances and directions in it. Distances and directions in 2D, 3D, or 768D follow the same rules. The math is identical. The intuition you have for “near” and “far” on a paper map carries straight over to a 768-dim map, even though your eyes can’t follow it.</p><p>So: vector = list of numbers = position of a pin on a high-dimensional map. Whenever someone says “we vectorize the input,” they mean “we turn it into one of those lists of numbers.”</p><p>That’s the whole word. You can use it now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EyHpgt1sXsLKFtns6Zc4Og.png" /></figure><h3>Sidebar — but how does “cat” actually become a list of numbers?</h3><p>I want to head off a thing that confused me for a while.</p><p>There is no spreadsheet somewhere that says <em>“cat = [0.21, -0.34, 0.07, …]”</em> — written down by a human. That would be impossible. There are millions of words and an infinite number of sentences. Nobody hand-coded these vectors.</p><p>Instead, the embedding model is a neural network — a giant tunable function with millions or billions of internal knobs (called <em>weights</em>). You feed text in; numbers come out. Same text in always produces the same numbers out. Different text in produces different numbers. The function is fixed once the model is trained — it doesn’t change between your queries.</p><p>Here’s roughly what happens when you ask a model to embed <em>“the cat sat on the mat”</em>:</p><ol><li>The text is chopped into tokens — small pieces, roughly word-sized but not always. “cat” is usually one token; “photosynthesis” might split into two or three.</li><li>Each token is looked up in a vocabulary table. This part <em>is</em> a small dictionary lookup — the model ships with a fixed vocabulary of (say) 50,000 tokens, and each token has a <em>starting</em> vector. This is the only step that resembles “look up the vector for cat.”</li><li>The starting vectors get passed through layers of math — dozens of layers, each reshaping the vectors based on the surrounding context. So the vector that comes out for <em>cat</em> in <em>“the cat sat on the mat”</em> is <em>not</em> the same as the one for <em>cat</em> in <em>“the cat 5 hurricane hit the coast”</em> — the surrounding words bleed into each token as the layers process them.</li><li>A final vector pops out — usually one per sentence (for retrieval models like the ones we’ve been talking about), or one per token (for word-level uses).</li></ol><p>The reason any of this <em>means</em> anything — the reason “cat sat on the mat” and “feline rested on the rug” produce nearby vectors — is that during training, those millions of knobs were tweaked. The model was shown billions of pairs of texts and told <em>“these two should produce nearby vectors; these two should produce far-apart vectors.”</em> Over many adjustments, the knobs settled into a configuration where the math, applied to text input, produces a useful map.</p><p>There’s no human-written rule mapping words to numbers anywhere in this system. The mapping is a side effect of the training process. The model <em>is</em> the mapping.</p><p>While we’re here: the number of dimensions (384, 768, 1536, etc.) is a <em>design choice</em>, not a property of language. The person training the model picks it before training starts. Smaller → cheaper to store and faster to query, but less capacity to express subtle distinctions. Larger → more expressive, but everything costs more. Models are typically released in size tiers (small, base, large) so you can pick the trade-off that fits your project. Nothing in the universe says meaning needs 768 axes — it’s just an engineering choice that empirically works well.</p><h3>Sidebar — wait, isn’t this just word2vec?</h3><p>You may have heard of word2vec. It comes up a lot in any “embeddings explainer.” Worth being clear: word2vec is the <em>idea’s grandfather</em>, not what runs in modern systems.</p><p>So: when this article and the previous one talked about “embeddings,” I was <em>not</em> talking about word2vec. I was talking about transformer-based sentence encoders, the great-grand-descendants of word2vec. Word2vec was the proof that the idea works at all. The mental model — <em>text → neural network → vector</em> — has stayed the same the whole decade. The architectures got dramatically better.</p><p>If you’ve heard the word “transformer” in the same breath as ChatGPT, you’re hearing it for the same reason. Modern embedding models and modern LLMs are cousins; both are transformer-based neural networks. They were trained for different jobs, but they share an architecture and a lineage. We’ll come back to that in the next article.</p><h3>Why cosine, and not a ruler</h3><p>This is the question that broke me when I first ran into it. <em>If meaning is a place on a map, and we want to know if two pins are close, why don’t we just measure the straight-line distance between them, like with a ruler?</em></p><p>We could. But we don’t. The standard tool for embeddings is cosine similarity, which measures the angle between two vectors as seen from the <em>origin</em> of the map (the center, where everything starts).</p><p>Picture every pin with an invisible string tied to it, and the other end of the string tied to the center of the map. Now look at the two strings for two different sentences. Do they point in the same direction? Or do they point in completely different directions? Cosine similarity is “how parallel are these two strings?” Strings pointing the same way → similarity ≈ 1. Strings at right angles → similarity ≈ 0. Strings pointing opposite ways → similarity ≈ −1.</p><p>A subtle point that trips people up: <em>all</em> the strings start at the same hub, but they fan out in different directions — like spokes on a wheel. Sharing a starting point doesn’t make two strings parallel. Two spokes going to neighboring points on the rim are nearly parallel (high cosine). Two spokes going to opposite sides of the wheel point in opposite directions (cosine -1). Two spokes that meet at right angles on the rim are perpendicular (cosine 0). It’s the <em>direction</em> the spoke points, not the fact that they share a hub, that we’re measuring.</p><p>Why is that better than a ruler? One reason. Here it is in a single example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sReN95v0KdpQm_G-qJMGTw.png" /></figure><p>Consider these two sentences:</p><ul><li><em>“The cat sat on the mat.”</em></li><li><em>“The cat, in a moment of profound contemplation, settled herself gently upon the mat that lay across the floor of the parlour.”</em></li></ul><p>Same meaning. Wildly different lengths and styles. When you embed them, both pins should land in the same general <em>direction</em> from the center of the map (because the meaning is the same). But the longer, more elaborate sentence may produce a vector with slightly larger magnitudes — a pin that sits a little <em>further out</em> from the center than the short version.</p><p>If you used a ruler, the long sentence would look “further away” from the short one, even though they mean the same thing — because you’d be measuring the gap created by <em>length</em>, not by <em>meaning</em>. Cosine similarity doesn’t care about length. It only cares about direction. Both pins point the same way from the origin → both pins are saying the same thing, and the similarity score will be near 1.</p><p>The slogan that finally made it click for me: meaning has a direction, not a length.</p><p>There’s a beautiful side effect. Most modern embedding models <em>normalize</em> their output — they rescale every vector to have length 1, putting all the pins on the surface of a giant sphere. Once everyone’s on the sphere, the question “how far apart are two pins?” and “what’s the angle between them?” become the same question. Mathematically identical. So when you see code that uses a “dot product” instead of a cosine — that’s not a different operation, it’s the same answer arrived at faster.</p><p>(For images, where a brighter version of a photo really does mean something different than a darker one, length carries signal and people sometimes use straight-line distance. For text, where length is mostly stylistic noise, cosine wins.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bhnk2Gv3_fY5oyowOQGP3g.png" /></figure><h3>Two maps from two models do not combine</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lfuW24GeNdD9Wa2fD_0czQ.png" /></figure><p>Here’s the gotcha that ruins more weekend projects than any other.</p><p>There is no <em>universal</em> embedding map. Every embedding model draws its own. When OpenAI trains its embedding model, it ends up with a particular map — a particular geography of where each meaning lives. When Google trains <em>its</em> embedding model, on different data with different training tricks, it ends up with a <em>different</em> map. The two maps both have the property that “similar meanings end up near each other,” but the actual coordinates are completely different. A sentence that lands at position [0.21, -0.34, 0.07, …] on OpenAI’s map might land at position [-0.55, 0.18, 0.92, …] on Google’s map. The two coordinate systems share <em>nothing</em>. They’re not just rotated or scaled versions of each other; they’re entirely separate maps.</p><p>This sounds abstract until it bites you. Here’s what it means in practice.</p><p>You cannot mix embedding vectors from different models. If you embedded a million documents with OpenAI’s model two years ago, and then today you embed a user’s question with a different model — even a “newer, better” one from the same provider — and you measure the cosine between the question and the documents, you will get <em>garbage</em>. Not “slightly worse than ideal” garbage. Random-noise garbage. The math runs without complaining. The numbers come out. The system feels like it’s working. But the results are nonsense, because you’re comparing pins from two different maps as if they were on the same one.</p><p>You cannot upgrade an embedding model without re-embedding everything. A new model, even from the same family, draws a new map. To use the new model, you have to re-run every document you’ve ever embedded through it, replace all the old pins with new pins on the new map, and only <em>then</em> can you embed queries with the new model and trust the results. For a small project that’s an afternoon. For a system with billions of vectors it’s an engineering project.</p><p>Two systems that don’t share an embedding model can’t share a search index. If your team built a vector store for product descriptions and another team built one for customer reviews using a different model, those two stores are not interoperable. You can’t run a query against both at once. They’ll happily return results, but the rankings will be meaningless — you’d be combining cosine scores measured in <em>different metric spaces</em>, which is the polite mathematical way of saying “don’t.”</p><p>The rule is simple, and it’s the single most important practical fact about embeddings: you must use the same model for everything that needs to be compared. Same model for indexing your documents. Same model for embedding the user’s query. If a vendor releases a new model, that’s not an upgrade — it’s a migration.</p><h3>Why this is the way the world is</h3><p>You might be asking: <em>couldn’t someone just train one model that everyone uses?</em> In a sense, yes — there are widely-shared open models that get reused across projects, and that is the closest thing to a universal map we have.</p><p>But fundamentally, the geography of the map is <em>learned</em>, not designed. Two models trained on different data, different objectives, or even just different random starting points will arrive at differently-organized maps. They both work, internally, but they work in different coordinate systems for the same reason that two cities can both have a “downtown” without having any agreement on which street is named what.</p><p>The map is a property of the model. The model <em>is</em> the map.</p><h3>What to take away</h3><p>Three things, the same three:</p><ol><li>A pin is a vector — a list of numbers, one per dimension of the map. Calling it a vector instead of a pin doesn’t change anything about how it works.</li><li>We measure the angle between vectors (cosine), not the ruler distance. Meaning has a direction, not a length, and the angle is what survives variations in style and length.</li><li>Every embedding model is its own map. Don’t mix vectors across models. Don’t upgrade without re-embedding. It’s the most common and most expensive mistake you can make with this technology.</li></ol><p>If you understood the first article, you understood the <em>idea</em>. If you understood this one, you understand the <em>thing</em> — enough to spot a real bug in someone’s vector-search system, enough to ask the right question when a vendor announces a new embedding model, enough to know why an embedding-based feature you tried to build at home didn’t behave the way you expected.</p><p>Next up: how the very same “embedding” idea shows up <em>inside</em> large language models, and what tokens really are. Different map, same trick.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d27797f9705b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What an embedding is, and why it might be the most important idea in modern AI]]></title>
            <link>https://medium.com/@priyansh1990_60788/what-an-embedding-is-and-why-it-might-be-the-most-important-idea-in-modern-ai-09d5bb3e12cb?source=rss-9277fb2fcf78------2</link>
            <guid isPermaLink="false">https://medium.com/p/09d5bb3e12cb</guid>
            <category><![CDATA[word-embeddings]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Priyansh]]></dc:creator>
            <pubDate>Sat, 23 May 2026 19:35:56 GMT</pubDate>
            <atom:updated>2026-05-31T03:25:16.699Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A 10-minute tour of the trick that powers smart search, AI memory, and “people who liked this also liked…”</em></p><p>A few weeks ago I tried to find a movie. I couldn’t remember the title. I typed into Google something like <em>“that film where a guy keeps reliving the same day until he becomes a better person.”</em></p><p>Google handed me the Wikipedia page for <em>Groundhog Day</em> in a fraction of a second. I’d used none of the words from the title, the cast, the director, the plot summary — and the search still worked.</p><p>I’d seen this happen a thousand times before. But that day I stopped and asked: <em>how does it actually do that?</em></p><p>The answer is a single idea that, once you see it, you can’t unsee. It’s the engine behind almost every “smart” feature you’ve ever used — Spotify’s recommendations, Gmail’s autocomplete, ChatGPT’s memory of what you said three messages ago, Google Photos finding every picture of your dog without you ever tagging one. They all share the same trick.</p><p>It’s called an embedding. Let me show you what it is.</p><h3>Computers don’t understand meaning. So how do they?</h3><p>A computer, deep down, only understands numbers. If you ask it, <em>“are these two sentences saying the same thing?”</em>, it has nothing to work with. To a computer, “the cat sat on the mat” and “a feline rested on the rug” share zero letters, zero words, zero anything. They look as related as “the cat sat on the mat” and “quarterly revenue rose 12%.”</p><p>For decades, the way around this was to get really good at comparing the <em>words themselves</em>. Search engines counted overlapping words, weighted by how rare each word was. It worked, kind of. It’s what got us through the 2000s. But it has a fatal flaw: if you don’t share words with the document, you don’t find the document. Period. You have to type “Groundhog Day” or “Bill Murray” or “comedy 1993” — words that actually appear on the page.</p><p>The breakthrough was a question: <em>what if we stop comparing the words, and start comparing the meaning?</em></p><p>That sounds nice. It also sounds impossible. Meaning isn’t a thing a computer can hold.</p><p>The trick is: turn meaning into a place.</p><h3>The map</h3><p>Imagine a giant, invisible map.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XHrRZdvJZeuvRq6QNqpq5A.png" /></figure><p>Every sentence anyone has ever written gets a pin on this map. The position of the pin doesn’t depend on the <em>words</em> in the sentence — it depends on the <em>meaning</em>. Sentences that mean similar things get pinned close together. Sentences about totally different topics get pinned far apart.</p><p>Picture a small corner of this map. There are two pins right next to each other:</p><blockquote>“The cat sat on the mat”<em> </em>“A feline rested on the rug”</blockquote><p>Same meaning, no shared words. They land in the same neighborhood.</p><p>And way off in the distance, in a totally different region of the map, sits another pin:</p><blockquote>“Quarterly revenue rose 12%”</blockquote><p>Different topic, different neighborhood, far away.</p><p>That’s it. That’s the whole trick.</p><p>If you want to find sentences that mean what you mean, you don’t have to compare words at all. You drop your sentence onto the map, look around, and grab the closest pins. They’ll mean what you meant — even if they share no words with you.</p><p>The fancy name for “where the pin lands on the map” is an embedding. The map itself is sometimes called an “embedding space.” When someone says <em>“we embedded the document,”</em> they mean: we figured out where on the map this document goes.</p><p>The only sleight of hand is that the map isn’t 2D. A real embedding map has hundreds of dimensions — usually 384, 768, or 1,536. We can’t picture that, but the math doesn’t care. The same idea applies: the position of each pin is a list of numbers (one per dimension), and “close on the map” means “the lists of numbers are similar.”</p><p>So when I tell you that an embedding is “just a list of 384 numbers,” that’s true. It’s also where every great AI feature of the last five years comes from.</p><h3>Watching it work, end to end</h3><p>Let me walk you through what actually happens when I do that Groundhog Day search.</p><p>Sunday, 9:47 PM. I open Google and type:</p><blockquote>“that film where a guy keeps reliving the same day until he becomes a better person”</blockquote><p>I hit enter. Less than half a second later, the <em>Groundhog Day</em> Wikipedia page is the top result. Here is the entire journey, in slow motion.</p><p>Step 1 — My query becomes a pin.</p><p>Google takes the sentence I typed and feeds it into an embedding model — a piece of software whose only job in life is to look at text and output its position on the map. Out comes a list of (let’s say) 768 numbers. My typed query now has coordinates. It is a pin.</p><p>Step 2 — Google already has a map full of pins.</p><p>This is the part most people don’t realize: the map wasn’t built when I hit enter. It was built <em>over the past decade</em>, every time Google’s crawlers indexed a page on the internet. Every Wikipedia article, every blog post, every Reddit thread Google has ever crawled was passed through the <em>same</em> embedding model and got a pin of its own. Billions of pins, sitting on a giant invisible map, waiting.</p><p>The pin for the <em>Groundhog Day</em> Wikipedia page was placed there long before I ever typed my query. It came from the page’s actual text — sentences like <em>“Phil, a cynical TV weatherman, finds himself inexplicably reliving February 2nd.”</em></p><p>Notice: the page does not contain the words “guy who keeps reliving” or “becomes a better person.” There is essentially zero word overlap with what I typed. A keyword-only search would have failed.</p><p>Step 3 — Google grabs the nearest pins.</p><p>Now Google does the only operation that actually matters: <em>given my query’s pin, which other pins on this map are closest?</em> It checks the angle between my pin and the pins of all the candidate pages, sorts by closeness, and grabs the top dozen.</p><p>The <em>Groundhog Day</em> Wikipedia pin and my query’s pin are right next to each other — because the model that made both of them was specifically trained so that “guy keeps reliving the same day” and “weatherman inexplicably reliving February 2nd” land in the same neighborhood. Different words, same meaning, same place.</p><p>Step 4 — I click the result. Everyone moves on.</p><p>That’s the whole thing. The reason it feels like Google understood me is because, in a literal geometric sense, my words and the page’s words ended up next to each other on a map of meaning that Google had been quietly drawing for years.</p><p>The same model has to be used at indexing time and at query time — that’s the trick that makes my pin and the page’s pin comparable in the first place. Use a different model for queries than you used for the pages, and they end up on different maps that don’t talk to each other.</p><p>It works because the model was <em>forced</em> to learn the geography. During training, you show it thousands of pairs of sentences and tell it: “these two should land in the same neighborhood.” Then thousands of pairs that should land far apart. The model adjusts itself, billions of tiny dials at a time, until it gets the map right. After that, every new sentence it sees just gets a pin dropped on the map it already knows.</p><p>Once the geography is right, <em>meaning has become a place</em>. And places are something a computer can absolutely work with.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HbC-o7W7YkLBG05Q18f3hA.png" /></figure><h3>The catch: every map is its own map</h3><p>I’ve been saying “the map” as if there’s one. There isn’t.</p><p>There’s a different map for every embedding model. The pin Model A places on “the cat sat on the mat” is <em>not</em> the same pin Model B places on the same sentence. Different numbers, different dimensions, different geography. A vector produced by one model is, to another model, gibberish.</p><p>This sounds academic until you live with it. The consequences are very real:</p><ul><li>Upgrade your embedding model and you redraw the entire map. Every document you’ve ever indexed has to be re-embedded from scratch. There’s no “convert” function — the new model’s geography simply isn’t the old one. For a company with billions of documents, that’s a serious project, not an afternoon’s work.</li><li>You can’t mix vectors from different sources. If your search system uses Model A and you want to add documents from a partner using Model B, you don’t get to merge the maps. Someone has to re-embed everything onto a single map first.</li><li>The intelligence of a system is locked to whoever drew its map. If a much better model comes out tomorrow, you can’t take advantage of it without redoing the work.</li></ul><p>This is one quiet reason production AI systems are conservative about which model they pick. The map you draw today is the map you live on for a while.</p><h3>What an embedding is not</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p-EYk9E_sLNKnDUmdv-53Q.png" /></figure><p>Three quick myth-busts, because the word “embedding” gets thrown around loosely.</p><p>It is not a hash. A hash function turns input into a fingerprint, where the smallest change to the input produces a <em>completely different</em> output — that’s its whole point. Embeddings are the opposite: small changes to the input produce small changes to the output. Change one word in your sentence and the pin nudges. Rephrase the whole sentence with no overlap and the pin stays in roughly the same place.</p><p>It is not a summary. You cannot reverse-engineer a sentence from its embedding. The vector captures the <em>shape</em> of the meaning, not the surface text. An embedding tells you “this is in the neighborhood of cooking-related ideas” but not “the original sentence was about pasta.”</p><p>It is not magic. Every embedding model has been trained on a specific kind of text — usually English, usually written in the last decade or two, usually skewed toward Wikipedia, news, and Reddit. Drop in a 19th-century legal contract or a sentence in Swahili and the geography breaks down. The map only knows the world it was shown.</p><h3>You’ve already used this, today, probably twice</h3><p>The reason this idea is everywhere is that “find things that mean the same as this thing” turns out to be <em>the</em> useful primitive in modern software. Once you have it, products fall out of it.</p><ul><li>Spotify’s recommendations. Every song has a pin. Songs you like cluster together. The next song in your discover queue is a pin near the cluster of songs you’ve loved.</li><li>Google Photos finding every picture of your dog. Every image has a pin in a different kind of map (image embeddings, same idea different inputs). Your query “show me my dog” lands somewhere in that map; nearby pins are the photos you want.</li><li>The Gmail autocomplete that finishes your sentence. It’s looking for emails — yours and millions of others — whose meaning is near the meaning of what you’ve typed so far.</li><li>ChatGPT remembering what you said earlier in the conversation. When the conversation gets long, it can’t reread everything. So it embeds each part and looks up the parts whose pins are nearest your latest message.</li><li>The “smart” search box on Notion, Slack, Linear, your company’s internal tools. Not keyword matching. Meaning matching.</li></ul><p>It’s one trick. It’s <em>everywhere</em>.</p><h3>The bit that surprised me</h3><p>Here’s the thing I didn’t expect, the thing that made me write this article instead of just nodding and moving on.</p><p>The map is <em>the</em> product. Once you have a good embedding model, you don’t have separate machinery for “search” and “recommendations” and “AI memory” and “duplicate detection” and “spam filtering” and “anomaly detection.” You have one operation — <em>find pins close to this pin</em> — and you assemble all of those features by asking that one question with different inputs.</p><p>Search? “Find documents whose pin is near my query’s pin.”</p><p>Recommendations? “Find products whose pin is near the average of pins this user has liked.”</p><p>Spam filtering? “Find emails whose pin is near known-spam pins.”</p><p>It’s not that each of these problems happens to be solvable with embeddings. It’s that, in a real sense, they are the same problem in different costumes, and we just didn’t see it until the map showed up.</p><p>That’s the part of this idea I keep finding more beautiful the longer I sit with it. We didn’t invent five different machine-learning techniques. We invented one — <em>meaning has a geometry</em> — and it wore enough different costumes for us to think it was five.</p><h3>So where does that leave you</h3><p>If you take only one thing away: when you next see something “smart” — a recommendation, a search result that feels uncannily right, an AI that remembers what you said an hour ago — you can make a pretty safe bet. Underneath, somewhere, is a giant map of everything it’s ever seen. Your input gets a pin. The system grabs the nearest neighbors. The thing that feels like understanding is, in the most literal sense, geography.</p><p>Meaning, it turns out, was a place all along. We just had to figure out how to draw the map.</p><p><em>This is the first article in a short series. The next piece looks under the hood at how the LLMs we just talked about actually work — what tokens are, why “the model reads your sentence” is also a story about embeddings, and what’s really happening when ChatGPT writes its next word. After that, a third article on how modern AI search (Google, ChatGPT-with-PDF, Notion AI) blends keyword matching, embeddings, and ranking to feel as good as it does.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=09d5bb3e12cb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How We Reduced LLM Inference Costs by Shifting the Source of Truth]]></title>
            <link>https://medium.com/@priyansh1990_60788/how-we-reduced-llm-inference-costs-by-shifting-the-source-of-truth-2d76deac7a2f?source=rss-9277fb2fcf78------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d76deac7a2f</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[web-design]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Priyansh]]></dc:creator>
            <pubDate>Sun, 17 May 2026 16:32:54 GMT</pubDate>
            <atom:updated>2026-05-17T16:32:54.219Z</atom:updated>
            <content:encoded><![CDATA[<p>Every team building an AI-powered product eventually hits the same wall. You build a “smart” frontend that tries to decide whether an expensive LLM call is actually needed. Then you spend weeks debugging why it fires when it shouldn’t, why it doesn’t fire when it should, and why your AI bill keeps surprising you.</p><p>We call this <strong>LLM Jitter</strong> — the phenomenon where any change to user data, meaningful or not, triggers a full inference run.</p><p>In our resume coaching platform, users would change their phone number and trigger a 15-second recruiter analysis. The AI never looks at contact information. We were burning credits on nothing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C2EVE6BW9Kh83mfoyl5hjA.png" /></figure><h3>The Intuitive Solution That Doesn’t Work</h3><p>The first instinct is to fix this in the frontend. Before firing the API, the client checks: “has anything the AI actually cares about changed?”</p><p>Simple in theory. In practice, we ended up maintaining a custom recursive serializer to handle key-ordering differences in JSON round-trips through DynamoDB, passing a 50KB snapshot object in every API response just so the client could do comparisons, and watching it occasionally trigger false positives when React’s strict mode double-rendered components.</p><p>The fundamental issue wasn’t the implementation. It was where the logic lived.</p><p>The question <em>“has anything meaningful changed?”</em> is a business rule. It belongs on the server — not in React, not in a TypeScript utility file, not in your component lifecycle. When business logic lives in the frontend, it gets bypassed by every other client you add. It gets broken by UI refactors that have nothing to do with caching. It creates a split source of truth between what the client thinks and what the server knows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uEmPwOIzlreprEz13tDvtQ.png" /></figure><h3>The Pattern: Semantic Timestamps</h3><p>The professional solution already has a name in computer science. HTTP browsers have used it since 1999. It’s called an <strong>ETag</strong>.</p><p>When your browser downloads an image, the server sends back a hash of the image content. Next request, the browser says: <em>“I have version </em><em>a1b2c3. Do you?&quot;</em> The server compares two strings and either returns 304 Not Modified or the new content. No deep file comparison. No round-tripping the full image. Two strings.</p><p>We applied the same principle to resume analysis.</p><p>Instead of one generic updated_at that fires on any change, we introduced a <strong>semantic timestamp</strong> — one that only updates when the AI-relevant content actually changes.</p><p><strong>At save time (once per edit):</strong> the backend computes a SHA-256 hash of only the four sections the AI reads — experience, projects, skills, education. If that hash differs from what’s stored, it bumps ai_content_updated_at. If the user only edited their phone number, ai_content_updated_at stays exactly where it was.</p><p><strong>At analysis time (every audit click):</strong> the analyzer compares two timestamp strings. That’s the entire check. Two strings, microseconds, no payload, no deep comparison.</p><pre>def compute_ai_content_hash(resume_data: dict) -&gt; str:<br>    ai_content = {<br>        &quot;experience&quot;: resume_data.get(&quot;experience&quot;, []),<br>        &quot;education&quot;:  resume_data.get(&quot;education&quot;,  []),<br>        &quot;projects&quot;:   resume_data.get(&quot;projects&quot;,   []),<br>        &quot;skills&quot;:     resume_data.get(&quot;skills&quot;,     []),<br>    }<br>    # sort_keys=True makes the output identical regardless of<br>    # dict insertion order — handles DynamoDB round-trip key reordering<br>    stable = json.dumps(ai_content, sort_keys=True, separators=(&#39;,&#39;, &#39;:&#39;))<br>    return hashlib.sha256(stable.encode()).hexdigest()</pre><p>The sort_keys=True detail matters. Python dictionaries preserve insertion order, but DynamoDB doesn&#39;t guarantee it on read. Without sorted keys, two identical resumes could produce different hashes depending on how the database returned the data. One line eliminates an entire class of subtle bugs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jZu_URLlfV0cym1Nz40Fjw.png" /></figure><h3>What This Fixed Beyond the Credits</h3><p>Shifting the decision to the backend solved a problem we hadn’t expected.</p><p>Our UI had a “stale analysis” banner — a gentle nudge that appeared when the user’s resume had changed since the last audit. This banner was driven by a server-side timestamp comparison. With our old frontend gate, the banner would appear after a phone number edit, even though we silently blocked the API call. The banner was technically correct (the updated_at had changed) but practically wrong (nothing AI-relevant had changed). Users were confused.</p><p>With semantic timestamps, when the user edits a phone number and clicks “Run Audit,” the backend confirms nothing changed and updates resume_updated_at on the analysis record to match the current timestamp. The next time the frontend polls, the timestamps match. The banner disappears — correctly. The system now tells the truth.</p><h3>The Results</h3><p>After shipping this:</p><ul><li><strong>50KB </strong><strong>resume_snapshot_json removed from every analysis record.</strong> That payload was stored in DynamoDB and returned in every API response solely to support a frontend comparison that no longer exists.</li><li><strong>Any client gets the same correct behaviour for free.</strong> A mobile app, a public API, a background job — they all route through the same Python analyzer, which means they all get the same staleness check without any extra code.</li><li><strong>The stale banner stopped lying.</strong> Small edits (contact info, summary text) no longer trigger false positive warnings.</li></ul><h3>The Principle</h3><p>If your frontend is doing complex delta-checking before calling an expensive API, ask one question: <em>who should own this decision?</em></p><p>If the answer is “it depends on business rules about what data matters” — that’s server territory. Move it there.</p><p><strong>Pay the computation cost at write time.</strong> You write infrequently. You read constantly. Amortize the expensive work across thousands of cheap reads, not the other way around. Your frontend becomes a POST button. Your backend becomes the authority. Your LLM bill stops being a surprise.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d76deac7a2f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Invisible Database Bug That Senior Engineers Miss: DynamoDB’s “Shallow GSI” Trap]]></title>
            <link>https://medium.com/@priyansh1990_60788/the-invisible-database-bug-that-senior-engineers-miss-dynamodbs-shallow-gsi-trap-b09767e06a8e?source=rss-9277fb2fcf78------2</link>
            <guid isPermaLink="false">https://medium.com/p/b09767e06a8e</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[dynamodb]]></category>
            <dc:creator><![CDATA[Priyansh]]></dc:creator>
            <pubDate>Thu, 19 Mar 2026 04:54:50 GMT</pubDate>
            <atom:updated>2026-03-19T05:10:32.423Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A deep-dive into the “False Positive” failure mode of DynamoDB Global Secondary Indexes, what it looks like in production, and how to fix it before it wakes you up at 2 AM.</em></p><h3>The “Smoking Gun”</h3><p>I was recently pushing a production update to an AI resume platform. On paper, the logic was textbook:</p><ol><li><strong>Lambda A</strong> parses a Job Description and dumps a structured JSON into DynamoDB, tagged with an association_ref_id.</li><li><strong>Lambda B</strong> (the Analyzer) picks up that ID later to run the comparison.</li></ol><p>Everything passed local QA. But the second we hit prod, my logs started gaslighting me. Lambda B kept spitting out this error:</p><blockquote><em>[WARNING] ❌ GapAnalyzer: Missing data_payload in the database.</em></blockquote><p>The problem? The log line <strong>directly above it</strong> said:</p><blockquote><em>[INFO] ✅ Found 1 records for tenant: &lt;TENANT_ID&gt; and reference: &lt;REF_ID&gt;</em></blockquote><p>It found the record. Then it immediately claimed it didn’t exist. If you’ve ever stared at a “Successful” query that returns undefined data, you know exactly how maddening this is.</p><h3>The Architecture: Why we use GSIs</h3><p>We’re using <strong>DynamoDB Single Table Design</strong> here. Since we can’t always query by the main Primary Key, we rely on a Global Secondary Index (GSI) to look up analyses via that association_ref_id.</p><p>Our schema looked roughly like this:</p><ul><li><strong>Primary Key:</strong> tenant_id</li><li><strong>Sort Key:</strong> entity_sort_val</li><li><strong>GSI Key:</strong> association_ref_id</li><li><strong>The Goods:</strong> data_payload (The massive JSON blob from the AI)</li></ul><p>A GSI lets us treat that association_ref_id like a primary key so we don&#39;t have to run an expensive, slow &quot;Table Scan.&quot;</p><h3>The “Hollow Shell” Problem</h3><p>Here is the mental shift: <strong>A GSI is not a “view” or a “shortcut.”</strong> It is a physically separate table that DynamoDB manages for you.</p><p>When you set one up, DynamoDB asks: <em>“How much of this data do you want me to photocopy over to the new table?”</em> This is called <strong>Projection</strong>.</p><p>I was trying to be “cost-effective” and “clever.” I didn’t want to pay to store that massive data_payload twice, so I set my Projection to INCLUDE only the basic IDs. I wanted a &quot;slim&quot; index. Instead, I built a hollow shell.</p><p><strong>The Anatomy of the Fail:</strong></p><ol><li><strong>The Write:</strong> The Base Table gets the full JSON. The GSI only gets the IDs.</li><li><strong>The Read:</strong> Lambda B queries the GSI. The GSI says, <em>“Yep, I’ve got a match for that ID!”</em></li><li><strong>The Result:</strong> Because data_payload wasn&#39;t projected, the GSI returns a record where that field is just... missing.</li><li><strong>The Crash:</strong> The code looks for the payload, finds None or undefined, and assumes the database is empty.</li></ol><h3>The Math: Why my “Optimization” was actually a bad deal</h3><p>You might think: <em>“Well, why not just use the GSI to find the ID, then go back to the main table for the full data?”</em> Let’s run the back-of-the-napkin math for 100,000 analyses (5 KB each) read 100,000 times a month.</p><p><strong>Option 1: The Projected GSI (The Fix)</strong></p><ul><li><strong>Data Flow:</strong> 1 Network Trip</li><li><strong>Latency:</strong> ~10ms</li><li><strong>The Bill:</strong> Storing that extra data costs about <strong>$0.12/month</strong>. Because it’s a single read of 5 KB, it costs <strong>$0.05</strong> in Read Request Units (RRUs).</li></ul><p><strong>Option 2: The Two-Step Lookup (The “Optimization”)</strong></p><ul><li><strong>Data Flow:</strong> 2 Sequential Network Trips.</li><li><strong>Latency:</strong> ~30ms (it triples).</li><li><strong>The Bill:</strong> You save 12 cents on storage, but you pay for <em>three</em> RRUs per lookup instead of two. Your monthly read bill jumps to <strong>$0.07</strong>.</li></ul><p><strong>The Verdict:</strong> I was trying to save 12 cents a month, but in exchange, I made my app 3x slower and increased my read costs by 50%. In high-scale systems, storage is cheap. Latency and compute are expensive.</p><h3>Making it Explicit: Option 1 vs. Option 2</h3><p>Here’s what the code looks like for both. Seeing the “Two-Step” version makes it obvious why it’s a headache.</p><p><strong>Option 1: The “Fast” Way (Projected)</strong></p><pre># One trip. Done.<br>response = table.query(<br>    IndexName=&#39;ExternalReferenceIndex&#39;,<br>    KeyConditionExpression=Key(&#39;tenant_id&#39;).eq(tenant_id) &amp; <br>                           Key(&#39;association_ref_id&#39;).eq(ref_id)<br>)<br>return response[&#39;Items&#39;][0].get(&#39;data_payload&#39;)</pre><p><strong>Option 2: The “Slow” Way (Two-Step)</strong></p><pre># Trip 1: Find the address<br>index_res = table.query(<br>    IndexName=&#39;ExternalReferenceIndex&#39;,<br>    KeyConditionExpression=Key(&#39;tenant_id&#39;).eq(tenant_id) &amp; <br>                           Key(&#39;association_ref_id&#39;).eq(ref_id),<br>    ProjectionExpression=&#39;entity_sort_val&#39;<br>)<br><br># Trip 2: Go to the main table to actually get the data<br>base_res = table.get_item(<br>    Key={&#39;tenant_id&#39;: tenant_id, &#39;entity_sort_val&#39;: index_res[&#39;Items&#39;][0][&#39;entity_sort_val&#39;]}<br>)<br>return base_res[&#39;Item&#39;].get(&#39;data_payload&#39;)</pre><h3>The Fix</h3><p>The fix lived in the <strong>Infrastructure as Code (CDK)</strong>. I had to tell the GSI to actually “photocopy” the payload so it was there when I needed it.</p><pre>// THE FIX: No more hollow shells.<br>this.mainDataTable.addGlobalSecondaryIndex({<br>    indexName: &#39;ExternalReferenceIndex&#39;, <br>    partitionKey: { name: &#39;tenant_id&#39;, type: dynamodb.AttributeType.STRING },<br>    sortKey: { name: &#39;association_ref_id&#39;, type: dynamodb.AttributeType.STRING },<br>    projectionType: dynamodb.ProjectionType.INCLUDE,<br>    nonKeyAttributes: [<br>        &#39;entity_sort_val&#39;, <br>        &#39;record_type_tag&#39;, <br>        &#39;data_payload&#39;,  // &lt;--- The missing piece<br>        &#39;last_modified_ts&#39;<br>    ], <br>});</pre><h3>Lessons Learned</h3><ul><li><strong>GSIs are NOT Views:</strong> They are separate tables. If the data isn’t in the GSI, it doesn’t exist for that query.</li><li><strong>Beware “Slim” Indexes:</strong> If your logs say “Found” but your code sees nothing, check your Projection mapping.</li><li><strong>SQL Habits Kill:</strong> In SQL, the DB “joins” the index for you. In DynamoDB, you are the join engine. Be explicit.</li></ul><p>Long story short: Don’t let a 12-cent “optimization” wake you up in the middle of the night.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b09767e06a8e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Taming the Gemini CLI: How I Connected Notion Behind School/Work Firewalls]]></title>
            <link>https://medium.com/@priyansh1990_60788/taming-the-gemini-cli-how-i-connected-notion-behind-school-work-firewalls-b31ea645179d?source=rss-9277fb2fcf78------2</link>
            <guid isPermaLink="false">https://medium.com/p/b31ea645179d</guid>
            <category><![CDATA[model-context-protocol]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[google-gemini]]></category>
            <category><![CDATA[notion]]></category>
            <category><![CDATA[google-gemini-cli]]></category>
            <dc:creator><![CDATA[Priyansh]]></dc:creator>
            <pubDate>Mon, 12 Jan 2026 04:31:46 GMT</pubDate>
            <atom:updated>2026-01-12T04:31:46.032Z</atom:updated>
            <content:encoded><![CDATA[<p>The promise of the Model Context Protocol (MCP) is incredible: connect your AI to your actual data. Instead of just chatting with Gemini, you can have Gemini read, analyze, and interact with your Notion workspace.</p><p>I recently tried setting this up using the Google Gemini CLI on my school MacBook. It should have been a five-minute setup. Instead, it turned into a debugging odyssey involving trailing slashes, OAuth rejections, and environment variable mysteries.</p><p>If you are trying to connect the Gemini CLI to Notion while using a school or enterprise Google account and are hitting brick walls, this guide is for you. Here is how I broke everything, and then fixed it by abandoning the “easy” way and going local.</p><h3>The “Four Horsemen” of Connection Failure</h3><p>My initial attempt followed the standard documentation: use the managed Notion MCP server and log in via the browser. This resulted in a cascade of increasingly frustrating errors.</p><h3>Error 1: The “Trailing Slash” Bug</h3><p>The Gemini CLI’s security check is currently incredibly strict. It expects the Notion server’s identity URL to match the configuration character-for-character.</p><p>The Notion server identified itself as https://mcp.notion.com. My configuration (or the CLI&#39;s internal normalization) expected <a href="https://mcp.notion.com/">https://mcp.notion.com/.</a></p><p>That single invisible slash caused a hard stop:</p><blockquote><em>✕ Failed to authenticate: Protected resource https://mcp.notion.com does not match expected </em><a href="https://mcp.notion.com/"><em>https://mcp.notion.com/</em></a></blockquote><h3>Error 2: The School Account Block (OAuth Access Denied)</h3><p>Even after fighting the slash issue, I hit a bigger wall. When the CLI tried to open my browser to log in to Google, it failed immediately.</p><p>Because I am on a managed school account, the IT administrators block unauthorized third-party apps from accessing Google data via OAuth.</p><blockquote><em>Google OAuth error: access_denied. No additional details provided.</em></blockquote><h3>Error 3: The macOS Environment Issue</h3><p>Trying to fix the above, I attempted to run servers locally, but macOS refused to play nice with the terminal environment, resulting in cryptic crashes:</p><blockquote><em>MCP error -32000: Connection closed</em></blockquote><h3>The Realization: Go Local or Go Home</h3><p>I realized the root cause of all these issues was relying on <strong>managed cloud services</strong> (mcp.notion.com and browser-based Google Login) in a restricted environment.</p><p>The managed services rely on redirects and permissions that school firewalls hate. The solution was to stop trying to go <em>around</em> the firewall and instead build a direct, authenticated tunnel from my local machine.</p><h3>The Visual Diagnosis</h3><p>Here is a diagram of why the standard method failed, and why the local method works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aRGxnYAXQ6cOWw8IL9WM4g.png" /></figure><h3>The Final Solution: A 3-Step “Pro” Setup</h3><p>To get this working robustly, we need two keys: one for the Gemini and one for the Notion.</p><h3>Step 1: Get a Google Cloud API Key</h3><p>Since the browser login is blocked, we bypass it by using a Google Cloud Platform (GCP) API Key. This authenticates the CLI directly without involving school permissions.</p><ol><li>Go to the Google Cloud Console and create a project.</li><li>Enable the <strong>“Gemini API”</strong>.</li><li>Create Credentials -&gt; <strong>API Key</strong>.</li><li>In the Gemini CLI, select <strong>“Use Gemini API Key”</strong> and paste it in.</li></ol><h3>Step 2: Get a Notion Integration Token</h3><p>We ditch the mcp.notion.com URL entirely. Instead, we will run the Notion connector directly on our laptops using npx. This requires an internal integration token.</p><ol><li>Go to <strong>notion.so/my-integrations</strong>.</li><li>Create a new internal integration called “Gemini CLI”.</li><li>Copy the “Internal Integration Secret” (it starts with ntn_...)</li></ol><p><strong>Crucial Step:</strong> By default, this integration can see <em>nothing</em>. You must go to the specific Notion pages you want Gemini to access, click the three dots ... in the top right, scroll to <strong>Connect to</strong>, and select your new integration.</p><h3>Step 3: The Golden Configuration</h3><p>Finally, we configure Gemini to ignore the cloud URLs and instead run a local command that uses our new Notion secret. We use a printf command to write the configuration directly to avoid any hidden character issues in text editors. Run this in your terminal (replacing YOUR_NOTION_SECRET_HERE with your actual token):</p><pre>printf &#39;{\n  &quot;security&quot;: {\n    &quot;auth&quot;: {\n      &quot;selectedType&quot;: &quot;gemini-api-key&quot;\n    }\n  },\n  &quot;mcpServers&quot;: {\n    &quot;Notion&quot;: {\n      &quot;command&quot;: &quot;npx&quot;,\n      &quot;args&quot;: [\n        &quot;-y&quot;,\n        &quot;@notionhq/notion-mcp-server&quot;\n      ],\n      &quot;env&quot;: {\n        &quot;NOTION_TOKEN&quot;: &quot;YOUR_NOTION_SECRET_HERE&quot;\n      }\n    }\n  }\n}&#39; &gt; ~/.gemini/settings.json</pre><p>Now, when you run gemini, it boots up instantly, spawns a local Notion connection, and shows that beautiful green &quot;Connected&quot; status.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*1cCm5q0OgpO7B-FyC-zdXQ.png" /></figure><h3>Key Takeaways</h3><p>If you are in a restricted environment, rely on API keys and local servers rather than browser-based OAuth flows. It gives you more control, bypasses institutional blocks, and ultimately provides a much more stable connection for building with AI.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b31ea645179d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>