artiti05/CHATBOT-ENG-GUILD

Python

0

36 commits

updated Sep 27, 2026

See the code

README

๐Ÿ‡ฏ๐Ÿ‡ด Arabic PDF Parser & Hybrid RAG Chatbot System

Jordan Engineers Association (ู†ู‚ุงุจุฉ ุงู„ู…ู‡ู†ุฏุณูŠู† ุงู„ุฃุฑุฏู†ูŠูŠู†)

An end-to-end Arabic PDF Vision Parser, Hybrid RAG (Retrieval-Augmented Generation) Engine, and AI Chatbot System built specifically for the Jordan Engineers Association.

It processes complex Arabic documents, handles reversed Bidi character streams, transcribes multi-header RTL tables using Qwen2.5-VL, embeds document chunks using GTE-Qwen / BAAI BGE-M3, reranks search results via BGE Cross-Encoder, normalizes Jordanian Dialect queries into formal Arabic, and serves a secure FastAPI Web UI, Admin Dashboard, and REST API.


Table of Contents


๐Ÿ’ก What the Project is About

The Jordan Engineers Association manages an extensive collection of legal bylaws, strategic plans, service guides, university admission criteria, and operational news. This system provides an intelligent knowledge base assistant capable of:

  1. Vision-Based Document Parsing: Uses OpenCV CLAHE image enhancement and Qwen2.5-VL (via Ollama) to transcribe Arabic prose and format complex nested RTL tables as HTML <table> elements with accurate colspan and rowspan.
  2. Jordanian Dialect Normalization: Translates colloquial Jordanian phrases (e.g., "ุดูˆ ุงู„ุฃูˆุฑุงู‚", "ุจุฏูŠ ุฃุณุฌู„", "ู‚ุฏูŠุด ุงู„ุฅุดุชุฑุงูƒ") into formal Modern Standard Arabic (MSA) search terms for accurate semantic retrieval.
  3. Hybrid Retrieval & Reranking (Dense + Arabic BM25 + RRF $k=60$): Combines dense vector similarity search in ChromaDB (BGE-M3) with sparse keyword search (Arabic Normalized BM25) fused via Reciprocal Rank Fusion ($k=60$), then reranks results using BAAI/bge-reranker-v2-m3 with a strict 50% quality floor.
  4. Hierarchical Parent-Child Chunking: Indexes granular Child Chunks (~150 tokens) for high-precision retrieval while providing rich Parent Context Blocks (~800 tokens) to the LLM for answer synthesis.
  5. FastAPI Web UI, Admin Dashboard & REST API: Provides an ambient dark-mode web UI (http://localhost:8000), an interactive Admin Dashboard (http://localhost:8000/admin/ui), and secure API endpoints protected by header authentication (ADMIN_API_KEY & USER_API_KEY).
  6. Agentic 4-Stage RAG Pipeline & CRAG Reflexion: Orchestrates intent classification, hybrid retrieval, cross-encoder verification, and response generation with automatic query expansion and self-correction loops when retrieval confidence is low.

๐Ÿ—๏ธ System Architecture & Storage

CHATBOT-ENG-GUILD/
โ”œโ”€โ”€ main.py                     # Unified CLI entry point & Web UI launcher
โ”œโ”€โ”€ Dockerfile                  # Container build file (Python 3.12-slim)
โ”œโ”€โ”€ docker-compose.yml          # Docker Compose orchestration (FastAPI RAG + Ollama)
โ”œโ”€โ”€ .env.example                # Environment template
โ”œโ”€โ”€ requirements.txt            # Python dependencies
โ”‚
โ”œโ”€โ”€ src/                        # Modular RAG Architecture
โ”‚   โ”œโ”€โ”€ api/                    # FastAPI Server & REST API Endpoints
โ”‚   โ”‚   โ”œโ”€โ”€ main.py             # FastAPI App instance & middleware
โ”‚   โ”‚   โ”œโ”€โ”€ routes_chat.py      # Conversational RAG & Search endpoints
โ”‚   โ”‚   โ”œโ”€โ”€ routes_admin.py     # Admin VDB management routes
โ”‚   โ”‚   โ”œโ”€โ”€ routes_admin_ui.py  # Admin HTML UI dashboard
โ”‚   โ”‚   โ””โ”€โ”€ dependencies.py     # API key authentication & security dependencies
โ”‚   โ”œโ”€โ”€ cache_db/               # Storage Registries & Caches
โ”‚   โ”‚   โ”œโ”€โ”€ document_registry.py# SQLite Document Registry (metadata, SHA256 hashes)
โ”‚   โ”‚   โ””โ”€โ”€ semantic_cache.py   # In-Memory/SQLite Cosine Semantic Cache (<10ms)
โ”‚   โ”œโ”€โ”€ core/                   # Global Engine & Configuration
โ”‚   โ”‚   โ”œโ”€โ”€ config.py           # Settings, paths, model names & hyperparameters
โ”‚   โ”‚   โ””โ”€โ”€ rag_engine.py       # Core RAG Coordinator
โ”‚   โ”œโ”€โ”€ monitoring/             # Diagnostics & Profiling
โ”‚   โ”‚   โ”œโ”€โ”€ diagnostic_report.py# System diagnostic generator
โ”‚   โ”‚   โ”œโ”€โ”€ profiler.py         # Latency & memory profiler
โ”‚   โ”‚   โ””โ”€โ”€ tracing.py          # Request tracing utilities
โ”‚   โ”œโ”€โ”€ pipeline/               # 4-Stage Agentic RAG Pipeline
โ”‚   โ”‚   โ”œโ”€โ”€ stage_01_understand/# Arabic/Jordanian Normalization & Intent Classification
โ”‚   โ”‚   โ”œโ”€โ”€ stage_02_retrieve/  # Hybrid Search (Dense + Arabic BM25 + RRF + Ingestion)
โ”‚   โ”‚   โ”œโ”€โ”€ stage_03_verify_rerank/ # BGE Cross-Encoder Reranking & Verification
โ”‚   โ”‚   โ””โ”€โ”€ stage_04_answer/    # Answer Synthesis, Dialect Rewriter & Generator Agents
โ”‚   โ”œโ”€โ”€ services/               # Domain Services
โ”‚   โ”œโ”€โ”€ kb_ingestor/            # Knowledge Base Ingestion & Chunking Inspection
โ”‚   โ”‚   โ”œโ”€โ”€ batch_ingest.py     # Batch Ingestion Manager
โ”‚   โ”‚   โ””โ”€โ”€ inspect_chunking.py # Chunking Inspection Diagnostic Tool
โ”‚   โ””โ”€โ”€ rag_chatbot_engine.py   # RAG Engine Implementation
โ”‚
โ”œโ”€โ”€ data/                       # Knowledge Base & Persistent Storage
โ”‚   โ”œโ”€โ”€ texts/                  # Raw text/markdown KB files (.md, .txt)
โ”‚   โ”œโ”€โ”€ pdfs/                   # Source PDF documents
โ”‚   โ”œโ”€โ”€ markdowns/              # Pre-parsed PDF Markdown files (*_parsed.md)
โ”‚   โ”œโ”€โ”€ output_dir/             # PDF Vision Parser debug artifacts & images
โ”‚   โ””โ”€โ”€ storage/                # ChromaDB vector store, BM25 index & SQLite registry.db
โ”‚
โ””โ”€โ”€ tests/                      # Pytest Unit & Integration Test Suites

Storage Architecture

  • SQLite Registry (data/storage/registry.db): Tracks document metadata, SHA-256 hashes, file types, page counts, and parsing statuses.
  • ChromaDB Store (data/storage/chroma_db): Persists dense vector embeddings under collection guild_knowledge_base.
  • BM25 Store (data/storage/bm25_index.pkl): Persists Arabic sparse keyword index.

๐Ÿš€ Quick Start Guide

Prerequisites

  • Docker & Docker Compose (for Docker setup), OR Python 3.10โ€“3.12 (for local setup).
  • Ollama installed with models pulled:
    ollama pull qwen2.5:7b
    ollama pull qwen2.5vl:7b
    

Docker Compose sets up both the FastAPI RAG Web Server and Ollama in orchestrated containers.

  1. Clone the repository and copy environment configuration:

    git clone https://github.com/artiti05/CHATBOT-ENG-GUILD.git
    cd CHATBOT-ENG-GUILD
    cp .env.example .env
    
  2. Configure API Keys in .env:

    ADMIN_API_KEY=your_admin_secret_key
    USER_API_KEY=your_user_secret_key
    
  3. Build and start the container stack:

    docker-compose up --build
    
  4. Access the application:

    • Web Chatbot UI: http://localhost:8000
    • Admin UI Dashboard: http://localhost:8000/admin/ui
    • API Docs (Swagger): http://localhost:8000/docs

Option B: Running Locally with Python

  1. Clone repository and set up Virtual Environment:

    git clone https://github.com/artiti05/CHATBOT-ENG-GUILD.git
    cd CHATBOT-ENG-GUILD
    
    # Create virtual environment
    python -m venv venv
    
    # Activate virtual environment (Windows PowerShell)
    .\venv\Scripts\Activate.ps1
    # Linux/macOS:
    # source venv/bin/activate
    
    # Install dependencies
    pip install -r requirements.txt
    
  2. Set up Environment Variables:

    Copy-Item .env.example .env
    

    Edit .env to set your API keys (ADMIN_API_KEY, USER_API_KEY) and Ollama settings.

  3. Ensure Ollama is running:

    ollama serve
    
  4. Launch the Web Application & Chatbot UI:

    python main.py
    

    (Or specify a custom port: python main.py serve --port 8000)

    Open your browser at http://localhost:8000.


๐Ÿ“ฅ CLI Ingestion Commands Reference

All ingestion workflows are controlled via the unified main.py entry point:

Ingestion CommandTarget DirectoryDescription & PurposeVision GPU Needed?DB Reset DefaultKey Flags
python main.py ingest-textsdata/texts/Ingests raw text knowledge base files (.md, .txt) into ChromaDB + BM25.โŒ NoWipes DB--no-reset-db
--dry-run
python main.py ingest-markdowndata/output_dir/Ingests pre-parsed Markdown documents (*_parsed.md) from output directory.โŒ NoWipes DB--no-reset-db
--dry-run
python main.py ingest-pdfsdata/pdfs/Vision parses un-parsed PDFs in data/pdfs/ using Qwen2.5-VL and embeds chunks into ChromaDB.YesWipes DB--no-reset-db
--dry-run
python main.py ingest-alldata/texts/
data/output_dir/
data/pdfs/
Full Build: Ingests texts, pre-parsed markdowns, and vision-parses un-parsed source PDFs.(PDFs only)Wipes DB--no-reset-db
--dry-run

Flag Descriptions:

  • --no-reset-db (Append Mode): Appends vectors to the existing ChromaDB collection without wiping previously indexed documents.
  • --dry-run (Preview Mode): Previews file counts and execution plan without modifying database storage.

๐Ÿ” Security & API Integration Guide

1. Authentication & CORS

Protected endpoints require header authentication.

  • Header Name: X-API-Key
  • Configuration: Set via USER_API_KEY or ADMIN_API_KEY in .env.
  • CORS Restrictions: Configured in .env under CORS_ORIGINS.
X-API-Key: your_super_secret_user_key_here
Content-Type: application/json

2. API Endpoints Reference

A. POST /api/chat โ€” Conversational RAG Endpoint

Executes query translation (Jordanian Dialect -> MSA), hybrid dense vector retrieval in ChromaDB, cross-encoder reranking, and local LLM context-augmented generation.

Request Headers:

X-API-Key: <USER_API_KEY>
Content-Type: application/json

Request Body Example:

{
  "query": "ุดูˆ ุงู„ุฃูˆุฑุงู‚ ุงู„ู…ุทู„ูˆุจุฉ ู„ู„ุชุณุฌูŠู„ ุจุงู„ู†ู‚ุงุจุฉุŸ",
  "history": [],
  "top_k": 10
}

Response Body Example:

{
  "query": "ุดูˆ ุงู„ุฃูˆุฑุงู‚ ุงู„ู…ุทู„ูˆุจุฉ ู„ู„ุชุณุฌูŠู„ ุจุงู„ู†ู‚ุงุจุฉุŸ",
  "normalized_query": "ู…ุง ู‡ูŠ ุงู„ูˆุซุงุฆู‚ ูˆุงู„ู…ุณุชู†ุฏุงุช ุงู„ู…ุทู„ูˆุจุฉ ู„ู„ุชุณุฌูŠู„ ูˆุงู„ุงู†ุชุณุงุจ ู„ู†ู‚ุงุจุฉ ุงู„ู…ู‡ู†ุฏุณูŠู†ุŸ",
  "detected_accent": "jordanian",
  "answer": "ู„ู„ุชุณุฌูŠู„ ูˆุงู„ุงู†ุชุณุงุจ ุจู†ู‚ุงุจุฉ ุงู„ู…ู‡ู†ุฏุณูŠู† ุงู„ุฃุฑุฏู†ูŠูŠู†ุŒ ูŠุฌุจ ุชู‚ุฏูŠู… ุงู„ูˆุซุงุฆู‚ ุงู„ุชุงู„ูŠุฉ:\n1. ุตูˆุฑุฉ ู…ุตุฏู‚ุฉ ุนู† ุดู‡ุงุฏุฉ ุงู„ุฏุฑุงุณุฉ ุงู„ุซุงู†ูˆูŠุฉ ุงู„ุนุงู…ุฉ.\n2. ุตูˆุฑุฉ ู…ุตุฏู‚ุฉ ุนู† ู…ุตุฏู‚ุฉ ุงู„ุจูƒุงู„ูˆุฑูŠูˆุณ ูˆุงู„ุดู‡ุงุฏุฉ ุงู„ุฌุงู…ุนูŠุฉ.\n...",
  "sources": [
    {
      "rank": 1,
      "source_id": "text_8f2a1b9c",
      "title": "ุงู„ุงู†ุชุณุงุจ ู„ู„ู†ู‚ุงุจุฉ",
      "text": "ุงู„ูˆุซุงุฆู‚ ุงู„ู…ุทู„ูˆุจุฉ ู„ู„ุงู†ุชุณุงุจ: 1- ุตูˆุฑุฉ ู…ุตุฏู‚ุฉ...",
      "similarity_score": 94
    }
  ],
  "llm_connected": true,
  "time_taken": 6.82
}

B. POST /api/search โ€” Raw Hybrid Search Endpoint

Performs vector retrieval and cross-encoder reranking directly without invoking the LLM generation stage.

Request Body Example:

{
  "query": "ุดุฑูˆุท ุงู„ุชู‚ุงุนุฏ ูˆุงู„ุชุฃู…ูŠู† ุงู„ุตุญูŠ",
  "top_k": 5
}

C. GET /api/stats โ€” System Health & Knowledge Base Stats

Returns operational metrics and counts for registered documents and indexed vector chunks. No authentication header required.

{
  "total_documents": 76,
  "chroma_chunks": 89,
  "collection_name": "guild_knowledge_base"
}

3. Integration Code Examples

cURL Example

curl -X POST "http://localhost:8000/api/chat" \
     -H "Content-Type: application/json" \
     -H "X-API-Key: your_super_secret_user_key_here" \
     -d '{
           "query": "ูƒูŠู ุจู‚ุฏุฑ ุงุดุชุฑูƒ ุจุงู„ุชุฃู…ูŠู† ุงู„ุตุญูŠุŸ",
           "top_k": 5
         }'

