<?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"><channel><title><![CDATA[Arjun's GenAI Blog]]></title><description><![CDATA[Arjun's GenAI Blog]]></description><link>https://arjuns-genai-blog.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Thu, 24 Sep 2026 20:33:31 GMT</lastBuildDate><atom:link href="https://arjuns-genai-blog.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Where RAG Fails (And How to Fix It)]]></title><description><![CDATA[A Practical Guide for GenAI Developers (with Simple Examples)
RAG (Retrieval-Augmented Generation) sounds powerful:

“Give the model your data, and it will answer correctly.”

But in real projects… RAG often fails 😅Not because the idea is wrong, but...]]></description><link>https://arjuns-genai-blog.hashnode.dev/where-rag-fails-and-how-to-fix-it</link><guid isPermaLink="true">https://arjuns-genai-blog.hashnode.dev/where-rag-fails-and-how-to-fix-it</guid><category><![CDATA[genai]]></category><category><![CDATA[ChaiCode]]></category><category><![CDATA[RAG ]]></category><category><![CDATA[llm]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[- #AIEngineering]]></category><dc:creator><![CDATA[Arjun Saxena]]></dc:creator><pubDate>Sun, 14 Dec 2025 18:30:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1766987868342/2363c7c0-6ec8-4a0a-a18f-21d9eab6eb69.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><em>A Practical Guide for GenAI Developers (with Simple Examples)</em></p>
<p>RAG (<strong>Retrieval-Augmented Generation</strong>) sounds powerful:</p>
<blockquote>
<p>“Give the model your data, and it will answer correctly.”</p>
</blockquote>
<p>But in real projects… <strong>RAG often fails</strong> 😅<br />Not because the idea is wrong, but because <strong>small mistakes break the pipeline</strong>.</p>
<p>In this article, we’ll clearly understand:</p>
<ul>
<li><p>What RAG actually does</p>
</li>
<li><p>Common RAG failure cases</p>
</li>
<li><p>Why they happen</p>
</li>
<li><p><strong>Quick, practical fixes</strong> for each problem</p>
</li>
</ul>
<p>All explained in a <strong>simple, non-researchy way</strong>.</p>
<h2 id="heading-first-what-is-rag-1-minute-explanation">First: What Is RAG? (1-Minute Explanation)</h2>
<p>RAG = <strong>Search + AI Answer</strong></p>
<h3 id="heading-simple-flow">Simple Flow</h3>
<ol>
<li><p>User asks a question</p>
</li>
<li><p>System <strong>searches documents</strong></p>
</li>
<li><p>Relevant text is sent to the LLM</p>
</li>
<li><p>LLM answers using that context</p>
</li>
</ol>
<p>👉 The model is <strong>not guessing</strong><br />👉 It is <strong>reading your data</strong></p>
<p>But… if step 2 or 3 goes wrong → <strong>bad answers</strong>.</p>
<h2 id="heading-simple-analogy-open-book-exam">Simple Analogy 🧠 (Open-Book Exam)</h2>
<p>Imagine:</p>
<ul>
<li><p>Exam = user question</p>
</li>
<li><p>Book = your documents</p>
</li>
<li><p>Student = LLM</p>
</li>
</ul>
<p>If:</p>
<ul>
<li><p>Book is missing pages ❌</p>
</li>
<li><p>Pages are badly cut ❌</p>
</li>
<li><p>Wrong chapter is opened ❌</p>
</li>
</ul>
<p>Even a smart student will fail.</p>
<p>That’s exactly how RAG fails.</p>
<h2 id="heading-high-level-rag-architecture">High-Level RAG Architecture</h2>
<p><img src="https://www.ibm.com/adobe/dynamicmedia/deliver/dm-aid--ba8a3265-c815-4c0d-a9ea-8381274dcc66/rag-product-mapping.png?preferwebp=true" alt="https://www.ibm.com/adobe/dynamicmedia/deliver/dm-aid--ba8a3265-c815-4c0d-a9ea-8381274dcc66/rag-product-mapping.png?preferwebp=true" class="image--center mx-auto" /></p>
<pre><code class="lang-powershell">User Query
   ↓
Embedding Search
   ↓
Retrieved Chunks
   ↓
LLM + Context
   ↓
