<?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 Priyanshu Patel on Medium]]></title>
        <description><![CDATA[Stories by Priyanshu Patel on Medium]]></description>
        <link>https://medium.com/@patelpriysnshu2410?source=rss-f05dad4b99f8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*gV02H82qJuoSN_4x</url>
            <title>Stories by Priyanshu Patel on Medium</title>
            <link>https://medium.com/@patelpriysnshu2410?source=rss-f05dad4b99f8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 00:08:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@patelpriysnshu2410/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[I tried the AI models that refuse to write anything]]></title>
            <link>https://medium.com/@patelpriysnshu2410/i-tried-the-ai-models-that-refuse-to-write-anything-5d678c40902f?source=rss-f05dad4b99f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d678c40902f</guid>
            <category><![CDATA[laya]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[system-one-model]]></category>
            <category><![CDATA[jevs]]></category>
            <dc:creator><![CDATA[Priyanshu Patel]]></dc:creator>
            <pubDate>Thu, 24 Sep 2026 07:14:35 GMT</pubDate>
            <atom:updated>2026-09-24T07:14:35.829Z</atom:updated>
            <content:encoded><![CDATA[<h3>Two models launched three days apart in September 2026. Neither one generates a single word — and that turns out to be the point.</h3><p>Every developer who has put an LLM into production knows this dance.</p><p>You need a decision. Which team handles this ticket. Is this comment spam. How urgent is this. So you ask a language model, and it writes you a paragraph.</p><p>You didn’t want a paragraph. So you ask for JSON.</p><p>Now you’re parsing JSON. Sometimes it arrives in a markdown fence. Sometimes a field is missing. Sometimes it invents a category you never listed. So you add a validator, then a retry, then a fallback.</p><p>Eventually you’re maintaining forty lines of defensive plumbing around a model that was meant to answer a four-way multiple-choice question.</p><blockquote>The problem was never the model’s intelligence. It’s that we asked a writer to do a clerk’s job.</blockquote><p>In September 2026, two teams shipped models that do the clerk’s job instead. One is closed and commercial. One is open and free. They launched three days apart.</p><p>I spent a while with both. Here’s what I found.</p><h3>The idea: System One models</h3><p>Language models are autoregressive — one token, look at it, next token. That’s why a yes/no question costs you a round trip through a text generator.</p><p>These don’t do that. You hand them <strong>state</strong> (an email, a ticket, a JSON blob) plus <strong>typed questions</strong>. They hand back typed values with probabilities.</p><p>No tokens. No parsing. One forward pass.</p><p>The name borrows from Kahneman: <strong>System 1</strong> is fast and automatic, <strong>System 2</strong> is slow and deliberate. LLMs are System 2. These are System 1.</p><p>The entire API is three question types:</p><ul><li><strong>Choice</strong> — pick one from a named set. Probability for every option.</li><li><strong>Score</strong> — rate against ordered levels. Probability per level.</li><li><strong>Noul</strong> — yes/no. You get P(yes).</li></ul><p>Small vocabulary, and that’s the trick: the answer is constrained to something your code already handles.</p><h3>Jev — the commercial one</h3><p><strong>Jev</strong> comes from TypeSafe AI, a San Francisco company founded in 2024 by Diogo Almeida — a former OpenAI researcher who worked on ChatGPT and RLHF — along with Erik Gafni and Sasha Sheng.</p><p>It launched on 15 September 2026 alongside a $40M seed round led by DCVC, behind a waitlist that lasted five days. Signup is open now, with $5 of free credit.</p><p>Routing a support ticket:</p><pre>from typesafe_sdk import Choice, Noul, Score, TypeSafeClient</pre><pre>client = TypeSafeClient()</pre><pre>response = client.system_one(<br>    state=&quot;I&#39;ve been trying to connect my Stripe account for 3 days and the &quot;<br>          &quot;integration keeps failing. I&#39;m losing sales. Please help ASAP.&quot;,<br>    questions={<br>        &quot;department&quot;: Choice(<br>            instructions=&quot;Which team should handle this?&quot;,<br>            criteria={<br>                &quot;billing&quot;: &quot;invoices, payments, refunds&quot;,<br>                &quot;technical&quot;: &quot;bugs, outages, integrations&quot;,<br>                &quot;sales&quot;: &quot;pricing and new contracts&quot;,<br>            },<br>        ),<br>        &quot;urgency&quot;: Score(<br>            instructions=&quot;How urgent is this request?&quot;,<br>            criteria=[&quot;not urgent&quot;, &quot;soon&quot;, &quot;critical&quot;],<br>        ),<br>        &quot;is_urgent&quot;: Noul(instructions=&quot;Does this message express urgency?&quot;),<br>    },<br>)</pre><pre>print(response.answers[&quot;department&quot;].choice)   # &quot;technical&quot;<br>print(response.answers[&quot;is_urgent&quot;].noul)      # 1.0</pre><p>Three questions, one network call, one pass. The response carries the model version, typed answers, a probability distribution for each, and token usage.</p><p>Two things worth pulling out of TypeSafe’s own writeup:</p><p><strong>It can’t hallucinate — in a narrow, literal sense.</strong> The output is constrained to the options you supplied. It cannot invent a department called purple.</p><p>A real guarantee — and emphatically <em>not</em> the same as being right. It can still pick the wrong department with total composure.</p><p><strong>They trained for calibration, not fluency.</strong> Their method is called Reinforcement Learning for Calibrated Decisions, aimed at what they describe as epistemically honest probabilities. If it says 70%, it should be right roughly 70% of the time.</p><p>Standard LLMs are bad at this, and a model that reports “95% confident” while being wrong a third of the time is worse than useless in a pipeline.</p><p>Then the pricing, which is what made people sit up:</p><blockquote>$0.042 per million input tokens. Output tokens free — TypeSafe’s own phrase is “too cheap to meter.”</blockquote><p>They also concede, in that same post, that the long-term sustainability of this is unproven.</p><h3>Laya — the open answer, three days later</h3><p>Jev had the category to itself for exactly 72 hours.</p><p>On 18 September, Convai Innovations released <strong>Laya</strong> under Apache 2.0. Same three question types. Open weights on Hugging Face. Free. Runs on your own hardware.</p><p>The timeline is the story:</p><ul><li><strong>15 Sep</strong> — TypeSafe ships Jev. Closed, waitlisted, $40M seed.</li><li><strong>18 Sep</strong> — Laya lands. Apache 2.0, weights public, no account needed.</li><li><strong>20 Sep</strong> — TypeSafe drops the Jev waitlist. Demand made it pointless.</li><li><strong>Days later</strong> — laya-mlx, a community port, runs the whole thing offline on a MacBook.</li></ul><p>Five days, start to finish.</p><p>And the best detail in the whole story: Laya’s author had been building non-autoregressive decision models for about a year <em>before</em> a frontier lab gave the idea a name and a $200M valuation.</p><p>Three checkpoints ship, with a router that picks between them:</p><ul><li><strong>laya</strong> — ModernBERT-large, 421M params, 512 context. English.</li><li><strong>laya-multilingual</strong> — mmBERT-base, 322M params, 1024 context. 100+ languages, and faster than the English one.</li><li><strong>laya-typed-decisions</strong> — ModernBERT-large, 421M, 1024 context. Workflow tasks.</li></ul><p>421 million parameters. Frontier LLMs are in the hundreds of billions. Picking one of four options does not require a model that can also write a sonnet.</p><p><strong>laya-mlx</strong> is the port worth knowing about — no PyTorch, no Transformers runtime, straight to the GPU on Apple Silicon. Same task as the Jev snippet above:</p><pre>import laya_mlx as laya</pre><pre>agent = laya.load(&quot;aac6fef/laya-mlx&quot;)</pre><pre>result = agent.predict(<br>    &quot;I&#39;ve been trying to connect my Stripe account for 3 days and the &quot;<br>    &quot;integration keeps failing. I&#39;m losing sales. Please help ASAP.&quot;,<br>    {<br>        &quot;department&quot;: {<br>            &quot;type&quot;: &quot;choice&quot;,<br>            &quot;instructions&quot;: &quot;Which team should handle this?&quot;,<br>            &quot;criteria&quot;: {<br>                &quot;billing&quot;: &quot;invoices, payments, refunds&quot;,<br>                &quot;technical&quot;: &quot;bugs, outages, integrations&quot;,<br>                &quot;sales&quot;: &quot;pricing and new contracts&quot;,<br>            },<br>        },<br>        &quot;urgency&quot;: {<br>            &quot;type&quot;: &quot;score&quot;,<br>            &quot;instructions&quot;: &quot;How urgent is this request?&quot;,<br>            &quot;criteria&quot;: [&quot;not urgent&quot;, &quot;soon&quot;, &quot;critical&quot;],<br>        },<br>        &quot;is_urgent&quot;: {<br>            &quot;type&quot;: &quot;noul&quot;,<br>            &quot;instructions&quot;: &quot;Does this message express urgency?&quot;,<br>        },<br>    },<br>)</pre><pre>print(result[&quot;answers&quot;])</pre><p>Same shape. Plain dicts instead of typed classes. predict instead of system_one. No API key anywhere in the file. The weights download once, then it runs offline.</p><p>It also ships the best demo in the category: laya-snake, a terminal Snake game where every move is a live model decision. 75.4 moves per second on an M3 Max.</p><p>Watching a neural network play Snake with the wifi switched off makes the point better than any benchmark table.</p><h3>The race this starts</h3><p>The pattern should look familiar. It’s the Stable Diffusion playbook, compressed into a working week:</p><ol><li>A funded lab defines a new category and sets the price.</li><li>Open weights answer within <strong>days</strong>, not months.</li><li>Community ports follow within days of <em>that</em>.</li><li>The closed product competes on managed service. The open one competes on control and cost.</li></ol><p>As I write this, Jev is nine days old and Laya is six. There’s no third entrant yet. There will be, and the shape of it is fairly predictable:</p><ul><li><strong>More open checkpoints.</strong> The architecture is ModernBERT plus decision heads. That is not a moat.</li><li><strong>Runtimes beyond Apple.</strong> laya-mlx proved the port is a weekend’s work. ONNX and llama.cpp-style builds are the obvious next step.</li><li><strong>JavaScript bindings.</strong> The biggest gap on the open side today, and the single reason Jev currently wins on integration.</li><li><strong>Frontier labs shipping their own.</strong> A typed-decision endpoint is a small feature next to an LLM, and a cheap way to keep classification traffic in-house.</li></ul><p>So pick for the next six months, not the next five years. This category will not look like this by spring.</p><h3>Choosing between them</h3><p><strong>Jev</strong> is closed and proprietary. It runs on TypeSafe’s servers. $0.042 per million input tokens, with $5 of free credit to start. Python <em>and</em> JavaScript SDKs. No hardware requirements — it’s an API. No fine-tuning.</p><p><strong>Laya</strong> is Apache 2.0 with open weights. It runs on your machine. It’s free. Python only. The MLX build needs Apple Silicon. You can fine-tune it.</p><p>The practical fork is less about the models than your stack. Jev’s JavaScript SDK drops into a Node or Next.js service in two minutes. Laya is Python-only, and shipping 421M parameters into a serverless function is a bad time — so “free, run it yourself” really means “on a machine you control.”</p><h3>About those benchmarks</h3><p>This is the part most write-ups skip, so let me be direct.</p><p>TypeSafe reports 40–200× faster and cheaper than frontier LLMs on comparable tasks, with 70–500ms responses.</p><p>Laya’s model card reports 83.8% accuracy against Jev’s 67.8%, and 32.8ms against Jev’s 236–276ms.</p><blockquote>Both of those are self-reported, on self-selected tasks.</blockquote><p>TypeSafe used their own internal workflows, which they acknowledge probably represent the high end. Laya’s comparison was run by the team whose model wins it. Neither is dishonest; neither is independent evidence. I haven’t reproduced either, and this post won’t pretend otherwise.</p><p>I’d trust the anecdote in TechCrunch’s coverage more: a Vercel engineer swapped an LLM out of a safety-review path and reported results five to eighteen times faster, with better accuracy. A real workload with a real before-and-after — still one data point, but a more honest shape of one.</p><p>The takeaway isn’t that the numbers are fake. It’s that the only benchmark that settles this is yours, on your data. Which is annoying, and also just true.</p><h3>When this is the right tool</h3><p>Reach for a System One model when your code needs a <strong>decision</strong>, not prose:</p><ul><li>Routing tickets, emails, or support requests</li><li>Moderation and safety filters</li><li>Classification, scoring, ranking, extraction</li><li>Real-time loops — games, robots, simulations — where 500ms is already too slow</li><li>As a cheap gate <em>in front of</em> an LLM, deciding whether the expensive call is needed at all</li></ul><p>Don’t reach for it when you want words out. Writing, summarising, translating, explaining, generating code — these are not LLM replacements, and the vendors don’t claim they are.</p><p>And there’s one thing you genuinely must not do: read the top answer and throw the probability away.</p><p>The entire value here is a calibrated number. Armin Ronacher made this point well when Jev launched — if something comes back at 50%, that’s a coin toss, and the correct move is to route it to a human rather than act on it.</p><p>If your code reads answer.choice and ignores confidence, you’ve bought a decision model and used it as a worse classifier.</p><h3>What I’d actually do</h3><p>Grab the $5 of Jev credit. It’s roughly 120 million input tokens — far more than you need to feel the idea. Wire it into one classification you currently hand to an LLM.</p><p>Then pip install &#39;laya-mlx[demo]&#39; and run laya-snake on a Mac with the wifi off.</p><p>Ten minutes across the two of them and the whole category clicks.</p><p>The interesting part isn’t that either model beats GPT at anything. It’s realising how much of what we currently spend LLM tokens on was never a language problem in the first place.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d678c40902f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Finally Understood Knowledge Graphs. It Took Five Sentences and a Sheet of Paper.]]></title>
            <link>https://medium.com/@patelpriysnshu2410/i-finally-understood-knowledge-graphs-it-took-five-sentences-and-a-sheet-of-paper-e2f82fd66edc?source=rss-f05dad4b99f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2f82fd66edc</guid>
            <category><![CDATA[neo4j]]></category>
            <category><![CDATA[vector-database]]></category>
            <category><![CDATA[knowledge-graph]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Priyanshu Patel]]></dc:creator>
            <pubDate>Mon, 24 Aug 2026 05:20:46 GMT</pubDate>
            <atom:updated>2026-08-24T05:20:46.370Z</atom:updated>
            <content:encoded><![CDATA[<h3>Going from “that sounds like enterprise jargon” to actually getting it — and where it connects to RAG.</h3><p>I kept running into the phrase. Job descriptions, conference talks, every third thread about GraphRAG.</p><p>And every time, I nodded like I knew what it meant. I didn’t.</p><p>My honest mental model was <em>some enterprise thing involving ontologies and consultants</em>. Filed next to “digital transformation.” Important-sounding, probably not for me.</p><p>Three weeks ago I decided to actually learn it instead of nodding. I was wrong about most of it. Here’s the short version of what I found.</p><h3>The definition that finally worked</h3><p>I read maybe fifteen definitions before one landed. Most were variations on “a semantic network representing entities and their interrelations,” which helps nobody.</p><p>The one that clicked:</p><blockquote><em>A knowledge graph stores facts as </em><strong><em>connections between things</em></strong><em>, instead of as sentences in a document.</em></blockquote><p>My wiki says: <em>“Priya is an engineer at Acme.”</em></p><p>A knowledge graph says: Priya —[WORKS_AT]→ Acme</p><p>My first reaction was, that’s the same information. Why does anyone care?</p><p>Here’s why. In the sentence, the relationship is <strong>trapped inside text</strong> — the only way to get it out is to read it. In the graph, the relationship exists on its own. You can follow it, count it, jump across it.</p><p>Everything else follows from that one difference.</p><h3>It’s built from three things</h3><p>I kept waiting for the complicated part. There isn’t one.</p><p><strong>Nodes</strong> are the things. Priya, Acme, Nimbus.</p><p><strong>Edges</strong> are the connections, each with a type and a direction. Priya —WORKS_AT→ Acme. Direction isn&#39;t decoration — the reverse is nonsense.</p><p><strong>Properties</strong> are the details, on either a node or an edge:</p><pre>(Priya {role: &quot;Backend Engineer&quot;})<br>      -[WORKS_AT {since: 2019}]-&gt;<br>(Acme {founded: 2011})</pre><p>The bit that made me stop: since: 2019 sits on the <strong>edge</strong>, not on Priya. That&#39;s not a fact about Priya, it&#39;s a fact about her <em>relationship with Acme</em>. Put it on her node and you&#39;ve got nowhere to put it when she changes jobs.</p><p>And every fact reduces to a three-part sentence called a <strong>triple</strong>:</p><pre>Priya    →  WORKS_AT    →  Acme<br>Acme     →  ACQUIRED    →  Bitway<br>Bitway   →  BUILT       →  Nimbus<br>Nimbus   →  DEPENDS_ON  →  Vault</pre><p>A graph with ten million facts is ten million of those lines. Nothing fancier is happening underneath. Once I got that, the intimidation went away.</p><h3>The five sentences that made it click</h3><p>I gave up on tutorials here and did it by hand. Best decision of the three weeks.</p><p>Five sentences from five different pages of our wiki:</p><ol><li>Priya is a backend engineer at Acme.</li><li>Rahul manages Priya.</li><li>Acme acquired Bitway in 2021.</li><li>Bitway originally built the Nimbus payment system.</li><li>Nimbus depends on the Vault service, which Rahul owns.</li></ol><p>Turned into triples, drawn on paper:</p><pre>(Rahul) ──MANAGES──▶ (Priya) ──WORKS_AT──▶ (Acme)<br>      │                                          │<br>      │ OWNS                                     │ ACQUIRED<br>      │                                          ▼<br>      │                                       (Bitway)<br>      ▼                                          │<br>   (Vault) ◀───DEPENDS_ON─── (Nimbus) ◀──BUILT───┘</pre><p>Then I sat back, because something had appeared that I hadn’t put there.</p><p><strong>Rahul is connected to Nimbus.</strong> Nobody wrote that down. It’s Rahul → Vault → Nimbus, assembled from two separate documents.</p><p><strong>Priya’s employer owns the company that built Nimbus.</strong> Also written nowhere. Four steps.</p><p>Five sentences in. Facts out that none of the five contained.</p><blockquote><em>A knowledge graph makes implicit knowledge explicit.</em></blockquote><p>I’d read that line a week earlier and dismissed it as marketing. Drawing it myself is what made it real. If you’re learning this — do this exercise. Five sentences, one sheet of paper. Worth more than three tutorials.</p><h3>The word that changed how I think: hops</h3><p>A <strong>hop</strong> is one step along one edge.</p><p><em>Where does Priya work?</em> One hop. <em>Who manages the person who works at Acme?</em> Two. <em>What does Priya’s employer’s acquisition’s product depend on?</em> Four.</p><p>I now count hops in ordinary conversation. It’s the number that predicts everything — one-hop questions are easy for any tool, two starts to hurt, three or four and a graph is basically the only thing that works.</p><p>Hold onto that. It comes back at the end.</p><h3>The layer I didn’t know existed</h3><p>Up to here I’d been inventing edge names as I went. Then I learned that real systems define the vocabulary <strong>first</strong> — what types of things exist and what connections are allowed. That blueprint is called an <strong>ontology</strong>. It’s the empty form; your data is the filled-in forms.</p><p>I skipped this on my first build and paid for it stupidly. Letting the extraction step invent its own relationship names, I ended up with WORKS_AT, WORKS_FOR, EMPLOYED_BY, IS_EMPLOYEE_OF, and works at. Five edges, one meaning. Every query found a fifth of my data, and it took me two days to figure out why.</p><p>The graph looked <em>great</em> in the visualiser. It was useless.</p><p>Three words I’d been using interchangeably and now keep straight: a <strong>taxonomy</strong> is pure hierarchy (Animal → Mammal → Dog). An <strong>ontology</strong> is hierarchy plus relationships and rules. A <strong>knowledge graph</strong> is an ontology filled with real data. <em>Categories, rules, facts.</em></p><h3>Two flavours — don’t lose a day on this like I did</h3><p>Search “knowledge graph tutorial” and you’ll get two completely different-looking things. Nobody tells you they’re two schools of the same idea.</p><p><strong>RDF</strong> is the academic standard — everything is a triple with a global URL-style ID. It powers Wikidata and Google’s Knowledge Graph. Great for merging data across organisations, verbose to work with. Queried with SPARQL.</p><p><strong>Property graphs</strong> are the engineering approach — nodes and edges carry labels and properties directly. Intuitive, fast to build with. Queried with Cypher. Neo4j is the well-known one.</p><p>I lost a day trying to work out which was “correct.” Neither is. <strong>Use a property graph</strong>, move on, come back to RDF the day you actually need to merge with someone else’s data.</p><h3>Querying looks like a drawing</h3><p>Cypher genuinely looks like the pattern you’re searching for:</p><pre>MATCH (p:Person)-[:WORKS_AT]-&gt;(c:Company {name: &quot;Acme&quot;})<br>RETURN p.name</pre><p>You can see the arrow. Once you notice that, the syntax teaches itself.</p><p>I also spent a week asking “why not just use SQL?” You can — but each hop is another join, and joins get slower as your tables grow. A graph database stores each node’s neighbours as direct pointers, so traversal costs the same whether you have a hundred nodes or a hundred million.</p><p>Where I landed: few relationships and lots of aggregation, <strong>SQL wins, don’t build a graph</strong>. Three or more hops where the relationships <em>are</em> the point — that’s when a graph earns it.</p><h3>Where this lines up with RAG</h3><p>Here’s where my learning suddenly had a job to do.</p><p>I’d been building a RAG chatbot over the same wiki. It handled “what does the Vault service do?” fine and fell apart on “which of our systems came from an acquisition?”</p><p>Once I understood graphs, I could name the reason.</p><p>Vector search embeds your question and finds the chunks closest in meaning — and crucially, <strong>each chunk is scored on its own merits.</strong></p><p>That acquisition question needs two chunks cooperating: one saying <em>Acme acquired Bitway</em>, one saying <em>Nimbus was built by the Bitway team</em>. The first scores high. The second is mostly about payment processing and never says “acquisition,” so it doesn’t make the cut. The bot gets half the picture and confidently serves it.</p><p>It’s a <strong>two-hop question</strong>. The word I’d learned in week one turned out to be the diagnosis.</p><p>Same shape sits behind a whole family of failures. <em>How many services depend on Vault?</em> fails because the model can’t know what it wasn’t shown. <em>What are the themes in our incident reports?</em> fails because no single chunk holds the answer. <em>Which services have no owner?</em> fails because search finds text that matches, not text that’s missing.</p><p>All the same problem. <strong>Vector search finds passages. It doesn’t understand structure.</strong></p><p>They’re not competitors, which took me a while to accept. Vector search handles fuzzy human phrasing beautifully — a graph is hopeless at that. A graph handles exact connection, counting, and paths, and it can <em>show its work</em>. What actually works is both: vector search finds where in the graph to start, the graph walks out to gather connected facts, then you pull the original text behind those facts and hand the model everything.</p><p>That’s all GraphRAG means. Once I understood graphs, the buzzword became fairly obvious.</p><h3>The order I’d learn it in, if I started over</h3><p><strong>Start with the paper exercise, not a tutorial.</strong> Five sentences from something you know well. Thirty minutes, and you’ll get the point of the whole field. I did this in week two; it should have been hour one.</p><p><strong>Then learn to count hops.</strong> Take ten real questions from your own work and count the steps each needs. This tells you which problems are graph-shaped — and later, it explains every RAG failure you have.</p><p><strong>Then write your relationship list.</strong> Fifteen types chosen deliberately, before any code. This is the step everyone skips and the one that decides whether your graph is usable.</p><p><strong>Then build something tiny.</strong> A hundred nodes on a domain you know, small enough that you can spot when it’s wrong.</p><p><strong>And only then decide if you need one at all.</strong> Mostly one-hop lookups? A graph is overhead you’ll regret maintaining. Connections, counts, gaps, the shape of everything? Then it’s realistically your only option.</p><p>Three weeks in: knowledge graphs are much simpler than the vocabulary makes them sound, and more useful than I gave them credit for. The concepts fit on one page. The value is noticing which of your problems are actually shaped like a graph.</p><p>Next on my list is entity resolution — working out that “Rahul,” “Rahul Menon,” and “R. Menon” are one person is where most of the real work hides. That’ll be its own post.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2f82fd66edc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What I Wish I Knew Before Building Headless Sitecore with Next.js]]></title>
            <link>https://medium.com/@patelpriysnshu2410/what-i-wish-i-knew-before-building-headless-sitecore-with-next-js-79640e5468f2?source=rss-f05dad4b99f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/79640e5468f2</guid>
            <category><![CDATA[sitecore]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[sitecore-ai]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[xmcloude]]></category>
            <dc:creator><![CDATA[Priyanshu Patel]]></dc:creator>
            <pubDate>Tue, 09 Jun 2026 09:25:38 GMT</pubDate>
            <atom:updated>2026-06-09T09:25:38.985Z</atom:updated>
            <content:encoded><![CDATA[<p>Building headless Sitecore with Next.js has some real surprises — the kind you only hit when you’re actually in a project. Some things work differently than you’d expect, and some things fail silently without telling you why.</p><p>If you’re a Sitecore dev moving to headless or a Next.js dev starting a Sitecore project — here are the four things I wish I’d known earlier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q0UQG0zhk7yNgLgoKrafZw.png" /></figure><h3>1. The Layout Service response is bigger than you expect</h3><p>If you’ve worked with other headless CMSes like Contentful or Sanity, you’re used to calling an API and getting back exactly the fields you asked for.</p><p>Sitecore doesn’t work like that.</p><p>When you call the Layout Service, you get back the <strong>entire page</strong> — every component, every placeholder, every field, all nested inside one big JSON object. The whole thing lands in a script tag called __NEXT_DATA__ in your HTML. Next.js uses it to rehydrate the page on the client side.</p><p>Here’s the problem: on a page with a lot of components and content, this JSON can be <strong>more than half your total HTML size</strong>. I saw this firsthand and it wasn’t pretty.</p><p>A basic Layout Service response looks like this:</p><pre>{<br>  &quot;sitecore&quot;: {<br>    &quot;context&quot;: { ... },<br>    &quot;route&quot;: {<br>      &quot;name&quot;: &quot;home&quot;,<br>      &quot;placeholders&quot;: {<br>        &quot;jss-main&quot;: [<br>          {<br>            &quot;componentName&quot;: &quot;Hero&quot;,<br>            &quot;dataSource&quot;: &quot;{ABC123}&quot;,<br>            &quot;fields&quot;: {<br>              &quot;Heading&quot;: { &quot;value&quot;: &quot;Welcome&quot; },<br>              &quot;Image&quot;: { &quot;value&quot;: { &quot;src&quot;: &quot;/media/hero.jpg&quot; } }<br>            }<br>          },<br>          {<br>            &quot;componentName&quot;: &quot;PromoStrip&quot;,<br>            &quot;fields&quot;: { ... }<br>          }<br>        ]<br>      }<br>    }<br>  }<br>}</pre><p>That whole thing goes into __NEXT_DATA__. Add 15 components with images and rich text fields and you&#39;ll feel it.</p><p><strong>The fix:</strong> Don’t pass the raw layoutData object further than you need to. At the route level, only pass down what&#39;s actually used:</p><pre>// pages/[[...path]].tsx<br>export const getStaticProps: GetStaticProps = async (context) =&gt; {<br>  const layoutData = await layoutServiceFactory<br>    .create()<br>    .fetchLayoutData(path, language);</pre><pre>  if (!layoutData?.sitecore?.route) {<br>    return { notFound: true };<br>  }</pre><pre>  return {<br>    props: { layoutData },<br>    revalidate: 60,<br>  };<br>};</pre><p>Also worth knowing — XM Cloud serves Layout Service responses through Experience Edge, which is CDN-cached. So the size issue hits harder at build time or when using SSR, not on every user request. But it’s still worth keeping an eye on, especially if you hit Vercel’s function payload limits.</p><h3>2. Your component won’t render and there’s no error — here’s why</h3><p>This one got me good.</p><p>You build a component. You add it to a page in Sitecore. You refresh. Nothing shows up. No error in the console. No crash. Just an empty space where your component should be.</p><p>The reason: <strong>every JSS component has to be registered in the component factory</strong>. If it’s not registered, Sitecore simply skips it. Silently.</p><p>If you look closely at the page HTML you’ll find this:</p><pre>JSS component is missing React implementation. See /components/YourComponent.</pre><p>But you have to go looking for it — it won’t jump out at you.</p><p>Now here’s the part that trips people up on XM Cloud specifically. There are actually <strong>two component factories</strong>:</p><pre>import { componentFactory } from &#39;temp/componentFactory&#39;;<br>import { editingComponentFactory } from &#39;temp/editingComponentFactory&#39;;</pre><pre>&lt;SitecoreContext<br>  componentFactory={isEditing ? editingComponentFactory : componentFactory}<br>  layoutData={layoutData}<br>&gt;</pre><ul><li>componentFactory is for the live site — what real users see</li><li>editingComponentFactory is for Sitecore Pages — what authors see when they&#39;re editing</li></ul><p>They’re different because the editing version includes extra wrappers that make inline editing work. Use the wrong one in the wrong context and your components either won’t be editable or won’t render at all.</p><p>The good news: both factories are <strong>auto-generated</strong> by JSS from your /src/components folder. You don&#39;t manage them by hand. But you do need to make sure codegen runs before your build, especially in CI/CD:</p><pre># Run this before your build step — always<br>jss build</pre><p>One more thing: if you rename a component file, update the component name in the Sitecore rendering item too. They have to match exactly. A mismatch gives you the same silent failure.</p><h3>3. Stop prop drilling — useSitecoreContext has what you need</h3><p>In traditional Sitecore MVC you used Sitecore.Context to get things like the current language, page mode, or site name from anywhere in your code.</p><p>In JSS, that’s useSitecoreContext. It&#39;s a hook from @sitecore-jss/sitecore-jss-nextjs and it gives you access to everything Sitecore knows about the current page — without having to pass it down through props.</p><pre>import { useSitecoreContext } from &#39;@sitecore-jss/sitecore-jss-nextjs&#39;;</pre><pre>const MyComponent = () =&gt; {<br>  const { sitecoreContext } = useSitecoreContext();</pre><pre>  const isEditing = sitecoreContext.pageState === &#39;edit&#39;;<br>  const language = sitecoreContext.language;     // &#39;en&#39;, &#39;fr&#39;, etc.<br>  const siteName = sitecoreContext.site?.name;   // your site name<br>  const itemId = sitecoreContext.itemId;         // current page item ID</pre><pre>  return (<br>    &lt;div&gt;<br>      {isEditing &amp;&amp; &lt;p&gt;You are in edit mode&lt;/p&gt;}<br>    &lt;/div&gt;<br>  );<br>};</pre><p>The pageState field is the one I use most. It tells you whether you&#39;re in:</p><ul><li>&#39;normal&#39; — live delivery mode</li><li>&#39;edit&#39; — author is editing in Sitecore Pages</li><li>&#39;preview&#39; — author is previewing before publishing</li></ul><p>A simple example — disabling lazy loading in edit mode so authors can actually see components without scrolling to trigger them:</p><pre>const { sitecoreContext } = useSitecoreContext();<br>const isEditing = sitecoreContext.pageState === &#39;edit&#39;;</pre><pre>return (<br>  &lt;Image<br>    src={fields.Image?.value?.src}<br>    alt={fields.Image?.value?.alt}<br>    loading={isEditing ? &#39;eager&#39; : &#39;lazy&#39;}<br>  /&gt;<br>);</pre><p>One rule to know: this hook only works inside components that are wrapped by &lt;SitecoreContext&gt;. If you try to use it in a utility function or an API route, it&#39;ll return undefined. Keep it inside your component tree.</p><h3>4. There are three ways to fetch data — and they’re not interchangeable</h3><p>This confused me for longer than I’d like to admit. In XM Cloud + JSS, you’ll run into three different data fetching patterns. Each one exists for a reason, and picking the wrong one causes problems that are hard to trace.</p><p>Here’s how to think about them:</p><p><strong>Pattern 1 — Layout Service (use this for most things)</strong></p><p>This is the default. When a page loads, the Layout Service fetches all component data automatically and puts it into props.fields in each component. You don&#39;t write any fetch logic.</p><pre>const HeroBanner = ({ fields }: HeroBannerProps) =&gt; {<br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;{fields.Heading?.value}&lt;/h1&gt;<br>      &lt;p&gt;{fields.Description?.value}&lt;/p&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><pre>export default withDatasourceCheck()&lt;HeroBannerProps&gt;(HeroBanner);</pre><p>Use this for any component where the content is managed in Sitecore and linked to a datasource. That’s probably 80% of your components.</p><p>One thing to watch: if an author adds a component to a page but doesn’t set the datasource, fields will be undefined. The withDatasourceCheck() wrapper handles this in edit mode — it shows a helpful message to the author. In delivery mode, the component just won&#39;t render. Always wrap your components with it.</p><p><strong>Pattern 2 — Integrated GraphQL</strong></p><p>Sometimes a component needs data from multiple Sitecore items — like a “Related Articles” block that pulls the 3 latest posts. A single datasource won’t cut it.</p><p>That’s where Integrated GraphQL (IGQL) comes in. You write a GraphQL query on the rendering item in Sitecore. It runs server-side during the Layout Service request and the result gets merged into props.fields. No separate API call from the frontend.</p><pre>// The component receives extra data from the IGQL query alongside normal fields<br>const RelatedArticles = ({ fields }: RelatedArticlesProps) =&gt; {<br>  return (<br>    &lt;ul&gt;<br>      {fields.articles?.results.map((article) =&gt; (<br>        &lt;li key={article.id}&gt;{article.title?.value}&lt;/li&gt;<br>      ))}<br>    &lt;/ul&gt;<br>  );<br>};</pre><p>Use this when you need to aggregate data from multiple items but still want it included in the Layout Service response.</p><p>Watch out: IGQL is cached with the Layout Service response. If you need data that changes in real time, this won’t work for that.</p><p><strong>Pattern 3 — Connected GraphQL</strong></p><p>This is a direct GraphQL call from your Next.js component, using GetStaticComponentProps. It runs at build time for SSG or at request time for SSR.</p><pre>import { GetStaticComponentProps } from &#39;@sitecore-jss/sitecore-jss-nextjs&#39;;<br>import graphqlClientFactory from &#39;lib/graphql-client-factory&#39;;<br>import { gql } from &#39;graphql-request&#39;;</pre><pre>const PROMO_QUERY = gql`<br>  query PromoQuery($datasource: String!, $language: String!) {<br>    item(path: $datasource, language: $language) {<br>      promoTitle: field(name: &quot;Title&quot;) { value }<br>    }<br>  }<br>`;</pre><pre>export const getStaticProps: GetStaticComponentProps = async (<br>  rendering,<br>  layoutData<br>) =&gt; {<br>  const graphQLClient = graphqlClientFactory();<br>  const data = await graphQLClient.request(PROMO_QUERY, {<br>    datasource: rendering.dataSource,<br>    language: layoutData.sitecore.context.language,<br>  });<br>  return data;<br>};</pre><pre>const PromoBlock = ({ promo }: PromoBlockProps) =&gt; {<br>  return &lt;p&gt;{promo?.item?.promoTitle?.value}&lt;/p&gt;;<br>};</pre><p>Use this when you’re pulling from an external API, or when the query is too complex for IGQL.</p><p>The thing to be careful about: if this component lives on 200 pages, that’s 200 separate GraphQL calls at build time. Build times can spiral fast. Only use this pattern when you actually need it.</p><h3>Quick recap before you close this tab</h3><ul><li><strong>Layout Service JSON gets large</strong> — keep an eye on your __NEXT_DATA__ payload, especially on content-heavy pages</li><li><strong>Two component factories</strong> — componentFactory for delivery, editingComponentFactory for Pages. Codegen builds both. Keep component names in sync with Sitecore.</li><li><strong>useSitecoreContext</strong> — your go-to hook for language, site name, page state, and item ID. Use it instead of prop drilling.</li><li><strong>Three data patterns</strong> — Layout Service for standard component fields, IGQL for server-side aggregated queries, Connected GraphQL for external data or complex fetches.</li></ul><p>This is the first post in a series I’m writing as part of my Sitecore MVP journey.</p><p>If something here saved you time, I’d love to hear about it. Drop a comment or find me on LinkedIn.</p><p><em>Sitecore · XM Cloud · Next.js · JSS · Headless CMS · Web Development</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79640e5468f2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Forget Fine-Tuning: Why RAG is the Real Backbone of Enterprise AI]]></title>
            <link>https://medium.com/@patelpriysnshu2410/forget-fine-tuning-why-rag-is-the-real-backbone-of-enterprise-ai-1ccde8140287?source=rss-f05dad4b99f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ccde8140287</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[agentic-rag]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[rags]]></category>
            <dc:creator><![CDATA[Priyanshu Patel]]></dc:creator>
            <pubDate>Mon, 09 Mar 2026 06:16:56 GMT</pubDate>
            <atom:updated>2026-03-09T06:16:56.641Z</atom:updated>
            <content:encoded><![CDATA[<p>The biggest hurdle with Large Language Models (LLMs) isn’t their intelligence — it’s their memory.</p><p>If you’ve ever asked a model about a company’s private Q4 revenue or a specific internal HR policy, you’ve likely met the “Knowledge Cutoff” or, worse, a confident hallucination. This is where <strong>Retrieval-Augmented Generation (RAG)</strong> changes the game.</p><p>Instead of trying to teach an LLM everything during training, RAG gives the model an “open-book exam” capability. Here is a deep dive into the concepts, the architecture, and the code to build one.</p><h3>1. The Core Concepts: Parametric vs. Non-Parametric Knowledge</h3><p>To understand RAG, you have to understand how an LLM “knows” things:</p><ul><li><strong>Parametric Knowledge:</strong> This is what the model learned during training. It’s hard-coded into the neural network’s weights. It’s static and gets outdated the moment training ends.</li><li><strong>Non-Parametric Knowledge:</strong> This is external information — your PDFs, databases, and live docs.</li></ul><p><strong>RAG</strong> is the bridge between the two. It retrieves the most relevant snippets of non-parametric data and “augments” the prompt so the LLM can generate an answer based on real-time facts rather than its 2-year-old memory.</p><h3>2. The Architecture of a RAG Pipeline</h3><p>A production-grade RAG system isn’t just a prompt; it’s a data pipeline. The architecture is generally split into two distinct environments: the <strong>Storage Layer</strong> (where data lives) and the <strong>Retrieval Layer</strong> (where the magic happens).</p><h3>The High-Level Flow:</h3><ol><li><strong>The User Query:</strong> A user asks a question.</li><li><strong>The Retriever:</strong> The system searches a Vector Database for relevant context.</li><li><strong>The Augmentation:</strong> The query + the retrieved context are combined into a specialized prompt template.</li><li><strong>The Generator:</strong> The LLM reads the context and produces a grounded response.</li></ol><h3>3. Phase 1: The Indexing Phase (The Preparation)</h3><p>You cannot search raw text efficiently. Before your RAG system goes live, you must convert your documents into a searchable mathematical format.</p><h3>The Logic:</h3><ul><li><strong>Loading:</strong> Importing your source files.</li><li><strong>Chunking:</strong> LLMs have “context windows” (limits on how much text they can read). We break large files into smaller, overlapping “chunks” (e.g., 500 characters) to ensure we don’t lose context.</li><li><strong>Embedding:</strong> We use an embedding model to turn text into vectors — arrays of numbers that represent the <em>semantic meaning</em> of the words.</li><li><strong>Vector Store:</strong> These vectors are stored in specialized databases like <strong>ChromaDB</strong>, <strong>Pinecone</strong>, or <strong>FAISS</strong>.</li></ul><h3>Python Implementation:</h3><p>Python</p><pre>from langchain_community.document_loaders import PyPDFLoader<br>from langchain_text_splitters import RecursiveCharacterTextSplitter<br>from langchain_openai import OpenAIEmbeddings<br>from langchain_community.vectorstores import Chroma</pre><pre># 1. Load your document<br>loader = PyPDFLoader(&quot;company_handbook.pdf&quot;)<br>data = loader.load()</pre><pre># 2. Chunking (Standard practice: 1000 char chunks with 10% overlap)<br>text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=100)<br>chunks = text_splitter.split_documents(data)</pre><pre># 3. Vectorization and Storage<br># This converts text into vectors and saves them locally in ChromaDB<br>vector_db = Chroma.from_documents(<br>    documents=chunks, <br>    embedding=OpenAIEmbeddings(),<br>    persist_directory=&quot;./chroma_db&quot;<br>)</pre><h3>4. Phase 2: The Retrieval &amp; Generation Phase (The Execution)</h3><p>This is the “live” part of the app. When a user asks a question, we don’t send it to the LLM immediately.</p><h3>The Logic:</h3><ul><li><strong>Similarity Search:</strong> We turn the user’s question into a vector and find the “top 3” chunks in our database that are mathematically closest to it.</li><li><strong>Prompt Stuffing:</strong> We create a prompt that says: <em>“Using the following pieces of context, answer the question. If the answer isn’t in the context, say you don’t know.”</em></li></ul><h3>Python Implementation:</h3><p>Python</p><pre>from langchain_openai import ChatOpenAI<br>from langchain.chains import RetrievalQA</pre><pre># Initialize the LLM (GPT-4o or 3.5-turbo)<br>llm = ChatOpenAI(model_name=&quot;gpt-4o&quot;, temperature=0)</pre><pre># Create the chain that links the Vector DB to the LLM<br>rag_chain = RetrievalQA.from_chain_type(<br>    llm=llm,<br>    chain_type=&quot;stuff&quot;, # &quot;Stuff&quot; means we shove all retrieved chunks into the prompt<br>    retriever=vector_db.as_retriever()<br>)</pre><pre># Ask a specific question<br>response = rag_chain.invoke(&quot;What is the policy on maternity leave?&quot;)<br>print(response[&quot;result&quot;])</pre><h3>5. Why This Matters for Professionals</h3><p>If you are building for a client or a company, RAG is almost always superior to fine-tuning for three reasons:</p><ul><li><strong>Cost:</strong> Fine-tuning costs thousands in compute. RAG costs pennies in storage.</li><li><strong>Citations:</strong> RAG can tell you exactly <em>which</em> document it used to get an answer, making it auditable.</li><li><strong>No Retraining:</strong> If your policy changes tomorrow, you just delete one vector and add a new one. No retraining required.</li></ul><h3>Conclusion</h3><p>RAG turns an LLM from a creative writer into a reliable researcher. While the setup requires some heavy lifting in the data pipeline (Indexing), the result is a system that is accurate, up-to-date, and — most importantly — trustworthy.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ccde8140287" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Tokenization in Generative AI]]></title>
            <link>https://medium.com/@patelpriysnshu2410/understanding-tokenization-in-generative-ai-11d89268440e?source=rss-f05dad4b99f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/11d89268440e</guid>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[tokenization]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Priyanshu Patel]]></dc:creator>
            <pubDate>Mon, 24 Nov 2025 11:17:01 GMT</pubDate>
            <atom:updated>2025-11-24T11:17:01.252Z</atom:updated>
            <content:encoded><![CDATA[<p>Tokenization is one of those foundational ideas in AI that everyone relies on, but very few take the time to understand properly. Before any model interprets meaning, generates text, or performs reasoning, it first has to break your input into units it can actually work with. These units are called <strong>tokens</strong>, and they quietly shape everything — from the cost of using an API to the quality of the model’s output.</p><p>This write‑up aims to explain tokenization in a straightforward, human way without unnecessary jargon.</p><h3>What We Actually Mean by “Tokens”</h3><p>A token isn’t the same thing as a word. Sometimes a whole word becomes a single token, but often it doesn’t. Models split text into chunks based on patterns they learned during training. Those chunks might be full words, partial words, or even punctuation marks.</p><p>For instance, a short sentence like:</p><p>Learning AI is fun.</p><p>might be split into several smaller pieces rather than word‑by‑word. The model assigns each piece a numeric ID. It never really “sees” the text — it only works with those numbers.</p><h3>Why This Splitting Is Necessary</h3><p>Modern language models don’t read characters or words directly. They depend on statistical patterns, and those patterns are learned from vast amounts of text that have already been tokenized. Tokenization keeps the vocabulary manageable and allows models to generalize across spelling variations, uncommon terms, and multiple languages.</p><p>If models had to treat every full word as a separate unit, the vocabulary would explode into the billions. Splitting words into smaller pieces solves that problem.</p><h3>The Myth of “One Word = One Token”</h3><p>This assumption causes a lot of confusion. A simple word like “cat” may be one token, but “cats” may become two. Rare words or longer terms may break into several fragments. Even names — especially those not common in English datasets — tend to split.</p><p>This matters because models charge per token and also have a maximum token capacity. Word count means very little compared to token count.</p><h3>How Tokenizers Actually Work</h3><p>Most LLMs today use one of two systems:</p><h3>Byte Pair Encoding (BPE)</h3><p>Used in GPT models, LLaMA and several others. It starts by treating every character separately and repeatedly merges frequently occurring pairs. Over time, these merges form the vocabulary.</p><h3>Sentence Piece</h3><p>Used widely in multilingual models. Instead of assuming that words are separated by spaces, it treats the entire text stream uniformly. This is especially useful for languages like Japanese or Chinese.</p><p>Both approaches aim for the same thing: efficiently breaking text into pieces that are meaningful enough for the model to understand, yet compact enough to keep the vocabulary from becoming enormous.</p><h3>Why Tokenization Matters in Practice</h3><p>It affects more than people assume:</p><ul><li><strong>Cost</strong>: Models bill based on tokens, not words.</li><li><strong>Speed</strong>: More tokens slow down processing.</li><li><strong>Context limits</strong>: Models can only handle a certain number of tokens at once.</li><li><strong>Understanding</strong>: If a word breaks into fragments the model rarely sees, its interpretation may weaken.</li></ul><p>If you’re working with prompts regularly, knowing how tokenization behaves can help you write more efficient and more precise instructions.</p><h3>A Simple Way to See Tokenization Yourself</h3><p>One of the easiest tools to experiment with is <a href="https://tiktokenizer.vercel.app/"><strong>https://tiktokenizer.vercel.app/</strong></a>. You paste text, and it shows how a tokenizer breaks it apart and how many tokens it produces. It’s a helpful way to understand how models perceive your input.</p><h3>Trying It Programmatically (Python Example)</h3><p>Below is a small script that demonstrates how GPT‑style tokenizers break text into tokens and reconstruct it:</p><pre>import tiktoken</pre><pre>model_name = &quot;gpt-3.5-turbo&quot;<br>tokenizer = tiktoken.encoding_for_model(model_name)</pre><pre># Example 1: Simple sentence<br>tokens_1 = tokenizer.encode(&quot;Hello, how are you?&quot;)<br>print(tokens_1)</pre><pre># Example 2: Name tokenization<br>tokens_2 = tokenizer.encode(&quot;Priyanshu Patel&quot;)<br>print(tokens_2)</pre><pre># Example 3: Decoding tokens<br>decoded = tokenizer.decode([88, 598])<br>print(decoded)</pre><p>Running this gives you a realistic sense of how much text actually costs in terms of tokens, and why certain names or rare words break into several pieces.</p><h3>Closing Thoughts</h3><p>Tokenization is often treated as a low‑level technical detail, but it quietly influences almost every interaction with a generative model. Understanding how text is split, and why, makes you better at prompt design, cost optimization, and debugging model responses. It’s a small concept with an outsized impact on how modern AI systems function.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=11d89268440e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ From Zero to Production: Deploying a Secure Go API with Gin, GORM, and JWT Auth (2025 Guide)]]></title>
            <link>https://medium.com/@patelpriysnshu2410/from-zero-to-production-deploying-a-secure-go-api-with-gin-gorm-and-jwt-auth-2025-guide-6aa733d68ff7?source=rss-f05dad4b99f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/6aa733d68ff7</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[gorm]]></category>
            <category><![CDATA[gin]]></category>
            <dc:creator><![CDATA[Priyanshu Patel]]></dc:creator>
            <pubDate>Mon, 07 Jul 2025 04:59:10 GMT</pubDate>
            <atom:updated>2025-07-07T04:59:10.982Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Go + Gin is like espresso for backend devs — fast, clean, and keeps your brain awake at 2 AM. Here’s exactly how I built a secure, production-ready REST API, with practical examples and tips I wish someone told me earlier.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ezGcEc-HZW4_phkymTRlqg.png" /></figure><h3>✅ Why Gin &amp; GORM Still Matter</h3><p>Gin: blazing fast router with powerful middleware.<br>GORM: simple but powerful ORM.<br>JWT: stateless, secure auth — no cookie mess.<br>Hot reload with Air: saves your sanity.</p><h3>⚡️ What I Used</h3><ul><li><strong>Gin</strong> — Web framework</li><li><strong>GORM</strong> + <a href="https://github.com/glebarez/sqlite">glebarez/sqlite</a> — Pure Go DB driver</li><li><strong>JWT</strong> (<a href="https://github.com/golang-jwt/jwt">golang-jwt/jwt/v5</a>)</li><li><strong>bcrypt</strong> — Secure password hashing</li><li><strong>Air</strong> (<a href="https://github.com/air-verse/air">air-verse/air</a>) — Instant reloads</li></ul><p>✅ <em>Pro Tip: </em><em>glebarez/sqlite removes CGO headaches. Great for static builds and Docker.</em></p><h3>🚦 Quick Setup &amp; Hot Reload</h3><pre>go mod init github.com/you/yourapp<br>go get github.com/gin-gonic/gin<br>go get github.com/glebarez/sqlite<br>go get github.com/golang-jwt/jwt/v5<br>go get golang.org/x/crypto/bcrypt<br>go install github.com/air-verse/air@latest</pre><p>Run with:</p><pre>air</pre><p>✅ Your API restarts automatically on file save. Love it.</p><h3>🗂️ Example: Hello World API</h3><pre>r := gin.Default()<br>r.GET(&quot;/hello&quot;, func(c *gin.Context) {<br>  c.JSON(200, gin.H{&quot;message&quot;: &quot;Hello, Gin!&quot;})<br>})<br>r.Run() // http://localhost:8080/hello</pre><h3>🔑 Example: JWT Auth Flow</h3><pre>import (<br>  &quot;github.com/golang-jwt/jwt/v5&quot;<br>  &quot;time&quot;<br>)</pre><pre>claims := jwt.RegisteredClaims{<br>  Subject: &quot;user-id-123&quot;,<br>  ExpiresAt: jwt.NewNumericDate(time.Now().Add(30 * time.Minute)),<br>}<br>token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)<br>signed, _ := token.SignedString([]byte(&quot;super_secret&quot;))</pre><p>Middleware example:</p><pre>func AuthRequired() gin.HandlerFunc {<br>  return func(c *gin.Context) {<br>    authHeader := c.GetHeader(&quot;Authorization&quot;)<br>    if authHeader == &quot;&quot; {<br>      c.AbortWithStatusJSON(401, gin.H{&quot;error&quot;: &quot;Missing token&quot;})<br>      return<br>    }<br>    tokenStr := strings.TrimPrefix(authHeader, &quot;Bearer &quot;)<br>    claims := &amp;jwt.RegisteredClaims{}<br>    token, err := jwt.ParseWithClaims(tokenStr, claims, func(t *jwt.Token) (interface{}, error) {<br>      return []byte(&quot;super_secret&quot;), nil<br>    })<br>    if err != nil || !token.Valid {<br>      c.AbortWithStatusJSON(401, gin.H{&quot;error&quot;: &quot;Invalid token&quot;})<br>      return<br>    }<br>    c.Set(&quot;userID&quot;, claims.Subject)<br>    c.Next()<br>  }<br>}</pre><h3>⚙️ GORM + SQLite Example</h3><pre>import (<br>  &quot;gorm.io/gorm&quot;<br>  &quot;github.com/glebarez/sqlite&quot;<br>)</pre><pre>db, err := gorm.Open(sqlite.Open(&quot;app.db&quot;), &amp;gorm.Config{})<br>if err != nil {<br>  panic(err)<br>}</pre><pre>type User struct {<br>  gorm.Model<br>  Name  string<br>  Email string `gorm:&quot;unique&quot;`<br>  Password string<br>}</pre><pre>db.AutoMigrate(&amp;User{})</pre><p>✅ Tip: Switch to Postgres for production scale. GORM makes it easy.</p><h3>🧪 Tiny Test Example</h3><pre>w := httptest.NewRecorder()<br>req, _ := http.NewRequest(&quot;GET&quot;, &quot;/hello&quot;, nil)<br>r.ServeHTTP(w, req)<br>fmt.Println(w.Body.String()) // {&quot;message&quot;:&quot;Hello, Gin!&quot;}</pre><p>✅ Use testify for clean asserts.</p><h3>🗝️ Production Pointers</h3><ul><li><strong>Secrets:</strong> Use .env or viper — no plain text keys in Git!</li><li><strong>CGO:</strong> Save time with glebarez/sqlite — zero CGO pain.</li><li><strong>Reload:</strong> Air forever. Live reload = dev happiness.</li><li><strong>JWT:</strong> Short expiry, refresh tokens if needed.</li><li><strong>Tests:</strong> Save your future self from debugging 3AM errors.</li></ul><h3>🚀 Ready to Deploy</h3><p>✅ Render, Railway, or Fly.io — all simple.<br> ✅ Use static builds if you ditch CGO.<br> ✅ Add NGINX or Caddy for HTTPS.<br> ✅ Rate limit before you get DDoSed by bots — they <em>will</em> come.</p><h3>📚 Must-Visit Docs</h3><ul><li><a href="https://gin-gonic.com/docs/">Gin</a></li><li><a href="https://gorm.io/docs/">GORM</a></li><li><a href="https://github.com/air-verse/air">Air</a></li><li><a href="https://github.com/glebarez/sqlite">glebarez/sqlite</a></li></ul><h3>🎉 Final Thoughts</h3><p><strong>This was my ride from “Go basics” to “Production-ready API.”</strong><br> If you learned something, share it — or break prod safely!<br> Got questions? Ping me. Now go ship something awesome. ☕️🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6aa733d68ff7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Redux vs Zustand vs React’s New useSignal: Who Rules the Future?]]></title>
            <link>https://medium.com/@patelpriysnshu2410/redux-vs-zustand-vs-reacts-new-usesignal-who-rules-the-future-fba41fb77291?source=rss-f05dad4b99f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/fba41fb77291</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[frontend-development]]></category>
            <category><![CDATA[zustand]]></category>
            <category><![CDATA[redux]]></category>
            <dc:creator><![CDATA[Priyanshu Patel]]></dc:creator>
            <pubDate>Tue, 24 Jun 2025 05:54:21 GMT</pubDate>
            <atom:updated>2025-06-24T06:12:50.400Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>When it comes to managing global state in React apps, are we sticking with the old, leaning into the lightweight, or waiting for the native magic?</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hmK5n9UttLs_XkllgjcRqQ.png" /></figure><h3>📝 Introduction</h3><p>React has come a long way from when useState and useEffect were the only tools in your belt. As applications grow, managing shared state between components becomes one of the most important architectural decisions you’ll make.</p><p>For years, <strong>Redux</strong> has been the go-to global state manager. But modern solutions like <strong>Zustand</strong> offer a lighter and more flexible alternative. And now, with React 19 around the corner, there’s buzz about a <strong>native global state API</strong> called useSignal.</p><p>In this blog, we’ll compare all three with practical insights:</p><ul><li>✅ Setup experience</li><li>🔁 State sharing and subscriptions</li><li>⚖️ Performance and DX (Developer Experience)</li><li>🔮 What the future might hold</li></ul><h3>🔴 Redux — The Classic State Management Giant</h3><p>Redux is the most widely known state manager in the React ecosystem. While its verbose syntax may scare newcomers, Redux still holds strong in many enterprise applications.</p><p>Here’s what modern Redux (with Redux Toolkit) looks like:</p><pre>// store/authSlice.js<br>import { createSlice } from &#39;@reduxjs/toolkit&#39;;</pre><pre>const authSlice = createSlice({<br>  name: &#39;auth&#39;,<br>  initialState: { isLoggedIn: false },<br>  reducers: {<br>    login: (state) =&gt; { state.isLoggedIn = true },<br>    logout: (state) =&gt; { state.isLoggedIn = false }<br>  }<br>});</pre><pre>export const { login, logout } = authSlice.actions;<br>export default authSlice.reducer;</pre><p>Usage in a component:</p><pre>import { useSelector, useDispatch } from &#39;react-redux&#39;;</pre><pre>const isLoggedIn = useSelector((state) =&gt; state.auth.isLoggedIn);<br>const dispatch = useDispatch();</pre><h3>✅ Why You Might Use Redux</h3><ul><li>Well-structured for large-scale apps</li><li>Powerful middleware support</li><li>Time-travel debugging via DevTools</li><li>Strong TypeScript integration</li></ul><h3>❌ Downsides</h3><ul><li>Requires boilerplate</li><li>Slight learning curve</li><li>Can be overkill for small/medium apps</li></ul><h3>🟠 Zustand — Lightweight, Hook-Based State That Just Works</h3><p>Zustand (German for “state”) is a <strong>minimal, hook-based global state manager</strong> that feels like native React.</p><h3>🔧 Simple Setup</h3><pre>// store/useTaskStore.js<br>import { create } from &#39;zustand&#39;;</pre><pre>export const useTaskStore = create((set) =&gt; ({<br>  tasks: [],<br>  addTask: (task) =&gt;<br>    set((state) =&gt; ({ tasks: [...state.tasks, task] })),<br>}));</pre><p>Usage in a component:</p><pre>const tasks = useTaskStore((state) =&gt; state.tasks);<br>const addTask = useTaskStore((state) =&gt; state.addTask);</pre><h3>✅ Why Developers Love Zustand</h3><ul><li>Minimal API and zero boilerplate</li><li>No context or provider required</li><li>Hook-based and idiomatic to React</li><li>Scales easily with middleware if needed</li></ul><h3>❌ Downsides</h3><ul><li>Less structured (can lead to inconsistency)</li><li>Middleware requires manual setup</li></ul><h3>📂 React’s Upcoming Native Global State — useSignal() (Experimental)</h3><p>React 19 introduces an experimental API called useSignal() — a <strong>reactive, shared state primitive</strong> that doesn’t need Redux, Zustand, or even Context.</p><p>Here’s a simplified example:</p><pre>import { useSignal } from &#39;react&#39;;</pre><pre>const counter = useSignal(0);</pre><pre>function IncrementButton() {<br>  return &lt;button onClick={() =&gt; counter.value++}&gt;+&lt;/button&gt;;<br>}</pre><pre>function DisplayCounter() {<br>  return &lt;p&gt;{counter.value}&lt;/p&gt;; // auto re-renders when value changes<br>}</pre><p>Each component <strong>automatically re-renders</strong> when the signal.value changes. It’s reactive and magical.</p><h3>⚠️ Caveats</h3><ul><li>Only available in <strong>React Canary builds</strong></li><li>Not stable or recommended for production</li><li>Needs React’s new compiler (not available yet)</li></ul><p>Still, it’s a strong signal (pun intended!) of where React might be headed.</p><h3>⚖️ Side-by-Side Comparison</h3><p>Feature <strong>Redux</strong> <strong>Zustand</strong> <strong>React </strong><strong>useSignal()</strong> Boilerplate High Low None Learning Curve Moderate Easy Very Easy Middleware Support ✅ Built-in 🔧 Custom ❌ Not applicable Requires Context ✅ Yes ❌ No ❌ No Auto Subscriptions ❌ Manual ✅ Yes ✅ Yes Prod-Ready ✅ Yes ✅ Yes ❌ Not yet</p><h3>🧪 My Own Project Setup</h3><p>In one of my recent demo projects, I tried combining all three in one app:</p><ul><li>🔐 <strong>Redux</strong> for authentication</li><li>✅ <strong>Zustand</strong> for task list</li><li>🎨 <strong>React Signals</strong> (via Preact) for theme toggle</li></ul><p>Each had a role — and surprisingly, they worked well together!</p><h3>🔮 What’s the Future of State in React?</h3><p>React’s useSignal() is an exciting sign of what’s coming:</p><ul><li>No external libraries</li><li>Automatic reactivity</li><li>Built-in subscriptions</li><li>Simpler mental model</li></ul><p>If fully released and adopted, it could <strong>reduce the need for external tools</strong> in simple to medium-sized apps.</p><p>However, that doesn’t mean Redux or Zustand will die:</p><ul><li>Redux will remain relevant for <strong>complex flows, async logic, and DevOps needs</strong>.</li><li>Zustand is here to stay as the go-to for <strong>fast and flexible state management</strong>.</li></ul><h3>💡 Final Thoughts</h3><p>You don’t have to choose one and stick to it forever.</p><p>Pick the right state manager based on your <strong>project size</strong>, <strong>team comfort</strong>, and <strong>complexity needs</strong>:</p><ul><li>Use <strong>Redux</strong> when structure, scale, and middleware matter.</li><li>Use <strong>Zustand</strong> when you want clean, modern state management without the ceremony.</li><li>Watch for <strong>React Signals</strong> — they may just reshape how we write stateful apps in the future.</li></ul><h3>💬 What’s Your Take?</h3><p>What state manager do you use today in your React apps?</p><p>Would you consider migrating to useSignal() once it’s stable?</p><p>Let me know in the comments — I’d love to hear your thoughts!</p><p>✅ <em>If this helped, clap it up and share with fellow devs.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fba41fb77291" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Building Your Own Modular Conceptual Processor (MCP) Server with Multi-Tool Chaining]]></title>
            <link>https://medium.com/@patelpriysnshu2410/building-your-own-modular-conceptual-processor-mcp-server-with-multi-tool-chaining-41196383f457?source=rss-f05dad4b99f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/41196383f457</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[mcp-protocol]]></category>
            <category><![CDATA[mcp-server]]></category>
            <dc:creator><![CDATA[Priyanshu Patel]]></dc:creator>
            <pubDate>Sat, 14 Jun 2025 09:17:15 GMT</pubDate>
            <atom:updated>2025-06-14T09:17:15.367Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>A hands-on guide to building an AI agent that can think, decide, and execute real-world tasks using multiple tools — all running from your local Node.js server.</em></blockquote><h3>🚀 What is an MCP Server?</h3><p>An <strong>MCP (Modular Conceptual Processor)</strong> is a local or hosted AI agent server that processes natural language input, reasons about it, and dynamically uses tools like calculators, web search, clocks, and more to fulfill complex tasks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1EB03NcJaml0pP7uIOmegg.png" /></figure><h3>Why the Hype?</h3><p>With the rise of AI agents and autonomous systems, MCPs are becoming the <strong>backbone of modern LLM-based workflows</strong>. The idea of not just chatting with an LLM but giving it the <strong>power to think and act</strong> using tools is unlocking massive possibilities:</p><ul><li>🧩 <strong>Composable AI agents</strong> for different domains</li><li>⚙️ <strong>Enterprise workflows</strong> with decision + execution</li><li>🚀 Inspiration behind big projects like AutoGPT, LangChain, and Devin</li></ul><p>MCP isn’t just another server. It’s a <strong>mental model for AI thinking</strong> — how humans solve problems using tools, memory, and logic. And now you can build your own.</p><h3>🧠 Imagine This:</h3><blockquote><em>You ask your agent: </em>“What is 25*4 and the current time?”</blockquote><p>The agent doesn’t just pass this to GPT blindly. It:</p><ol><li><strong>Breaks the query</strong> into sub-tasks.</li><li><strong>Executes tools</strong> (calculator, clock).</li><li><strong>Composes a final answer</strong> with logic.</li></ol><p>This is the core idea of an MCP — <strong>reasoning + tools + language</strong>.</p><h3>🏗️ Architecture Overview</h3><pre>User → MCP Server → [ Tool Decider (LLM) ] → [Tool 1, Tool 2, ...] → Final Answer</pre><ul><li><strong>Express.js</strong>: Handles routes &amp; JSON input</li><li><strong>OpenRouter/GPT-3.5</strong>: Decides tools &amp; answers</li><li><strong>Tools (custom)</strong>: calculator, getTime, webSearch, etc.</li><li><strong>File-based memory</strong>: memory.json stores per-user history</li></ul><h3>🧰 Tools You’ll Build</h3><p>Each tool follows a contract:</p><pre>{<br>  name: &#39;toolName&#39;,<br>  run: async (input) =&gt; string<br>}</pre><h3>Examples:</h3><ul><li>calculator(&quot;12 * 3&quot;) → 36</li><li>getTime() → &quot;⏰ 2:40 PM&quot;</li><li>webSearch(&quot;Elon Musk age&quot;) → top 3 results</li></ul><h3>🤖 AI-Driven Tool Selection</h3><p>Instead of hardcoding which tool to use, you delegate that to GPT:</p><pre>[<br>  { &quot;tool&quot;: &quot;calculator&quot;, &quot;input&quot;: &quot;25 * 4&quot; },<br>  { &quot;tool&quot;: &quot;time&quot; }<br>]</pre><p>This is done using a simple system prompt:</p><blockquote>“Given a user message, output a JSON array of tools to use.”</blockquote><p>It allows complex task orchestration without writing custom if/else logic.</p><h3>🔁 Multi-Tool Chaining: A Working Example</h3><pre>{<br>  &quot;input&quot;: &quot;Find Elon Musk&#39;s age and multiply it by 2.&quot;<br>}</pre><p>The chain would look like:</p><pre>[<br>  { &quot;tool&quot;: &quot;webSearch&quot;, &quot;input&quot;: &quot;Elon Musk age&quot; },<br>  { &quot;tool&quot;: &quot;calculator&quot;, &quot;input&quot;: &quot;52 * 2&quot; }<br>]</pre><p>Each step stores its result in memory, and the final answer includes it all.</p><h3>💾 Memory for Contextual Thinking</h3><p>Each user has:</p><pre>{<br>  &quot;user&quot;: &quot;priyanshu&quot;,<br>  &quot;memory&quot;: [<br>    { &quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;What’s the time?&quot; },<br>    { &quot;role&quot;: &quot;assistant&quot;, &quot;content&quot;: &quot;⏰ 2:45 PM&quot; }<br>  ]<br>}</pre><p>This allows the agent to remember past tool responses and build better answers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ASRn1bUWqPRRUf40ncG68w.png" /></figure><h3>📁 Folder Structure</h3><pre>mcp-server/<br>│<br>├── index.js              ← Express server<br>├── tool-decider.js       ← GPT-based tool planner<br>└── tools/<br>    └── index.js          ← Calculator, Date, Time, WebSearch</pre><p>🧩 Complete Code: Multi-Tool Chaining MCP Server (Node.js)</p><p>Below is the full implementation of a <strong>Modular Conceptual Processor (MCP)</strong> server built with Node.js and Express. This version supports <strong>multi-tool chaining</strong>, where an LLM decides which tools to run and in what order, then executes them sequentially before generating the final response.</p><pre>// index.js<br><br>require(&#39;dotenv&#39;).config();<br>const express = require(&#39;express&#39;);<br>const axios   = require(&#39;axios&#39;);<br>const fs      = require(&#39;fs-extra&#39;);<br><br>const decideToolChain = require(&#39;./tool-decider&#39;);<br>const { tools }       = require(&#39;./tools&#39;);<br><br>const app = express();<br>app.use(express.json());<br><br>const CONTEXT_FILE = &#39;memory.json&#39;;<br>let contextStore = fs.existsSync(CONTEXT_FILE)<br>  ? fs.readJsonSync(CONTEXT_FILE)<br>  : {};<br><br>const saveContext = () =&gt;<br>  fs.writeJsonSync(CONTEXT_FILE, contextStore, { spaces: 2 });<br><br>/* ------------ MAIN ENDPOINT ------------ */<br>app.post(&#39;/mcp&#39;, async (req, res) =&gt; {<br>  const { model = &#39;openai/gpt-3.5-turbo&#39;, context = {}, input } = req.body;<br>  const username = context.user || &#39;default&#39;;<br><br>  // 🧠 Initialize user memory<br>  if (!contextStore[username])<br>    contextStore[username] = { memory: [], lastUsed: Date.now() };<br>  const userMemory = contextStore[username].memory;<br><br>  userMemory.push({ role: &#39;user&#39;, content: input });<br><br>  /* --- 1. Ask GPT for a tool chain --- */<br>  const toolChain = await decideToolChain(input); // [{ tool, input }]<br><br>  /* --- 2. Execute tools in sequence --- */<br>  for (const step of toolChain) {<br>    const { tool: toolName, input: toolInput = &#39;&#39; } = step;<br>    const tool = tools[toolName];<br>    if (!tool) continue; // Skip unknown tools<br><br>    try {<br>      const result = await tool.run(toolInput || input);<br>      userMemory.push({<br>        role: &#39;assistant&#39;,<br>        content: `🔧 [${toolName}] → ${result}`<br>      });<br>    } catch (err) {<br>      userMemory.push({<br>        role: &#39;assistant&#39;,<br>        content: `❌ [${toolName}] failed: ${err.message}`<br>      });<br>    }<br>  }<br><br>  /* --- 3. Final answer generation --- */<br>  try {<br>    const chatResp = await axios.post(<br>      &#39;https://openrouter.ai/api/v1/chat/completions&#39;,<br>      {<br>        model,<br>        messages: [<br>          { role: &#39;system&#39;, content: &#39;You are a helpful AI agent.&#39; },<br>          ...userMemory<br>        ]<br>      },<br>      {<br>        headers: {<br>          Authorization: `Bearer ${process.env.OPENROUTER_API_KEY}`,<br>          &#39;Content-Type&#39;: &#39;application/json&#39;<br>        }<br>      }<br>    );<br><br>    const finalAnswer = chatResp.data.choices[0].message.content;<br>    userMemory.push({ role: &#39;assistant&#39;, content: finalAnswer });<br><br>    contextStore[username].lastUsed = Date.now();<br>    saveContext();<br><br>    res.json({<br>      toolChain,<br>      answer: finalAnswer,<br>      updatedContext: contextStore[username]<br>    });<br>  } catch (err) {<br>    console.error(err.response?.data || err.message);<br>    res.status(500).json({ error: &#39;Model call failed&#39; });<br>  }<br>});<br><br>app.listen(3000, () =&gt;<br>  console.log(&#39;✅ MCP server with multi-tool chaining on http://localhost:3000&#39;)<br>);</pre><h3>✨ Final Features</h3><p>✅ Memory-per-user<br> ✅ Tool plugin architecture<br> ✅ AI-decided tool chains<br> ✅ Sequential execution<br> ✅ Final model response synthesis</p><h3>🌍 Why This Matters</h3><p>Building an MCP agent helps you:</p><ul><li>Understand <strong>agentic architectures</strong></li><li>Learn how LLMs <strong>reason and plan</strong></li><li>Combine traditional tools with <strong>modern AI APIs</strong></li></ul><p>This isn’t just a toy project. It’s the foundation of next-gen agents.</p><h3>💡 Want More?</h3><p>Here’s how you can extend it:</p><ul><li>🌦️ Weather tool using OpenWeatherMap</li><li>💬 Stream responses from GPT</li><li>📚 Save &amp; load full conversations</li><li>🧠 Auto-memory summarization</li></ul><h3>📝 Final Thoughts</h3><p>You’ve just built a micro-agent server that can:</p><ul><li>Plan tasks</li><li>Call tools</li><li>Compose intelligent answers</li></ul><p>This is <strong>not ChatGPT</strong>. This is <strong>your GPT</strong> — extensible, agentic, local.</p><p>And as the AI space moves towards <strong>autonomous reasoning and modular execution</strong>, MCP-style agents will play a huge role in powering the next generation of intelligent apps, assistants, and bots.</p><p>Ready to make your own Siri, Jarvis, or enterprise bot?<br> <strong>This is where it starts.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=41196383f457" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Squashing the “Outdated Prisma Client” Error — A Practical Guide to Deploying Next.js]]></title>
            <link>https://medium.com/@patelpriysnshu2410/squashing-the-outdated-prisma-client-error-a-practical-guide-to-deploying-next-js-89e1e7c01d2c?source=rss-f05dad4b99f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/89e1e7c01d2c</guid>
            <category><![CDATA[vercel]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Priyanshu Patel]]></dc:creator>
            <pubDate>Fri, 06 Jun 2025 06:47:09 GMT</pubDate>
            <atom:updated>2025-06-06T06:47:09.770Z</atom:updated>
            <content:encoded><![CDATA[<h3>Squashing the “Outdated Prisma Client” Error — A Practical Guide to Deploying Next.js + Prisma on Vercel (2025)</h3><blockquote><em>“Prisma has detected that this project was built on Vercel, which caches dependencies. This leads to an outdated Prisma Client because Prisma’s auto‑generation isn’t triggered …”</em></blockquote><p>If this message has gate‑crashed your production deployment, you’re in the right place. In this post I’ll walk you through <strong>why</strong> it happens and the <strong>exact steps</strong> to fix it, based on my own battle with a Next.js / Prisma stack on Vercel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-EKBCuNhpxbamjr4DF8veg.png" /></figure><h3>TL;DR</h3><ol><li><strong>Run </strong><strong>prisma generate during every build.</strong></li><li><strong>Set your environment variables correctly inside Vercel’s dashboard (not just in </strong><strong>.env).</strong></li><li><strong>(Optional) Automate database migrations with </strong><strong>prisma migrate deploy.</strong></li></ol><p>That’s ‑‑ mostly ‑‑ it. Keep reading for the full story, code samples, and a checklist you can paste straight into your own project.</p><h3>The Baseline Setup</h3><h3>schema.prisma</h3><pre>// prisma/schema.prisma</pre><pre>generator client {<br>  provider = &quot;prisma-client-js&quot;<br>}</pre><pre>datasource db {<br>  provider = &quot;postgresql&quot;<br>  url      = env(&quot;DATABASE_URL&quot;)<br>}</pre><pre>model User {<br>  id        Int      @id @default(autoincrement())<br>  name      String?<br>  email     String   @unique<br>  password  String<br>  posts     Post[]   @relation(&quot;UserPosts&quot;)<br>  createdAt DateTime @default(now())<br>}</pre><pre>model Post {<br>  id        Int      @id @default(autoincrement())<br>  title     String<br>  content   String?<br>  createdAt DateTime @default(now())<br>  userId    Int<br>  user      User     @relation(&quot;UserPosts&quot;, fields: [userId], references: [id])<br>}</pre><h3>Example .env</h3><pre># Never commit real credentials. Use   *** PLACEHOLDER VALUES ***<br>DATABASE_URL=&quot;postgresql://USER:PASSWORD@HOST:PORT/DATABASE?sslmode=require&quot;<br>NEXT_PUBLIC_BASE_URL=&quot;https://your‑awesome‑app.vercel.app&quot;</pre><blockquote><strong><em>Remember:</em></strong><em> Add the same keys in </em><strong><em>Vercel → Project Settings → Environment Variables</em></strong><em>. Values defined only in local </em><em>.env files are invisible to the Vercel build machine.</em></blockquote><h3>The Problem: Vercel’s Dependency Cache</h3><p>Vercel optimises build times by caching node_modules. Unfortunately that means <strong>Prisma Client may not be regenerated</strong> if nothing else changes, leading to a binary mismatch between the generated client and the Node runtime used in the serverless functions. Prisma detects this and throws the error at the top of this post. (<a href="https://www.prisma.io/docs/orm/more/help-and-troubleshooting/vercel-caching-issue?utm_source=chatgpt.com">prisma.io</a>)</p><h3>Reproducing the Error (So You Know It When You See It)</h3><ol><li>Push a commit that changes your schema.prisma but <strong>does not</strong> touch package.json or clear the lockfile.</li><li>Deploy on Vercel.</li><li>Watch the build logs implode with:</li></ol><pre>Prisma has detected that this project was built on Vercel…</pre><h3>The Fix: Force prisma generate in the Build Step</h3><h3>1 — Override the Build Command</h3><p>In <strong>Vercel → Project Settings → Build &amp; Development Settings</strong> set <strong>Build Command</strong> to:</p><pre>npx prisma generate &amp;&amp; next build</pre><p>This guarantees that Prisma regenerates its client before Next.js compiles. (<a href="https://community.vercel.com/t/prisma-problem/2474?utm_source=chatgpt.com">community.vercel.com</a>)</p><h3>2 — Or, Use a Dedicated Script</h3><p>Some teams prefer a single script in package.json:</p><pre>&quot;scripts&quot;: {<br>  &quot;vercel-build&quot;: &quot;prisma generate &amp;&amp; next build&quot;<br>}</pre><p>Then set the Build Command in Vercel to npm run vercel-build (or pnpm run, yarn run, etc.). (<a href="https://www.prisma.io/docs/orm/prisma-client/deployment/serverless/deploy-to-vercel?utm_source=chatgpt.com">prisma.io</a>)</p><h3>3 — Keep Local ≈ Prod</h3><p>In <strong>development</strong>, add Prisma to your dev script as well:</p><pre>&quot;dev&quot;: &quot;prisma generate &amp;&amp; next dev&quot;</pre><p>That way you don’t forget to regenerate when you tweak the schema.</p><h3>Bonus: Automate Schema Migrations in CI/CD</h3><p>If you use Prisma Migrate, append:</p><pre>prisma migrate deploy &amp;&amp;</pre><p>so the full build command becomes:</p><pre>npx prisma generate &amp;&amp; prisma migrate deploy &amp;&amp; next build</pre><p>This applies pending migrations to your production database every deploy (no more “manual pgAdmin‑at‑midnight” sessions).</p><h3>Gotchas &amp; Pro Tips</h3><p>Issue Quick Check <strong>DATABASE_URL missing inside serverless functions</strong> Did you add the variable under <strong>Production</strong> scope in Vercel, not just <em>Preview</em>? <strong>Build still using old Prisma Client</strong> Click <strong>Redeploy</strong> with <em>Clear Cache</em> toggled (Settings → Git → Trigger Redeploy). <strong>Odd DLL / GLIBC errors</strong> Ensure the Postgres client libraries on Neon, Supabase, etc. match the Linux environment Vercel uses. <strong>Binary mismatch on edge runtime</strong> Edge Functions currently require the JavaScript version of Prisma Client (prisma generate --data-proxy).</p><h3>Final Checklist (Copy + Paste)</h3><ol><li><strong>Check .env:</strong></li></ol><ul><li>DATABASE_URL=&quot;postgresql://USER:PASSWORD@HOST:PORT/DB?sslmode=require&quot; NEXT_PUBLIC_BASE_URL=&quot;https://your‑app.vercel.app</li></ul><p><strong>2. Add those variables in Vercel</strong> (Production &amp; Preview).</p><p><strong>3. Set Build Command:</strong></p><ul><li>npx prisma generate &amp;&amp; next build # or with migrations npx prisma generate &amp;&amp; prisma migrate deploy &amp;&amp; next build</li></ul><p><strong>4. (Optional) Clear cache</strong> once to purge stale Prisma Client.</p><p><strong>5. Celebrate</strong> 🎉 — your deployment should now sail through.</p><h3>Conclusion</h3><p>Vercel’s zero‑config DX is fantastic, but its caching magic can bite you when using tools like Prisma that generate code at build time. The universal antidote is simple: <strong>explicitly run </strong><strong>prisma generate (and </strong><strong>prisma migrate deploy, if needed) every time you build.</strong></p><p>I hope this walkthrough saves you the hour(s) I spent staring at red logs. If you found it useful, tap the ❤️ on Medium, drop a comment.</p><p>Happy shipping! 🚀</p><p>That’s ‑‑ mostly ‑‑ it. Keep reading for the full story, code samples, and a checklist you can paste straight into your own project.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89e1e7c01d2c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>