Python Integration Example

import requests

API_URL = "http://localhost:8000/api/chat"
API_KEY = "your_super_secret_user_key_here"

payload = {
    "query": "ุดูˆ ุงู„ุฃูˆุฑุงู‚ ุงู„ู…ุทู„ูˆุจุฉ ู„ู„ุงู†ุชุณุงุจุŸ",
    "history": [],
    "top_k": 5
}

headers = {
    "Content-Type": "application/json",
    "X-API-Key": API_KEY
}

try:
    response = requests.post(API_URL, json=payload, headers=headers, timeout=90)
    response.raise_for_status()
    data = response.json()

    print(f"Dialect Detected: {data['detected_accent']}")
    print(f"Normalized Query: {data['normalized_query']}")
    print(f"\nAnswer:\n{data['answer']}")
    print(f"\nTop Source: {data['sources'][0]['title']} ({data['sources'][0]['similarity_score']}% match)")

except requests.exceptions.RequestException as e:
    print(f"API Integration Error: {e}")

4. Error Handling & Best Practices

Status CodeReasonCauseSolution
401 UnauthorizedInvalid/Missing KeyMissing or incorrect X-API-Key headerVerify USER_API_KEY or ADMIN_API_KEY in .env
500 Internal Server ErrorServer ErrorMissing environment setup or internal errorCheck server logs for full traceback
503 Service UnavailableLLM UnreachableOllama / VLM process is downVerify ollama serve is active

