Elffuss BraidHub

kikocis/lancedb public

main 路 4.1 KiBRenderedRawPermalink
1**Agentic RAG 馃**
2====================================================================
3Agentic RAG is Agent-based RAG introduces an advanced framework for answering questions by using intelligent agents instead of just relying on large language models. These agents act like expert researchers, handling complex tasks such as detailed planning, multi-step reasoning, and using external tools. They navigate multiple documents, compare information, and generate accurate answers. This system is easily scalable, with each new document set managed by a sub-agent, making it a powerful tool for tackling a wide range of information needs.
4
5<figure markdown="span">
6 ![agent-based-rag](https://raw.githubusercontent.com/lancedb/assets/main/docs/assets/rag/agentic_rag.png)
7 <figcaption>Agent-based RAG</figcaption>
8</figure>
9
10[![Open In Colab](../assets/colab.svg)](https://colab.research.google.com/github/lancedb/vectordb-recipes/blob/main/tutorials/Agentic_RAG/main.ipynb)
11
12Here鈥檚 a code snippet for defining retriever using Langchain
13
14```python
15from langchain.text_splitter import RecursiveCharacterTextSplitter
16from langchain_community.document_loaders import WebBaseLoader
17from langchain_community.vectorstores import LanceDB
18from langchain_openai import OpenAIEmbeddings
19
20urls = [
21 "https://content.dgft.gov.in/Website/CIEP.pdf",
22 "https://content.dgft.gov.in/Website/GAE.pdf",
23 "https://content.dgft.gov.in/Website/HTE.pdf",
24]
25
26
27docs = [WebBaseLoader(url).load() for url in urls]
28docs_list = [item for sublist in docs for item in sublist]
29
30text_splitter = RecursiveCharacterTextSplitter.from_tiktoken_encoder(
31 chunk_size=100, chunk_overlap=50
32)
33doc_splits = text_splitter.split_documents(docs_list)
34
35# add documents in LanceDB
36vectorstore = LanceDB.from_documents(
37 documents=doc_splits,
38 embedding=OpenAIEmbeddings(),
39)
40retriever = vectorstore.as_retriever()
41
42```
43
44Agent that formulates an improved query for better retrieval results and then grades the retrieved documents
45
46```python
47def grade_documents(state) -> Literal["generate", "rewrite"]:
48 class grade(BaseModel):
49 binary_score: str = Field(description="Relevance score 'yes' or 'no'")
50
51 model = ChatOpenAI(temperature=0, model="gpt-4-0125-preview", streaming=True)
52 llm_with_tool = model.with_structured_output(grade)
53 prompt = PromptTemplate(
54 template="""You are a grader assessing relevance of a retrieved document to a user question. \n
55 Here is the retrieved document: \n\n {context} \n\n
56 Here is the user question: {question} \n
57 If the document contains keyword(s) or semantic meaning related to the user question, grade it as relevant. \n
58 Give a binary score 'yes' or 'no' score to indicate whether the document is relevant to the question.""",
59 input_variables=["context", "question"],
60 )
61 chain = prompt | llm_with_tool
62
63 messages = state["messages"]
64 last_message = messages[-1]
65 question = messages[0].content
66 docs = last_message.content
67
68 scored_result = chain.invoke({"question": question, "context": docs})
69 score = scored_result.binary_score
70
71 return "generate" if score == "yes" else "rewrite"
72
73
74def agent(state):
75 messages = state["messages"]
76 model = ChatOpenAI(temperature=0, streaming=True, model="gpt-4-turbo")
77 model = model.bind_tools(tools)
78 response = model.invoke(messages)
79 return {"messages": [response]}
80
81
82def rewrite(state):
83 messages = state["messages"]
84 question = messages[0].content
85 msg = [
86 HumanMessage(
87 content=f""" \n
88 Look at the input and try to reason about the underlying semantic intent / meaning. \n
89 Here is the initial question:
90 \n ------- \n
91 {question}
92 \n ------- \n
93 Formulate an improved question: """,
94 )
95 ]
96 model = ChatOpenAI(temperature=0, model="gpt-4-0125-preview", streaming=True)
97 response = model.invoke(msg)
98 return {"messages": [response]}
99```
100
101[![Open In Colab](../assets/colab.svg)](https://colab.research.google.com/github/lancedb/vectordb-recipes/blob/main/tutorials/Agentic_RAG/main.ipynb)