Chuyển đến nội dung chính

Triển khai Corrective RAG (CRAG) với LangGraph

Corrective RAG (CRAG) là kỹ thuật RAG kết hợp tự đánh giá tài liệu truy xuất để cải thiện độ chính xác và mức độ phù hợp của phản hồi được tạo.
· 14 phút đọc

Khám phá cùng AI

Retrieval-augmented generation (RAG) cải thiện mô hình ngôn ngữ lớn bằng cách truy xuất các tài liệu liên quan từ nguồn bên ngoài để hỗ trợ việc tạo văn bản. Tuy nhiên, RAG không hoàn hảo—vẫn có thể tạo ra nội dung gây hiểu lầm nếu tài liệu truy xuất không chính xác hoặc không liên quan.

Để khắc phục các vấn đề này, corrective retrieval-augmented generation (CRAG) đã được đề xuất. CRAG hoạt động bằng cách thêm một bước kiểm tra và tinh chỉnh thông tin truy xuất trước khi dùng để tạo văn bản. Điều này giúp mô hình ngôn ngữ chính xác hơn và giảm khả năng tạo nội dung gây hiểu lầm.

Trong bài viết này, tôi sẽ giới thiệu CRAG và hướng dẫn bạn triển khai từng bước bằng LangGraph.

Corrective RAG (CRAG) là gì?

Corrective retrieval-augmented generation (CRAG) là phiên bản cải tiến của RAG nhằm giúp mô hình ngôn ngữ chính xác hơn.

Trong khi RAG truyền thống chỉ sử dụng tài liệu truy xuất để hỗ trợ tạo văn bản, CRAG tiến thêm một bước bằng cách chủ động kiểm tra và tinh chỉnh các tài liệu này để đảm bảo chúng liên quan và chính xác. Điều này giúp giảm lỗi hoặc hiện tượng ảo giác khi mô hình có thể tạo ra thông tin sai hoặc gây hiểu lầm.

Tổng quan về Corrective RAG

Nguồn: Shi-Qi Yan et al., 2024

Khung CRAG vận hành qua một vài bước chính, bao gồm một bộ đánh giá truy xuất và các hành động hiệu chỉnh cụ thể.

Với mỗi truy vấn đầu vào, một bộ truy xuất tiêu chuẩn trước tiên sẽ kéo về một tập tài liệu từ kho tri thức. Các tài liệu này sau đó được bộ đánh giá truy xuất xem xét để xác định mức độ liên quan với truy vấn.

Trong CRAG, bộ đánh giá truy xuất là một mô hình T5-large đã fine-tune. Bộ đánh giá gán điểm tin cậy cho từng tài liệu, phân loại thành ba mức độ tin cậy:

  1. Đúng: Nếu ít nhất một tài liệu có điểm vượt ngưỡng trên, tài liệu đó được xem là đúng. Hệ thống sau đó áp dụng quy trình tinh lọc tri thức, sử dụng thuật toán phân rã rồi tái hợp để trích xuất các mẩu tri thức quan trọng và phù hợp nhất, đồng thời lọc bỏ dữ liệu nhiễu hoặc không liên quan trong tài liệu. Điều này đảm bảo chỉ giữ lại thông tin chính xác và phù hợp nhất cho bước tạo nội dung.
  2. Sai: Nếu tất cả tài liệu đều dưới ngưỡng dưới, chúng được đánh dấu là sai. Khi đó, CRAG loại bỏ toàn bộ tài liệu truy xuất và thay vào đó thực hiện tìm kiếm web để thu thập tri thức bên ngoài mới, có khả năng chính xác hơn. Bước này mở rộng quy trình truy xuất vượt ra khỏi kho tri thức tĩnh hoặc hạn chế bằng cách tận dụng lượng thông tin khổng lồ và năng động trên web, tăng khả năng lấy được dữ liệu phù hợp và chính xác.
  3. Mơ hồ: Khi các tài liệu truy xuất có kết quả lẫn lộn, chúng được coi là mơ hồ. Khi đó, CRAG kết hợp cả hai chiến lược: tinh lọc thông tin từ các tài liệu truy xuất ban đầu và bổ sung thêm tri thức thu được từ tìm kiếm web.