๐Ÿงช Testing & Verification

The repository features a comprehensive 40+ test automated Pytest suite covering unit components, integration flows, and 13-stage latency profiling.

1. Running Test Suites

# Run all unit and integration tests
pytest -m "unit or integration"

# Run unit tests only (Stage 1-4 modular component tests)
pytest tests/unit

# Run integration tests only (API endpoints & end-to-end RAG engine)
pytest tests/integration

# Run 13-stage latency profiling & bottleneck diagnostic benchmarks
pytest tests/profiling

2. Test Architecture Breakdown

Test SuiteLocationCovered ComponentsPurpose
Unit Teststests/unit/QueryPreprocessor, RRFFusion, PriorityReranker, BM25Retriever, DeterministicConfidenceEvaluator, SemanticCache, DocumentRegistry, ResponseGeneratorAgentFast, isolated verification of algorithms, normalization, and scoring math without network dependencies.
Integration Teststests/integration/FastAPI routes (/api/chat, /health, /api/admin/reindex), RAGChatbot pipelineVerifies API HTTP contracts, status codes, and end-to-end multi-representation RAG output.
Profiling Benchmarkstests/profiling/PipelineProfiler, DiagnosticAnalyzerBenchmarks millisecond latency breakdowns across all 13 pipeline stages and tests automated bottleneck detection.
Test Fixturestests/conftest.pyShared Pytest fixtures (sample_queries, sample_documents, mock_chroma_db)Supplies standardized Arabic MSA/dialect and English test data across all test modules.