Final Answer
</code></pre>
<p>Failures happen <strong>before</strong> the LLM most of the time.</p>
<h1 id="heading-1-poor-recall-the-model-cant-find-the-right-info">1️⃣ Poor Recall (The Model Can’t Find the Right Info)</h1>
<h3 id="heading-what-it-means">What It Means</h3>
<p>The correct document <strong>exists</strong>, but retrieval <strong>does not fetch it</strong>.</p>
<h3 id="heading-example">Example</h3>
<p>User asks:</p>
<blockquote>
<p>“What is the refund policy for annual plans?”</p>
</blockquote>
<p>But retriever fetches:</p>
<ul>
<li><p>Pricing page</p>
</li>
<li><p>Marketing content</p>
</li>
<li><p>FAQ (without refund section)</p>
</li>
</ul>
<p>❌ Correct doc never reaches the LLM.</p>
<h3 id="heading-why-this-happens">Why This Happens</h3>
<ul>
<li><p>Weak embeddings</p>
</li>
<li><p>Small <code>topK</code> value</p>
</li>
<li><p>Bad search configuration</p>
</li>
<li><p>Wrong similarity metric</p>
</li>
</ul>
<h3 id="heading-quick-fixes">Quick Fixes ✅</h3>
<ul>
<li><p>Increase <code>topK</code> (e.g. from 3 → 8)</p>
</li>
<li><p>Use <strong>hybrid search</strong> (vector + keyword)</p>
</li>
<li><p>Improve embedding model</p>
</li>
<li><p>Add metadata filters</p>
</li>
</ul>
<p>👉 <strong>Recall first, precision later</strong></p>
<h1 id="heading-2-bad-chunking-context-is-broken">2️⃣ Bad Chunking (Context Is Broken)</h1>
<h3 id="heading-what-is-chunking">What Is Chunking?</h3>
<p>Breaking large documents into <strong>smaller pieces</strong> before embedding.</p>
<h3 id="heading-bad-chunking-example">Bad Chunking Example ❌</h3>
<pre><code class="lang-powershell">Chunk <span class="hljs-number">1</span>: <span class="hljs-string">"Refund policy applies..."</span>
Chunk <span class="hljs-number">2</span>: <span class="hljs-string">"...only if requested within 7 days"</span>
</code></pre>
<p>Each chunk <strong>loses meaning alone</strong>.</p>
<h3 id="heading-real-world-analogy">Real-World Analogy 📄</h3>
<p>Cutting a sentence in half and asking someone to understand it.</p>
<h3 id="heading-quick-fixes-1">Quick Fixes ✅</h3>
<ul>
<li><p>Chunk by <strong>semantic boundaries</strong> (headings, paragraphs)</p>
</li>
<li><p>Use <strong>overlap</strong> (20–30%)</p>
</li>
<li><p>Avoid fixed-size blind chunking</p>
</li>
<li><p>Test chunks by reading them manually</p>
</li>
</ul>
<p>👉 If a chunk doesn’t make sense alone, it’s bad.</p>
<h1 id="heading-3-query-drift-retriever-misunderstands-the-question">3️⃣ Query Drift (Retriever Misunderstands the Question)</h1>
<h3 id="heading-what-it-means-1">What It Means</h3>
<p>The <strong>search query changes meaning</strong> internally.</p>
<h3 id="heading-example-1">Example</h3>
<p>User asks:</p>
<blockquote>
<p>“How to cancel subscription?”</p>
</blockquote>
<p>But the system expands it to:</p>
<blockquote>
<p>“How to delete user account permanently”</p>
</blockquote>
<p>❌ Wrong intent → wrong docs.</p>
<h3 id="heading-why-this-happens-1">Why This Happens</h3>
<ul>
<li><p>Aggressive query rewriting</p>
</li>
<li><p>Over-smart LLM reformulation</p>
</li>
<li><p>No intent grounding</p>
</li>
</ul>
<h3 id="heading-quick-fixes-2">Quick Fixes ✅</h3>
<ul>
<li><p>Keep original query intact</p>
</li>
<li><p>Use <strong>light query expansion</strong>, not rewriting</p>
</li>
<li><p>Add user intent classification</p>
</li>
<li><p>Log &amp; review rewritten queries</p>
</li>
</ul>
<p>👉 Don’t “outsmart” the user’s question.</p>
<h1 id="heading-4-outdated-indexes-correct-data-wrong-version">4️⃣ Outdated Indexes (Correct Data, Wrong Version)</h1>
<h3 id="heading-what-it-means-2">What It Means</h3>
<p>Your database changed, but <strong>RAG still uses old data</strong>.</p>
<h3 id="heading-example-2">Example</h3>
<ul>
<li><p>Refund policy updated last week</p>
</li>
<li><p>RAG answers with <strong>old policy</strong></p>
</li>
</ul>
<p>❌ Model isn’t wrong — your index is.</p>
<h3 id="heading-why-this-happens-2">Why This Happens</h3>
<ul>
<li><p>No re-indexing strategy</p>
</li>
<li><p>Manual ingestion</p>
</li>
<li><p>No versioning</p>
</li>
</ul>
<h3 id="heading-quick-fixes-3">Quick Fixes ✅</h3>
<ul>
<li><p>Schedule re-indexing (daily / weekly)</p>
</li>
<li><p>Use document versioning</p>
</li>
<li><p>Timestamp chunks</p>
</li>
<li><p>Prefer <strong>fresh sources</strong> in retrieval</p>
</li>
</ul>
<p>👉 RAG is only as fresh as your index.</p>
<h1 id="heading-5-hallucinations-from-weak-context">5️⃣ Hallucinations from Weak Context 🧠⚠️</h1>
<h3 id="heading-what-it-means-3">What It Means</h3>
<p>The model <strong>fills gaps with guesses</strong>.</p>
<h3 id="heading-example-3">Example</h3>
<p>Context:</p>
<blockquote>
<p>“Refunds are available under certain conditions.”</p>
</blockquote>
<p>Model answers:</p>
<blockquote>
<p>“Refunds are available within 14 days for all plans.”</p>
</blockquote>
<p>❌ The number <strong>14</strong> was invented.</p>
<h3 id="heading-why-this-happens-3">Why This Happens</h3>
<ul>
<li><p>Retrieved chunks are too vague</p>
</li>
<li><p>Missing key details</p>
</li>
<li><p>Prompt doesn’t restrict guessing</p>
</li>
</ul>
<h3 id="heading-quick-fixes-4">Quick Fixes ✅</h3>
<ul>
<li><p>Add <strong>strong system prompts</strong>:</p>
<blockquote>
<p>“Answer only from provided context”</p>
</blockquote>
</li>
<li><p>Reject answers when context is insufficient</p>
</li>
<li><p>Add citations requirement</p>
</li>
<li><p>Lower temperature</p>
</li>
</ul>
<p>👉 LLMs guess when they’re unsure.</p>
<h2 id="heading-failure-summary-table">Failure Summary Table 📊</h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Failure</td><td>Root Cause</td><td>Quick Fix</td></tr>
</thead>
<tbody>
<tr>
<td>Poor Recall</td><td>Docs not retrieved</td><td>Increase topK, hybrid search</td></tr>
<tr>
<td>Bad Chunking</td><td>Broken meaning</td><td>Semantic chunks + overlap</td></tr>
<tr>
<td>Query Drift</td><td>Wrong intent</td><td>Minimal query rewriting</td></tr>
<tr>
<td>Outdated Index</td><td>Old data</td><td>Re-index + versioning</td></tr>
<tr>
<td>Hallucination</td><td>Weak context</td><td>Strict prompts + validation</td></tr>
</tbody>
</table>
</div><h2 id="heading-rag-is-not-set-and-forget">RAG Is NOT “Set and Forget” 🚨</h2>
<p>Big mistake beginners make:</p>
<blockquote>
<p>“RAG is just embeddings + LLM”</p>
</blockquote>
<p>Reality:</p>
<blockquote>
<p>RAG = <strong>search system + data engineering + prompt discipline</strong></p>
</blockquote>
<h2 id="heading-practical-rag-debugging-checklist">Practical RAG Debugging Checklist ✅</h2>
<p>Before blaming the model, ask:</p>
<ul>
<li><p>Did the correct doc get retrieved?</p>
</li>
<li><p>Do chunks make sense alone?</p>
</li>
<li><p>Is data fresh?</p>
</li>
<li><p>Is the prompt strict enough?</p>
</li>
<li><p>Can I explain why this answer exists?</p>
</li>
</ul>
<p>If not → RAG pipeline issue.</p>
]]></content:encoded></item><item><title><![CDATA[Advanced RAG Concepts: Scaling and Optimizing Retrieval-Augmented Generation]]></title><description><![CDATA[If you’ve ever used ChatGPT or any AI assistant, you might have noticed that sometimes it knows things really well, but sometimes it says “Sorry, I don’t know about this” or even gives a made-up answer.
This is because most AI models are trained on a...]]></description><link>https://arjuns-genai-blog.hashnode.dev/advanced-rag-concepts-scaling-and-optimizing-retrieval-augmented-generation</link><guid isPermaLink="true">https://arjuns-genai-blog.hashnode.dev/advanced-rag-concepts-scaling-and-optimizing-retrieval-augmented-generation</guid><category><![CDATA[ChaiCode]]></category><dc:creator><![CDATA[Arjun Saxena]]></dc:creator><pubDate>Fri, 22 Aug 2025 12:39:48 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1755866376120/798d4a54-369f-49d0-b724-43ed3d6451b6.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>If you’ve ever used <strong>ChatGPT or any AI assistant</strong>, you might have noticed that sometimes it knows things really well, but sometimes it says <em>“Sorry, I don’t know about this”</em> or even gives a made-up answer.</p>
<p>This is because most AI models are trained on a fixed dataset — they don’t “know” new things after their training cutoff.</p>
<p>That’s where <strong>RAG (Retrieval-Augmented Generation)</strong> comes in.<br />Think of RAG as giving the AI a <strong>search engine + memory card</strong>. Instead of only depending on what it already knows, the AI can <em>look up documents, databases, or websites</em> in real time and then generate a smarter answer.</p>
<p>👉 That’s why RAG is used in things like:</p>
<ul>
<li><p><strong>Enterprise chatbots</strong> (answering company policy questions)</p>
</li>
<li><p><strong>Healthcare assistants</strong> (checking latest research papers)</p>
</li>
<li><p><strong>Finance tools</strong> (explaining reports and market data)</p>
</li>
<li><p><strong>Customer support</strong> (instant answers from FAQs)</p>
</li>
</ul>
<p>But when RAG systems become big, they run into challenges like:</p>
<ul>
<li><p>How to make them <strong>fast</strong>?</p>
</li>
<li><p>How to make them <strong>accurate</strong>?</p>
</li>
<li><p>How to keep costs low?</p>
</li>
<li><p>And how to make them <strong>production-ready</strong> (real-world use)?</p>
</li>
</ul>
<h2 id="heading-scaling-rag-finding-the-needle-in-a-haystack">Scaling RAG: Finding the Needle in a Haystack</h2>
<p>Imagine you have <strong>10 million PDFs</strong> in your company library. If your AI tries to search all of them every time, it will be slow.</p>
<p>So we need some tricks:</p>
<ul>
<li><p><strong>Sharding (Partitioning)</strong> → Like splitting a huge library into sections (science books in one room, history in another). Searching becomes faster.</p>
</li>
<li><p><strong>Parallel Retrieval</strong> → Think of it as asking 3 librarians at once instead of 1. One checks by keywords, another checks by meaning, then results are merged.</p>
</li>
<li><p><strong>Batching</strong> → If 100 people ask questions at the same time, the system handles them in groups instead of one by one.</p>
</li>
</ul>
<p>👉 The result? Faster answers without missing important info.Techniques to Improve Accuracy</p>
<p>The quality of RAG answers depends on what documents it retrieves.</p>
<ul>
<li><p><strong>Re-ranking</strong> → First fetch top 50 results, then let a smarter model pick the best 5.</p>
</li>
<li><p><strong>Domain-specific embeddings</strong> → For example, medical chatbot embeddings should understand “BP” as “blood pressure,” not “business process.”</p>
</li>
<li><p><strong>Query Expansion</strong> → If a user asks: <em>“Why did the 2008 crisis happen?”</em> → expand it to include <em>“financial crash, housing bubble, banks”</em>.</p>
</li>
</ul>
<h2 id="heading-improving-accuracy-better-search-better-answers">Improving Accuracy: Better Search = Better Answers</h2>
<p>The AI’s answer is only as good as the documents it retrieves.</p>
<ul>
<li><p><strong>Re-ranking</strong> → If the AI finds 50 docs, another model double-checks and picks the best 5.</p>
</li>
<li><p><strong>Domain-specific embeddings</strong> → Example: In medicine, “BP” should mean <em>blood pressure</em>, not <em>business process</em>.</p>
</li>
<li><p><strong>Query Expansion</strong> → If a user asks: <em>“Why did the 2008 crisis happen?”</em> the AI should also search for “housing bubble, banks, financial crash.”</p>
</li>
</ul>
<p>👉 This way, the system doesn’t miss key context.</p>
<h2 id="heading-speed-vs-accuracy-the-trade-off">Speed vs Accuracy: The Trade-Off</h2>
<p>Quick answers aren’t always perfect, and perfect answers aren’t always quick.</p>
<ul>
<li><p><strong>Fast but less accurate</strong> → AI looks at only 5 docs.</p>
</li>
<li><p><strong>Slow but accurate</strong> → AI scans 100 docs and then filters them.</p>
</li>
</ul>
<p>Example:</p>
<ul>
<li><p>A <strong>customer service bot</strong> needs to be fast → speed is more important.</p>
</li>
<li><p>A <strong>legal assistant</strong> needs to be precise → accuracy is more important.</p>
</li>
</ul>
<h2 id="heading-query-translation-amp-sub-queries">Query Translation &amp; Sub-Queries</h2>
<p>Users don’t always ask questions in the best way.</p>
<ul>
<li><p><strong>Translation</strong> → If a French user asks in French, the system translates → searches in English → translates back.</p>
</li>
<li><p><strong>Sub-Queries</strong> → Example: <em>“How did Tesla’s profit change after Model 3?”</em></p>
<ul>
<li><p>Break it into smaller questions:</p>
<ol>
<li><p>“Tesla profit 2017–2019”</p>
</li>
<li><p>“When was Model 3 launched?”</p>
</li>
</ol>
</li>
<li><p>Combine both to form a clear answer.</p>
</li>
</ul>
</li>
</ul>
<p>👉 Breaking big questions into smaller ones = smarter retrieval.Ranking Strategies &amp; HyDE</p>
<ul>
<li><p><strong>Dense + Sparse Ranking</strong> → Mix semantic search (understands meaning) + keyword search (exact match).</p>
</li>
<li><p><strong>HyDE (Hypothetical Document Embeddings)</strong> → Before retrieving, ask the LLM to imagine a possible answer, embed it, and search using that.</p>
</li>
</ul>
<p>Example: For the question <em>“Why did dinosaurs go extinct?”</em> → The model generates a hypothetical explanation like “asteroid impact, volcanic activity,” then searches based on that → better recall.</p>
<h2 id="heading-llms-as-evaluators-ai-double-checks-itselfinstead-of-answering-in-one-go-the-system-can-refine-itself">LLMs as Evaluators: AI Double-Checks ItselfInstead of answering in one go, the system can refine itself:</h2>
<ol>
<li><p>LLMs can also <em>judge</em> the answers they give.</p>
<ul>
<li><p><strong>Relevance Check</strong> → Ignore useless docs.</p>
</li>
<li><p><strong>Validation</strong> → See if the answer is backed by evidence.</p>
</li>
<li><p><strong>Hallucination Check</strong> → Catch when the model is “making things up.”</p>
</li>
</ul>
</li>
</ol>
<p>    Example: If a health bot says <em>“Vitamin D cures flu”</em>, the evaluator checks: <em>Is there actually a document supporting this?</em> If not → fix it.Caching for Efficiency</p>
<p>Not every query needs fresh computation.</p>
<ul>
<li><p><strong>Query Caching</strong> → Save embeddings for repeated queries.</p>
</li>
<li><p><strong>Answer Caching</strong> → Store answers for common questions like <em>“What’s the refund policy?”</em>.</p>
</li>
<li><p><strong>Pipeline Caching</strong> → Cache sub-query results to save cost.</p>
</li>
</ul>
<p>👉 Example: In an e-commerce chatbot, the answer to <em>“Where’s my order?”</em> doesn’t change every second. Cache it for a few minutes.</p>
<h2 id="heading-ranking-amp-hyde-hypothetical-answer-trick">Ranking &amp; HyDE (Hypothetical Answer Trick)</h2>
<ul>
<li><p>Sometimes, ranking results smartly makes all the difference.</p>
<ul>
<li><p><strong>Dense + Sparse Ranking</strong> → Balance between meaning-based search (semantic) and keyword search.</p>
</li>
<li><p><strong>HyDE</strong> → Cool trick! Instead of directly searching the query, the AI first imagines a <em>hypothetical answer</em>, turns it into an embedding, and then searches.</p>
</li>
</ul>
</li>
</ul>
<p>    Example: Question → <em>“Why did dinosaurs go extinct?”</em></p>
<ul>
<li><p>AI first imagines: “Maybe asteroid impact, volcanoes, climate change.”</p>
</li>
<li><p>Then searches based on those terms.</p>
</li>
<li><p>Finds richer results than with the original vague query.GraphRAG for Complex Reasoning</p>
</li>
</ul>
<p>GraphRAG uses a <strong>knowledge graph</strong> (nodes = entities, edges = relationships).</p>
<p>Example:</p>
<ul>
<li><p>Query: <em>“Which scientists worked with Einstein?”</em></p>
</li>
<li><p>A normal RAG may only find Einstein-related documents.</p>
</li>
<li><p>GraphRAG follows connections in a knowledge graph → finds “Niels Bohr, Marie Curie, etc.”</p>
</li>
</ul>
<p>👉 Great for <strong>research, enterprise knowledge bases, and reasoning-heavy tasks</strong>.</p>
<h2 id="heading-corrective-rag-try-fail-fix">Corrective RAG: Try, Fail, Fix</h2>
<p>Instead of one-shot answers, RAG can improve itself step by step:</p>
<ol>
<li><p>Retrieve docs.</p>
</li>
<li><p>Generate an answer.</p>
</li>
<li><p>Spot gaps or contradictions.</p>
</li>
<li><p>Re-retrieve and fix.</p>
</li>
</ol>
<p>👉 Useful in research where multiple steps are needed.</p>
<h2 id="heading-caching-dont-re-invent-the-wheel">Caching: Don’t Re-Invent the Wheel</h2>
<p>Why repeat the same work again and again?</p>
<ul>
<li><p><strong>Query Cache</strong> → Save previous searches.</p>
</li>
<li><p><strong>Answer Cache</strong> → Store common answers like “What’s the refund policy?”</p>
</li>
<li><p><strong>Pipeline Cache</strong> → Save results of sub-queries.</p>
</li>
</ul>
<p>👉 Example: An e-commerce bot answering <em>“Where’s my order?”</em> doesn’t need to recheck the system every second. Cache it for a few minutes.</p>
<h2 id="heading-hybrid-search-amp-contextual-embeddings">Hybrid Search &amp; Contextual Embeddings</h2>
<ul>
<li><p><strong>Hybrid Search</strong> = Semantic + Keyword search together.</p>
<ul>
<li>Example: Searching <em>“apple”</em> → finds both the fruit and the company.</li>
</ul>
</li>
<li><p><strong>Contextual Embeddings</strong> → Change search based on context.</p>
<ul>
<li><p>If user is in a <em>tech forum</em>, “apple” = Apple Inc.</p>
</li>
<li><p>If in a <em>cooking blog</em>, “apple” = the fruit.</p>
</li>
</ul>
</li>
</ul>
<h2 id="heading-graphrag-connecting-the-dots">GraphRAG: Connecting the Dots</h2>
<p>Normal RAG just looks at flat documents. GraphRAG builds <strong>networks of knowledge</strong>.</p>
<p>Example:</p>
<ul>
<li><p>Query: <em>“Which scientists worked with Einstein?”</em></p>
</li>
<li><p>Normal RAG → Only Einstein docs.</p>
</li>
<li><p>GraphRAG → Uses connections → finds Niels Bohr, Marie Curie, and others.</p>
</li>
</ul>
<p>👉 Great for <strong>research, history, enterprise knowledge graphs</strong>.</p>
<h2 id="heading-making-rag-production-ready">Making RAG Production-Ready</h2>
<p>Building a demo is easy. Running it in the real world is hard. You need:</p>
<ul>
<li><p><strong>Monitoring</strong> → Check accuracy, speed, and hallucinations.</p>
</li>
<li><p><strong>Feedback loops</strong> → Improve using user ratings.</p>
</li>
<li><p><strong>Scalability</strong> → Handle thousands of queries per second.</p>
</li>
<li><p><strong>Data refresh</strong> → Keep knowledge base updated.</p>
</li>
</ul>
<p>Example: A banking chatbot must refresh policies and interest rates daily.</p>
]]></content:encoded></item><item><title><![CDATA[Retrieval-Augmented Generation (RAG) — How it Works, Why it Exists]]></title><description><![CDATA[What is RAG (in one line)
RAG (Retrieval-Augmented Generation) = search first, then generate.Retrieve the most relevant document snippets, then let an LLM compose an answer using only those snippets.
Example 1 — Librarian + Writer:You ask a question ...]]></description><link>https://arjuns-genai-blog.hashnode.dev/retrieval-augmented-generation-rag-how-it-works-why-it-exists</link><guid isPermaLink="true">https://arjuns-genai-blog.hashnode.dev/retrieval-augmented-generation-rag-how-it-works-why-it-exists</guid><category><![CDATA[ChaiCode]]></category><dc:creator><![CDATA[Arjun Saxena]]></dc:creator><pubDate>Wed, 20 Aug 2025 12:49:10 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1755694114357/75f538cd-7a38-43c2-9d41-77f18e2a2006.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-what-is-rag-in-one-line">What is RAG (in one line)</h2>
<p><strong>RAG (Retrieval-Augmented Generation)</strong> = search first, then generate.<br />Retrieve the most relevant document snippets, then let an LLM compose an answer using only those snippets.</p>
<p><strong>Example 1 — Librarian + Writer:</strong><br />You ask a question at a library. The librarian (retriever) pulls out 3 pages from various books that seem relevant. You give those pages to a writer (the generator). The writer writes an answer using only those pages. Result = focused, source-backed answer.</p>
<p><strong>Example 2 — Chef + Fridge:</strong><br />The fridge is the knowledge base. The chef (LLM) doesn’t open the whole fridge every time — they pick a few ingredients (retrieved snippets) and cook a dish (the final answer). That prevents waste and confusion.</p>
<h2 id="heading-why-rag-is-used">Why RAG is used</h2>
<ul>
<li><p><strong>Limited context window of LLMs</strong><br />  <em>Example:</em> You can't feed a 1000-page manual entirely into an LLM. RAG retrieves only the few paragraphs that matter.</p>
</li>
<li><p><strong>Reduce hallucination</strong> (fewer made-up facts)<br />  <em>Example:</em> A support bot answering from official policy snippets will produce factual responses rather than guessing.</p>
</li>
<li><p><strong>Up-to-date knowledge without retraining</strong><br />  <em>Example:</em> Add a new company policy doc to the index — the bot will use it immediately.</p>
</li>
<li><p><strong>Cost &amp; efficiency</strong><br />  <em>Example:</em> A small LLM + retrieval is much cheaper than constantly fine-tuning a giant model.</p>
<p>  <strong>raceability / citations</strong><br />  <em>Example:</em> The system can say “Answer based on KB doc X, paragraph 2.”</p>
</li>
</ul>
<h2 id="heading-main-components-retriever-generator-with-examples">Main components: Retriever + Generator (with examples)</h2>
<h3 id="heading-retriever-the-searcher-librarian"><strong>Retriever (the searcher / librarian)</strong></h3>
<ul>
<li><p>Converts a query into an embedding (a vector).</p>
</li>
<li><p>Finds top-k most similar document chunks from an index (FAISS/Pinecone/Milvus).</p>
</li>
</ul>
<p><em>Example:</em> Query “refund policy 2025” → retriever returns three snippets: policy update, step-by-step refund form, FAQ.</p>
<h3 id="heading-generator-the-composer-writer"><strong>Generator (the composer / writer)</strong></h3>
<ul>
<li><p>Builds a prompt including the query + retrieved snippets.</p>
</li>
<li><p>Instructs the LLM to answer using only those snippets, and optionally cite them.</p>
</li>
</ul>
<p><em>Flow example:</em><br />User asks → Retriever finds top snippets → Generator crafts a prompt like “Using only these snippets, answer the question” → LLM outputs an answer with citations.</p>
<h2 id="heading-what-is-indexing">What is indexing?</h2>
<p><strong>Analogy — library catalog or supermarket map:</strong><br />A catalog tells you exact shelves to check; an index organizes vectors to make nearest-neighbor search fast.</p>
<p><strong>Tech note:</strong> Indexes (FAISS/Annoy/Milvus) let you do fast similarity search over millions of embeddings — otherwise linear scan would be too slow.</p>
<h2 id="heading-why-vectorize-text">Why vectorize text</h2>
<p><strong>Analogy — coordinates for meanings:</strong><br />Every sentence is mapped to a point in space. Sentences with similar meaning are close to each other on that map.</p>
<p><strong>Mini example:</strong><br />“How to fix phone battery” and “phone battery not charging” — different words but similar meaning → embeddings close together. Keyword search might miss one, embeddings catch both.</p>
<p><strong>Similarity metrics:</strong> Cosine similarity or dot product are commonly used.</p>
<h2 id="heading-why-do-rags-exist">Why do RAGs exist?</h2>
<ul>
<li><p>LLMs are great at composing language but poor at storing and updating massive factual knowledge.<br />  <em>Example:</em> A research assistant that must reference the latest papers — you don’t retrain the model each time a new paper appears.</p>
</li>
<li><p>RAG provides control and grounding: you can restrict answers to trusted documents and add domain-specific knowledge quickly.</p>
</li>
</ul>
<h2 id="heading-why-chunking-is-necessary">Why chunking is necessary</h2>
<p><strong>Problem:</strong> Documents (books, manuals, long web pages) are long. Embedding whole text is inefficient or gets truncated.</p>
<p><strong>Chunking:</strong> split large documents into smaller logical pieces (paragraphs or fixed-size token windows).</p>
<p><strong>Concrete example:</strong><br />Manual text:</p>
<blockquote>
<p>“Install with <code>apt-get install X</code>. Then edit <code>/etc/x.conf</code>. For advanced options, see section 5.”<br />Chunks:</p>
</blockquote>
<ul>
<li><p>Chunk 1: “Install with <code>apt-get install X</code>.”</p>
</li>
<li><p>Chunk 2: “Then edit <code>/etc/x.conf</code>.”</p>
</li>
<li><p>Chunk 3: “For advanced options, see section 5.”</p>
</li>
</ul>
<p>If the user asks “How to enable X?”, returning Chunk 2 gives the exact instruction.</p>
<p><strong>Rule of thumb:</strong> 200–800 tokens per chunk (tune by model &amp; dataset).</p>
<h2 id="heading-why-overlapping-chunks-are-used">Why overlapping chunks are used</h2>
<p><strong>Problem without overlap:</strong> Important information may be split across the boundary of two chunks and be missed.</p>
<p><strong>Concrete example:</strong><br />Text: “The patient must fast for 12 hours. If emergency, contact the on-call physician.”<br />If you split exactly after “12 hours.”, neither chunk contains the full instruction about emergencies.</p>
<p><strong>With overlap:</strong> repeat the last 10–30% of chunk A at the start of chunk B. That ensures at least one chunk contains the complete instruction.</p>
<p><strong>Tradeoff:</strong> slightly more storage and compute for better retrieval accuracy.</p>
]]></content:encoded></item><item><title><![CDATA[Agentic AI & Tools: A Beginner’s Guide Explained]]></title><description><![CDATA[Agentic AI are AIs built to perform specific tasks using large language models (LLMs).
What does this mean?
LLMs have access to huge amounts of data from all over the world. But sometimes, you don’t need all that data—you only need it for a particula...]]></description><link>https://arjuns-genai-blog.hashnode.dev/agentic-ai-and-tools-a-beginners-guide-explained</link><guid isPermaLink="true">https://arjuns-genai-blog.hashnode.dev/agentic-ai-and-tools-a-beginners-guide-explained</guid><category><![CDATA[ChaiCode]]></category><dc:creator><![CDATA[Arjun Saxena]]></dc:creator><pubDate>Mon, 18 Aug 2025 12:26:51 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1755519934004/a4d3146c-3a09-4e33-a5be-00bfcfe3a6a4.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><strong>Agentic AI</strong> are AIs built to perform specific tasks using large language models (LLMs).</p>
<h2 id="heading-what-does-this-mean">What does this mean?</h2>
<p>LLMs have access to huge amounts of data from all over the world. But sometimes, you don’t need <em>all</em> that data—you only need it for a particular purpose. For example, you might want an AI to analyze your code, suggest optimizations, or make it cleaner and more efficient. That’s where <strong>Agentic AI</strong> comes in.</p>
<h3 id="heading-example-1-youtube-analogy">Example 1: YouTube Analogy</h3>
<h3 id="heading-example-1-youtube-analogy-revised">Example 1: YouTube Analogy (Revised)</h3>
<p>Imagine you open YouTube. There are millions of videos on every topic. But you don’t watch all of them—you only search for the videos you actually need.</p>
<p>Similarly, a <strong>large language model (LLM)</strong> has access to tons of information from all over the world. But most of that data is not relevant to your task. For example, you might want AI to:</p>
<ul>
<li><p>Improve your resume for ATS scoring</p>
</li>
<li><p>Write JavaScript code</p>
</li>
<li><p>Summarize only business articles</p>
</li>
</ul>
<p>In these cases, you don’t want the AI to process everything—it should focus only on what’s important for <em>your</em> goal. That’s where <strong>Agentic AI</strong> comes in. It’s like a smart filter or a tool that helps the LLM work efficiently on a specific task instead of trying to do everything.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755409317394/91cff379-5e4c-4431-b3f3-a618c38987dc.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-example-2-human-body-analogy">Example 2: Human Body Analogy</h3>
<p>Think of a human brain—it’s super powerful and can plan, think, and solve problems. But if you didn’t have eyes to see, hands to do tasks, or legs to move, how much of that brain power could you actually use? Not much, right?</p>
<p>Similarly, a <strong>large language model (LLM)</strong> is like a super-smart brain. It knows a lot and can come up with solutions, ideas, or code. But by itself, it can’t take real-world actions. That’s where <strong>Agentic AI</strong> comes in.</p>
<p>Agentic AI acts like the <strong>body</strong> for the brain. It gives the LLM the ability to “see,” “act,” and “interact” with the world—like sending an email, updating a spreadsheet, or cleaning files. Without the body, the brain’s power just stays in theory. With it, the brain’s ideas become real actions.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755410260382/a1c139b7-b32e-415d-a92b-0fe93ec6b092.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-how-agentic-ai-works">How Agentic AI Works</h2>
<p>Agentic AI works in <strong>four steps</strong>:</p>
<ol>
<li><p><strong>Perceive</strong> – It gathers data from different sources and extracts the most meaningful and relevant information.</p>
</li>
<li><p><strong>Reason</strong> – The AI uses techniques like <strong>RAG (Retrieval-Augmented Generation)</strong> to analyze the data, solve problems, and generate useful outputs for tasks like content creation, recommendations, or coding.</p>
</li>
<li><p><strong>Act</strong> – The AI can perform tasks automatically. For example, an AI cleaner can remove viruses, duplicate files, or temporary files quickly. However, it usually asks for human approval before performing critical actions.</p>
</li>
<li><p><strong>Learn</strong> – Agentic AI continuously improves through a <strong>feedback loop</strong>. The more it adapts to new data, the more effective and powerful it becomes over time.</p>
</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755414378123/88fda021-c00b-461e-9e89-7f0d8589647c.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-their-tools-how-agentic-ai-gets-things-done">Their Tools: How Agentic AI Gets Things Done</h2>
<p>Agentic AI doesn’t just think—it uses <strong>tools</strong> to act in the real world. These tools can be software, APIs, or automated systems that let AI perform specific tasks.</p>
<p>Here are some common categories of tools used by Agentic AI:</p>
<h3 id="heading-1-coding-amp-development-tools">1. Coding &amp; Development Tools</h3>
<ul>
<li><p><strong>Example:</strong> An AI that writes or optimizes JavaScript code using VS Code or GitHub APIs.</p>
</li>
<li><p><strong>How it works:</strong> You give it a task, like “Make this code faster,” and the AI uses coding tools to edit, run, and test it.</p>
</li>
</ul>
<h3 id="heading-2-data-amp-analysis-tools">2. Data &amp; Analysis Tools</h3>
<ul>
<li><p><strong>Example:</strong> AI that checks resumes for ATS scoring or analyzes customer feedback.</p>
</li>
<li><p><strong>How it works:</strong> It uses data-processing tools to scan files, extract insights, and give recommendations.</p>
</li>
</ul>
<h3 id="heading-3-automation-tools">3. Automation Tools</h3>
<ul>
<li><p><strong>Example:</strong> AI cleaners, email automation bots, or social media posting tools.</p>
</li>
<li><p><strong>How it works:</strong> The AI interacts with apps and software to perform tasks automatically, sometimes asking for human approval before final actions.</p>
</li>
</ul>
<h3 id="heading-4-research-amp-knowledge-tools">4. Research &amp; Knowledge Tools</h3>
<ul>
<li><p><strong>Example:</strong> <strong>Perplexity AI</strong> can give you <strong>real-time information</strong> by connecting to external sources, unlike ChatGPT which only uses its pre-trained model.</p>
</li>
<li><p><strong>How it works:</strong> Perplexity uses agentic AI tools to search websites, databases, and articles in real time, then summarizes and delivers the most relevant information.</p>
</li>
</ul>
<p><strong>Think of it this way:</strong><br />If the LLM is the brain and Agentic AI is the body, then <strong>these tools are the hands, eyes, and gadgets</strong> that help the AI actually do things in the real world. Without tools, the AI can plan and reason, but it can’t take action.</p>
<h2 id="heading-agentic-ai-tools-and-business-applications">Agentic AI Tools and Business Applications</h2>
<h3 id="heading-business-applications"><strong>Business Applications</strong></h3>
<p>Here are some concrete examples of how businesses use agentic AI tools:</p>
<ol>
<li><p><strong>Marketing Automation</strong></p>
<ul>
<li><p>AI tools that autonomously plan campaigns, optimize ad spend, and target audiences based on real-time data.</p>
</li>
<li><p>Example: An AI that can run A/B tests, analyze results, and automatically adjust messaging to maximize conversion.</p>
</li>
</ul>
</li>
<li><p><strong>Customer Service</strong></p>
<ul>
<li><p>AI chatbots and virtual assistants that don’t just answer questions but <strong>proactively solve problems</strong> and escalate issues.</p>
</li>
<li><p>Example: AI detecting customer dissatisfaction from tone and initiating a resolution before the complaint escalates.</p>
</li>
</ul>
</li>
<li><p><strong>Supply Chain &amp; Logistics</strong></p>
<ul>
<li><p>Autonomous AI systems can optimize inventory, predict demand, and route deliveries efficiently.</p>
</li>
<li><p>Example: AI adjusting shipments in real time based on weather, traffic, or supply disruptions.</p>
</li>
</ul>
</li>
<li><p><strong>Financial Analysis &amp; Decision-Making</strong></p>
<ul>
<li><p>Agentic AI can autonomously generate investment strategies, detect fraud, or optimize pricing models.</p>
</li>
<li><p>Example: AI adjusting stock portfolios based on market trends without human intervention.</p>
</li>
</ul>
</li>
<li><p><strong>Product Development</strong></p>
<ul>
<li>AI systems that analyze customer feedback, market trends, and competitor activity to suggest new product features or improvements.</li>
</ul>
</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755519654149/88f3f645-901d-422f-a57a-6452e60003cf.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-challenges-amp-considerations"><strong>Challenges &amp; Considerations</strong></h3>
<ul>
<li><p><strong>Ethical Decisions</strong>: Agentic AI may make decisions that require human ethical oversight.</p>
</li>
<li><p><strong>Reliability &amp; Transparency</strong>: Businesses must ensure AI actions are understandable and accountable.</p>
</li>
<li><p><strong>Integration Complexity</strong>: Deploying agentic AI often requires robust infrastructure and data pipelines.</p>
</li>
</ul>
<h3 id="heading-future-outlook">Future Outlook</h3>
<ul>
<li><p>Agentic AI is moving toward <strong>self-managing business units</strong> where AI can oversee end-to-end processes.</p>
</li>
<li><p>The next wave may involve AI collaborating with humans as <strong>autonomous co-workers</strong> rather than just tools.</p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Building a Thinking Model from a Non-Thinking Model using Chain-of-Thought]]></title><description><![CDATA[Chain-of-Thought (CoT) is a prompting technique that asks a model to show intermediate reasoning steps before giving the final result. Using CoT + a few complementary strategies (few-shot examples, self-consistency, scratchpads, iterative refinement)...]]></description><link>https://arjuns-genai-blog.hashnode.dev/building-a-thinking-model-from-a-non-thinking-model-using-chain-of-thought</link><guid isPermaLink="true">https://arjuns-genai-blog.hashnode.dev/building-a-thinking-model-from-a-non-thinking-model-using-chain-of-thought</guid><category><![CDATA[ChaiCode]]></category><dc:creator><![CDATA[Arjun Saxena]]></dc:creator><pubDate>Fri, 15 Aug 2025 14:55:05 GMT</pubDate><content:encoded><![CDATA[<p>Chain-of-Thought (CoT) is a prompting technique that asks a model to <strong>show intermediate reasoning steps</strong> before giving the final result. Using CoT + a few complementary strategies (few-shot examples, self-consistency, scratchpads, iterative refinement) you can turn a model that normally gives short one-line answers into one that behaves like it “thinks” step-by-step. This post gives practical templates, a Node.js example to run many CoT samples and vote, evaluation tips, and safety/limitations.</p>
<h2 id="heading-why-this-matters">Why this matters</h2>
<p>Most LLMs excel at <em>pattern completion</em>, not literal human thought. For many complex tasks (multi-step math, logic puzzles, multi-hop question answering, planning), a one-line answer is brittle and error-prone. When you explicitly ask for intermediate steps, you get:</p>
<ul>
<li><p>Better correctness on complex reasoning tasks</p>
</li>
<li><p>More interpretable outputs (you can audit the steps)</p>
</li>
<li><p>Opportunities to check and correct before the final answer</p>
</li>
</ul>
<p>But CoT isn't magic — it changes how you interact with the model and how you evaluate outputs.</p>
<h2 id="heading-what-is-chain-of-thought-cot">What is Chain-of-Thought (CoT)?</h2>
<p><strong>Chain-of-Thought</strong> prompting requests the model to produce intermediate reasoning steps (a “chain”) leading to the answer. Example (human style):</p>
<pre><code class="lang-bash">Question: If Alice has 3 apples and buys 4 more, how many?
Chain-of-Thought: Alice had 3 apples. She bought 4 more, so 3 + 4 = 7.
Answer: 7
</code></pre>
<h2 id="heading-types-of-cot-styles">Types of CoT styles</h2>
<h3 id="heading-zero-shot-cot"><strong>Zero-shot CoT</strong></h3>
<p>ask the model to “think step by step” in a single prompt (no examples).<br /><code>“Answer step by step, then give the final result.”</code></p>
<pre><code class="lang-bash">System: You are a careful reasoning assistant.
User: Solve the following and show your reasoning step by step.
Then give the final answer on a separate line prefixed with <span class="hljs-string">"Answer:"</span>.
Question: If a train goes 60 km/h <span class="hljs-keyword">for</span> 2 hours and 40 km/h 
<span class="hljs-keyword">for</span> 1 hour, what<span class="hljs-string">'s the average speed?</span>
</code></pre>
<h3 id="heading-few-shot-cot"><strong>Few-shot CoT</strong></h3>
<p>provide 1–3 fully worked examples (questions + stepwise solutions). This is more reliable.</p>
<pre><code class="lang-bash">Example 1:
Q: A bag has 3 red and 2 blue balls. If you draw two without replacement, what<span class="hljs-string">'s P(both red)?
CoT: First compute total ways, ...
Answer: 3/10

