Metadata-Version: 2.5
Name: dj-rag
Version: 2.0.1
Summary: 🎧 DJ's Production RAG Pipeline - PDFs → Pinecone → LLM → RAGAS (Sub-10s E2E)
Project-URL: Homepage, https://github.com/dhanunjairam/DJ_RAG
Project-URL: Documentation, https://github.com/dhanunjairam/DJ_RAG/blob/main/README.md
Project-URL: Repository, https://github.com/dhanunjairam/DJ_RAG/
Author: DJ
License: MIT
Keywords: fastapi,llm,opentelemetry,pdf,phoenix,pinecone,rag,ragas
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.13
Requires-Dist: apscheduler>=3.11.2
Requires-Dist: arize-phoenix>=18.1.0
Requires-Dist: docling>=2.66.0
Requires-Dist: einops>=0.8.1
Requires-Dist: fastapi>=0.128.0
Requires-Dist: gunicorn>=23.0.0
Requires-Dist: langchain-classic>=1.0.1
Requires-Dist: langchain-core>=1.2.6
Requires-Dist: langchain-huggingface>=1.2.0
Requires-Dist: langchain-openai>=1.1.7
Requires-Dist: langchain-text-splitters>=1.1.0
Requires-Dist: langchain>=1.2.2
Requires-Dist: litellm>=1.80.12
Requires-Dist: nest-asyncio>=1.6.0
Requires-Dist: openinference-instrumentation-langchain>=0.1.81
Requires-Dist: openinference-instrumentation-openai>=0.1.69
Requires-Dist: opentelemetry-sdk>=1.45.2
Requires-Dist: pinecone[asyncio]>=8.0.0
Requires-Dist: pydantic-settings>=2.0.0
Requires-Dist: python-multipart>=0.0.21
Requires-Dist: ragas>=0.4.2
Requires-Dist: sentence-transformers>=5.2.0
Requires-Dist: torch>=2.9.1
Requires-Dist: twine>=6.2.0
Requires-Dist: uvicorn>=0.40.0
Provides-Extra: dev
Requires-Dist: black>=23.0.0; extra == 'dev'
Requires-Dist: pytest>=7.4.0; extra == 'dev'
Requires-Dist: ruff>=0.1.0; extra == 'dev'
Description-Content-Type: text/markdown

# 🎧 DJ-Rag-Pipeline

