Elffuss BraidHub

kikocis/lancedb public

main 路 3.9 KiBRenderedRawPermalink
1**Self RAG 馃こ**
2====================================================================
3Self-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 ![agent-based-rag](https://raw.githubusercontent.com/lancedb/assets/main/docs/assets/rag/self_rag.png)
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
15Self-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
17Here鈥檚 a code snippet for defining retriever using Langchain
18
19```python
20from langchain.text_splitter import RecursiveCharacterTextSplitter
21from langchain_community.document_loaders import WebBaseLoader
22from langchain_community.vectorstores import LanceDB
23from langchain_openai import OpenAIEmbeddings
24
25urls = [
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
32docs = [WebBaseLoader(url).load() for url in urls]
33docs_list = [item for sublist in docs for item in sublist]
34
35text_splitter = RecursiveCharacterTextSplitter.from_tiktoken_encoder(
36 chunk_size=100, chunk_overlap=50
37)
38doc_splits = text_splitter.split_documents(docs_list)
39
40# add documents in LanceDB
41vectorstore = LanceDB.from_documents(
42 documents=doc_splits,
43 embedding=OpenAIEmbeddings(),
44)
45retriever = vectorstore.as_retriever()
46
47```
48
49Functions that grades the retrieved documents and if required formulates an improved query for better retrieval results
50
51```python
52def 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
79def 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```