Accéder au contenu principal

Implémentation de Corrective RAG (CRAG) avec LangGraph

Corrective RAG (CRAG) est une technique RAG qui intègre une auto-évaluation des documents récupérés pour améliorer la précision et la pertinence des réponses générées.
Actualisé 19 sept. 2026  · 14 min lire

Explorer avec l’IA

ChatGPTClaudePerplexity

La génération augmentée par récupération (RAG) améliore les grands modèles de langage en allant chercher des documents pertinents depuis une source externe pour soutenir la génération de texte. Cependant, la RAG n’est pas infaillible : elle peut encore produire du contenu trompeur si les documents récupérés ne sont pas exacts ou pertinents.

Pour pallier ces limites, on a proposé la génération augmentée par récupération corrective (CRAG). CRAG ajoute une étape de contrôle et d’affinage des informations récupérées avant de les utiliser pour générer du texte. Les modèles de langage gagnent ainsi en précision et réduisent le risque de produire des contenus trompeurs.

Dans cet article, je vous présente CRAG et vous guide pas à pas pour l’implémenter avec LangGraph.

Systèmes multi-agents avec LangGraph

Construisez des systèmes multi-agents puissants en appliquant les nouveaux modèles de conception agentique dans le cadre de LangGraph.
Cours D'exploration

Qu’est-ce que le Corrective RAG (CRAG) ?

Le Corrective RAG (CRAG) est une version améliorée de la RAG qui vise à rendre les modèles de langage plus précis.

Alors que la RAG traditionnelle se contente d’utiliser les documents récupérés pour aider à générer du texte, CRAG va plus loin en vérifiant et en affinant activement ces documents pour s’assurer de leur pertinence et de leur exactitude. Cela permet de réduire les erreurs ou hallucinations, lorsque le modèle pourrait produire des informations inexactes ou trompeuses.

Aperçu de Corrective RAG

Source : Shi-Qi Yan et al., 2024

Le cadre CRAG fonctionne en plusieurs étapes clés, faisant intervenir un évaluateur de récupération et des actions correctives spécifiques.

Pour une requête donnée, un récupérateur standard extrait d’abord un ensemble de documents depuis une base de connaissances. Ces documents sont ensuite passés en revue par un évaluateur de récupération afin de déterminer la pertinence de chaque document vis-à-vis de la requête.

Dans CRAG, l’évaluateur de récupération est un modèle T5-large affiné. L’évaluateur attribue un score de confiance à chaque document et les classe en trois niveaux :

  1. Correct : si au moins un document dépasse le seuil supérieur, il est considéré comme correct. Le système applique alors un processus d’affinage des connaissances, via un algorithme « décomposer puis recomposer », pour extraire les informations les plus importantes et pertinentes tout en filtrant le bruit et les éléments hors sujet. On ne conserve ainsi que les informations les plus exactes et utiles pour la génération.
  2. Incorrect : si tous les documents sont en dessous d’un seuil inférieur, ils sont marqués comme incorrects. Dans ce cas, CRAG écarte tous les documents récupérés et effectue à la place une recherche web pour rassembler de nouvelles connaissances externes potentiellement plus fiables. Cette étape étend la récupération au-delà d’une base statique ou limitée en s’appuyant sur la richesse et la dynamique du web, augmentant les chances d’obtenir des données pertinentes et exactes.
  3. Ambigu : lorsque les documents récupérés donnent des résultats mitigés, le cas est jugé ambigu. CRAG combine alors les deux stratégies : il affine l’information issue des documents initiaux et y intègre des connaissances complémentaires obtenues via des recherches web.

Après l’une de ces actions, les connaissances affinées sont utilisées pour générer la réponse finale.

CRAG vs RAG traditionnelle

CRAG apporte plusieurs améliorations majeures par rapport à la RAG traditionnelle. Son principal atout est sa capacité à corriger les erreurs dans les informations récupérées. L’évaluateur de récupération de CRAG détecte les informations erronées ou hors sujet pour les corriger avant qu’elles n’impactent la sortie finale. Résultat : des informations plus fiables et précises, avec moins d’erreurs et de désinformation.

CRAG excelle aussi à garantir à la fois pertinence et exactitude. Tandis que la RAG classique se limite souvent à des scores de pertinence, CRAG va plus loin en affinant les documents pour qu’ils soient non seulement pertinents, mais également précis. Il filtre les détails non essentiels et se concentre sur l’essentiel, pour fonder la génération sur des informations solides.

Implémentation de CRAG avec LangGraph

Dans cette section, nous parcourons pas à pas l’implémentation de CRAG avec LangGraph. Vous apprendrez à configurer votre environnement, créer une base de connaissances vectorielle simple et paramétrer les composants clés de CRAG, comme l’évaluateur de récupération, le réécrivain de question et l’outil de recherche web.

Nous verrons aussi comment construire un workflow LangGraph qui orchestre l’ensemble, afin de montrer comment CRAG gère différents types de requêtes pour des résultats plus précis et fiables.

Étape 1 : configuration et installation

Commencez par installer les packages requis. Cette étape prépare l’environnement d’exécution du pipeline CRAG.

pip install langchain_community tiktoken langchain-openai langchainhub chromadb langchain langgraph tavily-python

Ensuite, configurez vos clés d’API pour Tavily et OpenAI :

import os
os.environ["TAVILY_API_KEY"] = "YOUR_TAVILY_API_KEY"
os.environ["OPENAI_API_KEY"] = "YOUR_OPENAI_API_KEY"

Étape 2 : créer une base de connaissances proxy

Pour effectuer de la RAG, nous avons d’abord besoin d’une base de connaissances alimentée en documents. Dans cette étape, nous allons récupérer des documents d’exemple depuis une newsletter Substack pour créer un magasin vectoriel, qui jouera le rôle de base de connaissances proxy. Ce magasin vectoriel nous aide à retrouver des documents pertinents à partir des requêtes des utilisateurs.

