| """ |
| Portable RAG (Retrieval-Augmented Generation) System |
| ===================================================== |
| A completely portable, offline-capable RAG setup using ChromaDB and FastEmbed. |
| |
| Usage: |
| 1. Add a Document: |
| python rag_system.py ingest my_document.pdf |
| python rag_system.py ingest my_notes.txt |
| |
| 2. Query the Knowledge Base: |
| python rag_system.py query "What is the main topic?" |
| """ |
|
|
| import sys |
| import os |
| import argparse |
| from pathlib import Path |
|
|
| |
| import sqlite3 |
| import chromadb |
|
|
| |
| from langchain_community.document_loaders import PyPDFLoader, TextLoader |
| from langchain_text_splitters import RecursiveCharacterTextSplitter |
| from langchain_community.vectorstores import Chroma |
|
|
| |
| from langchain_huggingface import HuggingFaceEndpoint, HuggingFaceEmbeddings |
| from langchain_core.prompts import ChatPromptTemplate |
| from langchain_core.runnables import RunnablePassthrough |
| from langchain_core.output_parsers import StrOutputParser |
|
|
| |
| DEVTOOLS_ROOT = Path(os.environ.get("DEVTOOLS_ROOT", os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) |
| RAG_DATA_DIR = DEVTOOLS_ROOT / "rag_data" |
| RAG_DATA_DIR.mkdir(exist_ok=True) |
|
|
|
|
| |
| print("[INFO] Loading Embedding Model (Local - This may take a moment on first run)...") |
| embeddings = HuggingFaceEmbeddings( |
| model_name="sentence-transformers/all-MiniLM-L6-v2", |
| model_kwargs={'device': 'cpu'} |
| ) |
|
|
| |
| print(f"[INFO] Connecting to ChromaDB at {RAG_DATA_DIR}...") |
| vectorstore = Chroma( |
| embedding_function=embeddings, |
| persist_directory=str(RAG_DATA_DIR) |
| ) |
|
|
|
|
| def ingest_document(file_path: str): |
| """Reads a file, splits it into chunks, and saves to Vector DB.""" |
| path = Path(file_path) |
| if not path.exists(): |
| print(f"[ERROR] File not found: {file_path}") |
| sys.exit(1) |
|
|
| print(f"\n[1/3] Loading document: {path.name}...") |
| if path.suffix.lower() == '.pdf': |
| loader = PyPDFLoader(str(path)) |
| elif path.suffix.lower() == '.txt': |
| loader = TextLoader(str(path), encoding='utf-8') |
| else: |
| print("[ERROR] Unsupported file type. Please use .pdf or .txt") |
| sys.exit(1) |
|
|
| docs = loader.load() |
| print(f" Loaded {len(docs)} pages/sections.") |
|
|
| print("[2/3] Splitting into chunks...") |
| text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200) |
| splits = text_splitter.split_documents(docs) |
| print(f" Created {len(splits)} chunks.") |
|
|
| print("[3/3] Generating vectors and saving to database...") |
| vectorstore.add_documents(splits) |
| print("\n[SUCCESS] Document ingested successfully!") |
|
|
|
|
| def format_docs(docs): |
| return "\n\n".join(doc.page_content for doc in docs) |
|
|
|
|
| def query_rag(query: str): |
| """Retrieves relevant chunks and optionally uses an LLM to generate an answer.""" |
| print(f"\n[Q] {query}\n") |
|
|
| |
| print("βββ RETRIEVED CONTEXT ββββββββββββββββββββ") |
| retriever = vectorstore.as_retriever(search_kwargs={"k": 3}) |
| results = retriever.invoke(query) |
| |
| if not results: |
| print("No relevant context found in the database.") |
| return |
|
|
| for i, doc in enumerate(results): |
| source = doc.metadata.get('source', 'Unknown') |
| page = doc.metadata.get('page', '') |
| page_info = f" (Page {page})" if page else "" |
| print(f"[{i+1}] Source: {os.path.basename(source)}{page_info}") |
| print(f" {doc.page_content[:300]}...\n") |
|
|
| |
| hf_token = os.environ.get("HF_TOKEN") |
| if hf_token: |
| print("\nβββ AI GENERATED ANSWER ββββββββββββββββββ") |
| try: |
| llm = HuggingFaceEndpoint( |
| repo_id="meta-llama/Meta-Llama-3-8B-Instruct", |
| task="text-generation", |
| max_new_tokens=512, |
| huggingfacehub_api_token=hf_token |
| ) |
| |
| template = """You are an assistant for question-answering tasks. |
| Use the following pieces of retrieved context to answer the question. |
| If you don't know the answer, say that you don't know. |
| Keep the answer concise and accurate based ONLY on the context. |
| |
| Context: {context} |
| |
| Question: {question} |
| |
| Answer:""" |
| prompt = ChatPromptTemplate.from_template(template) |
| |
| rag_chain = ( |
| {"context": retriever | format_docs, "question": RunnablePassthrough()} |
| | prompt |
| | llm |
| | StrOutputParser() |
| ) |
| |
| response = rag_chain.invoke(query) |
| print(response.strip()) |
| |
| except Exception as e: |
| print(f"[WARN] Could not generate AI answer. (Are you logged into Hugging Face?)") |
| print(f" Error: {e}") |
| else: |
| print("\n[NOTE] HuggingFace token not found. Only returning retrieved documents.") |
| print(" Run 'hf auth login' in your terminal to enable AI Generation.") |
|
|
|
|
| def main(): |
| parser = argparse.ArgumentParser(description="Portable RAG System") |
| subparsers = parser.add_subparsers(dest="command", help="Commands") |
|
|
| |
| ingest_parser = subparsers.add_parser("ingest", help="Ingest a document into the database") |
| ingest_parser.add_argument("file", type=str, help="Path to PDF or TXT file") |
|
|
| |
| query_parser = subparsers.add_parser("query", help="Query the database") |
| query_parser.add_argument("query", type=str, help="Your question") |
|
|
| args = parser.parse_args() |
|
|
| if args.command == "ingest": |
| ingest_document(args.file) |
| elif args.command == "query": |
| query_rag(args.query) |
| else: |
| parser.print_help() |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|