惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
云风的 BLOG
云风的 BLOG
美团技术团队
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
爱范儿
爱范儿
Stack Overflow Blog
Stack Overflow Blog
WordPress大学
WordPress大学
GbyAI
GbyAI
雷峰网
雷峰网
P
Proofpoint News Feed
IT之家
IT之家
人人都是产品经理
人人都是产品经理
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
aimingoo的专栏
aimingoo的专栏
小众软件
小众软件
T
The Blog of Author Tim Ferriss
月光博客
月光博客
V
Visual Studio Blog
L
LINUX DO - 热门话题
L
Lohrmann on Cybersecurity
T
Troy Hunt's Blog
Project Zero
Project Zero
U
Unit 42
T
Tor Project blog
Scott Helme
Scott Helme
L
LINUX DO - 最新话题
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
I
InfoQ
Cloudbric
Cloudbric
P
Proofpoint News Feed
The Cloudflare Blog
H
Heimdal Security Blog
Google DeepMind News
Google DeepMind News
The GitHub Blog
The GitHub Blog
Attack and Defense Labs
Attack and Defense Labs
有赞技术团队
有赞技术团队
T
Threat Research - Cisco Blogs
T
The Exploit Database - CXSecurity.com
J
Java Code Geeks
博客园 - 【当耐特】
Security Latest
Security Latest
The Register - Security
The Register - Security
F
Fortinet All Blogs
I
Intezer
H
Hackread – Cybersecurity News, Data Breaches, AI and More
MongoDB | Blog
MongoDB | Blog
N
Netflix TechBlog - Medium
NISL@THU
NISL@THU
T
Tenable Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
RAG Series (1): Why LLMs Need External Memory
WonderLab · 2026-05-02 · via DEV Community

Two Root Causes Behind LLM "Hallucinations"

Anyone who has worked with large language models has run into these two situations:

Situation 1: Knowledge Cutoff

You: What were our company's Q1 sales figures?
GPT: I'm sorry, my training data only goes up to early 2024 and I have
     no access to your company's internal data.

Enter fullscreen mode Exit fullscreen mode

Situation 2: Hallucination