Nous commençons par charger des documents depuis les URLs fournies et les découper en sections plus petites via un découpeur de texte. Ces sections sont ensuite encodées en vecteurs avec OpenAIEmbeddings et stockées dans une base de données vectorielle (Chroma) pour une récupération efficace.

from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain_community.document_loaders import WebBaseLoader
from langchain_community.vectorstores import Chroma
from langchain_openai import OpenAIEmbeddings
urls = [
    "<https://ryanocm.substack.com/p/mystery-gift-box-049-law-1-fill-your>",
    "<https://ryanocm.substack.com/p/105-the-bagel-method-in-relationships>",
    "<https://ryanocm.substack.com/p/098-i-have-read-100-productivity>",
]
docs = [WebBaseLoader(url).load() for url in urls]
docs_list = [item for sublist in docs for item in sublist]
text_splitter = RecursiveCharacterTextSplitter.from_tiktoken_encoder(
    chunk_size=250, chunk_overlap=0
)
doc_splits = text_splitter.split_documents(docs_list)
# Add to vectorDB
vectorstore = Chroma.from_documents(
    documents=doc_splits,
    collection_name="rag-chroma",
    embedding=OpenAIEmbeddings(),
)
retriever = vectorstore.as_retriever()

Étape 3 : mettre en place une chaîne RAG

Ici, nous configurons une chaîne RAG de base qui prend la question d’un utilisateur et un ensemble de documents pour générer une réponse.

La chaîne RAG s’appuie sur un prompt prédéfini et un modèle de langage (GPT 4-o mini) pour créer des réponses fondées sur les documents récupérés. Un parseur de sortie formate ensuite le texte généré pour en faciliter la lecture.

### Generate
from langchain import hub
from langchain_core.output_parsers import StrOutputParser
# Prompt
rag_prompt = hub.pull("rlm/rag-prompt")
# LLM
rag_llm = ChatOpenAI(model_name="gpt-4o-mini", temperature=0)
# Post-processing
def format_docs(docs):
    return "\\n\\n".join(doc.page_content for doc in docs)
# Chain
rag_chain = rag_prompt | rag_llm | StrOutputParser()
print(rag_prompt.messages[0].prompt.template)
You are an assistant for question-answering tasks. Use the following pieces of retrieved context to answer the question. If you don't know the answer, just say that you don't know. Use three sentences maximum and keep the answer concise.
Question: {question} 
Context: {context} 
Answer:
generation = rag_chain.invoke({"context": docs, "question": question})
print("Question: %s" % question)
print("----")
print("Documents:\\n")
print('\\n\\n'.join(['- %s' % x.page_content for x in docs]))
print("----")
print("Final answer: %s" % generation)
Question: what is the bagel method
----
Documents:
- the book was called The Bagel Method.The Bagel Method is designed to help partners be on the same team when dealing with differences and trying to find a compromise.The idea behind the method is that, to truly compromise, we need to figure out a way to include both partners’ dreams and core needs; things that are super important to us that giving up on them is too much.Let’s dive into the bagel 😜🚀 If you are new here…Hi, I’m Ryan 👋� I am passionate about lifestyle gamification � and I am obsesssssssss with learning things that can help me live a happy and fulfilling life.And so, with The Limitless Playbook newsletter, I will share with you 1 actionable idea from the world's top thinkers every Sunday �So visit us weekly for highly actionable insights :)…or even better, subscribe below and have all these information send straight to your inbox every Sunday 🥳Subscribe🥯
- #105 | The Bagel Method in Relationships 🥯
- The Limitless Playbook 🧬SubscribeSign inShare this post#105 | The Bagel Method in Relationships 🥯ryanocm.substack.comCopy linkFacebookEmailNoteOther#105 | The Bagel Method in Relationships 🥯A collection of the best hidden gems, mental models, and frameworks from the world’s top thinkers; to help you become 1% better and live a happier life ��Ryan Ong �Feb 25, 2024Share this post#105 | The Bagel Method in Relationships 🥯ryanocm.substack.comCopy linkFacebookEmailNoteOtherShareHello curious minds 🧠I recently finished the book Fight Right: How Successful Couples Turn Conflict into Connection and oh my days, I love every chapter of it!There were many repeating concepts but this time, it was applied in the context of conflicts in relationships. As usual with the Gottman’s books, I highlighted the hell out of the entire book 😄One of the cool exercises in
- The Bagel MethodThe Bagel Method involves mapping out your core needs and areas of flexibility so that you and your partner understand what's important and where there's room for flexibility.It’s called The Bagel Method because, just like a bagel, it has both the inner and outer circles representing your needs.Here are the steps:In the inner circle, list all the aspects of an issue that you can’t give in on. These are your non-negotiables that are usually very closely related to your core needs and dreams.In the outer circle, list all the aspects of an issue that you are able to compromise on IF you are able to have what’s in your inner circle.Now, talk to your partners about your inner and outer circle. Ask each other:Why are the things in your inner circle so important to you?How can I support your core needs here?Tell me more about your areas of flexibility. What does it look like to be flexible?Compare both your “bagel� of needsWhat do we agree on?What feelings do we have in common?What shared goals do we have?How might we accomplish these goals
----
Final answer: The Bagel Method is a relationship strategy that helps partners identify their core needs and areas where they can be flexible. It involves mapping out non-negotiables in the inner circle and compromise areas in the outer circle, facilitating open communication about each partner's priorities. This method aims to foster understanding and collaboration in resolving differences.

Étape 4 : créer un évaluateur de récupération

Pour améliorer la précision des contenus générés, nous mettons en place un évaluateur de récupération. Cet outil vérifie la pertinence de chaque document récupéré pour ne conserver que l’information la plus utile.

L’évaluateur est configuré avec un prompt et un modèle de langage. Il détermine si les documents sont pertinents ou non, en filtrant ce qui ne l’est pas avant la génération d’une réponse.

### Retrieval Evaluator
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.pydantic_v1 import BaseModel, Field
from langchain_openai import ChatOpenAI
# Data model
class RetrievalEvaluator(BaseModel):
    """Classify retrieved documents based on how relevant it is to the user's question."""
    binary_score: str = Field(
        description="Documents are relevant to the question, 'yes' or 'no'"
    )
# LLM with function call
retrieval_evaluator_llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
structured_llm_evaluator = retrieval_evaluator_llm.with_structured_output(RetrievalEvaluator)
# Prompt
system = """You are a document retrieval evaluator that's responsible for checking the relevancy of a retrieved document to the user's question. \\n 
    If the document contains keyword(s) or semantic meaning related to the question, grade it as relevant. \\n
    Output a binary score 'yes' or 'no' to indicate whether the document is relevant to the question."""
retrieval_evaluator_prompt = ChatPromptTemplate.from_messages(
    [
        ("system", system),
        ("human", "Retrieved document: \\n\\n {document} \\n\\n User question: {question}"),
    ]
)
retrieval_grader = retrieval_evaluator_prompt | structured_llm_evaluator

Étape 5 : ajouter un réécrivain de question

Nous ajoutons un réécrivain de question pour clarifier et préciser les requêtes des utilisateurs, ce qui améliore la recherche.

Le réécrivain affine la requête d’origine afin de la focaliser, conduisant à des résultats plus pertinents.

### Question Re-writer
# LLM
question_rewriter_llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
# Prompt
system = """You are a question re-writer that converts an input question to a better version that is optimized \\n 
     for web search. Look at the input and try to reason about the underlying semantic intent / meaning."""
re_write_prompt = ChatPromptTemplate.from_messages(
    [
        ("system", system),
        (
            "human",
            "Here is the initial question: \\n\\n {question} \\n Formulate an improved question.",
        ),
    ]
)
question_rewriter = re_write_prompt | question_rewriter_llm | StrOutputParser()

Étape 6 : initialiser l’outil de recherche web Tavily

Si la base de connaissances est insuffisante, CRAG se tourne vers la recherche web pour combler les lacunes. Cela élargit la palette des sources d’information. Dans cette étape, nous utilisons l’API Tavily pour rechercher sur le web et trouver des documents supplémentaires.

### Search
from langchain_community.tools.tavily_search import TavilySearchResults
web_search_tool = TavilySearchResults(k=3)

Étape 7 : construire le workflow LangGraph

Pour bâtir le workflow CRAG avec LangGraph, suivez ces trois grandes étapes :

  1. Définir l’état du graphe
  2. Définir les nœuds fonctionnels
  3. Connecter tous les nœuds

Définir l’état du graphe

Créez un état partagé pour stocker les données lors de leur circulation entre les nœuds du workflow. Cet état contient toutes les variables, comme la question de l’utilisateur, les documents récupérés et les réponses générées.

from typing import List
from typing_extensions import TypedDict
class GraphState(TypedDict):
    """
    Represents the state of our graph.
    Attributes:
        question: question
        generation: LLM generation
        web_search: whether to add search
        documents: list of documents
    """
    question: str
    generation: str
    web_search: str
    documents: List[str]

Définir les nœuds fonctionnels

Dans le workflow LangGraph, chaque nœud exécute une tâche précise du pipeline CRAG : récupération de documents, génération de réponses, évaluation de la pertinence, transformation de requêtes et recherche web. Voici le rôle de chaque fonction :

La fonction retrieve trouve les documents pertinents dans la base de connaissances pour la question de l’utilisateur. Elle utilise un objet « retriever », généralement un magasin vectoriel construit à partir de documents prétraités. La fonction prend l’état courant (incluant la question) et ajoute les documents récupérés à l’état.

from langchain.schema import Document
def retrieve(state):
    """
    Retrieve documents
    Args:
        state (dict): The current graph state
    Returns:
        state (dict): New key added to state, documents, that contains retrieved documents
    """
    print("---RETRIEVE---")
    question = state["question"]
    # Retrieval
    documents = retriever.get_relevant_documents(question)
    return {"documents": documents, "question": question}

La fonction generate crée une réponse à la question de l’utilisateur en s’appuyant sur les documents récupérés. Elle s’appuie sur la chaîne RAG, qui combine un prompt et un modèle de langage. Cette fonction prend les documents et la question, les passe dans la chaîne RAG, puis ajoute la réponse à l’état.

def generate(state):
    """
    Generate answer
    Args:
        state (dict): The current graph state
    Returns:
        state (dict): New key added to state, generation, that contains LLM generation
    """
    print("---GENERATE---")
    question = state["question"]
    documents = state["documents"]
    # RAG generation
    generation = rag_chain.invoke({"context": documents, "question": question})
    return {"documents": documents, "question": question, "generation": generation}

La fonction evaluate_documents évalue la pertinence de chaque document récupéré par rapport à la question grâce à l’évaluateur de récupération. Elle garantit que seules les informations utiles servent à la réponse. La fonction note la pertinence de chaque document et écarte ceux qui ne le sont pas. Elle met aussi à jour l’état avec un indicateur web_search pour signaler s’il faut lancer une recherche web quand la plupart des documents ne sont pas pertinents.

def evaluate_documents(state):
    """
    Determines whether the retrieved documents are relevant to the question.
    Args:
        state (dict): The current graph state
    Returns:
        state (dict): Updates documents key with only filtered relevant documents
    """
    print("---CHECK DOCUMENT RELEVANCE TO QUESTION---")
    question = state["question"]
    documents = state["documents"]
    # Score each doc
    filtered_docs = []
    web_search = "No"
    for d in documents:
        score = retrieval_grader.invoke(
            {"question": question, "document": d.page_content}
        )
        grade = score.binary_score
        if grade == "yes":
            print("---GRADE: DOCUMENT RELEVANT---")
            filtered_docs.append(d)
        else:
            print("---GRADE: DOCUMENT NOT RELEVANT---")
            continue
    if len(filtered_docs) / len(documents) <= 0.7:
        web_search = "Yes"
    return {"documents": filtered_docs, "question": question, "web_search": web_search}

