Metadata-Version: 2.4
Name: polyrag
Version: 0.2.0
Summary: A modular, multi-paradigm Retrieval-Augmented Generation (RAG) framework supporting Vector, Agentic, and Graph RAG architectures.
Author-email: Nguyen Viet Ky Quan <nguyenvietkyquan2022@gmail.com>
Maintainer-email: Nguyen Viet Ky Quan <nguyenvietkyquan2022@gmail.com>
License-Expression: MIT
Project-URL: Homepage, https://github.com/NVKQ2022/PolyRAG
Project-URL: Repository, https://github.com/NVKQ2022/PolyRAG
Project-URL: Bug Tracker, https://github.com/NVKQ2022/PolyRAG/issues
Project-URL: Documentation, https://github.com/NVKQ2022/PolyRAG#readme
Keywords: rag,polyrag,agentic-rag,graphrag,vector-search,embeddings,react,llm
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Operating System :: OS Independent
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: pydantic>=2.0.0
Requires-Dist: langchain-core>=0.2.0
Requires-Dist: langchain-text-splitters>=0.2.0
Provides-Extra: openai
Requires-Dist: langchain-openai>=0.1.0; extra == "openai"
Provides-Extra: chroma
Requires-Dist: langchain-chroma>=0.1.0; extra == "chroma"
Provides-Extra: milvus
Requires-Dist: langchain-milvus>=0.1.0; extra == "milvus"
Provides-Extra: huggingface
Requires-Dist: langchain-huggingface>=0.1.0; extra == "huggingface"
Provides-Extra: community
Requires-Dist: langchain-community>=0.2.0; extra == "community"
Provides-Extra: embeddings
Requires-Dist: sentence-transformers>=2.2.0; extra == "embeddings"
Provides-Extra: all
Requires-Dist: langchain-openai>=0.1.0; extra == "all"
Requires-Dist: langchain-chroma>=0.1.0; extra == "all"
Requires-Dist: langchain-milvus>=0.1.0; extra == "all"
Requires-Dist: langchain-community>=0.2.0; extra == "all"
Requires-Dist: langgraph>=0.1.0; extra == "all"
Requires-Dist: fastapi>=0.100.0; extra == "all"
Requires-Dist: uvicorn>=0.20.0; extra == "all"
Provides-Extra: dev
Requires-Dist: pytest>=7.0.0; extra == "dev"
Requires-Dist: build>=1.0.0; extra == "dev"
Requires-Dist: twine>=4.0.0; extra == "dev"
Dynamic: license-file

# PolyRAG 🧬

