RAG_Techniques

NirDiamant / RAG_Techniques

Jupyter AI/ML 项目,涉及agentic-RAG、AI、embeddings

Jupyter Notebook RAG AI Agent LLM 应用 agentic-RAG AI embeddings generative-AI GPT

为什么值得看

编辑点评

适用于AI/大模型、基础设施、数据科学场景。使用 Jupyter 开发,涉及agentic-RAG、AI、embeddings等技术方向。建议关注其社区活跃度和文档完善程度。

Star 趋势

近 7 日
  • Star 总数29,513
  • 今日新增+7
  • 7 日增速-36%
  • Fork3,610

同类项目

同场景 · RAG / AI Agent / LLM 应用

项目文档

来自 GitHub README · main 分支

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.


🎓 From RAG prototypes to production

Prompt to Production - my full course on building software with AI the way professionals do: the methods and paradigms behind reliable, efficient, modular production systems, taught systematically. 20 modules, each pairing a video lecture with a hands-on lab, from your first structured prompt to a working production system.

The course is live. Every module is out, lecture and lab.

🎁 Try a full module, free

🎬
7-minute
video lecture
🛠️
Hands-on
tutorial
🤖
AI assistant
inside Claude Code

One npm install adds the module's AI assistant to your Claude Code, and it guides you through the tutorial as you build.

👉 Get the full course

Sponsors ❤️

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

Company Sponsors

Individual Sponsors

📫 Stay Updated!

🚀
Cutting-edge
Updates
💡
Expert
Insights
🎯
Top 0.1%
Content

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 to my book and the upcoming RAG Techniques course!

DiamantAI's newsletter

🎬 Prefer video?

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


🆕 AI Is Rewarded for Guessing [Hallucination]

why a model guesses instead of saying I don't know, watched on its own token probabilities, and where retrieval moves the fact out of the guess


RAG Explained: Why AI Gets Your Own Documents Wrong

why chunks overlap, what "meaning space" is, and where simple RAG breaks down

How Do You Search a Spreadsheet by Meaning?

turn each row into one labelled line and search the table by meaning

How Do You Know Your RAG Answer Isn't Made Up?

three checkpoints that catch a bad chunk on the way in and an unsupported claim on the way out

Why Does RAG Return a Paragraph When You Asked for One Fact?

why a paragraph's embedding is a blend that points at nothing in particular

  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.

📖 Go deeper: the book

RAG Made Simple - the 400-page visual companion to this repo. Amazon Bestseller in Generative AI · 1,500+ readers · ⭐ 4.6

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

🚀 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: MemoRAG (memory-augmented retrieval), End-to-End RAG Evaluation, Open-RAG-Eval, JSON RAG. 42 notebooks and growing.

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

🌱 Foundational RAG Techniques

  1. Simple RAG 🌱 - 🎬 Watch it explained: RAG Explained: Why AI Gets Your Own Documents Wrong — the intuition behind this notebook in 7 minutes: why chunks overlap, what "meaning space" actually is, and where simple RAG breaks down. - LangChain: - LlamaIndex: - Runnable Script

#### Overview 🔎 Introducing basic RAG techniques ideal for newcomers.

#### Implementation 🛠️ Start with basic retrieval queries and integrate incremental learning mechanisms.

  1. 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.

  2. 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.

  1. Choose Chunk Size 📏 - LangChain: - Runnable Script

#### 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.

  1. Proposition Chunking ⛓️‍💥: - 🎬 Watch it explained: Why Does RAG Return a Paragraph When You Asked for One Fact? — why a paragraph's embedding is a blend that points at nothing in particular, how a language model rewrites the chunk as single self-contained facts, and what the quality gate throws away.

#### 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.

  1. 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.

Additional Resources 📚

🔍 Query Enhancement

  1. Query Transformations 🔄 - LangChain: - Runnable Script - 🎬 Watch it explained: Why Does RAG Miss an Answer That's Right There in Your Documents? — why the words in a question never quite line up with the words on the page, the three transformations (rewrite, step back, split) that fix the question instead of the index, and the rule that keeps the original question in charge of the answer.