You: How do I use LangChain's RunnablePassthrough?
GPT: RunnablePassthrough can be enabled by calling .with_config(pass_through=True)...
     (This parameter doesn't exist.)

Enter fullscreen mode Exit fullscreen mode

Both problems share the same root cause: an LLM's knowledge is frozen at training time.

The moment training completes, the model's "memory" is locked in place. It has no idea what happened today, knows nothing about your internal documents, and won't go look things up—it can only answer from memory. When memory runs dry, it either admits ignorance or invents a plausible-sounding answer.

That's where hallucinations come from: the model uses fluent language to fill in the gaps in its knowledge.


Three Solutions and How They Compare

There are three engineering approaches to this problem:

Approach Mechanism Best For Cost
Fine-tuning Retrain on new data, "bake" knowledge into parameters Fixed-domain language style, output format Expensive, slow to update, limited factual recall
Long Context Stuff all documents into the prompt Small document sets, one-off queries Token cost grows exponentially; quality degrades at extreme lengths
RAG Dynamically retrieve relevant content at query time, inject into prompt Large knowledge bases, continuously updated data Requires retrieval infrastructure

A common misconception: fine-tuning is not good at injecting new facts.

Fine-tuning changes a model's behavioral patterns and language style—it doesn't "store a book" inside the parameters. Experiments consistently show that fine-tuning on specific Q&A pairs produces limited accuracy gains on related questions, and if training data contains errors, the model confidently repeats those errors.

RAG's core advantage is separating "what to know" from "how to say it":

  • Knowledge lives in an external database and can be updated anytime
  • The model focuses purely on understanding and generation, not memorization

When should you use long context instead of RAG?
When the total document volume is under ~100K tokens, the query is one-off (not recurring), and API costs are acceptable, long context is often simpler. Claude and Gemini's extended context windows make "stuffing a whole book in" genuinely viable. But for enterprise knowledge bases—thousands of documents, continuous updates, multiple concurrent users—RAG remains the more sensible architecture.


What RAG Is: An Open-Book Exam Analogy

RAG = Retrieval-Augmented Generation.

The most intuitive way to think about it: turning a closed-book exam into an open-book exam.

Closed-book (pure LLM): The student answers purely from memory. Anything not memorized gets guessed.

Open-book (RAG): The student can consult reference materials, but still needs to understand the question, find the relevant content, and compose the answer. The reference materials are the external knowledge base; looking things up is the retrieval step.

This analogy reveals two key properties of RAG:

  1. Knowledge lives outside the model — it can be swapped and updated independently
  2. The model handles understanding and generation — after retrieval, the model still needs to "read" the content and produce a coherent response

The Complete RAG Pipeline

RAG operates in two distinct phases: the indexing phase (one-time, offline) and the query phase (real-time, per request).

RAG Architecture Overview

The two-phase RAG architecture — top: offline indexing pipeline; bottom: real-time query pipeline; both share the same Vector DB

Indexing Phase

This phase completes before any user query arrives. It's a one-time preprocessing step.

Raw Documents → Document Loading → Text Splitting → Embedding → Vector Database

Enter fullscreen mode Exit fullscreen mode

Step 1: Document Loading

Convert raw content from various formats into plain text. PDFs, Word docs, Markdown, web pages, code—each format has its own parsing challenges (tables and images in PDFs are notoriously tricky).

Step 2: Text Splitting (Chunking)

Cut long documents into smaller chunks. This step has a significant impact on final quality—chunks too large reduce retrieval precision; chunks too small lose semantic coherence. (Chunking strategies are covered in depth in a later article; for now, just understand why we split.)

Step 3: Embedding

Use an embedding model to convert each text chunk into a high-dimensional vector. This vector captures the semantic meaning of the text—semantically similar texts produce vectors that are close together in the vector space.

Step 4: Store in Vector Database

Store all vectors along with their original text in a vector database that supports similarity search (Chroma, Qdrant, Weaviate, etc.).

Query Phase

Executed in real time for every user request.

User Question → Embedding → Similarity Search → Retrieved Chunks → Prompt Assembly → LLM → Answer

Enter fullscreen mode Exit fullscreen mode

Step 1: Query Embedding

Convert the user's question into a vector using the same embedding model.

Step 2: Similarity Search

Find the Top-K most similar text chunks in the vector database. Similarity is measured by distance in vector space (cosine similarity, etc.).

Step 3: Prompt Assembly

Combine the retrieved text chunks with the user's question into a complete prompt and send it to the LLM. A typical format:

You are a knowledge assistant. Answer the user's question based solely on
the reference content provided below.

Reference content:
[Retrieved chunk 1]
[Retrieved chunk 2]
...

User question: [original question]

Please base your answer on the reference content. If the reference content
does not contain relevant information, say so clearly.

Enter fullscreen mode Exit fullscreen mode

Step 4: LLM Generation

The LLM generates an answer grounded in the provided context, rather than from its internal parameters alone.


Hands-On: A Minimal RAG in 100 Lines

No frameworks—just the OpenAI API. Let's implement a working RAG from scratch. The goal is to see exactly what each step does, without the abstraction layers of a framework hiding the details.

"""
Minimal RAG implementation — no frameworks, OpenAI API only.
Demonstrates the complete RAG pipeline: indexing + querying.
"""

import numpy as np
from openai import OpenAI

client = OpenAI()  # requires OPENAI_API_KEY environment variable

# ─────────────────────────────────────────
# Simulated knowledge base: 5 technical docs
# ─────────────────────────────────────────
DOCUMENTS = [
    "LangChain is a framework for building LLM applications, providing chaining, memory management, and tool integration.",
    "Vector databases enable semantic search by converting text into high-dimensional vectors. Common options include Chroma, Qdrant, Weaviate, and Pinecone.",
    "RAG (Retrieval-Augmented Generation) reduces LLM hallucinations by retrieving relevant documents before generation, improving answer accuracy.",
    "Embedding models convert text into fixed-dimension vectors, where semantically similar texts are positioned closer together in vector space.",
    "Fine-tuning retrains a model on specific data to adjust its behavior — it's best suited for changing output style, not injecting new factual knowledge.",
]


# ─────────────────────────────────────────
# Indexing phase: convert documents to vectors
# ─────────────────────────────────────────
def build_index(documents: list[str]) -> list[dict]:
    """
    Convert each document into a vector.
    Returns [{text, embedding}, ...]
    In production, store these in a vector database.
    """
    print(f"Indexing {len(documents)} documents...")

    index = []
    for doc in documents:
        response = client.embeddings.create(
            model="text-embedding-3-small",
            input=doc
        )
        embedding = response.data[0].embedding
        index.append({"text": doc, "embedding": embedding})

    print("Index built successfully.")
    return index


def cosine_similarity(vec_a: list[float], vec_b: list[float]) -> float:
    """Cosine similarity between two vectors. Range: -1 to 1, higher = more similar."""
    a = np.array(vec_a)
    b = np.array(vec_b)
    return float(np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b)))