Sau khi thực hiện một trong các hành động này, tri thức đã tinh lọc sẽ được dùng để tạo phản hồi cuối cùng.

CRAG so với RAG truyền thống

CRAG mang đến một số cải tiến quan trọng so với RAG truyền thống. Một lợi thế lớn là khả năng sửa lỗi trong thông tin truy xuất. Bộ đánh giá truy xuất trong CRAG giúp phát hiện khi nào thông tin sai hoặc không liên quan, để có thể sửa trước khi ảnh hưởng đến đầu ra cuối. Điều này có nghĩa CRAG cung cấp thông tin chính xác và đáng tin cậy hơn, cắt giảm lỗi và thông tin sai lệch.

CRAG cũng vượt trội trong việc đảm bảo thông tin vừa liên quan vừa chính xác. Trong khi RAG truyền thống có thể chỉ kiểm tra điểm liên quan, CRAG đi xa hơn bằng cách tinh chỉnh tài liệu để đảm bảo không chỉ liên quan mà còn chuẩn xác. Nó lọc bỏ chi tiết không cần thiết và tập trung vào các điểm quan trọng nhất, để văn bản tạo ra dựa trên thông tin chính xác.

Triển khai CRAG bằng LangGraph

Trong phần này, chúng ta sẽ đi qua hướng dẫn từng bước về cách triển khai CRAG bằng LangGraph. Bạn sẽ học cách thiết lập môi trường, tạo một kho vector tri thức cơ bản và cấu hình các thành phần chính cần cho CRAG, như bộ đánh giá truy xuất, bộ viết lại câu hỏi và công cụ tìm kiếm web.

Chúng ta cũng sẽ học cách xây dựng một quy trình làm việc LangGraph để kết nối tất cả các phần này, minh họa cách CRAG có thể xử lý nhiều loại truy vấn nhằm mang lại kết quả chính xác và đáng tin cậy hơn.

Bước 1: Thiết lập và cài đặt

Trước tiên, cài đặt các gói cần thiết. Bước này thiết lập môi trường để chạy pipeline CRAG.

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

Tiếp theo, cấu hình khóa API cho Tavily và OpenAI:

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

Bước 2: Thiết lập kho tri thức proxy

Để thực hiện RAG, trước hết chúng ta cần một kho tri thức chứa tài liệu. Ở bước này, chúng ta sẽ thu thập một số tài liệu mẫu từ một bản tin Substack để tạo kho vector đóng vai trò là kho tri thức proxy. Kho vector này giúp tìm tài liệu liên quan dựa trên truy vấn của người dùng.

Chúng ta bắt đầu bằng cách tải tài liệu từ các URL cung cấp và chia chúng thành các đoạn nhỏ bằng bộ chia văn bản. Các đoạn này sau đó được nhúng vector bằng OpenAIEmbeddings và lưu trong cơ sở dữ liệu vector (Chroma) để truy xuất tài liệu hiệu quả.

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()

Bước 3: Thiết lập chuỗi RAG

Ở bước này, chúng ta thiết lập một chuỗi RAG cơ bản nhận câu hỏi của người dùng và một tập tài liệu để tạo câu trả lời.

Chuỗi RAG sử dụng một prompt định sẵn và mô hình ngôn ngữ (GPT 4-o mini) để tạo phản hồi dựa trên tài liệu truy xuất. Bộ phân tích đầu ra sau đó định dạng văn bản tạo ra để dễ đọc hơn.

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

Bước 4: Thiết lập bộ đánh giá truy xuất

Để cải thiện độ chính xác của nội dung tạo ra, chúng ta thiết lập một bộ đánh giá truy xuất. Công cụ này kiểm tra mức độ liên quan của từng tài liệu truy xuất để đảm bảo chỉ dùng thông tin hữu ích nhất.

Bộ đánh giá truy xuất được cấu hình với một prompt và mô hình ngôn ngữ. Nó xác định tài liệu có liên quan hay không, lọc bỏ nội dung không liên quan trước khi tạo phản hồi.

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

