Skip to content

About

This project is a Retrieval-Augmented Generation (RAG) application designed to act as an intelligent librarian. By indexing technical Python books, it allows users to ask complex questions and receive answers grounded in the specific text of those books, complete with context.

Topics

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

🏑 Rag_Library_AI

Last Commit Repo Size License

LangChain Python Rust Scikit-Learn Streamlit

This project is a Retrieval-Augmented Generation (RAG) application designed to act as an intelligent librarian. By indexing technical Python books, it allows users to ask complex questions and receive answers grounded in the specific text of those books, complete with context.


🌐 Live Demo

Try the live Hugging Face deployment:

πŸ‘‰ Launch RAG Library AI


πŸ“‘ Table of Contents

Section Link
Why This Project Exists The problem and solution.
Architectural Diagram Project overview.
Screenshots Application walkthrough.
Key Features Main functionality and architecture.
Project Structure Repository organisation.
Getting Started Installation and configuration.
Usage Running the web and CLI interface.
Testing Pytest Suite.
Hallucination Guardrail Semantic Verification.
Roadmap Features Future Improvements.

🎯 Why This Project Exists

Many RAG systems can retrieve relevant documents but still produce incorrect, misleading, or hallucinated responses.

This project explores how retrieval systems can be combined with lightweight semantic verification techniques to improve answer reliability.

The goal was not simply to build another RAG assistant, but to investigate methods for detecting and reducing hallucinations using local embeddings and mathematical similarity checks.


πŸ—οΈ Architectural Diagram

Documents are chunked, embedded, indexed in ChromaDB, retrieved on demand, and verified by a semantic guardrail before responses are returned to the user.

PDF Books
    ↓
fast_chunker (Rust)
    ↓
Embeddings
    ↓
ChromaDB
    ↓
Retriever
    ↓
Gemini
    ↓
Guardrail Audit
    ↓
User Response

πŸ“Έ Screenshots

UI of the Rag Library Dashboard

Screenshot 1

Interactive RAG Search Experience A simple web interface that enables users to query a Python-focused knowledge base using natural language. Dashboard 1

Screenshot 2

Context-Grounded AI Responses Answers are generated from retrieved document chunks, helping reduce hallucinations and improve response accuracy. Dashboard 2

Screenshot 3

Context-Aware Guardrails When relevant source material is unavailable, the system responds with "The answer isn't in the context" instead of generating unsupported information. Dashboard 3


πŸš€ Key Features

  • Dual Interfaces: Interaction via a clean Streamlit Web Dashboard (app.py) or a lightweight CLI Tool (query.py).

  • Rust-Powered Performance: Document ingestion uses a custom high-speed text splitting package (fast_chunker) built with Rust and exposed to Python using PyO3.

  • Semantic Guardrails: Every response undergoes a real-time Groundedness Audit using local embeddings (all-MiniLM-L6-v2) and Cosine Similarity to evaluate if the AI's response is mathematically justified by the source texts.

  • Deterministic Safety Fallbacks: Completely blocks hallucinated library syntax or jumbled text blocks, gracefully bypassing checks only when the AI correctly identifies a lack of context.

  • Multiple Interfaces: Query the knowledge base through either the Streamlit web dashboard or the lightweight command-line interface.


πŸ“ Project Structure

The project architecture is structured for scalability, featuring isolated scanning, processing, and documentation assembly engines.

rag-technical-app/
β”œβ”€β”€ fast_chunker/          # Custom Rust text splitting module
β”‚   β”œβ”€β”€ src/
β”‚   β”‚   └── lib.rs         # PyO3 Rust chunking implementation
β”‚   β”œβ”€β”€ Cargo.toml         # Rust dependency definitions
β”‚   └── pyproject.toml     # Rust build & metadata configuration
β”œβ”€β”€ vectorstore/
β”‚   └── db/                # Persistent ChromaDB vector storage files
β”œβ”€β”€ screenshots/           # Screenshots of the Rag App
β”œβ”€β”€ app.py                 # Core Streamlit Web Application interface
β”œβ”€β”€ query.py               # Command-line (CLI) interaction utility
β”œβ”€β”€ ingest.py              # PDF Parsing and Vector Store Ingestion engine
β”œβ”€β”€ guardrail.py           # Semantic Guardrail verification system
β”œβ”€β”€ pyproject.toml         # Python environment dependencies
β”œβ”€β”€ tests/                 # Pytest suite
└── .gitignore             # Git exclusion parameters  

πŸš€ Getting Started

Prerequisites Python 3.10 or higher

A Google Gemini API Key (obtained via Google AI Studio)

Installation & Environment Setup

Clone the repository and move into your project root:

git clone <https://github.com/reory/rag_library_ai>
cd rag_library_ai

Create and activate a virtual environment:

# Windows
uv venv .venv
.venv\Scripts\activate

# macOS / Linux
uv venv .venv
source .venv/bin/activate

Install the project dependencies.

This automatically installs the specialized, pre-compiled fast_chunker Linux/Windows target wheel along with core frameworks:

uv sync

Environment Variables Configuration

  • Create a .env file in the root directory to store your API credentials locally:

Code snippet

  • GOOGLE_API_KEY=your_actual_gemini_api_key_here

Ingesting Documents

Run the ingestion pipeline to compile the high-speed Rust chunks into your persistent vector store:

uv run python ingest.py

πŸ’» Usage

  • Web Interface (Streamlit Dashboard) Launch the responsive, styled dashboard interface locally:
uv run streamlit run app.py

The UI features styled badge elements for core Python libraries, interactive querying, a quick history clear utility, and full audit logs mapping your Guardrail Verification parameters.

Command-Line Interface (CLI)

Run the lightweight terminal interface:

uv run python query.py

πŸ›‘οΈ How the Hallucination Guardrail Works

  • Every response undergoes a real-time verification pipeline before reaching the interface:

  • Extraction & Generation: The system retrieves the top 3 document chunks and prompts Gemini 2.5 Flash to answer using only that context.

  • Semantic Auditing: A local SentenceTransformer maps both the raw context and the AI's response into dense vector arrays.

  • Similarity Check: A Cosine Similarity calculation evaluates factual alignment. If the score drops below 0.60, the response is immediately blocked.

  • Safe Refusal Pass: Standard phrases admitting a lack of context (e.g., "The answer isn't in the context") bypass the math filter with a perfect 1.0 score.

βš™οΈ Parameter Tuning

Adjust the strictness of the filter inside guardrail.py:

class RAGGuardrail:
    def __init__(self, threshold=0.60):
  • Drop to 0.55 if blocking valid text; raise to 0.65+ if hallucinations slip through 😊

πŸ§ͺ Pytest

  • Run the test suite:
python -m pytest

πŸ›£οΈ Roadmap Features

  • High-speed Rust text chunking integration (fast_chunker).
  • Core Streamlit Web UI and CLI query processing pipelines.
  • Semantic Guardrail Verification (Cosine Similarity Verification).
  • Source Citation Display: Document names and source references alongside answers.
  • Conversational Memory Support: Multi-turn discussions using Streamlit session state.
  • Semantic Input Routing: Reject out-of-scope questions before retrieval.
  • Self-Correction Loop: Retry responses when guardrail verification fails.
  • Multi-Document Knowledge Graph: Link related concepts across documents to improve retrieval.

  • Built by Roy Peters 😁 LinkedIn

About

This project is a Retrieval-Augmented Generation (RAG) application designed to act as an intelligent librarian. By indexing technical Python books, it allows users to ask complex questions and receive answers grounded in the specific text of those books, complete with context.

Topics

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages