| 1 | **Vanilla RAG 馃尡** |
| 2 | ==================================================================== |
| 3 | |
| 4 | RAG(Retrieval-Augmented Generation) works by finding documents related to the user's question, combining them with a prompt for a large language model (LLM), and then using the LLM to create more accurate and relevant answers. |
| 5 | |
| 6 | Here鈥檚 a simple guide to building a RAG pipeline from scratch: |
| 7 | |
| 8 | 1. **Data Loading**: Gather and load the documents you want to use for answering questions. |
| 9 | |
| 10 | 2. **Chunking and Embedding**: Split the documents into smaller chunks and convert them into numerical vectors (embeddings) that capture their meaning. |
| 11 | |
| 12 | 3. **Vector Store**: Create a LanceDB table to store and manage these vectors for quick access during retrieval. |
| 13 | |
| 14 | 4. **Retrieval & Prompt Preparation**: When a question is asked, find the most relevant document chunks from the table and prepare a prompt combining these chunks with the question. |
| 15 | |
| 16 | 5. **Answer Generation**: Send the prepared prompt to a LLM to generate a detailed and accurate answer. |
| 17 | |
| 18 | <figure markdown="span"> |
| 19 |  |
| 20 | <figcaption>Vanilla RAG |
| 21 | </figcaption> |
| 22 | </figure> |
| 23 | |
| 24 | [](https://colab.research.google.com/github/lancedb/vectordb-recipes/blob/main/tutorials/RAG-from-Scratch/RAG_from_Scratch.ipynb) |
| 25 | |
| 26 | Here鈥檚 a code snippet for defining a table with the [Embedding API](https://lancedb.github.io/lancedb/embeddings/embedding_functions/), which simplifies the process by handling embedding extraction and querying in one step. |
| 27 | |
| 28 | ```python |
| 29 | import pandas as pd |
| 30 | import lancedb |
| 31 | from lancedb.pydantic import LanceModel, Vector |
| 32 | from lancedb.embeddings import get_registry |
| 33 | |
| 34 | db = lancedb.connect("/tmp/db") |
| 35 | model = get_registry().get("sentence-transformers").create(name="BAAI/bge-small-en-v1.5", device="cpu") |
| 36 | |
| 37 | class Docs(LanceModel): |
| 38 | text: str = model.SourceField() |
| 39 | vector: Vector(model.ndims()) = model.VectorField() |
| 40 | |
| 41 | table = db.create_table("docs", schema=Docs) |
| 42 | |
| 43 | # considering chunks are in list format |
| 44 | df = pd.DataFrame({'text':chunks}) |
| 45 | table.add(data=df) |
| 46 | |
| 47 | query = "What is issue date of lease?" |
| 48 | actual = table.search(query).limit(1).to_list()[0] |
| 49 | print(actual.text) |
| 50 | ``` |
| 51 | |
| 52 | Check Colab for the complete code |
| 53 | |
| 54 | [](https://colab.research.google.com/github/lancedb/vectordb-recipes/blob/main/tutorials/RAG-from-Scratch/RAG_from_Scratch.ipynb) |