โš™๏ธ Configuration Reference

ParameterDefault ValuePurpose
QWEN_EMBEDDING_MODEL_NAMEAlibaba-NLP/gte-Qwen2-1.5B-instructDense vector embedding model
BGE_RERANKER_MODEL_NAMEBAAI/bge-reranker-v2-m3Cross-encoder reranking model
OLLAMA_CHAT_MODELministral-3:8bPrimary Ollama LLM for conversational responses
OLLAMA_VISION_MODELqwen2.5vl:7bOllama VLM for Arabic PDF visual table parsing

๐Ÿ“Š Master Feature Comparison Matrix

Feature ModuleLegacy BaselineCurrent Upgraded SystemStatus
Retrieval StrategyPure Dense Search (ChromaDB)Hybrid Search (ChromaDB + Arabic BM25 + RRF $k=60$)Resolved
Query ProcessingHardcoded regex rulesLLM Dialect Rewriter (Levantine/Jordanian $\rightarrow$ MSA)Resolved
Multi-Turn ContextRaw text appendedStandalone Query Synthesis before retrievalResolved
Chunking ArchitectureFixed word-count chunkingToken-accurate Parent-Child Chunking (~800/~150 tokens)Resolved
OrchestrationSingle linear script4-Stage Modular Pipeline (src/pipeline/)Resolved
Self-CorrectionStatic thresholdCRAG Verifier + Groundedness Check + Re-retrievalResolved
Performance / CachingNoneIn-Memory & Persisted Cosine Semantic Cache (<10ms)Resolved
ContainerizationNoneProduction Dockerfile & Docker Compose StackResolved

๐Ÿ“œ License

MIT License. Designed and developed for the Jordan Engineers Association (ู†ู‚ุงุจุฉ ุงู„ู…ู‡ู†ุฏุณูŠู† ุงู„ุฃุฑุฏู†ูŠูŠู†).