La fonction transform_query améliore la question de l’utilisateur pour obtenir de meilleurs résultats de recherche, notamment si la requête initiale ne renvoie pas de documents pertinents. Elle utilise un réécrivain de question pour la rendre plus claire et plus spécifique. Une meilleure question augmente les chances de trouver des documents utiles, tant dans la base que sur le web.

def transform_query(state):
    """
    Transform the query to produce a better question.
    Args:
        state (dict): The current graph state
    Returns:
        state (dict): Updates question key with a re-phrased question
    """
    print("---TRANSFORM QUERY---")
    question = state["question"]
    documents = state["documents"]
    # Re-write question
    better_question = question_rewriter.invoke({"question": question})
    return {"documents": documents, "question": better_question}

La fonction web_search cherche des informations supplémentaires en ligne à partir de la requête affinée. Elle est utilisée lorsque la base de connaissances ne suffit pas, afin de collecter plus de contenu. Cette fonction s’appuie sur l’outil Tavily pour trouver des documents web, ensuite ajoutés aux documents existants afin d’enrichir la base de connaissances.

def web_search(state):
    """
    Web search based on the re-phrased question.
    Args:
        state (dict): The current graph state
    Returns:
        state (dict): Updates documents key with appended web results
    """
    print("---WEB SEARCH---")
    question = state["question"]
    documents = state["documents"]
    # Web search
    docs = web_search_tool.invoke({"query": question})
    web_results = "\\n".join([d["content"] for d in docs])
    web_results = Document(page_content=web_results)
    documents.append(web_results)
    return {"documents": documents, "question": question}

La fonction decide_to_generate décide de la suite : générer une réponse avec les documents actuels ou bien affiner la requête et relancer une recherche. Le choix s’appuie sur la pertinence des documents (évaluée précédemment).

def decide_to_generate(state):
    """
    Determines whether to generate an answer, or re-generate a question.
    Args:
        state (dict): The current graph state
    Returns:
        str: Binary decision for next node to call
    """
    print("---ASSESS GRADED DOCUMENTS---")
    state["question"]
    web_search = state["web_search"]
    state["documents"]
    if web_search == "Yes":
        # All documents have been filtered check_relevance
        # We will re-generate a new query
        print(
            "---DECISION: ALL DOCUMENTS ARE NOT RELEVANT TO QUESTION, TRANSFORM QUERY---"
        )
        return "transform_query"
    else:
        # We have relevant documents, so generate answer
        print("---DECISION: GENERATE---")
        return "generate"

Connecter tous les nœuds

Une fois tous les nœuds définis, on les relie dans le workflow LangGraph pour construire le pipeline CRAG. Il s’agit de connecter les nœuds avec des arêtes afin d’orchestrer le flux d’informations et les décisions, et de garantir que le workflow s’exécute correctement selon les résultats de chaque étape.

from langgraph.graph import END, StateGraph, START
workflow = StateGraph(GraphState)
# Define the nodes
workflow.add_node("retrieve", retrieve)  # retrieve
workflow.add_node("grade_documents", evaluate_documents)  # evaluate documents
workflow.add_node("generate", generate)  # generate
workflow.add_node("transform_query", transform_query)  # transform_query
workflow.add_node("web_search_node", web_search)  # web search
# Build graph
workflow.add_edge(START, "retrieve")
workflow.add_edge("retrieve", "grade_documents")
workflow.add_conditional_edges(
    "grade_documents",
    decide_to_generate,
    {
        "transform_query": "transform_query",
        "generate": "generate",
    },
)
workflow.add_edge("transform_query", "web_search_node")
workflow.add_edge("web_search_node", "generate")
workflow.add_edge("generate", END)
# Compile
app = workflow.compile()
from IPython.display import Image, display
try:
    display(Image(app.get_graph(xray=True).draw_mermaid_png()))
except Exception:
    # This requires some extra dependencies and is optional
    pass

Workflow CRAG avec LangGraph

Étape 8 : tester le workflow

Pour valider notre configuration, nous exécutons le workflow avec des requêtes d’exemple afin d’observer la récupération d’information, l’évaluation de pertinence et la génération de réponses.

La première requête vérifie la capacité de CRAG à trouver des réponses au sein de sa base de connaissances.

from pprint import pprint
# Run
inputs = {"question": "What's the bagel method?"}
for output in app.stream(inputs):
    for key, value in output.items():
        # Node
        pprint(f"Node '{key}':")
        # Optional: print full state at each node
        pprint(value, indent=2, width=80, depth=None)
    pprint("\\n---\\n")
