RAG_Techniques

NirDiamant活跃维护 有专家点评

用 Jupyter Notebook 逐个演示 RAG 系统的进阶技巧,从嵌入、检索到重排都有可运行教程,适合动手搭建和优化检索增强生成流程。

This repository showcases various advanced techniques for Retrieval-Augmented Generation (RAG) systems. Each technique has a detailed notebook tutorial.

ai-agents-book-v1.0发布于 2026-10-26 15:36 UTC30,305star +43 / 7 天3,704fork同步于 2026-11-10 23:23 UTC

专家点评

上手难度:进阶更新于 2026-11-11

RAG 技术选型时的对照实验场,不是能直接部署的检索服务

适用场景

  • 在给现有 RAG 管线选检索策略时:把 naive、HyDE、contextual compression、rerank 等 notebook 各跑一遍,用同一份数据横向对比,比读论文快
  • 需要向团队解释某个 RAG 技巧到底在做什么时:每个目录自带直觉讲解和可运行代码,可以直接当内部技术分享的素材
  • 想验证某个新检索思路值不值得投入工程化时:先照 notebook 改两行跑通,再决定要不要写进生产代码,避免一上来就搭框架
  • 教学或新人 onboarding:让新人按目录顺序跑一遍,建立对检索增强整体流程的认知,比直接扔进 LangChain 文档里快

踩坑

  • 仓库没有统一的依赖声明,每个 notebook 各自为政,环境冲突会在跑第二个技术时出现;建议一个技术一个 venv,别指望一次 pip install 全跑通
  • issue 里反复出现 notebook 路径失效(README 指向的 ipynb 404)和 API 迁移(llama_index 的 service_context 改 Settings)两类问题,说明代码随上游库版本漂移,clone 到旧 commit 或锁定依赖版本再跑
  • 这是教程集合不是库,没有抽象层也没有测试,想把它当组件 import 进自己项目会撞上大量重复代码和硬编码的模型调用

同类对比

要的是能上生产的 RAG 引擎而不是教学材料,看 R2R 或 LlamaIndex 本身;只想快速搭个 demo 对比效果,LangChain 的模板仓库更省事。

怎么上手

由 README 提炼,执行前请确认
git clone https://github.com/NirDiamant/RAG_Techniques.git
cd all_rag_techniques/technique-name
硬件要求按 README 说明

README 未说明

下载:源码 zip·GitHub Releases(安装包)本站不镜像安装包

项目说明

由 README 自动翻译提炼

42+ 个可运行 notebook 覆盖 RAG 从基础到前沿技术,帮你快速上手并对比实现

用 Jupyter Notebook 逐个演示 RAG 系统的进阶技巧,从嵌入、检索到重排都有可运行教程,适合动手搭建和优化检索增强生成流程。

核心能力

  • 提供 42+ 个可运行的 RAG 技术 notebook
  • 每个技术配独立目录与详细实现教程
  • 覆盖从基础到前沿的检索增强生成方法
  • 附直觉讲解、代码与参考文献

容易踩的坑

README 未说明依赖安装步骤,需自行按各 notebook 准备环境;需先克隆仓库并进入具体技术目录再按教程运行

内容由模型根据 README 生成,可能不完整或不准确,以官方文档为准。看原文 README

最近发版