artiti05/CHATBOT-ENG-GUILD

Python

0

36 commits

updated Sep 27, 2026

See the code

README

๐Ÿ‡ฏ๐Ÿ‡ด Arabic PDF Parser & Hybrid RAG Chatbot System

Jordan Engineers Association (ู†ู‚ุงุจุฉ ุงู„ู…ู‡ู†ุฏุณูŠู† ุงู„ุฃุฑุฏู†ูŠูŠู†)

An end-to-end Arabic PDF Vision Parser, Hybrid RAG (Retrieval-Augmented Generation) Engine, and AI Chatbot System built specifically for the Jordan Engineers Association.

It processes complex Arabic documents, handles reversed Bidi character streams, transcribes multi-header RTL tables using Qwen2.5-VL, embeds document chunks using GTE-Qwen / BAAI BGE-M3, reranks search results via BGE Cross-Encoder, normalizes Jordanian Dialect queries into formal Arabic, and serves a secure FastAPI Web UI, Admin Dashboard, and REST API.


Table of Contents


๐Ÿ’ก What the Project is About

The Jordan Engineers Association manages an extensive collection of legal bylaws, strategic plans, service guides, university admission criteria, and operational news. This system provides an intelligent knowledge base assistant capable of:

  1. Vision-Based Document Parsing: Uses OpenCV CLAHE image enhancement and Qwen2.5-VL (via Ollama) to transcribe Arabic prose and format complex nested RTL tables as HTML <table> elements with accurate colspan and rowspan.
  2. Jordanian Dialect Normalization: Translates colloquial Jordanian phrases (e.g., "ุดูˆ ุงู„ุฃูˆุฑุงู‚", "ุจุฏูŠ ุฃุณุฌู„", "ู‚ุฏูŠุด ุงู„ุฅุดุชุฑุงูƒ") into formal Modern Standard Arabic (MSA) search terms for accurate semantic retrieval.
  3. Hybrid Retrieval & Reranking (Dense + Arabic BM25 + RRF $k=60$): Combines dense vector similarity search in ChromaDB (BGE-M3) with sparse keyword search (Arabic Normalized BM25) fused via Reciprocal Rank Fusion ($k=60$), then reranks results using BAAI/bge-reranker-v2-m3 with a strict 50% quality floor.
  4. Hierarchical Parent-Child Chunking: Indexes granular Child Chunks (~150 tokens) for high-precision retrieval while providing rich Parent Context Blocks (~800 tokens) to the LLM for answer synthesis.
  5. FastAPI Web UI, Admin Dashboard & REST API: Provides an ambient dark-mode web UI (http://localhost:8000), an interactive Admin Dashboard (http://localhost:8000/admin/ui), and secure API endpoints protected by header authentication (ADMIN_API_KEY & USER_API_KEY).
  6. Agentic 4-Stage RAG Pipeline & CRAG Reflexion: Orchestrates intent classification, hybrid retrieval, cross-encoder verification, and response generation with automatic query expansion and self-correction loops when retrieval confidence is low.

๐Ÿ—๏ธ System Architecture & Storage

CHATBOT-ENG-GUILD/
โ”œโ”€โ”€ main.py                     # Unified CLI entry point & Web UI launcher
โ”œโ”€โ”€ Dockerfile                  # Container build file (Python 3.12-slim)
โ”œโ”€โ”€ docker-compose.yml          # Docker Compose orchestration (FastAPI RAG + Ollama)
โ”œโ”€โ”€ .env.example                # Environment template
โ”œโ”€โ”€ requirements.txt            # Python dependencies
โ”‚
โ”œโ”€โ”€ src/                        # Modular RAG Architecture
โ”‚   โ”œโ”€โ”€ api/                    # FastAPI Server & REST API Endpoints
โ”‚   โ”‚   โ”œโ”€โ”€ main.py             # FastAPI App instance & middleware
โ”‚   โ”‚   โ”œโ”€โ”€ routes_chat.py      # Conversational RAG & Search endpoints
โ”‚   โ”‚   โ”œโ”€โ”€ routes_admin.py     # Admin VDB management routes
โ”‚   โ”‚   โ”œโ”€โ”€ routes_admin_ui.py  # Admin HTML UI dashboard
โ”‚   โ”‚   โ””โ”€โ”€ dependencies.py     # API key authentication & security dependencies
โ”‚   โ”œโ”€โ”€ cache_db/               # Storage Registries & Caches
โ”‚   โ”‚   โ”œโ”€โ”€ document_registry.py# SQLite Document Registry (metadata, SHA256 hashes)
โ”‚   โ”‚   โ””โ”€โ”€ semantic_cache.py   # In-Memory/SQLite Cosine Semantic Cache (<10ms)
โ”‚   โ”œโ”€โ”€ core/                   # Global Engine & Configuration
โ”‚   โ”‚   โ”œโ”€โ”€ config.py           # Settings, paths, model names & hyperparameters
โ”‚   โ”‚   โ””โ”€โ”€ rag_engine.py       # Core RAG Coordinator
โ”‚   โ”œโ”€โ”€ monitoring/             # Diagnostics & Profiling
โ”‚   โ”‚   โ”œโ”€โ”€ diagnostic_report.py# System diagnostic generator
โ”‚   โ”‚   โ”œโ”€โ”€ profiler.py         # Latency & memory profiler
โ”‚   โ”‚   โ””โ”€โ”€ tracing.py          # Request tracing utilities
โ”‚   โ”œโ”€โ”€ pipeline/               # 4-Stage Agentic RAG Pipeline
โ”‚   โ”‚   โ”œโ”€โ”€ stage_01_understand/# Arabic/Jordanian Normalization & Intent Classification
โ”‚   โ”‚   โ”œโ”€โ”€ stage_02_retrieve/  # Hybrid Search (Dense + Arabic BM25 + RRF + Ingestion)
โ”‚   โ”‚   โ”œโ”€โ”€ stage_03_verify_rerank/ # BGE Cross-Encoder Reranking & Verification
โ”‚   โ”‚   โ””โ”€โ”€ stage_04_answer/    # Answer Synthesis, Dialect Rewriter & Generator Agents
โ”‚   โ”œโ”€โ”€ services/               # Domain Services
โ”‚   โ”œโ”€โ”€ kb_ingestor/            # Knowledge Base Ingestion & Chunking Inspection
โ”‚   โ”‚   โ”œโ”€โ”€ batch_ingest.py     # Batch Ingestion Manager
โ”‚   โ”‚   โ””โ”€โ”€ inspect_chunking.py # Chunking Inspection Diagnostic Tool
โ”‚   โ””โ”€โ”€ rag_chatbot_engine.py   # RAG Engine Implementation
โ”‚
โ”œโ”€โ”€ data/                       # Knowledge Base & Persistent Storage
โ”‚   โ”œโ”€โ”€ texts/                  # Raw text/markdown KB files (.md, .txt)
โ”‚   โ”œโ”€โ”€ pdfs/                   # Source PDF documents
โ”‚   โ”œโ”€โ”€ markdowns/              # Pre-parsed PDF Markdown files (*_parsed.md)
โ”‚   โ”œโ”€โ”€ output_dir/             # PDF Vision Parser debug artifacts & images
โ”‚   โ””โ”€โ”€ storage/                # ChromaDB vector store, BM25 index & SQLite registry.db
โ”‚
โ””โ”€โ”€ tests/                      # Pytest Unit & Integration Test Suites

Storage Architecture

  • SQLite Registry (data/storage/registry.db): Tracks document metadata, SHA-256 hashes, file types, page counts, and parsing statuses.
  • ChromaDB Store (data/storage/chroma_db): Persists dense vector embeddings under collection guild_knowledge_base.
  • BM25 Store (data/storage/bm25_index.pkl): Persists Arabic sparse keyword index.

๐Ÿš€ Quick Start Guide

Prerequisites

  • Docker & Docker Compose (for Docker setup), OR Python 3.10โ€“3.12 (for local setup).
  • Ollama installed with models pulled:
    ollama pull qwen2.5:7b
    ollama pull qwen2.5vl:7b
    

Docker Compose sets up both the FastAPI RAG Web Server and Ollama in orchestrated containers.

  1. Clone the repository and copy environment configuration:

    git clone https://github.com/artiti05/CHATBOT-ENG-GUILD.git
    cd CHATBOT-ENG-GUILD
    cp .env.example .env
    
  2. Configure API Keys in .env:

    ADMIN_API_KEY=your_admin_secret_key
    USER_API_KEY=your_user_secret_key
    
  3. Build and start the container stack:

    docker-compose up --build
    
  4. Access the application:

    • Web Chatbot UI: http://localhost:8000
    • Admin UI Dashboard: http://localhost:8000/admin/ui
    • API Docs (Swagger): http://localhost:8000/docs

Option B: Running Locally with Python

  1. Clone repository and set up Virtual Environment:

    git clone https://github.com/artiti05/CHATBOT-ENG-GUILD.git
    cd CHATBOT-ENG-GUILD
    
    # Create virtual environment
    python -m venv venv
    
    # Activate virtual environment (Windows PowerShell)
    .\venv\Scripts\Activate.ps1
    # Linux/macOS:
    # source venv/bin/activate
    
    # Install dependencies
    pip install -r requirements.txt
    
  2. Set up Environment Variables:

    Copy-Item .env.example .env
    

    Edit .env to set your API keys (ADMIN_API_KEY, USER_API_KEY) and Ollama settings.

  3. Ensure Ollama is running:

    ollama serve
    
  4. Launch the Web Application & Chatbot UI:

    python main.py
    

    (Or specify a custom port: python main.py serve --port 8000)

    Open your browser at http://localhost:8000.


๐Ÿ“ฅ CLI Ingestion Commands Reference

All ingestion workflows are controlled via the unified main.py entry point:

Ingestion CommandTarget DirectoryDescription & PurposeVision GPU Needed?DB Reset DefaultKey Flags
python main.py ingest-textsdata/texts/Ingests raw text knowledge base files (.md, .txt) into ChromaDB + BM25.โŒ NoWipes DB--no-reset-db
--dry-run
python main.py ingest-markdowndata/output_dir/Ingests pre-parsed Markdown documents (*_parsed.md) from output directory.โŒ NoWipes DB--no-reset-db
--dry-run
python main.py ingest-pdfsdata/pdfs/Vision parses un-parsed PDFs in data/pdfs/ using Qwen2.5-VL and embeds chunks into ChromaDB.YesWipes DB--no-reset-db
--dry-run
python main.py ingest-alldata/texts/
data/output_dir/
data/pdfs/
Full Build: Ingests texts, pre-parsed markdowns, and vision-parses un-parsed source PDFs.(PDFs only)Wipes DB--no-reset-db
--dry-run

Flag Descriptions:

  • --no-reset-db (Append Mode): Appends vectors to the existing ChromaDB collection without wiping previously indexed documents.
  • --dry-run (Preview Mode): Previews file counts and execution plan without modifying database storage.

๐Ÿ” Security & API Integration Guide

1. Authentication & CORS

Protected endpoints require header authentication.

  • Header Name: X-API-Key
  • Configuration: Set via USER_API_KEY or ADMIN_API_KEY in .env.
  • CORS Restrictions: Configured in .env under CORS_ORIGINS.
X-API-Key: your_super_secret_user_key_here
Content-Type: application/json

2. API Endpoints Reference

A. POST /api/chat โ€” Conversational RAG Endpoint

Executes query translation (Jordanian Dialect -> MSA), hybrid dense vector retrieval in ChromaDB, cross-encoder reranking, and local LLM context-augmented generation.

Request Headers:

X-API-Key: <USER_API_KEY>
Content-Type: application/json

Request Body Example:

{
  "query": "ุดูˆ ุงู„ุฃูˆุฑุงู‚ ุงู„ู…ุทู„ูˆุจุฉ ู„ู„ุชุณุฌูŠู„ ุจุงู„ู†ู‚ุงุจุฉุŸ",
  "history": [],
  "top_k": 10
}

Response Body Example:

{
  "query": "ุดูˆ ุงู„ุฃูˆุฑุงู‚ ุงู„ู…ุทู„ูˆุจุฉ ู„ู„ุชุณุฌูŠู„ ุจุงู„ู†ู‚ุงุจุฉุŸ",
  "normalized_query": "ู…ุง ู‡ูŠ ุงู„ูˆุซุงุฆู‚ ูˆุงู„ู…ุณุชู†ุฏุงุช ุงู„ู…ุทู„ูˆุจุฉ ู„ู„ุชุณุฌูŠู„ ูˆุงู„ุงู†ุชุณุงุจ ู„ู†ู‚ุงุจุฉ ุงู„ู…ู‡ู†ุฏุณูŠู†ุŸ",
  "detected_accent": "jordanian",
  "answer": "ู„ู„ุชุณุฌูŠู„ ูˆุงู„ุงู†ุชุณุงุจ ุจู†ู‚ุงุจุฉ ุงู„ู…ู‡ู†ุฏุณูŠู† ุงู„ุฃุฑุฏู†ูŠูŠู†ุŒ ูŠุฌุจ ุชู‚ุฏูŠู… ุงู„ูˆุซุงุฆู‚ ุงู„ุชุงู„ูŠุฉ:\n1. ุตูˆุฑุฉ ู…ุตุฏู‚ุฉ ุนู† ุดู‡ุงุฏุฉ ุงู„ุฏุฑุงุณุฉ ุงู„ุซุงู†ูˆูŠุฉ ุงู„ุนุงู…ุฉ.\n2. ุตูˆุฑุฉ ู…ุตุฏู‚ุฉ ุนู† ู…ุตุฏู‚ุฉ ุงู„ุจูƒุงู„ูˆุฑูŠูˆุณ ูˆุงู„ุดู‡ุงุฏุฉ ุงู„ุฌุงู…ุนูŠุฉ.\n...",
  "sources": [
    {
      "rank": 1,
      "source_id": "text_8f2a1b9c",
      "title": "ุงู„ุงู†ุชุณุงุจ ู„ู„ู†ู‚ุงุจุฉ",
      "text": "ุงู„ูˆุซุงุฆู‚ ุงู„ู…ุทู„ูˆุจุฉ ู„ู„ุงู†ุชุณุงุจ: 1- ุตูˆุฑุฉ ู…ุตุฏู‚ุฉ...",
      "similarity_score": 94
    }
  ],
  "llm_connected": true,
  "time_taken": 6.82
}

B. POST /api/search โ€” Raw Hybrid Search Endpoint

Performs vector retrieval and cross-encoder reranking directly without invoking the LLM generation stage.

Request Body Example:

{
  "query": "ุดุฑูˆุท ุงู„ุชู‚ุงุนุฏ ูˆุงู„ุชุฃู…ูŠู† ุงู„ุตุญูŠ",
  "top_k": 5
}

C. GET /api/stats โ€” System Health & Knowledge Base Stats

Returns operational metrics and counts for registered documents and indexed vector chunks. No authentication header required.

{
  "total_documents": 76,
  "chroma_chunks": 89,
  "collection_name": "guild_knowledge_base"
}

3. Integration Code Examples

cURL Example

curl -X POST "http://localhost:8000/api/chat" \
     -H "Content-Type: application/json" \
     -H "X-API-Key: your_super_secret_user_key_here" \
     -d '{
           "query": "ูƒูŠู ุจู‚ุฏุฑ ุงุดุชุฑูƒ ุจุงู„ุชุฃู…ูŠู† ุงู„ุตุญูŠุŸ",
           "top_k": 5
         }'