Example 2:
Q: Solve 7*(5+3) - 4
CoT: ...
Answer: 52

Now solve:
Q: A car travels 120 km in 2 hours and 60 km in 1 hour. What'</span>s the average speed?
</code></pre>
<h3 id="heading-self-consistency"><strong>Self-consistency</strong></h3>
<p>sample many independent CoT chains (by using temperature &gt; 0), then aggregate final answers by majority vote.</p>
<pre><code class="lang-bash">{
  <span class="hljs-string">"step"</span>: <span class="hljs-string">"THINK"</span>,
  <span class="hljs-string">"content"</span>: <span class="hljs-string">"First compute distances or rates..."</span>
}
</code></pre>
<ul>
<li><p><strong>Scratchpad / Intermediate Storage</strong> — keep an external memory of the model’s intermediate steps and feed them back for verification/refinement.</p>
</li>
<li><p><strong>Iterative refinement</strong> — ask the model to produce steps, then critique or verify them, then produce a corrected final answer.</p>
</li>
</ul>
<h2 id="heading-design-patterns-to-improve-reliability">Design patterns to improve reliability</h2>
<h3 id="heading-few-shot-cot-with-high-quality-worked-examples">Few-shot CoT with high-quality worked examples</h3>
<p>Give the model 2–3 <em>carefully curated</em> examples that illustrate the exact style you want. Quality beats quantity.</p>
<h3 id="heading-ask-for-structured-steps">Ask for <em>structured steps</em></h3>
<p>Instead of free-form text, ask for numbered steps or JSON objects. This makes parsing and validation easier.</p>
<pre><code class="lang-bash">Step 1: ...
Step 2: ...
Final Answer: ...
</code></pre>
<h3 id="heading-use-checkers-validators">Use checkers / validators</h3>
<p>After the model produces steps, run a lightweight checker (math evaluator, unit tests) to verify intermediate computations. If a step fails validation, prompt the model to re-evaluate that step.</p>
<h3 id="heading-iterative-critique-loop">Iterative critique loop</h3>
<p>Have the model critique its own steps:</p>
<ul>
<li><p>Ask it: “Check step 3 — is the arithmetic correct?”</p>
</li>
<li><p>If it finds an issue, request corrected steps and a new final answer.</p>
</li>
</ul>
<h3 id="heading-combine-model-strengths-tooling">Combine model strengths (tooling)</h3>
<p>If available, use tools or functions: <code>calculate()</code>, <code>run_python()</code>, or external libraries to evaluate sub expressions. Let the model orchestrate the tool calls and reason over the results.</p>
<h2 id="heading-lets-code">Let’s Code</h2>
<pre><code class="lang-bash">import OpenAI from <span class="hljs-string">"openai"</span>;

