Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
48 commits
Select commit Hold shift + click to select a range
fcf3e02
portfolio item 3
sklsp Oct 15, 2026
7e1fdc7
portfolio item 4
sklsp Oct 15, 2026
e42b36e
portfolio item 5: safe automatic lint fixes
sklsp Oct 17, 2026
396fc6a
portfolio item 6: fix F findings by hand (F821 undefined config in st…
sklsp Oct 17, 2026
e8bdd28
portfolio item 7: fix B and E findings by hand (B904 exception chaini…
sklsp Oct 17, 2026
e1909c2
portfolio item 8: zero lint findings (auto-fix I001/UP/W292/F401 in a…
sklsp Oct 17, 2026
3e4e2a1
portfolio item 9: lint in CI (ruff job)
sklsp Oct 17, 2026
315f8d5
portfolio item 10: type-check configuration (mypy.ini)
sklsp Oct 17, 2026
d08d0a9
portfolio item 11: types in lora_routes.py (pydantic mypy plugin, str…
sklsp Oct 17, 2026
c6edeae
portfolio item 12: types in routes.py (strict module section, no code…
sklsp Oct 17, 2026
f48ba87
portfolio item 13: types in dataset + ComfyUI services (strict sectio…
sklsp Oct 17, 2026
f2c9489
portfolio item 14: zero type errors (6 fixes across launcher, diagnos…
sklsp Oct 17, 2026
d946605
portfolio item 15: type check in CI (typecheck job, mypy via requirem…
sklsp Oct 17, 2026
4707fe8
portfolio item 16: coverage in CI (pytest --cov=app, dev requirements)
sklsp Oct 17, 2026
de90a7e
portfolio item 17: RAG eval corpus and question set (12 docs, 48 ques…
sklsp Oct 17, 2026
e5640a5
Item 18: typed loader for the RAG eval dataset
sklsp Oct 17, 2026
49f2ffc
Item 19: retrieval metrics for the RAG eval
sklsp Oct 17, 2026
7434682
Item 20: build the eval retrieval index
sklsp Oct 17, 2026
0cee35b
Item 21: retrieval runner for the RAG eval
sklsp Oct 17, 2026
7677432
Item 22: evaluate the RAG service in the eval
sklsp Oct 17, 2026
70af685
Item 23: report generation for the RAG eval
sklsp Oct 17, 2026
7249591
Item 24: command-line entry point for the RAG eval
sklsp Oct 17, 2026
a3db5c6
Item 25: record actual embedding backend/model in eval reports
sklsp Oct 17, 2026
00c51bb
Item 26: chunking grid for the RAG eval
sklsp Oct 17, 2026
d76652d
Item 27 (prep): --grid mode on the eval command
sklsp Oct 17, 2026
769b831
Item 29: reciprocal rank fusion for hybrid retrieval
sklsp Oct 17, 2026
bbcd47a
Item 28: BM25 keyword index (pure Python, no new deps)
sklsp Oct 17, 2026
155d030
Item 30: rebuild BM25 keyword index from stored chunks at startup
sklsp Oct 17, 2026
099ec5e
Item 31: RAG_HYBRID setting (auto/vector/keyword) with normalized hyb…
sklsp Oct 17, 2026
b0854fb
Item 34: query() follows RAG_HYBRID (auto fuses vector + keyword)
sklsp Oct 17, 2026
4979763
Item 35: hybrid eval mode (mode param + --hybrid-mode flag)
sklsp Oct 17, 2026
0f69532
Item 36: docs/EVAL.md (harness guide + baselines); ignore generated e…
sklsp Oct 17, 2026
dc81ef6
Item 37: CI regression gate (pinned-backend baseline + one-sided pyte…
sklsp Oct 17, 2026
10ad849
Docker: image, compose file, and CI build+smoke job (items 38-40)
sklsp Oct 17, 2026
caab658
Tests: never write into the real data/ folder
sklsp Oct 19, 2026
d5ba9fb
Item 41: docs honesty test (tests/test_docs.py)
sklsp Oct 19, 2026
bb2e282
Item 42: ARCHITECTURE.md with module map
sklsp Oct 19, 2026
175ce8e
Item 43: ARCHITECTURE.md request flows
sklsp Oct 19, 2026
754757b
Item 44: ARCHITECTURE.md state and failures
sklsp Oct 19, 2026
f617877
Item 45: DESIGN.md opening and how a question becomes an answer
sklsp Oct 19, 2026
e78073a
Item 46: RAG design decisions
sklsp Oct 19, 2026
6493985
Item 47: DESIGN.md decisions 6 to 10
sklsp Oct 19, 2026
9982483
Item 48: DESIGN.md questions people ask
sklsp Oct 19, 2026
3bcbfce
Item 49: DESIGN.md numbers and weaknesses
sklsp Oct 19, 2026
421f546
Item 50: README engineering section, Docker run and RAG_HYBRID
sklsp Oct 19, 2026
1a5cdc2
Item 51: CHANGELOG v1.1.0 entry
sklsp Oct 19, 2026
1505e55
Item 49 follow-up: DESIGN.md question 12
sklsp Oct 19, 2026
bd0d064
dash scan: replace em dashes with hyphens in docs, code and eval corp…
sklsp Oct 19, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions .dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# Keep the build context small and free of local state/secrets.
.git
.github
.env*
.venv*
__pycache__/
*.py[cod]
.pytest_cache/
.mypy_cache/
.ruff_cache/
.coverage

# Runtime state — created at startup, lives in a volume (see Dockerfile).
data/

# Demo GIFs for the README; not used by the app.
images/

# Local test-suite logs.
*.log
65 changes: 62 additions & 3 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,37 @@ on:
pull_request:

jobs:
lint:
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.12"
- name: Install ruff
run: pip install "ruff==0.17.0"
- name: Lint (ruff)
run: ruff check .

typecheck:
runs-on: ubuntu-latest
timeout-minutes: 20
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.12"
cache: pip
- name: Install dependencies
# Full install (CPU-only torch first) so mypy resolves the same imports as locally;
# mypy.ini's pydantic plugin also needs pydantic present.
run: |
pip install torch --index-url https://download.pytorch.org/whl/cpu
pip install -r requirements-dev.txt
- name: Type check (mypy)
run: python -m mypy

test:
runs-on: ubuntu-latest
timeout-minutes: 30
Expand All @@ -19,6 +50,34 @@ jobs:
# CPU-only torch first, so sentence-transformers does not pull the multi-GB CUDA build
run: |
pip install torch --index-url https://download.pytorch.org/whl/cpu
pip install -r requirements.txt
- name: Run tests
run: python -m pytest
pip install -r requirements-dev.txt
- name: Run tests (with coverage)
# Coverage is reported for now; a minimum threshold will be added once the
# eval work has established what the number should protect.
run: python -m pytest --cov=app --cov-report=term-missing

docker:
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- uses: actions/checkout@v4
- name: Build image
run: docker build -t apollo:ci .
- name: Smoke test (start container, wait for /live)
# The app boots fine without Ollama - the embedding client falls back to
# sentence-transformers and the vector store starts empty. /live is the
# dependency-free liveness probe; /health would 503 without Ollama.
run: |
docker run -d --name apollo -p 8000:8000 apollo:ci
for i in $(seq 1 60); do
if curl -fs http://localhost:8000/live > /dev/null; then
echo "alive after ${i} polls"
exit 0
fi
sleep 2
done
docker logs apollo
exit 1
- name: Stop container
if: always()
run: docker stop apollo || true
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -270,3 +270,6 @@ data/jobs.json

# Runtime state (created by the app at startup)
data/

# Eval reports (generated by python -m evals.cli; reproducible, see docs/EVAL.md)
evals/reports/
8 changes: 8 additions & 0 deletions CHANGELOG.MD
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
# Changelog

## v1.1.0
- Retrieval evaluation: 48 questions, hit@k and MRR, a hashing baseline and MiniLM (`python -m evals.cli`)
- Optional hybrid retrieval: BM25 plus reciprocal rank fusion behind `RAG_HYBRID`
- CI: ruff, mypy, coverage reporting (TOTAL 81%), retrieval regression gate, Docker build
- Dockerfile and docker-compose.yml (CPU-only image)
- Test suite runs in about 89 seconds instead of 323 (network probes fail fast in tests)
- docs/ARCHITECTURE.md, docs/DESIGN.md and docs/EVAL.md

## v1.0.0
- Initial release of AI Document Agent
- Added RAG pipeline with FAISS
Expand Down
47 changes: 47 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# Apollo - FastAPI backend (portfolio item 38)
#
# Build: docker build -t apollo .
# Run: docker run --rm -p 8000:8000 -v apollo-data:/app/data \
# -e OLLAMA_BASE_URL=http://host.docker.internal:11434 apollo
#
# The app expects Ollama (and optionally ComfyUI) to run OUTSIDE the container;
# from inside, reach them via host.docker.internal (Docker Desktop) or with
# --network=host on Linux.

FROM python:3.12-slim

ENV PYTHONDONTWRITEBYTECODE=1 \
PYTHONUNBUFFERED=1 \
PIP_NO_CACHE_DIR=1

WORKDIR /app

# CPU-only torch first, so sentence-transformers does not pull the multi-GB
# CUDA build (same trick as .github/workflows/ci.yml). Runtime deps only -
# ruff/mypy/pytest stay out of the image.
COPY requirements.txt ./
RUN pip install torch --index-url https://download.pytorch.org/whl/cpu \
&& pip install -r requirements.txt

# Run as an unprivileged user; /app/data is a volume for runtime state
# (LoRA library, generated images, jobs.json - created at startup). The dir
# must exist in the image owned by appuser: Docker initializes an empty
# volume from the image contents on first run, which preserves ownership.
RUN useradd --create-home appuser \
&& mkdir -p data/loras data/generated \
&& chown -R appuser:appuser /app/data

USER appuser

COPY --chown=appuser:appuser . .

VOLUME ["/app/data"]

EXPOSE 8000

# Liveness check: /live is deliberately dependency-free (Ollama/ComfyUI down
# does not make the API "not started"); /health reports dependency state.
HEALTHCHECK --interval=30s --timeout=5s --start-period=15s \
CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:8000/live', timeout=4)" || exit 1

CMD ["python", "main.py", "--api"]
21 changes: 19 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,14 @@ or process adapter. Nothing in the document pipeline imports ComfyUI code.

---

## Engineering

- **Tested:** the suite runs without Ollama or ComfyUI (425 tests). CI runs lint (ruff), a type check (mypy), the tests with coverage reporting, a retrieval regression gate and a Docker build.
- **Measured:** retrieval is scored on 48 questions: MiniLM hit@4 1.0000, MRR 0.9757. See [docs/EVAL.md](docs/EVAL.md).
- **Documented:** [architecture](docs/ARCHITECTURE.md) and [design decisions and trade-offs](docs/DESIGN.md).

---

## Setup

### Prerequisites
Expand Down Expand Up @@ -235,6 +243,14 @@ Run uvicorn directly without the variable and Apollo stays open, as a local tool
python -m uvicorn app.main:app --host 0.0.0.0 --port 8000
```

**Docker:**

```bash
docker compose up --build
```

The image is CPU-only. Ollama keeps running on the host; the container reaches it at `host.docker.internal`.

**Interactive CLI (legacy agent):**

```bash
Expand All @@ -258,6 +274,7 @@ python main.py --api
| `RAG_CHUNK_SIZE` | `800` | Characters per chunk |
| `RAG_CHUNK_OVERLAP` | `150` | Overlap between chunks |
| `RAG_TOP_K` | `4` | Retrieved chunks per query |
| `RAG_HYBRID` | `auto` | Retrieval mode; auto fuses BM25 and vector with reciprocal rank fusion (also accepts vector or keyword) |
| `OLLAMA_VISION_MODEL` | `llava` | Vision model for AI dataset captions |
| `COMFYUI_BASE_URL` | `http://127.0.0.1:8188` | Local ComfyUI instance |
| `COMFYUI_WORKFLOW_DIR` | `./workflows` | Where workflow JSON + mappings are stored |
Expand Down Expand Up @@ -474,7 +491,7 @@ Apollo/
│ ├── smoke_preflight.py # Live training-preflight demo
│ └── smoke_rag_persistence.py # Restart-survival verification for the index
├── workflows/ # ComfyUI workflows + node-input mappings
├── tests/ # Test suite (261 tests) + legacy debug scripts
├── tests/ # Test suite (425 tests) + legacy debug scripts
├── data/ # Documents, sessions, jobs, LoRA projects, generated images, rag index
├── images/ # Feature demo GIFs (README showcase)
├── launcher.py # One-command startup (API + tunnel)
Expand Down Expand Up @@ -648,7 +665,7 @@ Local-first does not mean unguarded:
- Documents, sessions, jobs, LoRA projects, workflows and generated images all persist on disk
- Upload debug logs appear in the server console: `[UPLOAD] filename`, `extracted chars`, `rag chunks indexed`
- Utility scripts: `python scripts/verify_system.py`, `python scripts/diagnostics_ollama.py`
- Run the tests with `python -m pytest` (261 tests); stress tests: `pytest tests/test_stress.py -m slow`
- Run the tests with `python -m pytest` (425 tests); stress tests: `pytest tests/test_stress.py -m slow`
- Log prefixes: `[COMFYUI]`, `[COMFYUI JOB]`, `[LORA]`, `[LORA TRAINING]`, `[DATASET]`, `[RAG]`, `[RUN HISTORY]`
- `tests/` also contains standalone diagnostic scripts (`test_endpoints.py`,
`test_ollama_detailed.py`, …) that predate the suite. They print at import time
Expand Down
2 changes: 1 addition & 1 deletion ai_agent/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from .agent import run_agent
from .llm import ask_llm, list_models
from .tools import summarize, find_keywords, answer_questions
from .tools import answer_questions, find_keywords, summarize

__all__ = ["run_agent", "ask_llm", "list_models", "summarize", "find_keywords", "answer_questions"]
2 changes: 1 addition & 1 deletion ai_agent/agent.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from .tools import summarize, find_keywords, answer_questions
from .tools import answer_questions, find_keywords, summarize


def run_agent(question: str, document: str) -> str:
Expand Down
5 changes: 3 additions & 2 deletions ai_agent/cli.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import os

from .core import run_agent
from .io import import_document, list_supported_files
import os


def main():
Expand All @@ -9,7 +10,7 @@ def main():
if os.path.exists(default_path):
document = import_document(default_path)

print('AI Document Agent — interactive')
print('AI Document Agent - interactive')
print('Commands: load <path>, summary, keywords, files, exit')

while True:
Expand Down
7 changes: 3 additions & 4 deletions ai_agent/config.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
import os
from pathlib import Path
from typing import Dict

DEFAULT_OLLAMA_BASE_URL = "http://localhost:11434"


def _load_dotenv(path: Path) -> Dict[str, str]:
values: Dict[str, str] = {}
def _load_dotenv(path: Path) -> dict[str, str]:
values: dict[str, str] = {}

try:
with path.open("r", encoding="utf-8") as handle:
Expand Down Expand Up @@ -56,4 +55,4 @@ def get_ollama_base_url() -> str:
return DEFAULT_OLLAMA_BASE_URL


OLLAMA_BASE_URL = get_ollama_base_url()
OLLAMA_BASE_URL = get_ollama_base_url()
2 changes: 1 addition & 1 deletion ai_agent/io.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@


def import_document(file_path):
with open(file_path, 'r', encoding='utf-8') as f:
with open(file_path, encoding='utf-8') as f:
return f.read()


Expand Down
8 changes: 4 additions & 4 deletions ai_agent/llm_client.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
from __future__ import annotations

from typing import Any, Dict, Optional
from typing import Any

try:
import requests
except ImportError: # pragma: no cover - exercised in minimal environments
requests = None
requests = None # type: ignore[assignment]

from .config import OLLAMA_BASE_URL

Expand All @@ -16,7 +16,7 @@ def _format_url(base_url: str, endpoint: str) -> str:
return f"{base_url.rstrip('/')}{endpoint}"


def _build_payload(prompt: str, model: str) -> Dict[str, Any]:
def _build_payload(prompt: str, model: str) -> dict[str, Any]:
return {
"model": model,
"prompt": prompt,
Expand Down Expand Up @@ -89,4 +89,4 @@ def list_models(base_url: str | None = None) -> dict:
results[url] = resp.text
except Exception as exc:
results[url] = str(exc)
return results
return results
3 changes: 1 addition & 2 deletions app/api/lora_routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,6 @@ def hardware_info(
) -> dict:
"""What this machine can run: GPU, VRAM, RAM, disk."""
from app.core.config import settings as app_settings

from app.services.hardware import detect_hardware

return detect_hardware(
Expand Down Expand Up @@ -372,8 +371,8 @@ def generate_captions(
@router.post("/projects/{project_id}/caption-jobs", response_model=JobResponse)
def start_caption_job(
project_id: str,
request: Request,
payload: CaptionGenerateRequest | None = None,
request: Request = None,
service: LoRAProjectService = Depends(get_project_service),
) -> JobResponse:
"""Queue dataset captioning as a background job (for large datasets).
Expand Down
14 changes: 7 additions & 7 deletions app/api/routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ def get_rag_service(request: Request) -> RAGService:
def live() -> dict:
"""Process liveness probe: the HTTP server is up and responding.

Deliberately dependency-free — Ollama/ComfyUI/AI Toolkit being down does
Deliberately dependency-free - Ollama/ComfyUI/AI Toolkit being down does
not make the API "not started". The launcher uses this to decide whether
startup succeeded; `/health` reports dependency state separately.
"""
Expand Down Expand Up @@ -111,7 +111,7 @@ def health(service: LLMService = Depends(get_llm_service)) -> HealthResponse:
try:
payload = service.health_check()
except OllamaServiceError as exc:
# A structured 503 with setup guidance, not a bare error — the UI
# A structured 503 with setup guidance, not a bare error - the UI
# renders this as an actionable card rather than a dead endpoint.
base_url = getattr(getattr(service, "client", None), "base_url",
settings.ollama_base_url)
Expand Down Expand Up @@ -171,7 +171,7 @@ def rag_debug_query(
"""Developer view of one retrieval: query → chunks → scores → context.

Shows exactly what the model would see for this question. Not used by the
normal chat flow — it exists to explain why an answer came out the way it
normal chat flow - it exists to explain why an answer came out the way it
did.
"""
if not q.strip():
Expand Down Expand Up @@ -346,14 +346,14 @@ async def upload_document(

return DocumentResponse(id=doc_id, source=file.filename)

except UnicodeDecodeError:
raise HTTPException(status_code=400, detail="File must be valid UTF-8 text")
except UnicodeDecodeError as err:
raise HTTPException(status_code=400, detail="File must be valid UTF-8 text") from err
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc))
raise HTTPException(status_code=400, detail=str(exc)) from exc
except OllamaServiceError as exc:
raise exc.to_http_exception() from exc
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error uploading document: {str(e)}")
raise HTTPException(status_code=500, detail=f"Error uploading document: {str(e)}") from e
finally:
if temp_path and os.path.exists(temp_path):
os.unlink(temp_path)
Expand Down
4 changes: 2 additions & 2 deletions app/clients/ollama_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ def _request(
# Never return 4xx status codes as that confuses clients about endpoint availability
if response.status_code == 404:
# Ollama returns 404 both for unknown routes AND for "model not
# found" — distinguish them so the message points at the real fix.
# found" - distinguish them so the message points at the real fix.
detail = _extract_ollama_error(response)
if "not found, try pulling" in detail:
raise OllamaServiceError(
Expand Down Expand Up @@ -73,7 +73,7 @@ def generate(self, *, model: str, prompt: str) -> dict:
# Use chat completion with system role for simple prompt completion
messages = [{"role": "user", "content": prompt}]
response = self.chat_completion(model=model, messages=messages)

# Convert OpenAI response format to Ollama generate format for compatibility
if "choices" in response and response["choices"]:
return {
Expand Down
Loading
Loading