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

推荐订阅源

C
Cisco Blogs
Schneier on Security
Schneier on Security
T
Tor Project blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
T
Tenable Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
T
Threat Research - Cisco Blogs
C
CERT Recently Published Vulnerability Notes
Security Latest
Security Latest
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
NISL@THU
NISL@THU
L
Lohrmann on Cybersecurity
Scott Helme
Scott Helme
Webroot Blog
Webroot Blog
Project Zero
Project Zero
Google Online Security Blog
Google Online Security Blog
The Last Watchdog
The Last Watchdog
Spread Privacy
Spread Privacy
Hacker News: Ask HN
Hacker News: Ask HN
PCI Perspectives
PCI Perspectives
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
W
WeLiveSecurity
Attack and Defense Labs
Attack and Defense Labs
D
Darknet – Hacking Tools, Hacker News & Cyber Security
N
News | PayPal Newsroom
Help Net Security
Help Net Security
The Hacker News
The Hacker News
H
Heimdal Security Blog
O
OpenAI News
S
Security @ Cisco Blogs
N
News and Events Feed by Topic
Cyberwarzone
Cyberwarzone
Simon Willison's Weblog
Simon Willison's Weblog
G
GRAHAM CLULEY
www.infosecurity-magazine.com
www.infosecurity-magazine.com
博客园 - 叶小钗
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
Hacker News - Newest:
Hacker News - Newest: "LLM"
T
Tailwind CSS Blog
大猫的无限游戏
大猫的无限游戏
A
Arctic Wolf
I
Intezer
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
S
Security Affairs
P
Proofpoint News Feed
S
Secure Thoughts
腾讯CDC
Google DeepMind News
Google DeepMind News
量子位
罗磊的独立博客

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
86. RAG: Giving Language Models Long-Term Memory
Akhilesh · 2026-05-17 · via DEV Community

Large language models know a lot. They do not know everything.

They were trained on internet text up to a cutoff date. They have no idea what happened last week. They have no idea what is in your company's internal documentation. They have no idea what your customer support tickets say.

When asked about things outside their training, they have two choices: say they do not know, or hallucinate something plausible-sounding. They often choose the latter. Confidently. Wrongly.

RAG (Retrieval-Augmented Generation) solves this by giving the model access to an external knowledge base at query time. You retrieve relevant documents and include them in the prompt as context. The model reads the context, then answers based on what it finds there, not what it vaguely remembers from training.

The result: answers grounded in your specific, current, accurate knowledge base. Hallucinations drop dramatically. The model can cite its sources. The knowledge base updates without retraining the model.


The RAG Pipeline

import os
import re
import numpy as np
from typing import List, Dict
from sentence_transformers import SentenceTransformer
from sklearn.metrics.pairwise import cosine_similarity
import warnings
warnings.filterwarnings("ignore")

np.random.seed(42)

print("RAG Pipeline Components:")
print()
print("1. DOCUMENT INGESTION")
print("   Load documents → chunk → embed → store in vector DB")
print()
print("2. RETRIEVAL")
print("   User query → embed → find top-k similar chunks")
print()
print("3. AUGMENTED GENERATION")
print("   context = retrieved chunks")
print("   prompt  = question + context")
print("   answer  = LLM(prompt)")
print()
print("The LLM never sees the full knowledge base.")
print("It only sees: the question + the retrieved context.")

Enter fullscreen mode Exit fullscreen mode


Building a Complete RAG System