Bước 5: Thiết lập bộ viết lại câu hỏi

Chúng ta sẽ thêm bộ viết lại câu hỏi để làm cho truy vấn của người dùng rõ ràng và cụ thể hơn, giúp cải thiện quá trình tìm kiếm.

Bộ viết lại tinh chỉnh truy vấn gốc để việc tìm kiếm tập trung hơn, dẫn đến kết quả tốt và phù hợp hơn.

### 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()

Bước 6: Khởi tạo công cụ tìm kiếm web Tavily

Nếu kho tri thức không có đủ thông tin, CRAG sẽ chuyển sang tìm kiếm web để bù đắp khoảng trống. Điều này mở rộng phạm vi nguồn thông tin có thể có. Ở bước này, chúng ta sử dụng Tavily API để tìm kiếm web và thu thập thêm tài liệu.

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

Bước 7: Thiết lập quy trình LangGraph

Để xây dựng quy trình CRAG với LangGraph, hãy làm theo ba bước chính sau:

  1. Định nghĩa trạng thái của đồ thị
  2. Định nghĩa các nút hàm
  3. Kết nối tất cả các nút hàm

Định nghĩa trạng thái của đồ thị

Tạo một trạng thái dùng chung để lưu dữ liệu khi di chuyển giữa các nút trong quy trình. Trạng thái này sẽ giữ tất cả biến, như câu hỏi của người dùng, tài liệu truy xuất và câu trả lời đã tạo.

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]

Định nghĩa các nút hàm

Trong quy trình LangGraph, mỗi nút hàm xử lý một tác vụ cụ thể trong pipeline CRAG, như truy xuất tài liệu, tạo câu trả lời, đánh giá mức độ liên quan, biến đổi truy vấn và tìm kiếm web. Dưới đây là mô tả từng hàm:

Hàm retrieve tìm các tài liệu từ kho tri thức liên quan đến câu hỏi của người dùng. Nó dùng một đối tượng retriever, thường là kho vector được tạo từ tài liệu tiền xử lý. Hàm này nhận trạng thái hiện tại, bao gồm câu hỏi của người dùng, và dùng retriever để lấy tài liệu liên quan. Sau đó thêm các tài liệu này vào trạng thái.

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}

Hàm generate tạo phản hồi cho câu hỏi của người dùng bằng các tài liệu đã truy xuất. Nó hoạt động với chuỗi RAG, kết hợp một prompt với mô hình ngôn ngữ. Hàm này nhận tài liệu truy xuất và câu hỏi của người dùng, xử lý qua chuỗi RAG, rồi thêm câu trả lời vào trạng thái.

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}

Hàm evaluate_documents kiểm tra mức độ liên quan của từng tài liệu truy xuất với câu hỏi của người dùng bằng bộ đánh giá truy xuất. Điều này giúp đảm bảo chỉ sử dụng thông tin hữu ích cho câu trả lời cuối cùng. Hàm này chấm điểm mức độ liên quan của mỗi tài liệu và lọc bỏ những tài liệu không hữu ích. Nó cũng cập nhật trạng thái với cờ web_search để cho biết có cần tìm kiếm web hay không khi phần lớn tài liệu không liên quan.

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}

Hàm transform_query cải thiện câu hỏi của người dùng để có kết quả tìm kiếm tốt hơn, đặc biệt khi truy vấn gốc không tìm thấy tài liệu liên quan. Nó sử dụng bộ viết lại câu hỏi để làm câu hỏi rõ ràng và cụ thể hơn. Câu hỏi tốt hơn sẽ tăng khả năng tìm được tài liệu hữu ích từ cả kho tri thức và tìm kiếm 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}

Hàm web_search tra cứu thêm thông tin trực tuyến bằng truy vấn đã tinh chỉnh. Nó được dùng khi kho tri thức không có đủ thông tin, giúp thu thập thêm nội dung. Hàm này sử dụng công cụ tìm kiếm web Tavily để tìm tài liệu bổ sung trên web, sau đó thêm vào các tài liệu hiện có để cải thiện kho tri thức.

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}