2 个版本ai-agents-book-v1.0
  1. ai-agents-book-v1.0AI Agents Made Simple: the new book from the author of this repo最新正式版2026-10-26 · 2026-10-26 15:36 UTC

    📖 New book from the author of this repo: AI Agents Made Simple

    From the author of RAG Techniques, and the maintainer of the GenAI Agents and Agents Towards Production repos: a decision guide to AI agents. 28 chapters, 148 illustrations, no code. For every agent pattern: how it works, what breaks, what it costs, and when it is overkill.

    Launch price: $0.99 on Kindle for the first 24 hours → https://www.amazon.com/dp/B0HNXRSRH2

    Thank you for the stars. They are why these books exist.

  2. book-v1.0RAG Made Simple: Visual Companion Book2026-04-15 · 2026-04-15 15:30 UTC
    查看更新说明

    After years of writing and teaching RAG techniques through this repository, I'm sharing something I've been working on alongside it: a companion book that turns the ideas behind this repo into a visual, code-free learning experience.

    RAG Made Simple: The Complete Visual Guide to Retrieval-Augmented Generation is built around a simple idea. You can't build what you don't understand. Every technique is taught through clear visual diagrams and plain-English analogies, so you grasp the why before you write a single line of code.

    What's inside

    22 production-grade RAG techniques, grouped into four themes:

    • The foundations. Simple RAG, reliable RAG, semantic chunking, contextual headers.
    • Smarter retrieval. HyDE, query transformations, fusion retrieval, reranking, hierarchical indices.
    • Advanced architectures. Corrective RAG, adaptive RAG, self-RAG with feedback loops, multi-modal RAG.
    • The cutting edge. Graph RAG, agentic RAG, dartboard retrieval, explainable retrieval, RAG evaluation.

    Who this book is for

    AI engineers, ML practitioners, software developers, and technical leaders who want to build RAG systems that actually work in production, without wading through hundreds of pages of boilerplate code.

    If you've ever tried to follow a RAG tutorial and ended up more confused than when you started, this book exists for you. By the final chapter you'll understand 22 distinct techniques well enough to choose the right one, explain it to your team, and ship it.

    Launch pricing this week only

    RAG Made Simple is at $0.99 for a short time while the launch window is open. Grab it now before the price goes up.

    Get RAG Made Simple on Amazon: https://amzn.to/4cvxqSw

    Also available on Kindle Unlimited for subscribers.

    Companion book also on countdown this week

    The series prerequisite, Prompt Engineering: Master the Art of AI Interaction from Zero to Hero, is on a Kindle Countdown Deal at $2.99 for 7 days (April 15 through 21). If you want to strengthen your prompting foundations before working through the RAG techniques, this is the moment to grab it.

    Get Prompt Engineering at countdown pricing: https://www.amazon.com/dp/B0DZ85RPB5?tag=diamantai-ragrm-20

    A personal thank you

    This repo wouldn't exist in its current form without the community around it. Every star, every issue, every pull request, every email from an engineer who learned RAG from these notebooks shaped what this book became. Thank you for making this one of the most referenced RAG resources on GitHub, with over 26,000 stars and readers across the AI engineering community.

    If you read the book and have feedback, whether technical errors, missing techniques, or anything that could be explained better, open an issue on this repo or reach out directly. I'd love to hear from you.

    Nir Diamant

用户点评

