Metadata-Version: 2.5
Name: pilotrag
Version: 0.1.0
Summary: Markdown-first, local-first Retrieval-Augmented Generation for Python developers.
Project-URL: Homepage, https://github.com/praveen9392/pilot-rag
Project-URL: Documentation, https://github.com/praveen9392/pilot-rag/blob/main/docs/index.md
Project-URL: Repository, https://github.com/praveen9392/pilot-rag.git
Project-URL: Issues, https://github.com/praveen9392/pilot-rag/issues
Project-URL: Changelog, https://github.com/praveen9392/pilot-rag/blob/main/docs/releases/release-notes.md
Author: Praveenkumar B
License-Expression: MIT
License-File: LICENSE
Keywords: chroma,embeddings,huggingface,llm,markdown,ollama,rag,retrieval,sentence-transformers
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: filelock<5,>=3.16
Requires-Dist: pydantic<3,>=2.9
Requires-Dist: pyyaml<7,>=6.0.1
Requires-Dist: twine>=7.0.0
Requires-Dist: typer<1,>=0.16
Provides-Extra: chroma
Requires-Dist: chromadb<2,>=1.0; extra == 'chroma'
Provides-Extra: dev
Requires-Dist: build>=1.2; extra == 'dev'
Requires-Dist: check-wheel-contents>=0.6; extra == 'dev'
Requires-Dist: chromadb<2,>=1.0; extra == 'dev'
Requires-Dist: hypothesis<7,>=6; extra == 'dev'
Requires-Dist: import-linter<3,>=2.0; extra == 'dev'
Requires-Dist: langchain-core<2,>=1.0; extra == 'dev'
Requires-Dist: langchain-ollama<2,>=1.0; extra == 'dev'
Requires-Dist: mypy<3,>=2.4; extra == 'dev'
Requires-Dist: pytest-asyncio<2,>=1.0; extra == 'dev'
Requires-Dist: pytest-cov<8,>=5; extra == 'dev'
Requires-Dist: pytest-httpx<0.37,>=0.30; extra == 'dev'
Requires-Dist: pytest<10,>=8; extra == 'dev'
Requires-Dist: python-dotenv<2,>=1.0; extra == 'dev'
Requires-Dist: ruff<0.18,>=0.17; extra == 'dev'
Requires-Dist: twine>=6; extra == 'dev'
Requires-Dist: types-pyyaml>=6.0; extra == 'dev'
Provides-Extra: dotenv
Requires-Dist: python-dotenv<2,>=1.0; extra == 'dotenv'
Provides-Extra: huggingface
Requires-Dist: sentence-transformers<7,>=3; extra == 'huggingface'
Provides-Extra: local
Requires-Dist: chromadb<2,>=1.0; extra == 'local'
Requires-Dist: langchain-core<2,>=1.0; extra == 'local'
Requires-Dist: langchain-ollama<2,>=1.0; extra == 'local'
Requires-Dist: sentence-transformers<7,>=3; extra == 'local'
Provides-Extra: ollama
Requires-Dist: langchain-core<2,>=1.0; extra == 'ollama'
Requires-Dist: langchain-ollama<2,>=1.0; extra == 'ollama'
Description-Content-Type: text/markdown

# PilotRAG

Markdown-first, local-first Retrieval-Augmented Generation for Python.

