Run a customer pilot end to end

Simulate a complete forward deployed engagement for a fictional customer, Northwind Benefits, whose case workers spend too long finding answers in a large set of policy documents. You will write the discovery summary and pilot plan, build a permission-aware question-answering service with citations over real public documents, create an evaluation set and measure against a baseline, package and deploy it with Docker Compose behind a login, prepare the security pack, run a demo, and hand it over with runbooks and an outcome report. Every artefact is something an FDE produces in a real engagement.

Intermediate about 10 hours 7 phases · 27 steps 0 / 27 done
What you will have at the end

A public repository containing docs/ (discovery summary, pilot plan, design note, security pack, outcome report, runbooks), app/ (FastAPI service with permission-filtered retrieval and citations, Streamlit UI), evals/ (question set, harness and results), and deploy/ (Compose stack with health checks), plus a recorded 15-minute demo. Reviewers can follow your thinking from the customer's problem to a measured result.

Before you start
  • Python, git and Docker basics
  • The stage 2 and 3 lessons of this track (discovery, scoping, customer data, communication, LLM apps, prototyping)
  • Access to any LLM API or a local model you can call from Python
Tools you will install
  • FastAPI — the backend API that holds retrieval and answer logic ↗
  • Streamlit — a thin prototype UI for users and demos ↗
  • DuckDB — a local store with full-text search for the keyword half of hybrid retrieval ↗
  • Docker Compose — package and run the stack the way a customer pilot would ↗
  • pytest — tests for the permission filter and parsing logic ↗
Repository layout at the end
northwind-pilot/
├── docs/
│   ├── 01-discovery-summary.md
│   ├── 02-pilot-plan.yaml
│   ├── 03-design-note.md
│   ├── 04-security-pack.md
│   ├── 05-outcome-report.md
│   └── runbooks/
├── data/
│   ├── raw/                 # public documents standing in for customer policies
│   └── acl.csv              # which group may read which document
├── app/
│   ├── ingest.py            # parse, chunk, index with ACLs
│   ├── retrieve.py          # keyword search + permission filter
│   ├── api.py               # FastAPI: /healthz /readyz /ask
│   └── ui.py                # Streamlit front end
├── evals/
│   ├── questions.csv        # question, expected answer, source doc, group
│   └── run_evals.py
├── tests/
└── deploy/compose.yml

Tick each step as you finish it — your progress is saved in this browser only (back up or restore on the hub). Every code block has a copy button. If something goes wrong, the troubleshooting section at the end covers the usual suspects.

Phase 1

Set the scene and run discovery

A realistic customer context and a one-page discovery summary that defines the problem, users, data and success metric.

  1. Create the repository and folder layout.
    bash
    gh repo create northwind-pilot --public --clone && cd northwind-pilot
    mkdir -p docs/runbooks data/raw app evals tests deploy
  2. Choose 40 to 80 public documents that stand in for Northwind's policies: for example a government's benefit guidance pages or public regulations saved as text or PDF. Put them in data/raw/.
    Use documents you are allowed to republish in a public repository; government publications are usually fine. Record the source of each in a data/SOURCES.md.
  3. Write the customer brief in your own words: Northwind's 60 case workers answer benefit questions by searching these documents; finding the right clause takes several minutes; mistakes cause appeals. Split the documents into two groups, general and fraud-team, and write data/acl.csv mapping each document to the groups allowed to read it.
    text
    doc_id,groups
    housing-support-2025,general|fraud-team
    fraud-investigation-procedures,fraud-team
  4. Role-play two discovery interviews (ask a friend to be a case worker and a team lead) using the question bank from the discovery lesson, and record five facts with numbers and two quotes.
    If you have nobody to interview, write the answers you would expect and mark them clearly as assumptions to validate.
  5. Write docs/01-discovery-summary.md with the eight sections from the discovery lesson, ending with the decision you request: proceed to a six-week pilot for the general case-worker team.
    Check: Someone who has never heard of the project can explain the problem, the user and the metric after reading it.
Phase 2

Scope the pilot

A pilot plan with success criteria, boundaries, dependencies, risks and a decision date.

  1. Write docs/02-pilot-plan.yaml with users, duration, primary metric (median time to answer a case question), guardrails (answer accuracy, citation correctness, no restricted-document leaks) and in-scope and out-of-scope lists.
    yaml
    pilot: northwind-policy-assistant
    duration_weeks: 6
    users: 10 general case workers
    success_criteria:
      primary: median time to answer a case question down >= 40% vs baseline
      guardrails:
        - correct answer on >= 90% of 60 expert-checked questions
        - every answer cites at least one source
        - zero answers drawn from documents the user may not read
    in_scope: [general policy documents, web UI behind login, English]
    out_of_scope: [writing to case systems, mobile, other languages]
    decision: sponsor go/no-go at end of week 6
  2. Add a dependencies table (document export, SSO registration, security review slot, expert reviewer time) with owners and dates, and a risk register with at least five risks.
    Put both in the YAML or a markdown file next to it; what matters is owners and dates.
  3. Write docs/03-design-note.md comparing two hosting options for the model (a hosted API with zero-retention terms versus a self-hosted open model) and recommend one with reasons.
    Check: The note ends with 'Decision needed from: ... by: ...'.