# Final generation
pprint(value["generation"])
---RETRIEVE---
"Node 'retrieve':"
{ 'documents': [ Document(page_content="the book was called The Bagel Method.The Bagel Method is designed to help partners be on the same team when dealing with differences and trying to find a compromise.The idea behind the method is that, to truly compromise, we need to figure out a way to include both partners’ dreams and core needs; things that are super important to us that giving up on them is too much.Let’s dive into the bagel 😜🚀 If you are new here…Hi, I’m Ryan 👋� I am passionate about lifestyle gamification � and I am obsesssssssss with learning things that can help me live a happy and fulfilling life.And so, with The Limitless Playbook newsletter, I will share with you 1 actionable idea from the world's top thinkers every Sunday �So visit us weekly for highly actionable insights :)…or even better, subscribe below and have all these information send straight to your inbox every Sunday 🥳Subscribe🥯", metadata={'description': 'A collection of the best hidden gems, mental models, and frameworks from the world’s top thinkers; to help you become 1% better and live a happier life ��', 'language': 'en', 'source': '<https://ryanocm.substack.com/p/105-the-bagel-method-in-relationships>', 'title': '#105 | The Bagel Method in Relationships 🥯'}),
                 Document(page_content='#105 | The Bagel Method in Relationships 🥯', metadata={'description': 'A collection of the best hidden gems, mental models, and frameworks from the world’s top thinkers; to help you become 1% better and live a happier life ��', 'language': 'en', 'source': '<https://ryanocm.substack.com/p/105-the-bagel-method-in-relationships>', 'title': '#105 | The Bagel Method in Relationships 🥯'}),
                 Document(page_content='The Limitless Playbook 🧬SubscribeSign inShare this post#105 | The Bagel Method in Relationships 🥯ryanocm.substack.comCopy linkFacebookEmailNoteOther#105 | The Bagel Method in Relationships 🥯A collection of the best hidden gems, mental models, and frameworks from the world’s top thinkers; to help you become 1% better and live a happier life â�¤ï¸�Ryan Ong ğŸ�®Feb 25, 2024Share this post#105 | The Bagel Method in Relationships 🥯ryanocm.substack.comCopy linkFacebookEmailNoteOtherShareHello curious minds ğŸ§\\xa0I recently finished the book Fight Right: How Successful Couples Turn Conflict into Connection and oh my days, I love every chapter of it!There were many repeating concepts but this time, it was applied in the context of conflicts in relationships. As usual with the Gottman’s books, I highlighted the hell out of the entire book 😄One of the cool exercises in', metadata={'description': 'A collection of the best hidden gems, mental models, and frameworks from the world’s top thinkers; to help you become 1% better and live a happier life â�¤ï¸�', 'language': 'en', 'source': '<https://ryanocm.substack.com/p/105-the-bagel-method-in-relationships>', 'title': '#105 | The Bagel Method in Relationships 🥯'}),
                 Document(page_content="The Bagel MethodThe Bagel Method involves mapping out your core needs and areas of flexibility so that you and your partner understand what's important and where there's room for flexibility.It’s called The Bagel Method because, just like a bagel, it has both the inner and outer circles representing your needs.Here are the steps:In the inner circle, list all the aspects of an issue that you can’t give in on. These are your non-negotiables that are usually very closely related to your core needs and dreams.In the outer circle, list all the aspects of an issue that you are able to compromise on IF you are able to have what’s in your inner circle.Now, talk to your partners about your inner and outer circle. Ask each other:Why are the things in your inner circle so important to you?How can I support your core needs here?Tell me more about your areas of flexibility. What does it look like to be flexible?Compare both your “bagel� of needsWhat do we agree on?What feelings do we have in common?What shared goals do we have?How might we accomplish these goals", metadata={'description': 'A collection of the best hidden gems, mental models, and frameworks from the world’s top thinkers; to help you become 1% better and live a happier life ��', 'language': 'en', 'source': '<https://ryanocm.substack.com/p/105-the-bagel-method-in-relationships>', 'title': '#105 | The Bagel Method in Relationships 🥯'})],
  'question': "What's the bagel method?"}
'\\n---\\n'
---CHECK DOCUMENT RELEVANCE TO QUESTION---
---GRADE: DOCUMENT RELEVANT---
---GRADE: DOCUMENT RELEVANT---
---GRADE: DOCUMENT NOT RELEVANT---
---GRADE: DOCUMENT RELEVANT---
---ASSESS GRADED DOCUMENTS---
---DECISION: GENERATE---
"Node 'evaluate_documents':"
{ 'documents': [ Document(page_content="the book was called The Bagel Method.The Bagel Method is designed to help partners be on the same team when dealing with differences and trying to find a compromise.The idea behind the method is that, to truly compromise, we need to figure out a way to include both partners’ dreams and core needs; things that are super important to us that giving up on them is too much.Let’s dive into the bagel 😜🚀 If you are new here…Hi, I’m Ryan 👋� I am passionate about lifestyle gamification � and I am obsesssssssss with learning things that can help me live a happy and fulfilling life.And so, with The Limitless Playbook newsletter, I will share with you 1 actionable idea from the world's top thinkers every Sunday �So visit us weekly for highly actionable insights :)…or even better, subscribe below and have all these information send straight to your inbox every Sunday 🥳Subscribe🥯", metadata={'description': 'A collection of the best hidden gems, mental models, and frameworks from the world’s top thinkers; to help you become 1% better and live a happier life ��', 'language': 'en', 'source': '<https://ryanocm.substack.com/p/105-the-bagel-method-in-relationships>', 'title': '#105 | The Bagel Method in Relationships 🥯'}),
                 Document(page_content='#105 | The Bagel Method in Relationships 🥯', metadata={'description': 'A collection of the best hidden gems, mental models, and frameworks from the world’s top thinkers; to help you become 1% better and live a happier life ��', 'language': 'en', 'source': '<https://ryanocm.substack.com/p/105-the-bagel-method-in-relationships>', 'title': '#105 | The Bagel Method in Relationships 🥯'}),
                 Document(page_content="The Bagel MethodThe Bagel Method involves mapping out your core needs and areas of flexibility so that you and your partner understand what's important and where there's room for flexibility.It’s called The Bagel Method because, just like a bagel, it has both the inner and outer circles representing your needs.Here are the steps:In the inner circle, list all the aspects of an issue that you can’t give in on. These are your non-negotiables that are usually very closely related to your core needs and dreams.In the outer circle, list all the aspects of an issue that you are able to compromise on IF you are able to have what’s in your inner circle.Now, talk to your partners about your inner and outer circle. Ask each other:Why are the things in your inner circle so important to you?How can I support your core needs here?Tell me more about your areas of flexibility. What does it look like to be flexible?Compare both your “bagel� of needsWhat do we agree on?What feelings do we have in common?What shared goals do we have?How might we accomplish these goals", metadata={'description': 'A collection of the best hidden gems, mental models, and frameworks from the world’s top thinkers; to help you become 1% better and live a happier life ��', 'language': 'en', 'source': '<https://ryanocm.substack.com/p/105-the-bagel-method-in-relationships>', 'title': '#105 | The Bagel Method in Relationships 🥯'})],
  'question': "What's the bagel method?",
  'web_search': 'No'}