Python Integration Example

import requests

API_URL = "http://localhost:8000/api/chat"
API_KEY = "your_super_secret_user_key_here"

payload = {
    "query": "ุดูˆ ุงู„ุฃูˆุฑุงู‚ ุงู„ู…ุทู„ูˆุจุฉ ู„ู„ุงู†ุชุณุงุจุŸ",
    "history": [],
    "top_k": 5
}

headers = {
    "Content-Type": "application/json",
    "X-API-Key": API_KEY
}

try:
    response = requests.post(API_URL, json=payload, headers=headers, timeout=90)
    response.raise_for_status()
    data = response.json()

    print(f"Dialect Detected: {data['detected_accent']}")
    print(f"Normalized Query: {data['normalized_query']}")
    print(f"\nAnswer:\n{data['answer']}")
    print(f"\nTop Source: {data['sources'][0]['title']} ({data['sources'][0]['similarity_score']}% match)")

except requests.exceptions.RequestException as e:
    print(f"API Integration Error: {e}")

4. Error Handling & Best Practices

Status CodeReasonCauseSolution
401 UnauthorizedInvalid/Missing KeyMissing or incorrect X-API-Key headerVerify USER_API_KEY or ADMIN_API_KEY in .env
500 Internal Server ErrorServer ErrorMissing environment setup or internal errorCheck server logs for full traceback
503 Service UnavailableLLM UnreachableOllama / VLM process is downVerify ollama serve is active