const client = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });

<span class="hljs-keyword">function</span> extractFirstJsonObject(text) {
  text = text.replace(/```(?:json)?\n?([\s\S]*?)```/g, <span class="hljs-string">"<span class="hljs-variable">$1</span>"</span>);
  const start = text.indexOf(<span class="hljs-string">"{"</span>);
  <span class="hljs-keyword">if</span> (start === -1) throw new Error(<span class="hljs-string">"No JSON start"</span>);
  <span class="hljs-built_in">let</span> depth = 0;
  <span class="hljs-keyword">for</span> (<span class="hljs-built_in">let</span> i = start; i &lt; text.length; i++) {
    const ch = text[i];
    <span class="hljs-keyword">if</span> (ch === <span class="hljs-string">"{"</span>) depth++;
    <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (ch === <span class="hljs-string">"}"</span>) {
      depth--;
      <span class="hljs-keyword">if</span> (depth === 0) {
        const candidate = text.slice(start, i + 1).trim();
        try {
          <span class="hljs-built_in">return</span> JSON.parse(candidate);
        } catch {
          const attempt = candidate.replace(/<span class="hljs-string">'/g, '</span><span class="hljs-string">"');
          return JSON.parse(attempt);
        }
      }
    }
  }
  throw new Error("</span>No balanced JSON found<span class="hljs-string">");
}

async function main() {
  const systemPrompt = `
STRICT INSTRUCTIONS:
Output EXACTLY one JSON object and nothing else.
JSON schema: {"</span>step<span class="hljs-string">":"</span>&lt;START|THINK|OUTPUT&gt;<span class="hljs-string">","</span>content<span class="hljs-string">":"</span>&lt;string&gt;<span class="hljs-string">"}
Return ONLY one step per assistant message.
Sequence must be: START, one or more THINK, then OUTPUT.
START: single-line summary of the user query.
Each THINK: one focused reasoning step, short and precise.
Do multiple THINK steps before OUTPUT.
OUTPUT: concise final answer in content.
Do not include markdown, backticks, commentary, or extra fields.
Use plain ASCII only and keep content &lt;200 chars.
If computation needed follow BODMAS order.
Do not proceed until next message prompts you.
Respond deterministically and without apologies.
If you understand, produce START for the user's query.
`.trim();

  const messages = [
    { role: "</span>system<span class="hljs-string">", content: systemPrompt },
    { role: "</span>user<span class="hljs-string">", content: "</span>Please solve this equation 8 + 8 * 8 + -10<span class="hljs-string">" }
  ];

  while (true) {
    const response = await client.chat.completions.create({
      model: "</span>gpt-4o-mini<span class="hljs-string">",
      messages
    });

    const raw = response.choices?.[0]?.message?.content;
    if (!raw) throw new Error("</span>Empty response<span class="hljs-string">");
    const parsed = extractFirstJsonObject(raw);
    console.log(`<span class="hljs-variable">${parsed.step}</span>: <span class="hljs-variable">${parsed.content}</span>`);
    messages.push({ role: "</span>assistant<span class="hljs-string">", content: raw });
    if (parsed.step === "</span>OUTPUT<span class="hljs-string">") {
      break;
    }
  }
}

main().catch(err =&gt; {
  console.error("</span>Error:<span class="hljs-string">", err.message);
  process.exit(1);
});</span>
</code></pre>
]]></content:encoded></item><item><title><![CDATA[System prompts, prompt formats, and prompting styles — explained simply]]></title><description><![CDATA[Opening — why prompts matter
Large language models (LLMs) don’t “know” your intent unless you tell them. The prompt is your instruction to the model. If the prompt is unclear or wrong, the model’s answer will be poor — that’s Garbage In, Garbage Out ...]]></description><link>https://arjuns-genai-blog.hashnode.dev/system-prompts-prompt-formats-and-prompting-styles-explained-simply</link><guid isPermaLink="true">https://arjuns-genai-blog.hashnode.dev/system-prompts-prompt-formats-and-prompting-styles-explained-simply</guid><category><![CDATA[ChaiCode]]></category><dc:creator><![CDATA[Arjun Saxena]]></dc:creator><pubDate>Fri, 15 Aug 2025 14:35:17 GMT</pubDate><content:encoded><![CDATA[<h2 id="heading-opening-why-prompts-matter">Opening — why prompts matter</h2>
<p>Large language models (LLMs) don’t “know” your intent unless you tell them. The <em>prompt</em> is your instruction to the model. If the prompt is unclear or wrong, the model’s answer will be poor — that’s <strong>Garbage In, Garbage Out (GIGO)</strong>. Good prompts = better, predictable outputs.</p>
<h3 id="heading-who-builds-models">Who builds models</h3>
<ul>
<li><p><strong>OpenAI</strong> builds the GPT family (GPT-3, GPT-4, etc.).</p>
</li>
<li><p><strong>Google</strong> builds <strong>Gemini</strong> (sometimes people say “Gemma” by mistake).</p>
</li>
<li><p><strong>Meta</strong> (Facebook) developed <strong>LLaMA</strong> and variants.</p>
</li>
<li><p><strong>Anthropic</strong> builds <strong>Claude</strong>.</p>
</li>
<li><p>There are many instruction-tuned derivatives: <strong>Flan-T5</strong>, <strong>Alpaca</strong>, <strong>Vicuna</strong>, <strong>Mistral</strong>, etc.</p>
</li>
</ul>
<p><strong><mark>NOTE :</mark></strong> Each model family may prefer different prompt formats or have different strengths (instruction following, reasoning, short answers, code, etc.), but the core prompting ideas are shared.</p>
<h2 id="heading-what-is-a-system-prompt">What is a system prompt?</h2>
<p>In chat-based interactions, messages have roles. Common roles:</p>
<ul>
<li><p><strong><em>system</em></strong> — highest priority instructions (sets behaviour/persona/constraints). Example: “You are a helpful, concise assistant that answers in bullet points.”</p>
</li>
<li><p><strong><em>user</em></strong> — the user’s question or request.</p>
</li>
<li><p><strong><em>assistant</em></strong> — the model’s previous replies.</p>
</li>
<li><p><strong><em>developer</em></strong> — similar to system for developer-level controls.</p>
</li>
</ul>
<h2 id="heading-how-many-way-to-write-prompt-prompt-styles">How many way to write Prompt ( Prompt Styles )</h2>
<h3 id="heading-alpaca-instruction-format"><strong>Alpaca instruction format</strong></h3>
<p>A simple instruction template some instruction-tuned models use:</p>
<pre><code class="lang-bash"><span class="hljs-comment">### Input:</span>
&lt;task description and context&gt;
<span class="hljs-comment">### Response:</span>
&lt;model output&gt;
</code></pre>
<h3 id="heading-inst-format-used-by-models-like-some-llama-2-instruction-sets"><strong>INST format</strong> (used by models like some LLaMA-2 instruction sets)</h3>
<pre><code class="lang-bash">[INST]What is an LRU cache?[/INST]
</code></pre>
<h3 id="heading-flan-t5-style">FLAN-T5 style</h3>
<p>Flan instruction finetuning often used prompts like:</p>
<ul>
<li>The model completes after <code>Answer:</code>. Simple and works well for instruction-tuned seq2seq models.</li>
</ul>
<pre><code class="lang-bash">Question: What is AI?
Answer:
</code></pre>
<h2 id="heading-chatml-message-arrays-chat-format">ChatML (message arrays / chat format)</h2>
<ul>
<li>ChatML (or similar schemas) is used widely: OpenAI Chat API, Google Gemini, Anthropic Claude all accept chat-style messages (names differ).</li>
</ul>
<ul>
<li>ChatML is <em>stateless</em> — you must send relevant previous messages if you want the model to "remember" them.</li>
</ul>
<pre><code class="lang-bash">[
  { role: <span class="hljs-string">"system"</span>, content: <span class="hljs-string">"You are a concise assistant."</span> },
  { role: <span class="hljs-string">"user"</span>, content: <span class="hljs-string">"Explain neural networks like I'm 10."</span> },
  { role: <span class="hljs-string">"assistant"</span>, content: <span class="hljs-string">"Short answer..."</span> }
]
</code></pre>
<h2 id="heading-stateless-vs-stateful-what-you-must-know">Stateless vs Stateful — what you must know</h2>
<p>Most public LLM APIs are stateless: each API call is independent. If you want the model to have conversation history, you must include previous messages (or a summarized version) in each request. That increases token usage, which increases cost. So:</p>
<ul>
<li><p>For multi-turn chats, either send full history or maintain a compressed memory (summary).</p>
</li>
<li><p>Always be mindful of token size limits.</p>
</li>
</ul>
<h2 id="heading-prompting-techniques">Prompting techniques</h2>
<h3 id="heading-zero-shot-prompting">Zero-shot prompting</h3>
<p><strong>Definition:</strong> No examples provided; you just ask the task.<br /><strong>When:</strong> Quick questions or when model is instruction-tuned.<br /><strong><mark>Example prompt:</mark></strong> Explain DNS to a beginner in 3 bullet points.</p>
<h3 id="heading-few-shot-prompting">Few-shot prompting</h3>
<p><strong>Definition:</strong> Give 1–5 examples in the prompt so the model sees the pattern.<br /><strong>When:</strong> When you want consistent formatting or special style.</p>
<p><strong><mark>Example prompt:</mark></strong></p>
<ul>
<li><p>Example 1: Q: Convert "January 2, 2025" to YYYY-MM-DD. A: 2025-01-02</p>
</li>
<li><p>Example 2: Q: Convert "July 15, 2024" to YYYY-MM-DD. A: 2024-07-15</p>
</li>
<li><p>Now convert: "August 3, 2023" A:</p>
</li>
</ul>
<h3 id="heading-chain-of-thought-cot-prompting">Chain-of-Thought (CoT) prompting</h3>
<p><strong>Definition:</strong> Ask the model to show its reasoning steps before the final answer.<br /><strong>When:</strong> For complex reasoning tasks; improves correctness sometimes.</p>
<h3 id="heading-self-consistency-prompting">Self-consistency prompting</h3>
<p><strong>Definition:</strong> Sample multiple reasoning chains (multiple completions) and pick the most consistent final answer among them (majority vote).<br /><strong>When:</strong> When reasoning is uncertain; reduces fragility of single sample CoT.<br /><strong>How:</strong> Generate N different chains using temperature&gt;0, then extract the final answers and pick the most common one.</p>
<h2 id="heading-lets-code">Let’s Code</h2>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> OpenAI <span class="hljs-keyword">from</span> <span class="hljs-string">"openai"</span>;