登录用户的真实使用记录,可按版本和硬件筛选
共 0 条

    还没有人点评。第一个说出真实体验的人最有价值。

    README 原文

    未翻译

    AI Agents Made Simple reached #1 in Software Development, Software Engineering and Software Design Tools on Amazon.com's Kindle Store. A decision guide to building AI agents that work: 28 chapters, 148 illustrations, no code. Get the book on Amazon →

    Advanced RAG Techniques 🚀

    Elevating Your Retrieval-Augmented Generation Systems

    A community-driven hub of 42+ runnable notebooks covering RAG techniques from foundational to cutting-edge - the intuition, the code, and the references to build more accurate, context-rich retrieval systems.


    PRs Welcome LinkedIn Twitter Reddit Discord Sponsor

    RAG Made Simple - the 400-page visual companion to this repo. Amazon Bestseller in Generative AI

    Get it on Amazon (paperback · Kindle · free on Kindle Unlimited) → · Read Chapter 1 free

    Sponsors ❤️

    We gratefully acknowledge the organizations and individuals who have made significant contributions to this project.

    Company Sponsors

    Individual Sponsors

    📫 Stay Updated!

    Subscribe to DiamantAI Newsletter

    Join over 50,000 AI enthusiasts getting unique cutting-edge insights and free tutorials! Plus, subscribers get exclusive early access and special 33% discounts on my books!

    DiamantAI's newsletter

    I break these ideas down into short, one-idea-per-episode explainers on YouTube.

    Subscribe on YouTube   Browse every episode →

    Introduction

    Retrieval-Augmented Generation (RAG) is revolutionizing the way we combine information retrieval with generative AI. This repository showcases a curated collection of advanced techniques designed to supercharge your RAG systems, enabling them to deliver more accurate, contextually relevant, and comprehensive responses.

    Our goal is to provide a valuable resource for researchers and practitioners looking to push the boundaries of what's possible with RAG. By fostering a collaborative environment, we aim to accelerate innovation in this exciting field.

    Related Projects

    🚀 Agents Towards Production - code-first tutorials for shipping production-grade GenAI agents, prototype to scale.

    🤖 GenAI Agents - a broad collection of AI agent implementations and tutorials.

    🖋️ Prompt Engineering Techniques - prompting strategies from basics to advanced.

    🧠 Agent Memory Techniques - 30 notebooks on agent memory: vector stores, knowledge graphs, Mem0, MemGPT, Zep, Graphiti.

    Join the community

    Contributions make this better - propose ideas, share techniques, or give feedback via CONTRIBUTING.md.

    r/EducationalAI · Discord · LinkedIn

    Key Features

    • 🧠 State-of-the-art RAG enhancements
    • 📚 Comprehensive documentation for each technique
    • 🛠️ Practical implementation guidelines
    • 🌟 Regular updates with the latest advancements

    Advanced Techniques

    Explore our extensive list of cutting-edge RAG techniques:

    Recently added: Document Parsing with Mistral OCR 4.1 (sponsored by Mistral AI), MemoRAG (memory-augmented retrieval), End-to-End RAG Evaluation, Open-RAG-Eval, JSON RAG. 42 notebooks and growing.

    #CategoryTechniqueView
    1Foundational 🌱Basic RAG
    2Foundational 🌱RAG with CSV Files
    3Foundational 🌱Reliable RAG
    4Foundational 🌱Optimizing Chunk Sizes
    5Foundational 🌱Proposition Chunking
    6Query Enhancement 🔍Query Transformations
    7Query Enhancement 🔍HyDE (Hypothetical Document Embedding)
    8Query Enhancement 🔍HyPE (Hypothetical Prompt Embedding)
    9Context Enrichment 📚Contextual Chunk Headers
    10Context Enrichment 📚Relevant Segment Extraction
    11Context Enrichment 📚Context Window Enhancement
    12Context Enrichment 📚Semantic Chunking
    13Context Enrichment 📚Contextual Compression
    14Context Enrichment 📚Document Augmentation
    15Advanced Retrieval 🚀Fusion Retrieval
    16Advanced Retrieval 🚀Reranking
    17Advanced Retrieval 🚀Multi-faceted Filtering
    18Advanced Retrieval 🚀Hierarchical Indices
    19Advanced Retrieval 🚀Dartboard Retrieval
    20Advanced Retrieval 🚀Multi-modal RAG with Captioning
    21Iterative Techniques 🔁Retrieval with Feedback Loop
    22Iterative Techniques 🔁Adaptive Retrieval
    23Evaluation 📊DeepEval
    24Evaluation 📊GroUSE
    25Explainability 🔬Explainable Retrieval
    26Advanced Architecture 🏗️Graph RAG with LangChain
    27Advanced Architecture 🏗️Microsoft GraphRAG
    28Advanced Architecture 🏗️RAPTOR
    29Advanced Architecture 🏗️Agentic RAG with Contextual AI
    30Advanced Architecture 🏗️Self-RAG
    31Advanced Architecture 🏗️Corrective RAG (CRAG)
    32Advanced Architecture 🏗️Local Graph RAG with Verifiable Attribution
    33Advanced Architecture 🏗️LightRAG
    34Evaluation 📊End-to-End RAG Evaluation
    35Evaluation 📊Open-RAG-Eval
    36Advanced 🔬MemoRAG
    37Special Technique 🌟Sophisticated Controllable Agent
    38Foundational 🌱Document Parsing with Mistral OCR 4.1 (sponsored by Mistral AI)

    🌱 Foundational RAG Techniques

    1. Simple RAG 🌱

      Overview 🔎

      Introducing basic RAG techniques ideal for newcomers.

      Implementation 🛠️

      Start with basic retrieval queries and integrate incremental learning mechanisms.

    2. Simple RAG using a CSV file 🧩

      • 🎬 Watch it explained: How Do You Search a Spreadsheet by Meaning? — turn each row into one labelled line and search the table by meaning; ask which customers are "in South American countries" and the Chile record comes back even though those words never appear.
      • LangChain:
      • LlamaIndex:

      Overview 🔎

      Introducing basic RAG using CSV files.

      Implementation 🛠️

      This uses CSV files to create basic retrieval and integrates with openai to create question and answering system.

    3. Reliable RAG 🏷️:

      • 🎬 Watch it explained: How Do You Know Your RAG Answer Isn't Made Up? — the three checkpoints that catch a bad chunk on the way in and an unsupported claim on the way out, plus the source highlighting that lets a skeptical reader verify the answer themselves.

      Overview 🔎

      Enhances the Simple RAG by adding validation and refinement to ensure the accuracy and relevance of retrieved information.

      Implementation 🛠️

      Check for retrieved document relevancy and highlight the segment of docs used for answering.

    4. Choose Chunk Size 📏

      Overview 🔎

      Selecting an appropriate fixed size for text chunks to balance context preservation and retrieval efficiency.

      Implementation 🛠️

      Experiment with different chunk sizes to find the optimal balance between preserving context and maintaining retrieval speed for your specific use case.

    5. Proposition Chunking ⛓️‍💥:

      Overview 🔎

      Breaking down the text into concise, complete, meaningful sentences allowing for better control and handling of specific queries (especially extracting knowledge).

      Implementation 🛠️

      • 💪 Proposition Generation: The LLM is used in conjunction with a custom prompt to generate factual statements from the document chunks.
      • ✅ Quality Checking: The generated propositions are passed through a grading system that evaluates accuracy, clarity, completeness, and conciseness.
    6. Simple RAG with JSON

      Overview 🔎

      RAG with JSON documents is a method of using JSON files to create a retrieval and question answering system.

      Implementation 🛠️

      • 📄 Data Loading & Extraction: JSON data with multiple fields per entry is loaded, and most relevant text fields are combined to generate an embedding.
      • 🔍 Retrieval: The system retrieves the most relevant JSON entries based on the user's query.
    1. Document Parsing with Mistral OCR 4.1 📄:

    Overview 🔎

    Most PDF-based techniques here start with a plain text extractor, and none of them checks what it produced. This notebook prints it, shows a results table losing its structure before indexing, and swaps the parsing step for Mistral OCR 4.1 while the rest of the pipeline stays identical.

    Implementation 🛠️

    • 🧪 Controlled comparison: the repository's own encode_pdf() pipeline, then the same pipeline with OCR 4.1 as the parser.
    • 🧱 Block-aware chunking: OCR 4.1 labels every block, so each table stays whole together with its caption instead of being cut by a character splitter.
    • 📈 Reranking all three pipelines: PyPDF ends with a confident wrong number, the block-aware pipeline with the right one.
    • 💾 Runs without a Mistral key: the OCR output ships in data/mistral_ocr_cache/.
    Additional Resources 📚

    🔍 Query Enhancement

    1. Query Transformations 🔄

      Overview 🔎

      Modifying and expanding queries to improve retrieval effectiveness.

      Implementation 🛠️

      • ✍️ Query Rewriting: Reformulate queries to improve retrieval.
      • 🔙 Step-back Prompting: Generate broader queries for better context retrieval.
      • 🧩 Sub-query Decomposition: Break complex queries into simpler sub-queries.
    2. Hypothetical Questions (HyDE Approach) ❓

      Overview 🔎

      Generating hypothetical questions to improve alignment between queries and data.

      Implementation 🛠️

      Create hypothetical questions that point to relevant locations in the data, enhancing query-data matching.

      Additional Resources 📚

    📚 Context and Content Enrichment

    1. Hypothetical Prompt Embeddings (HyPE) ❓🚀

      Overview 🔎

      HyPE (Hypothetical Prompt Embeddings) is an enhancement to traditional RAG retrieval that precomputes hypothetical prompts at the indexing stage, but inseting the chunk in their place. This transforms retrieval into a question-question matching task. This avoids the need for runtime synthetic answer generation, reducing inference-time computational overhead while improving retrieval alignment.

      Implementation 🛠️

      • 📖 Precomputed Questions: Instead of embedding document chunks, HyPE generates multiple hypothetical queries per chunk at indexing time.
      • 🔍 Question-Question Matching: User queries are matched against stored hypothetical questions, leading to better retrieval alignment.
      • ⚡ No Runtime Overhead: Unlike HyDE, HyPE does not require LLM calls at query time, making retrieval faster and cheaper.
      • 📈 Higher Precision & Recall: Improves retrieval context precision by up to 42 percentage points and claim recall by up to 45 percentage points.

      Additional Resources 📚

    2. Contextual Chunk Headers :label::

      Overview 🔎

      Contextual chunk headers (CCH) is a method of creating document-level and section-level context, and prepending those chunk headers to the chunks prior to embedding them.

      Implementation 🛠️

      Create a chunk header that includes context about the document and/or section of the document, and prepend that to each chunk in order to improve the retrieval accuracy.

      Additional Resources 📚

      dsRAG: open-source retrieval engine that implements this technique (and a few other advanced RAG techniques)

    3. Relevant Segment Extraction 🧩:

      Overview 🔎

      Relevant segment extraction (RSE) is a method of dynamically constructing multi-chunk segments of text that are relevant to a given query.

      Implementation 🛠️

      Perform a retrieval post-processing step that analyzes the most relevant chunks and identifies longer multi-chunk segments to provide more complete context to the LLM.

    4. Context Enrichment Techniques 📝

    Overview 🔎

    Enhancing retrieval accuracy by embedding individual sentences and extending context to neighboring sentences.

    Implementation 🛠️

    Retrieve the most relevant sentence while also accessing the sentences before and after it in the original text.

    1. Semantic Chunking 🧠

    Overview 🔎

    Dividing documents based on semantic coherence rather than fixed sizes.

    Implementation 🛠️

    Use NLP techniques to identify topic boundaries or coherent sections within documents for more meaningful retrieval units.

    Additional Resources 📚

    1. Contextual Compression 🗜️

    Overview 🔎

    Compressing retrieved information while preserving query-relevant content.

    Implementation 🛠️

    Use an LLM to compress or summarize retrieved chunks, preserving key information relevant to the query.

    1. Document Augmentation through Question Generation for Enhanced Retrieval

    Overview 🔎

    This implementation demonstrates a text augmentation technique that leverages additional question generation to improve document retrieval within a vector database. By generating and incorporating various questions related to each text fragment, the system enhances the standard retrieval process, thus increasing the likelihood of finding relevant documents that can be utilized as context for generative question answering.

    Implementation 🛠️

    Use an LLM to augment text dataset with all possible questions that can be asked to each document.

    🚀 Advanced Retrieval Methods

    1. Fusion Retrieval 🔗

      Overview 🔎

      Optimizing search results by combining different retrieval methods.

      Implementation 🛠️

      Combine keyword-based search with vector-based search for more comprehensive and accurate retrieval.

    2. Intelligent Reranking 📈

      Overview 🔎

      Applying advanced scoring mechanisms to improve the relevance ranking of retrieved results.

      Implementation 🛠️

      • 🧠 LLM-based Scoring: Use a language model to score the relevance of each retrieved chunk.
      • 🔀 Cross-Encoder Models: Re-encode both the query and retrieved documents jointly for similarity scoring.
      • 🏆 Metadata-enhanced Ranking: Incorporate metadata into the scoring process for more nuanced ranking.

      Additional Resources 📚

    3. Multi-faceted Filtering 🔍

      Overview 🔎

      Applying various filtering techniques to refine and improve the quality of retrieved results.

      Implementation 🛠️

      • 🏷️ Metadata Filtering: Apply filters based on attributes like date, source, author, or document type.
      • 📊 Similarity Thresholds: Set thresholds for relevance scores to keep only the most pertinent results.
      • 📄 Content Filtering: Remove results that don't match specific content criteria or essential keywords.
      • 🌈 Diversity Filtering: Ensure result diversity by filtering out near-duplicate entries.
    4. Hierarchical Indices 🗂️

      Overview 🔎

      Creating a multi-tiered system for efficient information navigation and retrieval.

      Implementation 🛠️

      Implement a two-tiered system for document summaries and detailed chunks, both containing metadata pointing to the same location in the data.

      Additional Resources 📚

    5. Dartboard Retrieval 🎯

      • LangChain:

      Overview 🔎

      Optimizing over Relevant Information Gain in Retrieval

      Implementation 🛠️

      • Combine both relevance and diversity into a single scoring function and directly optimize for it.
      • POC showing plain simple RAG underperforming when the database is dense, and the dartboard retrieval outperforming it.
    6. Multi-modal Retrieval 📽️

      Overview 🔎

      Extending RAG capabilities to handle diverse data types for richer responses.

      Implementation 🛠️

      • Multi-model RAG with Multimedia Captioning: - Caption and store all the other multimedia data like pdfs, ppts, etc., with text data in