Phase 3

Ingest documents with permissions

Every chunk indexed with its source, heading and access groups, ready for keyword search.

  1. Create the environment.
    bash
    uv init --app . && uv add fastapi uvicorn streamlit duckdb pypdf httpx pydantic
    uv add --dev pytest ruff
  2. Write the ingestion script: extract text, split by headings into chunks of at most 1,500 characters, attach doc_id, heading and groups, and load everything into DuckDB with a full-text index.
    python
    # app/ingest.py
    import csv
    import pathlib
    import re
    
    import duckdb
    from pypdf import PdfReader
    
    RAW = pathlib.Path("data/raw")
    acl = {r["doc_id"]: r["groups"] for r in csv.DictReader(open("data/acl.csv"))}
    
    
    def text_of(path: pathlib.Path) -> str:
        if path.suffix == ".pdf":
            return "\n".join(p.extract_text() or "" for p in PdfReader(path).pages)
        return path.read_text(errors="ignore")
    
    
    rows = []
    for path in sorted(RAW.iterdir()):
        doc_id = path.stem
        for i, sec in enumerate(re.split(r"\n(?=[A-Z][^\n]{3,80}\n)", text_of(path))):
            heading = sec.strip().splitlines()[0][:100] if sec.strip() else doc_id
            for start in range(0, len(sec), 1500):
                rows.append((f"{doc_id}:{i}:{start}", doc_id, heading,
                             acl.get(doc_id, ""), sec[start:start + 1500]))
    
    con = duckdb.connect("data/index.duckdb")
    con.execute("CREATE OR REPLACE TABLE chunks(id TEXT, doc_id TEXT, heading TEXT, groups TEXT, body TEXT)")
    con.executemany("INSERT INTO chunks VALUES (?, ?, ?, ?, ?)", rows)
    con.execute("INSTALL fts; LOAD fts")
    con.execute("PRAGMA create_fts_index('chunks', 'id', 'heading', 'body', overwrite=1)")
    print(f"indexed {len(rows)} chunks from {len(acl)} documents")
    Check: The script prints a chunk count, and documents missing from acl.csv are reported rather than silently readable by everyone (add that check).
  3. Make documents without an ACL entry fail loudly instead of defaulting to readable: in ingest.py, collect any doc_id not in acl and exit with an error listing them.
    Defaulting to open is the classic permission leak.
Phase 4

Retrieve with permissions and answer with citations

An API that only ever uses passages the user may read and cites them in every answer.

  1. Write retrieval: full-text search, then filter by the user's groups before anything else happens.
    python
    # app/retrieve.py
    import duckdb
    
    con = duckdb.connect("data/index.duckdb", read_only=True)
    con.execute("LOAD fts")
    
    
    def search(question: str, user_groups: set[str], k: int = 6) -> list[dict]:
        rows = con.execute(
            """SELECT id, doc_id, heading, groups, body,
                      fts_main_chunks.match_bm25(id, ?) AS score
               FROM chunks WHERE score IS NOT NULL ORDER BY score DESC LIMIT 50""",
            [question]).fetchall()
        allowed = [r for r in rows if user_groups & set(r[3].split("|"))]
        return [{"id": r[0], "doc_id": r[1], "heading": r[2], "text": r[4]} for r in allowed[:k]]
  2. Write a test proving a general user never receives a fraud-team document, even for a question that matches it exactly.
    python
    # tests/test_permissions.py
    from app.retrieve import search
    
    
    def test_general_user_cannot_see_fraud_docs():
        hits = search("fraud investigation procedures", {"general"})
        assert all(h["doc_id"] != "fraud-investigation-procedures" for h in hits)
    
    
    def test_fraud_team_can_see_them():
        hits = search("fraud investigation procedures", {"fraud-team"})
        assert any(h["doc_id"] == "fraud-investigation-procedures" for h in hits)
    Check: uv run pytest -q passes.
  3. Write the API with health, readiness and an /ask endpoint that builds a cited prompt from allowed passages and calls your model through one call_llm function.
    python
    # app/api.py
    from fastapi import FastAPI
    from pydantic import BaseModel
    
    from app.llm import call_llm          # your provider or local model, one function
    from app.retrieve import search
    
    app = FastAPI(title="Northwind policy assistant")
    GROUPS = {"alice": {"general"}, "bob": {"general", "fraud-team"}}   # stands in for SSO groups
    
    
    class Ask(BaseModel):
        user: str
        question: str
    
    
    @app.get("/healthz")
    def healthz():
        return {"ok": True}
    
    
    @app.post("/ask")
    def ask(req: Ask):
        hits = search(req.question, GROUPS.get(req.user, set()))
        if not hits:
            return {"answer": "I could not find this in documents you can access.", "sources": []}
        context = "\n\n".join(f"[{i + 1}] ({h['doc_id']}) {h['text']}" for i, h in enumerate(hits))
        answer = call_llm("Answer only from the numbered sources and cite them like [1]. "
                          "If they do not contain the answer, say so.\n\n"
                          f"{context}\n\nQuestion: {req.question}")
        return {"answer": answer, "sources": [h["doc_id"] for h in hits]}
    Unknown users get no groups and therefore no documents: deny by default.
  4. Add a /readyz endpoint that returns 503 if the index cannot be opened or the model call fails a tiny test prompt.
    Check: Stopping the model or deleting the index makes /readyz return 503.