<span class="hljs-keyword">const</span> client = <span class="hljs-keyword">new</span> OpenAI({
  <span class="hljs-attr">apiKey</span>: process.env.OPENAI_API_KEY,
  <span class="hljs-attr">baseURL</span>: process.env.OPENAI_API_BASE_URL,
});

<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">parseJsonLike</span>(<span class="hljs-params">text</span>) </span>{
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">JSON</span>.parse(text);
  } <span class="hljs-keyword">catch</span> {
    <span class="hljs-keyword">const</span> start = text.indexOf(<span class="hljs-string">"{"</span>);
    <span class="hljs-keyword">const</span> end = text.lastIndexOf(<span class="hljs-string">"}"</span>);
    <span class="hljs-keyword">if</span> (start !== <span class="hljs-number">-1</span> &amp;&amp; end !== <span class="hljs-number">-1</span> &amp;&amp; end &gt; start) {
      <span class="hljs-keyword">const</span> candidate = text.slice(start, end + <span class="hljs-number">1</span>);
      <span class="hljs-keyword">return</span> <span class="hljs-built_in">JSON</span>.parse(candidate);
    }
    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">"Unable to parse JSON from model response"</span>);
  }
}

<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">main</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> systemPrompt = <span class="hljs-string">`
STRICT RULES:
- ALWAYS return a single JSON object only (no extra text).
- JSON MUST follow sequence steps: "START", one or more "THINK", then "OUTPUT".
- JSON schema: {"step":"&lt;START|THINK|OUTPUT&gt;","content":"&lt;string&gt;"}
- Do one step per assistant message and wait for the next user/assistant message.
- Do multiple THINK steps before OUTPUT.
`</span>;

  <span class="hljs-keyword">const</span> messages = [
    { <span class="hljs-attr">role</span>: <span class="hljs-string">"system"</span>, <span class="hljs-attr">content</span>: systemPrompt.trim() },
    { <span class="hljs-attr">role</span>: <span class="hljs-string">"user"</span>, <span class="hljs-attr">content</span>: <span class="hljs-string">"Please solve this equation 8 + 8 * 8 + -10"</span> },
  ];

  <span class="hljs-keyword">while</span> (<span class="hljs-literal">true</span>) {
    <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> client.chat.completions.create({
      <span class="hljs-attr">model</span>: <span class="hljs-string">"gpt-4o-mini"</span>,
      messages
    });

    <span class="hljs-keyword">const</span> raw = response.choices?.[<span class="hljs-number">0</span>]?.message?.content;
    <span class="hljs-keyword">if</span> (!raw) <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">"Empty response from model"</span>);

    <span class="hljs-keyword">const</span> parsed = <span class="hljs-keyword">await</span> parseJsonLike(raw);
    messages.push({ <span class="hljs-attr">role</span>: <span class="hljs-string">"assistant"</span>, <span class="hljs-attr">content</span>: raw });

    <span class="hljs-keyword">if</span> (parsed.step === <span class="hljs-string">"START"</span>) <span class="hljs-keyword">continue</span>;
    <span class="hljs-keyword">if</span> (parsed.step === <span class="hljs-string">"THINK"</span>) <span class="hljs-keyword">continue</span>;
    <span class="hljs-keyword">if</span> (parsed.step === <span class="hljs-string">"OUTPUT"</span>) <span class="hljs-keyword">return</span> parsed;
    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">"Model returned an unexpected step value"</span>);
  }
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> main;
</code></pre>
]]></content:encoded></item><item><title><![CDATA[Vector Embeddings: Turning Data into Meaningful Numbers]]></title><description><![CDATA[Think of this post as “Google Maps for meaning”: we’ll put words and ideas on a map, then show how Transformers (the tech behind ChatGPT) use that map to understand context and answer smartly.
Quick Primer: Tokens & Tokenization
Before anything enter...]]></description><link>https://arjuns-genai-blog.hashnode.dev/vector-embeddings-turning-data-into-meaningful-numbers</link><guid isPermaLink="true">https://arjuns-genai-blog.hashnode.dev/vector-embeddings-turning-data-into-meaningful-numbers</guid><category><![CDATA[ChaiCode]]></category><dc:creator><![CDATA[Arjun Saxena]]></dc:creator><pubDate>Fri, 15 Aug 2025 13:45:41 GMT</pubDate><content:encoded><![CDATA[<p>Think of this post as “Google Maps for meaning”: we’ll put words and ideas on a map, then show how Transformers (the tech behind ChatGPT) use that map to understand context and answer smartly.</p>
<h2 id="heading-quick-primer-tokens-amp-tokenization">Quick Primer: Tokens &amp; Tokenization</h2>
<p>Before anything enters a Transformer, text is split into <strong>tokens</strong> (small chunks like words/sub-words). Each token is then turned into numbers. That’s the gateway to everything below.<br />If you’ve written a tokenization post, link it here:</p>
<p><strong><mark>Link:</mark></strong> <a target="_blank" href="https://arjuns-genai-blog.hashnode.dev/from-words-to-numbers-understanding-tokenization-in-ai"><strong><em>Tokenization Blog</em></strong></a></p>
<h2 id="heading-input-embeddings-turning-tokens-into-meaning-vectors">Input Embeddings: turning tokens into meaning-vectors</h2>
<p>When you write “dog”, the model doesn’t see letters — it looks up a <strong>vector</strong> (a list of numbers) that captures what “dog” <strong>means</strong> in the training world. Do the same for “cat”, “dog food”, etc. Now you have points on a <strong>meaning map</strong> (vector space). Close points = similar meaning.</p>
<ol>
<li><p><strong>Dog–Cat example (your original idea):</strong><br /> Plot “dog” and “cat”; they land close (both pets). Add “dog food” and “cat food”. A search for “dog food” travels short distance from “dog” → “dog food”. Since “cat” is near “dog”, it’s easy to reach “cat food” too.</p>
</li>
<li><p><strong>Country–PM–Monument example:</strong><br /> “India PM” and “Italy PM” are both political leaders (near each other). Monuments like <strong>India Gate</strong> and <strong>Colosseum</strong> are close to their countries. Jumping from “India PM” to “Italy PM” tends to pass through related neighborhoods (countries, monuments).</p>
</li>
</ol>
<h3 id="heading-where-to-add-an-image-right-after-this-section"><strong>Where to add an image (right after this section):</strong></h3>
<ul>
<li><em>Concept art:</em> “3D scatter plot with tokens (dog, cat, dog food, cat food) clustered.”<br />  Example: The TensorFlow <strong>Embedding Projector</strong> is perfect to show neighborhoods.<br />  <mark>Link:</mark> <a target="_blank" href="https://projector.tensorflow.org/">TensorFlow Project</a> (zoom, click a point, see its nearest neighbors; great interactive for readers)</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755263275336/31c3188f-d4cf-4070-a3a8-4167c64408a9.png" alt class="image--center mx-auto" /></p>
<p>Embeddings are widely used for semantic search, clustering, recommendations, and more. For a concise official intro, see <a target="_blank" href="https://platform.openai.com/docs/guides/embeddings">OpenAI’s embeddings guide.</a></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755263433954/cd8a7dae-ddf1-4916-a46d-2953eeee2db1.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-positional-encoding">Positional Encoding</h2>
<p>Transformers don’t read left-to-right like humans. They see a <strong>set</strong> of tokens at once. Without extra info, they don’t know positions. So we <strong>add a position signal</strong> to each token embedding — classically with <strong>sinusoidal positional encodings</strong> (or with learned/rotary variants). This lets the model understand “who came before/after”.</p>
<ul>
<li><p><strong>Input</strong> to the first block = <code>token_embedding + position_embedding</code>.</p>
</li>
<li><p>Now “cat sat on the mat” isn’t the same as “mat sat on the cat”.</p>
</li>
</ul>
<h3 id="heading-where-to-add-images-end-of-this-section"><strong>Where to add images (end of this section):</strong></h3>
<ul>
<li><p>Diagram: “Token embedding + Positional encoding → Sum → fed to Transformer.”<br />  Fantastic, readable diagrams: Jay Alammar’s <em>Illustrated Transformer</em> &amp; <em>Illustrated GPT-2</em></p>
<p>  <mark>Link :-</mark> <a target="_blank" href="https://jalammar.github.io/illustrated-transformer/">https://jalammar.github.io/illustrated-transformer</a></p>
</li>
<li><p>Deep-dive references on positional encodings (sinusoidal, RoPE): useful for a “further reading” box.</p>
</li>
</ul>
<h2 id="heading-self-attention">Self-Attention</h2>
<p>Self-attention computes <strong>how relevant each other token is</strong> to the current token.</p>
<p>For each token, the model makes three projections:</p>
<ul>
<li><p><strong>Query (Q)</strong>: “What am I looking for?”</p>
</li>
<li><p><strong>Key (K)</strong>: “What do I offer?”</p>
</li>
<li><p><strong>Value (V)</strong>: “What information do I carry?”</p>
</li>
</ul>
<p>Attention weights ≈ <code>softmax((Q · K^T) / sqrt(d_k))</code><br />Then the token’s updated representation = weighted sum of <strong>V</strong> (values) across all tokens. That’s how “cat” can pay attention to “sat” and “mat” appropriately.</p>
<h2 id="heading-multi-head-attention">Multi-Head Attention</h2>
<ul>
<li><p>One attention head might focus on <strong>subject–verb</strong>, another on <strong>named entities</strong>, another on <strong>long-range dependencies</strong>.</p>
</li>
<li><p>We run <strong>several</strong> attention heads in parallel, then <strong>concatenate</strong> and <strong>project</strong> them. This gives richer context than a single head.</p>
</li>
</ul>
<h2 id="heading-transformer-block-training-vs-inference-and-softmax">Transformer Block, Training vs Inference, and Softmax</h2>
<h3 id="heading-the-block-encoderdecoder-style">The block (Encoder/Decoder style)</h3>
<p>Each block typically does:</p>
<ol>
<li><p><strong>(Multi-Head) Self-Attention</strong></p>
</li>
<li><p><strong>Add &amp; LayerNorm</strong></p>
</li>
<li><p><strong>Feed-Forward Network (MLP)</strong></p>
</li>
<li><p><strong>Add &amp; LayerNorm</strong></p>
</li>
</ol>
<h3 id="heading-training-phase-learn-everything">Training Phase (learn everything)</h3>
<ul>
<li><p>We show the model many sequences with correct answers (next word, masked word, etc.).</p>
</li>
<li><p>The model makes predictions (via <strong>softmax</strong> at the output), compares to truth, computes a <strong>loss</strong>, and updates weights via backprop.</p>
</li>
</ul>
<h3 id="heading-inference-phase-use-what-it-learned">Inference Phase (use what it learned)</h3>
<ul>
<li><p>No weight updates; the model just <strong>applies</strong> what it learned.</p>
</li>
<li><p>For generation: it predicts the next token, appends it, repeats.</p>
</li>
<li><p>For embeddings: you <strong>only</strong> run the forward pass of the embedding model to get vectors (no softmax head needed).</p>
</li>
</ul>
<h3 id="heading-softmax-the-last-mile-of-many-tasks">Softmax (the last mile of many tasks)</h3>
<p>Softmax converts raw scores (logits) into a probability distribution. For language modeling, the highest-probability token is a natural pick (or sample from the distribution for diversity).<br />In attention, a <strong>softmax</strong> turns similarity scores into attention weights (so they sum to 1).</p>
]]></content:encoded></item><item><title><![CDATA[From Words to Numbers: Understanding Tokenization in AI]]></title><description><![CDATA[What is Tokenization?
Whenever you type or ask something — For example:

“Hey, how are you?”


An AI model first breaks that text into smaller pieces.These small pieces are called tokens.
A token can be:

a letter

a word

a number

a special charact...]]></description><link>https://arjuns-genai-blog.hashnode.dev/from-words-to-numbers-understanding-tokenization-in-ai</link><guid isPermaLink="true">https://arjuns-genai-blog.hashnode.dev/from-words-to-numbers-understanding-tokenization-in-ai</guid><category><![CDATA[ChaiCode]]></category><dc:creator><![CDATA[Arjun Saxena]]></dc:creator><pubDate>Fri, 15 Aug 2025 12:05:32 GMT</pubDate><content:encoded><![CDATA[<h2 id="heading-what-is-tokenization">What is Tokenization?</h2>
<p>Whenever you type or ask something — <strong><mark>For example:</mark></strong></p>
<ul>
<li>“Hey, how are you?”</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755256839087/e054b71e-af99-4142-99fe-94a7e6f28c63.png" alt class="image--center mx-auto" /></p>
<p>An AI model first <strong>breaks that text into smaller pieces</strong>.<br />These small pieces are called <strong>tokens</strong>.</p>
<p>A token can be:</p>
<ul>
<li><p>a <strong>letter</strong></p>
</li>
<li><p>a <strong>word</strong></p>
</li>
<li><p>a <strong>number</strong></p>
</li>
<li><p>a <strong>special character</strong></p>
</li>
<li><p>a <strong>space</strong></p>
</li>
<li><p>sometimes even a <strong>whole sentence</strong></p>
</li>
</ul>
<p>The exact way depends on how the AI tool is built.</p>
<h2 id="heading-how-tokenization-works">How Tokenization Works : -</h2>
<p>An AI model have a <strong>vocabulary</strong> or <strong>dictionary</strong> that stores the most commonly used words and assigns each of them a unique ID (a number).</p>
<p><strong><mark>For example:</mark></strong></p>
<ul>
<li><p>“hello” → 02423</p>
</li>
<li><p>“hey” → 4324</p>
</li>
</ul>
<p>These numbers are called <strong>token IDs</strong>.<br />The <strong>vocabulary size</strong> means how many unique tokens the model knows.</p>
<h2 id="heading-tokenization-algorithms">Tokenization Algorithms</h2>
<p>Different models (like GPT, BERT, etc.) use different tokenization algorithms.<br />Some common types are:</p>
<ul>
<li><p><strong>Character-based</strong> → each letter is a token</p>
</li>
<li><p><strong>Word-based</strong> → each whole word is a token</p>
</li>
<li><p><strong>Subword-based</strong> (Byte Pair Encoding, Word Piece, TikToken) → common words become one token, rare words get split into smaller parts</p>
</li>
</ul>
<p>Tools like <a target="_blank" href="https://tiktokenizer.vercel.app/"><strong>TikTokenizer</strong></a> show you exactly how a model will break your text and what token IDs it assigns.</p>
<h2 id="heading-where-tokenization-is-used">Where Tokenization is Used</h2>
<h3 id="heading-search-engines">Search Engines</h3>
<p>When you search in Google, Bing, or Firefox, your query is tokenized so the system can match keywords with relevant results.</p>
<h3 id="heading-machine-translation">Machine Translation</h3>
<p>Google Translate and DeepL tokenize your sentences before converting them into another language.</p>
<h3 id="heading-chatbots-amp-virtual-assistants">Chatbots &amp; Virtual Assistants</h3>
<p>Siri, Alexa, and ChatGPT tokenize your input to understand your intent.</p>
<h3 id="heading-speech-to-text">Speech to Text</h3>
<p>Voice input is first converted to text, then tokenized for processing.</p>
<h3 id="heading-text-classification">Text Classification</h3>
<p>Used in spam detection, sentiment analysis (positive/negative review), etc.</p>
<h2 id="heading-tokenization-in-data-privacy">Tokenization In Data Privacy</h2>
<p>Here, tokenization means <strong>replacing sensitive data with fake but usable data</strong>, so the real data stays safe.</p>
<p><mark>For examples:</mark></p>
<ul>
<li><p><strong>Payments</strong> → Credit/Debit card numbers are tokenized</p>
</li>
<li><p><strong>Healthcare</strong> → Patient data is tokenized for security</p>
</li>
<li><p><strong>E-commerce Checkout</strong> → Hiding payment details</p>
</li>
<li><p><strong>Mobile Payments</strong> → Protecting UPI/card details</p>
</li>
<li><p><strong>Bank APIs</strong> → Secure transactions</p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Explained: The Real Meaning of GPT and How It Works]]></title><description><![CDATA[How AI gives you Answer

When you ask something from AI, it looks like the AI is “thinking” for a moment. But in reality, the AI is not actually thinking like humans do — it’s generating something and then giving you an answer or reply.

Every time, ...]]></description><link>https://arjuns-genai-blog.hashnode.dev/explained-the-real-meaning-of-gpt-and-how-it-works</link><guid isPermaLink="true">https://arjuns-genai-blog.hashnode.dev/explained-the-real-meaning-of-gpt-and-how-it-works</guid><category><![CDATA[Chaiaurcode]]></category><category><![CDATA[ChaiCode]]></category><category><![CDATA[AI]]></category><category><![CDATA[genai]]></category><dc:creator><![CDATA[Arjun Saxena]]></dc:creator><pubDate>Thu, 14 Aug 2025 04:38:20 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1755145829506/857c81ab-8886-4dd6-a3dc-0bde8cd66681.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-how-ai-gives-you-answer">How AI gives you Answer</h1>
<ol>
<li><p>When you ask something from AI, it looks like the AI is “thinking” for a moment.<br /> But in reality, the AI is not actually thinking like humans do — it’s generating something and then giving you an answer or reply.</p>
</li>
<li><p>Every time, the AI might give a different reply, even for the same question.</p>
</li>
<li><p>i’s an automatic process that creates your answer.</p>
</li>
</ol>
<p><strong><mark>Example :</mark></strong></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755052754718/b764be03-ea44-4d6c-a8a6-a9dd47d51a1f.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-note"><strong><mark>Note :</mark></strong></h3>
<p>Ques : - Now you might wonder — how does AI actually generate your answer?<br />Ans :- It uses something called <strong>GPT</strong>.</p>
<h1 id="heading-what-is-gpt">What is GPT?</h1>
<p><strong>GPT</strong> stands for <strong>Generative Pretrained Transformer</strong>.</p>
<p>Most famous AI tools like ChatGPT, Gemini AI, Grok, and Claude work on the same GPT concept — Generative Pretrained Transformer — even though their actual models may be different.</p>
<p>Let’s break it down:</p>
<ol>
<li><p><strong>Generative</strong> :- mean by Nature generate something whatever you give to it.</p>
</li>
<li><p><strong>Pretrained</strong> :- already we have a data so generate bases on the answer, this data is parameter of generative.</p>
</li>
<li><p><strong>Transformer</strong> : - we will talk about little later.</p>
</li>
</ol>
<p><strong><mark>Example 1:</mark></strong></p>
<ol>
<li><p>Imagine you go to an exam.</p>
</li>
<li><p>Before the exam, you studied your books, notes, and materials.</p>
</li>
<li><p>When you see the question paper, you write your answers based on what you learned earlier.</p>
</li>
<li><p>That’s exactly how GPT works — it “studies” data first, then uses it to answer your questions.</p>
</li>
</ol>
<p><strong><mark>Example 2:</mark></strong></p>
<ol>
<li><p>Humans also do the same thing.</p>
</li>
<li><p>We learn from our past knowledge, experiences, and mistakes.</p>
</li>
<li><p>When we face a new situation, we use what we learned in the past to think about the present and the future.</p>
</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755055498062/0109a658-feda-474b-9e0c-2320931a4c76.png" alt class="image--center mx-auto" /></p>
<h1 id="heading-what-is-a-transformer">What is a Transformer?</h1>
<ol>
<li><p>A Transformer is a special type of computer program first made by Google in 2017.</p>
</li>
<li><p>Google explained it in a research paper called <strong>“</strong><a target="_blank" href="https://arxiv.org/abs/1706.03762"><strong>Attention Is All You Need</strong></a><strong>”</strong>.</p>
</li>
<li><p>They first built Transformers to improve Google Translate.</p>
</li>
<li><p>A Transformer takes an input (your question) and produces an output (the answer).</p>
</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755056158628/9db33c62-1de9-4df4-aa49-69cb22b80bba.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-ai-transformers">AI Transformers</h2>
<ol>
<li><p>In AI, the Transformer predicts the next word (or actually, the next “token”) in a sentence.</p>
</li>
<li><p>For example, if you type <strong>“Hello”</strong> into ChatGPT, the model might predict the next token to be “Hey,” or “Hello there,” depending on its training data.</p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755056839566/9dec2c87-8356-42f5-be63-89c1ecea90df.png" alt class="image--center mx-auto" /></p>
</li>
<li><p>It keeps predicting tokens one by one until it reaches a special “end point.” Here I’ve called it <strong>&lt;EOF&gt;</strong> (End of File) as an example — it’s not that the transformer actually has something named EOF inside it, but it has its own internal way to know when to stop generating.</p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755057699715/640f293d-576c-44e3-8a8d-1d4837a38784.png" alt class="image--center mx-auto" /></p>
</li>
</ol>
<h3 id="heading-why-is-chatgpt-fast">Why is ChatGPT fast?</h3>
<p>Even though it’s predicting one token at a time, it does it extremely quickly because OpenAI uses many powerful GPUs (graphic processing units) working together.<br />This uses a lot of memory but allows ChatGPT to reply almost instantly.</p>
<h3 id="heading-what-is-a-token">What is a Token?</h3>
<p>A token is a small piece of text — it could be:</p>
<ul>
<li><p>a letter</p>
</li>
<li><p>a word</p>
</li>
<li><p>a space</p>
</li>
<li><p>a punctuation mark</p>
</li>
<li><p>or even a number</p>
</li>
</ul>
<p>Example:</p>
<p>In the sentence <strong>“Hey, how’s your day going?”</strong> —</p>
<ol>
<li><p>Every letter, word, space, and punctuation mark counts as a token.</p>
</li>
<li><p>Different AI models (like ChatGPT, Grok, Gemini AI, Claude) may break text into tokens in slightly different ways.</p>
</li>
<li><p>If you want to see how tokenization works, there’s a website called <strong>“</strong><a target="_blank" href="https://enc-dec-tokenization.vercel.app/"><strong>EncDec Tokenization</strong></a><strong>”</strong> where you can type something and see how it’s broken into tokens.</p>
</li>
</ol>
]]></content:encoded></item></channel></rss>