Hàm decide_to_generate quyết định bước tiếp theo: hoặc tạo câu trả lời với các tài liệu hiện có, hoặc tinh chỉnh truy vấn và tìm kiếm lại. Quyết định dựa trên mức độ liên quan của tài liệu (đã được đánh giá trước đó).

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"

Kết nối tất cả các nút hàm

Sau khi định nghĩa xong các nút hàm, chúng ta có thể liên kết tất cả chúng trong quy trình LangGraph để xây dựng pipeline CRAG. Điều này có nghĩa kết nối các nút bằng các cạnh để quản lý luồng thông tin và quyết định, đảm bảo quy trình chạy đúng theo kết quả của từng bước.

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

Quy trình làm việc CRAG LangGraph

Bước 8: Kiểm thử quy trình

Để kiểm thử thiết lập của chúng ta, hãy chạy quy trình với các truy vấn mẫu để kiểm tra cách truy xuất thông tin, đánh giá mức độ liên quan của tài liệu và tạo phản hồi.

Truy vấn đầu tiên kiểm tra mức độ CRAG tìm câu trả lời trong kho tri thức của nó.

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

Và truy vấn thứ hai kiểm tra khả năng CRAG tìm kiếm web để bổ sung thông tin khi kho tri thức không có tài liệu liên quan.

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

Hạn chế của CRAG

Mặc dù CRAG cải tiến so với RAG truyền thống, nó vẫn có một số hạn chế cần lưu ý.

Một vấn đề lớn là phụ thuộc vào chất lượng của bộ đánh giá truy xuất. Bộ đánh giá này rất quan trọng để xác định tài liệu truy xuất có liên quan và chính xác hay không. Tuy nhiên, việc huấn luyện và fine-tuning bộ đánh giá có thể tốn kém, đòi hỏi rất nhiều dữ liệu chất lượng cao và tài nguyên tính toán. Việc giữ cho bộ đánh giá luôn cập nhật với các loại truy vấn và nguồn dữ liệu mới làm tăng thêm độ phức tạp và chi phí.

Một hạn chế khác là việc CRAG sử dụng tìm kiếm web để tìm hoặc thay thế các tài liệu sai hoặc mơ hồ. Dù cách tiếp cận này có thể cung cấp thông tin mới và đa dạng hơn, nó cũng có nguy cơ đưa vào dữ liệu thiên lệch hoặc không đáng tin cậy. Chất lượng nội dung web rất khác nhau, và việc sàng lọc để tìm thông tin chính xác nhất có thể đầy thách thức. Điều này có nghĩa là ngay cả một bộ đánh giá được huấn luyện tốt cũng không thể hoàn toàn ngăn chặn việc đưa vào thông tin kém chất lượng hoặc thiên lệch.

Những thách thức này nhấn mạnh nhu cầu nghiên cứu và phát triển liên tục.

Kết luận

Nhìn chung, CRAG cải tiến so với hệ thống RAG truyền thống bằng cách bổ sung các bước kiểm tra và tinh chỉnh thông tin truy xuất, giúp mô hình ngôn ngữ chính xác và đáng tin cậy hơn. Điều này khiến CRAG trở thành công cụ hữu ích cho nhiều ứng dụng khác nhau.

Để tìm hiểu thêm về CRAG, hãy xem bài báo gốc tại đây.

Nếu bạn đang tìm thêm tài nguyên học về RAG, tôi đề xuất các blog sau:

Ryan Ong

Tác giả

Ryan Ong

Ryan là trưởng nhóm khoa học dữ liệu, chuyên xây dựng các ứng dụng AI sử dụng LLM. Anh là nghiên cứu sinh Tiến sĩ về Xử lý Ngôn ngữ Tự nhiên và Đồ thị Tri thức tại Imperial College London, nơi anh cũng hoàn thành bằng Thạc sĩ Khoa học Máy tính. Ngoài lĩnh vực khoa học dữ liệu, anh viết bản tin Substack hàng tuần, The Limitless Playbook, nơi anh chia sẻ một ý tưởng có thể áp dụng ngay từ các tư tưởng gia hàng đầu thế giới và đôi khi viết về những khái niệm cốt lõi của AI.

Chủ đề

Liên quan