[![PyPI Version](https://img.shields.io/pypi/v/polyrag.svg)](https://pypi.org/project/polyrag/)
[![Python Version](https://img.shields.io/badge/python-3.10%20%7C%203.11%20%7C%203.12-blue)](https://pypi.org/project/polyrag/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

**PolyRAG** is a modular, multi-paradigm Retrieval-Augmented Generation (RAG) framework designed to unify multiple RAG architectures—from standard **Naive 1-Shot RAG** and **Advanced Multi-Query RAG**, to autonomous **Agentic RAG** and future expansions like **GraphRAG**.

---

## 🏛️ The RAG Class Hierarchy

PolyRAG is architected around an object-oriented class hierarchy rooted in `BaseRAG`:

```
                       ┌─────────────────────────┐
                       │         BaseRAG         │
                       │  (Abstract Base Class)  │
                       └────────────┬────────────┘
                                    │
         ┌──────────────────────────┼──────────────────────────┐
         ▼                          ▼                          ▼
  ┌──────────────┐           ┌──────────────┐           ┌──────────────┐
  │   NaiveRAG   │           │ AdvancedRAG  │           │  AgenticRAG  │
  │ (1-Shot RAG) │           │ (Expand/RRF) │           │ (Reflection) │
  └──────────────┘           └──────────────┘           └──────┬───────┘
                                                               │
                                                               ▼
                                                        ┌──────────────┐
                                                        │  ReActAgent  │
                                                        │ (ReActRAG)   │
                                                        └──────────────┘
```

All derived pipelines inherit shared document ingestion (`ingest_text`, `ingest_file`, `ingest_directory`), vector search (`retrieve`), and context assembly (`format_context`) from `BaseRAG`.

---

## 🌟 Key Features

- **Multi-Paradigm Pipelines**:
  - `NaiveRAG`: Standard retrieve-then-read pipeline with minimal latency.
  - `AdvancedRAG`: Multi-query expansion, parallel search, and Reciprocal Rank Fusion (RRF) re-ranking.
  - `AgenticRAG`: Planning, keyword rewriting, iterative multi-round search, deduplication, and fused self-reflection with source citations.
  - `ReActAgent`: Structured Thought-Action-Observation reasoning loop with dynamic tool execution.
  - *Coming Soon*: `GraphRAG` (knowledge graph entity extraction, community detection, and summarization).

- **Native LangChain Foundation**:
  - Built directly on top of `langchain-core` and `langchain-text-splitters` primitives.
  - Zero-wrapper pluggability: pass ANY LangChain `VectorStore` (Chroma, Milvus, Pinecone, FAISS, PGVector), `Embeddings` (OpenAI, HuggingFace, Ollama, Cohere), `BaseChatModel` (`ChatOpenAI`, `ChatAnthropic`, `ChatGoogleGenerativeAI`, `ChatOllama`), or `TextSplitter` directly into PolyRAG pipelines.
  - Full bidirectional compatibility: PolyRAG components can be used anywhere a LangChain runnable or component is expected.

- **Dependency Injection**:
  - Built-in `Container` acting as the Composition Root for all services, adapters, and pipelines.
  - Seamless DI resolution and alias mapping for both PolyRAG and LangChain types (`VectorStore`, `Embeddings`, `BaseChatModel`, `TextSplitter`).
  - Full support for Singleton and Transient scopes, lifecycle management, and 1-line test mocking.

- **Clean & Swappable Components**:
  - **Vector Stores**: Built-in `InMemoryVectorStore` (zero-dependency cosine/L2/dot similarity) or any LangChain `VectorStore` (`Chroma`, `Milvus`, `FAISS`, `Pinecone`, `PGVector`, `Qdrant`).
  - **Chunkers**: `FixedSizeChunker`, `RecursiveCharacterChunker` (subclassing LangChain's `TextSplitter`).
  - **Embeddings**: Built-in `FakeEmbeddings` for zero-setup local dev or any LangChain `Embeddings` (`OpenAIEmbeddings`, `HuggingFaceEmbeddings`, `OllamaEmbeddings`, `CohereEmbeddings`).
  - **Chat Models**: Standard LangChain `BaseChatModel` and `ChatOpenAI` (supporting OpenAI, Anthropic, Gemini, Ollama, Azure, and vLLM).

---

## 📚 Documentation

Comprehensive documentation is available in the [`docs/`](docs/) directory:

- **[Getting Started](docs/getting-started/)**: [Installation](docs/getting-started/installation.md) & [Quickstart](docs/getting-started/quickstart.md)
- **[Configuration](docs/configuration/)**: [Environment Variables](docs/configuration/environment.md), [Custom Pipelines](docs/configuration/custom-pipeline.md), & [Dependency Injection Guide](docs/configuration/dependency-injection.md)
- **[Guides](docs/guides/)**: [Class Hierarchy](docs/guides/class-hierarchy.md), [Naive RAG](docs/guides/naive-rag.md), [Advanced RAG](docs/guides/advanced-rag.md), [Agentic RAG](docs/guides/agentic-rag.md), & [ReAct Agent](docs/guides/react-agent.md)
- **[Modules](docs/modules/)**: [Vector Stores](docs/modules/vector-stores.md), [Embeddings](docs/modules/embeddings.md), [LLMs](docs/modules/llms.md), [Chunkers](docs/modules/chunkers.md), [App & Factory](docs/modules/app.md)
- **[API Reference](docs/api-reference/)**: [Core Entities](docs/api-reference/core.md), [Pipelines](docs/api-reference/pipelines.md), & [Services / Container](docs/api-reference/service.md)
- **[Roadmap](docs/roadmap/)**: [GraphRAG & Hybrid Search](docs/roadmap/graphrag.md)
- **[Deep Analysis](docs/deep-agents/)**: [Deep Agents Cost & Architecture](docs/deep-agents/README.md)

---

## 📦 Installation

```bash
# Minimal installation (core pipelines, DI container, in-memory vector store)
pip install polyrag

# With OpenAI support (langchain-openai)
pip install "polyrag[openai]"

# With ChromaDB vector store (langchain-chroma)
pip install "polyrag[chroma]"

# With Milvus vector store (langchain-milvus)
pip install "polyrag[milvus]"

# With HuggingFace embeddings (langchain-huggingface)
pip install "polyrag[huggingface]"

# Complete installation with all official partner packages
pip install "polyrag[all]"
```

---

## 🚀 Quick Start

### 1. Instant Setup from Environment (`PolyRAG`)

```python
from polyrag import PolyRAG

# Automatically loads configuration from environment variables (.env)
app = PolyRAG.from_env()

# Ingest raw text, a file, or an entire folder into the shared store
app.ingest("RFC 1035 specifies DNS domain name syntax.", source="rfc1035.txt")
app.ingest_file("data/rfc9000.txt")
app.ingest_directory("docs/", glob_pattern="*.txt")

# End-to-end question answering (convenience shortcut)
response = app.query("How does DNS translate domain names?")
print("Answer:", response.answer)
print("Sources:", response.sources)
```

---

### 2. Manufacturing Across the Pipeline Hierarchy

Manufacture the exact pipeline strategy you need from the configured setup:

```python
# Level 1: Standard 1-Shot RAG
naive = app.create_naive_rag()
naive_res = naive.query("What is DNS?")

# Level 2: Advanced RAG (Multi-Query Expansion & RRF Re-ranking)
advanced = app.create_advanced_rag(num_expanded_queries=3, top_k=5)
advanced_res = advanced.query("How does DNS handle packet truncation?")

# Level 3: Agentic RAG (Autonomous Multi-Round Loop & Fused Reflection)
agentic = app.create_agentic_rag(max_rounds=2, top_k=3, verbose=True)
agentic_res = agentic.query(
    "What transport protocol does HTTP/3 rely on, and how does connection migration work?"
)

print("Agentic Grounded Answer:\n", agentic_res.answer)
print("Confidence:", agentic_res.confidence)
print("Trajectory:", agentic_res.reasoning_summary)
```

---

### 3. Advanced: Dependency Injection (For Custom Backends & Testing)

> [!TIP]
> If you are using standard models and environment variables, `PolyRAG.from_env()` (above) is all you need. Use `Container` when you need to inject custom vector stores (e.g., Milvus, Qdrant), self-hosted LLMs (e.g., Ollama, vLLM), or mock dependencies for unit tests without hitting external APIs.

```python
from polyrag import (
    Container,
    PolyRAG,
    BaseVectorStore,
    BaseLLMClient,
    InMemoryVectorStore,
)

# 1. Initialize DI Container (Composition Root)
container = Container()

# 2. Register custom implementations or test mocks
container.register_instance(BaseVectorStore, InMemoryVectorStore())
# container.register_instance(BaseLLMClient, MyCustomOllamaLLM())

# 3. Option A: Build pipelines directly with injected dependencies
pipeline = container.build_agentic_rag(top_k=3, max_rounds=2)
response = pipeline.query("Explain TLS 1.3 0-RTT handshakes.")
print(response.answer)

# 3. Option B: Pass to PolyRAG for familiar ingestion & pipeline manufacturing
app = PolyRAG.from_container(container)
app.ingest("RFC 8446 defines the TLS 1.3 protocol.")
advanced = app.create_advanced_rag()
```

---

## 🧪 Testing

PolyRAG includes a complete suite of unit tests verifying all chunkers, stores, pipelines, and the DI container:

```bash
pytest tests
```

---

## 🛠️ Building & Publishing

To package PolyRAG for distribution:

```bash
# Build wheel and sdist
python -m build

# Upload to PyPI using twine
twine upload dist/*
```

---

## 📄 License

This project is licensed under the [MIT License](LICENSE).