#### 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.

  1. Hypothetical Questions (HyDE Approach) ❓ - LangChain: - Runnable Script - 🎬 Watch it explained: HyDE for RAG: Search With a Fake Answer to Find the Real One — why a short question and a long document land far apart in embedding space even when they mean the same thing, why the made-up answer never has to be correct, and the two places the technique genuinely fails.

#### 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 📚 - HyDE: Exploring Hypothetical Document Embeddings for AI Retrieval - A short blog post explaining this method clearly.

📚 Context and Content Enrichment

  1. Hypothetical Prompt Embeddings (HyPE) ❓🚀 - LangChain: - Runnable Script

#### 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 📚 - Preprint: Hypothetical Prompt Embeddings (HyPE) - Research paper detailing the method, evaluation, and benchmarks.

  1. 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)

  2. 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.

  3. Context Enrichment Techniques 📝 - LangChain: - LlamaIndex: - Runnable Script

#### 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 🧠 - LangChain: - Runnable Script

#### 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 📚 - Semantic Chunking: Improving AI Information Retrieval - A comprehensive blog post exploring the benefits and implementation of semantic chunking in RAG systems.

  1. Contextual Compression 🗜️ - LangChain: - Runnable Script

#### 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 - LangChain: - Runnable Script

#### 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 vector store and retrieve them together.
    • Multi-model RAG with Colpali: - Instead of captioning convert all the data into image, then find the most relevant images and pass them to a vision large language model.

🔁 Iterative and Adaptive Techniques

  1. Retrieval with Feedback Loops 🔁

    Overview 🔎

    Implementing mechanisms to learn from user interactions and improve future retrievals.

    Implementation 🛠️

    Collect and utilize user feedback on the relevance and quality of retrieved documents and generated responses to fine-tune retrieval and ranking models.

  2. Adaptive Retrieval 🎯

    Overview 🔎

    Dynamically adjusting retrieval strategies based on query types and user contexts.

    Implementation 🛠️

    Classify queries into different categories and use tailored retrieval strategies for each, considering user context and preferences.

📊 Evaluation

  1. DeepEval Evaluation: | Comprehensive RAG system evaluation |

    Overview 🔎

    Performing evaluations Retrieval-Augmented Generation systems, by covering several metrics and creating test cases.

    Implementation 🛠️

    Use the deepeval library to conduct test cases on correctness, faithfulness and contextual relevancy of RAG systems.

  2. GroUSE Evaluation: | Contextually-grounded LLM evaluation |

    Overview 🔎

    Evaluate the final stage of Retrieval-Augmented Generation using metrics of the GroUSE framework and meta-evaluate your custom LLM judge on GroUSE unit tests.

    Implementation 🛠️

    Use the grouse package to evaluate contextually-grounded LLM generations with GPT-4 on the 6 metrics of the GroUSE framework and use unit tests to evaluate a custom Llama 3.1 405B evaluator.

  3. End-to-End RAG Evaluation: | Complete evaluation pipeline |

    Overview 🔎

    A comprehensive tutorial covering evaluation criteria selection, LLM-as-a-judge metrics, RAGAS integration, and full evaluation pipeline assembly.

    Implementation 🛠️

    • Build custom metrics for completeness, relevance, and hallucination detection using the RAG-12000 dataset.
  4. Open-RAG-Eval: | Open-source RAG evaluation |

    Overview 🔎

    Demonstrates the open-rag-eval library for evaluation using UMBRELA scoring, AutoNuggetizer, and citation/hallucination detection.

    Implementation 🛠️

    • Evaluate RAG pipelines using multiple open-source metrics against the FIQA financial dataset.

🧠 Memory-Augmented Retrieval

  1. MemoRAG: [](https://colab.research.google.com/github/NirDiamant/RAG_Te

README 内容较长,此处已截断,完整内容请查看 GitHub 仓库。

文档抓取自 GitHub 仓库 README,版权归原作者所有;已过滤徽章等噪音并经安全消毒后展示。