class SimpleRAG:
    """A minimal but complete RAG implementation."""

    def __init__(self, embedding_model_name="all-MiniLM-L6-v2"):
        self.embed_model = SentenceTransformer(embedding_model_name)
        self.documents   = []
        self.embeddings  = None

    def add_documents(self, docs: List[Dict]):
        """Add documents with their metadata."""
        self.documents.extend(docs)
        texts = [d["text"] for d in docs]
        new_embeddings = self.embed_model.encode(texts, show_progress_bar=False)
        if self.embeddings is None:
            self.embeddings = new_embeddings
        else:
            self.embeddings = np.vstack([self.embeddings, new_embeddings])
        print(f"  Added {len(docs)} documents. Total: {len(self.documents)}")

    def retrieve(self, query: str, top_k: int = 3) -> List[Dict]:
        """Find top-k most similar documents to the query."""
        query_emb   = self.embed_model.encode([query])
        similarities = cosine_similarity(query_emb, self.embeddings)[0]
        top_indices  = np.argsort(similarities)[::-1][:top_k]
        results = []
        for idx in top_indices:
            doc = self.documents[idx].copy()
            doc["score"] = float(similarities[idx])
            results.append(doc)
        return results

    def build_prompt(self, query: str, retrieved: List[Dict]) -> str:
        """Build the augmented prompt with retrieved context."""
        context_parts = []
        for i, doc in enumerate(retrieved, 1):
            source = doc.get("source", f"Document {i}")
            context_parts.append(f"[{i}] Source: {source}\n{doc['text']}")

        context = "\n\n".join(context_parts)
        prompt  = f"""You are a helpful assistant. Answer the question based ONLY on the provided context.
If the answer is not in the context, say "I cannot find this information in the provided context."
Always cite the source numbers [1], [2], etc. when using information from the context.

Context:
{context}

Question: {query}

Answer:"""
        return prompt

    def answer(self, query: str, top_k: int = 3,
               llm_fn=None, verbose=False) -> Dict:
        """Full RAG pipeline: retrieve + generate."""
        retrieved  = self.retrieve(query, top_k=top_k)
        prompt     = self.build_prompt(query, retrieved)

        if verbose:
            print(f"Retrieved {len(retrieved)} documents:")
            for r in retrieved:
                print(f"  [{r['score']:.3f}] {r['text'][:60]}...")
            print()

        if llm_fn is not None:
            answer_text = llm_fn(prompt)
        else:
            answer_text = "[LLM not configured — see prompt below]"

        return {
            "query":     query,
            "retrieved": retrieved,
            "prompt":    prompt,
            "answer":    answer_text,
        }

rag = SimpleRAG()

knowledge_base = [
    {
        "text": "Our Q3 2024 revenue was $4.2 million, representing a 23% increase year-over-year. "
                "Subscription revenue grew 31% to $3.1 million. Professional services declined 5%.",
        "source": "Q3 Financial Report"
    },
    {
        "text": "The refund policy allows returns within 30 days of purchase. "
                "Digital products are non-refundable once downloaded. "
                "Hardware returns require original packaging.",
        "source": "Customer Service Policy"
    },
    {
        "text": "Our machine learning platform supports Python 3.8+. "
                "Required packages: torch>=2.0, transformers>=4.30, datasets>=2.0. "
                "GPU with 8GB+ VRAM recommended for fine-tuning.",
        "source": "Technical Documentation"
    },
    {
        "text": "The CEO is Sarah Chen, appointed in January 2023. "
                "CTO is James Park, with the company since 2019. "
                "The company was founded in 2018 and is headquartered in San Francisco.",
        "source": "Company Overview"
    },
    {
        "text": "Premium plan costs $49/month and includes unlimited API calls, "
                "priority support, and access to all models. "
                "Free tier allows 1000 API calls per month.",
        "source": "Pricing Page"
    },
    {
        "text": "Model training typically takes 2-4 hours for small datasets (< 10K examples) "
                "and 12-24 hours for large datasets (> 100K examples) on a single A100 GPU. "
                "Distributed training can reduce this by 4-8x.",
        "source": "Technical Documentation"
    },
    {
        "text": "To contact support: email support@company.com or use the in-app chat. "
                "Response time: 2 hours for premium, 24 hours for free tier. "
                "Enterprise clients have a dedicated account manager.",
        "source": "Support Guide"
    },
    {
        "text": "Q4 2024 product roadmap includes: LLaMA 3 integration (January), "
                "multi-modal support (February), AutoML features (March), "
                "and enterprise SSO (April).",
        "source": "Product Roadmap"
    },
]

print("Loading knowledge base into RAG system:")
rag.add_documents(knowledge_base)

Enter fullscreen mode Exit fullscreen mode


Testing the RAG System

test_queries = [
    "What was the Q3 revenue growth?",
    "Can I get a refund for a digital product?",
    "What Python version is required?",
    "Who is the CEO?",
    "How much does the premium plan cost?",
    "What is the support response time for free users?",
    "What new features are coming in February?",
]

