Apa Itu Corrective RAG (CRAG)?
Corrective retrieval-augmented generation (CRAG) adalah versi RAG yang disempurnakan dengan tujuan membuat model bahasa lebih akurat.
Sementara RAG tradisional hanya menggunakan dokumen yang diambil untuk membantu menghasilkan teks, CRAG melangkah lebih jauh dengan secara aktif memeriksa dan menyempurnakan dokumen tersebut untuk memastikan dokumen itu relevan dan akurat. Ini membantu mengurangi kesalahan atau halusinasi ketika model mungkin menghasilkan informasi yang salah atau menyesatkan.

Sumber: Shi-Qi Yan dkk., 2024
Kerangka kerja CRAG berjalan melalui beberapa langkah kunci, yang melibatkan evaluator pengambilan dan tindakan korektif tertentu.
Untuk setiap kueri masukan, sebuah retriever standar terlebih dahulu mengambil sekumpulan dokumen dari basis pengetahuan. Dokumen-dokumen ini kemudian ditinjau oleh evaluator pengambilan untuk menentukan relevansi setiap dokumen terhadap kueri.
Dalam CRAG, evaluator pengambilan adalah model T5-large yang telah di-fine-tune. Evaluator memberikan skor keyakinan untuk setiap dokumen, mengelompokkannya ke dalam tiga tingkat keyakinan:
- Benar: Jika setidaknya satu dokumen melampaui ambang atas, dokumen tersebut dianggap benar. Sistem kemudian menerapkan proses penyempurnaan pengetahuan, menggunakan algoritma decompose-then-recompose untuk mengekstrak potongan pengetahuan yang paling penting dan relevan sambil menyaring data yang tidak relevan atau berisik dalam dokumen. Ini memastikan hanya informasi yang paling akurat dan relevan yang dipertahankan untuk proses generasi.
- Salah: Jika semua dokumen berada di bawah ambang bawah, dokumen tersebut ditandai sebagai salah. Dalam kasus ini, CRAG membuang semua dokumen yang diambil dan sebagai gantinya melakukan penelusuran web untuk mengumpulkan pengetahuan eksternal baru yang berpotensi lebih akurat. Langkah ini memperluas proses pengambilan melampaui basis pengetahuan statis atau terbatas dengan memanfaatkan informasi luas dan dinamis yang tersedia di web, sehingga meningkatkan kemungkinan mengambil data yang relevan dan akurat.
- Ambigu: Ketika dokumen yang diambil berisi hasil yang bercampur, hal ini dianggap ambigu. Dalam kasus ini, CRAG menggabungkan kedua strategi: menyempurnakan informasi dari dokumen yang awalnya diambil dan memasukkan pengetahuan tambahan yang diperoleh dari penelusuran web.
Setelah salah satu tindakan ini dilakukan, pengetahuan yang telah disempurnakan digunakan untuk menghasilkan respons akhir.
CRAG vs. RAG tradisional
CRAG menghadirkan beberapa peningkatan penting dibandingkan RAG tradisional. Salah satu keunggulan terbesarnya adalah kemampuannya memperbaiki kesalahan dalam informasi yang diambil. Evaluator pengambilan dalam CRAG membantu mendeteksi ketika informasi salah atau tidak relevan, sehingga dapat dikoreksi sebelum memengaruhi keluaran akhir. Ini berarti CRAG menyediakan informasi yang lebih akurat dan andal, sekaligus mengurangi kesalahan dan disinformasi.
CRAG juga unggul dalam memastikan informasi tidak hanya relevan tetapi juga akurat. Sementara RAG tradisional mungkin hanya memeriksa skor relevansi, CRAG melangkah lebih jauh dengan menyempurnakan dokumen agar tidak sekadar relevan, melainkan juga presisi. Ia menyaring detail yang tidak relevan dan berfokus pada poin paling penting, sehingga teks yang dihasilkan bertumpu pada informasi yang akurat.
Implementasi CRAG Menggunakan LangGraph
Pada bagian ini, kita akan melalui panduan langkah demi langkah tentang cara mengimplementasikan CRAG menggunakan LangGraph. Anda akan mempelajari cara menyiapkan lingkungan, membuat knowledge vector store dasar, dan mengonfigurasi komponen kunci yang diperlukan untuk CRAG, seperti evaluator pengambilan, penulis ulang pertanyaan, dan alat penelusuran web.
Kita juga akan mempelajari cara membangun alur kerja LangGraph yang menyatukan semua bagian ini, menunjukkan bagaimana CRAG dapat menangani berbagai jenis kueri untuk hasil yang lebih akurat dan andal.
Langkah 1: Penyiapan dan instalasi
Pertama, instal paket yang diperlukan. Langkah ini menyiapkan lingkungan untuk menjalankan pipeline CRAG.
pip install langchain_community tiktoken langchain-openai langchainhub chromadb langchain langgraph tavily-python
Selanjutnya, konfigurasikan kunci API Anda untuk Tavily dan OpenAI:
import os
os.environ["TAVILY_API_KEY"] = "YOUR_TAVILY_API_KEY"
os.environ["OPENAI_API_KEY"] = "YOUR_OPENAI_API_KEY"
Langkah 2: Menyiapkan basis pengetahuan proxy
Untuk melakukan RAG, kita terlebih dahulu memerlukan basis pengetahuan yang berisi dokumen. Pada langkah ini, kita akan men-scrape beberapa dokumen contoh dari newsletter Substack untuk membuat vector store, yang bertindak sebagai basis pengetahuan proxy. Vector store ini membantu kita menemukan dokumen relevan berdasarkan kueri pengguna.
Kita mulai dengan memuat dokumen dari URL yang disediakan dan membaginya menjadi bagian-bagian kecil menggunakan text splitter. Bagian-bagian ini kemudian di-embed menggunakan OpenAIEmbeddings dan disimpan dalam basis data vektor (Chroma) untuk pengambilan dokumen yang efisien.
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()
Langkah 3: Menyiapkan rantai RAG
Pada langkah ini, kita menyiapkan rantai RAG dasar yang mengambil pertanyaan pengguna dan sekumpulan dokumen untuk menghasilkan jawaban.
Rantai RAG menggunakan prompt yang telah ditentukan dan model bahasa (GPT 4-o mini) untuk membuat respons berdasarkan dokumen yang diambil. Sebuah output parser kemudian memformat teks yang dihasilkan agar lebih mudah dibaca.
### 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.
Langkah 4: Menyiapkan evaluator pengambilan
Untuk meningkatkan akurasi konten yang dihasilkan, kita menyiapkan evaluator pengambilan. Alat ini memeriksa seberapa relevan setiap dokumen yang diambil untuk memastikan hanya informasi paling berguna yang digunakan.
Evaluator pengambilan dikonfigurasi dengan sebuah prompt dan model bahasa. Ia menentukan apakah dokumen relevan atau tidak, menyaring konten yang tidak relevan sebelum respons dihasilkan.
### 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
Langkah 5: Menyiapkan penulis ulang pertanyaan
Kita akan menambahkan penulis ulang pertanyaan untuk membuat kueri pengguna lebih jelas dan spesifik, sehingga membantu meningkatkan proses pencarian.
Penulis ulang menyempurnakan kueri asli agar pencarian lebih terfokus, menghasilkan temuan yang lebih baik dan relevan.
### 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()
Langkah 6: Inisialisasi alat penelusuran web Tavily
Jika basis pengetahuan tidak memiliki informasi yang cukup, CRAG beralih ke penelusuran web untuk menutup celah. Ini memperluas cakupan sumber informasi yang mungkin. Pada langkah ini, kita menggunakan API Tavily untuk menelusuri web dan menemukan dokumen tambahan.
### Search
from langchain_community.tools.tavily_search import TavilySearchResults
web_search_tool = TavilySearchResults(k=3)
Langkah 7: Menyiapkan alur kerja LangGraph
Untuk membangun alur kerja CRAG dengan LangGraph, ikuti tiga langkah utama berikut:
- Definisikan state graf
- Definisikan node fungsi
- Hubungkan semua node fungsi
Definisikan state graf
Buat state bersama untuk menyimpan data saat berpindah antar node selama alur kerja. State ini akan menampung semua variabel, seperti pertanyaan pengguna, dokumen yang diambil, dan jawaban yang dihasilkan.
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]
Definisikan node fungsi
Dalam alur kerja LangGraph, setiap node fungsi menangani tugas tertentu dalam pipeline CRAG, seperti mengambil dokumen, menghasilkan jawaban, mengevaluasi relevansi, mentransformasi kueri, dan menelusuri web. Berikut rincian setiap fungsi:
Fungsi retrieve menemukan dokumen dari basis pengetahuan yang relevan dengan pertanyaan pengguna. Fungsi ini menggunakan objek retriever, yang biasanya merupakan vector store yang dibuat dari dokumen yang telah dipra-proses. Fungsi ini mengambil state saat ini, termasuk pertanyaan pengguna, dan menggunakan retriever untuk mendapatkan dokumen relevan. Lalu menambahkan dokumen tersebut ke state.
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}
Fungsi generate membuat respons atas pertanyaan pengguna menggunakan dokumen yang diambil. Fungsi ini bekerja dengan rantai RAG, yang menggabungkan prompt dengan model bahasa. Fungsi ini mengambil dokumen yang diambil dan pertanyaan pengguna, memprosesnya melalui rantai RAG, lalu menambahkan jawaban ke state.
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}
Fungsi evaluate_documents memeriksa seberapa relevan setiap dokumen yang diambil terhadap pertanyaan pengguna menggunakan evaluator pengambilan. Ini membantu memastikan hanya informasi yang berguna yang digunakan untuk jawaban akhir. Fungsi ini menilai relevansi setiap dokumen dan menyaring yang tidak berguna. Fungsi ini juga memperbarui state dengan flag web_search untuk menunjukkan apakah penelusuran web diperlukan saat sebagian besar dokumen tidak relevan.
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}
Fungsi transform_query memperbaiki pertanyaan pengguna untuk mendapatkan hasil pencarian yang lebih baik, terutama jika kueri asli tidak menemukan dokumen relevan. Fungsi ini menggunakan penulis ulang pertanyaan untuk membuat pertanyaan lebih jelas dan spesifik. Pertanyaan yang lebih baik meningkatkan peluang menemukan dokumen berguna baik dari basis pengetahuan maupun dari penelusuran 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}
Fungsi web_search mencari informasi tambahan secara online menggunakan kueri yang telah disempurnakan. Fungsi ini digunakan saat basis pengetahuan tidak memiliki informasi yang cukup, membantu mengumpulkan lebih banyak konten. Fungsi ini menggunakan alat penelusuran web Tavily untuk menemukan dokumen tambahan di web, yang kemudian ditambahkan ke dokumen yang ada untuk memperkaya basis pengetahuan.
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}
Fungsi decide_to_generate memutuskan langkah berikutnya: apakah menghasilkan jawaban dengan dokumen saat ini atau menyempurnakan kueri dan mencari lagi. Keputusan ini dibuat berdasarkan seberapa relevan dokumen (sebagaimana dinilai sebelumnya).
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"
Hubungkan semua node fungsi
Setelah semua node fungsi didefinisikan, kita dapat menautkan semua node tersebut dalam alur kerja LangGraph untuk membangun pipeline CRAG. Ini berarti menghubungkan node dengan edge untuk mengelola aliran informasi dan keputusan, memastikan alur kerja berjalan dengan benar berdasarkan hasil tiap langkah.
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

