scoutrag 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,147 @@
1
+ Metadata-Version: 2.4
2
+ Name: scoutrag
3
+ Version: 0.1.0
4
+ Summary: Active-exploration RAG agent that fetches, indexes, and cites live web sources instead of answering from an empty index.
5
+ License-Expression: MIT
6
+ Requires-Python: >=3.12
7
+ Description-Content-Type: text/markdown
8
+ Requires-Dist: beautifulsoup4>=4.12.0
9
+ Requires-Dist: fastapi>=0.115.0
10
+ Requires-Dist: httpx>=0.27.0
11
+ Requires-Dist: lxml>=5.2.0
12
+ Requires-Dist: playwright>=1.48.0
13
+ Requires-Dist: pydantic>=2.7.0
14
+ Requires-Dist: sentence-transformers>=3.0.0
15
+ Requires-Dist: sqlite-vec>=0.1.6
16
+ Requires-Dist: uvicorn>=0.30.0
17
+ Provides-Extra: dev
18
+ Requires-Dist: pytest>=8.0.0; extra == "dev"
19
+
20
+ # ScoutRAG
21
+
22
+ **Active-exploration RAG agent that refuses to answer from an empty or thin index.**
23
+
24
+ When a question arrives, ScoutRAG checks what its local vector index actually covers. If coverage is thin or empty, it does **not** hallucinate from model weights—it plans search queries, searches DuckDuckGo HTML, fetches live web pages politely with headless Playwright, chunks and embeds them locally into `sqlite-vec`, and synthesizes a grounded answer where every factual claim cites a page actually fetched in SQLite. If the fetched pages don't contain the answer, it replies `"I could not find that in the sources I fetched."` with zero citations.
25
+
26
+ ---
27
+
28
+ ## Architecture & Deliberate Trade-offs
29
+
30
+ | Layer | Choice | Why (1-week solo developer tool) |
31
+ |---|---|---|
32
+ | **Embeddings** | `sentence-transformers/all-MiniLM-L6-v2` (CPU) | Zero API keys, zero network latency per chunk, reproducible locally. |
33
+ | **Chunking** | **~256 tokens / 50-token overlap** | *Deliberate deviation from ~500 tokens:* `all-MiniLM-L6-v2` silently truncates inputs past 256 wordpiece tokens. Sizing chunks to ~256 tokens ensures 100% of every chunk is represented in its embedding, while top-5 retrieval still provides ~1,250 tokens of synthesis context. |
34
+ | **Vector Store** | `sqlite-vec` | Single inspectable local SQLite file (`~/.scoutrag/scoutrag.db`) alongside source metadata and fetch timestamps—no separate vector DB server. |
35
+ | **Search (Default)** | DuckDuckGo HTML (`html.duckduckgo.com/html/`) | Zero search API keys required. If DDG returns HTTP `202` or a human-verification challenge, ScoutRAG stops immediately (never retries or falls back to another DDG endpoint) and surfaces an explicit `"Search unavailable"` error (HTTP `503` / CLI exit `1`). |
36
+ | **Search (Opt-in CC)** | Common Crawl (`SCOUTRAG_SEARCH=commoncrawl`) | Free, open, zero API key or card required. Resolves the latest crawl from `collinfo.json` and queries its CDX index. Snapshot data (weeks old, not live) and URL-pattern matching (not keyword ranking) — works best when questions name target domains; returns no candidates (`not_found`) if no domain is named. |
37
+ | **Search (Opt-in Brave)** | Brave Search API (`SCOUTRAG_SEARCH_API_KEY`) | Optional sanctioned JSON API (`api.search.brave.com/res/v1/web/search`) used when `SCOUTRAG_SEARCH=brave` or `SCOUTRAG_SEARCH_API_KEY` is set. Brave provides $5/month in free credits (~1,000 queries/month) after payment-card verification at signup. |
38
+ | **Fetcher** | Headless Playwright (Chromium) | Handles JS-rendered docs; hard-capped at 8 pages/question, 15s timeout/page, 1s per-host gap, `robots.txt` enforced, stops host on HTTP `429`. |
39
+ | **LLM (Default)** | Local Ollama (`qwen2.5:7b`) | Runs 100% locally with no API keys set. |
40
+ | **LLM (Opt-in)** | Gemini API (`SCOUTRAG_LLM=gemini` + `GEMINI_API_KEY`) | Strictly opt-in only. Even if `GEMINI_API_KEY` is in your shell, Ollama stays active unless `SCOUTRAG_LLM=gemini` is explicitly set. Setting the flag without a key fails loudly instead of falling back. |
41
+
42
+ ### Pipeline Flow
43
+ 1. **Coverage Gate (`scoutrag/coverage.py`):** Embeds the question, retrieves top-10 non-stale chunks, counts `hits` (`similarity >= 0.35`) and `best_similarity`. Routes to `INDEX` only if `hits >= 3` and `best_similarity >= 0.45`; otherwise `EXPLORE`.
44
+ 2. **Exploration Planner (`scoutrag/planner.py`):** One LLM call generates 2–4 search queries (hard-capped at 4), optional `target_domains` (only if named in the question), and `stop_if`, then routes to DuckDuckGo HTML by default (`SCOUTRAG_SEARCH=duckduckgo`), Common Crawl (`SCOUTRAG_SEARCH=commoncrawl`), or Brave Search (`SCOUTRAG_SEARCH=brave` / `SCOUTRAG_SEARCH_API_KEY`), interleaving URLs round-robin. If DDG returns HTTP `202` or a challenge page, ScoutRAG halts immediately with `"Search unavailable"`.
45
+ 3. **Polite Fetcher (`scoutrag/fetcher.py`):** Checks `robots.txt` per host, enforces ≥1s gap per host, aborts a host on `429`, fetches up to 8 pages (`15s` timeout), and strips nav/ads/scripts/chrome.
46
+ 4. **Indexer (`scoutrag/indexer.py`):** Deduplicates chunks by `(url, sha256)`, refreshes timestamps on re-fetch without duplicating vectors, and excludes chunks older than 7 days (`stale_count` exposed in API & UI).
47
+ 5. **Answerer (`scoutrag/answerer.py`):** Retrieves top-5 non-stale chunks, runs one strictly grounded LLM call, programmatically verifies every `[n]` citation against `sources` in SQLite, and forces exact refusal if no verified citation exists.
48
+ 6. **Observability (`scoutrag/logging_utils.py`):** Appends 1 JSON line per question to `~/.scoutrag/queries.jsonl`.
49
+
50
+ ---
51
+
52
+ ## Setup
53
+
54
+ ### 1. Python environment & package
55
+ ```bash
56
+ python3.12 -m venv .venv
57
+ source .venv/bin/activate
58
+ pip install -e ".[dev]"
59
+ ```
60
+
61
+ ### 2. Playwright Chromium
62
+ ```bash
63
+ playwright install chromium
64
+ ```
65
+
66
+ ### 3. Local LLM via Ollama (`qwen2.5:7b`)
67
+ ```bash
68
+ brew install ollama
69
+ ollama serve &
70
+ ollama pull qwen2.5:7b
71
+ ```
72
+
73
+ ---
74
+
75
+ ## Usage
76
+
77
+ ### Web UI & API Server
78
+ ```bash
79
+ scoutrag serve
80
+ # Open http://127.0.0.1:8000
81
+ ```
82
+
83
+ Endpoints:
84
+ - `POST /ask` — `{"question": "..."}` → `{"answer", "route", "coverage", "fetched_pages", "citations", "latency_ms", "queries"}`
85
+ - `GET /index` — indexed sources, chunk counts, fetch times, and `stale_count`
86
+ - `DELETE /index` — clear the local index
87
+
88
+ ### CLI
89
+ ```bash
90
+ scoutrag ask "How do you configure timeouts in Python HTTPX?"
91
+ scoutrag index --list
92
+ scoutrag index --clear
93
+ ```
94
+
95
+ ### Opt-in Common Crawl Discovery (Free, Keyless, No Card)
96
+ If DuckDuckGo gates automated requests and you want a 100% free, open, zero-key discovery backend, set `SCOUTRAG_SEARCH=commoncrawl`:
97
+ ```bash
98
+ export SCOUTRAG_SEARCH=commoncrawl
99
+ scoutrag ask "According to flask.palletsprojects.com, what are blueprints in Flask intended for?"
100
+ ```
101
+ Important characteristics of the Common Crawl backend:
102
+ - **Free & open:** Uses `https://index.commoncrawl.org/collinfo.json` and the latest CDX index API with no API key or payment card.
103
+ - **Snapshot data:** Reflects the latest completed Common Crawl snapshot (typically weeks old, not live real-time web results).
104
+ - **URL-pattern matching, not keyword ranking:** Matches domains and URL slugs rather than full-text page relevance, so it works best when the question explicitly names a domain (allowing the planner to emit `target_domains`). If the planner names no domains, it returns no candidates (`not_found`) and never falls back to DuckDuckGo.
105
+
106
+ ### Opt-in Brave Search API (Optional)
107
+ ScoutRAG defaults to keyless DuckDuckGo HTML so the local demo requires zero API keys. However, automated IPs may occasionally be gated by DuckDuckGo (`HTTP 202` / challenge), which causes ScoutRAG to stop with a clear `"Search unavailable"` error (`503`).
108
+
109
+ To use the sanctioned Brave Search API instead:
110
+ 1. Sign up at [Brave Search API](https://api-dashboard.search.brave.com/) (Brave includes **$5/month in free credits** — ~1,000 search queries/month — and requires payment-card verification during account creation).
111
+ 2. Export your token:
112
+ ```bash
113
+ export SCOUTRAG_SEARCH_API_KEY="your-brave-subscription-token"
114
+ scoutrag ask "Your question"
115
+ ```
116
+
117
+ ### Opt-in Gemini Backend
118
+ Ollama (`qwen2.5:7b`) is always the default—even if `GEMINI_API_KEY` is exported. To opt in to Gemini:
119
+ ```bash
120
+ export SCOUTRAG_LLM=gemini
121
+ export GEMINI_API_KEY="your-key-here"
122
+ scoutrag ask "Your question"
123
+ ```
124
+ If `SCOUTRAG_LLM=gemini` is set without `GEMINI_API_KEY`, ScoutRAG exits with a clear configuration error instead of falling back silently.
125
+
126
+ ### Configuration Environment Variables
127
+ - `SCOUTRAG_DATA_DIR` (default: `~/.scoutrag`)
128
+ - `SCOUTRAG_DB_PATH` (default: `~/.scoutrag/scoutrag.db`)
129
+ - `SCOUTRAG_LOG_PATH` (default: `~/.scoutrag/queries.jsonl`)
130
+ - `SCOUTRAG_SEARCH` (default: `duckduckgo`; supports `commoncrawl` and `brave`)
131
+ - `SCOUTRAG_CC_COLLINFO_URL` (default: `https://index.commoncrawl.org/collinfo.json`)
132
+ - `SCOUTRAG_SEARCH_API_KEY` (unset by default; enables opt-in Brave Search API)
133
+ - `SCOUTRAG_DDG_URL` (default: `https://html.duckduckgo.com/html/`)
134
+ - `SCOUTRAG_BRAVE_URL` (default: `https://api.search.brave.com/res/v1/web/search`)
135
+ - `SCOUTRAG_LLM` (unset or `ollama` by default; `gemini` opt-in)
136
+ - `SCOUTRAG_OLLAMA_URL` (default: `http://localhost:11434`)
137
+ - `SCOUTRAG_OLLAMA_MODEL` (default: `qwen2.5:7b`)
138
+ - `SCOUTRAG_GEMINI_MODEL` (default: `gemini-2.5-flash`)
139
+
140
+ ---
141
+
142
+ ## Running Tests
143
+ ```bash
144
+ pytest
145
+ ```
146
+
147
+ See [demo/script.md](demo/script.md) for the ~2-minute walkthrough.
@@ -0,0 +1,128 @@
1
+ # ScoutRAG
2
+
3
+ **Active-exploration RAG agent that refuses to answer from an empty or thin index.**
4
+
5
+ When a question arrives, ScoutRAG checks what its local vector index actually covers. If coverage is thin or empty, it does **not** hallucinate from model weights—it plans search queries, searches DuckDuckGo HTML, fetches live web pages politely with headless Playwright, chunks and embeds them locally into `sqlite-vec`, and synthesizes a grounded answer where every factual claim cites a page actually fetched in SQLite. If the fetched pages don't contain the answer, it replies `"I could not find that in the sources I fetched."` with zero citations.
6
+
7
+ ---
8
+
9
+ ## Architecture & Deliberate Trade-offs
10
+
11
+ | Layer | Choice | Why (1-week solo developer tool) |
12
+ |---|---|---|
13
+ | **Embeddings** | `sentence-transformers/all-MiniLM-L6-v2` (CPU) | Zero API keys, zero network latency per chunk, reproducible locally. |
14
+ | **Chunking** | **~256 tokens / 50-token overlap** | *Deliberate deviation from ~500 tokens:* `all-MiniLM-L6-v2` silently truncates inputs past 256 wordpiece tokens. Sizing chunks to ~256 tokens ensures 100% of every chunk is represented in its embedding, while top-5 retrieval still provides ~1,250 tokens of synthesis context. |
15
+ | **Vector Store** | `sqlite-vec` | Single inspectable local SQLite file (`~/.scoutrag/scoutrag.db`) alongside source metadata and fetch timestamps—no separate vector DB server. |
16
+ | **Search (Default)** | DuckDuckGo HTML (`html.duckduckgo.com/html/`) | Zero search API keys required. If DDG returns HTTP `202` or a human-verification challenge, ScoutRAG stops immediately (never retries or falls back to another DDG endpoint) and surfaces an explicit `"Search unavailable"` error (HTTP `503` / CLI exit `1`). |
17
+ | **Search (Opt-in CC)** | Common Crawl (`SCOUTRAG_SEARCH=commoncrawl`) | Free, open, zero API key or card required. Resolves the latest crawl from `collinfo.json` and queries its CDX index. Snapshot data (weeks old, not live) and URL-pattern matching (not keyword ranking) — works best when questions name target domains; returns no candidates (`not_found`) if no domain is named. |
18
+ | **Search (Opt-in Brave)** | Brave Search API (`SCOUTRAG_SEARCH_API_KEY`) | Optional sanctioned JSON API (`api.search.brave.com/res/v1/web/search`) used when `SCOUTRAG_SEARCH=brave` or `SCOUTRAG_SEARCH_API_KEY` is set. Brave provides $5/month in free credits (~1,000 queries/month) after payment-card verification at signup. |
19
+ | **Fetcher** | Headless Playwright (Chromium) | Handles JS-rendered docs; hard-capped at 8 pages/question, 15s timeout/page, 1s per-host gap, `robots.txt` enforced, stops host on HTTP `429`. |
20
+ | **LLM (Default)** | Local Ollama (`qwen2.5:7b`) | Runs 100% locally with no API keys set. |
21
+ | **LLM (Opt-in)** | Gemini API (`SCOUTRAG_LLM=gemini` + `GEMINI_API_KEY`) | Strictly opt-in only. Even if `GEMINI_API_KEY` is in your shell, Ollama stays active unless `SCOUTRAG_LLM=gemini` is explicitly set. Setting the flag without a key fails loudly instead of falling back. |
22
+
23
+ ### Pipeline Flow
24
+ 1. **Coverage Gate (`scoutrag/coverage.py`):** Embeds the question, retrieves top-10 non-stale chunks, counts `hits` (`similarity >= 0.35`) and `best_similarity`. Routes to `INDEX` only if `hits >= 3` and `best_similarity >= 0.45`; otherwise `EXPLORE`.
25
+ 2. **Exploration Planner (`scoutrag/planner.py`):** One LLM call generates 2–4 search queries (hard-capped at 4), optional `target_domains` (only if named in the question), and `stop_if`, then routes to DuckDuckGo HTML by default (`SCOUTRAG_SEARCH=duckduckgo`), Common Crawl (`SCOUTRAG_SEARCH=commoncrawl`), or Brave Search (`SCOUTRAG_SEARCH=brave` / `SCOUTRAG_SEARCH_API_KEY`), interleaving URLs round-robin. If DDG returns HTTP `202` or a challenge page, ScoutRAG halts immediately with `"Search unavailable"`.
26
+ 3. **Polite Fetcher (`scoutrag/fetcher.py`):** Checks `robots.txt` per host, enforces ≥1s gap per host, aborts a host on `429`, fetches up to 8 pages (`15s` timeout), and strips nav/ads/scripts/chrome.
27
+ 4. **Indexer (`scoutrag/indexer.py`):** Deduplicates chunks by `(url, sha256)`, refreshes timestamps on re-fetch without duplicating vectors, and excludes chunks older than 7 days (`stale_count` exposed in API & UI).
28
+ 5. **Answerer (`scoutrag/answerer.py`):** Retrieves top-5 non-stale chunks, runs one strictly grounded LLM call, programmatically verifies every `[n]` citation against `sources` in SQLite, and forces exact refusal if no verified citation exists.
29
+ 6. **Observability (`scoutrag/logging_utils.py`):** Appends 1 JSON line per question to `~/.scoutrag/queries.jsonl`.
30
+
31
+ ---
32
+
33
+ ## Setup
34
+
35
+ ### 1. Python environment & package
36
+ ```bash
37
+ python3.12 -m venv .venv
38
+ source .venv/bin/activate
39
+ pip install -e ".[dev]"
40
+ ```
41
+
42
+ ### 2. Playwright Chromium
43
+ ```bash
44
+ playwright install chromium
45
+ ```
46
+
47
+ ### 3. Local LLM via Ollama (`qwen2.5:7b`)
48
+ ```bash
49
+ brew install ollama
50
+ ollama serve &
51
+ ollama pull qwen2.5:7b
52
+ ```
53
+
54
+ ---
55
+
56
+ ## Usage
57
+
58
+ ### Web UI & API Server
59
+ ```bash
60
+ scoutrag serve
61
+ # Open http://127.0.0.1:8000
62
+ ```
63
+
64
+ Endpoints:
65
+ - `POST /ask` — `{"question": "..."}` → `{"answer", "route", "coverage", "fetched_pages", "citations", "latency_ms", "queries"}`
66
+ - `GET /index` — indexed sources, chunk counts, fetch times, and `stale_count`
67
+ - `DELETE /index` — clear the local index
68
+
69
+ ### CLI
70
+ ```bash
71
+ scoutrag ask "How do you configure timeouts in Python HTTPX?"
72
+ scoutrag index --list
73
+ scoutrag index --clear
74
+ ```
75
+
76
+ ### Opt-in Common Crawl Discovery (Free, Keyless, No Card)
77
+ If DuckDuckGo gates automated requests and you want a 100% free, open, zero-key discovery backend, set `SCOUTRAG_SEARCH=commoncrawl`:
78
+ ```bash
79
+ export SCOUTRAG_SEARCH=commoncrawl
80
+ scoutrag ask "According to flask.palletsprojects.com, what are blueprints in Flask intended for?"
81
+ ```
82
+ Important characteristics of the Common Crawl backend:
83
+ - **Free & open:** Uses `https://index.commoncrawl.org/collinfo.json` and the latest CDX index API with no API key or payment card.
84
+ - **Snapshot data:** Reflects the latest completed Common Crawl snapshot (typically weeks old, not live real-time web results).
85
+ - **URL-pattern matching, not keyword ranking:** Matches domains and URL slugs rather than full-text page relevance, so it works best when the question explicitly names a domain (allowing the planner to emit `target_domains`). If the planner names no domains, it returns no candidates (`not_found`) and never falls back to DuckDuckGo.
86
+
87
+ ### Opt-in Brave Search API (Optional)
88
+ ScoutRAG defaults to keyless DuckDuckGo HTML so the local demo requires zero API keys. However, automated IPs may occasionally be gated by DuckDuckGo (`HTTP 202` / challenge), which causes ScoutRAG to stop with a clear `"Search unavailable"` error (`503`).
89
+
90
+ To use the sanctioned Brave Search API instead:
91
+ 1. Sign up at [Brave Search API](https://api-dashboard.search.brave.com/) (Brave includes **$5/month in free credits** — ~1,000 search queries/month — and requires payment-card verification during account creation).
92
+ 2. Export your token:
93
+ ```bash
94
+ export SCOUTRAG_SEARCH_API_KEY="your-brave-subscription-token"
95
+ scoutrag ask "Your question"
96
+ ```
97
+
98
+ ### Opt-in Gemini Backend
99
+ Ollama (`qwen2.5:7b`) is always the default—even if `GEMINI_API_KEY` is exported. To opt in to Gemini:
100
+ ```bash
101
+ export SCOUTRAG_LLM=gemini
102
+ export GEMINI_API_KEY="your-key-here"
103
+ scoutrag ask "Your question"
104
+ ```
105
+ If `SCOUTRAG_LLM=gemini` is set without `GEMINI_API_KEY`, ScoutRAG exits with a clear configuration error instead of falling back silently.
106
+
107
+ ### Configuration Environment Variables
108
+ - `SCOUTRAG_DATA_DIR` (default: `~/.scoutrag`)
109
+ - `SCOUTRAG_DB_PATH` (default: `~/.scoutrag/scoutrag.db`)
110
+ - `SCOUTRAG_LOG_PATH` (default: `~/.scoutrag/queries.jsonl`)
111
+ - `SCOUTRAG_SEARCH` (default: `duckduckgo`; supports `commoncrawl` and `brave`)
112
+ - `SCOUTRAG_CC_COLLINFO_URL` (default: `https://index.commoncrawl.org/collinfo.json`)
113
+ - `SCOUTRAG_SEARCH_API_KEY` (unset by default; enables opt-in Brave Search API)
114
+ - `SCOUTRAG_DDG_URL` (default: `https://html.duckduckgo.com/html/`)
115
+ - `SCOUTRAG_BRAVE_URL` (default: `https://api.search.brave.com/res/v1/web/search`)
116
+ - `SCOUTRAG_LLM` (unset or `ollama` by default; `gemini` opt-in)
117
+ - `SCOUTRAG_OLLAMA_URL` (default: `http://localhost:11434`)
118
+ - `SCOUTRAG_OLLAMA_MODEL` (default: `qwen2.5:7b`)
119
+ - `SCOUTRAG_GEMINI_MODEL` (default: `gemini-2.5-flash`)
120
+
121
+ ---
122
+
123
+ ## Running Tests
124
+ ```bash
125
+ pytest
126
+ ```
127
+
128
+ See [demo/script.md](demo/script.md) for the ~2-minute walkthrough.
@@ -0,0 +1,37 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68.0", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "scoutrag"
7
+ version = "0.1.0"
8
+ description = "Active-exploration RAG agent that fetches, indexes, and cites live web sources instead of answering from an empty index."
9
+ readme = "README.md"
10
+ requires-python = ">=3.12"
11
+ license = "MIT"
12
+ dependencies = [
13
+ "beautifulsoup4>=4.12.0",
14
+ "fastapi>=0.115.0",
15
+ "httpx>=0.27.0",
16
+ "lxml>=5.2.0",
17
+ "playwright>=1.48.0",
18
+ "pydantic>=2.7.0",
19
+ "sentence-transformers>=3.0.0",
20
+ "sqlite-vec>=0.1.6",
21
+ "uvicorn>=0.30.0",
22
+ ]
23
+
24
+ [project.optional-dependencies]
25
+ dev = [
26
+ "pytest>=8.0.0",
27
+ ]
28
+
29
+ [project.scripts]
30
+ scoutrag = "scoutrag.cli:main"
31
+
32
+ [tool.setuptools.packages.find]
33
+ include = ["scoutrag*"]
34
+
35
+ [tool.pytest.ini_options]
36
+ testpaths = ["tests"]
37
+ addopts = "-v -s"
@@ -0,0 +1,3 @@
1
+ """ScoutRAG — active-exploration RAG agent."""
2
+
3
+ __version__ = "0.1.0"
@@ -0,0 +1,186 @@
1
+ """Grounded answer synthesis and strict programmatic citation verification."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import re
7
+ from dataclasses import dataclass
8
+
9
+ from scoutrag.config import Settings, get_settings
10
+ from scoutrag.indexer import RetrievedChunk, VectorIndex
11
+ from scoutrag.llm import LLMClient
12
+ from scoutrag.logging_utils import logger
13
+
14
+ NOT_FOUND_ANSWER = "I could not find that in the sources I fetched."
15
+
16
+ ANSWERER_SYSTEM_PROMPT = """You are ScoutRAG's strictly grounded RAG answerer.
17
+ Given numbered source excerpts [1]..[N] and a question, determine whether ANY excerpt directly states the answer.
18
+
19
+ Return a single JSON object with EXACTLY these keys:
20
+ {
21
+ "found": true or false,
22
+ "supporting_excerpt_number": integer 1..N or null,
23
+ "answer": "Concise complete sentence answering the question using ONLY facts in the excerpts, with inline [n] citations (e.g. 'The default timeout is 5 seconds [2].'). Empty string if found is false."
24
+ }
25
+
26
+ Rules:
27
+ - Read ALL excerpts [1] through [N] carefully, including code snippets, function/class parameter defaults, and short notes.
28
+ - Set "found": true whenever ANY excerpt directly contains the answer.
29
+ - Set "found": false if the answer is NOT present in the excerpts (never guess or use outside memory).
30
+ - Every factual claim in "answer" MUST include an inline [n] citation matching the excerpt number.
31
+ - Do NOT write external citation URLs; cite only with [n]."""
32
+
33
+ _CITATION_GROUP_RE = re.compile(r"\[(\d+(?:\s*,\s*\d+)*)\]")
34
+ _RAW_URL_RE = re.compile(r"https?://[^\s\)\]>\"']+")
35
+
36
+
37
+ @dataclass(frozen=True)
38
+ class AnswerResult:
39
+ answer: str
40
+ citations: list[dict[str, object]]
41
+ route: str # "answered" | "not_found"
42
+
43
+
44
+ def _normalize_citation_groups(text: str) -> str:
45
+ """Convert '[1, 2]' into '[1][2]' so every marker holds a single index."""
46
+
47
+ def _repl(match: re.Match[str]) -> str:
48
+ nums = [part.strip() for part in match.group(1).split(",") if part.strip().isdigit()]
49
+ return "".join(f"[{n}]" for n in nums)
50
+
51
+ return _CITATION_GROUP_RE.sub(_repl, text)
52
+
53
+
54
+ def _extract_json_dict(raw: str) -> dict[str, object] | None:
55
+ text = raw.strip()
56
+ if text.startswith("```"):
57
+ text = re.sub(r"^```(?:json)?\s*", "", text)
58
+ text = re.sub(r"\s*```$", "", text)
59
+ try:
60
+ obj = json.loads(text)
61
+ if isinstance(obj, dict):
62
+ return obj
63
+ except json.JSONDecodeError:
64
+ pass
65
+ start = text.find("{")
66
+ end = text.rfind("}")
67
+ if start != -1 and end > start:
68
+ try:
69
+ obj = json.loads(text[start : end + 1])
70
+ if isinstance(obj, dict):
71
+ return obj
72
+ except json.JSONDecodeError:
73
+ return None
74
+ return None
75
+
76
+
77
+ def verify_and_format_answer(
78
+ raw_answer: str,
79
+ chunks: list[RetrievedChunk],
80
+ known_source_urls: set[str],
81
+ ) -> AnswerResult:
82
+ """Enforce exact refusal and programmatically verify all [n] citations against DB URLs."""
83
+ text = raw_answer.strip()
84
+ if not text:
85
+ return AnswerResult(answer=NOT_FOUND_ANSWER, citations=[], route="not_found")
86
+
87
+ text = re.sub(r"^(?:Answer|Response)\s*:\s*", "", text, flags=re.IGNORECASE).strip()
88
+
89
+ normalized_refusal = text.lower().rstrip(".! ")
90
+ if "i could not find that in the sources i fetched" in normalized_refusal:
91
+ return AnswerResult(answer=NOT_FOUND_ANSWER, citations=[], route="not_found")
92
+
93
+ # Reject invented raw URLs not present in the fetched index or verbatim inside retrieved chunks
94
+ # (preserving example URLs like http://127.0.0.1:5000 quoted directly from fetched code snippets).
95
+ chunk_corpus = "\n".join(c.content for c in chunks)
96
+ for raw_url in _RAW_URL_RE.findall(text):
97
+ cleaned_url = raw_url.rstrip(".,;:)")
98
+ if cleaned_url not in known_source_urls and cleaned_url not in chunk_corpus:
99
+ logger.warning("Stripping unverified raw URL emitted by LLM: %s", cleaned_url)
100
+ text = text.replace(raw_url, "")
101
+
102
+ text = _normalize_citation_groups(text)
103
+
104
+ url_to_new_n: dict[str, int] = {}
105
+ citations: list[dict[str, object]] = []
106
+
107
+ def _rewrite_marker(match: re.Match[str]) -> str:
108
+ raw_num = int(match.group(1))
109
+ if 1 <= raw_num <= len(chunks):
110
+ chunk = chunks[raw_num - 1]
111
+ if chunk.url in known_source_urls:
112
+ if chunk.url not in url_to_new_n:
113
+ new_n = len(citations) + 1
114
+ url_to_new_n[chunk.url] = new_n
115
+ citations.append({"n": new_n, "url": chunk.url})
116
+ else:
117
+ new_n = url_to_new_n[chunk.url]
118
+ return f"[{new_n}]"
119
+ logger.warning("Stripping out-of-range or unindexed citation [%d]", raw_num)
120
+ return ""
121
+
122
+ verified_text = re.sub(r"\[(\d+)\]", _rewrite_marker, text)
123
+ verified_text = re.sub(r"(\[\d+\])(?:\s*\1)+", r"\1", verified_text)
124
+ verified_text = re.sub(r"[ \t]+([.,;:])", r"\1", verified_text)
125
+ verified_text = re.sub(r" {2,}", " ", verified_text).strip()
126
+
127
+ # Invariant: never return factual prose with zero verified citations.
128
+ if not citations or not verified_text:
129
+ return AnswerResult(answer=NOT_FOUND_ANSWER, citations=[], route="not_found")
130
+
131
+ return AnswerResult(
132
+ answer=verified_text,
133
+ citations=citations,
134
+ route="answered",
135
+ )
136
+
137
+
138
+ async def synthesize_answer(
139
+ question: str,
140
+ index: VectorIndex,
141
+ llm: LLMClient,
142
+ settings: Settings | None = None,
143
+ ) -> AnswerResult:
144
+ """Retrieve top-5 non-stale chunks, run 1 grounded LLM call, and verify citations."""
145
+ cfg = settings or get_settings()
146
+ chunks = index.search(question, top_k=cfg.answer_top_k, hybrid_rerank=True)
147
+ if not chunks:
148
+ return AnswerResult(answer=NOT_FOUND_ANSWER, citations=[], route="not_found")
149
+
150
+ excerpts: list[str] = []
151
+ for i, ch in enumerate(chunks, start=1):
152
+ title_part = f" | Title: {ch.title}" if ch.title else ""
153
+ excerpts.append(f"[{i}] URL: {ch.url}{title_part}\n{ch.content}")
154
+ context_block = "\n\n---\n\n".join(excerpts)
155
+
156
+ user_prompt = (
157
+ f"Excerpts:\n{context_block}\n\n"
158
+ f"Question: {question}"
159
+ )
160
+
161
+ raw = await llm.chat(
162
+ ANSWERER_SYSTEM_PROMPT,
163
+ user_prompt,
164
+ json_mode=True,
165
+ temperature=0.0,
166
+ )
167
+ known_urls = index.get_source_urls()
168
+
169
+ parsed = _extract_json_dict(raw)
170
+ if parsed is not None:
171
+ if not parsed.get("found"):
172
+ return AnswerResult(answer=NOT_FOUND_ANSWER, citations=[], route="not_found")
173
+ ans_text = str(parsed.get("answer") or "").strip()
174
+ if not ans_text:
175
+ return AnswerResult(answer=NOT_FOUND_ANSWER, citations=[], route="not_found")
176
+ supp = parsed.get("supporting_excerpt_number")
177
+ if (
178
+ not re.search(r"\[\d+(?:\s*,\s*\d+)*\]", ans_text)
179
+ and isinstance(supp, int)
180
+ and not isinstance(supp, bool)
181
+ and 1 <= supp <= len(chunks)
182
+ ):
183
+ ans_text = f"{ans_text} [{supp}]"
184
+ return verify_and_format_answer(ans_text, chunks, known_urls)
185
+
186
+ return verify_and_format_answer(raw, chunks, known_urls)
@@ -0,0 +1,89 @@
1
+ """FastAPI server and static UI mount for ScoutRAG."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from contextlib import asynccontextmanager
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+ from fastapi import FastAPI, HTTPException
10
+ from fastapi.responses import FileResponse
11
+ from pydantic import BaseModel, Field
12
+
13
+ from scoutrag.config import Settings, get_settings
14
+ from scoutrag.llm import LLMConfigError, LLMRequestError
15
+ from scoutrag.pipeline import ScoutRAGAgent
16
+ from scoutrag.planner import SearchUnavailableError
17
+
18
+ UI_PATH = Path(__file__).resolve().parent.parent / "ui" / "index.html"
19
+
20
+
21
+ class AskRequest(BaseModel):
22
+ question: str = Field(..., min_length=1)
23
+
24
+
25
+ def create_app(settings: Settings | None = None) -> FastAPI:
26
+ @asynccontextmanager
27
+ async def lifespan(app_instance: FastAPI):
28
+ agent = ScoutRAGAgent(settings or get_settings())
29
+ app_instance.state.agent = agent
30
+ try:
31
+ yield
32
+ finally:
33
+ await agent.close()
34
+
35
+ app_instance = FastAPI(
36
+ title="ScoutRAG",
37
+ description="Active-exploration RAG agent that fetches live sources when coverage is thin.",
38
+ version="0.1.0",
39
+ lifespan=lifespan,
40
+ )
41
+
42
+ def _get_agent() -> ScoutRAGAgent:
43
+ agent = getattr(app_instance.state, "agent", None)
44
+ if agent is None:
45
+ agent = ScoutRAGAgent(settings or get_settings())
46
+ app_instance.state.agent = agent
47
+ return agent
48
+
49
+ @app_instance.get("/")
50
+ @app_instance.get("/ui")
51
+ @app_instance.get("/ui/index.html")
52
+ async def serve_ui() -> FileResponse:
53
+ if not UI_PATH.exists():
54
+ raise HTTPException(status_code=404, detail="ui/index.html not found")
55
+ return FileResponse(UI_PATH, media_type="text/html")
56
+
57
+ @app_instance.get("/health")
58
+ async def health() -> dict[str, str]:
59
+ return {"status": "ok"}
60
+
61
+ @app_instance.post("/ask")
62
+ async def ask(req: AskRequest) -> dict[str, Any]:
63
+ agent = _get_agent()
64
+ try:
65
+ return await agent.ask(req.question)
66
+ except ValueError as exc:
67
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
68
+ except LLMConfigError as exc:
69
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
70
+ except SearchUnavailableError as exc:
71
+ raise HTTPException(status_code=503, detail=str(exc)) from exc
72
+ except LLMRequestError as exc:
73
+ raise HTTPException(status_code=502, detail=str(exc)) from exc
74
+
75
+ @app_instance.get("/index")
76
+ async def get_index() -> dict[str, Any]:
77
+ agent = _get_agent()
78
+ return agent.index.list_sources()
79
+
80
+ @app_instance.delete("/index")
81
+ async def delete_index() -> dict[str, Any]:
82
+ agent = _get_agent()
83
+ counts = agent.index.clear()
84
+ return {"cleared": True, **counts}
85
+
86
+ return app_instance
87
+
88
+
89
+ app = create_app()