AI Engineering · Capstone 1 of 4
Build a RAG docs assistant that cites its sources: hybrid search, streaming FastAPI and an eval gate in CI
Build a docs assistant end to end: ingest Markdown, HTML and PDF with heading-aware chunks, re-index only what changed, retrieve with BM25 + vectors + RRF and an optional reranker, answer with checked citations or refuse, stream it from FastAPI to a chat page, and gate every change on evals in CI.
⏱ 480 minAdvanced💸 Free (local models)9 milestones
Python 3.12uvOllamallama3.2:3bnomic-embed-textrank-bm25 0.2.2FastAPIServer-Sent EventspypdfBeautifulSoupsentence-transformers (optional)pytestGitHub Actions
Overview video
What you will build
A docs assistant for Pebble Queue, a made-up hosted job queue with eight pages of docs in three formats: Markdown guides, HTML reference pages (with menus and scripts that must stay out of the index) and a PDF price list. Ask it "How long are dead jobs kept?" and it streams "Dead jobs are kept for 14 days [1]." into a chat page, with [1] linking to the exact section it came from. Ask it "Who is the CEO of Pebble Queue?" and it says "I could not find that in the docs." instead of making something up.
Under the hood: ingestion that keeps sections together and remembers their heading path; an index that re-embeds only the chunks whose content changed (by SHA-256 hash); hybrid retrieval with BM25 for exact terms like PQ-1042, vectors for paraphrases, Reciprocal Rank Fusion to merge them and an optional cross-encoder reranker; an answer step that checks the citations in code and refuses when retrieval is weak or the model does not cite; a FastAPI service with a streaming /ask endpoint (Server-Sent Events) and /health; a single-file chat page; and an eval set of 25 questions (5 that must be refused) scored with recall@5, MRR, citation and refusal checks, with a regression gate that fails CI when a score drops.
How a capstone works. Every milestone gives you the requirements, the exact names the tests import, Done when checks and hints. The reference solution is folded away under each milestone. Each milestone has a test file, tests/test_m<n>.py: copy only that file from the solution into your project first (plus tests/fakes.py in milestones 3 and 5), then write your own code until it passes. The tests use fakes, so they need no model and run in about a second.
Before you start
- This capstone combines five labs. You can build it without them, but each one explains a part in depth: Your first LLM call (settings, errors), RAG from scratch (chunking, grounding, refusals), Hybrid search and reranking (BM25, RRF, cross-encoders), Streaming chat (SSE with FastAPI and
fetch) and An evals pipeline (metrics, baselines, CI). - Comfortable reading Python: dataclasses, generators (
yield) and list comprehensions. New to Python? Start with Set up Python the modern way. - About 3 GB of free disk for the two models, plus about 1 GB more if you try the optional reranker. A GitHub account for milestone 9 (optional).
Setup
S1Install uv (skip if you did lab 1)
uv installs Python for you, creates the virtual environment and manages packages: one tool instead of pyenv + venv + pip.
curl -LsSf https://astral.sh/uv/install.sh | sh
export PATH="$HOME/.local/bin:$PATH"curl -LsSf https://astral.sh/uv/install.sh | sh
export PATH="$HOME/.local/bin:$PATH"powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex" everything's installed!
S2Check uv works
The export PATH=... line makes uv work in this terminal right away. New terminal windows find it on their own (the installer added it to your shell settings). On Windows, open a new terminal after installing.
uv --version uv 0.x.y
S3Install Ollama (skip if you did lab 1)
Download it from ollama.com/download and open it once. It runs a server on port 11434 with an OpenAI-compatible API for chat (/v1/chat/completions) and embeddings (/v1/embeddings).
ollama --version ollama version is 0.x.y
S4Pull the chat model and the embedding model
llama3.2:3b (about 2 GB) writes the answers; nomic-embed-text (about 270 MB) turns text into 768 numbers for vector search. If you did the earlier labs, both are already there and this finishes at once.
ollama pull llama3.2:3b
ollama pull nomic-embed-text pulling manifest ... success pulling manifest ... success
S5Check both models answer
The first call loads the model into memory and can take 10 to 30 seconds. Later calls are much faster.
ollama run llama3.2:3b "Say hello in five words." Hello there, how are you?
Project, settings and the doc set
A uv project on Python 3.12 with every package, all settings in one place, friendly errors, and the Pebble Queue docs in `docs/`.
The data. Copy the eight files of docs/ from the solution as they are: five Markdown pages, two HTML pages and pricing-and-sla.pdf. The PDF is written as plain-text PDF source, so it copies like any text file and still opens in any PDF viewer. Do not tidy the HTML pages: their menu, script and footer are there on purpose, for milestone 2.
Create the project with uv init --python 3.12 docs-assistant, then uv add these packages: beautifulsoup4 (reads HTML), fastapi and uvicorn (the web service), numpy, openai (the SDK, which also talks to Ollama), pypdf (reads PDF text), python-dotenv and "rank-bm25==0.2.2" (BM25, pinned exactly), plus pytest as a dev dependency (uv add --dev pytest). Then add this table to pyproject.toml by hand, so tests can import config from the project folder: [tool.pytest.ini_options] with pythonpath = ["."] and testpaths = ["tests"].
config.py: a function settings() that returns a frozen dataclass Settings. Read each field from an environment variable (and .env, through python-dotenv), with these defaults:
| Field | Variable | Default |
|---|---|---|
base_url |
LLM_BASE_URL |
http://localhost:11434/v1 |
api_key |
LLM_API_KEY |
ollama |
model |
LLM_MODEL |
llama3.2:3b |
embed_model |
EMBED_MODEL |
nomic-embed-text |
rerank_model |
RERANK_MODEL |
empty (reranker off) |
docs_dir |
DOCS_DIR |
docs |
index_dir |
INDEX_DIR |
index |
min_similarity |
MIN_SIMILARITY |
0.6 (a float) |
min_rerank_score |
MIN_RERANK_SCORE |
-3.0 (a float) |
Read the environment inside settings(), not once at import time: the tests change variables and call it again.
llm.py: make_client() returns an openai.OpenAI client built from the settings, with timeout=120 and max_retries=2. friendly(err) turns an SDK exception into one sentence for the user: a timeout must contain "too long", a connection error must start with "Cannot reach", a 404 names the ollama pull commands, a 401 points at LLM_API_KEY.
uv run python --versionprintsPython 3.12.x.uv run pytest -q tests/test_m1.pypasses (4 tests).ls docslists 8 files: 5.md, 2.htmland 1.pdf.
Hints
uv init --python 3.12writes a.python-versionfile. uv then uses Python 3.12 for every command in this folder, even when a newer Python is installed.- Floats from the environment are strings:
float(os.environ.get("MIN_SIMILARITY", "0.6")). openai.APITimeoutErroris a subclass ofopenai.APIConnectionError, and Python takes the firstisinstancecheck (orexcept) that matches. Which one must come first?
Show the reference solution for milestone 1
Try it yourself first. This is one good way to do it, not the only one.
3.12 - Written by
uv init --python 3.12. Everyuv runin this folder uses Python 3.12, so your output matches this page.line 1
[project]
name = "docs-assistant"
version = "0.1.0"
requires-python = ">=3.12"
dependencies = [
"beautifulsoup4>=4.15.0",
"fastapi>=0.165.0",
"numpy>=2.5.5",
"openai>=3.60.0",
"pypdf>=7.2.0",
"python-dotenv>=1.2.4",
"rank-bm25==0.2.2",
"uvicorn>=0.55.0",
]
[dependency-groups]
dev = ["pytest>=9.2.0"]
[tool.pytest.ini_options]
pythonpath = ["."]
testpaths = ["tests"] - Pinned exactly: milestone 4 relies on its BM25 formula and its defaults (k1 = 1.5, b = 0.75).line 12
- Added by hand. pytest reads its settings from this table.line 19
- Puts the project folder on the import path, so
tests/test_m1.pycanimport config.line 20 - A plain
uv run pytestlooks only intests/.line 21
# Local models through Ollama (free). Ollama ignores the key, but the SDK needs a value.
LLM_BASE_URL=http://localhost:11434/v1
LLM_API_KEY=ollama
LLM_MODEL=llama3.2:3b
EMBED_MODEL=nomic-embed-text
# Optional cross-encoder reranker (milestone 4). Empty = off.
RERANK_MODEL=
# Where the docs and the index live
DOCS_DIR=docs
INDEX_DIR=index
# Refusal thresholds (milestone 5). Calibrate them with the evals in milestone 8.
MIN_SIMILARITY=0.6
MIN_RERANK_SCORE=-3.0 - Ollama's OpenAI-compatible API. Chat and embeddings both go here.line 2
- Empty means off. Milestone 4 shows how to turn the cross-encoder on.line 8
- The refusal thresholds of milestone 5. Milestone 8 prints the numbers you need to set them from your own data.line 15
import os
from dataclasses import dataclass
from dotenv import load_dotenv
load_dotenv() # read .env into environment variables (real env vars win)
@dataclass(frozen=True)
class Settings:
base_url: str
api_key: str
model: str
embed_model: str
rerank_model: str
docs_dir: str
index_dir: str
min_similarity: float
min_rerank_score: float
def settings() -> Settings:
env = os.environ.get
return Settings(
base_url=env("LLM_BASE_URL", "http://localhost:11434/v1"),
api_key=env("LLM_API_KEY", "ollama"),
model=env("LLM_MODEL", "llama3.2:3b"),
embed_model=env("EMBED_MODEL", "nomic-embed-text"),
rerank_model=env("RERANK_MODEL", ""),
docs_dir=env("DOCS_DIR", "docs"),
index_dir=env("INDEX_DIR", "index"),
min_similarity=float(env("MIN_SIMILARITY", "0.6")),
min_rerank_score=float(env("MIN_RERANK_SCORE", "-3.0")),
) - Copies
.envintoos.environ. Variables already set in your shell or on a server win.line 6 @dataclasswrites the constructor for you, like a Java record.frozen=Truemakes it read-only.line 9os.environ.get(name, default)isSystem.getenvwith a fallback. A short name keeps the lines below readable.line 23- Environment variables are always strings. Convert once, here, so the rest of the code gets a float.line 32
import openai
from openai import OpenAI
from config import settings
def make_client() -> OpenAI:
s = settings()
return OpenAI(base_url=s.base_url, api_key=s.api_key, timeout=120, max_retries=2)
def friendly(err: openai.OpenAIError) -> str:
"""One clear sentence for the errors you will actually hit."""
if isinstance(err, openai.APITimeoutError): # before APIConnectionError: it is a subclass
return "The model server took too long to answer. Try again, or use a smaller model."
if isinstance(err, openai.APIConnectionError):
return "Cannot reach the model server. Is Ollama running? (open the app or run: ollama serve)"
if isinstance(err, openai.NotFoundError):
s = settings()
return f"A model was not found. Run: ollama pull {s.model} and ollama pull {s.embed_model}"
if isinstance(err, openai.AuthenticationError):
return "The API key was rejected. Check LLM_API_KEY in .env"
return f"The model request failed: {err}" - A function, not a global client: tests never call it, they pass a fake client instead.line 7
- 120 seconds: a small model on a laptop CPU can be slow on a long prompt.
max_retries=2retries timeouts, 429 and 5xx with backoff.line 9 - First on purpose:
APITimeoutErroris a subclass ofAPIConnectionError, so the other order would report a slow server as "cannot reach".line 14 - Ollama answers 404 when a model was not pulled. The message gives both pull commands, because it can be either model.line 18
.venv/
__pycache__/
.env
index/
reports/ - The index is built from
docs/and can always be rebuilt: keep it out of git.reports/too: CI keeps its report as an artifact.line 4
import httpx2
import openai
from config import settings
from llm import friendly
REQ = httpx2.Request("POST", "http://test/v1/chat/completions")
def test_defaults_point_at_local_ollama(monkeypatch):
for name in ["LLM_BASE_URL", "LLM_MODEL", "EMBED_MODEL", "RERANK_MODEL", "MIN_SIMILARITY"]:
monkeypatch.delenv(name, raising=False)
s = settings()
assert s.base_url == "http://localhost:11434/v1"
assert s.model == "llama3.2:3b"
assert s.embed_model == "nomic-embed-text"
assert s.rerank_model == "" # reranker off unless you turn it on
assert s.min_similarity == 0.6
def test_environment_wins(monkeypatch):
monkeypatch.setenv("LLM_MODEL", "other-model")
monkeypatch.setenv("MIN_SIMILARITY", "0.72")
s = settings()
assert s.model == "other-model"
assert s.min_similarity == 0.72 # a float, not the string "0.72"
def test_a_timeout_is_not_reported_as_unreachable():
timeout = openai.APITimeoutError(request=REQ)
assert isinstance(timeout, openai.APIConnectionError) # why the order of the checks matters
assert "too long" in friendly(timeout)
assert "Cannot reach" in friendly(openai.APIConnectionError(request=REQ))
def test_the_doc_set_is_there():
from pathlib import Path
names = {p.name for p in Path("docs").iterdir()}
assert {"getting-started.md", "errors.html", "pricing-and-sla.pdf"} <= names
assert len(names) == 8 monkeypatchis a pytest fixture that changes the environment for one test and puts it back afterwards.line 12- The SDK's exceptions need the request that failed.
httpx2is the HTTP library inside openai 3.x, installed with it.line 7 - Documents the trap: a timeout IS a connection error, so check it first.line 31
# Getting started with Pebble Queue
Pebble Queue is a hosted queue for background jobs. Your app pushes jobs over HTTPS, and workers that you run pull them, do the work and report the result. Pebble keeps the jobs safe until a worker finishes them.
## Install the CLI
The `pebble` command-line tool works on macOS, Linux and Windows. Install it with Homebrew or npm:
```bash
brew install pebblequeue/tap/pebble
# or
npm install -g @pebblequeue/cli
```
Check the install with `pebble --version`. The CLI needs version 2.4 or newer for everything in these docs.
## Log in and create a project
Run `pebble login`. It opens your browser, and after you sign in the CLI stores a token in `~/.pebble/credentials`. Each project has its own queues, API keys and usage limits. Create one with:
```bash
pebble projects create shop-backend --region eu
```
The region is `us` or `eu` and cannot be changed later. Jobs and their payloads never leave the region you choose.
## API keys
Workers and servers use API keys, not your login token. Create a key with `pebble keys create --name worker`. A key starts with `pk_live_` (production) or `pk_test_` (test projects). Send it in the `Authorization: Bearer` header. The full key is shown only once, so store it in your secret manager. You can revoke a key at any time with `pebble keys revoke`.
## Your first job
Create a queue and push a job:
```bash
pebble queues create emails
pebble jobs push emails '{"to": "ana@example.com", "template": "welcome"}'
```
Then start a worker. The worker asks for jobs in a loop, runs your handler and acknowledges each job when it succeeds:
```bash
pebble worker --queue emails --exec ./send_email.sh
```
If the handler exits with a non-zero status, the job is retried. See Jobs and retries. - A
#line inside a code block. It is a shell comment, not a heading: milestone 2 must not split here.line 11
# Jobs and retries
A job is a JSON payload plus options. Every job moves through the states `queued`, `running`, `succeeded`, `failed` and `dead`.
## Job lifecycle
When a worker takes a job, Pebble hides it from other workers for the visibility timeout, 30 seconds by default. The worker must acknowledge the job before the timeout ends, or send a heartbeat to extend it. A job that is not acknowledged in time goes back to `queued` and another worker can take it. Set the timeout per queue with `pebble queues update emails --visibility-timeout 120`. The maximum is 12 hours.
## Retry policy
A failed job is retried automatically. By default Pebble makes up to 5 attempts in total, waiting longer before each one: 10 seconds, then 40 seconds, 160 seconds and 640 seconds (exponential backoff with a factor of 4). Every wait gets up to 20% random jitter, so many failed jobs do not all come back at the same moment.
You can change the policy per job with the `max_attempts` option (1 to 25) and the `backoff` option (`exponential`, `linear` or `fixed`).
## Dead-letter queue
After the last attempt fails, the job moves to the state `dead` and is copied to the queue's dead-letter queue, named `<queue>.dlq`. Dead jobs are kept for 14 days. You can inspect them with `pebble jobs list emails.dlq` and send them back with `pebble jobs replay emails.dlq --all`.
## Idempotency keys
Networks fail, so your app may push the same job twice. Add an `idempotency_key` when you push: Pebble keeps each key for 24 hours and returns the original job instead of creating a duplicate. Workers can also receive a job more than once, for example after a timeout, so make your handlers safe to run twice. # Scheduling jobs
Pebble can run a job later, or on a repeating schedule.
## Delayed jobs
Add `delay_seconds` when you push a job, or `run_at` with an exact time in ISO 8601 format. A job can be delayed by at most 30 days. Delayed jobs count towards your queued-jobs limit while they wait.
## Cron schedules
A schedule pushes a new job on a repeating timetable written in cron syntax with five fields: minute, hour, day of month, month and day of week.
```bash
pebble schedules create nightly-report --queue reports --cron "30 2 * * *" --payload '{"type": "daily"}'
```
Schedules run in UTC unless you set a time zone with `--timezone`, for example `--timezone Europe/Berlin`. The shortest interval allowed is one minute. If a scheduled run would start while the previous job from the same schedule is still running, Pebble skips it by default; set `--overlap allow` to run them side by side.
## Pausing a schedule
Pause a schedule with `pebble schedules pause nightly-report` and resume it with `pebble schedules resume nightly-report`. Runs that were missed while it was paused are not made up later. # Webhooks
Webhooks tell your server when something happens in Pebble, so you do not have to poll.
## Events
You can subscribe to these events: `job.succeeded`, `job.failed`, `job.dead` and `queue.backlog`. The `queue.backlog` event fires when a queue has more than the backlog threshold of waiting jobs, 1,000 by default. Add an endpoint with `pebble webhooks create --url https://example.com/hooks/pebble --events job.dead,queue.backlog`.
## Verifying signatures
Every webhook request has a `Pebble-Signature` header. It holds a timestamp and an HMAC-SHA256 signature of the timestamp and the raw request body, made with your endpoint's signing secret. Compute the same HMAC on your side and compare the two in constant time. Reject requests whose timestamp is more than 5 minutes old: that stops an attacker from replaying a request they captured.
## Delivery and retries
Your endpoint must answer with a 2xx status within 10 seconds. Any other answer, or no answer, counts as a failure. Pebble retries a failed delivery up to 8 times over about 24 hours. After 3 days of failed deliveries the endpoint is disabled and the project owners get an email. Deliveries can arrive out of order, so use the `created_at` field to order events. # Limits and quotas
Limits protect every customer from noisy neighbours. They depend on your plan.
## Payload size
A job payload can be at most 256 KB of JSON on every plan. For bigger data, upload it to your own storage and put a link in the payload.
## Rate limits
The API allows 50 requests per second per project on the Free plan, 500 on Team and 2,000 on Business. Pushing jobs in a batch counts as one request, with up to 100 jobs per batch. When you go over the limit the API answers `429 Too Many Requests` with a `Retry-After` header that says how many seconds to wait.
## Queues and retention
| Plan | Queues | Jobs per month | Job history |
| --- | --- | --- | --- |
| Free | 3 | 100,000 | 1 day |
| Team | 50 | 10 million | 7 days |
| Business | Unlimited | 100 million | 30 days |
Job history is how long finished jobs stay visible in the dashboard and the API.
## Concurrency
Each worker connection can hold at most 100 running jobs at once. There is no limit on the number of workers. <!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error codes | Pebble Queue docs</title>
<script>window.analytics = { page: "errors" };</script>
<style>table { border-collapse: collapse; }</style>
</head>
<body>
<nav><a href="/">Docs home</a> <a href="/pricing">Pricing</a> <a href="/status">Status</a></nav>
<main>
<h1>Error codes</h1>
<p>Every API error has an HTTP status and a Pebble error code in the body, for example <code>{"error": {"code": "PQ-1042", "message": "..."}}</code>. Log the code: support can find your request with it.</p>
<h2>Authentication errors</h2>
<table>
<tr><th>Code</th><th>Status</th><th>Meaning</th></tr>
<tr><td>PQ-1001</td><td>401</td><td>The API key is missing or malformed. Send it as Authorization: Bearer pk_live_...</td></tr>
<tr><td>PQ-1002</td><td>401</td><td>The API key was revoked. Create a new key with pebble keys create.</td></tr>
<tr><td>PQ-1003</td><td>403</td><td>The key belongs to another project or region.</td></tr>
</table>
<h2>Job errors</h2>
<table>
<tr><th>Code</th><th>Status</th><th>Meaning</th></tr>
<tr><td>PQ-1042</td><td>413</td><td>The job payload is larger than 256 KB. Store large data elsewhere and send a link.</td></tr>
<tr><td>PQ-1043</td><td>400</td><td>The payload is not valid JSON.</td></tr>
<tr><td>PQ-1050</td><td>409</td><td>A job with this idempotency key already exists. The response contains the original job.</td></tr>
<tr><td>PQ-1061</td><td>400</td><td>delay_seconds or run_at is more than 30 days in the future.</td></tr>
</table>
<h2>Limit errors</h2>
<table>
<tr><th>Code</th><th>Status</th><th>Meaning</th></tr>
<tr><td>PQ-2001</td><td>429</td><td>Rate limit reached. Wait for the number of seconds in the Retry-After header.</td></tr>
<tr><td>PQ-2002</td><td>402</td><td>The monthly jobs quota of your plan is used up. Upgrade, or wait for the next billing month.</td></tr>
<tr><td>PQ-2003</td><td>403</td><td>The plan's queue limit is reached. Delete a queue or upgrade.</td></tr>
</table>
</main>
<footer>Copyright Pebble Queue. All rights reserved.</footer>
</body>
</html> - Not content: milestone 2 must drop scripts, menus and footers.line 6
- Error codes are exact strings that vector search handles badly and BM25 handles well (milestone 4).line 13
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>REST API reference | Pebble Queue docs</title>
</head>
<body>
<nav><a href="/">Docs home</a> <a href="/errors">Error codes</a></nav>
<main>
<h1>REST API reference</h1>
<p>The base URL is <code>https://api.pebblequeue.dev/v1</code> for the us region and <code>https://eu.api.pebblequeue.dev/v1</code> for the eu region. Every request needs an API key in the <code>Authorization: Bearer</code> header and sends and receives JSON.</p>
<h2>Push a job</h2>
<p><code>POST /queues/{queue}/jobs</code> creates a job. The body has <code>payload</code> (any JSON value) and optional <code>delay_seconds</code>, <code>run_at</code>, <code>max_attempts</code>, <code>backoff</code> and <code>idempotency_key</code>. The answer is <code>201 Created</code> with the job, including its <code>id</code>.</p>
<pre>curl -X POST https://api.pebblequeue.dev/v1/queues/emails/jobs \
-H "Authorization: Bearer $PEBBLE_KEY" \
-d '{"payload": {"to": "ana@example.com"}}'</pre>
<h2>Push jobs in a batch</h2>
<p><code>POST /queues/{queue}/jobs:batch</code> takes a <code>jobs</code> list with up to 100 jobs and counts as one request for rate limiting. Each job in the answer has its own status, so one bad job does not fail the batch.</p>
<h2>Get a job</h2>
<p><code>GET /jobs/{id}</code> returns the job with its <code>state</code>, <code>attempts</code> and the <code>last_error</code> of the most recent failed attempt.</p>
<h2>Cancel a job</h2>
<p><code>DELETE /jobs/{id}</code> cancels a job that is still <code>queued</code>. A job that is already <code>running</code> cannot be cancelled: the answer is <code>409 Conflict</code>.</p>
<h2>Pagination</h2>
<p>List endpoints return at most 100 items per page. Pass the <code>next_cursor</code> from one answer as the <code>cursor</code> parameter of the next request. When <code>next_cursor</code> is null you have reached the last page.</p>
</main>
<footer>Copyright Pebble Queue.</footer>
</body>
</html> %PDF-1.4
1 0 obj
<< /Type /Catalog /Pages 2 0 R >>
endobj
2 0 obj
<< /Type /Pages /Kids [6 0 R 8 0 R] /Count 2 >>
endobj
3 0 obj
<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>
endobj
4 0 obj
<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Bold >>
endobj
5 0 obj
<< /Length 1462 >>
stream
BT
/F1 11 Tf
14 TL
72 740 Td
/F2 18 Tf
(Pebble Queue Pricing and Service Levels) Tj
0 -28 Td
/F1 11 Tf
(Version 2026.3, effective 1 March 2026. Prices are in US dollars and exclude tax.) Tj
0 -14 Td
0 -6 Td
0 -8 Td
/F2 13 Tf
(1 Plans and prices) Tj
0 -18 Td
/F1 11 Tf
(Free costs nothing. It includes 100,000 jobs per month, 3 queues and community support) Tj
0 -14 Td
(in the forum.) Tj
0 -14 Td
0 -6 Td
(Team costs 49 dollars per month per project. It includes 10 million jobs per month, 50) Tj
0 -14 Td
(queues and email support with an answer within one business day.) Tj
0 -14 Td
0 -6 Td
(Business costs 399 dollars per month per project. It includes 100 million jobs per) Tj
0 -14 Td
(month, unlimited queues, single sign-on \(SAML\) and priority support.) Tj
0 -14 Td
0 -6 Td
0 -8 Td
/F2 13 Tf
(1.1 Overage) Tj
0 -18 Td
/F1 11 Tf
(Team and Business projects keep working when they go over their monthly jobs. Every) Tj
0 -14 Td
(extra million jobs costs 4 dollars, billed at the end of the month. Free projects stop) Tj
0 -14 Td
(accepting new jobs with error PQ-2002 until the next month starts.) Tj
0 -14 Td
0 -6 Td
0 -8 Td
/F2 13 Tf
(1.2 Annual billing) Tj
0 -18 Td
/F1 11 Tf
(Paying for a year up front costs the price of ten months, so two months are free. Annual) Tj
0 -14 Td
(plans can be upgraded at any time; the price difference is charged for the rest of the) Tj
0 -14 Td
(year.) Tj
0 -14 Td
0 -6 Td
ET
BT
/F1 9 Tf
280 40 Td
(Page 1 of 2) Tj
ET
endstream
endobj
6 0 obj
<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << /Font << /F1 3 0 R /F2 4 0 R >> >> /Contents 5 0 R >>
endobj
7 0 obj
<< /Length 1428 >>
stream
BT
/F1 11 Tf
14 TL
72 740 Td
0 -8 Td
/F2 13 Tf
(2 Service level agreement) Tj
0 -18 Td
/F1 11 Tf
(The uptime commitment is measured per calendar month for the API. Business has a 99.95%) Tj
0 -14 Td
(commitment and Team has 99.9%. The Free plan has no SLA. Planned maintenance announced) Tj
0 -14 Td
(48 hours ahead on the status page does not count as downtime.) Tj
0 -14 Td
0 -6 Td
0 -8 Td
/F2 13 Tf
(2.1 Service credits) Tj
0 -18 Td
/F1 11 Tf
(When monthly uptime is below the commitment, the customer gets a service credit: 10% of) Tj
0 -14 Td
(the monthly fee below the commitment, and 25% when uptime is below 99.0%. Credits must) Tj
0 -14 Td
(be requested within 30 days by email to billing@pebblequeue.dev and are applied to the) Tj
0 -14 Td
(next invoice. Credits are never paid out as cash.) Tj
0 -14 Td
0 -6 Td
0 -8 Td
/F2 13 Tf
(3 Support) Tj
0 -18 Td
/F1 11 Tf
(Business support answers urgent incidents within 1 hour, 24 hours a day, 7 days a week,) Tj
0 -14 Td
(and every Business customer has a named support engineer. Team support works on business) Tj
0 -14 Td
(days and answers within one business day.) Tj
0 -14 Td
0 -6 Td
0 -8 Td
/F2 13 Tf
(4 Cancelling) Tj
0 -18 Td
/F1 11 Tf
(You can cancel at any time in the dashboard. The plan stays active until the end of the) Tj
0 -14 Td
(period you paid for. There are no refunds for partial months.) Tj
0 -14 Td
0 -6 Td
ET
BT
/F1 9 Tf
280 40 Td
(Page 2 of 2) Tj
ET
endstream
endobj
8 0 obj
<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << /Font << /F1 3 0 R /F2 4 0 R >> >> /Contents 7 0 R >>
endobj
9 0 obj
<< /Title (Pebble Queue Pricing and Service Levels) /Producer (Pebble docs) >>
endobj
xref
0 10
0000000000 65535 f
0000000009 00000 n
0000000058 00000 n
0000000121 00000 n
0000000191 00000 n
0000000266 00000 n
0000001780 00000 n
0000001916 00000 n
0000003396 00000 n
0000003532 00000 n
trailer
<< /Size 10 /Root 1 0 R /Info 9 0 R >>
startxref
3626
%%EOF - The PDF's metadata title. Milestone 2 reads it as the document title.line 150
- A numbered heading: PDFs have no heading tags, so milestone 2 finds headings by this pattern.line 50
uv init --python 3.12 docs-assistant
cd docs-assistant
uv add beautifulsoup4 fastapi numpy openai pypdf python-dotenv "rank-bm25==0.2.2" uvicorn
uv add --dev pytest
uv run python --version
uv run pytest -q tests/test_m1.py Initialized project `docs-assistant` at `.../docs-assistant` Using CPython 3.12.13 Creating virtual environment at: .venv Resolved 28 packages in 619ms Installed 26 packages in 154ms + beautifulsoup4==4.15.0 + fastapi==0.165.0 + numpy==2.5.5 + openai==3.60.0 + pypdf==7.2.0 + python-dotenv==1.2.4 + rank-bm25==0.2.2 + uvicorn==0.55.0 ... Python 3.12.13 .... [100%] 4 passed in 0.50s
settings(), so moving from your laptop to a hosted model or a server is a change to .env, never to code. And pinning Python 3.12 in .python-version makes your machine, a teammate's and CI run the same interpreter.Stuck on this milestone?
uv: command not found- Run
export PATH="$HOME/.local/bin:$PATH"(macOS and Linux), or open a new terminal so the installer's PATH change applies. uv run python --versionprints 3.13, 3.14 or 3.15- The project was created without
--python 3.12, so uv chose the newest Python it found. Runuv python pin 3.12(it writes.python-version), thenuv sync. - uv also created
main.py - uv writes a hello-world
main.py. This project does not use it: delete it. zsh: no matches foundor a file called=0.2.2appears- The package spec was not in quotes. Type it exactly as shown:
"rank-bm25==0.2.2".
Heading-aware chunks from Markdown, HTML and PDF
Turn every file into sections with a heading path, then into chunks that keep paragraphs whole and know where they came from.
Cutting text every 1,000 characters splits answers in half and throws away context. Here a chunk is a section (or part of a long one), and it carries its heading path, like Jobs and retries > Retry policy. The path is embedded and searched together with the text, so a short chunk still says what it is about, and every citation can link to the exact section.
loaders.py: two dataclasses, Section(headings: list[str], blocks: list[str]) and Document(title: str, sections: list[Section]). A block is one paragraph, list item, table row, table or code block. Also SUPPORTED = {".md", ".html", ".htm", ".pdf"} and load_document(path), which picks the parser by file suffix. Sections without blocks are dropped. The rules for each format:
parse_markdown(text, fallback_title=""): lines starting with 1 to 6#and a space are headings. A heading closes every open heading at its level or deeper, so## Installafter### On Windowsgoes back up. Blank lines separate blocks. A fenced code block (from a line starting with three backticks or~~~to the closing fence) is one block, fences included, and a#line inside it is a comment, not a heading. The title is the first heading.parse_html(html, fallback_title=""): removescript,style,nav,header,footerandnoscript. Readh1toh6,p,li,preandtrin document order, and skip an element that sits inside another one of those (apinside anliis read once, with theli). A table row becomes its cells joined with" | ". Collapse runs of spaces and newlines, except inpre. The title is theh1, else the<title>.parse_pdf(path): the title is the PDF's metadata title (else the file name). PDF text has no heading tags, so a heading is a line like2.1 Service credits: a number with optional.nparts, a space, a capital letter, no full stop, up to about 60 characters. Its level is the number of parts. Drop the title line andPage n of mfooters, and join the wrapped lines of each section back into one paragraph.
chunking.py: a frozen dataclass Chunk with id, doc (the file path relative to docs/), title, headings (a tuple), anchor and text, and three properties: source is f"{doc}#{anchor}", embed_text is the heading path joined with " > ", a blank line, then the text, and content_hash is the SHA-256 hex digest of embed_text. slugify(heading) lowercases, keeps only a-z, 0-9, spaces and hyphens, and turns spaces into - ("2.1 Service credits" gives "21-service-credits"). chunk_document(doc, document, max_chars=1200) packs whole blocks, joined by a blank line, into chunks of at most max_chars; only a single block longer than that is split, at sentence ends (and hard-cut only if one sentence is still too long). Ids are f"{doc}#{anchor}/{n}" with n from 1; a second section with the same anchor in one file gets -1 added to its anchor (examples, then examples-1).
show_chunks.py: prints the number of chunks per file and the total; with a file name as argument, it also prints every chunk of that file.
uv run pytest -q tests/test_m2.pypasses (8 tests).uv run show_chunks.pyprints one line per file and about 41 chunks in total (a different count is fine if your rules differ slightly and the tests pass).uv run show_chunks.py getting-started.mdshows the# orline inside the install code block, not as a heading of its own.- No chunk of
errors.htmlcontainswindow.analyticsorCopyright.
Hints
- Keep a stack of
(level, text)pairs. On a new heading, pop while the top level is greater than or equal to the new one, then push; the heading path is the texts on the stack. - BeautifulSoup:
soup(["script", "nav"])finds every such tag andtag.decompose()deletes it.el.find_parent([...])returns the nearest ancestor with one of those names, orNone. PdfReader(path).metadata.titlegives the title;page.extract_text().splitlines()gives the lines of a page.- To split at sentence ends and keep the punctuation:
re.split(r"(?<=[.!?])\s+", block). The(?<=...)part is a lookbehind: it matches the space after a full stop without consuming the full stop.
Show the reference solution for milestone 2
Try it yourself first. This is one good way to do it, not the only one.
import re
from dataclasses import dataclass, field
from pathlib import Path
from bs4 import BeautifulSoup
from pypdf import PdfReader
SUPPORTED = {".md", ".html", ".htm", ".pdf"}
@dataclass
class Section:
headings: list[str] # the heading path, e.g. ["Jobs and retries", "Retry policy"]
blocks: list[str] = field(default_factory=list) # paragraphs, list items, tables, code
@dataclass
class Document:
title: str
sections: list[Section]
def load_document(path: Path) -> Document:
"""Read one file into a title and a list of sections, whatever its format."""
suffix = path.suffix.lower()
if suffix == ".md":
return parse_markdown(path.read_text(encoding="utf-8"), fallback_title=path.stem)
if suffix in (".html", ".htm"):
return parse_html(path.read_text(encoding="utf-8"), fallback_title=path.stem)
if suffix == ".pdf":
return parse_pdf(path)
raise ValueError(f"unsupported file type: {path.name}")
def _open_section(sections: list[Section], stack: list[tuple[int, str]], level: int, text: str) -> None:
while stack and stack[-1][0] >= level: # a heading closes every heading at its level or deeper
stack.pop()
stack.append((level, text))
sections.append(Section([t for _, t in stack]))
MD_HEADING = re.compile(r"^(#{1,6})\s+(.+?)\s*#*\s*$")
def parse_markdown(text: str, fallback_title: str = "") -> Document:
sections: list[Section] = [Section([])] # text before the first heading
stack: list[tuple[int, str]] = []
block: list[str] = []
in_code = False
def flush():
if block:
sections[-1].blocks.append("\n".join(block).strip())
block.clear()
for line in text.splitlines():
if line.lstrip().startswith(("```", "~~~")):
block.append(line)
in_code = not in_code
if not in_code: # the closing fence ends the code block
flush()
continue
if in_code:
block.append(line) # inside code, "# comment" is not a heading
continue
m = MD_HEADING.match(line)
if m:
flush()
_open_section(sections, stack, len(m.group(1)), m.group(2))
elif not line.strip():
flush()
else:
block.append(line)
flush()
title = next((s.headings[0] for s in sections if s.headings), fallback_title)
return Document(title, [s for s in sections if s.blocks])
SKIP_TAGS = ["script", "style", "nav", "header", "footer", "noscript"]
HTML_BLOCKS = ["h1", "h2", "h3", "h4", "h5", "h6", "p", "li", "pre", "tr"]
def parse_html(html: str, fallback_title: str = "") -> Document:
soup = BeautifulSoup(html, "html.parser")
for tag in soup(SKIP_TAGS):
tag.decompose() # menus, scripts and footers are not content
sections: list[Section] = [Section([])]
stack: list[tuple[int, str]] = []
for el in (soup.main or soup.body or soup).find_all(HTML_BLOCKS):
if el.find_parent(HTML_BLOCKS):
continue # a <p> inside an <li> was already read with the <li>
if el.name[0] == "h":
_open_section(sections, stack, int(el.name[1]), " ".join(el.get_text().split()))
elif el.name == "pre":
sections[-1].blocks.append(el.get_text().strip())
elif el.name == "tr":
cells = [c.get_text(" ", strip=True) for c in el.find_all(["th", "td"])]
sections[-1].blocks.append(" | ".join(cells))
else:
sections[-1].blocks.append(" ".join(el.get_text().split())) # collapse runs of spaces and newlines
h1 = soup.find("h1")
title = h1.get_text(" ", strip=True) if h1 else (soup.title.get_text(strip=True) if soup.title else fallback_title)
return Document(title, [s for s in sections if s.blocks])
PDF_HEADING = re.compile(r"^(\d+(?:\.\d+)*)\s+([A-Z][^.]{0,60})$") # "2.1 Service credits"
PDF_FOOTER = re.compile(r"^Page \d+ of \d+$")
def parse_pdf(path: Path) -> Document:
reader = PdfReader(path)
title = (reader.metadata.title if reader.metadata else None) or path.stem
sections: list[Section] = [Section([title])]
stack: list[tuple[int, str]] = [(0, title)]
para: list[str] = []
def flush():
if para:
sections[-1].blocks.append(" ".join(para))
para.clear()
for page in reader.pages:
for line in (page.extract_text() or "").splitlines():
line = line.strip()
if not line or line == title or PDF_FOOTER.match(line):
continue
m = PDF_HEADING.match(line)
if m:
flush()
_open_section(sections, stack, m.group(1).count(".") + 1, line)
else:
para.append(line) # PDF text comes as wrapped lines: join them back into paragraphs
flush()
return Document(title, [s for s in sections if s.blocks]) - A section is a heading path plus its blocks.
field(default_factory=list)gives each section its own new list (a plain= []default would be shared by all of them).line 12 - One entry point for every format, chosen by suffix. Adding
.docxlater means one more branch here.line 23 - The heading stack: an
##closes the open##and everything below it, then becomes the new last heading.line 36 - One to six
#, a space, the text. The optional#*at the end allows the closing hashes some people write:## Install ##.line 42 startswithaccepts a tuple: either fence style. The fence lines stay in the block, so the code renders as code in the prompt.line 57- The trap this milestone tests: shell and Python comments start with
#.line 64 - Deletes the tag and everything inside it from the tree, so the loop below never sees menus or scripts.line 86
- A
<p>inside an<li>would otherwise be read twice: once as the list item, once as a paragraph.line 90 - A table row as one line:
PQ-1042 | 413 | The job payload.... The code, status and meaning stay together in one block.line 98 - A numbered heading:
2.1 Service credits.[A-Z]after the number keeps a wrapped line like10 million jobs...from looking like a heading.line 106 2is level 1,2.1is level 2: the same stack logic as Markdown.line 130- PDF text comes back as the visual lines of the page. Joining them gives the paragraph back.line 132
import hashlib
import re
from dataclasses import dataclass
from loaders import Document
@dataclass(frozen=True)
class Chunk:
id: str # "jobs-and-retries.md#retry-policy/1": unique in the index
doc: str # the file, relative to the docs folder
title: str # the document title
headings: tuple[str, ...] # the heading path
anchor: str # slug of the nearest heading, for links
text: str
@property
def source(self) -> str:
"""What eval labels and citations point at: file plus section."""
return f"{self.doc}#{self.anchor}"
@property
def embed_text(self) -> str:
"""The text that gets embedded and searched: the heading path gives the chunk its context."""
return " > ".join(self.headings) + "\n\n" + self.text
@property
def content_hash(self) -> str:
return hashlib.sha256(self.embed_text.encode("utf-8")).hexdigest()
def slugify(heading: str) -> str:
"""'2.1 Service credits' -> '21-service-credits' (the way GitHub makes heading anchors)."""
s = re.sub(r"[^a-z0-9 -]", "", heading.lower().strip())
return re.sub(r"\s+", "-", s)
def split_long(block: str, max_chars: int) -> list[str]:
"""Split one block that is too long: at sentence ends first, then hard cuts as a last resort."""
pieces, current = [], ""
for sentence in re.split(r"(?<=[.!?])\s+", block):
while len(sentence) > max_chars:
pieces.append(sentence[:max_chars])
sentence = sentence[max_chars:]
if current and len(current) + 1 + len(sentence) > max_chars:
pieces.append(current)
current = sentence
else:
current = f"{current} {sentence}" if current else sentence
if current:
pieces.append(current)
return pieces
def chunk_document(doc: str, document: Document, max_chars: int = 1200) -> list[Chunk]:
"""One chunk per section, or several when a section is longer than max_chars.
Blocks are never split unless one block alone is too long."""
chunks: list[Chunk] = []
seen: dict[str, int] = {}
for section in document.sections:
headings = tuple(section.headings) or (document.title,)
anchor = slugify(headings[-1])
seen[anchor] = seen.get(anchor, 0) + 1
if seen[anchor] > 1:
anchor = f"{anchor}-{seen[anchor] - 1}" # a second "Examples" heading becomes examples-1
parts, current = [], ""
for block in section.blocks:
for piece in [block] if len(block) <= max_chars else split_long(block, max_chars):
if current and len(current) + 2 + len(piece) > max_chars:
parts.append(current)
current = piece
else:
current = f"{current}\n\n{piece}" if current else piece
if current:
parts.append(current)
for n, text in enumerate(parts, start=1):
chunks.append(Chunk(f"{doc}#{anchor}/{n}", doc, document.title, headings, anchor, text))
return chunks - Frozen: a chunk never changes after it is made, which makes its hash safe to use as a key.line 8
- A tuple, not a list: frozen dataclasses should hold immutable values, and tuples compare and hash by value.line 13
@propertymakes a method read like a field:chunk.source, like a getter in Java. Eval labels and citations use thisfile#anchorform.line 18- What gets embedded and what BM25 indexes. The heading path adds the words a short chunk may be missing ("retry", "policy").line 23
- Milestone 3 reuses a vector when this hash is unchanged. It hashes
embed_text, so renaming a heading also counts as a change.line 28 - Only for a single block longer than
max_chars: split at sentence ends, hard-cut only a sentence that is still too long.line 38 - Pack whole blocks until the next one would not fit. A conditional expression picks the list to loop over: the block itself, or its pieces.line 68
- Two "Examples" sections in one file get different anchors, the way GitHub numbers duplicate heading anchors.line 65
import sys
from pathlib import Path
from chunking import chunk_document
from config import settings
from loaders import SUPPORTED, load_document
docs_dir = Path(settings().docs_dir)
only = sys.argv[1] if len(sys.argv) > 1 else None
total = 0
for path in sorted(p for p in docs_dir.rglob("*") if p.suffix.lower() in SUPPORTED):
rel = path.relative_to(docs_dir).as_posix()
if only and rel != only:
continue
chunks = chunk_document(rel, load_document(path))
total += len(chunks)
print(f"{rel}: {len(chunks)} chunks")
if only:
for c in chunks:
print(f"\n--- {c.id} ({len(c.text)} chars)\n{' > '.join(c.headings)}\n{c.text}")
print(f"{total} chunks in total") - Every file in
docs/and its subfolders.sortedmakes the order the same on every machine.line 11 - Forward slashes on Windows too, so ids and eval labels are the same everywhere.line 12
from pathlib import Path
from chunking import chunk_document, slugify
from loaders import load_document, parse_html, parse_markdown
MD = """# Guide
Intro paragraph.
## Install
Run this:
```bash
# not a heading: a comment inside code
pip install thing
```
### On Windows
Use the installer.
## Use it
First paragraph.
Second paragraph.
"""
def test_markdown_heading_paths_and_code_blocks():
doc = parse_markdown(MD)
assert doc.title == "Guide"
assert [s.headings for s in doc.sections] == [
["Guide"],
["Guide", "Install"],
["Guide", "Install", "On Windows"],
["Guide", "Use it"],
]
install = doc.sections[1]
assert install.blocks[0] == "Run this:"
assert install.blocks[1].startswith("```bash") and "# not a heading" in install.blocks[1]
assert install.blocks[1].endswith("```") # the code block stays in one piece
assert doc.sections[3].blocks == ["First paragraph.", "Second paragraph."]
def test_html_keeps_content_and_drops_menus_and_scripts():
html = """<html><head><title>T | Site</title><script>var x = 1;</script></head><body>
<nav>Home Pricing</nav>
<main><h1>Errors</h1><p>Every error has a
code.</p><h2>Auth</h2><table><tr><th>Code</th><th>Meaning</th></tr>
<tr><td>E1</td><td>Bad key</td></tr></table><ul><li><p>One</p></li></ul></main>
<footer>Copyright</footer></body></html>"""
doc = parse_html(html)
assert doc.title == "Errors"
assert doc.sections[0].headings == ["Errors"]
assert doc.sections[0].blocks == ["Every error has a code."]
assert doc.sections[1].headings == ["Errors", "Auth"]
assert doc.sections[1].blocks == ["Code | Meaning", "E1 | Bad key", "One"] # the <p> inside <li> once
text = str([s.blocks for s in doc.sections])
assert "var x" not in text and "Home Pricing" not in text and "Copyright" not in text
def test_pdf_numbered_headings_and_no_page_footers():
doc = load_document(Path("docs/pricing-and-sla.pdf"))
assert doc.title == "Pebble Queue Pricing and Service Levels"
paths = [s.headings for s in doc.sections]
assert [doc.title, "2 Service level agreement", "2.1 Service credits"] in paths
credits = next(s for s in doc.sections if s.headings[-1] == "2.1 Service credits")
assert "within 30 days" in credits.blocks[0]
assert "\n" not in credits.blocks[0] # wrapped PDF lines are joined back into one paragraph
assert not any("Page 1 of" in b for s in doc.sections for b in s.blocks)
def test_chunks_carry_metadata_and_stable_ids():
chunks = chunk_document("guide.md", parse_markdown(MD))
windows = chunks[2]
assert windows.id == "guide.md#on-windows/1"
assert windows.doc == "guide.md" and windows.title == "Guide"
assert windows.headings == ("Guide", "Install", "On Windows")
assert windows.source == "guide.md#on-windows"
assert windows.embed_text.startswith("Guide > Install > On Windows\n\n")
again = chunk_document("guide.md", parse_markdown(MD))
assert [c.content_hash for c in again] == [c.content_hash for c in chunks] # same input, same hashes
def test_long_sections_split_at_block_boundaries():
md = "# T\n\n" + "\n\n".join(f"Paragraph {i} " + "word " * 30 for i in range(6))
chunks = chunk_document("t.md", parse_markdown(md), max_chars=400)
assert len(chunks) > 1
assert all(len(c.text) <= 400 for c in chunks)
assert all(c.text.startswith("Paragraph") for c in chunks) # no chunk starts mid-paragraph
assert [c.id for c in chunks][:2] == ["t.md#t/1", "t.md#t/2"]
def test_one_huge_paragraph_is_split_at_sentences():
md = "# T\n\n" + " ".join(f"Sentence number {i} is here." for i in range(100))
chunks = chunk_document("t.md", parse_markdown(md), max_chars=300)
assert all(len(c.text) <= 300 for c in chunks)
assert all(c.text.endswith(".") for c in chunks)
def test_slugs_and_duplicate_headings():
assert slugify("2.1 Service credits") == "21-service-credits"
assert slugify("Push jobs in a batch") == "push-jobs-in-a-batch"
chunks = chunk_document("d.md", parse_markdown("# D\n\n## Examples\n\nA.\n\n## Examples\n\nB.\n"))
assert [c.anchor for c in chunks] == ["examples", "examples-1"]
def test_every_shipped_doc_gives_chunks():
for path in Path("docs").iterdir():
chunks = chunk_document(path.name, load_document(path))
assert chunks, path.name
assert all(c.text.strip() for c in chunks) - The heading stack and the code-block trap, on a small Markdown text written in the test.line 31
- Whitespace collapsed, table rows joined, nested
<p>read once, script, menu and footer gone.line 47 - Runs on the real PDF in
docs/.line 64 max_chars=400forces splits, so you can see the packing rule work on a small input.line 87
uv run show_chunks.py
uv run show_chunks.py pricing-and-sla.pdf api-reference.html: 6 chunks errors.html: 4 chunks getting-started.md: 5 chunks jobs-and-retries.md: 5 chunks limits-and-quotas.md: 5 chunks pricing-and-sla.pdf: 8 chunks scheduling.md: 4 chunks webhooks.md: 4 chunks 41 chunks in total pricing-and-sla.pdf: 8 chunks --- pricing-and-sla.pdf#pebble-queue-pricing-and-service-levels/1 (81 chars) Pebble Queue Pricing and Service Levels Version 2026.3, effective 1 March 2026. Prices are in US dollars and exclude tax. --- pricing-and-sla.pdf#1-plans-and-prices/1 (404 chars) Pebble Queue Pricing and Service Levels > 1 Plans and prices Free costs nothing. It includes 100,000 jobs per month, 3 queues and community support in the forum. Team costs 49 dollars per month per project. ... ... 8 chunks in total
Stuck on this milestone?
ModuleNotFoundError: No module named 'bs4'- The package is called
beautifulsoup4, the module you import isbs4. Runuv add beautifulsoup4. - The PDF gives no text at all
- Not for the shipped PDF, but common in real life: a scanned PDF is just images.
extract_text()returns an empty string, and you need OCR (for example Tesseract) before it can be indexed. Log such files instead of indexing nothing silently. UnicodeDecodeErroron Windows- Always pass
encoding="utf-8"toread_textandwrite_text. Without it Python on Windows may use an older code page. - A test fails with
assert ("Guide",) == ["Guide"] Section.headingsis a list andChunk.headingsa tuple: convert withtuple(section.headings)when you make the chunk.
An index that only re-embeds what changed
Save chunks and vectors to disk, and on every run embed only the chunks whose content is new.
Embedding is the slow part of indexing (and the paid part with a hosted model), and docs change a page at a time. So the index remembers a SHA-256 hash of every file and of every chunk's embed_text. An unchanged file is not even parsed again; in a changed file, only chunks with a new hash go to the embedding model; a deleted file's chunks disappear. A different embedding model re-embeds everything: vectors from two models live in different spaces and cannot be compared.
embedder.py (the same as lab 7): Embedder(client, model, batch_size=16) with embed(texts), which sends the texts in batches to client.embeddings.create, puts the rows back in input order by each item's index, and scales every row to length 1 (a NumPy float32 array, one row per text); embed_documents(texts) adds the prefix "search_document: " and embed_query(text) adds "search_query: " and returns one row. nomic-embed-text was trained with those prefixes.
store.py: an Index dataclass with embed_model, max_chars, doc_hashes (file to SHA-256 of its bytes), chunks, vectors (one row per chunk, same order) and chunker_version (a constant CHUNKER_VERSION = 1 you raise when you change the chunking code). save_index(index, index_dir) writes index.json (everything but the vectors) and vectors.npy, each to a temporary file first and then renamed, so a crash never leaves half an index. load_index(index_dir) returns the Index, or None if there is none.
sync_index(docs_dir, index_dir, embedder, max_chars=1200) returns a SyncReport with the lists added, changed, removed and unchanged (file names) and the counts embedded (chunks sent to the model), reused and total_chunks. The rules: a file with the same hash keeps its old chunks; a new or changed file is chunked again; a chunk whose content_hash is in the old index reuses that vector; all the other chunks go to embedder.embed_documents in one call (it batches inside); if embedder.model differs from the old index, no vector is reused; if max_chars or CHUNKER_VERSION differ, every file is chunked again (its vectors can still be reused by hash).
index_docs.py runs sync_index with the settings and prints the report. Tests use tests/fakes.py: a FakeEmbedder with the same methods, which turns text into a hashed bag of words and counts its calls. Copy it with tests/test_m3.py.
Then try it for real: run uv run index_docs.py twice, then open docs/scheduling.md, change "at most 30 days" to "at most 60 days", save, and run it a third time. Change it back afterwards (the evals in milestone 8 expect 30).
uv run pytest -q tests/test_m3.pypasses (6 tests).- The first
uv run index_docs.pyreports 8 added and every chunk embedded; the second reports8 unchangedand0 embedded. - After the edit to
docs/scheduling.md, it reports1 changedand1 embedded.
Hints
- Build a dict from
content_hashto vector from the old index first. Everything else is a lookup in it. hashlib.sha256(path.read_bytes()).hexdigest()hashes a file;os.replace(tmp, final)renames atomically, replacing the old file.- JSON has no tuples:
json.loadsgives the headings back as a list. Turn them back into a tuple when you rebuild eachChunk, or the chunks will not compare equal. np.save(path, array)andnp.load(path)store a NumPy array exactly. Name the temporary filevectors.tmp.npy:np.saveadds.npyto names that do not end in it.
Show the reference solution for milestone 3
Try it yourself first. This is one good way to do it, not the only one.
import numpy as np
DOC_PREFIX = "search_document: "
QUERY_PREFIX = "search_query: "
def normalize(v: np.ndarray) -> np.ndarray:
"""Scale every row to length 1, so a dot product is the cosine similarity."""
norms = np.linalg.norm(v, axis=-1, keepdims=True)
return v / np.where(norms == 0, 1, norms)
class Embedder:
def __init__(self, client, model: str, batch_size: int = 16):
self.client = client
self.model = model
self.batch_size = batch_size
def embed(self, texts: list[str]) -> np.ndarray:
"""One row per text, in the same order, each of length 1."""
rows = []
for start in range(0, len(texts), self.batch_size):
batch = texts[start:start + self.batch_size]
resp = self.client.embeddings.create(model=self.model, input=batch)
for item in sorted(resp.data, key=lambda d: d.index):
rows.append(item.embedding)
return normalize(np.array(rows, dtype=np.float32))
def embed_documents(self, texts: list[str]) -> np.ndarray:
return self.embed([DOC_PREFIX + t for t in texts])
def embed_query(self, text: str) -> np.ndarray:
return self.embed([QUERY_PREFIX + text])[0] - The task prefixes
nomic-embed-textwas trained with. Other models use other prefixes or none.line 3 - The length of each row, kept as a column so the division on the next line works row by row (NumPy broadcasting).line 9
- Each result carries the index of its input. Sorting by it guarantees row 5 is text 5, whatever order the server used.line 25
- A query is one text: embed a list of one and take row
[0].line 33
import hashlib
import json
import os
from dataclasses import asdict, dataclass, field
from pathlib import Path
import numpy as np
from chunking import Chunk, chunk_document
from loaders import SUPPORTED, load_document
CHUNKER_VERSION = 1 # bump when you change how chunks are made: every doc is chunked again
@dataclass
class Index:
embed_model: str
max_chars: int
doc_hashes: dict[str, str] # file -> sha256 of its bytes
chunks: list[Chunk]
vectors: np.ndarray # one row per chunk, same order
chunker_version: int = CHUNKER_VERSION
@dataclass
class SyncReport:
added: list[str] = field(default_factory=list)
changed: list[str] = field(default_factory=list)
removed: list[str] = field(default_factory=list)
unchanged: list[str] = field(default_factory=list)
embedded: int = 0 # chunks sent to the embedding model
reused: int = 0 # chunks whose vector came from the old index
total_chunks: int = 0
def file_hash(path: Path) -> str:
return hashlib.sha256(path.read_bytes()).hexdigest()
def save_index(index: Index, index_dir: Path) -> None:
index_dir.mkdir(parents=True, exist_ok=True)
meta = {
"embed_model": index.embed_model,
"max_chars": index.max_chars,
"chunker_version": index.chunker_version,
"doc_hashes": index.doc_hashes,
"chunks": [asdict(c) for c in index.chunks],
}
# write to temporary files, then rename: a crash halfway never leaves a half-written index
np.save(index_dir / "vectors.tmp.npy", index.vectors)
(index_dir / "index.tmp.json").write_text(json.dumps(meta, indent=1), encoding="utf-8")
os.replace(index_dir / "vectors.tmp.npy", index_dir / "vectors.npy")
os.replace(index_dir / "index.tmp.json", index_dir / "index.json")
def load_index(index_dir: Path) -> Index | None:
meta_path = index_dir / "index.json"
if not meta_path.exists():
return None
meta = json.loads(meta_path.read_text(encoding="utf-8"))
chunks = [Chunk(**{**c, "headings": tuple(c["headings"])}) for c in meta["chunks"]]
vectors = np.load(index_dir / "vectors.npy")
return Index(meta["embed_model"], meta["max_chars"], meta["doc_hashes"], chunks, vectors,
meta.get("chunker_version", 0))
def sync_index(docs_dir: Path, index_dir: Path, embedder, max_chars: int = 1200) -> SyncReport:
"""Bring the index in line with the docs folder, embedding only chunks it has not seen before."""
old = load_index(index_dir)
same_model = old is not None and old.embed_model == embedder.model
same_chunker = old is not None and (old.chunker_version, old.max_chars) == (CHUNKER_VERSION, max_chars)
# vectors we can reuse, by chunk content: only valid for the same embedding model
vectors = {c.content_hash: v for c, v in zip(old.chunks, old.vectors)} if same_model else {}
old_hashes = old.doc_hashes if old else {}
old_chunks: dict[str, list[Chunk]] = {}
for c in old.chunks if same_chunker else []:
old_chunks.setdefault(c.doc, []).append(c)
report = SyncReport()
chunks: list[Chunk] = []
hashes: dict[str, str] = {}
for path in sorted(p for p in docs_dir.rglob("*") if p.suffix.lower() in SUPPORTED):
rel = path.relative_to(docs_dir).as_posix()
hashes[rel] = file_hash(path)
if old_hashes.get(rel) == hashes[rel]:
report.unchanged.append(rel)
if rel in old_chunks: # same bytes, same chunker: no need to even parse the file
chunks += old_chunks[rel]
continue
else:
(report.changed if rel in old_hashes else report.added).append(rel)
chunks += chunk_document(rel, load_document(path), max_chars)
report.removed = sorted(set(old_hashes) - set(hashes))
todo = [c for c in chunks if c.content_hash not in vectors]
if todo:
new = embedder.embed_documents([c.embed_text for c in todo])
vectors.update({c.content_hash: v for c, v in zip(todo, new)})
report.embedded = len(todo)
report.reused = len(chunks) - len(todo)
report.total_chunks = len(chunks)
rows = np.array([vectors[c.content_hash] for c in chunks], dtype=np.float32)
save_index(Index(embedder.model, max_chars, hashes, chunks, rows), index_dir)
return report - Raise it when you change
chunking.pyorloaders.py: the next sync chunks every file again, because unchanged files would otherwise keep their old chunks.line 12 - File to SHA-256 of its bytes: the cheap check that skips unchanged files without parsing them.line 19
- Write both files under temporary names first...line 50
- ...then rename. A rename is atomic on one disk: a reader sees the old file or the new one, never half of one.line 52
- JSON turned the tuple into a list.
**{...}spreads the dict into keyword arguments, likeChunk(id=..., doc=...).line 61 - Vectors are reusable only for the same embedding model.line 70
- The heart of incremental indexing: every known vector, by the hash of the text it was made from.
zipwalks chunks and vector rows side by side.line 73 - Same bytes and same chunker: take the old chunks as they are.line 87
- Set difference: files the old index had and the folder no longer has.line 93
- Only these go to the model. On the second run this list is empty and no request is made at all.line 95
import sys
import time
from pathlib import Path
import openai
from config import settings
from embedder import Embedder
from llm import friendly, make_client
from store import sync_index
s = settings()
started = time.perf_counter()
try:
report = sync_index(Path(s.docs_dir), Path(s.index_dir), Embedder(make_client(), s.embed_model))
except openai.OpenAIError as err:
sys.exit(friendly(err))
for label, names in [("added", report.added), ("changed", report.changed), ("removed", report.removed)]:
for name in names:
print(f" {label:<8} {name}")
print(f"{len(report.unchanged)} unchanged, {len(report.added)} added, {len(report.changed)} changed, "
f"{len(report.removed)} removed")
print(f"{report.total_chunks} chunks: {report.embedded} embedded, {report.reused} reused "
f"({time.perf_counter() - started:.1f}s)") - Every SDK error, turned into one sentence by
friendly.sys.exit("text")prints it and exits with status 1.line 16 - Prints only what changed, then the totals.line 19
"""Fakes for the tests: no model, no network, the same answers every run."""
import hashlib
import re
from types import SimpleNamespace
import numpy as np
from embedder import normalize
DIM = 256
def bag_of_words(text: str) -> np.ndarray:
"""A stand-in embedding: each word adds 1 to one of 256 slots (chosen by a stable hash).
Texts that share words point in similar directions, which is all the tests need."""
v = np.zeros(DIM, dtype=np.float32)
for word in re.findall(r"[a-z0-9]+", text.lower()):
if word not in {"search", "document", "query"}: # ignore the nomic prefixes
v[int(hashlib.md5(word.encode()).hexdigest(), 16) % DIM] += 1
return v
class FakeEmbedder:
"""Same interface as embedder.Embedder. Counts how many texts it was asked to embed."""
def __init__(self, model: str = "fake-embed"):
self.model = model
self.calls = 0
self.texts_embedded = 0
def embed(self, texts: list[str]) -> np.ndarray:
self.calls += 1
self.texts_embedded += len(texts)
return normalize(np.array([bag_of_words(t) for t in texts]))
def embed_documents(self, texts: list[str]) -> np.ndarray:
return self.embed(texts)
def embed_query(self, text: str) -> np.ndarray:
return self.embed([text])[0]
class FakeEmbeddingsClient:
"""Looks like OpenAI().embeddings for embedder.Embedder: answers in REVERSE order, like a server may."""
def __init__(self):
self.batches = []
self.embeddings = self
def create(self, model, input):
self.batches.append(list(input))
data = [SimpleNamespace(index=i, embedding=bag_of_words(t).tolist()) for i, t in enumerate(input)]
return SimpleNamespace(data=list(reversed(data))) - A stand-in embedding: texts that share words get similar vectors. Good enough to test the plumbing, nothing like a real model.line 13
- A stable hash. Python's own
hash()of a string changes between runs, which would make the tests flaky.line 19 - The tests check these counters to prove that unchanged chunks are not embedded again.line 29
- Answers in reverse order on purpose: the test proves the embedder sorts by
index.line 53
import shutil
from pathlib import Path
import numpy as np
import pytest
from embedder import Embedder
from store import load_index, sync_index
from embedder import normalize
from tests.fakes import FakeEmbedder, FakeEmbeddingsClient, bag_of_words
@pytest.fixture
def docs(tmp_path) -> Path:
"""A copy of the shipped docs that each test may change."""
return Path(shutil.copytree("docs", tmp_path / "docs"))
def test_embedder_batches_and_keeps_the_order():
client = FakeEmbeddingsClient()
vectors = Embedder(client, "m", batch_size=2).embed_documents(["alpha", "beta", "gamma"])
assert [len(b) for b in client.batches] == [2, 1]
assert client.batches[0][0] == "search_document: alpha" # the prefix nomic-embed-text expects
assert vectors.shape == (3, 256)
assert np.allclose(np.linalg.norm(vectors, axis=1), 1.0) # every row has length 1
assert np.allclose(vectors[0], normalize(bag_of_words("alpha"))) # back in input order, not reversed
def test_first_sync_embeds_everything_and_saves(docs, tmp_path):
emb = FakeEmbedder()
report = sync_index(docs, tmp_path / "index", emb)
assert len(report.added) == 8 and report.embedded == report.total_chunks > 20
index = load_index(tmp_path / "index")
assert len(index.chunks) == report.total_chunks
assert index.vectors.shape[0] == len(index.chunks)
assert index.embed_model == "fake-embed"
def test_second_sync_embeds_nothing(docs, tmp_path):
sync_index(docs, tmp_path / "index", FakeEmbedder())
emb = FakeEmbedder()
report = sync_index(docs, tmp_path / "index", emb)
assert len(report.unchanged) == 8
assert report.embedded == 0 and emb.calls == 0
def test_editing_one_section_re_embeds_only_that_chunk(docs, tmp_path):
first = sync_index(docs, tmp_path / "index", FakeEmbedder())
page = docs / "scheduling.md"
page.write_text(page.read_text().replace("at most 30 days", "at most 60 days"))
report = sync_index(docs, tmp_path / "index", FakeEmbedder())
assert report.changed == ["scheduling.md"]
assert report.embedded == 1 # only the "Delayed jobs" chunk is new
assert report.reused == first.total_chunks - 1
index = load_index(tmp_path / "index")
assert any("60 days" in c.text for c in index.chunks)
assert not any("at most 30 days" in c.text for c in index.chunks)
def test_deleted_docs_leave_the_index(docs, tmp_path):
sync_index(docs, tmp_path / "index", FakeEmbedder())
(docs / "webhooks.md").unlink()
report = sync_index(docs, tmp_path / "index", FakeEmbedder())
assert report.removed == ["webhooks.md"]
assert not any(c.doc == "webhooks.md" for c in load_index(tmp_path / "index").chunks)
def test_a_new_embedding_model_rebuilds_every_vector(docs, tmp_path):
sync_index(docs, tmp_path / "index", FakeEmbedder("model-a"))
report = sync_index(docs, tmp_path / "index", FakeEmbedder("model-b"))
assert report.embedded == report.total_chunks # vectors from two models cannot be mixed
assert load_index(tmp_path / "index").embed_model == "model-b" - Each test gets its own copy of
docs/in a temporary folder (tmp_path), so editing or deleting files there is safe.line 16 - The key behaviour: one changed sentence, one embedded chunk.line 47
- Mixing vectors from two models would silently break search. This test makes sure it cannot happen.line 68
uv run index_docs.py
uv run index_docs.py
# now edit docs/scheduling.md: "at most 30 days" -> "at most 60 days"
uv run index_docs.py added api-reference.html added errors.html added getting-started.md added jobs-and-retries.md added limits-and-quotas.md added pricing-and-sla.pdf added scheduling.md added webhooks.md 0 unchanged, 8 added, 0 changed, 0 removed 41 chunks: 41 embedded, 0 reused (2.1s) 8 unchanged, 0 added, 0 changed, 0 removed 41 chunks: 0 embedded, 41 reused (0.1s) changed scheduling.md 7 unchanged, 0 added, 1 changed, 0 removed 41 chunks: 1 embedded, 40 reused (0.2s)
Stuck on this milestone?
A model was not found. Run: ollama pull ...- Run
ollama pull nomic-embed-text, and checkEMBED_MODELin.envmatchesollama list. - Every run embeds everything again
- Something in your hash changes between runs: an id with a counter, a timestamp, or a set (sets have no fixed order). Hash only
embed_text, and compareembed_modelexactly. - Editing one sentence re-embeds the whole file
- You compared file hashes only. Reuse vectors by chunk hash: chunk the changed file again, then look every new chunk up in the old hash-to-vector dict.
Hybrid retrieval with an optional reranker
Find the right chunks for exact terms and for paraphrases: BM25 + vectors, fused with RRF, optionally reordered by a cross-encoder.
Users ask both ways. "What does PQ-1042 mean?" needs an exact term: BM25 finds it, vector search often does not. "How long do I wait after being throttled?" shares no word with "Retry-After header": vectors find it, BM25 does not. So run both and merge the two rankings with Reciprocal Rank Fusion: every list gives each chunk 1 / (60 + rank), and the sums decide. RRF uses positions only, so the BM25 scale (0 to 30 here) and the cosine scale (0 to 1) never have to be compared.
retrieve.py:
tokenize(text): lowercase runs ofa-z0-9, minus a small stop-word list that includeswhatanddoes."What does PQ-1042 mean?"gives["pq", "1042", "mean"].rrf(rankings, k=60): a list of ranked lists in,(item, score)pairs out, best first.Hit, a dataclass:chunk,score(what the list is sorted by),bm25_score(0 when no word is shared),vector_score(the cosine) andrerank_score(defaultNone).HybridRetriever(index, embedder, reranker=None, depth=20)builds BM25 (rank_bm25.BM25Okapi) over every chunk'stokenize(embed_text)once.search(query, k=5)returns a list ofHit: the topdepthchunks by BM25 (only those with a score above 0), the topdepthby cosine (index.vectors @ embedder.embed_query(query), both have length 1), fused withrrf, cut todepth. EveryHitkeeps both raw scores: milestone 5 needs them. With a reranker, callreranker.score(query, [h.chunk.embed_text for h in hits]), store each result asrerank_scoreandscore, and sort again. Return the firstk.
rerank.py: CrossEncoderReranker(model_name, model=None) with score(query, texts) -> list[float]. Without a model it loads sentence_transformers.CrossEncoder(model_name, device="cpu"), importing it inside the function: PyTorch takes seconds to import and the tests must never load it. A cross-encoder reads the question and one chunk together and scores the pair, which is far more accurate than comparing two separate vectors, and far slower, so it only sees the 20 candidates.
The reranker is optional and lives in an extra, so the normal install, the tests and CI stay small: uv add --optional rerank "sentence-transformers>=6.3.0,<7". A plain uv sync removes extras again; use uv sync --extra rerank or uv run --extra rerank ... while you use it. Turn it on with RERANK_MODEL=cross-encoder/ms-marco-MiniLM-L6-v2 (about 90 MB, downloaded from Hugging Face on first use).
search.py: loads the index, builds the retriever (with the reranker when RERANK_MODEL is set) and prints the top 5 with their scores.
uv run pytest -q tests/test_m4.pypasses (6 tests).uv run search.py "What does PQ-1042 mean?"listserrors.html#job-errorsfirst.- Optional:
RERANK_MODEL=cross-encoder/ms-marco-MiniLM-L6-v2 uv run --extra rerank search.py "How long should I wait after a 429?"shows a rerank column, withlimits-and-quotas.md#rate-limitsfirst.
Hints
np.argsort(-scores, kind="stable")gives positions from the highest score to the lowest;stablekeeps ties in index order, so results are the same on every run.- RRF by hand for two lists
[1, 2, 3]and[3, 1, 4]: item 1 gets1/61 + 1/62, item 3 gets1/63 + 1/61, item 4 only1/63. - A query with only stop words tokenizes to
[]. Give BM25 a row of zeros then instead of calling it with nothing. - The test's fake cross-encoder only has a
predict(pairs)method, like the real one: pass it asmodel=and yourscoremust callmodel.predict([(query, text), ...]).
Show the reference solution for milestone 4
Try it yourself first. This is one good way to do it, not the only one.
import re
from dataclasses import dataclass
import numpy as np
from rank_bm25 import BM25Okapi
from chunking import Chunk
from store import Index
STOP_WORDS = {
"a", "an", "and", "are", "be", "can", "do", "does", "for", "how", "i", "in", "is", "it", "me", "my",
"not", "of", "on", "or", "the", "to", "what", "when", "where", "which", "will", "with", "you", "your",
}
def tokenize(text: str) -> list[str]:
"""Lowercase words and numbers without filler words. 'PQ-1042' becomes ['pq', '1042']."""
return [w for w in re.findall(r"[a-z0-9]+", text.lower()) if w not in STOP_WORDS]
def rrf(rankings: list[list[int]], k: int = 60) -> list[tuple[int, float]]:
"""Reciprocal Rank Fusion: every list gives each item 1 / (k + rank); add them up, best first."""
scores: dict[int, float] = {}
for ranking in rankings:
for rank, item in enumerate(ranking, start=1):
scores[item] = scores.get(item, 0.0) + 1 / (k + rank)
return sorted(scores.items(), key=lambda pair: pair[1], reverse=True)
@dataclass
class Hit:
chunk: Chunk
score: float # the score the list is sorted by: RRF, or the reranker's score when there is one
bm25_score: float # 0 when the chunk shares no word with the question
vector_score: float # cosine similarity with the question
rerank_score: float | None = None
class HybridRetriever:
def __init__(self, index: Index, embedder, reranker=None, depth: int = 20):
self.index = index
self.embedder = embedder
self.reranker = reranker
self.depth = depth
self.bm25 = BM25Okapi([tokenize(c.embed_text) for c in index.chunks])
def search(self, query: str, k: int = 5) -> list[Hit]:
if not self.index.chunks:
return []
terms = tokenize(query)
bm25 = self.bm25.get_scores(terms) if terms else np.zeros(len(self.index.chunks))
cosine = self.index.vectors @ self.embedder.embed_query(query)
by_keyword = [int(i) for i in np.argsort(-bm25, kind="stable")[:self.depth] if bm25[i] > 0]
by_vector = [int(i) for i in np.argsort(-cosine, kind="stable")[:self.depth]]
fused = rrf([by_keyword, by_vector])[:self.depth]
hits = [Hit(self.index.chunks[i], score, float(bm25[i]), float(cosine[i])) for i, score in fused]
if self.reranker is not None and hits:
scores = self.reranker.score(query, [h.chunk.embed_text for h in hits])
for h, s in zip(hits, scores):
h.rerank_score = h.score = float(s)
hits.sort(key=lambda h: h.score, reverse=True)
return hits[:k] - Filler words that would match almost every chunk. BM25 already gives common words a low weight; removing them also keeps them from counting as a "shared word" in milestone 5.line 10
- Reciprocal Rank Fusion (Cormack and others, 2009).
k = 60is the paper's value and still the usual default.line 21 - Ranks count from 1, as in the formula.
enumerategives (position, item) pairs, like a for loop with an index.line 25 - Every score survives fusion. The refusal rule in milestone 5 and the calibration table in milestone 8 both read them.line 31
- Built once per index: BM25 computes document frequencies and lengths up front.line 45
@is matrix multiplication: one dot product per chunk in a single NumPy call. All rows have length 1, so each is the cosine similarity.line 52- BM25 lists only chunks that share at least one word. Vector search always returns
depthchunks, however unrelated.line 53 - At most 20 candidates go on: to the reranker, or straight to the cut.line 55
- Chained assignment sets both.
float()turns NumPy'sfloat32into a plain Python float, which JSON can write.line 60
class CrossEncoderReranker:
"""Reads the question and each candidate together and scores how well they match (higher is better)."""
def __init__(self, model_name: str, model=None):
if model is None:
from sentence_transformers import CrossEncoder # imported here: loading PyTorch takes seconds
model = CrossEncoder(model_name, device="cpu")
self.model = model
def score(self, query: str, texts: list[str]) -> list[float]:
if not texts:
return []
return [float(s) for s in self.model.predict([(query, t) for t in texts])] - Imported here, not at the top: only a real run with the reranker on pays the seconds PyTorch takes to load.line 6
- Without it sentence-transformers picks a GPU when it finds one. For a model this small the CPU is fast and behaves the same everywhere.line 8
- One score per (question, text) pair. Raw numbers, higher is more relevant; for this model they run from about -11 to +10.line 14
[project]
name = "docs-assistant"
version = "0.1.0"
requires-python = ">=3.12"
dependencies = [
"beautifulsoup4>=4.15.0",
"fastapi>=0.165.0",
"numpy>=2.5.5",
"openai>=3.60.0",
"pypdf>=7.2.0",
"python-dotenv>=1.2.4",
"rank-bm25==0.2.2",
"uvicorn>=0.55.0",
]
[project.optional-dependencies]
rerank = [
"sentence-transformers>=6.3.0,<7",
]
[dependency-groups]
dev = ["pytest>=9.2.0"]
[tool.pytest.ini_options]
pythonpath = ["."]
testpaths = ["tests"] - Written by
uv add --optional rerank ....uv syncleaves it out;uv sync --extra rerankinstalls it.line 16 - Below 7: the next major version may change the API. It brings PyTorch (about 200 MB on a Mac, more on Linux: see Stuck).line 18
import sys
import time
from pathlib import Path
import openai
from config import settings
from embedder import Embedder
from llm import friendly, make_client
from retrieve import HybridRetriever
from store import load_index
s = settings()
index = load_index(Path(s.index_dir))
if index is None:
sys.exit("No index yet. Run: uv run index_docs.py")
reranker = None
if s.rerank_model:
from rerank import CrossEncoderReranker
reranker = CrossEncoderReranker(s.rerank_model)
retriever = HybridRetriever(index, Embedder(make_client(), s.embed_model), reranker)
query = " ".join(sys.argv[1:]) or "How many times is a failed job retried?"
started = time.perf_counter()
try:
hits = retriever.search(query, k=5)
except openai.OpenAIError as err:
sys.exit(friendly(err))
print(f"{query!r} ({(time.perf_counter() - started) * 1000:.0f} ms, reranker {'on' if reranker else 'off'})")
for n, h in enumerate(hits, start=1):
rerank = f" rerank {h.rerank_score:6.2f}" if h.rerank_score is not None else ""
print(f"{n}. {h.chunk.source:<42} bm25 {h.bm25_score:5.2f} cos {h.vector_score:.3f}{rerank}") - The reranker is loaded only when
RERANK_MODELis set, so the extra is only needed then.line 18 - A clock for measuring durations, like
System.nanoTime(). It times only the search, not loading the index.line 25
import shutil
from pathlib import Path
import numpy as np
import pytest
from rerank import CrossEncoderReranker
from retrieve import HybridRetriever, rrf, tokenize
from store import load_index, sync_index
from tests.fakes import DIM, FakeEmbedder
@pytest.fixture(scope="module")
def index(tmp_path_factory):
tmp = tmp_path_factory.mktemp("m4")
sync_index(Path("docs"), tmp / "index", FakeEmbedder())
return load_index(tmp / "index")
class ZeroEmbedder(FakeEmbedder):
"""Vector search that knows nothing: every question becomes an all-zero vector."""
def embed_query(self, text):
return np.zeros(DIM, dtype=np.float32)
def test_tokenize_splits_error_codes_and_drops_filler():
assert tokenize("What does PQ-1042 mean?") == ["pq", "1042", "mean"]
def test_rrf_by_hand():
fused = dict(rrf([[1, 2, 3], [3, 1, 4]]))
assert fused[1] == pytest.approx(1 / 61 + 1 / 62)
assert fused[3] == pytest.approx(1 / 63 + 1 / 61)
assert fused[4] == pytest.approx(1 / 63)
assert [i for i, _ in rrf([[1, 2, 3], [3, 1, 4]])][:2] == [1, 3] # found by both lists wins
def test_hits_carry_the_chunk_and_every_score(index):
hits = HybridRetriever(index, FakeEmbedder()).search("How many times is a failed job retried by default?", k=3)
assert len(hits) == 3
top = hits[0]
assert top.chunk.source == "jobs-and-retries.md#retry-policy"
assert top.bm25_score > 0 and -1.0 <= top.vector_score <= 1.0
assert top.rerank_score is None
assert [h.score for h in hits] == sorted([h.score for h in hits], reverse=True)
def test_keywords_rescue_an_exact_error_code(index):
hits = HybridRetriever(index, ZeroEmbedder()).search("PQ-1061", k=5)
assert hits[0].chunk.source == "errors.html#job-errors" # BM25 alone found it
def test_a_question_with_no_shared_words_has_no_keyword_hits(index):
hits = HybridRetriever(index, FakeEmbedder()).search("bake sourdough bread", k=5)
assert all(h.bm25_score == 0 for h in hits)
class FakeCrossEncoder:
"""Stands in for sentence_transformers.CrossEncoder: likes texts that mention 'Retry-After'."""
def predict(self, pairs):
return [5.0 if "Retry-After" in text else -5.0 for _, text in pairs]
def test_the_reranker_reorders_and_sets_rerank_scores(index):
reranker = CrossEncoderReranker("unused", model=FakeCrossEncoder())
hits = HybridRetriever(index, FakeEmbedder(), reranker).search("how long should I wait", k=5)
assert "Retry-After" in hits[0].chunk.text
assert hits[0].rerank_score == hits[0].score == 5.0
assert all(h.rerank_score is not None for h in hits) - One index for every test in this file: built once with the fake embedder, read by all.line 13
- Vector search that knows nothing. If
PQ-1061still comes first, BM25 found it on its own.line 20 - Has only
predict, like the realCrossEncoder. No PyTorch, no download.line 59
uv run search.py "What does PQ-1042 mean?"
uv add --optional rerank "sentence-transformers>=6.3.0,<7"
RERANK_MODEL=cross-encoder/ms-marco-MiniLM-L6-v2 uv run --extra rerank search.py "How long should I wait after a 429?" 'What does PQ-1042 mean?' (35 ms, reranker off) 1. errors.html#job-errors bm25 6.71 cos 0.712 2. errors.html#error-codes bm25 6.84 cos 0.688 3. errors.html#authentication-errors bm25 3.27 cos 0.655 4. errors.html#limit-errors bm25 3.21 cos 0.651 5. limits-and-quotas.md#payload-size bm25 0.00 cos 0.640 Resolved 61 packages in 1.2s + sentence-transformers==6.3.0 + torch==2.15.0 ... 'How long should I wait after a 429?' (712 ms, reranker on) 1. limits-and-quotas.md#rate-limits bm25 5.90 cos 0.701 rerank 0.96 2. errors.html#limit-errors bm25 7.06 cos 0.662 rerank 0.30 3. jobs-and-retries.md#retry-policy bm25 1.61 cos 0.645 rerank -5.60 4. scheduling.md#delayed-jobs bm25 2.26 cos 0.610 rerank -6.24 5. webhooks.md#delivery-and-retries bm25 1.46 cos 0.598 rerank -7.75
nomic-embed-text they mostly fall between about 0.5 and 0.85). The rerank column spreads them out: about +1 for the chunk that answers the question, -5 and lower for the rest. That spread is why a reranker is the better signal for refusing, in the next milestone.Stuck on this milestone?
- Linux: installing the reranker downloads gigabytes
- PyTorch from PyPI for Linux includes GPU libraries. Lab 7 shows the
[tool.uv.sources]setting that installs the CPU-only build from download.pytorch.org instead: Hybrid search and reranking. ModuleNotFoundError: No module named 'sentence_transformers'- You ran
uv sync(which removes extras) oruv runwithout--extra rerank. Runuv sync --extra rerank, or leaveRERANK_MODELempty. - Intel Mac:
torchhas no wheel for this platform - PyTorch stopped publishing Intel Mac builds after version 2.2. Leave the reranker off: everything else works without it.
- The first reranked search takes 30 seconds
- The model downloads from Hugging Face the first time, then loads from
~/.cache/huggingface. Later runs take about a second to load and well under a second to search.
Answers with checked citations, and a refusal path
Answer from the retrieved chunks only, prove it with [n] citations checked in code, and refuse when the docs do not have the answer.
A small local model will break the rules in the prompt. On the maintainer's Mac, llama3.2:3b sometimes answered from general knowledge after a search, asked the user a question instead of answering, cited a source number that did not exist, or wrote the refusal sentence and then answered anyway. So the rules are enforced in code, in layers: a retrieval check before the model is called, citation checks after it answers, one retry with a reminder (a "nudge") when the answer has no valid citation, and a refusal when the retry fails too.
answer.py:
REFUSAL = "I could not find that in the docs.", exactly.build_messages(question, hits): a system message with the rules (cite every fact as[n], use only the sources, reply with exactlyREFUSALwhen they do not answer, do not ask the user questions), then one user message:"Sources:\n\n", one block per hit,"[n] <heading path joined with ' > '> (<doc>)\n<text>", joined by blank lines, and finally"\n\nQuestion: <question>".weak_retrieval(hits, min_similarity, min_rerank_score):Truewhen there are no hits; when the top hit has arerank_score,Trueif it is belowmin_rerank_score; otherwiseTrueonly if the best cosine is belowmin_similarityand no hit shares a word with the question (bm25_score > 0).cited_numbers(text): every number in[2]or[1, 3]markers, in order of first appearance, without repeats.drop_invalid_citations(text, n_sources): removes numbers outside 1..n, and a marker left empty disappears with the space before it ("Made up [8]."becomes"Made up.").- Dataclasses
Citation(n, source, title, section, url), wheresectionis the heading path below the title joined with" > "(empty for the text before the first subheading) andurlisf"/files/{doc}#{anchor}", andAnswer(text, citations=[], refused=False, reason="", attempts=0). check(text, hits, attempts) -> Answer: the refusal sentence anywhere in the text (ignoring case) givesrefused=True,reason="model refused"andtext=REFUSAL; otherwise drop invalid citations; no valid number left givesreason="no valid citation"; otherwise oneCitationper cited number, in order.
The Assistant class: Assistant(retriever, client, model, k=5, min_similarity=0.6, min_rerank_score=-3.0, max_tokens=400). Its events(question) is a generator of dicts: search; if weak_retrieval, yield only {"type": "final", "answer": Answer(REFUSAL, [], True, "weak retrieval", 0)} and stop, without a model call; otherwise stream the answer (stream=True, temperature=0.1), yielding {"type": "token", "text": ...} per piece, then check it. If the reason is "no valid citation" on the first attempt, yield {"type": "reset"}, add the model's answer as an assistant message and the reminder NUDGE as a user message, and stream once more. End with {"type": "final", "answer": <Answer>}. ask(question) runs the same events and returns the final Answer: one code path for the CLI, the API and the evals.
factory.py: build_assistant(s=None) wires the real pieces from the settings (index, client, embedder, reranker if RERANK_MODEL is set) and raises FileNotFoundError("No index yet. Run: uv run index_docs.py") when there is no index. ask.py: streams one answer to the terminal and prints the sources, or the refusal and its reason. tests/fakes.py grows a FakeChat that streams scripted replies: copy the new version too.
uv run pytest -q tests/test_m5.pypasses (10 tests).uv run ask.py "How long are dead jobs kept?"streams an answer that mentions 14 days with a[n]marker, then aSources:list withjobs-and-retries.md#dead-letter-queue.uv run ask.py "What is the capital of Australia?"printsRefused (weak retrieval)orRefused (model refused), never an answer.
Hints
- A regex for one marker:
\[(\d+(?:\s*,\s*\d+)*)\].findallreturns the inside of each, like"1, 3". - For
drop_invalid_citations,re.subaccepts a function as the replacement: it gets each match and returns the new text. Capture the whitespace before the marker in its own group, so you can drop it together with an empty marker. - A generator can
yieldinside aforloop over another generator. Keep the streamed text in a variable while you yield its pieces, thencheckthe whole text. - Streaming chunks:
chunk.choices[0].delta.content. Some servers end with a chunk that has no choices at all, and the first chunk often has empty content: skip both.
Show the reference solution for milestone 5
Try it yourself first. This is one good way to do it, not the only one.
import re
from collections.abc import Iterator
from dataclasses import dataclass, field
from retrieve import Hit
REFUSAL = "I could not find that in the docs."
SYSTEM = f"""You answer questions about Pebble Queue using ONLY the numbered sources you are given.
Rules:
- Every sentence with a fact must end with the number of its source in square brackets, like [1] or [2][3].
- Use only facts that are written in the sources. Do not use anything else you know.
- If the sources do not answer the question, reply with exactly: {REFUSAL}
- Do not ask the user questions. Answer in at most four sentences."""
NUDGE = f"""Your answer had no valid citation. Answer again using only the sources above, \
and end each sentence with its source number in square brackets, like [1]. \
If the sources do not contain the answer, reply with exactly: {REFUSAL}"""
CITATION = re.compile(r"\[(\d+(?:\s*,\s*\d+)*)\]") # [1] or [1, 3]
@dataclass
class Citation:
n: int # the number used in the answer text
source: str # "jobs-and-retries.md#retry-policy"
title: str
section: str # the heading path below the title, "" for the text before the first subheading
url: str # where the chat page links to
@dataclass
class Answer:
text: str
citations: list[Citation] = field(default_factory=list)
refused: bool = False
reason: str = "" # why it refused: "weak retrieval", "model refused" or "no valid citation"
attempts: int = 0 # model calls made: 0, 1 or 2
def build_messages(question: str, hits: list[Hit]) -> list[dict]:
"""The system rules, then the sources numbered from 1, then the question."""
blocks = []
for n, h in enumerate(hits, start=1):
blocks.append(f"[{n}] {' > '.join(h.chunk.headings)} ({h.chunk.doc})\n{h.chunk.text}")
user = "Sources:\n\n" + "\n\n".join(blocks) + f"\n\nQuestion: {question}"
return [{"role": "system", "content": SYSTEM}, {"role": "user", "content": user}]
def weak_retrieval(hits: list[Hit], min_similarity: float, min_rerank_score: float) -> bool:
"""True when nothing retrieved looks relevant enough to be worth a model call."""
if not hits:
return True
if hits[0].rerank_score is not None: # a cross-encoder score is the most reliable signal
return hits[0].rerank_score < min_rerank_score
best_cosine = max(h.vector_score for h in hits)
shares_a_word = any(h.bm25_score > 0 for h in hits)
return best_cosine < min_similarity and not shares_a_word
def cited_numbers(text: str) -> list[int]:
"""Every number cited in the text, in order of first appearance, without repeats."""
seen: list[int] = []
for group in CITATION.findall(text):
for n in (int(x) for x in group.split(",")):
if n not in seen:
seen.append(n)
return seen
def drop_invalid_citations(text: str, n_sources: int) -> str:
"""Remove citation numbers that point at no source: [2, 9] with 5 sources becomes [2]; [9] disappears."""
def keep(m: re.Match) -> str:
valid = [x.strip() for x in m.group(2).split(",") if 1 <= int(x) <= n_sources]
return f"{m.group(1)}[{', '.join(valid)}]" if valid else "" # drop it with the space before it
return re.sub(r"(\s*)" + CITATION.pattern, keep, text).strip()
def is_refusal(text: str) -> bool:
return REFUSAL.lower().rstrip(".") in " ".join(text.lower().split())
def check(text: str, hits: list[Hit], attempts: int) -> Answer:
"""Turn the model's text into an Answer, enforcing the rules in code instead of trusting the model."""
if is_refusal(text):
return Answer(REFUSAL, [], True, "model refused", attempts)
clean = drop_invalid_citations(text, len(hits))
numbers = cited_numbers(clean)
if not numbers: # general knowledge, a question back to the user, or citations that point nowhere
return Answer(REFUSAL, [], True, "no valid citation", attempts)
citations = []
for n in numbers:
c = hits[n - 1].chunk
section = " > ".join(c.headings[1:])
citations.append(Citation(n, c.source, c.title, section, f"/files/{c.doc}#{c.anchor}"))
return Answer(clean, citations, False, "", attempts)
class Assistant:
def __init__(self, retriever, client, model: str, k: int = 5, min_similarity: float = 0.6,
min_rerank_score: float = -3.0, max_tokens: int = 400):
self.retriever = retriever
self.client = client
self.model = model
self.k = k
self.min_similarity = min_similarity
self.min_rerank_score = min_rerank_score
self.max_tokens = max_tokens
def _stream(self, messages: list[dict]) -> Iterator[str]:
stream = self.client.chat.completions.create(
model=self.model, messages=messages, temperature=0.1, max_tokens=self.max_tokens, stream=True)
for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
yield chunk.choices[0].delta.content
def events(self, question: str) -> Iterator[dict]:
"""The whole answer as events: token ..., maybe reset and tokens again, then final."""
hits = self.retriever.search(question, self.k)
if weak_retrieval(hits, self.min_similarity, self.min_rerank_score):
yield {"type": "final", "answer": Answer(REFUSAL, [], True, "weak retrieval", 0)}
return
messages = build_messages(question, hits)
for attempt in (1, 2):
text = ""
for token in self._stream(messages):
text += token
yield {"type": "token", "text": token}
answer = check(text, hits, attempt)
if answer.reason == "no valid citation" and attempt == 1:
yield {"type": "reset"} # the page clears what it showed: a second, nudged try follows
messages = messages + [{"role": "assistant", "content": text}, {"role": "user", "content": NUDGE}]
continue
yield {"type": "final", "answer": answer}
return
def ask(self, question: str) -> Answer:
"""The same pipeline without streaming: run the events and keep the final answer."""
for event in self.events(question):
if event["type"] == "final":
return event["answer"]
raise RuntimeError("the pipeline ended without a final event") - One exact sentence, used in the prompt, in the checks and by the evals. Exact strings are easy to detect; "I am not sure, but..." is not.line 7
- The rules for the model. They lower the error rate; the code below catches what is left.line 9
- Small models like to answer with a question ("Which plan are you on?"). It has no citation, so the code would nudge and then refuse it anyway; saying it here saves a model call.line 14
- The one reminder for an uncited answer. Repeating the rule right after a mistake works far better on small models than a longer system prompt.line 16
[1]or[1, 3].(?:...)groups without capturing;*allows any number of extra, nparts.line 20- Each source starts with its number, its heading path and its file: the model cites the number, the code maps it back to the chunk.line 45
- Layer 1: do not call the model when retrieval found nothing relevant. Cheaper, faster, and the model never gets a chance to answer from memory.line 50
- With a reranker its score decides: it reads the question and the chunk together. Milestone 8 shows why -3 is the default.line 54
- Without a reranker, refuse only when BOTH signals are weak. Real cosine scores are bunched, so a cosine threshold alone either lets weak chunks through or refuses good questions.line 58
- A
[7]with five sources points nowhere: remove it rather than show a broken link.line 71 - Group 1 is the whitespace before the marker. A kept marker keeps it; a removed one takes it along.line 76
- Contains, not equals: small models often add a sentence after the refusal. Lowercase and collapsed spaces make the check forgiving.line 81
- The text becomes exactly
REFUSAL: whatever the model added after it is not shown.line 88 - Layer 2: no valid citation means no evidence. General knowledge, a question back to the user, or citations that point nowhere all end here.line 91
- The link milestone 7 serves: the original file, at the section's anchor.line 97
- A generator: it yields each piece of text as it arrives. The
ifskips the empty first chunk and a final chunk with no choices.line 112 attemptsis 0: the model was never called.line 123- Layer 3: at most two model calls per question. A loop with a fixed limit, never "until it works".line 126
- Tells the client to clear what it showed: the first answer is being replaced.line 133
- The model sees its own uncited answer, then the reminder.
+builds a new list, so the first request (kept by the test fake) is not changed.line 134 - The non-streaming version is the same pipeline: the CLI, the API and the evals cannot drift apart.line 139
from pathlib import Path
from answer import Assistant
from config import Settings, settings
from embedder import Embedder
from llm import make_client
from retrieve import HybridRetriever
from store import load_index
def build_assistant(s: Settings | None = None) -> Assistant:
"""Wire the real pieces together from the settings. Tests build an Assistant from fakes instead."""
s = s or settings()
index = load_index(Path(s.index_dir))
if index is None:
raise FileNotFoundError("No index yet. Run: uv run index_docs.py")
client = make_client()
reranker = None
if s.rerank_model:
from rerank import CrossEncoderReranker # only when it is turned on: it needs the rerank extra
reranker = CrossEncoderReranker(s.rerank_model)
retriever = HybridRetriever(index, Embedder(client, s.embed_model), reranker)
return Assistant(retriever, client, s.model, min_similarity=s.min_similarity,
min_rerank_score=s.min_rerank_score) - The only place that knows about real clients and files. Everything it builds takes its dependencies as arguments, which is what lets the tests use fakes.line 11
- Imported only when
RERANK_MODELis set, so a normal install never needs the extra.line 20 - One client for chat and embeddings: both go to the same server.line 23
import sys
import openai
from factory import build_assistant
from llm import friendly
question = " ".join(sys.argv[1:]) or "How many times is a failed job retried?"
answer = None
streamed = False
try:
assistant = build_assistant()
for event in assistant.events(question):
if event["type"] == "token":
print(event["text"], end="", flush=True)
streamed = True
elif event["type"] == "reset":
print("\n[no valid citation: asking again with a reminder]\n")
elif event["type"] == "final":
answer = event["answer"]
except FileNotFoundError as err:
sys.exit(str(err))
except openai.OpenAIError as err:
sys.exit(friendly(err))
print("\n\n" if streamed else "", end="")
if answer.refused:
print(f"Refused ({answer.reason}): {answer.text}")
else:
print("Sources:")
for c in answer.citations:
where = f"{c.title} > {c.section}" if c.section else c.title
print(f" [{c.n}] {where} ({c.source})") end=""stopsprintfrom adding a newline;flush=Trueshows each piece at once instead of when the buffer fills.line 15- In a terminal you cannot erase what was printed, so it says what happened instead.line 17
- A blank line after streamed text; nothing when the answer was refused before any token.line 26
- No index yet:
build_assistantsays which command to run.line 21
"""Fakes for the tests: no model, no network, the same answers every run."""
import hashlib
import re
from types import SimpleNamespace
import numpy as np
from embedder import normalize
DIM = 256
def bag_of_words(text: str) -> np.ndarray:
"""A stand-in embedding: each word adds 1 to one of 256 slots (chosen by a stable hash).
Texts that share words point in similar directions, which is all the tests need."""
v = np.zeros(DIM, dtype=np.float32)
for word in re.findall(r"[a-z0-9]+", text.lower()):
if word not in {"search", "document", "query"}: # ignore the nomic prefixes
v[int(hashlib.md5(word.encode()).hexdigest(), 16) % DIM] += 1
return v
class FakeEmbedder:
"""Same interface as embedder.Embedder. Counts how many texts it was asked to embed."""
def __init__(self, model: str = "fake-embed"):
self.model = model
self.calls = 0
self.texts_embedded = 0
def embed(self, texts: list[str]) -> np.ndarray:
self.calls += 1
self.texts_embedded += len(texts)
return normalize(np.array([bag_of_words(t) for t in texts]))
def embed_documents(self, texts: list[str]) -> np.ndarray:
return self.embed(texts)
def embed_query(self, text: str) -> np.ndarray:
return self.embed([text])[0]
class FakeEmbeddingsClient:
"""Looks like OpenAI().embeddings for embedder.Embedder: answers in REVERSE order, like a server may."""
def __init__(self):
self.batches = []
self.embeddings = self
def create(self, model, input):
self.batches.append(list(input))
data = [SimpleNamespace(index=i, embedding=bag_of_words(t).tolist()) for i, t in enumerate(input)]
return SimpleNamespace(data=list(reversed(data)))
def stream_of(text: str):
"""What client.chat.completions.create(stream=True) returns: chunks with a delta each.
The last chunk has no choices at all, like the usage chunk some servers send."""
pieces = re.findall(r"\S+\s*", text)
chunks = [SimpleNamespace(choices=[SimpleNamespace(delta=SimpleNamespace(content=p))]) for p in pieces]
return iter(chunks + [SimpleNamespace(choices=[])])
class FakeChat:
"""Looks like OpenAI() to the Assistant. Plays the scripted replies in order and records each request.
A reply that is an exception is raised instead, like a server that is down."""
def __init__(self, *replies):
self.replies = list(replies)
self.requests: list[dict] = []
self.chat = SimpleNamespace(completions=self)
def create(self, **kwargs):
self.requests.append(kwargs)
if not self.replies:
raise AssertionError("the model was called more times than the test expected")
reply = self.replies.pop(0)
if isinstance(reply, Exception):
raise reply
return stream_of(reply) - What
create(stream=True)returns: an iterator of chunks withchoices[0].delta.content.SimpleNamespacemakes an object with any attributes you name, like an anonymous class.line 56 - The last chunk has no choices, like the usage chunk some servers send. Your code must skip it.line 61
- Scripted replies, played in order. It records every request, so tests can check what was sent, like the nudge.line 64
- A
FakeChat()with no replies proves the model is never called: any call fails the test.line 76
from answer import NUDGE, REFUSAL, Assistant, build_messages, check, cited_numbers, drop_invalid_citations
from chunking import Chunk
from retrieve import Hit
from tests.fakes import FakeChat
def hit(doc, headings, text, bm25=3.0, cosine=0.8, rerank=None):
anchor = headings[-1].lower().replace(" ", "-")
chunk = Chunk(f"{doc}#{anchor}/1", doc, headings[0], tuple(headings), anchor, text)
return Hit(chunk, 0.03, bm25, cosine, rerank)
RETRY = hit("jobs-and-retries.md", ["Jobs and retries", "Retry policy"], "Pebble makes up to 5 attempts in total.")
DLQ = hit("jobs-and-retries.md", ["Jobs and retries", "Dead-letter queue"], "Dead jobs are kept for 14 days.")
class FixedRetriever:
def __init__(self, hits):
self.hits = hits
self.queries = []
def search(self, query, k=5):
self.queries.append(query)
return self.hits[:k]
def assistant(chat, hits=(RETRY, DLQ)):
return Assistant(FixedRetriever(list(hits)), chat, "test-model")
def test_the_prompt_numbers_the_sources():
messages = build_messages("How many attempts?", [RETRY, DLQ])
assert messages[0]["role"] == "system" and REFUSAL in messages[0]["content"]
user = messages[1]["content"]
assert "[1] Jobs and retries > Retry policy (jobs-and-retries.md)\nPebble makes up to 5" in user
assert "[2] Jobs and retries > Dead-letter queue" in user
assert user.endswith("Question: How many attempts?")
def test_citation_parsing():
assert cited_numbers("A [2]. B [1, 2]. C [3][1].") == [2, 1, 3]
assert drop_invalid_citations("Five attempts [1][7]. Kept [2, 9].", 2) == "Five attempts [1]. Kept [2]."
assert drop_invalid_citations("Made up [8].", 2) == "Made up."
def test_a_cited_answer_streams_and_maps_citations():
chat = FakeChat("A failed job gets up to 5 attempts [1]. Then it is dead [2].")
events = list(assistant(chat).events("How many attempts?"))
assert [e["type"] for e in events[:-1]] == ["token"] * (len(events) - 1)
answer = events[-1]["answer"]
assert "".join(e["text"] for e in events[:-1]) == answer.text
assert not answer.refused and answer.attempts == 1
assert [c.source for c in answer.citations] == ["jobs-and-retries.md#retry-policy",
"jobs-and-retries.md#dead-letter-queue"]
assert answer.citations[0].url == "/files/jobs-and-retries.md#retry-policy"
assert chat.requests[0]["stream"] is True and chat.requests[0]["model"] == "test-model"
def test_an_uncited_answer_gets_one_nudge():
chat = FakeChat("Usually jobs are retried three times.", "Up to 5 attempts [1].")
events = list(assistant(chat).events("How many attempts?"))
assert {"type": "reset"} in events
second = chat.requests[1]["messages"]
assert second[-2] == {"role": "assistant", "content": "Usually jobs are retried three times."}
assert second[-1] == {"role": "user", "content": NUDGE}
answer = events[-1]["answer"]
assert answer.text == "Up to 5 attempts [1]." and answer.attempts == 2
def test_still_uncited_after_the_nudge_means_refusal():
chat = FakeChat("Which plan are you on?", "Could you tell me more about your setup?")
answer = assistant(chat).ask("How many attempts?")
assert answer.refused and answer.reason == "no valid citation"
assert answer.text == REFUSAL and answer.citations == [] and len(chat.requests) == 2
def test_the_model_can_refuse_and_is_not_nudged():
chat = FakeChat(f"{REFUSAL} But in general, queues retry jobs.")
answer = assistant(chat).ask("What is the CEO's name?")
assert answer.refused and answer.reason == "model refused" and len(chat.requests) == 1
def test_weak_retrieval_refuses_without_calling_the_model():
weak = hit("scheduling.md", ["Scheduling jobs", "Cron schedules"], "Cron text.", bm25=0.0, cosine=0.41)
chat = FakeChat() # no replies: any model call fails the test
answer = assistant(chat, [weak]).ask("How do I bake bread?")
assert answer.refused and answer.reason == "weak retrieval" and answer.attempts == 0
assert assistant(FakeChat(), []).ask("anything").reason == "weak retrieval" # nothing found at all
def test_one_shared_word_or_a_high_similarity_is_enough_to_try():
keyword_only = hit("errors.html", ["Error codes", "Job errors"], "PQ-1061 ...", bm25=4.2, cosine=0.3)
assert not assistant(FakeChat("PQ-1061 means too far ahead [1]."), [keyword_only]).ask("PQ-1061?").refused
similar_only = hit("webhooks.md", ["Webhooks", "Events"], "...", bm25=0.0, cosine=0.75)
assert not assistant(FakeChat("It fires at 1,000 jobs [1]."), [similar_only]).ask("backlog alert?").refused
def test_a_reranker_score_decides_when_there_is_one():
low = hit("webhooks.md", ["Webhooks", "Events"], "...", bm25=5.0, cosine=0.9, rerank=-7.5)
assert assistant(FakeChat(), [low]).ask("q").reason == "weak retrieval"
def test_check_on_its_own():
answer = check("Kept for 14 days [2].", [RETRY, DLQ], attempts=1)
assert answer.citations[0].n == 2 and answer.citations[0].section == "Dead-letter queue" - Not the real retriever: it returns exactly the hits the test wants, so the answer logic is tested on its own.line 17
- The general-knowledge answer of a small model, then a cited one after the nudge.line 59
- The clarifying-question habit of small models: no citation, so nudge, then refuse.line 71
- Off-topic and nothing shared: refused with zero model calls.line 83
uv run ask.py "How long are dead jobs kept?"
uv run ask.py "What is the capital of Australia?"
uv run ask.py "Who is the CEO of Pebble Queue?" Dead jobs are kept for 14 days in the dead-letter queue [1]. You can replay them with pebble jobs replay [1]. Sources: [1] Jobs and retries > Dead-letter queue (jobs-and-retries.md#dead-letter-queue) Refused (weak retrieval): I could not find that in the docs. I could not find that in the docs. Refused (model refused): I could not find that in the docs.
Stuck on this milestone?
- Every answer is refused with
no valid citation - Look at the streamed text: the model may write
[Source 1],(1)or【1】. Make the example in the system prompt clearer, or accept that form inCITATIONtoo. Count it in the evals before and after. - Answers cite [1] but the fact is not in source 1
- Citations prove the model pointed somewhere, not that it read correctly. The
factscheck in milestone 8 catches wrong facts; an LLM judge (lab 12) catches unsupported claims. - An answerable question is refused with
weak retrieval - Print the scores with
uv run search.py "...". With the reranker on, the toprerank_scorewas belowMIN_RERANK_SCORE: milestone 8 shows how to pick it from your eval questions instead of guessing. - The answer never stops, or is cut off
max_tokens=400caps it. A cut-off answer may lose its last citation; keep the instruction "at most four sentences" in the system prompt.
A FastAPI service: streaming /ask and /health
Serve the assistant over HTTP: answers stream as Server-Sent Events, and a health endpoint reports the index.
app.py, a FastAPI app named app:
GET /healthreturns200and{"status": "ok", "docs": 8, "chunks": 41, "model": ..., "embed_model": ..., "reranker": false}, read from the assistant's index, without calling any model. With no index yet it returns503with adetailthat containsindex_docs.py.POST /asktakes the JSON body{"question": "..."}. The question is trimmed and must be 1 to 500 characters, or FastAPI answers422before any work is done. The response has the typetext/event-streamand the headersCache-Control: no-cacheandX-Accel-Buffering: no. Each event fromAssistant.eventsis sent as one Server-Sent Event:data: <JSON>and an empty line. The final event's answer becomes a JSON object (text,citationsas a list of objects withn,source,title,section,url, thenrefused,reason,attempts).- A model error in the middle of a stream becomes the event
{"type": "error", "message": friendly(err)}: the200status was sent with the first byte, so the error has to travel inside the stream. - The assistant comes from a dependency function
get_assistant(), cached withfunctools.cacheand turningFileNotFoundErrorinto the503. Tests replace it withapp.dependency_overrides[get_assistant].
The endpoint and the event generator are plain def, not async def, because the OpenAI client and the retriever block. Starlette runs a synchronous body iterator in a worker thread (iterate_in_threadpool), and FastAPI runs a def endpoint in one too, so a slow model call never blocks the server's event loop. Run it with uv run uvicorn app:app --port 8000, and use curl -N in a second terminal (-N turns off curl's own buffering).
uv run pytest -q tests/test_m6.pypasses (9 tests).curl -s localhost:8000/healthprints the JSON with"status":"ok"and"chunks":41.curl -N -X POST localhost:8000/ask -H "content-type: application/json" -d '{"question": "How long are dead jobs kept?"}'printsdata:lines one by one, the last one afinalevent with citations.
Hints
StreamingResponse(generator(), media_type="text/event-stream", headers={...})sends each string the generator yields as soon as it is yielded.json.dumps(event, default=asdict):defaultis called for objects JSON cannot write, anddataclasses.asdictturns a dataclass (and the dataclasses inside it) into dicts.Annotated[str, StringConstraints(strip_whitespace=True, min_length=1, max_length=500)]from Pydantic makes" "fail validation too.functools.cachedoes not cache a call that raised, so once the index exists the next request builds the assistant.
Show the reference solution for milestone 6
Try it yourself first. This is one good way to do it, not the only one.
import json
from dataclasses import asdict
from functools import cache
from typing import Annotated
import openai
from fastapi import Depends, FastAPI, HTTPException
from fastapi.responses import StreamingResponse
from pydantic import BaseModel, StringConstraints
from answer import Assistant
from factory import build_assistant
from llm import friendly
app = FastAPI(title="Pebble Queue docs assistant")
Question = Annotated[str, StringConstraints(strip_whitespace=True, min_length=1, max_length=500)]
class AskRequest(BaseModel):
question: Question
@cache
def get_assistant() -> Assistant:
"""Built once, on the first request, then reused. Tests replace it with dependency_overrides."""
try:
return build_assistant()
except FileNotFoundError as err:
raise HTTPException(status_code=503, detail=str(err))
def sse(event: dict) -> str:
"""One Server-Sent Event: 'data: <json>' and an empty line."""
return f"data: {json.dumps(event, default=asdict)}\n\n"
@app.get("/health")
def health(assistant: Assistant = Depends(get_assistant)) -> dict:
index = assistant.retriever.index
return {
"status": "ok",
"docs": len(index.doc_hashes),
"chunks": len(index.chunks),
"model": assistant.model,
"embed_model": index.embed_model,
"reranker": assistant.retriever.reranker is not None,
}
@app.post("/ask")
def ask(req: AskRequest, assistant: Assistant = Depends(get_assistant)) -> StreamingResponse:
def events():
try:
for event in assistant.events(req.question):
yield sse(event)
except openai.OpenAIError as err: # the status (200) is already sent: report it as an event
yield sse({"type": "error", "message": friendly(err)})
return StreamingResponse(events(), media_type="text/event-stream",
headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"}) - A reusable type with rules: trimmed, 1 to 500 characters. Pydantic checks it before your code runs, like Bean Validation's
@Sizein Spring.line 17 - Built once on the first request, then reused: loading the index and (optionally) the reranker takes time.line 24
- 503 Service Unavailable: the service runs, but is not ready. Load balancers and Kubernetes readiness probes understand it.line 30
- Turns the
Answerdataclass, with its list ofCitationdataclasses, into plain dicts that JSON can write.line 35 - Cheap on purpose: it reads the index already in memory and never calls a model, so a monitor can call it every few seconds.line 39
Depends(get_assistant)is dependency injection, like@Autowired: FastAPI callsget_assistant()and passes the result in.line 52- Inside the generator: by the time the model fails, the client already has the 200 and some tokens.line 57
- Asks nginx, if you put it in front later, not to hold the stream back.
no-cachekeeps proxies from storing it.line 61
import json
from pathlib import Path
import httpx2
import openai
import pytest
from fastapi.testclient import TestClient
from answer import REFUSAL, Assistant
from app import app, get_assistant
from retrieve import HybridRetriever
from store import load_index, sync_index
from tests.fakes import FakeChat, FakeEmbedder
client = TestClient(app)
@pytest.fixture(scope="module")
def index(tmp_path_factory):
tmp = tmp_path_factory.mktemp("m6")
sync_index(Path("docs"), tmp / "index", FakeEmbedder())
return load_index(tmp / "index")
@pytest.fixture
def use(index):
"""use(*replies): serve the app with the real retriever on a fake index and a scripted fake model."""
def install(*replies):
chat = FakeChat(*replies)
app.dependency_overrides[get_assistant] = lambda: Assistant(HybridRetriever(index, FakeEmbedder()), chat, "test-model")
return chat
yield install
app.dependency_overrides.clear()
def events_of(response) -> list[dict]:
"""Parse an SSE body: events are separated by an empty line, each is 'data: <json>'."""
blocks = [b for b in response.text.split("\n\n") if b.strip()]
assert all(b.startswith("data: ") for b in blocks)
return [json.loads(b[len("data: "):]) for b in blocks]
def test_health_reports_the_index(use):
use()
r = client.get("/health")
assert r.status_code == 200
body = r.json()
assert body["status"] == "ok" and body["docs"] == 8 and body["chunks"] > 20
assert body["model"] == "test-model" and body["reranker"] is False
def test_health_without_an_index_says_what_to_do(monkeypatch, tmp_path):
monkeypatch.setenv("INDEX_DIR", str(tmp_path / "nothing-here"))
get_assistant.cache_clear()
r = client.get("/health")
assert r.status_code == 503 and "index_docs.py" in r.json()["detail"]
get_assistant.cache_clear()
def test_ask_streams_tokens_then_a_final_answer(use):
use("Up to 5 attempts in total [1].")
r = client.post("/ask", json={"question": "How many times is a failed job retried by default?"})
assert r.status_code == 200
assert r.headers["content-type"].startswith("text/event-stream")
events = events_of(r)
assert events[0]["type"] == "token" and events[-1]["type"] == "final"
answer = events[-1]["answer"]
assert answer["refused"] is False and answer["text"] == "Up to 5 attempts in total [1]."
assert answer["citations"][0]["source"] == "jobs-and-retries.md#retry-policy"
def test_off_topic_is_refused_without_a_model_call(use):
chat = use()
events = events_of(client.post("/ask", json={"question": "bake sourdough bread"}))
assert events == [{"type": "final", "answer": {"text": REFUSAL, "citations": [], "refused": True,
"reason": "weak retrieval", "attempts": 0}}]
assert chat.requests == []
def test_a_model_error_becomes_an_error_event(use):
use(openai.APIConnectionError(request=httpx2.Request("POST", "http://test")))
events = events_of(client.post("/ask", json={"question": "How are failed jobs retried?"}))
assert events[-1]["type"] == "error" and "Cannot reach" in events[-1]["message"]
@pytest.mark.parametrize("body", [{}, {"question": ""}, {"question": " "}, {"question": "x" * 501}])
def test_bad_requests_are_rejected_before_any_work(use, body):
chat = use()
assert client.post("/ask", json=body).status_code == 422
assert chat.requests == [] - Calls the app in memory, with no server and no port, like Spring's
MockMvc.line 15 - Swaps the real assistant for one built from the real retriever on a fake index and a scripted model.line 30
- Parses an SSE body the way a client does: split on empty lines, strip
data:, parse the JSON.line 36 @cachefunctions havecache_clear(): this test needsget_assistantto run again with anotherINDEX_DIR.line 54- One test, four inputs: pytest runs it once per body, like JUnit's
@ParameterizedTest.line 86
uv run uvicorn app:app --port 8000
# in a second terminal:
curl -s localhost:8000/health
curl -N -X POST localhost:8000/ask -H "content-type: application/json" -d '{"question": "How long are dead jobs kept?"}' INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
{"status":"ok","docs":8,"chunks":41,"model":"llama3.2:3b","embed_model":"nomic-embed-text","reranker":false}
data: {"type": "token", "text": "Dead"}
data: {"type": "token", "text": " jobs"}
...
data: {"type": "final", "answer": {"text": "Dead jobs are kept for 14 days [1].", "citations": [{"n": 1, "source": "jobs-and-retries.md#dead-letter-queue", "title": "Jobs and retries", "section": "Dead-letter queue", "url": "/files/jobs-and-retries.md#dead-letter-queue"}], "refused": false, "reason": "", "attempts": 1}} Stuck on this milestone?
503withNo index yet- Run
uv run index_docs.pyfrom the project folder, then call/healthagain: the cached dependency builds on the next request. - curl prints everything at once at the end
- Add
-N: without it curl buffers the output. If it still comes at once, something in between (a proxy, compression) buffers it. [Errno 48] Address already in use- Another server uses port 8000. Stop it, or use
--port 8001and change the curl URLs. - Windows: the curl command fails on the quotes
- In PowerShell use
curl.exeand escape the inner quotes:-d "{\"question\": \"How long are dead jobs kept?\"}".
A chat page served by the app
One HTML file with no build step: tokens appear live, citations become links to the source, refusals and errors look different.
static/index.html: one file with its CSS and JavaScript inline, no libraries. app.py serves it at GET / (a FileResponse) and serves the docs at /files/... with StaticFiles(directory=settings().docs_dir), so citation links open the original file. Not /docs: FastAPI already uses /docs for its Swagger UI.
What the page must do:
- A form with a text input (at most 500 characters) and a button. On submit, show the question, then an empty answer bubble.
POST /askwithfetch: the browser'sEventSourcecan only make GET requests without a body. Readresponse.body.getReader()with aTextDecoder, keep a buffer, split it on empty lines (\n\n), keep the unfinished last piece for the next read, and parse the JSON afterdata:.token: add the text to the bubble.reset: clear the bubble.final: replace the bubble with the final answer, every[n]turned into a link to that citation'surl, and a numbered list of the sources under it (title › section). A refused answer is shown in grey italics.error: show the message in red. A non-2xx response (such as 422) is an error too.- Build the answer with
textContentanddocument.createElementonly, neverinnerHTML: the text comes from a model that read your docs, and a doc (or a user) can make it write<img src=x onerror=...>. - A viewport meta tag, and no sideways scrolling at 390 px wide.
uv run pytest -q tests/test_m7.pypasses (4 tests).- With
uv run uvicorn app:app --port 8000running, open http://localhost:8000 and ask "How do I verify webhook signatures?": tokens appear one by one, then the answer gets[1]links and a source list, and clicking one openswebhooks.md. - Ask "What is the capital of Australia?": the refusal appears in grey italics.
- In your browser's device toolbar at 390 px wide, the page does not scroll sideways.
Hints
text.split(/(\[\d+(?:\s*,\s*\d+)*\])/): a regex with a capturing group makessplitkeep the separators, so the markers come out as their own pieces.decoder.decode(value, { stream: true })keeps a multi-byte character that was cut between two network chunks.li.value = 3makes an<ol>item show number 3, so the list numbers match the[n]markers even when only[2]was cited.
Show the reference solution for milestone 7
Try it yourself first. This is one good way to do it, not the only one.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Pebble Queue docs assistant</title>
<style>
:root { color-scheme: light dark; --line: #8884; --muted: #888; --accent: #2563eb; }
* { box-sizing: border-box; }
body { margin: 0; font: 16px/1.5 system-ui, sans-serif; }
main { max-width: 720px; margin: 0 auto; padding: 16px; display: grid; gap: 12px; }
#log { display: grid; gap: 10px; }
.msg { padding: 10px 14px; border: 1px solid var(--line); border-radius: 12px; white-space: pre-wrap; overflow-wrap: anywhere; }
.user { justify-self: end; background: #2563eb22; }
.refused { color: var(--muted); font-style: italic; }
.error { border-color: #dc2626; color: #dc2626; }
.sources { margin: 8px 0 0; padding-left: 18px; font-size: 14px; white-space: normal; }
sup a, .sources a { color: var(--accent); }
form { display: flex; gap: 8px; }
input { flex: 1; min-width: 0; font: inherit; padding: 10px 12px; border: 1px solid var(--line); border-radius: 10px; }
button { font: inherit; padding: 10px 16px; border: 0; border-radius: 10px; background: var(--accent); color: #fff; }
button:disabled { opacity: 0.5; }
</style>
</head>
<body>
<main>
<h1>Ask the Pebble Queue docs</h1>
<div id="log" aria-live="polite"></div>
<form id="ask">
<input id="q" name="question" maxlength="500" placeholder="How many times is a failed job retried?" autocomplete="off" required>
<button>Ask</button>
</form>
</main>
<script>
const log = document.getElementById("log");
const form = document.getElementById("ask");
const input = document.getElementById("q");
function bubble(cls, text) {
const div = document.createElement("div");
div.className = "msg " + cls;
div.textContent = text;
log.append(div);
div.scrollIntoView({ block: "end" });
return div;
}
// Show the final answer: text with [n] turned into links, then the list of sources.
// Built with textContent and createElement only: model text is never parsed as HTML.
function showFinal(div, answer) {
div.textContent = "";
if (answer.refused) { div.classList.add("refused"); div.textContent = answer.text; return; }
const byN = new Map(answer.citations.map((c) => [c.n, c]));
const parts = answer.text.split(/(\[\d+(?:\s*,\s*\d+)*\])/);
for (const part of parts) {
const m = part.match(/^\[(.+)\]$/);
if (!m) { div.append(part); continue; }
const sup = document.createElement("sup");
m[1].split(",").map((x) => Number(x.trim())).forEach((n, i) => {
const a = document.createElement("a");
a.href = byN.get(n)?.url ?? "#";
a.target = "_blank";
a.textContent = (i ? "," : "") + "[" + n + "]";
sup.append(a);
});
div.append(sup);
}
const ol = document.createElement("ol");
ol.className = "sources";
for (const c of answer.citations) {
const li = document.createElement("li");
li.value = c.n;
const a = document.createElement("a");
a.href = c.url;
a.target = "_blank";
a.textContent = c.section ? c.title + " › " + c.section : c.title;
li.append(a);
ol.append(li);
}
div.append(ol);
}
function handle(event, div) {
if (event.type === "token") div.textContent += event.text;
else if (event.type === "reset") div.textContent = "";
else if (event.type === "final") showFinal(div, event.answer);
else if (event.type === "error") { div.classList.add("error"); div.textContent = event.message; }
}
form.addEventListener("submit", async (e) => {
e.preventDefault();
const question = input.value.trim();
if (!question) return;
bubble("user", question);
const div = bubble("bot", "");
input.value = "";
form.querySelector("button").disabled = true;
try {
const res = await fetch("/ask", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ question }),
});
if (!res.ok) throw new Error("The server answered " + res.status);
const reader = res.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const events = buffer.split("\n\n");
buffer = events.pop(); // the last piece may be an unfinished event: keep it for later
for (const block of events) {
const data = block.split("\n").filter((l) => l.startsWith("data:")).map((l) => l.slice(5).trim()).join("");
if (data) handle(JSON.parse(data), div);
}
}
} catch (err) {
handle({ type: "error", message: String(err.message || err) }, div);
} finally {
form.querySelector("button").disabled = false;
input.focus();
}
});
</script>
</body>
</html> - Without it a phone renders the page at desktop width and shrinks it.line 5
- One line for a dark mode that follows the system: the browser picks matching default colours.line 8
- Long URLs and error codes wrap instead of pushing the page sideways on a phone.line 13
- A flex item will not shrink below its content without it: the input would overflow the form on narrow screens.line 20
- Screen readers announce new messages without interrupting.line 28
- The checked final answer replaces whatever was streamed: after a nudge or a refusal, the screen shows exactly what the server decided.line 50
- The safety rule of this milestone: model text is data, never markup.line 49
- Splits around the markers; the capturing group keeps them in the result.line 54
?.and??, as in TypeScript: no crash for a number without a citation.line 61- The list number matches the marker in the text.line 72
- The server is retrying after an uncited answer: start the bubble again.line 85
- Reads the response body piece by piece, as it arrives over the network.line 105
- The network does not respect event boundaries: the last piece may be half an event. Keep it and finish it with the next read.line 113
- A 422 or 503 has no event stream. Turn it into an error bubble instead of reading nothing.line 104
import json
from dataclasses import asdict
from functools import cache
from typing import Annotated
import openai
from fastapi import Depends, FastAPI, HTTPException
from fastapi.responses import FileResponse, StreamingResponse
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel, StringConstraints
from answer import Assistant
from config import settings
from factory import build_assistant
from llm import friendly
app = FastAPI(title="Pebble Queue docs assistant")
app.mount("/files", StaticFiles(directory=settings().docs_dir), name="files") # what citations link to
Question = Annotated[str, StringConstraints(strip_whitespace=True, min_length=1, max_length=500)]
class AskRequest(BaseModel):
question: Question
@cache
def get_assistant() -> Assistant:
"""Built once, on the first request, then reused. Tests replace it with dependency_overrides."""
try:
return build_assistant()
except FileNotFoundError as err:
raise HTTPException(status_code=503, detail=str(err))
def sse(event: dict) -> str:
"""One Server-Sent Event: 'data: <json>' and an empty line."""
return f"data: {json.dumps(event, default=asdict)}\n\n"
@app.get("/", include_in_schema=False)
def page() -> FileResponse:
return FileResponse("static/index.html")
@app.get("/health")
def health(assistant: Assistant = Depends(get_assistant)) -> dict:
index = assistant.retriever.index
return {
"status": "ok",
"docs": len(index.doc_hashes),
"chunks": len(index.chunks),
"model": assistant.model,
"embed_model": index.embed_model,
"reranker": assistant.retriever.reranker is not None,
}
@app.post("/ask")
def ask(req: AskRequest, assistant: Assistant = Depends(get_assistant)) -> StreamingResponse:
def events():
try:
for event in assistant.events(req.question):
yield sse(event)
except openai.OpenAIError as err: # the status (200) is already sent: report it as an event
yield sse({"type": "error", "message": friendly(err)})
return StreamingResponse(events(), media_type="text/event-stream",
headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"}) - Serves the docs folder as static files:
/files/webhooks.mdisdocs/webhooks.md. The#anchorpart of a link never reaches the server; the browser uses it.line 18 include_in_schema=Falsekeeps the page out of the generated API docs at/docs.line 42
import json
import re
from pathlib import Path
from fastapi.testclient import TestClient
from answer import Assistant
from app import app, get_assistant
from retrieve import HybridRetriever
from store import load_index, sync_index
from tests.fakes import FakeChat, FakeEmbedder
client = TestClient(app)
def test_the_page_is_served_at_the_root():
r = client.get("/")
assert r.status_code == 200 and r.headers["content-type"].startswith("text/html")
html = r.text
assert '<meta name="viewport"' in html # usable on a phone
assert 'fetch("/ask"' in html # POST with fetch: EventSource cannot send a body
assert "getReader()" in html # reads the stream as it arrives
def test_the_page_never_puts_model_text_into_html():
html = client.get("/").text
assert "innerHTML" not in html and "insertAdjacentHTML" not in html and "document.write" not in html
assert "textContent" in html
def test_the_page_handles_every_event_type():
script = client.get("/").text
for event_type in ["token", "reset", "final", "error"]:
assert re.search(rf"""["']{event_type}["']""", script), event_type
def test_citation_links_open_the_cited_document(tmp_path):
sync_index(Path("docs"), tmp_path / "index", FakeEmbedder())
index = load_index(tmp_path / "index")
chat = FakeChat("Signatures use HMAC-SHA256 [1].")
app.dependency_overrides[get_assistant] = lambda: Assistant(HybridRetriever(index, FakeEmbedder()), chat, "m")
try:
body = client.post("/ask", json={"question": "How do I verify webhook signatures?"}).text
finally:
app.dependency_overrides.clear()
final = json.loads(body.strip().split("\n\n")[-1][len("data: "):])
url = final["answer"]["citations"][0]["url"]
assert url == "/files/webhooks.md#verifying-signatures"
r = client.get(url.split("#")[0])
assert r.status_code == 200 and "Pebble-Signature" in r.text - A blunt but useful rule: no
innerHTMLanywhere in the page. Code review would catch it too; a test never forgets.line 25 - End to end on the server side: ask, take the citation URL from the final event, fetch it.line 37
uv run uvicorn app:app --port 8000
# then open http://localhost:8000 INFO: Started server process [12345] INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) INFO: 127.0.0.1:52811 - "GET / HTTP/1.1" 200 OK INFO: 127.0.0.1:52811 - "POST /ask HTTP/1.1" 200 OK INFO: 127.0.0.1:52812 - "GET /files/webhooks.md HTTP/1.1" 200 OK
Stuck on this milestone?
- Clicking a Markdown citation downloads the file
- Browsers treat
text/markdowndifferently: some show it, some download it. In a real product the links would point at your docs website; here, the HTML and PDF links open in the browser. RuntimeError: Directory 'docs' does not existStaticFileschecks the folder when the app starts, relative to where you start it. Run uvicorn from the project folder, or setDOCS_DIRto an absolute path.- Nothing appears until the whole answer is done
- Check that you read with
getReader()in a loop, notawait res.text()orres.json(), which wait for the end of the body.
Evals: recall@k, MRR, citation and refusal checks
Score every change on 25 labelled questions, and set the refusal thresholds from measured numbers instead of guesses.
evals/questions.jsonl: one JSON object per line, {"id", "question", "sources", "facts"}. sources lists the sections that answer it, as file#anchor (the Chunk.source form); facts lists strings a correct answer must contain. Copy the 25 questions from the solution: 20 answerable ones in all three formats, and 5 that must be refused, with an empty sources. Two of those are clearly off-topic; three are traps: "Who is the CEO of Pebble Queue?" and "Can Pebble Queue read jobs directly from a Kafka topic?" sound on-topic but the docs do not say, and "What is the weather in Berlin today?" shares the word "Berlin" with the cron docs (Europe/Berlin).
scoring.py: a Case dataclass with those four fields and an answerable property (sources is not empty); load_cases(path); first_relevant_rank(retrieved, expected) (1-based rank of the first retrieved source in expected, or None); recall_at_k(rank, k) (1.0 if found in the top k, else 0.0); reciprocal_rank(rank) (1/rank, 0.0 for None); check_answer(case, answer), which returns {"answered", "right_source"} plus "facts" when the case has facts (every fact in the answer text, ignoring case) for answerable cases, and {"refused"} for the others; evaluate_case(assistant, case, k=5, retrieval_only=False), one report row with id, rank, top_cosine, top_bm25, top_rerank, recall@5 and mrr (answerable only) and the checks plus answer and reason (unless retrieval_only); and summarize(rows): the mean of each metric in METRICS = ["recall@5", "mrr", "answered", "right_source", "facts", "refused"] over the rows that have it, rounded to 4 places, None when no row has it.
run_evals.py: --retrieval-only (no chat model, a few seconds) and --save-baseline (writes the summary to evals/baseline.json). It prints one row per question, the summary line and the range of the best cosine for answerable and for refused questions, and writes reports/latest.json.
Calibrate the thresholds with it. We ran the 25 questions through the real cross-encoder/ms-marco-MiniLM-L6-v2. The top rerank score of most answerable questions was between +4 and +9, but two were about -1.4 and -1.1 ("My push fails with PQ-2002" and "Can I move a project from us to eu?", whose sections use other words). The two clearly off-topic questions scored about -11, but the CEO and Kafka traps scored about +0.2 and +0.3, higher than those two answerable ones. No threshold separates them: 0 would refuse two good questions and still let both traps through. That is why MIN_RERANK_SCORE defaults to -3: it refuses what is clearly off-topic and leaves the traps to the model and the citation checks. Cosine scores are worse: with nomic-embed-text they are bunched between about 0.5 and 0.85, so a cosine threshold of 0.65 still lets weak chunks through, which is why weak_retrieval also requires that no word is shared. Read your own ranges before you change either number.
uv run pytest -q tests/test_m8.pypasses (7 tests).uv run run_evals.py --retrieval-onlyprints a row per question andrecall@5 ... mrr ...in seconds.uv run run_evals.py --save-baselineprints the full table, writesreports/latest.jsonandevals/baseline.json, and every one of the 5 off-topic rows showsokorFAILin therefusedcolumn.
Hints
- Booleans are numbers in Python (
True == 1), sofloat(True)gives 1.0 and a mean of booleans is the pass rate. - Skip
Nonewhen averaging: a metric that does not apply to a row is not a failure. - Read
hits[0].rerank_scorefortop_rerank; it isNonewhen the reranker is off, and JSON writes that asnull.
Show the reference solution for milestone 8
Try it yourself first. This is one good way to do it, not the only one.
{"id": "retry-default", "question": "How many times does Pebble try a failed job by default?", "sources": ["jobs-and-retries.md#retry-policy"], "facts": ["5"]}
{"id": "retry-first-wait", "question": "How long does Pebble wait before it retries a failed job for the first time?", "sources": ["jobs-and-retries.md#retry-policy"], "facts": ["10 seconds"]}
{"id": "dead-job-retention", "question": "How long are dead jobs kept?", "sources": ["jobs-and-retries.md#dead-letter-queue"], "facts": ["14 days"]}
{"id": "idempotency-window", "question": "How long does Pebble remember an idempotency key?", "sources": ["jobs-and-retries.md#idempotency-keys"], "facts": ["24 hours"]}
{"id": "visibility-timeout", "question": "What is the default visibility timeout for a job?", "sources": ["jobs-and-retries.md#job-lifecycle"], "facts": ["30 seconds"]}
{"id": "max-delay", "question": "How far in the future can I delay a job?", "sources": ["scheduling.md#delayed-jobs", "errors.html#job-errors"], "facts": ["30 days"]}
{"id": "cron-timezone", "question": "Which time zone do cron schedules use by default?", "sources": ["scheduling.md#cron-schedules"], "facts": ["UTC"]}
{"id": "paused-schedule", "question": "Are runs that were missed while a schedule was paused made up later?", "sources": ["scheduling.md#pausing-a-schedule"], "facts": []}
{"id": "webhook-signature", "question": "How do I check that a webhook request really came from Pebble?", "sources": ["webhooks.md#verifying-signatures"], "facts": ["HMAC"]}
{"id": "webhook-timeout", "question": "How quickly must my webhook endpoint answer?", "sources": ["webhooks.md#delivery-and-retries"], "facts": ["10 seconds"]}
{"id": "payload-limit", "question": "What is the largest job payload I can send?", "sources": ["limits-and-quotas.md#payload-size", "errors.html#job-errors"], "facts": ["256 KB"]}
{"id": "team-rate-limit", "question": "How many API requests per second does the Team plan allow?", "sources": ["limits-and-quotas.md#rate-limits"], "facts": ["500"]}
{"id": "error-pq-1042", "question": "What does error PQ-1042 mean?", "sources": ["errors.html#job-errors"], "facts": ["256 KB"]}
{"id": "error-pq-2002", "question": "My push fails with PQ-2002. What happened?", "sources": ["errors.html#limit-errors", "pricing-and-sla.pdf#11-overage"], "facts": ["quota"]}
{"id": "test-key-prefix", "question": "What does a test API key start with?", "sources": ["getting-started.md#api-keys"], "facts": ["pk_test_"]}
{"id": "change-region", "question": "Can I move an existing project from the us region to eu?", "sources": ["getting-started.md#log-in-and-create-a-project"], "facts": []}
{"id": "team-price", "question": "How much does the Team plan cost per month?", "sources": ["pricing-and-sla.pdf#1-plans-and-prices"], "facts": ["49"]}
{"id": "sla-credit", "question": "What service credit do customers get when uptime is below 99.0%?", "sources": ["pricing-and-sla.pdf#21-service-credits"], "facts": ["25%"]}
{"id": "cancel-running", "question": "Can I cancel a job that is already running?", "sources": ["api-reference.html#cancel-a-job"], "facts": ["409"]}
{"id": "batch-size", "question": "How many jobs can I push in one batch request?", "sources": ["api-reference.html#push-jobs-in-a-batch", "limits-and-quotas.md#rate-limits"], "facts": ["100"]}
{"id": "off-topic-capital", "question": "What is the capital of Australia?", "sources": [], "facts": []}
{"id": "off-topic-code", "question": "Write a Python function that reverses a string.", "sources": [], "facts": []}
{"id": "off-topic-ceo", "question": "Who is the CEO of Pebble Queue?", "sources": [], "facts": []}
{"id": "off-topic-kafka", "question": "Can Pebble Queue read jobs directly from a Kafka topic?", "sources": [], "facts": []}
{"id": "off-topic-weather", "question": "What is the weather in Berlin today?", "sources": [], "facts": []} - One question per line.
sourcesuses thefile#anchorform ofChunk.source; the test checks that every one exists.line 1 - Two sections answer this one: either counts as a hit.line 6
- An exact code: the BM25 half of hybrid search earns its keep here.line 13
- Empty
sources: the only right answer is a refusal.line 21 - A trap: on-topic words, no answer in the docs. Retrieval cannot refuse it; the model and the citation check must.line 23
- Shares "Berlin" with the cron docs, so it passes the shared-word rule.line 25
import json
from dataclasses import dataclass
from pathlib import Path
from answer import Answer
@dataclass
class Case:
id: str
question: str
sources: list[str] # "file#anchor" of every section that answers it; empty = should be refused
facts: list[str] # strings a correct answer must contain
@property
def answerable(self) -> bool:
return bool(self.sources)
def load_cases(path: Path) -> list[Case]:
lines = path.read_text(encoding="utf-8").splitlines()
return [Case(**json.loads(line)) for line in lines if line.strip()]
def first_relevant_rank(retrieved: list[str], expected: list[str]) -> int | None:
"""1-based rank of the first retrieved source that is one of the expected ones, or None."""
for rank, source in enumerate(retrieved, start=1):
if source in expected:
return rank
return None
def recall_at_k(rank: int | None, k: int) -> float:
return 1.0 if rank is not None and rank <= k else 0.0
def reciprocal_rank(rank: int | None) -> float:
return 1.0 / rank if rank else 0.0
def check_answer(case: Case, answer: Answer) -> dict[str, bool]:
"""Rule-based checks. Answerable questions must be answered from the right section;
off-topic ones must be refused."""
if not case.answerable:
return {"refused": answer.refused}
checks = {
"answered": not answer.refused,
"right_source": any(c.source in case.sources for c in answer.citations),
}
if case.facts:
text = answer.text.lower()
checks["facts"] = all(f.lower() in text for f in case.facts)
return checks
def evaluate_case(assistant, case: Case, k: int = 5, retrieval_only: bool = False) -> dict:
"""One row of the report: retrieval metrics, the top scores (to calibrate thresholds), the answer checks."""
hits = assistant.retriever.search(case.question, k)
rank = first_relevant_rank([h.chunk.source for h in hits], case.sources)
row = {
"id": case.id,
"rank": rank,
"top_cosine": round(max((h.vector_score for h in hits), default=0.0), 3),
"top_bm25": round(max((h.bm25_score for h in hits), default=0.0), 2),
"top_rerank": hits[0].rerank_score if hits else None,
}
if case.answerable:
row[f"recall@{k}"] = recall_at_k(rank, k)
row["mrr"] = reciprocal_rank(rank)
if not retrieval_only:
answer = assistant.ask(case.question)
row.update(check_answer(case, answer))
row["answer"] = answer.text
row["reason"] = answer.reason
return row
METRICS = ["recall@5", "mrr", "answered", "right_source", "facts", "refused"]
def summarize(rows: list[dict]) -> dict[str, float | None]:
"""The mean of every metric over the rows that have it. None when no row has it."""
out: dict[str, float | None] = {}
for m in METRICS:
values = [float(r[m]) for r in rows if r.get(m) is not None]
out[m] = round(sum(values) / len(values), 4) if values else None
return out - An empty
sourceslist is falsy, like an empty collection being "nothing" in JavaScript.bool([])isFalse.line 16 - The building block of both metrics: where did the first right section land?line 25
- Rule checks: free, instant and the same every run. Each failing row points at one answer you can read.line 41
any(...)isstream().anyMatch(...): at least one citation points at an expected section.line 48- The same
retriever.searchandaskthe API uses: the evals test the real pipeline, not a copy of it.line 56 - Not a metric: these columns are for calibrating
MIN_SIMILARITYandMIN_RERANK_SCORE.line 63 answeredis averaged over answerable rows only,refusedover the off-topic ones only: each rate means one thing.line 81
import argparse
import json
import sys
import time
from pathlib import Path
import openai
from factory import build_assistant
from llm import friendly
from scoring import evaluate_case, load_cases, summarize
BASELINE = Path("evals/baseline.json")
parser = argparse.ArgumentParser(description="Run the eval questions and score retrieval and answers.")
parser.add_argument("--retrieval-only", action="store_true", help="skip the chat model (fast)")
parser.add_argument("--save-baseline", action="store_true", help=f"save the scores as {BASELINE}")
args = parser.parse_args()
cases = load_cases(Path("evals/questions.jsonl"))
started = time.perf_counter()
try:
assistant = build_assistant()
rows = [evaluate_case(assistant, case, retrieval_only=args.retrieval_only) for case in cases]
except FileNotFoundError as err:
sys.exit(str(err))
except openai.OpenAIError as err:
sys.exit(friendly(err))
def mark(value) -> str:
return "-" if value is None else ("ok" if value else "FAIL")
print(f"{'case':<20} {'rank':>4} {'cos':>6} {'bm25':>6} answered source facts refused")
for r in rows:
print(f"{r['id']:<20} {r['rank'] or '-':>4} {r['top_cosine']:>6.3f} {r['top_bm25']:>6.2f} "
f"{mark(r.get('answered')):<8} {mark(r.get('right_source')):<6} {mark(r.get('facts')):<5} "
f"{mark(r.get('refused'))}")
summary = summarize(rows)
print("\n" + " ".join(f"{k} {v:.2f}" for k, v in summary.items() if v is not None))
on = [r["top_cosine"] for r, c in zip(rows, cases) if c.answerable]
off = [r["top_cosine"] for r, c in zip(rows, cases) if not c.answerable]
print(f"best cosine: answerable {min(on):.3f} to {max(on):.3f}, off-topic {min(off):.3f} to {max(off):.3f}"
f" ({time.perf_counter() - started:.0f}s)")
Path("reports").mkdir(exist_ok=True)
report = {"summary": summary, "rows": rows, "retrieval_only": args.retrieval_only}
Path("reports/latest.json").write_text(json.dumps(report, indent=2), encoding="utf-8")
if args.save_baseline:
BASELINE.write_text(json.dumps(summary, indent=2) + "\n", encoding="utf-8")
print(f"saved {BASELINE}") - The standard library's command-line parser.
--retrieval-onlybecomesargs.retrieval_only.line 14 - One row per question. With a local model the full run takes a few minutes: two model calls at most per question.line 23
- The ranges you need to set
MIN_SIMILARITY: if they overlap, a cosine threshold alone cannot separate the two groups.line 44 - The report says how it was made, so nobody compares a retrieval-only run with a full one by mistake.line 48
import json
from pathlib import Path
from answer import REFUSAL, Answer, Citation
from scoring import (Case, check_answer, evaluate_case, first_relevant_rank, load_cases, recall_at_k,
reciprocal_rank, summarize)
from tests.test_m5 import DLQ, RETRY as RETRY_HIT, assistant
RETRY = Case("r", "How many attempts?", ["jobs-and-retries.md#retry-policy"], ["5"])
OFF = Case("o", "Capital of Australia?", [], [])
def cite(source):
return Citation(1, source, "T", "S", f"/files/{source}")
def test_the_question_set_is_big_enough_and_points_at_real_sections():
cases = load_cases(Path("evals/questions.jsonl"))
assert len(cases) >= 15
assert sum(not c.answerable for c in cases) >= 3 # off-topic questions test the refusal path
assert len({c.id for c in cases}) == len(cases)
from chunking import chunk_document
from loaders import load_document
real = {ch.source for p in Path("docs").iterdir() for ch in chunk_document(p.name, load_document(p))}
for c in cases:
assert set(c.sources) <= real, f"{c.id} points at a section that does not exist"
def test_rank_recall_and_reciprocal_rank():
retrieved = ["a.md#x", "b.md#y", "c.md#z"]
assert first_relevant_rank(retrieved, ["b.md#y", "c.md#z"]) == 2
assert first_relevant_rank(retrieved, ["d.md#w"]) is None
assert recall_at_k(2, 5) == 1.0 and recall_at_k(6, 5) == 0.0 and recall_at_k(None, 5) == 0.0
assert reciprocal_rank(2) == 0.5 and reciprocal_rank(None) == 0.0
def test_a_good_answer_passes_every_check():
answer = Answer("Up to 5 attempts [1].", [cite("jobs-and-retries.md#retry-policy")])
assert check_answer(RETRY, answer) == {"answered": True, "right_source": True, "facts": True}
def test_citing_the_wrong_section_or_missing_a_fact_fails():
wrong = Answer("Up to 5 attempts [1].", [cite("webhooks.md#delivery-and-retries")])
assert check_answer(RETRY, wrong)["right_source"] is False
no_fact = Answer("Several attempts [1].", [cite("jobs-and-retries.md#retry-policy")])
assert check_answer(RETRY, no_fact)["facts"] is False
def test_refusals():
refused = Answer(REFUSAL, [], refused=True, reason="weak retrieval")
assert check_answer(OFF, refused) == {"refused": True}
assert check_answer(OFF, Answer("Canberra [1].", [cite("x.md#y")])) == {"refused": False}
assert check_answer(RETRY, refused)["answered"] is False # refusing an answerable question is a failure
def test_summary_averages_only_the_rows_that_have_a_metric():
rows = [{"recall@5": 1.0, "mrr": 1.0, "answered": True},
{"recall@5": 0.0, "mrr": 0.0, "answered": False},
{"refused": True}]
s = summarize(rows)
assert s["recall@5"] == 0.5 and s["answered"] == 0.5 and s["refused"] == 1.0
assert s["facts"] is None # no row had it: not 0
json.dumps(s) # it goes into the JSON report
def test_one_report_row_end_to_end_with_fakes():
from tests.fakes import FakeChat
bot = assistant(FakeChat("Up to 5 attempts [2]."), [DLQ, RETRY_HIT])
row = evaluate_case(bot, RETRY)
assert row["rank"] == 2 and row["recall@5"] == 1.0 and row["mrr"] == 0.5
assert row["answered"] and row["right_source"] and row["facts"]
assert row["top_cosine"] == 0.8 and row["top_bm25"] == 3.0
fast = evaluate_case(assistant(FakeChat(), [DLQ]), RETRY, retrieval_only=True) # no model call
assert fast["rank"] is None and fast["recall@5"] == 0.0 and "answered" not in fast - Tests the data too: a typo in a label would otherwise show up as a retrieval failure.line 17
- Uses milestone 5's fixed retriever and fake chat: the right section at rank 2 gives MRR 0.5.line 67
uv run run_evals.py --retrieval-only
uv run run_evals.py --save-baseline case rank cos bm25 answered source facts refused retry-default 1 0.733 8.14 - - - - ... off-topic-weather - 0.561 2.24 - - - - recall@5 1.00 mrr 0.93 best cosine: answerable 0.612 to 0.811, off-topic 0.528 to 0.664 (4s) case rank cos bm25 answered source facts refused retry-default 1 0.733 8.14 ok ok ok - retry-first-wait 1 0.702 8.01 ok ok FAIL - ... off-topic-capital - 0.542 0.00 - - - ok off-topic-ceo - 0.664 1.34 - - - ok off-topic-kafka - 0.640 3.21 - - - FAIL off-topic-weather - 0.561 2.24 - - - ok recall@5 1.00 mrr 0.93 answered 0.95 right_source 0.90 facts 0.83 refused 0.80 best cosine: answerable 0.612 to 0.811, off-topic 0.528 to 0.664 (214s) saved evals/baseline.json
right_source is low, the search found the section and the model cited something else: fix the prompt. If recall@5 is low, no prompt can help: fix chunking or retrieval. And keep the trap questions: an assistant that refuses everything scores perfectly on refused, which is why answered sits next to it.Stuck on this milestone?
AssertionError: <id> points at a section that does not exist- An eval label does not match any
Chunk.source. Runuv run show_chunks.py <file>and copy the anchor from a chunk id (the part between#and/). - The full run takes many minutes
- Normal on a laptop CPU: up to two chat calls per question. Use
--retrieval-onlywhile you work on retrieval, and the full run before you commit. - Scores change a little between two full runs
- Even at temperature 0.1 a model is not fully repeatable. Look at which rows flip: those are your borderline cases. Milestone 9 sets the gate's tolerance with that in mind.
A regression gate in CI
Fail the build when a change makes retrieval or answers worse: a baseline, a gate with a tolerance, and a GitHub Actions workflow.
gate.py: TOLERANCE = 0.05. load_baseline(path) reads the JSON, or raises FileNotFoundError with a message that contains --save-baseline. compare(now, baseline, tolerance=0.05, metrics=None) -> list[str] returns one message per problem, in baseline order, and an empty list when the gate passes: a metric that is None in the baseline is skipped; one missing (or None) now gives "<name>: missing now, baseline 1.00"; one more than the tolerance below the baseline gives "<name>: 0.80, baseline 1.00 (allowed drop 0.05)"; metrics limits the comparison to those names.
run_evals.py gets --gate: after the report, compare the summary with evals/baseline.json (only recall@5 and mrr with --retrieval-only), print GATE FAIL <message> for each problem and gate: passed or gate: failed, and exit with status 1 on failure. CI reads the exit status, not the text.
.github/workflows/ci.yml: a tests job on every push and pull request (uv sync, uv run pytest -q: fast, no model), and an eval-gate job on pull requests and on the Run workflow button (workflow_dispatch) that needs tests, installs Ollama on the runner, pulls both models, runs uv run index_docs.py and uv run run_evals.py --gate, and uploads reports/latest.json even when the gate fails. A GitHub-hosted runner has no GPU: expect the job to take several minutes.
The tolerance is a trade-off. With 20 answerable questions, one question flipping moves answered by 0.05, which the gate allows; two fail it. With 5 refusal questions, one flip moves refused by 0.2, so a single new "made it up" fails the build, which is what you want. Then prove the gate works by breaking retrieval on purpose: move docs/jobs-and-retries.md out of the folder, re-index (milestone 3 removes its chunks), run the gate, and put the file back.
To use it on GitHub: commit everything including uv.lock and the evals/baseline.json you made with your model, and push. Open a pull request to see the gate run.
uv run pytest -qpasses: all 61 tests of the 9 milestones.- With
docs/jobs-and-retries.mdmoved away and the index rebuilt,uv run run_evals.py --gateprintsGATE FAIL recall@5: ...andecho $?prints1. - With the file back and the index rebuilt, the same command prints
gate: passed.
Hints
- Compare
value < base - tolerancewith a tiny extra margin (- 1e-9):0.95and1.0 - 0.05are both floating-point numbers and should not fail on rounding. sys.exit(1)ends the program with status 1;sys.exit("text")prints the text and also exits with 1.- In the workflow,
if: always()on the upload step runs it even after the gate step failed: that is when you need the report most.
Show the reference solution for milestone 9
Try it yourself first. This is one good way to do it, not the only one.
import json
from pathlib import Path
TOLERANCE = 0.05 # how far a score may fall below the baseline before the gate fails
def load_baseline(path: Path) -> dict:
if not path.exists():
raise FileNotFoundError(f"{path} is missing. Create it with: uv run run_evals.py --save-baseline")
return json.loads(path.read_text(encoding="utf-8"))
def compare(now: dict, baseline: dict, tolerance: float = TOLERANCE, metrics: list[str] | None = None) -> list[str]:
"""Every metric that dropped by more than the tolerance. An empty list means the gate passes."""
problems = []
for name, base in baseline.items():
if base is None or (metrics is not None and name not in metrics):
continue
value = now.get(name)
if value is None:
problems.append(f"{name}: missing now, baseline {base:.2f}")
elif value < base - tolerance - 1e-9: # the tiny extra stops 0.95 vs 1.00 - 0.05 failing on rounding
problems.append(f"{name}: {value:.2f}, baseline {base:.2f} (allowed drop {tolerance:.2f})")
return problems - How far a score may fall before the gate fails. One question out of 20 is exactly 0.05.line 4
- The error says how to fix it, instead of a bare "no such file".line 9
- A pure function: two dicts in, a list of messages out. That is what makes it easy to test.line 13
- A metric that did not apply when the baseline was saved is not compared.line 17
- A metric that vanished is a failure: for example, every row now refused, so no
factscould be checked.line 21 - Higher scores always pass. Save a new baseline on purpose when you improve something.line 22
import argparse
import json
import sys
import time
from pathlib import Path
import openai
from factory import build_assistant
from gate import compare, load_baseline
from llm import friendly
from scoring import evaluate_case, load_cases, summarize
BASELINE = Path("evals/baseline.json")
parser = argparse.ArgumentParser(description="Run the eval questions and score retrieval and answers.")
parser.add_argument("--retrieval-only", action="store_true", help="skip the chat model (fast)")
parser.add_argument("--save-baseline", action="store_true", help=f"save the scores as {BASELINE}")
parser.add_argument("--gate", action="store_true", help="exit with status 1 if a score dropped below the baseline")
args = parser.parse_args()
cases = load_cases(Path("evals/questions.jsonl"))
started = time.perf_counter()
try:
assistant = build_assistant()
rows = [evaluate_case(assistant, case, retrieval_only=args.retrieval_only) for case in cases]
except FileNotFoundError as err:
sys.exit(str(err))
except openai.OpenAIError as err:
sys.exit(friendly(err))
def mark(value) -> str:
return "-" if value is None else ("ok" if value else "FAIL")
print(f"{'case':<20} {'rank':>4} {'cos':>6} {'bm25':>6} answered source facts refused")
for r in rows:
print(f"{r['id']:<20} {r['rank'] or '-':>4} {r['top_cosine']:>6.3f} {r['top_bm25']:>6.2f} "
f"{mark(r.get('answered')):<8} {mark(r.get('right_source')):<6} {mark(r.get('facts')):<5} "
f"{mark(r.get('refused'))}")
summary = summarize(rows)
print("\n" + " ".join(f"{k} {v:.2f}" for k, v in summary.items() if v is not None))
on = [r["top_cosine"] for r, c in zip(rows, cases) if c.answerable]
off = [r["top_cosine"] for r, c in zip(rows, cases) if not c.answerable]
print(f"best cosine: answerable {min(on):.3f} to {max(on):.3f}, off-topic {min(off):.3f} to {max(off):.3f}"
f" ({time.perf_counter() - started:.0f}s)")
Path("reports").mkdir(exist_ok=True)
report = {"summary": summary, "rows": rows, "retrieval_only": args.retrieval_only}
Path("reports/latest.json").write_text(json.dumps(report, indent=2), encoding="utf-8")
if args.save_baseline:
BASELINE.write_text(json.dumps(summary, indent=2) + "\n", encoding="utf-8")
print(f"saved {BASELINE}")
if args.gate:
try:
baseline = load_baseline(BASELINE)
except FileNotFoundError as err:
sys.exit(str(err))
problems = compare(summary, baseline, metrics=["recall@5", "mrr"] if args.retrieval_only else None)
for p in problems:
print(f"GATE FAIL {p}")
print("gate: failed" if problems else "gate: passed")
sys.exit(1 if problems else 0) - The same script for local runs and CI: one code path.line 18
- A retrieval-only run has no answer metrics; comparing them would report them all as missing.line 60
- The exit status is the gate. GitHub Actions marks the step red on anything but 0.line 64
name: ci
on:
push:
pull_request:
workflow_dispatch: # a "Run workflow" button on the Actions tab
jobs:
tests:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: astral-sh/setup-uv@v6
- run: uv sync
- run: uv run pytest -q
eval-gate:
if: github.event_name == 'pull_request' || github.event_name == 'workflow_dispatch'
needs: tests
runs-on: ubuntu-latest
timeout-minutes: 45
steps:
- uses: actions/checkout@v4
- uses: astral-sh/setup-uv@v6
- run: uv sync
- name: Start Ollama and pull the models
run: |
curl -fsSL https://ollama.com/install.sh | sh
curl -sf http://localhost:11434/api/version || (ollama serve > ollama.log 2>&1 &)
for i in $(seq 30); do curl -sf http://localhost:11434/api/version && break; sleep 1; done
ollama pull llama3.2:3b
ollama pull nomic-embed-text
- name: Build the index
run: uv run index_docs.py
- name: Run the evals and the regression gate
run: uv run run_evals.py --gate
- name: Keep the report
if: always()
uses: actions/upload-artifact@v4
with:
name: eval-report
path: reports/latest.json - What starts the workflow. GitHub reads every
.ymlfile in.github/workflows/.line 5 - Adds a **Run workflow** button on the Actions tab, to run the gate without a pull request.line 6
- Installs uv on the runner.
uv syncthen installs Python 3.12 (from.python-version) and the locked packages fromuv.lock.line 13 - The fast job: no model, about a second, on every push.line 15
- The slow job runs only for pull requests and the button, not for every push to a branch.line 18
- No point running a slow eval when the unit tests already fail.line 19
- The installer usually starts Ollama as a service; if it did not, start it in the background, then wait until it answers.line 29
- The runner starts empty: build the index first.line 34
- Upload the report even when the gate failed, so you can see which rows changed.line 38
from pathlib import Path
import pytest
from gate import compare, load_baseline
BASE = {"recall@5": 1.0, "mrr": 0.9, "answered": 0.95, "facts": None, "refused": 1.0}
def test_equal_or_better_scores_pass():
assert compare(dict(BASE), BASE) == []
assert compare({"recall@5": 1.0, "mrr": 1.0, "answered": 1.0, "refused": 1.0}, BASE) == []
def test_a_drop_within_the_tolerance_passes():
now = {"recall@5": 0.95, "mrr": 0.86, "answered": 0.90, "refused": 1.0}
assert compare(now, BASE) == [] # one case of 20 flipping is 0.05: still allowed
def test_a_bigger_drop_fails_with_a_clear_message():
now = {"recall@5": 1.0, "mrr": 0.9, "answered": 0.95, "refused": 0.8}
assert compare(now, BASE) == ["refused: 0.80, baseline 1.00 (allowed drop 0.05)"]
def test_a_metric_that_disappeared_fails():
assert compare({"recall@5": 1.0, "mrr": 0.9, "answered": 0.95}, BASE) == ["refused: missing now, baseline 1.00"]
def test_baseline_none_is_not_compared_and_metrics_can_be_limited():
assert compare({"recall@5": 1.0, "mrr": 0.9}, BASE, metrics=["recall@5", "mrr"]) == []
def test_a_missing_baseline_says_how_to_make_one(tmp_path):
with pytest.raises(FileNotFoundError, match="--save-baseline"):
load_baseline(tmp_path / "baseline.json")
def test_ci_runs_the_tests_and_the_gate():
workflow = Path(".github/workflows/ci.yml").read_text()
assert "uv run pytest -q" in workflow
assert "uv run index_docs.py" in workflow # the gate needs an index on the runner
assert "run_evals.py --gate" in workflow
assert "ollama pull nomic-embed-text" in workflow and "ollama pull llama3.2:3b" in workflow - Exactly one question in 20 flipping: allowed.line 15
- A small guard: nobody can quietly delete the gate step from the workflow.line 38
uv run run_evals.py --gate
mv docs/jobs-and-retries.md .
uv run index_docs.py
uv run run_evals.py --gate; echo "exit status $?"
mv jobs-and-retries.md docs/
uv run index_docs.py ... recall@5 1.00 mrr 0.93 answered 0.95 right_source 0.90 facts 0.83 refused 0.80 gate: passed removed jobs-and-retries.md 7 unchanged, 0 added, 0 changed, 1 removed 36 chunks: 0 embedded, 36 reused (0.1s) ... recall@5 0.75 mrr 0.70 answered 0.85 right_source 0.70 facts 0.67 refused 0.80 GATE FAIL recall@5: 0.75, baseline 1.00 (allowed drop 0.05) GATE FAIL mrr: 0.70, baseline 0.93 (allowed drop 0.05) GATE FAIL answered: 0.85, baseline 0.95 (allowed drop 0.05) GATE FAIL right_source: 0.70, baseline 0.90 (allowed drop 0.05) GATE FAIL facts: 0.67, baseline 0.83 (allowed drop 0.05) gate: failed exit status 1 added jobs-and-retries.md 7 unchanged, 1 added, 0 changed, 0 removed 41 chunks: 5 embedded, 36 reused (0.4s)
Stuck on this milestone?
evals/baseline.json is missing- Run
uv run run_evals.py --save-baselinewith your model, commit the file, and push again. - The gate fails on a run where nothing changed
- One borderline question flipped twice. Open
reports/latest.json(or the CI artifact), find the rows that changed and read the answers. Fix the label or the question if it is ambiguous; do not just raise the tolerance. - Windows:
mvorecho $?do not work - In PowerShell use
Move-Item docs\jobs-and-retries.md .and$LASTEXITCODEinstead of$?. - The CI job times out
- A runner without a GPU is slow: raise
timeout-minutes, or run--retrieval-only --gateon every pull request and the full gate nightly with aschedule:trigger.
Check it works
Two checks. All 61 tests pass with no model running, and the full eval run against your local models passes the gate against the baseline you saved in milestone 8. Then open http://localhost:8000 and ask three questions of your own: one the docs answer, one with an exact error code, and one they do not answer.
uv run pytest -q && uv run run_evals.py --gate ............................................................. [100%] 61 passed in 1.30s ... gate: passed
Review rubric
Review your project the way a senior engineer or an interviewer would. Aim for the right column on every row.
| Area | Works | Production-ready |
|---|---|---|
| Ingestion and chunking | All three formats load; chunks are a fixed number of characters. | Sections with heading paths, code blocks and table rows kept whole, menus and footers dropped, stable ids and anchors, and a test for each format. |
| Index freshness | The whole index is rebuilt on every change. | Only chunks with a new content hash are embedded; deletes and model changes are handled; writes are atomic; the report says what changed. |
| Retrieval | Vector search returns the top 5. | BM25 + vectors with RRF, an optional reranker behind an interface, every score kept on each hit, and recall@5 and MRR measured before and after each change. |
| Grounding and citations | The prompt asks for citations. | Citations are parsed and validated in code, invalid numbers are dropped, uncited answers get one nudge and are then refused, and every citation links to the exact section. |
| Refusals | The prompt says "say you do not know". | A retrieval check skips the model for off-topic questions, thresholds are set from measured score ranges, trap questions are in the eval set, and refused and answered are both tracked. |
| API and UI | An endpoint returns the whole answer as JSON. | Streaming SSE with a typed final event and in-stream errors, input validation, a cheap /health with a 503 when not ready, and a page that never injects model text as HTML. |
| Evals and CI | A script prints some scores. | A labelled set with traps, rule checks per row, a JSON report, a baseline with a justified tolerance, and a CI gate that fails pull requests (proven by breaking it on purpose). |
Stretch goals
- Re-index without a restart: add
POST /reindex(protected by a token) that runssync_indexand swaps the cached assistant, or watchdocs/for changes. Keep serving the old index until the new one is complete. - Follow-up questions: accept the conversation history and rewrite a follow-up like "and on the Team plan?" into a standalone question before retrieval. Add three follow-up cases to the evals.
- An LLM judge for faithfulness (lab 12): grade whether every claim in the answer is in the cited chunk, calibrate the judge against a few hand labels, and add it to the report and the gate.
- Access control: give each doc a
groupsfield in the metadata and filter chunks by the user's groups before retrieval, so a user can never get an answer from a page they cannot see. Add a test that proves it. - Compare models: run the evals with a larger local model and a hosted one, and add latency and cost per question to the report. Decide with a table, not a feeling.
Troubleshooting
Cannot reach the model server. Is Ollama running?
Open the Ollama app or run ollama serve, then try again. If you changed LLM_BASE_URL, check it ends in /v1.
Answers are slow (20 seconds or more)
The model runs on the CPU, and each question sends five chunks. Lower k in Assistant to 3, keep max_chars at 1200, and close other heavy apps. The first question after a pause also reloads the model.
Answers changed after you edited a doc, but search still finds the old text
The server cached the assistant with the old index. Run uv run index_docs.py and restart uvicorn (or build the /reindex stretch goal).
Results are wrong after switching EMBED_MODEL
sync_index rebuilds every vector when the model name changes. If you changed the model behind the same name (a new version pulled under the same tag), delete index/ and index again.
It answers from general knowledge with a citation
The model cited a source that does not contain the fact. The facts and right_source checks catch it in the evals. Make the system prompt stricter, try a larger model, or add the LLM judge stretch goal.
What changes in production
- Index offline, serve read-only. Build the index in CI or a job when docs change, ship it as an artifact, and let the service only load it. A web request should never trigger embedding.
- Treat docs as untrusted input. A page can contain text like "ignore your rules". Keep the system prompt short and firm, never let model output run code or become HTML, and log questions that produce refusals or nudges.
- Log every answer with its evidence: question, retrieved chunk ids and scores, the model, attempts, the refusal reason and latency. That log is where new eval cases come from.
- Version the knobs together. Chunker version, embedding model,
k, thresholds and prompt all change answers. Record them in the report next to the scores, and change one at a time. - Put limits on
/ask: authentication, a rate limit per user, and a cap on concurrent model calls, because every question costs real compute.
Interview angle
“Walk me through the docs assistant you built. How do you know it does not make things up?”
It is a RAG service in Python. Ingestion parses Markdown, HTML and PDF into sections with their heading path, so each chunk carries context and a link target, and an index embeds only chunks whose content hash changed. Retrieval is hybrid: BM25 for exact terms like error codes, vectors for paraphrases, merged with Reciprocal Rank Fusion, with an optional cross-encoder reranker. For grounding I do not trust the prompt alone: the code refuses before calling the model when retrieval is weak, validates every [n] citation after it answers, nudges once when an answer has no valid citation, and refuses if it still does not. It streams from FastAPI over Server-Sent Events, and the final event carries the checked answer. To know it works I keep 25 labelled questions, five of which must be refused, including traps that share words with the docs. I track recall@5, MRR, right-source citations, facts and refusals, and a CI gate fails any pull request that drops a score by more than 0.05. Then I quote my own numbers from the report, and the trade-offs: the reranker costs latency per question, and thresholds come from the measured score ranges, not from guesses.
Clean up
Keep the models: the next capstone uses them too. The index and reports can always be rebuilt, and .venv comes back with uv sync.
rm -rf index reports .venv Practice
No model needed: these run in your browser and check your answer.
Parse the citations
Write cited_numbers(text): return every number cited in [n] or [n, m] markers, in order of first appearance, without repeats. Ignore brackets that do not hold only numbers, like [note].
import re
def cited_numbers(text):
# your code here
return []
print(cited_numbers("A [2]. B [1, 2]. C [3][1]."))
Hint
A regex for the inside of one marker: `\[(\d+(?:\s*,\s*\d+)*)\]`. `re.findall` returns the captured group of each match; split it on commas.
Mean reciprocal rank
Write mrr(ranks). ranks holds, for each eval question, the 1-based rank of the first right result, or None when it was not found. Return the mean of 1 / rank, counting None as 0. An empty list gives 0.0.
def mrr(ranks):
# your code here
return 0.0
print(mrr([1, 2, None, 1]))
Hint
Turn each rank into `1 / rank` or `0.0`, then divide the sum by `len(ranks)`. Check for the empty list first.
The full project
The full reference solution, as it is after the last milestone. Build your own first, then compare.