Langkah 8: Pengujian alur kerja
Untuk menguji setelan kita, jalankan alur kerja dengan kueri contoh untuk memeriksa bagaimana ia mengambil informasi, mengevaluasi relevansi dokumen, dan menghasilkan respons.
Kueri pertama memeriksa sebaik apa CRAG menemukan jawaban dalam basis pengetahuannya.
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.')
Dan kueri kedua menguji kemampuan CRAG untuk menelusuri web guna memperoleh informasi tambahan ketika basis pengetahuan tidak memiliki dokumen yang relevan.
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.')
Keterbatasan CRAG
Meskipun CRAG meningkatkan RAG tradisional, ada beberapa keterbatasan yang perlu diperhatikan.
Salah satu masalah utama adalah ketergantungannya pada kualitas evaluator pengambilan. Evaluator ini penting untuk menilai apakah dokumen yang diambil relevan dan akurat. Namun, pelatihan dan fine-tuning evaluator dapat menuntut banyak data berkualitas tinggi dan daya komputasi. Menjaga evaluator tetap mutakhir dengan jenis kueri dan sumber data baru menambah kompleksitas dan biaya.
Keterbatasan lain adalah penggunaan penelusuran web oleh CRAG untuk menemukan atau mengganti dokumen yang salah atau ambigu. Meskipun pendekatan ini dapat menyediakan informasi yang lebih baru dan beragam, ada risiko memasukkan data yang bias atau tidak dapat diandalkan. Kualitas konten web sangat bervariasi, dan memilahnya untuk menemukan informasi paling akurat bisa jadi menantang. Ini berarti bahkan evaluator yang terlatih dengan baik sekalipun tidak dapat sepenuhnya mencegah masuknya informasi berkualitas buruk atau bias.
Tantangan ini menyoroti perlunya penelitian dan pengembangan berkelanjutan.
Kesimpulan
Secara keseluruhan, CRAG meningkatkan sistem RAG tradisional dengan menambahkan fitur yang memeriksa dan menyempurnakan informasi yang diambil, sehingga model bahasa menjadi lebih akurat dan andal. Ini menjadikan CRAG alat yang berguna untuk berbagai aplikasi.
Untuk mempelajari lebih lanjut tentang CRAG, baca paper aslinya di sini.
Jika Anda mencari sumber belajar lain tentang RAG, saya merekomendasikan blog berikut:
Ryan adalah lead data scientist yang mengkhususkan diri dalam membangun aplikasi AI menggunakan LLM. Ia adalah kandidat PhD di bidang Pemrosesan Bahasa Alami dan Knowledge Graph di Imperial College London, tempat ia juga menyelesaikan gelar Master di Ilmu Komputer. Di luar data science, ia menulis newsletter Substack mingguan, The Limitless Playbook, di mana ia membagikan satu ide yang dapat langsung dipraktikkan dari para pemikir top dunia dan sesekali menulis tentang konsep inti AI.


Retrieval-augmented generation (RAG) meningkatkan model bahasa besar dengan mengambil dokumen relevan dari sumber eksternal untuk mendukung pembuatan teks. Namun, RAG tidak sempurna—ia masih dapat menghasilkan konten yang menyesatkan jika dokumen yang diambil tidak akurat atau tidak relevan.
Untuk mengatasi masalah ini, corrective retrieval-augmented generation (CRAG) diusulkan. CRAG bekerja dengan menambahkan langkah untuk memeriksa dan menyempurnakan informasi yang diambil sebelum menggunakannya untuk menghasilkan teks. Ini membuat model bahasa lebih akurat dan mengurangi kemungkinan menghasilkan konten yang menyesatkan.
Dalam artikel ini, saya akan memperkenalkan CRAG dan memandu Anda melalui implementasi langkah demi langkah menggunakan LangGraph.