<?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 Aanchal Sikarwar on Medium]]></title>
        <description><![CDATA[Stories by Aanchal Sikarwar on Medium]]></description>
        <link>https://medium.com/@aanchal3104?source=rss-e3126e21e8be------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*pnMck04hFz4dOlCqMYA5UA@2x.jpeg</url>
            <title>Stories by Aanchal Sikarwar on Medium</title>
            <link>https://medium.com/@aanchal3104?source=rss-e3126e21e8be------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 00:05:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aanchal3104/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[Understanding RAG: A Deep Dive into the Four-Stage Pipeline Behind Grouned AI]]></title>
            <link>https://medium.com/@aanchal3104/understanding-rag-a-deep-dive-into-the-four-stage-pipeline-behind-modern-ai-systems-7830421c3e66?source=rss-e3126e21e8be------2</link>
            <guid isPermaLink="false">https://medium.com/p/7830421c3e66</guid>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[agentic-rag]]></category>
            <dc:creator><![CDATA[Aanchal Sikarwar]]></dc:creator>
            <pubDate>Thu, 18 Jun 2026 12:53:54 GMT</pubDate>
            <atom:updated>2026-06-19T04:31:01.404Z</atom:updated>
            <content:encoded><![CDATA[<p>For most people, RAG is simply using external sources like PDFs, documents, or databases to help an LLM answer questions it otherwise could not. From a high level perspective, that is not wrong. But there is considerably more to it than that.</p><p><em>The foundation of RAG is a four stage pipeline: Ingestion, Retrieval, Augmentation, and Generation. </em>Each stage contains multiple layers, and each layer shapes the final output in ways that are not obvious until something goes wrong. This blog walks through all four stages, what happens inside each one, and why every layer matters. Suited for all readers.</p><h3>But before we begin, why did RAG come into existence in the first place?</h3><p>Let’s say you upload your own resume and ask an AI to help you write a cover letter tailored to it. A standalone LLM has never seen your resume. Without access to that document at the moment you ask, it writes something generic that could apply to anyone.</p><p>More broadly, any query requiring knowledge the model was never trained on runs the same risk. As covered in <a href="https://medium.com/@aanchal3104/why-ai-hallucination-is-a-feature-of-the-system-not-a-bug-i-like-this-085e8058de61">Why AI Hallucination Is a Feature of the System, Not a Bug</a>, this is where hallucination occurs. Retraining the model for every new use case is not a viable solution.</p><p>This is where RAG, Retrieval Augmented Generation, comes into picture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XoDHSP0erOYB6aND-h4CnA.png" /></figure><h3>Traditional RAG pipeline:</h3><h4><strong>A. Ingestion</strong></h4><p>Before the model can retrieve anything, it needs something to retrieve from. Ingestion is the process of taking raw documents, whether PDFs, web pages, or databases, and transforming them into a format that can be searched at query time. The quality of everything that follows depends on how well this stage is done.</p><p>Ingestion breaks down into two steps: chunking and embedding.</p><p><strong>A.1 Chunking</strong></p><p>A document cannot go into the retrieval system whole. A 50 page PDF as a single unit would return the entire document for every query, flooding the context window with irrelevant content.</p><p>Chunking splits documents into smaller, retrievable pieces. Each chunk should be specific enough to be useful but large enough to make sense on its own.</p><p>The way you chunk determines what the system can and cannot find. A boundary that cuts across a key sentence means neither chunk contains the complete information. A chunk that is too small loses the surrounding context. A chunk that is too large retrieves noise alongside the relevant content.</p><p>There is no universal chunk size. The right strategy depends on your document type, your query patterns, and what your users are asking. Most RAG systems that underperform in production have a chunking problem, not a model problem.</p><p><strong>A.2 Embedding</strong></p><p>Once chunked, each piece of text needs to be converted into a format the retrieval system can compare. That format is a vector, a list of numbers that represents the meaning of the text in a high dimensional space.</p><p>Chunks with similar meaning produce vectors that sit close together in that space. Chunks with unrelated meaning sit far apart. When a user asks a question, the query is embedded using the same model, producing a vector in the same space. The retrieval system finds the chunks whose vectors are closest to the query vector.</p><p>Closest in vector space means most similar in meaning, not most similar in wording. A user asking “how do I cancel my subscription” will retrieve a chunk containing “steps to terminate your membership” even though no words overlap.</p><p>Two things matter here that are easy to miss.</p><p>The same embedding model must be used for both chunks at ingestion time and queries at retrieval time. Different models produce vectors in different spaces. Comparing them produces meaningless results.</p><p>The choice of embedding model matters as much as the choice of LLM. A general purpose model trained on web text may not understand domain specific vocabulary well enough to cluster related concepts correctly. Medical, legal, and financial systems often need domain specific embedding models to get reliable retrieval.</p><p>In practice, the full ingestion pipeline looks like this:</p><pre>from langchain_text_splitters import RecursiveCharacterTextSplitter<br>from langchain_openai import OpenAIEmbeddings<br>from langchain_pinecone import PineconeVectorStore<br><br># Load documents<br>documents = load_documents(&quot;class_notes_mid_sem/&quot;)<br><br># Chunk documents<br>text_splitter = RecursiveCharacterTextSplitter(<br>    chunk_size=500,<br>    chunk_overlap=50<br>)<br>chunks = text_splitter.split_documents(documents)<br><br># Embed and store<br>embeddings = OpenAIEmbeddings()<br>vector_store = PineconeVectorStore.from_documents(<br>    documents=chunks,<br>    embedding=embeddings<br>)</pre><p>The vector store is now ready. Every chunk is embedded and indexed. Retrieval can begin. A vector database stores embeddings and performs efficient nearest-neighbor search (Pinecone, Weaviate, Chroma, and FAISS are examples).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U4KjgLwNYzMQffQw_uY9lQ.png" /></figure><h4><strong>B. Retrieval</strong></h4><p>Once ingestion is complete, the vector store has every chunk embedded and indexed. Nothing happens until a user asks a question. That question triggers retrieval.</p><p>Retrieval finds the chunks most relevant to the query. In practice it is where most RAG systems fail quietly.</p><p><strong>B.1 Query Embedding</strong></p><p>The first step in retrieval mirrors the last step in ingestion. The user’s query is passed through the same embedding model used during ingestion, producing a vector in the same space as the document chunks.</p><p>The same model must be used for both. If the query and chunks are embedded with different models, the vectors are not comparable and similarity search produces meaningless results.</p><p><strong>B.2 Similarity Search</strong></p><p>With the query embedded, the retrieval system searches the vector store for the closest chunk vectors. This is called nearest neighbour search and it is the core operation of every RAG retrieval system.</p><p>The system returns the top-k most similar chunks, where k is a parameter you control. Too low and you risk missing the relevant chunk. Too high and you flood the context window with noise.</p><p>Most systems default to k=3 or k=5. The right value depends on your documents, your queries, and your context window budget.</p><p><strong>B.3 Why Retrieval Fails</strong></p><p>Retrieval failure is silent. The system does not error. It returns chunks confidently and the model generates from whatever it received, relevant or not.</p><p>Three ways this happens:</p><p><strong>Semantic gap</strong> — the query and the relevant chunk use different words for the same concept. Embeddings handle this better than keyword search but not perfectly. Specialised terminology can still produce poor similarity scores.</p><p><strong>Boundary failure</strong> — the relevant information was split across two chunks during ingestion. Neither chunk contains the complete answer. Both score lower than a complete but less relevant chunk.</p><p><strong>Top-k too small</strong> — the answer exists in the index but sits just outside the top-k results. A tuning decision with significant impact on answer quality.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vdDMmNAHpJtXl_vqBcUqmA.png" /></figure><p><strong>B.4 Beyond Naive Retrieval</strong></p><p>Production systems address these failure modes with two main strategies.</p><p><strong>Hybrid search</strong> combines dense vector search with sparse keyword search. Vector search captures semantic similarity. Keyword search captures exact terminology. Together they cover more ground than either approach alone.</p><p><strong>Reranking</strong> adds a second pass after retrieval. A cross-encoder model scores each retrieved chunk against the query more precisely than embedding similarity alone. You retrieve a larger set cheaply, rerank precisely, then pass only the top results forward.</p><p>Both are common in production systems, and retrieval quality requirements often determine whether they are worth the added complexity.</p><h4><strong>C. Augmentation</strong></h4><p>Retrieval returns chunks. Augmentation decides what to do with them before the model sees them.</p><p>Most explanations skip from retrieval directly to generation. They are not directly connected. What happens between retrieved chunks and the final prompt affects the quality of the generated response significantly.</p><p><strong>C.1 Context Construction</strong></p><p>Retrieved chunks cannot be dumped into the prompt as raw text. They need to be assembled into a context block the model can use effectively.</p><p>Three practical considerations:</p><p><strong>Ordering</strong> — which chunk appears first matters. Models perform worse on information placed in the middle of long contexts, a finding documented in Liu et al. 2023. The most relevant chunk should lead.</p><p><strong>Presentation</strong> — clear separators between chunks and consistent formatting help the model treat each chunk as a distinct piece of evidence rather than one continuous block of text.</p><p><strong>Filtering</strong> — not every retrieved chunk is worth including. A chunk that scored just above the retrieval threshold may add noise rather than signal. Production systems apply a similarity score cutoff below which chunks are dropped even if they were technically retrieved.</p><p><strong>C.2 Prompt Construction</strong></p><p>Once the context block is assembled, it is combined with the user query into a final prompt. This is where augmentation gets its name. The raw query is augmented with retrieved context before being passed to the model.</p><pre>You are a helpful assistant. Answer the question below<br>using only the context provided. If the context does<br>not contain enough information to answer, say so.<br>Context:<br>[chunk 1]<br>[chunk 2]<br>[chunk 3]<br>Question: [user query]<br>Answer:</pre><p>Three things this prompt does deliberately:</p><p>It tells the model to use only the provided context, reducing the chance of falling back to parametric memory.</p><p>It gives the model permission to say it does not know. Without this, models tend to generate an answer regardless of whether the context supports one.</p><p>It separates context from question clearly so the model knows what is retrieved evidence and what is the query.</p><p><strong>C.3 Why Augmentation Matters</strong></p><p>A poorly constructed prompt can cause the model to ignore correctly retrieved content. This is faithfulness failure, and it happens at the augmentation stage, not the retrieval stage.</p><p>If the prompt does not clearly instruct the model to prioritise retrieved context, training priors take over. The model reads the chunks and generates from memory anyway.</p><p>Augmentation is the stage that determines whether retrieval actually influences generation</p><h4>D. Generation</h4><p>Generation is the final stage. The augmented prompt, containing the query and the retrieved context, is passed to the model. The model reads the assembled context and produces a response.</p><p>This is the stage most people think of when they think of RAG. It gets the least attention in production engineering, mostly because by the time a well designed system reaches generation, most of the hard work is already done.</p><p><strong>D.1 What the Model Actually Does</strong></p><p>At generation time the model is not retrieving, searching, or reasoning over a knowledge base. It is doing what it always does: predicting the most probable next token given everything in the context window.</p><p>What changes is what that context window contains. Instead of just a user query, it contains retrieved context. The model’s job shifts from recalling knowledge to reading and synthesising what it was given.</p><p>RAG does not make the model smarter. It changes what the model has to work with.</p><p><strong>D.2 Where Generation Still Fails</strong></p><p>Even with a well constructed prompt, generation can fail in two ways.</p><p><strong>Faithfulness failure: </strong>the model ignores the retrieved context and generates from parametric memory instead. The retrieved content was correct. The model chose not to use it.</p><p><strong>Faithfulness hallucination: </strong>the model uses the retrieved context but misrepresents it. Facts are correct but scope or framing is wrong. Common in summarisation, where compressing content drops important qualifiers.</p><p>Both are generation stage failures. Better retrieval does not fix them. They need changes to prompt construction, model choice, or verification after generation.</p><p><strong>D.3 Post-Generation</strong></p><p>Production systems do not stop at generation. The output goes through verification before reaching the user.</p><p><strong>Citation grounding: </strong>checking that every claim in the answer can be traced to a specific retrieved chunk. Claims with no grounding get flagged.</p><p><strong>Confidence thresholding:</strong> if the response signals uncertainty or the retrieved context was weak, the system returns a fallback rather than risking a wrong answer.</p><p><strong>Output formatting:</strong> structuring the response for the interface, adding source references, formatting citations.</p><p><strong>D.4 The Full Pipeline in One View</strong></p><pre># INGESTION (offline, runs once)<br>chunks = chunk(documents, size=500, overlap=50)<br>embeddings = embed(chunks)<br>vector_store.index(chunks, embeddings)<br><br># RETRIEVAL (every query)<br>query_vector = embed(user_query)<br>retrieved_chunks = vector_store.search(query_vector, top_k=3)<br><br># AUGMENTATION (every query)<br>prompt = build_prompt(user_query, retrieved_chunks)<br><br># GENERATION (every query)<br>response = llm.generate(prompt)<br><br># POST-PROCESSING (optional)<br>response = verify_and_format(response)</pre><p>This is the complete traditional RAG pipeline.</p><h3>Beyond the Basic Pipeline</h3><p>The four stage pipeline above is the foundation. It works. But production systems rarely stop here. Once you see where the basic pipeline fails, the extensions stop looking optional.</p><h4>E. When the Basic Pipeline Is Not Enough</h4><p>Three scenarios where naive RAG underperforms:</p><p><strong>Complex multi-part queries:</strong> a question requires information from three different documents. Naive RAG retrieves the top-k chunks from a single similarity search. If the relevant information is spread across sources, one retrieval pass may not surface all of it.</p><p><strong>Specialised terminology:</strong> embedding models trained on general web text may not cluster domain-specific vocabulary correctly. A query about a specific medical procedure may miss the most relevant clinical document if the embedding model treats clinical language as noise.</p><p><strong>Queries that do not need retrieval:</strong> naive RAG retrieves for every query regardless of whether it helps. A conversational follow-up or a question the model already knows still goes through the full retrieval pipeline, adding latency for no benefit.</p><h4>F. Production RAG: Four Variants Worth Knowing</h4><p><strong>F.1 Hybrid Search</strong></p><p>Combines dense vector search with sparse keyword search, typically BM25. Vector search captures semantic similarity. Keyword search captures exact terminology. A scoring function combines both.</p><p>Use it when: your domain has specific product names, codes, or technical terms that must match precisely. Semantic similarity alone is not enough when exact terms matter.</p><p><strong>F.2 Reranking</strong></p><p>A second pass between retrieval and augmentation. After the initial top-k chunks are retrieved by embedding similarity, a cross-encoder model re-scores each chunk against the query more precisely.</p><p>The cross-encoder evaluates the query and chunk together rather than independently, producing a more accurate relevance score. You retrieve a larger set cheaply, rerank precisely, then pass only the top results forward.</p><p>Use it when: retrieval quality is the bottleneck and your latency budget allows for the extra step.</p><p><strong>F.3 HyDE: Hypothetical Document Embeddings</strong></p><p>Queries are short and interrogative. Documents are long and declarative. Their embeddings may not cluster well even when the document directly answers the query.</p><p>HyDE generates a hypothetical answer to the query first, then embeds that answer instead of the raw query. The hypothetical answer reads like the document chunks, making the similarity search more meaningful.</p><p><strong>Use it when:</strong> queries are short or ambiguous and retrieval quality is poor despite good chunking and embedding.</p><p><strong>F.4 Self-RAG</strong></p><p>Changes the assumption that retrieval should always happen. The model is trained to decide when retrieval is necessary, evaluate whether retrieved chunks are relevant, and check whether its own output is grounded in the evidence.</p><p>Use it when: queries vary significantly in whether they need external knowledge. Self-RAG avoids retrieval on queries the model can already answer confidently.</p><p>Once we begin optimizing retrieval, another question appears: how do we know whether these changes are actually improving the system?</p><h3>How to Know if Your RAG System Is Working (RAGAS)</h3><p>Building a RAG system without evaluation is building blind. Most tutorials skip this entirely. It is why most RAG systems work in demos and fail in production.</p><p>The current standard is RAGAS, Retrieval Augmented Generation Assessment, an evaluation framework that measures three distinct metrics.</p><p><strong>Faithfulness: </strong>does the answer stay grounded in the retrieved context? A score below 1.0 means the model is generating claims that cannot be traced back to retrieved chunks. Fix: prompt construction and model instruction.</p><p><strong>Context relevance: </strong>are the retrieved chunks actually relevant to the query? Low context relevance means retrieval is failing, not generation. Fix: chunking strategy, embedding model, or retrieval parameters.</p><p><strong>Answer relevance: </strong>does the answer actually address what was asked? An answer can be faithful to retrieved content and still miss the question if retrieval returned the wrong chunks. Fix: retrieval strategy.</p><p>A single end-to-end score tells you the system is failing. These three metrics tell you where.</p><pre>from ragas import evaluate<br>results = evaluate(<br> dataset,<br> metrics=[faithfulness, context_relevance, answer_relevance]<br>)</pre><h4><strong>We have come far from traditional RAG:</strong></h4><p>When RAG was first introduced, the pipeline was simple. A query comes in, relevant chunks are retrieved, injected into the prompt, and the model generates a response. Same path for every query.</p><p>This works for straightforward tasks. The problem is the pipeline is fixed. If the first retrieval returns poor results, nothing catches it. If the answer needs information from multiple sources, one retrieval pass may not surface all of it.</p><p>Agentic RAG gives the model a more active role. Instead of passively receiving retrieved chunks, it decides what to retrieve, checks whether the results are sufficient, and repeats until it has enough to answer. It acts as an orchestrator, not just a generator.</p><p>The practical difference comes down to accuracy and relevance. Traditional RAG is fast and simple. Agentic RAG trades some speed for better accuracy, making sure the answer is correct, and better relevance, making sure the retrieved content actually addresses the query.</p><h4>When RAG Is Worth It and When It Is Not</h4><p>RAG adds retrieval latency, vector store infrastructure, chunking pipelines, embedding costs, and ongoing maintenance. A standalone LLM is simpler, cheaper, and faster. RAG is worth it only when the problem actually needs it.</p><p>Worth it when:</p><p>• The knowledge is private or proprietary and was never in training data<br> • The information changes frequently and retraining is not viable<br> • Answers need to be traceable to specific sources<br> • Hallucination risk is high and the domain is high stakes</p><p>Not worth it when:</p><p>• The domain is stable and well covered in training data<br> • Queries are conversational or creative and retrieval adds no value<br> • Latency requirements are strict and retrieval overhead is unacceptable</p><p>RAG is not a universal upgrade. It is a specific solution to a specific class of problems. Using it when the problem does not call for it adds complexity without adding value.</p><p><strong>Closing and Bridge to next one</strong></p><p>RAG changed what AI systems could do. Instead of being limited to what a model memorised during training, systems can now reach into external knowledge and answer questions that would have been impossible before.</p><p>But RAG depends entirely on one piece of infrastructure we have not examined closely: the vector store. Every chunk is indexed there. Every similarity search runs against it. The speed, scale, and accuracy of retrieval all come down to how it works underneath.</p><p>Most people treat vector stores as a black box, where embeddings go in and relevant chunks come out. That black box contains some of the most interesting engineering in modern AI infrastructure.</p><p>The next blog opens it up.</p><p><strong>References</strong></p><p>Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks — Lewis et al., 2020<br> <a href="https://arxiv.org/abs/2005.11401">https://arxiv.org/abs/2005.11401</a></p><p>Lost in the Middle: How Language Models Use Long Contexts — Liu et al., 2023<br> <a href="https://arxiv.org/abs/2307.03172">https://arxiv.org/abs/2307.03172</a></p><p>RAGAS: Automated Evaluation of Retrieval Augmented Generation — Es et al., 2023<br> <a href="https://arxiv.org/abs/2309.15217">https://arxiv.org/abs/2309.15217</a></p><p>Precise Zero-Shot Dense Retrieval without Relevance Labels (HyDE) — Gao et al., 2022<br> <a href="https://arxiv.org/abs/2212.10496">https://arxiv.org/abs/2212.10496</a></p><p>Self-RAG: Learning to Retrieve, Generate, and Critique through Self-Reflection — Asai et al., 2023<br> <a href="https://arxiv.org/abs/2310.11511">https://arxiv.org/abs/2310.11511</a></p><p><strong>Previous blogs in this series:</strong></p><p><a href="https://medium.com/@aanchal3104/how-llms-work-key-concepts-behind-every-prompt-f6985a478917">How LLMs Work: Key Concepts Behind Every Prompt<br></a> <a href="https://medium.com/@aanchal3104/how-humans-learned-to-communicate-with-ai-prompt-engineering-broken-down-ce7b179e00d7">How Humans Learned to Communicate with AI: Prompt Engineering Broken Down</a><br><a href="https://medium.com/@aanchal3104/why-ai-hallucination-is-a-feature-of-the-system-not-a-bug-i-like-this-085e8058de61"> Why AI Hallucination Is a Feature of the System, Not a Bug</a></p><p>Linkedin — <a href="https://www.linkedin.com/in/aanchal-sikarwar-711223258/">https://www.linkedin.com/in/aanchal-sikarwar-711223258/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7830421c3e66" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why AI Hallucination Is a Feature of the System, Not a Bug]]></title>
            <link>https://medium.com/@aanchal3104/why-ai-hallucination-is-a-feature-of-the-system-not-a-bug-i-like-this-085e8058de61?source=rss-e3126e21e8be------2</link>
            <guid isPermaLink="false">https://medium.com/p/085e8058de61</guid>
            <category><![CDATA[llm-agent]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Aanchal Sikarwar]]></dc:creator>
            <pubDate>Wed, 03 Jun 2026 04:16:42 GMT</pubDate>
            <atom:updated>2026-06-03T04:28:04.043Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OQH-CB2jDDFXaLlD7BPZjw.png" /></figure><p>Every model that has ever confidently told you something wrong was not malfunctioning. It was doing exactly what it was trained to do.</p><p>In <a href="https://medium.com/@aanchal3104/how-humans-learned-to-communicate-with-ai-prompt-engineering-broken-down-ce7b179e00d7"><strong>How Humans Learned to Communicate with AI</strong></a>, we saw that prompts shift probability distributions. In <a href="https://medium.com/@aanchal3104/how-llms-work-key-concepts-behind-every-prompt-f6985a478917"><strong>How LLMs Work</strong></a>, we covered what happens inside the model when you hit send. This blog builds on both. Rather than re-explaining probability distributions, this blog focuses on what happens when those distributions generate fluent and convincing but incorrect outputs, and why preventing that is fundamentally difficult.</p><p>This blog is divided into two sections. The deeper problem is that language models optimise for probable continuations, not verified truth. Hallucination is therefore not an accidental bug but a structural property of how these systems generate language. Part 1 covers what hallucination is, why it happens, and why every fix has limits. Part 2 is for those who want the formal technical grounding behind those claims.</p><h3>Part 1: What Hallucination Actually Is</h3><h3>The Definition Most People Get Wrong</h3><p>Most people define hallucination as “the model making things up.” That definition is not wrong. It is just too shallow to be useful.</p><p>The more precise definition:</p><blockquote>Hallucination is any model output that is fluent and confident but unsupported by, inconsistent with, or unverifiable against reality or the provided source material.</blockquote><p>Three properties matter: fluency, perceived confidence, and lack of grounding in reality or source material. Uncertainty can reduce the risk of hallucination, but hallucinations do not always require explicit confidence.</p><p>This is what makes it dangerous. <em>Outputs that look wrong are easy to catch. The most dangerous hallucinations look right.</em></p><h3>The Four Types</h3><p>Hallucination is not one thing. There are four distinct types, each with a different cause and a different mitigation profile.</p><p><strong>Type 1: Intrinsic Hallucination</strong></p><p>The model directly contradicts provided source material.</p><pre>Source: &quot;The trial found no significant difference <br>between the treatment and control groups.&quot;</pre><pre>Model output: &quot;The trial confirmed the treatment <br>was significantly more effective than the control.&quot;</pre><p>The source is in the context window. The model contradicts it anyway, because patterns learned during training can dominate over the specific evidence provided in context.</p><p><strong>Type 2: Extrinsic Hallucination</strong></p><p>The model adds detail that cannot be verified against the source. It is neither confirmed nor contradicted by what was provided.</p><pre>Source: &quot;Einstein was born in Ulm in 1879.&quot;</pre><pre>Model output: &quot;Einstein was born in Ulm in 1879 <br>and showed exceptional mathematical ability <br>from the age of three.&quot;</pre><p>The added detail may or may not be true. The model generated it because similar sequences appear frequently in training data about Einstein, not because it was grounded in the source. This type is harder to detect because it does not contradict anything you can directly check.</p><p><strong>Type 3: Factual Hallucination</strong></p><p>Incorrect world knowledge stated as fact, independent of any source document.</p><pre>Model output: &quot;The Eiffel Tower was completed in 1901.&quot;</pre><p>It was 1889. No source document is involved. The model has learned an incorrect statistical association, and it states the wrong answer with the same fluency as a correct one.</p><p><strong>Type 4: Faithfulness Hallucination</strong></p><p>The facts are correct but the framing misrepresents what the sources actually say.</p><pre>Source A: &quot;Study A found X in population group 1.&quot;<br>Source B: &quot;Study B found Y in population group 2.&quot;</pre><pre>Model output: &quot;Studies have consistently shown X <br>across all population groups.&quot;</pre><p>Nothing is fabricated. But the summary misrepresents the scope and consistency of the evidence. Common in research summarisation tasks and particularly difficult to catch without reading the original sources.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dqNb0K2AF1_rf3Vz9eF1Mw.png" /><figcaption>Four types of hallucination</figcaption></figure><p>This often happens because summarisation rewards coherence and compression, even when important qualifiers, uncertainties, or population differences are lost.</p><h3>Why the Model Cannot Catch Itself Hallucinating</h3><p>The intuitive assumption is that a wrong answer should come with low confidence. A well-calibrated system would behave that way. Language models do not.</p><p>Kadavath et al. (2022) tested whether models could accurately assess their own correctness. The findings:</p><ul><li>Large models show some self-knowledge when explicitly asked to evaluate their own answers</li><li>This self-assessment degrades significantly on tasks outside the training distribution, precise factual recall, and multi-step reasoning</li><li>Confidence and correctness are not reliably correlated</li></ul><p>The practical implication: asking the model “are you sure?” is not a reliable verification strategy. The model can confirm a wrong answer confidently, correct a right answer under pressure, or produce a different wrong answer with equal confidence.</p><p>The reason is architectural. The model has no external reference to check against at inference time. It has only its frozen weights and the current context window. Both can be wrong. The model has no guaranteed mechanism for independently verifying that at generation time.</p><h3>Why Fluency and Truth Are Independent</h3><p>This is the core insight of this blog.</p><p>During pretraining, the model learns to predict the next token from human-written text. Human text is almost always fluent. The model generalises fluency as a near-universal property and applies it to every output regardless of content.</p><p>Factual correctness is a different matter. Training data contains misinformation, outdated facts, and confidently stated falsehoods alongside correct information. The model can reproduce both with similar fluency. It has no mechanism to separate them at output time.</p><p>The result: fluency becomes a weak signal for truthfulness. Sometimes more so, for reasons covered in the sycophancy section below.</p><h3>Why Every Fix Has Limits</h3><p><strong>Retrieval Augmented Generation (RAG)</strong></p><p>RAG grounds the model in external documents at inference time, reducing extrinsic and factual hallucination on covered topics. It does not solve intrinsic hallucination (the model can still contradict retrieved content), faithfulness hallucination (the model can misrepresent correct sources), or retrieval failure (wrong documents retrieved, or retrieval not triggered). Full coverage of RAG is in the next blog.</p><p><strong>Self-Consistency</strong></p><p>Sample multiple outputs and select the most consistent answer. Reduces hallucination on stable reasoning tasks. Does not work when the model consistently produces the same wrong answer across samples. Consistency is not correctness.</p><p><strong>Chain-of-Thought Verification</strong></p><p>Ask the model to verify its own output after generating it. The model verifies using the same weights that produced the hallucination.If the underlying internal associations are wrong, the verification step can reproduce the same error.</p><p><strong>Fine-tuning on Factual Data</strong></p><p>Reduces factual hallucination within the fine-tuning distribution. Does not generalise beyond it. Requires continuous updating. Does not address faithfulness or extrinsic hallucination.</p><p>The pattern across all four: each approach reduces hallucination in the specific failure mode it targets and fails to address other failure modes. This is why production systems layer multiple strategies rather than relying on any single fix.</p><h3>The Sycophancy Problem</h3><p>This is the most underappreciated contributor to hallucination and the one most coverage misses entirely.</p><p>RLHF (Reinforcement Learning from Human Feedback), the process used to align models after pretraining, works by collecting human ratings of model outputs and training the model to produce responses that score higher. In simple terms: humans rate which responses they prefer, and the model learns to generate more of what gets rated highly. One side effect of this process is sycophancy, where the model learns to agree with and flatter the user rather than prioritise accuracy, because agreeable responses tend to get rated higher.</p><p>Human raters consistently rate outputs higher when they are confident, agreeable, and flattering, even when uncertain or critical answers would be more accurate.</p><p>The Anthropic sycophancy paper (2023) documented three specific behaviours:</p><ul><li>Models shift answers to align with a user’s expressed prior belief, even when that belief is factually wrong</li><li>Models change a correct answer when users push back, despite no new information being provided</li><li>Models give more favourable evaluations to work when users indicate it is their own</li></ul><p>All three emerge from the same RLHF dynamic. The reward signal can unintentionally prioritise agreement and user approval over factual accuracy</p><p>This compounds hallucination in a specific way. The model’s already weak self-correction mechanism is further degraded. When a user pushes back on a hallucination, a sycophantic model may reinforce or defend the wrong answer instead of correcting it, because agreement-like behaviour can be implicitly rewarded during alignment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XqbfQubX_3j9EbsuPrAA0A.png" /></figure><p><em>I’m impressed that you’ve reached so far in this blog. You might want to consider taking a small walk and continue. Too much information for you to start hallucinating in a while. The section beyond dives deeper into some more technicality, go ahead and have fun.</em></p><h3>Part 2: The Technical Grounding</h3><p><em>This section assumes familiarity with probability distributions and basic attention mechanisms from the previous blogs.</em></p><h3>Formal Definition</h3><p>Ji et al. (2022) define hallucination as divergence between model output and grounded truth. Their taxonomy distinguishes two primary types: —</p><ul><li>intrinsic hallucination, where output contradicts the provided source, and extrinsic hallucination, where output cannot be verified against it.</li><li>Factual and faithfulness hallucination are related subtypes drawn from broader NLP literature.</li></ul><p>The key formal property is the confidence-accuracy gap:</p><pre>P(output is fluent) ≠ P(output is factually correct)</pre><pre>P(output is fluent | output is factually correct) <br>≈ <br>P(output is fluent | output is factually incorrect)</pre><p>Modern large language models are optimised for statistical fluency and coherence rather than guaranteed factual correctness. The model applies fluency indiscriminately.</p><h3>Why the Model Cannot Self-Verify</h3><p>The model computes:</p><pre>P(token | context, weights)</pre><p>Self-verification would require computing something like:</p><pre>P(token is factually correct | context, world knowledge)</pre><p>These are related but fundamentally different objectives. The model only has access to the first. The second generally requires grounding signals beyond what is contained in the model weights and current context.</p><p>Kadavath et al. (2022) operationalise this by asking models to predict their own correctness across a range of tasks. They find that while large models show above-chance self-knowledge, calibration degrades significantly on out-of-distribution inputs and multi-step reasoning tasks, precisely the settings where hallucination is most likely.</p><h3>Calibration Error</h3><p>Guo et al. (2017) show that modern neural networks are systematically overconfident. Expected Calibration Error (ECE) measures the gap between expressed confidence and actual accuracy:</p><pre>ECE = Σ (|Bm| / n) × |acc(Bm) - conf(Bm)|</pre><p>Where Bm is a confidence bucket, acc is accuracy within that bucket, and conf is average expressed confidence.</p><p>Standard training minimises classification loss, not calibration error. These are different objectives. A model can achieve high accuracy while remaining poorly calibrated because accuracy on known examples does not require honest uncertainty on unknown ones.</p><p>Temperature scaling post-training adjusts the sharpness of the output distribution:</p><pre>P(y | x) = softmax(logits / T)</pre><p>Where T &gt; 1 flattens the distribution, reducing overconfidence. It is the most widely used calibration technique but only adjusts confidence levels post-hoc. It does not change what the model knows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1NL-VayxL6r345TQ1zXrkA.png" /></figure><h3>The RLHF Sycophancy Dynamic</h3><p>Formally, the reward model trained during RLHF learns:</p><pre>R(output) ≈ P(human rates output highly)</pre><p>Human preference signals often favour outputs that appear confident, coherent, and agreeable. The language model fine-tuned to maximise R therefore:</p><blockquote>Maximising R directly rewards confident, agreeable outputs over honest uncertainty.</blockquote><p>The Anthropic paper demonstrates this through pushback experiments. When users disagree with a correct model answer, providing no new information or argument, models shift their answer toward user agreement at rates significantly above chance. The reward incentives for agreement can compete with the model’s internally learned associations for correctness.</p><h3>RAG Failure Modes Formally</h3><p>RAG changes the generation condition from:</p><pre>P(output | query, weights)</pre><p>to:</p><pre>P(output | query, retrieved_documents, weights)</pre><p>This is strictly better when retrieval is accurate and the model attends to retrieved content. The RAGAS paper (Es et al., 2023) identifies three formal failure modes:</p><p><strong>Faithfulness failure:</strong></p><pre>P(output faithful to retrieved_docs | retrieved_docs accurate) &lt; 1</pre><p>Models do not always use retrieved context even when directly relevant.</p><p><strong>Context relevance failure:</strong></p><pre>P(retrieved_docs relevant | query) &lt; 1</pre><p>Retrieval systems return irrelevant documents. The model grounds itself in wrong source material confidently.</p><p><strong>Answer relevance failure:</strong></p><pre>P(output answers query | output faithful) &lt; 1</pre><p>Output can be faithful to retrieved documents while failing to answer the actual query.</p><p>Each failure mode requires separate evaluation and mitigation. RAGAS provides automated metrics for measuring all three, and has become one of the most widely adopted frameworks for automated RAG evaluation.</p><h3>Where This Leaves Us</h3><p>Every mitigation strategy covered here reduces hallucination within a specific failure mode. None eliminates it at the model level. The most widely deployed approach in production systems is retrieval augmented generation, grounding the model in external source material at inference time. The next blog covers how RAG works, where it succeeds, and where it fails to address other failure modes.</p><p><em>Understanding why hallucination cannot be fully solved is the first step to building systems that handle it responsibly.</em></p><h3>Try It Yourself</h3><p>These experiments demonstrate hallucination types directly. Run them in any frontier model.</p><p><strong>Experiment 1: Intrinsic hallucination</strong> Paste a short paragraph with a specific claim. Then ask the model to summarise it. Check whether the summary contradicts any claim in the original. Try with a counterintuitive claim the model’s priors would push against.</p><p><strong>Experiment 2: Sycophancy</strong> Ask the model a factual question. Get its answer. Then say “I don’t think that’s right, I believe the answer is [wrong answer].” Observe whether the model maintains its correct answer or shifts to agree with you.</p><p><strong>Experiment 3: Confidence vs accuracy</strong> Ask the model ten factual questions in a domain where you know the answers. Rate each response as correct or incorrect. Then ask the model to rate its own confidence on each from 1 to 10. Check whether confidence correlates with correctness.</p><p><strong>Experiment 4: Faithfulness hallucination</strong> Provide two short paragraphs with slightly different findings on the same topic. Ask the model to summarise both. Check whether the summary accurately preserves the distinction or collapses them into a false consensus.</p><blockquote>The real danger of hallucination is not that models can be wrong. It is that they can be wrong fluently.</blockquote><h3>References</h3><p><strong>Foundational papers:</strong></p><p>Survey of Hallucination in Natural Language Generation — Ji et al., 2022 <a href="https://arxiv.org/abs/2202.03629">https://arxiv.org/abs/2202.03629</a></p><p>Language Models (Mostly) Know What They Know — Kadavath et al., 2022 <a href="https://arxiv.org/abs/2207.05221">https://arxiv.org/abs/2207.05221</a></p><p>On Calibration of Modern Neural Networks — Guo et al., 2017 <a href="https://arxiv.org/abs/1706.04599">https://arxiv.org/abs/1706.04599</a></p><p>Self-Consistency Improves Chain of Thought Reasoning — Wang et al., 2022 <a href="https://arxiv.org/abs/2203.11171">https://arxiv.org/abs/2203.11171</a></p><p><strong>Alignment research:</strong></p><p>Sycophancy to Subterfuge — Anthropic, 2023 <a href="https://arxiv.org/abs/2310.13548">https://arxiv.org/abs/2310.13548</a></p><p><strong>RAG evaluation:</strong></p><p>RAGAS: Automated Evaluation of Retrieval Augmented Generation — Es et al., 2023 <a href="https://arxiv.org/abs/2309.15217">https://arxiv.org/abs/2309.15217</a></p><p><strong>Previous blogs in this series:</strong></p><p>How LLMs Work: Key Concepts Behind Every Prompt —<a href="https://medium.com/@aanchal3104/how-llms-work-key-concepts-behind-every-prompt-f6985a478917"> </a><a href="https://medium.com/@aanchal3104/how-llms-work-key-concepts-behind-every-prompt-f6985a478917">https://medium.com/@aanchal3104/how-llms-work-key-concepts-behind-every-prompt-f6985a478917</a></p><p>How Humans Learned to Communicate with AI: Prompt Engineering Broken Down — <a href="https://medium.com/@aanchal3104/how-humans-learned-to-communicate-with-ai-prompt-engineering-broken-down-ce7b179e00d7">https://medium.com/@aanchal3104/how-humans-learned-to-communicate-with-ai-prompt-engineering-broken-down-ce7b179e00d7</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=085e8058de61" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Humans Learned to Communicate with AI: Prompt Engineering Broken Down]]></title>
            <link>https://medium.com/@aanchal3104/how-humans-learned-to-communicate-with-ai-prompt-engineering-broken-down-ce7b179e00d7?source=rss-e3126e21e8be------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce7b179e00d7</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Aanchal Sikarwar]]></dc:creator>
            <pubDate>Mon, 25 May 2026 15:53:25 GMT</pubDate>
            <atom:updated>2026-05-25T15:53:25.667Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*tnNJWR3-DXxpsYZrRBSyaw@2x.jpeg" /></figure><p>Same model. Same question. Completely different answer. The only variable was the prompt. In <a href="https://medium.com/@aanchal3104/how-llms-work-key-concepts-behind-every-prompt-f6985a478917">How LLMs Work</a>, we covered what happens inside the model. Now we cover what you can control from the outside.</p><p>This blog is divided into two sections. The first explains what each technique does. The second is for those who want to understand why and how it works from a technical and mathematical point of view.</p><p>Some of you may or may not already know some of these techniques, but this blog is meant to bridge the gap for all the upcoming blogs.</p><p>Let’s deep dive into the 5 main techniques of prompt engineering -</p><h3>Part 1: What Each Technique Does</h3><h4>1. Zero-Shot Prompting</h4><p>The simplest form of prompting. You give the model a task with <strong>no examples, no context, no guidance.</strong> Just the instruction.</p><p><strong>A zero-shot prompt looks like:</strong></p><pre>Help me create a frontend project from scratch.</pre><p>That’s it. No context about your stack, your experience level, your goals, or what “from scratch” even means to you. The model makes all of those assumptions itself.</p><p><strong>When to use it:</strong> Quick tasks where the ask is unambiguous and the stakes are low. Summarising a paragraph, translating a sentence, explaining a concept.</p><p><strong>When it breaks:</strong> The moment your task has any specificity to it. “Frontend project” could mean a React app, a vanilla HTML page, a design system, or a portfolio site. The model picks the most statistically common interpretation, which may have nothing to do with what you actually need.</p><h4>2. Few-Shot Prompting</h4><p>You give the model<strong> 2–3 examples</strong> of what good output looks like before making your actual request. The model infers the pattern from the examples in-context and applies it during generation.</p><p><strong>A few-shot prompt looks like:</strong></p><pre>Here are examples of how I structure frontend projects:</pre><pre>Example 1:<br>Project: E-commerce site<br>Structure: /components, /pages, /hooks, /utils, /api<br>Stack: Next.js, Tailwind, React Query</pre><pre>Example 2:<br>Project: Internal dashboard<br>Structure: /views, /components, /store, /services<br>Stack: React, Redux, Axios</pre><pre>Now create a project structure for a real-time <br>chat application.</pre><p><strong>When to use it:</strong> When you have a specific style, format, or judgment you want replicated. Code reviews, documentation, writing in a consistent tone across a team.</p><p><strong>When it breaks:</strong> When your examples are inconsistent. The model picks up bad patterns just as readily as good ones. It also costs you context window space on longer tasks.</p><h4>3. Chain-of-Thought Prompting</h4><p>You ask the model to reason through the <strong>problem step by step </strong>before giving a final answer. Instead of jumping straight to output, it works through intermediate reasoning first.</p><p><strong>A chain-of-thought prompt looks like:</strong></p><pre>Help me create a frontend project from scratch.</pre><pre>Before suggesting anything, think through:<br>- What are the most common mistakes in frontend <br>  project setup that cause problems later?<br>- What decisions made early are hardest to change?<br>- What does this project need to scale?</pre><pre>Then give me your recommendations.</pre><p><strong>When to use it:</strong> Complex decisions, architecture choices, debugging, anything where the right answer depends on reasoning through tradeoffs rather than just pattern matching.</p><p><strong>When it breaks:</strong> The model can generate confident, fluent reasoning that still leads to a wrong conclusion. Each step sounds logical but an early error compounds through the chain. Chain-of-thought reduces wrong answers. It does not eliminate them. It is also worth noting that the original CoT paper found this technique only improves performance in sufficiently large models. In smaller models it has little to no effect and can occasionally hurt performance</p><h4>4. Role Prompting</h4><p>You assign the model a specific identity before the task. The role shifts the model’s tone, vocabulary, reasoning depth, and perspective.</p><p><strong>A role prompt looks like:</strong></p><pre>You are a senior frontend engineer with 10 years <br>of experience who has built and scaled 3 production <br>applications from scratch. You are opinionated, <br>direct, and prioritise maintainability over cleverness.</pre><pre>Help me create a frontend project from scratch.</pre><p><strong>When to use it:</strong> When tone, expertise level, or perspective matters. Getting code review feedback, writing for a specific audience, generating advice that reflects real experience.</p><p><strong>When it breaks:</strong> Role prompting shifts style reliably. <em>It cannot inject knowledge the model does not have</em>. Assigning a role does not give the model facts it was never trained on. A model told it is a security expert still does not know about vulnerabilities discovered last week.</p><h4>5. Structured Prompting</h4><p>You use explicit formatting, sections, delimiters, and XML tags to separate your context, task, constraints, and expected output format. Nothing is left for the model to guess.</p><p><strong>A structured prompt looks like:</strong></p><pre>&lt;context&gt;<br>I am a mid-level frontend engineer building a <br>real-time chat application. Stack: React, TypeScript, <br>WebSockets. Team size: 3 engineers.<br>&lt;/context&gt;</pre><pre>&lt;constraints&gt;<br>Must be production-ready from day one.<br>No Redux. We want minimal state management overhead.<br>Must support future mobile app sharing components.<br>&lt;/constraints&gt;</pre><pre>&lt;task&gt;<br>Create a project structure with folder organisation, <br>key architectural decisions, and the first 5 files <br>I should create.<br>&lt;/task&gt;</pre><pre>&lt;format&gt;<br>- Folder structure: visual tree<br>- Key decisions: bullet points with one-line reasoning<br>- First 5 files: name and purpose<br>&lt;/format&gt;</pre><p><strong>When to use it:</strong> Any task with multiple moving parts, context, constraints, and format requirements. The more complex the task, the more structure pays off.</p><p><strong>When it breaks:</strong> If the delimiter style does not match the model’s training patterns. Historically, Claude was explicitly trained on XML structures while GPT-4 leaned toward markdown-style formatting. In 2025 and beyond, XML tag parsing has been adopted across almost all frontier models including those from OpenAI, Google, and Meta. Structured delimiters such as XML tags are widely used because they often improve instruction separation and readability. The underlying mechanism is the same regardless: use whatever delimiter style was most associated with high-quality structured content in that model’s training data</p><p>If the above gave you enough to use these techniques effectively, you are done. <em>This section is for those who want the technical/mathematical intuition behind why these techniques change model behaviour so dramatically.</em></p><h3>Part 2: Why It Actually Works</h3><h4>Why Prompting Changes the Distribution</h4><p>An LLM is not following instructions the way a computer executes code. At every step, it is predicting a probability distribution over possible next tokens and sampling from it, given everything that came before it. Formally, given a sequence of tokens x₁, x₂, …, xₙ, the model computes:</p><pre>P(xₙ₊₁ | x₁, x₂, ..., xₙ)</pre><p>A prompt does not tell the model what to do. It shifts the probability distribution over possible next tokens. Every token you add as context is another constraint that narrows that distribution.</p><p>Different prompts shift probability mass toward different tokens. To see why, consider what the model is doing after reading a vague prompt like “Help me create a frontend project from scratch.”</p><p>The next token could be almost anything. The model has no signal about your stack, your goals, or your constraints. So it defaults to the highest probability continuations given that generic context: connective, filler tokens like “using”, “with”, “in”, “you”, “the”. These are not wrong tokens. They are just the most statistically common way to continue that kind of sentence across all the training data the model has seen.</p><p>Now give the model a structured prompt with context, constraints, and a defined output format. The probability landscape shifts entirely. Tokens like “create”, “structure”, “ensure”, “React”, “WebSockets” now carry far higher probability mass, because the context you provided made them the most likely continuation. The model did not get smarter. The distribution just got narrower and more precise.</p><pre>P(&quot;create&quot; | structured prompt) &gt;&gt; P(&quot;create&quot; | vague prompt)<br>P(&quot;using&quot;  | vague prompt)      &gt;&gt; P(&quot;using&quot;  | structured prompt)</pre><p>This is the core mechanism behind every prompting technique in this blog. You are not instructing the model. You are reshaping what it considers probable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z1zV5aRTef0DoGq0Q5Ko-g.png" /></figure><p>This single insight explains everything that follows.</p><h4>Why Zero-Shot Works — and Averages</h4><p>When you type “Help me create a frontend project from scratch,” the model computes attention over those tokens and activates patterns from training data where similar sequences appeared.</p><p>The output distribution reflects the average of every frontend project explanation the model was trained on: tutorials, Stack Overflow answers, GitHub READMEs, blog posts.</p><p>That average is rarely what you specifically need.</p><h4>Why Few-Shot Works — In-Context Learning</h4><p>Your examples land in the context window and become tokens the model attends to at every generation step. The probability of the next token is now conditioned on the demonstrated pattern:</p><pre>P(xₙ₊₁ | x₁, ..., xₙ, example₁, example₂)</pre><p>The attention mechanism heavily weights those examples, collapsing the distribution toward the format and judgment you showed. No weights are updated. No fine-tuning happens. The pattern is extracted entirely from what is in the context window at inference time. This is called in-context learning.</p><p>This is also why few-shot encodes more than format. It encodes decision criteria. You never write a rule. The model statistically infers the latent patterns and preferences reflected in your examples</p><h4>Why Chain-of-Thought Works — Intermediate Token Conditioning</h4><p>Without chain-of-thought, the model compresses the entire reasoning chain into a single prediction. The correct final answer must compete directly against all plausible-sounding wrong answers in the distribution.</p><p>With chain-of-thought, intermediate reasoning tokens are generated first and those tokens become new context. Each subsequent prediction is conditioned on the previous reasoning step:</p><pre>P(answer | question, reasoning_step_1, reasoning_step_2, ...)</pre><p>instead of:</p><pre>P(answer | question)</pre><p>Intermediate reasoning tokens create additional conditioning context, which often improves performance on multi-step problems. This is also why chain-of-thought only helps on multi-step tasks. For simple lookups, there is nothing to chain.</p><p>(Note: Modern reasoning-oriented models like OpenAI’s o1/o3 series and DeepSeek-R1 appear to internally perform multi-step reasoning before producing visible output. For these models, explicitly prompting “think step by step” is unnecessary. The underlying token-conditioning math, however, remains identical.)</p><h4>Why Role Prompting Works — Training Data Co-occurrence</h4><p>The tokens “senior frontend engineer, opinionated, prioritises maintainability” activate a specific cluster of co-occurring patterns from training data: the vocabulary, reasoning depth, and tone of how engineers with that profile actually write.</p><p>This works through learned token associations. During training, these tokens appeared together with specific writing styles millions of times. At inference, including them in the prompt biases the attention mechanism toward that learned cluster.</p><p>The more specific the role, the narrower the activated cluster, the more consistent the output.</p><p>The hard limit: role prompting shifts style and reasoning pattern. It cannot add probability mass where none exists in the weights. Knowledge the model was never trained on cannot be obtained by a role.</p><h4>How Attention Decides What Matters</h4><p>At each generation step, the attention mechanism computes a relevance score between every token in the context and the token being predicted. Formally, for query Q, key K, and value V:</p><pre>Attention(Q, K, V) = softmax(QKᵀ / √dₖ) · V</pre><p>Tokens that are more relevant to the current prediction receive higher attention scores and contribute more to the output distribution. Tokens that are irrelevant are attended to less.</p><p>This is why structure matters. XML-style delimiters create clearer semantic separation between sections of the prompt, often helping the model separate instructions, context, and constraints more reliably. Without them, a long unstructured prompt creates ambiguity about what modifies what</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gSANGfkDwu0HtzdiROzdGQ.png" /></figure><h4>Why Structured Prompting Works —</h4><p>Structured prompting does three things simultaneously.</p><p>First, it creates clearer boundaries between context, instructions, constraints, and output format, helping the model associate the right information with the right task. Second, the output format itself shapes generation before the first output token is produced. Third, it compounds the effects of every other prompting technique. Role instructions, examples, reasoning steps, and formatting constraints all become part of the conditioning context the model predicts from.</p><p>These effects are compositional rather than independent. Each additional constraint reshapes the probability distribution conditioned on everything that came before it, progressively narrowing the space of likely continuations:</p><pre>P(next token | context, role, examples, reasoning, format)</pre><p>This compounding effect reflects a broader industry trend: increasingly, modern AI systems rely on context engineering techniques beyond prompting alone. The real leverage is not in clever wording. It is in precisely designing everything that enters the context window</p><h4>The Hard Limits — Where All of This Breaks</h4><p>No combination of prompting techniques can solve:</p><p><strong>Hallucination:</strong> The model always samples from a distribution. When the correct answer has low probability mass because it was never in training data, the model outputs whatever has highest probability instead. Fluency and accuracy are independent properties of the distribution.</p><p><strong>Knowledge cutoff:</strong> Weights are frozen after training. Prompting operates on fixed weights. You can steer which region of the distribution you sample from, but you cannot update what the weights know.</p><p><strong>Brittleness:</strong> Small changes in prompt tokens shift which training patterns are activated, sometimes dramatically. You are operating on a probability distribution, not a deterministic function.</p><p>These limits are not failures of prompting technique. They are fundamental properties of how language models work. It is also worth noting that user prompts interact with system instructions and alignment tuning already embedded into the model, meaning behaviour is shaped by more than just what you type.</p><p>That is what the next blog covers.</p><p><em>Prompt engineering is becoming less about clever wording and more about designing reliable AI interactions. Understanding why is the first step to building systems that actually work.</em></p><p><strong>References and Further Reading for further deep dive into mathematical understanding —</strong></p><p><strong>Foundational papers:</strong></p><ul><li>Chain-of-Thought Prompting Elicits Reasoning in Large Language Models — Wei et al., 2022 <a href="https://arxiv.org/abs/2201.11903">https://arxiv.org/abs/2201.11903</a></li><li>Attention Is All You Need — Vaswani et al., 2017 <a href="https://arxiv.org/abs/1706.03762">https://arxiv.org/abs/1706.03762</a></li><li>Language Models are Few-Shot Learners (GPT-3 paper, origin of few-shot prompting) — Brown et al., 2020 <a href="https://arxiv.org/abs/2005.14165">https://arxiv.org/abs/2005.14165</a></li></ul><p><strong>Official documentation:</strong></p><ul><li>Anthropic Prompt Engineering Guide <a href="https://docs.anthropic.com/en/docs/build-with-claude/prompt-engineering/overview">https://docs.anthropic.com/en/docs/build-with-claude/prompt-engineering/overview</a></li><li>OpenAI Prompt Engineering Guide <a href="https://platform.openai.com/docs/guides/prompt-engineering">https://platform.openai.com/docs/guides/prompt-engineering</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce7b179e00d7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Salesforce AMTS Intern Interview Experience — Summer ‘25]]></title>
            <link>https://medium.com/@aanchal3104/salesforce-amts-intern-interview-experience-summer-25-f53f57b2d130?source=rss-e3126e21e8be------2</link>
            <guid isPermaLink="false">https://medium.com/p/f53f57b2d130</guid>
            <category><![CDATA[futureforce]]></category>
            <category><![CDATA[salesforce]]></category>
            <category><![CDATA[interview]]></category>
            <dc:creator><![CDATA[Aanchal Sikarwar]]></dc:creator>
            <pubDate>Wed, 20 May 2026 15:44:01 GMT</pubDate>
            <atom:updated>2026-05-21T02:01:54.887Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Salesforce AMTS Intern Interview Experience — Summer ‘25 | Selected</strong></h3><p>The AMTS internship interview for Summer 2025 was conducted as part of the <a href="https://www.linkedin.com/posts/aanchal-sikarwar-711223258_salesforce-beatrailblazer-womenintech-activity-7208500744612634624-UhpD?utm_source=social_share_send&amp;utm_medium=member_desktop_web&amp;rcm=ACoAAD9kkj0BTTzFVxTKdDDTUBhqPT6ijeyW0Ug"><strong>Futureforce WIT Summit</strong>,</a> held from <strong>June 12–14, 2024</strong> at Salesforce’s Hyderabad office. The process unfolded across three rounds:</p><p><strong>Round 1 — Online Assessment</strong> Out of approximately <strong>4,000 applications</strong>, resumes were shortlisted for an online assessment consisting of <strong>3 coding questions</strong> to be solved within <strong>90 minutes</strong>.</p><p><strong>Round 2 — Technical Interview</strong> Candidates who qualified Round 1 were invited for an online technical interview covering:</p><ul><li>Two DSA problems</li><li>Core CS concepts: OOPs, OS, and DBMS (based on what was mentioned in the resume)</li><li>In-depth discussion on projects <em>(my projects were Deep Learning based, so those projects were discussed in depth)</em></li></ul><p>On qualifying Round 2, candidates received an invitation to the <strong>3-day in-person summit</strong>, 120 candidates out of 4000+ applicants were invited for the final round.</p><p>The OA difficulty was around LeetCode Medium to Hard, and the technical interviews followed a similar level (with most questions being around the LeetCode Medium level). The questions were primarily based on standard problem-solving patterns across topics such as dynamic programming, graphs, trees, arrays, stacks, queues, and strings.</p><p>A strong emphasis was also placed on projects and resume depth. Since my projects were deep learning–based, a significant part of the discussion focused on implementation details, technical decisions, challenges encountered, and the reasoning behind different approaches.</p><p>One of the key preparation areas for the process was being thorough with resume projects and having a clear understanding of the systems, methodologies, and tradeoffs involved in them, along with a strong understanding of CS fundamentals. Candidates were also expected to be comfortable implementing OOPs concepts in their preferred programming language and answering fundamental questions related to the language they chose for the interview.</p><p><strong>Round 3 — Techno-Managerial Round (Senior Manager)</strong> Held in-person at the summit, this round varied from candidate to candidate but was broadly a techno-managerial interview. <em>Core CS fundamentals and project</em>s were discussed in depth, with a strong emphasis on connecting technical decisions to managerial thinking, how challenges were approached, how obstacles were overcome, and the reasoning behind key choices.</p><p>Personally, I found this round to be the most engaging. The questions were challenging yet thought-provoking, and the conversation felt genuinely substantive rather than formulaic.</p><h3><strong>Beyond the Interview — The Summit Experience</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*twpJTZKSpJHIkCIi" /></figure><p>The interview was just one part of the three days. The Futureforce Women in Tech Summit itself was an experience worth talking about on its own.</p><p>The schedule was packed but well-thought-out: a networking dinner on the first evening, followed by leadership connects, panel discussions, an AI deep dive session, an alumni panel, and a volunteering activity. Every session had something concrete to take away, and none of it felt like filler.</p><p>Talking to people at Salesforce gave me a lot to think about, not just in terms of the technology they’re building, but how they think about building it. There’s a certain intentionality in how they approach product development that was genuinely interesting to observe up close.</p><p>Meeting fellow attendees was equally valuable. Being in a room with female engineering students from across the country, all at different stages and with different experiences, made for some really good conversations. You pick up a lot just from listening.</p><p>To the Futureforce team and everyone at Salesforce who put this together: it was a well-run, genuinely enriching experience. The effort to make everyone feel included and at ease was evident throughout, and it made a real difference.</p><h4><strong>What Came Next</strong></h4><p>The summit marked the beginning of something I’m grateful for. I had the opportunity to join<a href="https://www.linkedin.com/posts/aanchal-sikarwar-711223258_salesforce-futureforce-gratitude-activity-7359860318195363840-b74A?utm_source=social_share_send&amp;utm_medium=member_desktop_web&amp;rcm=ACoAAD9kkj0BTTzFVxTKdDDTUBhqPT6ijeyW0Ug"> Salesforce’s <strong>Data Cloud team</strong> as an <strong>AMTS Intern in Summer 2025</strong></a> and the experience has been every bit as interesting as those three days in Hyderabad suggested it would be.</p><p><strong>Preparation Takeaways :</strong></p><ul><li>Focus on standard DSA patterns across arrays, strings, trees, graphs, stacks, queues, and dynamic programming.</li><li>Be thorough with every project mentioned on the resume, including implementation details, tradeoffs, and technical decisions.</li><li>Revise CS fundamentals such as OOPs, OS, and DBMS.</li><li>Be comfortable writing clean code in your preferred programming language and answering language-specific fundamentals.</li></ul><p><em>Connect with me on </em><a href="https://www.linkedin.com/in/aanchal-sikarwar-711223258/"><em>LinkedIn</em></a></p><p>#Salesforce</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f53f57b2d130" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How LLMs Work: Key Concepts Behind Every Prompt]]></title>
            <link>https://medium.com/@aanchal3104/how-llms-work-key-concepts-behind-every-prompt-f6985a478917?source=rss-e3126e21e8be------2</link>
            <guid isPermaLink="false">https://medium.com/p/f6985a478917</guid>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[prompt]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <dc:creator><![CDATA[Aanchal Sikarwar]]></dc:creator>
            <pubDate>Thu, 23 Apr 2026 15:01:18 GMT</pubDate>
            <atom:updated>2026-04-23T15:01:18.500Z</atom:updated>
            <content:encoded><![CDATA[<p>If ChatGPT has ever misunderstood you, this is why. We’re in a phase where everyone is either using agentic systems or trying to build with them. Whether you’re from a tech background or not, we are encouraged to leverage LLMs to increase efficiency and deliver projects that could once take a month in less than a week. Newly turned grads and engineers like me have a lot to catch up on in this domain, even if we are not actively building an LLM but simply using one.</p><p>This is an introductory blog covering some of the essential LLM fundamentals, what happens <em>behind the screens </em>when you write a prompt and an LLM processes it. Trust me, no heavy math here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/0*28piurb1QVGiXBnT" /></figure><h4>1. Let’s begin with the difference between what you see vs what LLMs see – Tokens :</h4><p>A token is a piece of text that can represent a full word, part of a word, a single character, or even a space. Each token is mapped to a numerical (integer) value. A model’s vocabulary is made up of these tokens, and any text you provide is first broken down into them before further processing.</p><blockquote>For example:</blockquote><blockquote>“hello”→ 1 token [hello]</blockquote><blockquote>“unbelievable”→ 3 tokens [un] [bel] [ievable]</blockquote><p>Try it out yourself here – <a href="https://platform.openai.com/tokenizer">Tokenizer- OpenAI API</a>. Try with huge paragraphs, or maybe even emojis, or different languages</p><p><strong>Why is this an important parameter?</strong></p><ol><li><em>Pricing</em> – API providers charge per token, not per word. A sentence that looks short to you might be expensive in tokens, especially with code or special characters.</li><li><em>Context window </em>– Every model has a token limit (e.g., 128K for GPT-4o, 200K for Claude). Your prompt, the system instructions, the model’s response, all of it counts. Once you hit the limit, the model either refuses or starts losing information.</li><li><em>Model behavior</em> – The model doesn’t see “unbelievable” as one concept. It sees three separate pieces. This is why LLMs sometimes struggle with spelling, character counting, or word-level tasks<em>. </em>Even though LLMs have come a long way, this is why they still say – always verify the LLM’s response.</li></ol><h4>2. Next-Token Prediction – LLM Astrology?</h4><p>No, I don’t mean the LLM predicting your future – but it is predicting its next response. One token at a time.</p><p>Now that we know LLMs see tokens, the next question is, how do they generate a response?</p><p>The answer is surprisingly simple. Given everything before it, the model picks the most likely next token, appends it, and repeats. Your entire conversation with ChatGPT, every essay it writes, every piece of code it generates, it’s all built one token at a time.</p><p>Think of it like autocomplete on your phone, but trained on a massive amount of text and significantly better at it.</p><blockquote>I gave it a try, typed “The capital of France is” and set max tokens to 1. I expected “Paris” I got “The”. The model wasn’t answering my question, it was starting to rephrase it. It had no plan to say “Paris”.It just picked the single most probable next token given my input.</blockquote><blockquote>Then I changed my prompt to “Return one word with the answer to the capital of France” – and got “Paris” instantly.</blockquote><blockquote>Same knowledge, same model, but a different prompt led to a completely different first token.</blockquote><p>The model doesn’t know what you want, it predicts what text is most likely to follow your input. This might look simple, but understanding how the model picks its next token is the foundation of prompt engineering, and better prompts mean fewer wasted tokens, less cost, and faster results.</p><p>When it feels like the model understands you, what’s actually happening is that your prompt closely resembles patterns it has seen before, and it’s generating statistically likely continuations. This is also why LLMs hallucinate. If the most probable next token leads to a confident-sounding but factually wrong sentence, the model will generate it anyway. <strong><em>It has no concept of truth – only probability</em></strong>.</p><p>S<em>ome resources where you could experiment:</em></p><p>Google AI Studio –<a href="https://aistudio.google.com/"> https://aistudio.google.com</a></p><p>OpenAI Playground – <a href="https://platform.openai.com/playground">https://platform.openai.com/playground</a></p><p>HuggingFace Chat – <a href="https://huggingface.co/chat">https://huggingface.co/chat</a></p><p>Ollama –<a href="https://ollama.com/"> https://ollama.com</a></p><h4>3. Temperature – The Creativity parameter :</h4><p>So if the model predicts the next token, who decides how predictable it gets? That’s <em>temperature.</em></p><p>Temperature is a parameter that typically ranges from 0 to 1 (and sometimes beyond). At 0, the model consistently selects the most probable next token, producing deterministic and repeatable outputs. As the temperature increases toward 1, the model considers less likely tokens, resulting in more diverse and occasionally unexpected responses.</p><blockquote>I ran “Give me a metaphor for time” three times at temperature 1:</blockquote><blockquote>“Time is a river…</blockquote><blockquote>“Time is a thief…</blockquote><blockquote>“Time is a mirror…</blockquote><blockquote>Same prompt, same model – three different answers.</blockquote><blockquote>At temperature 0, all three runs gave me nearly identical structured lists of metaphors – same format, same categories, same tone. The model locked onto one path and repeated it.</blockquote><blockquote>Then I asked “What is 2 + 2?” at both temperatures – got “4&quot; every time.</blockquote><p>As we can see temperature matters most when multiple tokens have similar probabilities. At low temperature, the model sticks to the most likely option. As temperature increases, it starts considering less likely tokens, making the output more diverse.</p><p>For factual, constrained answers, it makes no difference. In practice most AI agents and coding assistants use low temperature – they need reliable, consistent outputs, not creative flair. And when you’re using ChatGPT for brainstorming, you’re benefiting from a higher temperature whether you realize it or not.</p><p>Just remember, temperature controls randomness.</p><h4>4. Context Window – The Model’s Short-Term Memory :</h4><p>We briefly mentioned the context window when talking about tokens — now let’s understand it better.</p><p>The context window is the total amount of information a model can process at one time. This includes your input, system instructions, previous messages, and even the model’s reply — all of it shares the same space.</p><p>Think of it like a whiteboard with limited space. Everything the model needs to read and write has to fit on it. If the board fills up, older content may get erased to make room for new information.</p><p>Different models come with different “whiteboard sizes,” meaning some can handle much more context than others.</p><p>For example: GPT-4o supports up to ~128K tokens, Claude 3.5 Sonnet up to ~200K tokens, while smaller open models like Llama 3 8B typically handle around 8K tokens (though this can vary by setup).</p><p>Sounds like a lot, right? But it fills up fast. A single page of text is roughly 500–800 tokens. A long document, a few back-and-forth messages, a detailed system prompt, and you’re already eating into that limit.</p><p>This is why long conversations with ChatGPT sometimes feel like the model forgot what you said earlier, it literally did. The older messages fell off the window.</p><p>For agents, this is a critical constraint. Every tool call, every observation, every reasoning step takes up space. An agent that’s verbose with its outputs will hit the ceiling faster and start losing track of what it was doing. This is why techniques like summarization, retrieval-augmented generation (bringing in only the relevant information when needed), and efficient prompt design exist, they’re all strategies to make the most of a limited whiteboard.</p><p>Want to try this yourself?</p><p>- Open any LLM chat – ChatGPT, Google AI Studio, whatever you have. Start a conversation and give it a name, a number, and a fact about yourself in the first message. Something like “My name is __, my lucky number is 42, and I love mangoes” Keep chatting about random topics for 30–40 messages. Then ask “What’s my name? What’s my lucky number? What do I love?”</p><p>With shorter context window models, it’ll start forgetting. With larger ones, it’ll hold on longer —but eventually, everything has a limit.</p><blockquote>You can also try this – paste a long article into the prompt, then ask a question about something mentioned only at the very beginning. Compare the answer with a question about something near the end. You’ll notice the model handles recent context better than older context, this is the “<strong><em>lost in the middle</em></strong>” problem, where information buried in the middle of a long context gets less attention.</blockquote><p>That’s it for this blog.</p><p>I hope by the end of this blog you’re able to clearly explain these 4 concepts, not just define them.</p><p>It’s not the intelligence you’re conversing with, it is the probability you’re guiding.</p><p><strong><em>LLMs don’t understand you, they predict you. Now you know how to work with that.</em></strong></p><p>Happy reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f6985a478917" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>