๐Ÿงช Testing & Verification

The repository features a comprehensive 40+ test automated Pytest suite covering unit components, integration flows, and 13-stage latency profiling.

1. Running Test Suites

# Run all unit and integration tests
pytest -m "unit or integration"

# Run unit tests only (Stage 1-4 modular component tests)
pytest tests/unit

# Run integration tests only (API endpoints & end-to-end RAG engine)
pytest tests/integration

# Run 13-stage latency profiling & bottleneck diagnostic benchmarks
pytest tests/profiling

2. Test Architecture Breakdown

Test SuiteLocationCovered ComponentsPurpose
Unit Teststests/unit/QueryPreprocessor, RRFFusion, PriorityReranker, BM25Retriever, DeterministicConfidenceEvaluator, SemanticCache, DocumentRegistry, ResponseGeneratorAgentFast, isolated verification of algorithms, normalization, and scoring math without network dependencies.
Integration Teststests/integration/FastAPI routes (/api/chat, /health, /api/admin/reindex), RAGChatbot pipelineVerifies API HTTP contracts, status codes, and end-to-end multi-representation RAG output.
Profiling Benchmarkstests/profiling/PipelineProfiler, DiagnosticAnalyzerBenchmarks millisecond latency breakdowns across all 13 pipeline stages and tests automated bottleneck detection.
Test Fixturestests/conftest.pyShared Pytest fixtures (sample_queries, sample_documents, mock_chroma_db)Supplies standardized Arabic MSA/dialect and English test data across all test modules.

