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.
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:
<table> elements with accurate colspan and rowspan.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).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
data/storage/registry.db): Tracks document metadata, SHA-256 hashes, file types, page counts, and parsing statuses.data/storage/chroma_db): Persists dense vector embeddings under collection guild_knowledge_base.data/storage/bm25_index.pkl): Persists Arabic sparse keyword index.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.
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
Configure API Keys in .env:
ADMIN_API_KEY=your_admin_secret_key
USER_API_KEY=your_user_secret_key
Build and start the container stack:
docker-compose up --build
Access the application:
http://localhost:8000http://localhost:8000/admin/uihttp://localhost:8000/docsClone 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
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.
Ensure Ollama is running:
ollama serve
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.
All ingestion workflows are controlled via the unified main.py entry point:
| Ingestion Command | Target Directory | Description & Purpose | Vision GPU Needed? | DB Reset Default | Key Flags |
|---|---|---|---|---|---|
python main.py ingest-texts | data/texts/ | Ingests raw text knowledge base files (.md, .txt) into ChromaDB + BM25. | โ No | Wipes DB | --no-reset-db--dry-run |
python main.py ingest-markdown | data/output_dir/ | Ingests pre-parsed Markdown documents (*_parsed.md) from output directory. | โ No | Wipes DB | --no-reset-db--dry-run |
python main.py ingest-pdfs | data/pdfs/ | Vision parses un-parsed PDFs in data/pdfs/ using Qwen2.5-VL and embeds chunks into ChromaDB. | Yes | Wipes DB | --no-reset-db--dry-run |
python main.py ingest-all | data/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 |
--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.Protected endpoints require header authentication.
X-API-KeyUSER_API_KEY or ADMIN_API_KEY in .env..env under CORS_ORIGINS.X-API-Key: your_super_secret_user_key_here
Content-Type: application/json
POST /api/chat โ Conversational RAG EndpointExecutes 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
}
POST /api/search โ Raw Hybrid Search EndpointPerforms vector retrieval and cross-encoder reranking directly without invoking the LLM generation stage.
Request Body Example:
{
"query": "ุดุฑูุท ุงูุชูุงุนุฏ ูุงูุชุฃู
ูู ุงูุตุญู",
"top_k": 5
}
GET /api/stats โ System Health & Knowledge Base StatsReturns 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"
}
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
}'
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}")
| Status Code | Reason | Cause | Solution |
|---|---|---|---|
401 Unauthorized | Invalid/Missing Key | Missing or incorrect X-API-Key header | Verify USER_API_KEY or ADMIN_API_KEY in .env |
500 Internal Server Error | Server Error | Missing environment setup or internal error | Check server logs for full traceback |
503 Service Unavailable | LLM Unreachable | Ollama / VLM process is down | Verify ollama serve is active |
The repository features a comprehensive 40+ test automated Pytest suite covering unit components, integration flows, and 13-stage latency profiling.
# 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
| Test Suite | Location | Covered Components | Purpose |
|---|---|---|---|
| Unit Tests | tests/unit/ | QueryPreprocessor, RRFFusion, PriorityReranker, BM25Retriever, DeterministicConfidenceEvaluator, SemanticCache, DocumentRegistry, ResponseGeneratorAgent | Fast, isolated verification of algorithms, normalization, and scoring math without network dependencies. |
| Integration Tests | tests/integration/ | FastAPI routes (/api/chat, /health, /api/admin/reindex), RAGChatbot pipeline | Verifies API HTTP contracts, status codes, and end-to-end multi-representation RAG output. |
| Profiling Benchmarks | tests/profiling/ | PipelineProfiler, DiagnosticAnalyzer | Benchmarks millisecond latency breakdowns across all 13 pipeline stages and tests automated bottleneck detection. |
| Test Fixtures | tests/conftest.py | Shared Pytest fixtures (sample_queries, sample_documents, mock_chroma_db) | Supplies standardized Arabic MSA/dialect and English test data across all test modules. |
| Parameter | Default Value | Purpose |
|---|---|---|
QWEN_EMBEDDING_MODEL_NAME | Alibaba-NLP/gte-Qwen2-1.5B-instruct | Dense vector embedding model |
BGE_RERANKER_MODEL_NAME | BAAI/bge-reranker-v2-m3 | Cross-encoder reranking model |
OLLAMA_CHAT_MODEL | ministral-3:8b | Primary Ollama LLM for conversational responses |
OLLAMA_VISION_MODEL | qwen2.5vl:7b | Ollama VLM for Arabic PDF visual table parsing |
| Feature Module | Legacy Baseline | Current Upgraded System | Status |
|---|---|---|---|
| Retrieval Strategy | Pure Dense Search (ChromaDB) | Hybrid Search (ChromaDB + Arabic BM25 + RRF $k=60$) | Resolved |
| Query Processing | Hardcoded regex rules | LLM Dialect Rewriter (Levantine/Jordanian $\rightarrow$ MSA) | Resolved |
| Multi-Turn Context | Raw text appended | Standalone Query Synthesis before retrieval | Resolved |
| Chunking Architecture | Fixed word-count chunking | Token-accurate Parent-Child Chunking (~800/~150 tokens) | Resolved |
| Orchestration | Single linear script | 4-Stage Modular Pipeline (src/pipeline/) | Resolved |
| Self-Correction | Static threshold | CRAG Verifier + Groundedness Check + Re-retrieval | Resolved |
| Performance / Caching | None | In-Memory & Persisted Cosine Semantic Cache (<10ms) | Resolved |
| Containerization | None | Production Dockerfile & Docker Compose Stack | Resolved |
MIT License. Designed and developed for the 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.
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:
<table> elements with accurate colspan and rowspan.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).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
data/storage/registry.db): Tracks document metadata, SHA-256 hashes, file types, page counts, and parsing statuses.data/storage/chroma_db): Persists dense vector embeddings under collection guild_knowledge_base.data/storage/bm25_index.pkl): Persists Arabic sparse keyword index.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.
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
Configure API Keys in .env:
ADMIN_API_KEY=your_admin_secret_key
USER_API_KEY=your_user_secret_key
Build and start the container stack:
docker-compose up --build
Access the application:
http://localhost:8000http://localhost:8000/admin/uihttp://localhost:8000/docsClone 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
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.
Ensure Ollama is running:
ollama serve
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.
All ingestion workflows are controlled via the unified main.py entry point:
| Ingestion Command | Target Directory | Description & Purpose | Vision GPU Needed? | DB Reset Default | Key Flags |
|---|---|---|---|---|---|
python main.py ingest-texts | data/texts/ | Ingests raw text knowledge base files (.md, .txt) into ChromaDB + BM25. | โ No | Wipes DB | --no-reset-db--dry-run |
python main.py ingest-markdown | data/output_dir/ | Ingests pre-parsed Markdown documents (*_parsed.md) from output directory. | โ No | Wipes DB | --no-reset-db--dry-run |
python main.py ingest-pdfs | data/pdfs/ | Vision parses un-parsed PDFs in data/pdfs/ using Qwen2.5-VL and embeds chunks into ChromaDB. | Yes | Wipes DB | --no-reset-db--dry-run |
python main.py ingest-all | data/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 |
--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.Protected endpoints require header authentication.
X-API-KeyUSER_API_KEY or ADMIN_API_KEY in .env..env under CORS_ORIGINS.X-API-Key: your_super_secret_user_key_here
Content-Type: application/json
POST /api/chat โ Conversational RAG EndpointExecutes 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
}
POST /api/search โ Raw Hybrid Search EndpointPerforms vector retrieval and cross-encoder reranking directly without invoking the LLM generation stage.
Request Body Example:
{
"query": "ุดุฑูุท ุงูุชูุงุนุฏ ูุงูุชุฃู
ูู ุงูุตุญู",
"top_k": 5
}
GET /api/stats โ System Health & Knowledge Base StatsReturns 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"
}
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
}'
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}")
| Status Code | Reason | Cause | Solution |
|---|---|---|---|
401 Unauthorized | Invalid/Missing Key | Missing or incorrect X-API-Key header | Verify USER_API_KEY or ADMIN_API_KEY in .env |
500 Internal Server Error | Server Error | Missing environment setup or internal error | Check server logs for full traceback |
503 Service Unavailable | LLM Unreachable | Ollama / VLM process is down | Verify ollama serve is active |
The repository features a comprehensive 40+ test automated Pytest suite covering unit components, integration flows, and 13-stage latency profiling.
# 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
| Test Suite | Location | Covered Components | Purpose |
|---|---|---|---|
| Unit Tests | tests/unit/ | QueryPreprocessor, RRFFusion, PriorityReranker, BM25Retriever, DeterministicConfidenceEvaluator, SemanticCache, DocumentRegistry, ResponseGeneratorAgent | Fast, isolated verification of algorithms, normalization, and scoring math without network dependencies. |
| Integration Tests | tests/integration/ | FastAPI routes (/api/chat, /health, /api/admin/reindex), RAGChatbot pipeline | Verifies API HTTP contracts, status codes, and end-to-end multi-representation RAG output. |
| Profiling Benchmarks | tests/profiling/ | PipelineProfiler, DiagnosticAnalyzer | Benchmarks millisecond latency breakdowns across all 13 pipeline stages and tests automated bottleneck detection. |
| Test Fixtures | tests/conftest.py | Shared Pytest fixtures (sample_queries, sample_documents, mock_chroma_db) | Supplies standardized Arabic MSA/dialect and English test data across all test modules. |
| Parameter | Default Value | Purpose |
|---|---|---|
QWEN_EMBEDDING_MODEL_NAME | Alibaba-NLP/gte-Qwen2-1.5B-instruct | Dense vector embedding model |
BGE_RERANKER_MODEL_NAME | BAAI/bge-reranker-v2-m3 | Cross-encoder reranking model |
OLLAMA_CHAT_MODEL | ministral-3:8b | Primary Ollama LLM for conversational responses |
OLLAMA_VISION_MODEL | qwen2.5vl:7b | Ollama VLM for Arabic PDF visual table parsing |
| Feature Module | Legacy Baseline | Current Upgraded System | Status |
|---|---|---|---|
| Retrieval Strategy | Pure Dense Search (ChromaDB) | Hybrid Search (ChromaDB + Arabic BM25 + RRF $k=60$) | Resolved |
| Query Processing | Hardcoded regex rules | LLM Dialect Rewriter (Levantine/Jordanian $\rightarrow$ MSA) | Resolved |
| Multi-Turn Context | Raw text appended | Standalone Query Synthesis before retrieval | Resolved |
| Chunking Architecture | Fixed word-count chunking | Token-accurate Parent-Child Chunking (~800/~150 tokens) | Resolved |
| Orchestration | Single linear script | 4-Stage Modular Pipeline (src/pipeline/) | Resolved |
| Self-Correction | Static threshold | CRAG Verifier + Groundedness Check + Re-retrieval | Resolved |
| Performance / Caching | None | In-Memory & Persisted Cosine Semantic Cache (<10ms) | Resolved |
| Containerization | None | Production Dockerfile & Docker Compose Stack | Resolved |
MIT License. Designed and developed for the Jordan Engineers Association (ููุงุจุฉ ุงูู ููุฏุณูู ุงูุฃุฑุฏูููู).