'\\n---\\n'
---GENERATE---
"Node 'generate':"
{ 'documents': [ Document(page_content="the book was called The Bagel Method.The Bagel Method is designed to help partners be on the same team when dealing with differences and trying to find a compromise.The idea behind the method is that, to truly compromise, we need to figure out a way to include both partners’ dreams and core needs; things that are super important to us that giving up on them is too much.Let’s dive into the bagel 😜🚀 If you are new here…Hi, I’m Ryan 👋� I am passionate about lifestyle gamification � and I am obsesssssssss with learning things that can help me live a happy and fulfilling life.And so, with The Limitless Playbook newsletter, I will share with you 1 actionable idea from the world's top thinkers every Sunday �So visit us weekly for highly actionable insights :)…or even better, subscribe below and have all these information send straight to your inbox every Sunday 🥳Subscribe🥯", metadata={'description': 'A collection of the best hidden gems, mental models, and frameworks from the world’s top thinkers; to help you become 1% better and live a happier life ��', 'language': 'en', 'source': '<https://ryanocm.substack.com/p/105-the-bagel-method-in-relationships>', 'title': '#105 | The Bagel Method in Relationships 🥯'}),
                 Document(page_content='#105 | The Bagel Method in Relationships 🥯', metadata={'description': 'A collection of the best hidden gems, mental models, and frameworks from the world’s top thinkers; to help you become 1% better and live a happier life ��', 'language': 'en', 'source': '<https://ryanocm.substack.com/p/105-the-bagel-method-in-relationships>', 'title': '#105 | The Bagel Method in Relationships 🥯'}),
                 Document(page_content="The Bagel MethodThe Bagel Method involves mapping out your core needs and areas of flexibility so that you and your partner understand what's important and where there's room for flexibility.It’s called The Bagel Method because, just like a bagel, it has both the inner and outer circles representing your needs.Here are the steps:In the inner circle, list all the aspects of an issue that you can’t give in on. These are your non-negotiables that are usually very closely related to your core needs and dreams.In the outer circle, list all the aspects of an issue that you are able to compromise on IF you are able to have what’s in your inner circle.Now, talk to your partners about your inner and outer circle. Ask each other:Why are the things in your inner circle so important to you?How can I support your core needs here?Tell me more about your areas of flexibility. What does it look like to be flexible?Compare both your “bagel� of needsWhat do we agree on?What feelings do we have in common?What shared goals do we have?How might we accomplish these goals", metadata={'description': 'A collection of the best hidden gems, mental models, and frameworks from the world’s top thinkers; to help you become 1% better and live a happier life ��', 'language': 'en', 'source': '<https://ryanocm.substack.com/p/105-the-bagel-method-in-relationships>', 'title': '#105 | The Bagel Method in Relationships 🥯'})],
  'generation': 'The Bagel Method is a framework designed to help partners '
                'navigate differences and find compromises by mapping out '
                'their core needs and areas of flexibility. It involves '
                'creating two circles: the inner circle for non-negotiable '
                'needs and the outer circle for aspects where compromise is '
                'possible. This method encourages open communication about '
                "each partner's priorities and shared goals.",
  'question': "What's the bagel method?"}
'\\n---\\n'
('The Bagel Method is a framework designed to help partners navigate '
 'differences and find compromises by mapping out their core needs and areas '
 'of flexibility. It involves creating two circles: the inner circle for '
 'non-negotiable needs and the outer circle for aspects where compromise is '
 "possible. This method encourages open communication about each partner's "
 'priorities and shared goals.')

La seconde requête évalue la capacité de CRAG à rechercher des informations en ligne lorsque la base de connaissances ne contient pas de documents pertinents.

from pprint import pprint
# Run
inputs = {"question": "What is prompt engineering?"}
for output in app.stream(inputs):
    for key, value in output.items():
        # Node
        pprint(f"Node '{key}':")
        # Optional: print full state at each node
        pprint(value, indent=2, width=80, depth=None)
    pprint("\\n---\\n")