โš™๏ธ Configuration Reference

ParameterDefault ValuePurpose
QWEN_EMBEDDING_MODEL_NAMEAlibaba-NLP/gte-Qwen2-1.5B-instructDense vector embedding model
BGE_RERANKER_MODEL_NAMEBAAI/bge-reranker-v2-m3Cross-encoder reranking model
OLLAMA_CHAT_MODELministral-3:8bPrimary Ollama LLM for conversational responses
OLLAMA_VISION_MODELqwen2.5vl:7bOllama VLM for Arabic PDF visual table parsing

๐Ÿ“Š Master Feature Comparison Matrix

Feature ModuleLegacy BaselineCurrent Upgraded SystemStatus
Retrieval StrategyPure Dense Search (ChromaDB)Hybrid Search (ChromaDB + Arabic BM25 + RRF $k=60$)Resolved
Query ProcessingHardcoded regex rulesLLM Dialect Rewriter (Levantine/Jordanian $\rightarrow$ MSA)Resolved
Multi-Turn ContextRaw text appendedStandalone Query Synthesis before retrievalResolved
Chunking ArchitectureFixed word-count chunkingToken-accurate Parent-Child Chunking (~800/~150 tokens)Resolved
OrchestrationSingle linear script4-Stage Modular Pipeline (src/pipeline/)Resolved
Self-CorrectionStatic thresholdCRAG Verifier + Groundedness Check + Re-retrievalResolved
Performance / CachingNoneIn-Memory & Persisted Cosine Semantic Cache (<10ms)Resolved
ContainerizationNoneProduction Dockerfile & Docker Compose StackResolved

๐Ÿ“œ License

MIT License. Designed and developed for the Jordan Engineers Association (ู†ู‚ุงุจุฉ ุงู„ู…ู‡ู†ุฏุณูŠู† ุงู„ุฃุฑุฏู†ูŠูŠู†).