[![FastAPI](https://img.shields.io/badge/FastAPI-0.128%2B-brightgreen.svg)](https://fastapi.tiangolo.com)
[![Python](https://img.shields.io/badge/Python-3.13%2B-blue.svg)](https://python.org)
[![Pinecone](https://img.shields.io/badge/Pinecone-8.0%2B-orange.svg)](https://pinecone.io)
[![Ragas](https://img.shields.io/badge/Ragas-0.4%2B-purple.svg)](https://github.com/explodinggradients/ragas)
[![Arize Phoenix](https://img.shields.io/badge/Phoenix-Observability-red.svg)](https://phoenix.arize.com)
[![UV](https://img.shields.io/badge/UV-0.4%2B-brightgreen)](https://astral.sh/uv)

> **Production RAG Pipeline** — PDFs → Pinecone → LLM → Ragas (**Sub-10s E2E**)

**One-command production RAG API** for **any PDF documents**. Built on **Clean Layered Architecture (SOLID Principles)** with built-in **Arize Phoenix Observability** & OpenInference tracing.

---

## 🚀 Key Features

| Feature | Status | Description |
| :--- | :--- | :--- |
| **Clean SOLID Architecture** | ✅ Layered | Protocol-driven domain, adapters, and services with 100% dependency injection testability. |
| **Phoenix Observability** | 🔭 Built-in UI | Live tracing dashboard at `http://localhost:6006` with OpenInference conventions. |
| **PDF Processing** | ✅ Docling | High-accuracy incremental PDF-to-Markdown conversion. |
| **Smart Chunking** | ✅ 2-Stage | Markdown header splitting + recursive token character splitting. |
| **Pinecone Records API** | ✅ Server-side | Integrated embedding schema, hybrid search, and batch upserting. |
| **Grounded LLM Generation** | ✅ Strict Context | Zero hallucination prompt design with mandatory source citations. |
| **Ragas Quality Evaluation** | 🎯 Automated | 5 metrics (`context_precision`, `recall`, `relevance`, `faithfulness`, `relevancy`) with nested span tracing. |
| **FastAPI + UV** | ⚡ High Performance | Clean modular endpoints with UV package management on Python 3.13. |

---

## 📦 Install & Run (60 seconds)

```bash
# 1. Install
pip install dj-rag

# 2. Create project
dj-rag init my_rag_project

# 3. Setup & run
cd my_rag_project
# Edit .env with your credentials
uv sync
uv run uvicorn main:app --reload --port 8000
```
- **API Swagger Docs:** `http://localhost:8000/docs` 🎉
- **Phoenix Tracing UI:** `http://localhost:6006` 🔥

---

## 🏗️ Project Structure (Clean Layered Architecture)

`dj-rag init` sets up the following SOLID architecture:

```text
my_rag_project/
├── main.py                         # 🚀 FastAPI entrypoint & lifespan management (~75 lines)
├── pyproject.toml
├── env_example.txt
└── src/
    ├── domain/                     # 🏛️ Layer 1: Contracts & Models (Zero external deps)
    │   ├── contracts.py            # Protocols: BaseRetriever, BaseChatbot, BaseEvaluator, BaseDocConverter
    │   └── base_models.py          # Unified DTOs: DocumentChunk, RetrievalResult, PipelineResult
    ├── infrastructure/             # 🔌 Layer 2: Vendor Adapters
    │   ├── vector_stores/          # PineconeRetriever (implements BaseRetriever)
    │   ├── llm/                    # RAGChatbot (implements BaseChatbot)
    │   ├── evaluators/             # RagasEvaluator with OTel spans (implements BaseEvaluator)
    │   └── doc_parsers/            # DoclingPDFConverter (implements BaseDocConverter)
    ├── services/                   # ⚙️ Layer 3: Application Workflows
    │   ├── rag_service.py          # Coordinates Query -> Retrieve -> Generate
    │   ├── ingestion_service.py    # Coordinates PDF Convert -> Chunk -> Batch Upsert
    │   └── check_pincone_index.py  # Pinecone index inspection & chunk statistics
    ├── api/                        # 🌐 Layer 4: HTTP Transport
    │   ├── routes/v1.py            # Route handlers: /chat, /evaluate-ragas, /full-pipeline
    │   └── dependencies.py         # FastAPI dependency injection providers (Depends())
    ├── core/                       # 🧩 Cross-cutting concerns (config.py, tracing.py)
    ├── embeddings/                 # ⚡ Cached global embedding manager
    └── data/                       # 📂 PDF storage (data_source/) and Markdown (markdown_data_sources/)
```

---

## 🔭 Arize Phoenix Observability (`http://localhost:6006`)

Whenever your server starts, an in-process **Arize Phoenix UI** launches automatically:
- **Dashboard URL:** `http://localhost:6006/`
- **Collector Endpoint:** `http://localhost:6006/v1/traces`
- **Tracing Conventions:** OpenInference (`CHAIN`, `LLM`, `EVALUATOR`)
- **Self-Tracing Muted:** Phoenix's internal `/graphql` server polling is suppressed to keep traces and console logs clean.
- **Bulk Ingestion Suppression:** Bulk embedding calls during `/full-pipeline` are muted via `suppress_tracing()` to avoid trace flooding.

### 📊 What You Can Check on the Dashboard

```
┌────────────────────────────────────────────────────────────────────────┐
│  ARIZE PHOENIX DASHBOARD (http://localhost:6006)                       │
├─────────────────┬──────────────────────────────────────────────────────┤
│ 📁 Traces       │ Chronological list of every /chat & /evaluate request│
│ 🔍 Spans        │ Search & filter by kind: LLM, CHAIN, EVALUATOR       │
│ 🎯 Evaluations  │ Quality metrics: Faithfulness, Precision, Recall     │
│ ⚡ Latency & $  │ Token usage, estimated cost, and latency percentiles │
└─────────────────┴──────────────────────────────────────────────────────┘
```

#### Trace Waterfall Breakdown:
- **`/chat` Execution Tree:**
  ```text
  ▼ rag_chat_generation (CHAIN) ─────────────────────────────── [482ms]
      │  ├─ Input: User query + retrieved document contexts
      │  └─ Output: Generated grounded answer
      │
      └─► ChatOpenAI / Groq (LLM) ──────────────────────────── [465ms]
            ├─ Model: openai/gpt-oss-120b | Temperature: 0.1
            ├─ Tokens: Prompt: 1,240 | Completion: 85 | Total: 1,325
            └─ System Prompt: Strict "context-only" instructions
  ```
- **`/evaluate-ragas` Execution Tree:**
  ```text
  ▼ ragas_evaluation (EVALUATOR) ────────────────────────────── [3.1s]
      │  Attributes: eval.context_precision: 1.0 | eval.faithfulness: 0.95 | ...
      │
      ├─► ragas_context_precision (EVALUATOR) ───────────────── [620ms] -> LLM prompt & score
      ├─► ragas_context_recall (EVALUATOR) ──────────────────── [580ms] -> LLM prompt & score
      ├─► ragas_context_relevance (EVALUATOR) ───────────────── [510ms] -> LLM prompt & score
      ├─► ragas_faithfulness (EVALUATOR) ────────────────────── [710ms] -> Hallucination detection
      └─► ragas_answer_relevancy (EVALUATOR) ────────────────── [680ms] -> Answer relevancy
  ```

#### 🛠️ Debugging Workflows:
- **Detecting Hallucinations:** When `faithfulness < 0.90`, expand `ragas_faithfulness` $\rightarrow$ inspect the judge LLM's explanation of ungrounded statements.
- **Verifying Retrieval:** Inspect the `rag_chat_generation` span input to verify chunk rank order.
- **Tracking Costs & Latency:** Monitor token usage, cost estimations, and $p50/p90/p99$ latencies.

---

## 🎯 Upload & Query PDFs (API-First)

### 1. Upload + Index PDFs (One Command)
```bash
curl -X POST "http://localhost:8000/full-pipeline" \
  -F "files=@yoga-guide.pdf" \
  -F "files=@asana-manual.pdf"
```

### 2. Query Instantly!
```bash
curl -X POST "http://localhost:8000/chat" \
  -H "Content-Type: application/json" \
  -d '{"query": "What are the primary benefits of pranayama?", "top_k": 5}'
```

**Response:**
```json
{
  "success": true,
  "data": {
    "answer": "Based on the provided context: Pranayama improves lung capacity and calms the nervous system... [yoga-guide.md | Chunk: 2]",
    "sources": [
      {
        "id": "yoga-guide_2",
        "text": "Pranayama practices improve respiratory stamina...",
        "source": "yoga-guide.md",
        "score": 0.912
      }
    ],
    "retrieval_metrics": {
      "retrieved_count": 5,
      "latency_seconds": 0.234,
      "avg_score": 0.891
    }
  }
}
```

### 3. Evaluate Answer Quality (Ragas)
```bash
curl -X POST "http://localhost:8000/evaluate-ragas" \
  -H "Content-Type: application/json" \
  -d '{
    "question": "What are the primary benefits of pranayama?",
    "answer": "Pranayama improves lung capacity and calms the nervous system.",
    "contexts": ["Pranayama practices improve respiratory stamina and regulate stress."]
  }'
```

---

## 🌐 API Endpoints

| Endpoint | Method | Purpose | Latency |
| :--- | :---: | :--- | :---: |
| `/chat` | `POST` | Core RAG (Retrieve $\rightarrow$ Generate) | ~500ms ⚡ |
| `/full-pipeline` | `POST` | PDFs $\rightarrow$ Markdown $\rightarrow$ Pinecone | ~30s 🏭 |
| `/evaluate-ragas`| `POST` | 5 Ragas Quality Metrics | ~3s 🎯 |
| `/index-status` | `GET` | Vector Store Health & Chunk Counts | ~50ms 📊 |
| `/health` | `GET` | API Status & Version | ~5ms ✅ |

---

## ⚙️ Environment Configuration (`.env`)

```ini
PINECONE_API_KEY=your_pinecone_api_key
INDEX_NAME=your_index_name
PINECONE_INDEX_HOST=https://your-index-host.pinecone.io  # Optional

EMBEDDING_MODEL=nomic-ai/nomic-embed-text-v1.5
MAX_CHUNK_SIZE=1500
CHUNK_OVERLAP=400

LLM_MODEL=openai/gpt-oss-120b
LLM_BASE_URL=https://api.groq.com/openai/v1
LLM_PROVIDER=openai
LLM_MAX_TOKENS=16384
LLM_API_KEY=your_llm_api_key

PHONIEX_PORT=6006
PHONIEX_HOST=0.0.0.0
```

---

## 📈 Production Targets

| Metric | Target | Description |
| :--- | :--- | :--- |
| **Retrieval Latency** | `< 500ms` | Vector search duration in Pinecone |
| **Context Precision** | `> 0.90` | Most relevant chunks prioritized first |
| **Faithfulness** | `> 0.90` | Zero hallucination score against retrieved docs |
| **Answer Relevancy** | `> 0.85` | Response directness to user's question |

---

## 📝 License
Distributed under the **MIT License**.  
Made with ❤️ by **DJ** 🎧