# ─────────────────────────────────────────
# Query phase: retrieve + generate
# ─────────────────────────────────────────
def retrieve(query: str, index: list[dict], top_k: int = 2) -> list[str]:
    """
    Embed the query and find the top_k most similar documents.
    """
    response = client.embeddings.create(
        model="text-embedding-3-small",
        input=query
    )
    query_embedding = response.data[0].embedding

    scored = []
    for doc in index:
        score = cosine_similarity(query_embedding, doc["embedding"])
        scored.append((score, doc["text"]))

    scored.sort(key=lambda x: x[0], reverse=True)
    return [text for _, text in scored[:top_k]]


def generate(query: str, context_docs: list[str]) -> str:
    """
    Assemble retrieved docs + user question into a prompt and call the LLM.
    """
    context = "\n".join([f"- {doc}" for doc in context_docs])

    prompt = f"""You are a knowledge assistant. Answer the user's question based
solely on the reference content below. If the reference content does not contain
relevant information, say so clearly — do not make anything up.

Reference content:
{context}

User question: {query}

Answer:"""

    response = client.chat.completions.create(
        model="gpt-4o-mini",
        messages=[{"role": "user", "content": prompt}]
    )
    return response.choices[0].message.content


def rag_query(query: str, index: list[dict]) -> str:
    """Full RAG query pipeline."""
    print(f"\nQuestion: {query}")

    docs = retrieve(query, index, top_k=2)
    print(f"Retrieved {len(docs)} relevant documents:")
    for i, doc in enumerate(docs, 1):
        print(f"  [{i}] {doc[:60]}...")

    answer = generate(query, docs)
    print(f"\nAnswer: {answer}")
    return answer


# ─────────────────────────────────────────
# Run the demo
# ─────────────────────────────────────────
if __name__ == "__main__":
    # Build the index (only needs to be done once in a real system)
    index = build_index(DOCUMENTS)

    # Test with a few questions
    rag_query("What is a vector database?", index)
    rag_query("What's the difference between RAG and fine-tuning?", index)
    rag_query("What is Python's GIL?", index)  # Not in the knowledge base — testing refusal

Enter fullscreen mode Exit fullscreen mode

Sample output:

Indexing 5 documents...
Index built successfully.

Question: What is a vector database?
Retrieved 2 relevant documents:
  [1] Vector databases enable semantic search by converting text into high-dim...
  [2] Embedding models convert text into fixed-dimension vectors, where semant...

Answer: A vector database is a database system that enables semantic search by
converting text into high-dimensional vectors. Common examples include Chroma,
Qdrant, Weaviate, and Pinecone...

Question: What is Python's GIL?
Retrieved 2 relevant documents:
  [1] LangChain is a framework for building LLM applications...
  [2] Fine-tuning retrains a model on specific data...

Answer: Based on the provided reference content, I cannot answer your question
about Python's GIL — the reference material does not contain relevant information.

Enter fullscreen mode Exit fullscreen mode

Notice the last question: the knowledge base has nothing about Python's GIL, and the LLM explicitly says it can't answer rather than inventing a response. This is how RAG controls hallucinations: a constraint in the prompt instructs the model to answer only from retrieved content.


Limitations of This Implementation

The 100 lines above demonstrate the complete RAG pipeline, but there are obvious shortcomings:

Problem Cause Engineering Solution
Vectors live in memory, lost on restart No persistence Vector database (Chroma / Qdrant)
Long documents passed in directly will exceed token limits No chunking Text Splitter strategies (next article)
Poor keyword matching; pure vector retrieval only No hybrid search Hybrid search (later in series)
No quality measurement No evaluation RAGAS evaluation framework (later in series)

Each limitation maps directly to a topic covered in the upcoming articles.


Summary

This article addressed three core questions:

  1. Why RAG? — LLM knowledge cutoff and hallucinations both stem from knowledge being frozen in model parameters
  2. What is RAG? — Dynamically retrieve external knowledge at query time, inject it into the prompt, and let the LLM answer based on evidence
  3. RAG vs. alternatives — Fine-tuning changes behavior; long context works for small documents; RAG is built for large-scale, continuously-updated knowledge bases

Next up: the first deep dive into RAG's core components — text chunking strategies. Why does the chunking approach have such a dramatic impact on quality, and how do you choose between the four main strategies?


References