# Final generation
pprint(value["generation"])
---RETRIEVE---
"Node 'retrieve':"
{ 'documents': [ Document(page_content='Mystery Gift Box #049 | Law 1: Fill your Five Buckets in the Right Order (The Diary of a CEO)', metadata={'description': "The best hidden gems I've found; interesting ideas and concepts, thought-provoking questions, mind-blowing books/podcasts, cool animes/films, and other mysteries ��", 'language': 'en', 'source': '<https://ryanocm.substack.com/p/mystery-gift-box-049-law-1-fill-your>', 'title': 'Mystery Gift Box #049 | Law 1: Fill your Five Buckets in the Right Order (The Diary of a CEO)'}),
                 Document(page_content='ğŸ�¦Â\\xa0Twitter, 👨ğŸ�»â€�💻Â\\xa0LinkedIn, ğŸŒ�Â\\xa0Personal Website, and 📸Â\\xa0InstagramShare this postMystery Gift Box #049 | Law 1: Fill your Five Buckets in the Right Order (The Diary of a CEO)ryanocm.substack.comCopy linkFacebookEmailNoteOtherSharePreviousNextCommentsTopLatestDiscussionsNo postsReady for more?Subscribe© 2024 Ryan Ong ğŸ�®Privacy ∙ Terms ∙ Collection notice Start WritingGet the appSubstack is the home for great cultureShareCopy linkFacebookEmailNoteOther', metadata={'description': "The best hidden gems I've found; interesting ideas and concepts, thought-provoking questions, mind-blowing books/podcasts, cool animes/films, and other mysteries â�¤ï¸�", 'language': 'en', 'source': '<https://ryanocm.substack.com/p/mystery-gift-box-049-law-1-fill-your>', 'title': 'Mystery Gift Box #049 | Law 1: Fill your Five Buckets in the Right Order (The Diary of a CEO)'}),
                 Document(page_content='skills are the foundation of which you build your life and career and it’s truly yours to own; you can lose your network, resources, and reputation but you will never lose your knowledge and skills.Never try to skip the first two buckets. If you try to jump straight to network, resources, and / or reputation bucket, you might “succeed� in the short-run but in the long run, your lack of knowledge and skill will catch on to you.There is no skipping the first two buckets of knowledge and skills if you’re playing long-term sustainable results. Any attempt to do so is equivalent to building your house on sand.💥 Key takeawayFocus on using your knowledge and skills to create lots of values in the world and the world will reward you with growing network (people will come to you), resources (people will pay for your services), and reputation (people will know what you are capable of).⛰ 4-4-4 Exploration ProjectEach month, I would explore one new thing; a skill, a subject, or an experience.January 2023: Writing and Storytelling (Subject)', metadata={'description': "The best hidden gems I've found; interesting ideas and concepts, thought-provoking questions, mind-blowing books/podcasts, cool animes/films, and other mysteries ��", 'language': 'en', 'source': '<https://ryanocm.substack.com/p/mystery-gift-box-049-law-1-fill-your>', 'title': 'Mystery Gift Box #049 | Law 1: Fill your Five Buckets in the Right Order (The Diary of a CEO)'}),
                 Document(page_content='This site requires JavaScript to run correctly. Please turn on JavaScript or unblock scripts', metadata={'description': 'A collection of the best hidden gems, mental models, and frameworks from the world’s top thinkers; to help you become 1% better and live a happier life ��', 'language': 'en', 'source': '<https://ryanocm.substack.com/p/105-the-bagel-method-in-relationships>', 'title': '#105 | The Bagel Method in Relationships 🥯'})],
  'question': 'What is prompt engineering?'}
'\\n---\\n'
---CHECK DOCUMENT RELEVANCE TO QUESTION---
---GRADE: DOCUMENT NOT RELEVANT---
---GRADE: DOCUMENT NOT RELEVANT---
---GRADE: DOCUMENT NOT RELEVANT---
---GRADE: DOCUMENT NOT RELEVANT---
---ASSESS GRADED DOCUMENTS---
---DECISION: ALL DOCUMENTS ARE NOT RELEVANT TO QUESTION, TRANSFORM QUERY---
"Node 'evaluate_documents':"
{ 'documents': [],
  'question': 'What is prompt engineering?',
  'web_search': 'Yes'}
'\\n---\\n'
---TRANSFORM QUERY---
"Node 'transform_query':"
{ 'documents': [],
  'question': 'What is the concept of prompt engineering and how is it applied '
              'in artificial intelligence?'}
'\\n---\\n'
---WEB SEARCH---
"Node 'web_search_node':"
{ 'documents': [ Document(page_content="Prompt engineering is the method to ask generative AI to produce what the individual needs. There are two main principles of building a successful prompt for any AI, specificity and iteration. The box below includes one example of a framework that can be applied when prompting any generative AI.\\nPrompt Engineering is the process of designing and refining text inputs (prompts) to achieve specific application objectives with AI models. Think of it as a two-step journey: Designing the Initial Prompt: Creating the initial input for the model to achieve the desired result. Refining the Prompt: Continuously adjusting the prompt to enhance ...\\nPrompt engineering is the process of designing and refining the inputs given to language models, like those in AI, to achieve desired outputs more effectively. It involves creatively crafting prompts that guide the model in generating responses that are accurate, relevant, and aligned with the user's intentions.. For students and researchers in higher education, mastering prompt engineering is ...\\nJune 25, 2024. Prompt engineering means writing precise instructions for AI models. These instructions are different from coding because they use natural language. And today, everybody does it—from software developers to artists and content creators. Prompt engineering can help you improve productivity and save time by automating repetitive ...\\nMaster Prompt Engineering - The (AI) Prompt\\nAI Takes Wall Street by Storm: C3.ai's Strong Forecast Sparks a Surge in AI Stocks\\nAsk Me Anything (AMA) Prompting\\nHow Self-Critique Improves Logic and Reasoning in LLMs Like ChatGPT\\nOptimizing Large Language Models to Maximize Performance\\nThe Black Box Problem: Opaque Inner Workings of Large Language Models\\nHow to Evaluate Large Language Models for Business Tasks\\nIntroduction to the AI Prompt Development Process\\nSubscribe to new posts\\nThe Official Source For Everything Prompt Engineering & Generative AI Defining Prompt Engineering\\nGiven that the prompt is the singular input channel to large language models, prompt engineering can be defined as:\\nPrompt Engineering can be thought of as any process that contributes to the development of a well-crafted prompt to generate quality, useful outputs from an AI system.\\n A Simplified Approach to Defining Prompt Engineering\\nThe Prompt is the Sole Input\\nWhen interacting with Generative AI Models such as large language models (LLMs), the prompt is the only thing that gets input into the AI system. Its applications cut across diverse sectors, from healthcare and education to business, securing its place as a cornerstone of our interactions with AI.\\nExploration of Essential Prompt Engineering Techniques and Concepts\\nIn the rapidly evolving landscape of Artificial Intelligence (AI), mastering key techniques of Prompt Engineering has become increasingly vital. The key concepts of Prompt Engineering include prompts and prompting the AI, training the AI, developing and maintaining a prompt library, and testing, evaluation, and categorization.\\n")],
  'question': 'What is the concept of prompt engineering and how is it applied '
              'in artificial intelligence?'}
