| 1 | **Adaptive RAG 🤹♂️** |
| 2 | ==================================================================== |
| 3 | Adaptive RAG introduces a RAG technique that combines query analysis with self-corrective RAG. |
| 4 | |
| 5 | For Query Analysis, it uses a small classifier(LLM), to decide the query’s complexity. Query Analysis helps routing smoothly to adjust between different retrieval strategies No retrieval, Single-shot RAG or Iterative RAG. |
| 6 | |
| 7 | **[Official Paper](https://arxiv.org/pdf/2403.14403)** |
| 8 | |
| 9 | <figure markdown="span"> |
| 10 |  |
| 11 | <figcaption>Adaptive-RAG: <a href="https://github.com/starsuzi/Adaptive-RAG">Source</a> |
| 12 | </figcaption> |
| 13 | </figure> |
| 14 | |
| 15 | **[Offical Implementation](https://github.com/starsuzi/Adaptive-RAG)** |
| 16 | |
| 17 | Here’s a code snippet for query analysis |
| 18 | |
| 19 | ```python |
| 20 | from langchain_core.prompts import ChatPromptTemplate |
| 21 | from langchain_core.pydantic_v1 import BaseModel, Field |
| 22 | from langchain_openai import ChatOpenAI |
| 23 | |
| 24 | class RouteQuery(BaseModel): |
| 25 | """Route a user query to the most relevant datasource.""" |
| 26 | |
| 27 | datasource: Literal["vectorstore", "web_search"] = Field( |
| 28 | ..., |
| 29 | description="Given a user question choose to route it to web search or a vectorstore.", |
| 30 | ) |
| 31 | |
| 32 | |
| 33 | # LLM with function call |
| 34 | llm = ChatOpenAI(model="gpt-3.5-turbo-0125", temperature=0) |
| 35 | structured_llm_router = llm.with_structured_output(RouteQuery) |
| 36 | ``` |
| 37 | |
| 38 | For defining and querying retriever |
| 39 | |
| 40 | ```python |
| 41 | # add documents in LanceDB |
| 42 | vectorstore = LanceDB.from_documents( |
| 43 | documents=doc_splits, |
| 44 | embedding=OpenAIEmbeddings(), |
| 45 | ) |
| 46 | retriever = vectorstore.as_retriever() |
| 47 | |
| 48 | # query using defined retriever |
| 49 | question = "How adaptive RAG works" |
| 50 | docs = retriever.get_relevant_documents(question) |
| 51 | ``` |