| 1 | **Self RAG 馃こ** |
| 2 | ==================================================================== |
| 3 | Self-RAG is a strategy for Retrieval-Augmented Generation (RAG) to get better retrieved information, generated text, and checking their own work, all without losing their flexibility. Unlike the traditional Retrieval-Augmented Generation (RAG) method, Self-RAG retrieves information as needed, can skip retrieval if not needed, and evaluates its own output while generating text. It also uses a process to pick the best output based on different preferences. |
| 4 | |
| 5 | **[Official Paper](https://arxiv.org/pdf/2310.11511)** |
| 6 | |
| 7 | <figure markdown="span"> |
| 8 |  |
| 9 | <figcaption>Self RAG: <a href="https://github.com/AkariAsai/self-rag">Source</a> |
| 10 | </figcaption> |
| 11 | </figure> |
| 12 | |
| 13 | **[Offical Implementation](https://github.com/AkariAsai/self-rag)** |
| 14 | |
| 15 | Self-RAG starts by generating a response without retrieving extra info if it's not needed. For questions that need more details, it retrieves to get the necessary information. |
| 16 | |
| 17 | Here鈥檚 a code snippet for defining retriever using Langchain |
| 18 | |
| 19 | ```python |
| 20 | from langchain.text_splitter import RecursiveCharacterTextSplitter |
| 21 | from langchain_community.document_loaders import WebBaseLoader |
| 22 | from langchain_community.vectorstores import LanceDB |
| 23 | from langchain_openai import OpenAIEmbeddings |
| 24 | |
| 25 | urls = [ |
| 26 | "https://lilianweng.github.io/posts/2023-06-23-agent/", |
| 27 | "https://lilianweng.github.io/posts/2023-03-15-prompt-engineering/", |
| 28 | "https://lilianweng.github.io/posts/2023-10-25-adv-attack-llm/", |
| 29 | ] |
| 30 | |
| 31 | |
| 32 | docs = [WebBaseLoader(url).load() for url in urls] |
| 33 | docs_list = [item for sublist in docs for item in sublist] |
| 34 | |
| 35 | text_splitter = RecursiveCharacterTextSplitter.from_tiktoken_encoder( |
| 36 | chunk_size=100, chunk_overlap=50 |
| 37 | ) |
| 38 | doc_splits = text_splitter.split_documents(docs_list) |
| 39 | |
| 40 | # add documents in LanceDB |
| 41 | vectorstore = LanceDB.from_documents( |
| 42 | documents=doc_splits, |
| 43 | embedding=OpenAIEmbeddings(), |
| 44 | ) |
| 45 | retriever = vectorstore.as_retriever() |
| 46 | |
| 47 | ``` |
| 48 | |
| 49 | Functions that grades the retrieved documents and if required formulates an improved query for better retrieval results |
| 50 | |
| 51 | ```python |
| 52 | def grade_documents(state) -> Literal["generate", "rewrite"]: |
| 53 | class grade(BaseModel): |
| 54 | binary_score: str = Field(description="Relevance score 'yes' or 'no'") |
| 55 | |
| 56 | model = ChatOpenAI(temperature=0, model="gpt-4-0125-preview", streaming=True) |
| 57 | llm_with_tool = model.with_structured_output(grade) |
| 58 | prompt = PromptTemplate( |
| 59 | template="""You are a grader assessing relevance of a retrieved document to a user question. \n |
| 60 | Here is the retrieved document: \n\n {context} \n\n |
| 61 | Here is the user question: {question} \n |
| 62 | If the document contains keyword(s) or semantic meaning related to the user question, grade it as relevant. \n |
| 63 | Give a binary score 'yes' or 'no' score to indicate whether the document is relevant to the question.""", |
| 64 | input_variables=["context", "question"], |
| 65 | ) |
| 66 | chain = prompt | llm_with_tool |
| 67 | |
| 68 | messages = state["messages"] |
| 69 | last_message = messages[-1] |
| 70 | question = messages[0].content |
| 71 | docs = last_message.content |
| 72 | |
| 73 | scored_result = chain.invoke({"question": question, "context": docs}) |
| 74 | score = scored_result.binary_score |
| 75 | |
| 76 | return "generate" if score == "yes" else "rewrite" |
| 77 | |
| 78 | |
| 79 | def rewrite(state): |
| 80 | messages = state["messages"] |
| 81 | question = messages[0].content |
| 82 | msg = [ |
| 83 | HumanMessage( |
| 84 | content=f""" \n |
| 85 | Look at the input and try to reason about the underlying semantic intent / meaning. \n |
| 86 | Here is the initial question: |
| 87 | \n ------- \n |
| 88 | {question} |
| 89 | \n ------- \n |
| 90 | Formulate an improved question: """, |
| 91 | ) |
| 92 | ] |
| 93 | model = ChatOpenAI(temperature=0, model="gpt-4-0125-preview", streaming=True) |
| 94 | response = model.invoke(msg) |
| 95 | return {"messages": [response]} |
| 96 | ``` |