Point PilotRAG at a folder of Markdown files, build a local search index once, and
ask questions that are answered **only** from those files, with source references.
Embeddings run locally through Hugging Face sentence-transformers, answers come
from a local [Ollama](https://ollama.com) model, and the index is a local
[Chroma](https://www.trychroma.com) directory, so nothing leaves your machine and
no API key is needed. It is a library first (a thin CLI is included); every
component can be replaced without touching your application code.

## How it works

PilotRAG has two separate phases. **Asking a question never re-embeds your
documents**: only the question itself is embedded.

**Phase 1: build the index** (only when you run `pilotrag ingest`)

1. **Find files**: scan the docs folder for `.md` files. Hidden files, files over the
   size limit and files with other extensions are never discovered (they are not
   counted anywhere); the report's `skipped` count covers discovered files that no
   loader handles.
2. **Read**: extract the text, the frontmatter (e.g. `team: platform`) and the title.
3. **Chunk**: split each file into pieces of about 1000 characters at headings and
   paragraphs, with 200 characters of overlap.
4. **Embed**: the Hugging Face model turns every chunk into a vector (384 numbers
   that capture its meaning). This is the slow part.
5. **Save**: store chunks and vectors in a new Chroma index under `.pilotrag/index/`.
6. **Swap**: when the new index is complete, the `CURRENT` pointer switches to it and
   the old one is removed. If anything failed, the old index stays in use.

**Phase 2: answer a question** (every `pilotrag query` / `rag.query()`)

1. **Open** the saved index from disk; documents are not re-read or re-embedded.
2. **Embed the question** only (one short text, milliseconds).
3. **Search** for the chunks whose vectors are closest to the question (top 5 by default).
4. **Check evidence**: if nothing is retrieved (or, when you set `retrieval.min_score`,
   everything scores below it), reply "not enough information" without calling the
   LLM.
5. **Ask the LLM** (Ollama) with the question plus those chunks, instructed to answer
   only from them and to say when they are insufficient.
6. **Return** the answer with its sources (file, heading, score, snippet).

```text
INGEST (when you run it):  docs/*.md -> chunks -> embeddings -> saved index
QUERY  (every question):   question -> embedding -> search saved index -> LLM -> answer + sources
```

The index does **not** update by itself: nothing watches your files and nothing
runs on a schedule. When documents change, run `pilotrag ingest` again, by hand or
on a schedule (see [Keep the index up to date](#step-8-keep-the-index-up-to-date)).

## Features

- **Local and free by default**: Hugging Face embeddings, Ollama chat, Chroma
  storage, no accounts or API keys.
- **Grounded answers with sources**: every `Answer` lists the files, headings,
  scores and snippets of the chunks given to the model. When nothing relevant is
  found (no chunks retrieved, or all below `retrieval.min_score`) you get
  `status="insufficient_evidence"` and no LLM call. By default `min_score` is unset,
  so a non-empty index always returns `top_k` chunks and the model itself is
  instructed to say when the context does not answer the question.
- **Safe index updates**: each ingest builds a new index generation and swaps it in
  atomically; a failed run leaves the previous index queryable.
- **Compatibility checks**: the index records which embedding model and chunker
  built it, and queries refuse a mismatched index instead of returning wrong results.
- **Metadata filters**: restrict a query to documents whose frontmatter matches.
- **Typed errors with hints**: every failure has a stable `code` and a fix.
- **Extensible and testable**: plugin entry points, deterministic fakes and
  contract test suites.

## Step-by-step guide

Commands are shown for Windows PowerShell; macOS/Linux differences are noted.

### Step 1: Install the prerequisites (once)

1. **Python 3.10 - 3.13**: check with `python --version`.
2. **Ollama** (generates the answers): install from
   <https://ollama.com/download> and make sure it is running (it starts
   automatically on Windows/macOS; on Linux run `ollama serve`).
3. **Pull a chat model**:

   ```bash
   ollama pull qwen2.5:0.5b
   ```

   This one is small and fast. For better answers use a larger model such as
   `qwen2.5:3b` or `llama3.2:3b` and set `llm.model` accordingly.

### Step 2: Create a project and install PilotRAG

```powershell
mkdir my-kb
cd my-kb
python -m venv .venv
.venv\Scripts\activate          # macOS/Linux: source .venv/bin/activate
pip install "pilotrag[local]"
pilotrag --version              # verify the install
```

`local` = Hugging Face embeddings + Ollama client + Chroma. It pulls in PyTorch,
so the first install is large. Smaller installs: `pilotrag[huggingface]`,
`pilotrag[ollama]`, `pilotrag[chroma]`; plain `pip install pilotrag` is the core
only (bring your own providers or use the shipped test fakes).

To install from a local checkout of this repository instead of PyPI:

```powershell
pip install "C:/path/to/pilot-rag[local]"
```

### Step 3: Add your documents

```powershell
mkdir docs
```

Put your `.md` files in `docs/` (subfolders are fine). Optionally add frontmatter
at the top of a file so you can filter on it later:

```markdown
---
team: platform
---
# Deploy process

Deploys happen every Tuesday at 10am UTC.
```

### Step 4: Write the config file

Create `pilotrag.yaml` in `my-kb/`:

```yaml
version: 1
documents:
  path: ./docs
  on_error: skip            # skip unreadable files instead of stopping the run
chunking:
  strategy: recursive_markdown
  size: 1000
  overlap: 200
embeddings:
  provider: huggingface
  model: BAAI/bge-small-en-v1.5
llm:
  provider: ollama
  model: qwen2.5:0.5b
vector_store:
  provider: chroma
  path: ./.pilotrag/index
retrieval:
  strategy: dense
  top_k: 5
```

> **Relative paths are resolved from the folder you run the command in, not from the
> config file's location.** `./docs` and `./.pilotrag/index` above work when you run
> `pilotrag` from `my-kb/`. If you run it from elsewhere (for example a scheduler),
> either `cd` into the project folder first or use absolute paths.

### Step 5: Build the index

```powershell
pilotrag ingest
```

- The first run downloads the embedding model (about 130 MB) to your Hugging Face
  cache; later runs reuse it.
- The output shows documents discovered/processed/skipped, chunks indexed and
  `Status: success`.
- Preview without embedding or writing anything: `pilotrag ingest --dry-run`.

### Step 6: Ask questions

```powershell
pilotrag query "When do deploys happen?"
pilotrag query "When do deploys happen?" --top-k 3
```

You get the answer plus the source files and headings it used. The model is
instructed to answer only from the retrieved chunks and to say when they do not
contain the answer (small models may still guess). To make weak matches count as
"no evidence" (`status="insufficient_evidence"`, no LLM call), set
`retrieval.min_score` (for example `0.5`; tune it per embedding model).

### Step 7: Use it from Python (your application)

```python
import asyncio

from pilotrag import RAG
from pilotrag.core.types import MetadataFilter

with RAG.from_config("pilotrag.yaml") as rag:        # closes resources on exit
    answer = rag.query("When do deploys happen?")     # Answer
    print(answer.text)
    for source in answer.sources:                     # SourceReference
        print(source.relative_path, source.heading_path, source.score)

    if answer.status == "insufficient_evidence":
        print("Not in the docs.")

    # Only search documents whose frontmatter has `team: platform`
    scoped = rag.query(
        "Deploy steps?",
        filters=MetadataFilter(equalities={"team": "platform"}),
    )

    # Async twin for async apps (e.g. FastAPI): runs on a worker thread
    later = asyncio.run(rag.aquery("What is the rate limit?"))
```

Your application should **only query**. Build the index separately (Step 5 or
Step 8), not before every question. Ingesting from Python is also possible:

```python
with RAG.from_config("pilotrag.yaml") as rag:
    report = rag.ingest()                 # IngestionReport
    print(report.status, report.chunks_indexed, report.skipped)
```

Also available: `RAG.from_mapping({...})`, `RAG.from_settings(settings)`,
`rag.validate()`, `rag.ingest(dry_run=True)`. Full reference:
[docs/api-reference/overview.md](https://github.com/praveen9392/pilot-rag/blob/main/docs/api-reference/overview.md).

### Step 8: Keep the index up to date

Whenever your documents change, run `pilotrag ingest` again. It builds a fresh
index and swaps it in safely; a lock file prevents two ingests from overlapping.
To automate it:

- **Windows Task Scheduler** (daily at 02:00; use `/sc hourly` instead of
  `/sc daily /st 02:00` for every hour). Scheduled tasks start in
  `C:\Windows\System32`, so the task changes into the project folder first
  (relative paths in the config resolve from there):

  ```powershell
  schtasks /create /tn "pilotrag-ingest" /sc daily /st 02:00 /tr "cmd /c cd /d C:\path\to\my-kb && .venv\Scripts\pilotrag.exe ingest"
  ```

- **macOS/Linux cron** (every hour):

  ```text
  0 * * * * cd /path/to/my-kb && .venv/bin/pilotrag ingest
  ```

- **On every new build or deploy**: add `pilotrag ingest -c pilotrag.yaml` as a step
  in your CI/CD pipeline.

Current limitations to plan around:

- Every ingest re-embeds **all** documents, even unchanged ones (no incremental
  ingestion yet).
- A long-running application keeps using the index it already opened; restart it
  (or create a new `RAG` object) after a scheduled ingest to pick up the new index.

### Step 9: If something goes wrong

| Problem | Fix |
| --- | --- |
| `Error [index_not_found]` | Run `pilotrag ingest` first |
| `Error [index_incompatible]` | You changed the embedding model or chunking settings: run `pilotrag ingest` again |
| `Error [provider_unavailable]` (Ollama) | Start Ollama (`ollama serve`) and check `llm.base_url` |
| `Error [provider_response]` 404 | The model is not pulled: `ollama pull <model>` |
| `Error [missing_extra]` | `pip install "pilotrag[local]"` |
| Embedding model download fails | The first run needs internet; afterwards you can set `HF_HUB_OFFLINE=1`. See [troubleshooting](https://github.com/praveen9392/pilot-rag/blob/main/docs/operations/troubleshooting.md#hugging-face-embedder) |
| Weak or off-topic answers | Use a larger chat model, or set `retrieval.min_score: 0.5` to drop weak matches |

More: [docs/operations/troubleshooting.md](https://github.com/praveen9392/pilot-rag/blob/main/docs/operations/troubleshooting.md).
Known limitations: [docs/releases/known-issues.md](https://github.com/praveen9392/pilot-rag/blob/main/docs/releases/known-issues.md).

## Configuration summary

Required sections: `documents`, `chunking`, `embeddings`, `llm`, `vector_store`.
`version` is optional and defaults to `1` (setting it is recommended). Every key is
validated; unknown keys and bad values are reported together with their paths.
Relative paths resolve from the current working directory.

| Section | Key options (defaults) |
| --- | --- |
| `documents` | `path`, `extensions` (`[".md"]`), `follow_symlinks` (false), `include_hidden` (false), `max_file_size_mb` (5), `on_error` (`fail` or `skip`) |
| `chunking` | `strategy: recursive_markdown`, `size` (1000), `overlap` (200) |
| `embeddings` | `provider: huggingface` (default) or `ollama`; `model`, `batch_size`, `device`, ... |
| `llm` | `provider: ollama`, `model`, `temperature` (0.0), `timeout_s` (120), `base_url` |
| `vector_store` | `provider: chroma`, `path` (`./.pilotrag/index`), `collection` |
| `retrieval` | `strategy: dense`, `top_k` (5), `min_score` (null, range -1..1) |
| `generation` | `insufficient_evidence_message`, `max_context_chunks` (8) |
| `logging` | `level`, `format` (`text` or `json`), `redact` |

Override any value with `PILOTRAG__SECTION__KEY` environment variables or
`${ENV}` references. Complete reference:
[docs/development/configuration.md](https://github.com/praveen9392/pilot-rag/blob/main/docs/development/configuration.md).

## CLI reference

```text
pilotrag --version
pilotrag ingest [--config/-c PATH] [--dry-run]
pilotrag query QUESTION [--config/-c PATH] [--top-k N]
```

| Option | Default | Meaning |
| --- | --- | --- |
| `--config`, `-c` | `pilotrag.yaml` | Config file |
| `--dry-run` (ingest) | off | Plan only; nothing embedded or written |
| `--top-k` (query) | config value | Chunks to retrieve |

| Exit code | Meaning |
| --- | --- |
| 0 | Success |
| 1 | Failure (see `Error [code]` / `Hint:` on stderr) |
| 2 | Invalid configuration or usage |
| 3 | Ingest finished with some files failed (`on_error: skip`) |

## Choosing an embedding model

The default is `BAAI/bge-small-en-v1.5` (384 dimensions, MIT license), a strong
small English model that runs on CPU. For an even smaller model use
`sentence-transformers/all-MiniLM-L6-v2`; any sentence-transformers model id
works. Use `device: cuda` or `mps` for acceleration, `query_instruction` for
models that need a query prefix, and `HF_HOME` / `HF_HUB_OFFLINE=1` to control the
model cache and network use. Ollama embeddings (`provider: ollama`) remain
available.

**Switching models requires re-ingesting.** The index fingerprint records the
embedding provider, model, dimension and vector settings (and the chunker
settings); after a change, queries fail with `index_incompatible` until you run
`pilotrag ingest` again.

## Extending

Replace any component (chunker, loader, embedder, chat model, vector store,
retriever, reranker) by registering a `ProviderSpec` in code or publishing it
under a `pilotrag.<kind>` entry-point group, then select it in YAML. See
[docs/technical-design/integration-design.md](https://github.com/praveen9392/pilot-rag/blob/main/docs/technical-design/integration-design.md)
and the offline example [examples/custom_chunker](https://github.com/praveen9392/pilot-rag/tree/main/examples/custom_chunker/).
A runnable end-to-end project lives in [examples/markdown_qa](https://github.com/praveen9392/pilot-rag/tree/main/examples/markdown_qa/).

## Documentation

Start at [docs/index.md](https://github.com/praveen9392/pilot-rag/blob/main/docs/index.md): requirements, architecture and
decisions, technical design, API reference, development setup, deployment, testing,
operations and release notes. Release history:
[docs/releases/release-notes.md](https://github.com/praveen9392/pilot-rag/blob/main/docs/releases/release-notes.md).

## License

MIT. See [LICENSE](https://github.com/praveen9392/pilot-rag/blob/main/LICENSE).