'\\n---\\n'
---GENERATE---
"Node 'generate':"
{ 'documents': [ Document(page_content="Prompt engineering is the method to ask generative AI to produce what the individual needs. There are two main principles of building a successful prompt for any AI, specificity and iteration. The box below includes one example of a framework that can be applied when prompting any generative AI.\\nPrompt Engineering is the process of designing and refining text inputs (prompts) to achieve specific application objectives with AI models. Think of it as a two-step journey: Designing the Initial Prompt: Creating the initial input for the model to achieve the desired result. Refining the Prompt: Continuously adjusting the prompt to enhance ...\\nPrompt engineering is the process of designing and refining the inputs given to language models, like those in AI, to achieve desired outputs more effectively. It involves creatively crafting prompts that guide the model in generating responses that are accurate, relevant, and aligned with the user's intentions.. For students and researchers in higher education, mastering prompt engineering is ...\\nJune 25, 2024. Prompt engineering means writing precise instructions for AI models. These instructions are different from coding because they use natural language. And today, everybody does it—from software developers to artists and content creators. Prompt engineering can help you improve productivity and save time by automating repetitive ...\\nMaster Prompt Engineering - The (AI) Prompt\\nAI Takes Wall Street by Storm: C3.ai's Strong Forecast Sparks a Surge in AI Stocks\\nAsk Me Anything (AMA) Prompting\\nHow Self-Critique Improves Logic and Reasoning in LLMs Like ChatGPT\\nOptimizing Large Language Models to Maximize Performance\\nThe Black Box Problem: Opaque Inner Workings of Large Language Models\\nHow to Evaluate Large Language Models for Business Tasks\\nIntroduction to the AI Prompt Development Process\\nSubscribe to new posts\\nThe Official Source For Everything Prompt Engineering & Generative AI Defining Prompt Engineering\\nGiven that the prompt is the singular input channel to large language models, prompt engineering can be defined as:\\nPrompt Engineering can be thought of as any process that contributes to the development of a well-crafted prompt to generate quality, useful outputs from an AI system.\\n A Simplified Approach to Defining Prompt Engineering\\nThe Prompt is the Sole Input\\nWhen interacting with Generative AI Models such as large language models (LLMs), the prompt is the only thing that gets input into the AI system. Its applications cut across diverse sectors, from healthcare and education to business, securing its place as a cornerstone of our interactions with AI.\\nExploration of Essential Prompt Engineering Techniques and Concepts\\nIn the rapidly evolving landscape of Artificial Intelligence (AI), mastering key techniques of Prompt Engineering has become increasingly vital. The key concepts of Prompt Engineering include prompts and prompting the AI, training the AI, developing and maintaining a prompt library, and testing, evaluation, and categorization.\\n")],
  'generation': 'Prompt engineering is the process of designing and refining '
                'text inputs to guide AI models in generating desired outputs. '
                'It focuses on specificity and iteration to create effective '
                'prompts that align with user intentions. This technique is '
                'widely applicable across various sectors, enhancing '
                'productivity and automating tasks.',
  'question': 'What is the concept of prompt engineering and how is it applied '
              'in artificial intelligence?'}
'\\n---\\n'
('Prompt engineering is the process of designing and refining text inputs to '
 'guide AI models in generating desired outputs. It focuses on specificity and '
 'iteration to create effective prompts that align with user intentions. This '
 'technique is widely applicable across various sectors, enhancing '
 'productivity and automating tasks.')

Les limites de CRAG

Même si CRAG améliore la RAG traditionnelle, il présente certaines limites qui méritent attention.

Un premier enjeu majeur réside dans la qualité de l’évaluateur de récupération. Cet évaluateur est essentiel pour juger si les documents récupérés sont pertinents et exacts. Or, l’entraînement et le fine-tuning de cet évaluateur sont exigeants : ils nécessitent beaucoup de données de qualité et de ressources de calcul. Le maintenir à jour face à de nouveaux types de requêtes et de sources accentue la complexité et les coûts.

Autre limite : l’usage par CRAG de recherches web pour compléter ou remplacer des documents incorrects ou ambigus. Si cette approche apporte des informations plus récentes et variées, elle risque aussi d’introduire des données biaisées ou peu fiables. La qualité du contenu web est très hétérogène, et le tri pour en extraire les informations les plus justes peut s’avérer complexe. Même un évaluateur bien entraîné ne peut totalement prévenir l’inclusion d’informations de faible qualité ou biaisées.

Ces défis soulignent la nécessité de poursuivre la recherche et le développement.

Conclusion

Dans l’ensemble, CRAG améliore les systèmes RAG traditionnels en ajoutant des mécanismes de contrôle et d’affinage des informations récupérées, rendant les modèles de langage plus précis et plus fiables. CRAG s’avère ainsi utile dans de nombreux cas d’usage.

Pour en savoir plus sur CRAG, consultez l’article original ici.

Pour approfondir la RAG, je vous recommande ces articles :

Développer des applications d'IA

Apprenez à créer des applications d'IA à l'aide de l'API OpenAI.

Ryan Ong's photo
Author
Ryan Ong
LinkedIn
Twitter

Ryan est un data scientist de premier plan spécialisé dans la création d'applications d'IA utilisant des LLM. Il est candidat au doctorat en traitement du langage naturel et graphes de connaissances à l'Imperial College de Londres, où il a également obtenu une maîtrise en informatique. En dehors de la science des données, il rédige une lettre d'information hebdomadaire Substack, The Limitless Playbook, dans laquelle il partage une idée exploitable provenant des plus grands penseurs du monde et écrit occasionnellement sur les concepts fondamentaux de l'IA.

Sujets
Intelligence artificielle
Grands modèles linguistiques

Créez des agents d'IA avec ces cours !

Cours

Créer des agents IA avec Google ADK

1 h
7.5K
Développez progressivement un assistant de service client à l'aide du kit de développement d'agent (ADK) de Google.
Afficher les détailsRight Arrow
Commencer Le Cours
Voir plusRight Arrow