Phase 5

Evaluate against a baseline

Numbers for accuracy, citations and leak-safety, plus a measured time-to-answer comparison.

  1. Write 60 evaluation questions in evals/questions.csv with the expected answer, the source document and the asking group; include ten questions whose answer is not in the documents and five that would require fraud-team documents asked as a general user.
    text
    question,expected,source_doc,group
    What is the maximum housing support period?,12 months,housing-support-2025,general
    What is the penalty for late renewal?,NOT_IN_DOCS,,general
  2. Write evals/run_evals.py to call /ask for each question and record: whether the expected source was cited, whether the answer contains the expected fact (manual review or a calibrated judge), whether 'not found' was said when expected, and whether any restricted document appeared.
    For the correctness column, a simple first pass is to review 60 answers by hand; it takes under an hour and is exactly what customer experts would do.
  3. Measure the baseline: time yourself (or a volunteer) answering ten questions by searching the raw documents manually, then answering ten different questions with the assistant. Record times per question.
    Check: You have two lists of times and can compute medians.
  4. Change one thing (chunk size, k, or the prompt), rerun the evaluation, and keep whichever version scores better; record both results.
    One variable at a time, as in the inference track.
Phase 6

Package, secure and deploy

A Compose stack a customer could run, with health checks, configuration from the environment and a security pack.

  1. Write a Dockerfile for the API (non-root user, pinned base) and one for the UI, then a Compose file with health checks and configuration from an env file.
    yaml
    # deploy/compose.yml
    services:
      api:
        build: {context: .., dockerfile: deploy/Dockerfile.api}
        env_file: ../.env
        volumes: ["../data:/app/data:ro"]
        healthcheck:
          test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8000/healthz')"]
          interval: 15s
      ui:
        build: {context: .., dockerfile: deploy/Dockerfile.ui}
        environment: {API_URL: "http://api:8000"}
        ports: ["8501:8501"]
        depends_on: {api: {condition: service_healthy}}
  2. Build and start the stack and confirm the UI answers questions with sources.
    bash
    cp .env.example .env   # model endpoint and key, never committed
    docker compose -f deploy/compose.yml up -d --build
    docker compose -f deploy/compose.yml ps
    Check: Both services show healthy; http://localhost:8501 works.
  3. Write docs/04-security-pack.md: a data-flow table for every arrow, a STRIDE list with at least eight threats and mitigations, and answers to the seven standard and seven AI-specific questions from the security-review lesson.
    Be honest about what a pilot lacks (for example real SSO) and how production would close it.
Phase 7

Demo, measure, hand over

A recorded demo, an outcome report with a decision request, and documentation that lets someone else run it.

  1. Prepare a seeded demo of eight questions (six that show value, one 'not found', one permission refusal) and record a 15-minute demo following the problem, live case, evidence, limits and ask structure.
    Check: The recording shows the permission refusal working live.
  2. Write docs/05-outcome-report.md: decision requested, headline result with medians, evaluation table, ROI estimate with written assumptions and a range, what did not work, and the proposed next phase.
    Use the ROI template from the outcomes lesson; label any assumed numbers clearly.
  3. Write three runbooks in docs/runbooks/ (re-index after new documents, rotate the model API key, everything answers 'not found') in the symptoms, check, fix, verify, escalate format.
  4. Ask a friend to follow your README and runbooks to run the stack and re-index from scratch without your help; fix every step where they stalled.
    Check: They succeed without asking you a question.
  5. Tidy, commit and publish; delete any API keys from your environment files and rotate the key you used for testing.
    bash
    docker compose -f deploy/compose.yml down
    git add -A && git commit -m "Northwind pilot: discovery to outcome report" && git push
Help

Troubleshooting

DuckDB says the fts extension is not installed
Run INSTALL fts; LOAD fts once with network access (the ingest script does this); in an offline environment, pre-download the extension. Retrieval loads it read-only after ingestion.
Answers ignore the sources or invent facts
Check whether retrieval returned the right passage (print hits). If it did, tighten the instruction and lower temperature; if not, fix chunking or add keyword variants. Add the case to the evaluation set.
A general user sees a fraud-team document
Treat it as a sev-1 bug: check acl.csv for the document, confirm ingestion failed loudly on missing ACLs, and make sure filtering happens in search() before the prompt is built. Add the case to tests.
PDF text comes out empty or garbled
The PDF may be scanned images; use a text version of the document or add OCR, and note it as a data-quality finding in the discovery summary.
The UI cannot reach the API inside Compose
Use the service name (http://api:8000), not localhost, from the UI container, and check the API health check passes.
Next

Where to go from here

Did a step fail or feel unclear? Tell me which one →