print("\nTesting RAG retrieval:")
print("=" * 65)

for query in test_queries:
    result = rag.answer(query, top_k=2, verbose=False)
    print(f"\nQ: {query}")
    print(f"Top retrieved document:")
    top_doc = result["retrieved"][0]
    print(f"  Source: {top_doc['source']}  (score={top_doc['score']:.3f})")
    print(f"  Text:   {top_doc['text'][:80]}...")

print()
print("=" * 65)
print("\nSample prompt for 'What was the Q3 revenue growth?':")
result = rag.answer("What was the Q3 revenue growth?", top_k=2)
print(result["prompt"])

Enter fullscreen mode Exit fullscreen mode


Connecting to a Real LLM

print("\nConnecting RAG to a real LLM:")
print()
print("Option 1: OpenAI API")
openai_integration = """
import openai

client = openai.OpenAI(api_key="your_key")

def call_gpt(prompt):
    response = client.chat.completions.create(
        model="gpt-3.5-turbo",
        messages=[{"role": "user", "content": prompt}],
        temperature=0.1,  # Low temperature for factual answers
        max_tokens=500
    )
    return response.choices[0].message.content

result = rag.answer("What was Q3 revenue?", llm_fn=call_gpt)
print(result["answer"])
"""
print(openai_integration)

print("Option 2: Anthropic Claude API")
claude_integration = """
import anthropic

client = anthropic.Anthropic(api_key="your_key")

def call_claude(prompt):
    response = client.messages.create(
        model="claude-3-haiku-20240307",
        max_tokens=500,
        messages=[{"role": "user", "content": prompt}]
    )
    return response.content[0].text

result = rag.answer("What was Q3 revenue?", llm_fn=call_claude)
print(result["answer"])
"""
print(claude_integration)

print("Option 3: Local LLM (Ollama)")
ollama_integration = """
import requests

def call_ollama(prompt, model="llama3"):
    response = requests.post(
        "http://localhost:11434/api/generate",
        json={"model": model, "prompt": prompt, "stream": False}
    )
    return response.json()["response"]

result = rag.answer("What was Q3 revenue?", llm_fn=call_ollama)
print(result["answer"])
"""
print(ollama_integration)

Enter fullscreen mode Exit fullscreen mode


Advanced RAG Techniques

print("Advanced RAG Techniques:")
print()
print("1. HYBRID SEARCH")
print("   Combine dense (embedding) and sparse (BM25/keyword) retrieval.")
print("   Dense: good at semantic understanding")
print("   Sparse: good at exact keyword matching")
print("   Hybrid: combine scores with alpha weighting")
print("   α=0: pure BM25, α=1: pure embedding, α=0.5: balanced")
print()

print("2. RERANKING")
print("   First-pass: fast retrieval with embeddings (top-20)")
print("   Second-pass: precise reranking with cross-encoder (top-3)")
print("   Cross-encoders jointly encode query+document for better scoring")
print("   Models: cross-encoder/ms-marco-MiniLM-L-6-v2 (fast)")
print()

reranker_code = """
from sentence_transformers import CrossEncoder

reranker = CrossEncoder("cross-encoder/ms-marco-MiniLM-L-6-v2")

# First pass: fast retrieval
candidates = rag.retrieve(query, top_k=20)

# Second pass: precise reranking
pairs  = [(query, doc["text"]) for doc in candidates]
scores = reranker.predict(pairs)

# Sort by reranker score
reranked = sorted(zip(scores, candidates), key=lambda x: -x[0])
top_3    = [doc for _, doc in reranked[:3]]
"""
print(reranker_code)

print("3. QUERY REWRITING")
print("   Original query: 'How does it work?'")
print("   Problem: 'it' is ambiguous")
print("   Rewritten: 'How does the RAG pipeline retrieve documents?'")
print("   Use LLM to rewrite queries before embedding")
print()

print("4. MULTI-QUERY RETRIEVAL")
print("   Generate 3-5 variations of the original query")
print("   Retrieve for each variation")
print("   Deduplicate and merge results")
print("   Captures more relevant documents with diverse phrasings")
print()

print("5. PARENT-CHILD CHUNKING")
print("   Store large parent chunks (512 tokens)")
print("   Index small child chunks (128 tokens) for precise retrieval")
print("   When child is retrieved, return its parent for more context")
print("   Best of both worlds: precise matching, rich context")

Enter fullscreen mode Exit fullscreen mode


Evaluating RAG Quality

def evaluate_retrieval(rag_system, test_cases):
    """
    test_cases: list of dicts with 'query' and 'relevant_sources'
    """
    results = []
    for case in test_cases:
        retrieved = rag_system.retrieve(case["query"], top_k=3)
        retrieved_sources = [r["source"] for r in retrieved]
        relevant = case["relevant_sources"]

        hits = sum(1 for s in retrieved_sources if s in relevant)
        recall_at_3 = hits / len(relevant) if relevant else 0
        results.append({
            "query":       case["query"],
            "recall@3":    recall_at_3,
            "retrieved":   retrieved_sources,
            "relevant":    relevant,
        })
    return results

test_cases = [
    {"query": "Q3 revenue figures",      "relevant_sources": ["Q3 Financial Report"]},
    {"query": "refund for software",     "relevant_sources": ["Customer Service Policy"]},
    {"query": "Python requirements",     "relevant_sources": ["Technical Documentation"]},
    {"query": "company leadership team", "relevant_sources": ["Company Overview"]},
    {"query": "pricing monthly plan",    "relevant_sources": ["Pricing Page"]},
]

eval_results = evaluate_retrieval(rag, test_cases)

print("RAG Retrieval Evaluation:")
print(f"{'Query':<35} {'Recall@3':>10} {'Correct?':>9}")
print("=" * 58)
for r in eval_results:
    correct = "" if r["recall@3"] == 1.0 else ""
    print(f"{r['query']:<35} {r['recall@3']:>10.2f} {correct:>9}")

avg_recall = np.mean([r["recall@3"] for r in eval_results])
print(f"\nMean Recall@3: {avg_recall:.3f}")
print()
print("Evaluation frameworks for production RAG:")
print("  RAGAS: ragasframework.com — automated RAG evaluation")
print("  TruLens: trulens.org — LLM app evaluation")
print("  DeepEval: confident-ai.com — unit tests for LLM applications")

Enter fullscreen mode Exit fullscreen mode


A Resource Worth Reading

The original RAG paper "Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks" by Lewis et al. (2020) from Facebook AI introduces the concept and evaluates it on open-domain QA benchmarks. Short and readable. Shows the evidence that retrieval dramatically reduces hallucination. Search "Lewis retrieval-augmented generation knowledge-intensive NLP 2020."

Lilian Weng wrote "Large Language Model Based Agents" at lilianweng.github.io which covers RAG as part of the broader agent architecture landscape. Includes evaluation frameworks, advanced retrieval techniques, and production patterns. One of the most comprehensive technical posts on LLM applications available. Search "Lilian Weng large language model agents."


Try This

Create rag_practice.py.

Part 1: build a RAG system over a real document set. Use 20+ Wikipedia articles on a topic you know well (machine learning, history, sports, whatever). Load them, chunk into 512-character pieces with 64-character overlap, embed with all-MiniLM-L6-v2, store in a simple NumPy array.

Part 2: implement retrieval. Given 10 different queries, retrieve top 3 chunks. Print the query, the source document name, the similarity score, and the chunk text. Are the retrieved chunks relevant?

Part 3: connect to an LLM. Use either OpenAI, Anthropic, or Ollama. Build the full pipeline: question → retrieve → augment prompt → LLM → answer. Ask 5 questions. Compare the answers with and without RAG context. Do the RAG answers cite specific facts from the documents?

Part 4: test hallucination. Ask a question whose answer is NOT in your knowledge base. With a good RAG prompt, the LLM should say "I cannot find this information." Without RAG, the base model will likely hallucinate. Document both behaviors.


What's Next

RAG gives models knowledge. The next post puts it all together: building a complete chatbot with conversation memory, RAG, and a web interface. This is the practical application that everything in Phase 8 has been building toward.