{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## Week 05 — Code quality, unit testing (TDD), debugging (Syllabus 05)\n", "\n", "**Capstone track**: **B — Data collector + LLM analysis (OpenRouter) → report**\n", "\n", "### What you’ll build this week\n", "By the end of Week 05 you will have:\n", "\n", "- A **quality baseline** (Pythonic, clean, readable code)\n", "- A **test suite** that protects your core logic (and supports TDD)\n", "- A debugging workflow (logs, debugger, minimal reproductions)\n", "- A full capstone loop: **collect → store (SQLite) → analyze (OpenRouter) → report**\n", "\n", "### Primary resources\n", "- CS50P: [CS50P](https://cs50.harvard.edu/python/)\n", "- PEP 20 (Zen of Python): [PEP 20](https://peps.python.org/pep-0020/)\n", "- PEP 8 (Style Guide): [PEP 8](https://peps.python.org/pep-0008/)\n", "- Python docs: `unittest`: [unittest](https://docs.python.org/3/library/unittest.html)\n", "- Python docs: `logging`: [logging](https://docs.python.org/3/library/logging.html)\n", "- Python docs: `pdb`: [pdb](https://docs.python.org/3/library/pdb.html)\n", "- pytest (optional but recommended): [pytest](https://docs.pytest.org/)\n", "\n", "---\n", "\n", "## Lesson 05.1 — Code quality (clean code, code reviews)\n", "\n", "### You must understand\n", "- Write code for **humans first** (readability)\n", "- Keep functions small and composable\n", "- Keep I/O at the edges (“**pure core, impure shell**”)\n", "- Prefer explicit over clever\n", "\n", "### Lesson assignment (deliverables)\n", "- **E1 (quality)**: Refactor your capstone into 3 clear layers:\n", " - `sources/` (fetch + parse)\n", " - `pipeline/` (normalize, validate, dedupe)\n", " - `storage/` (JSONL + SQLite)\n", "- **E2 (quality)**: Add docstrings + type hints to all public functions.\n", "- **E3 (reviews)**: Write a `REVIEW_CHECKLIST.md` with a simple review rubric:\n", " - correctness, readability, tests, logging, failure modes, performance\n", "\n", "---\n", "\n", "## Lesson 05.2 — Unit testing (writing test cases, TDD)\n", "\n", "### You must understand\n", "- Unit tests should be **fast**, **deterministic**, and **isolated**\n", "- Test the core logic without network access\n", "- TDD workflow: **red → green → refactor**\n", "\n", "### Lesson assignment (deliverables)\n", "- **E4 (tests)**: Write tests for:\n", " - schema validation\n", " - deduplication\n", " - JSONL read/write\n", " - SQLite upsert\n", "- **E5 (TDD)**: Pick one feature and implement it using TDD:\n", " - Example: `normalize_text(text)`, `safe_slug(title)`, or `dedupe(items)`\n", "\n", "---\n", "\n", "## Lesson 05.3 — Debugging techniques and tools\n", "\n", "### You must understand\n", "- Debugging is a process: reproduce → minimize → inspect → fix → prevent (test)\n", "- Use logs for long-running pipelines\n", "- Use a debugger (`pdb` or IDE) for step-by-step inspection\n", "\n", "### Lesson assignment (deliverables)\n", "- **E6 (debug)**: Introduce 3 intentional bugs and fix them using:\n", " - structured logging (`logging`)\n", " - a minimal reproduction test\n", " - debugger (pdb or IDE)\n", "- **E7 (postmortem)**: Write a short note: what caused each bug + how you prevented it.\n", "\n", "---\n", "\n", "## Week 05 capstone milestone (Track B)\n", "\n", "### Goal\n", "Run an end-to-end pipeline and produce something useful.\n", "\n", "### Deliverables\n", "- **M1**: SQLite contains:\n", " - `items`\n", " - `llm_runs` (prompt + response + model + timestamps)\n", "- **M2**: A notebook cell (or script) that:\n", " - selects N items from SQLite\n", " - sends them to OpenRouter for analysis/summarization/classification\n", " - stores the result in `llm_runs`\n", "- **M3**: A final `report.md` (or `reports/week05_report.md`) that includes:\n", " - dataset description\n", " - collection method + limitations\n", " - 3–5 insights found by the LLM analysis\n", " - what you’d do next\n", "\n", "---\n", "\n", "## Optional add-on (DSA/LeetCode)\n", "- 6 problems: **dynamic programming**\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Quick sanity: the Zen of Python (read it!)\n", "import this # noqa: F401\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "\"\"\"Unit testing template (stdlib)\n", "\n", "You can run this cell as-is. Then replace the toy functions with your real ones.\n", "\n", "If you prefer pytest, keep the same test ideas but move them into `tests/`.\n", "\"\"\"\n", "\n", "from __future__ import annotations\n", "\n", "import unittest\n", "\n", "\n", "def normalize_text(s: str) -> str:\n", " # TODO (E5): implement using TDD; start with the tests below\n", " return \" \".join(s.strip().split())\n", "\n", "\n", "def dedupe_ids(ids: list[str]) -> list[str]:\n", " \"\"\"Return unique ids preserving first-seen order.\"\"\"\n", " seen: set[str] = set()\n", " out: list[str] = []\n", " for x in ids:\n", " if x in seen:\n", " continue\n", " seen.add(x)\n", " out.append(x)\n", " return out\n", "\n", "\n", "class TestCore(unittest.TestCase):\n", " def test_normalize_text_trims_and_collapses_whitespace(self):\n", " self.assertEqual(normalize_text(\" hello world \\n\"), \"hello world\")\n", "\n", " def test_dedupe_ids_preserves_order(self):\n", " self.assertEqual(dedupe_ids([\"a\", \"b\", \"a\", \"c\", \"b\"]), [\"a\", \"b\", \"c\"])\n", "\n", "\n", "unittest.TextTestRunner(verbosity=2).run(unittest.defaultTestLoader.loadTestsFromTestCase(TestCore))\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "\"\"\"Capstone B — OpenRouter analysis template\n", "\n", "This cell shows:\n", "- reading items from SQLite\n", "- calling OpenRouter (chat completions)\n", "- storing results in `llm_runs`\n", "\n", "Setup (Windows PowerShell example):\n", " $env:OPENROUTER_API_KEY = \"...\"\n", "\n", "Optional identification headers (recommended by OpenRouter):\n", " $env:OPENROUTER_HTTP_REFERER = \"http://localhost\"\n", " $env:OPENROUTER_APP_TITLE = \"AIEngineering Capstone\"\n", "\n", "Note: Endpoint/payload are written to match OpenAI-style chat APIs.\n", "\"\"\"\n", "\n", "from __future__ import annotations\n", "\n", "import json\n", "import os\n", "import sqlite3\n", "from datetime import datetime, timezone\n", "from pathlib import Path\n", "from typing import Any\n", "\n", "DB_PATH = Path(\"data/app.db\")\n", "\n", "\n", "def now_iso() -> str:\n", " return datetime.now(timezone.utc).isoformat()\n", "\n", "\n", "def connect() -> sqlite3.Connection:\n", " con = sqlite3.connect(DB_PATH)\n", " con.row_factory = sqlite3.Row\n", " return con\n", "\n", "\n", "def init_llm_table() -> None:\n", " with connect() as con:\n", " con.execute(\n", " \"\"\"\n", " CREATE TABLE IF NOT EXISTS llm_runs (\n", " id INTEGER PRIMARY KEY AUTOINCREMENT,\n", " item_id TEXT NOT NULL,\n", " model TEXT NOT NULL,\n", " prompt TEXT NOT NULL,\n", " response_json TEXT NOT NULL,\n", " created_at TEXT NOT NULL\n", " );\n", " \"\"\"\n", " )\n", " con.commit()\n", "\n", "\n", "def select_items(limit: int = 5) -> list[dict[str, Any]]:\n", " with connect() as con:\n", " rows = con.execute(\n", " \"SELECT id, title, text, url, source, fetched_at FROM items ORDER BY fetched_at DESC LIMIT ?\",\n", " (limit,),\n", " ).fetchall()\n", " return [dict(r) for r in rows]\n", "\n", "\n", "def store_llm_run(*, item_id: str, model: str, prompt: str, response: dict[str, Any]) -> None:\n", " with connect() as con:\n", " con.execute(\n", " \"\"\"\n", " INSERT INTO llm_runs (item_id, model, prompt, response_json, created_at)\n", " VALUES (?, ?, ?, ?, ?)\n", " \"\"\",\n", " (item_id, model, prompt, json.dumps(response, ensure_ascii=False), now_iso()),\n", " )\n", " con.commit()\n", "\n", "\n", "# --- OpenRouter call (requires requests) ---\n", "try:\n", " import requests # type: ignore\n", "except ImportError:\n", " requests = None\n", " print(\"Install deps: pip install requests\")\n", "\n", "\n", "def openrouter_chat(\n", " *,\n", " model: str,\n", " messages: list[dict[str, str]],\n", " temperature: float = 0.2,\n", ") -> dict[str, Any]:\n", " if requests is None:\n", " raise RuntimeError(\"requests not installed\")\n", "\n", " api_key = os.environ.get(\"OPENROUTER_API_KEY\")\n", " if not api_key:\n", " raise RuntimeError(\"Missing OPENROUTER_API_KEY env var\")\n", "\n", " http_referer = os.environ.get(\"OPENROUTER_HTTP_REFERER\")\n", " app_title = os.environ.get(\"OPENROUTER_APP_TITLE\")\n", "\n", " headers = {\n", " \"Authorization\": f\"Bearer {api_key}\",\n", " \"Content-Type\": \"application/json\",\n", " }\n", " if http_referer:\n", " headers[\"HTTP-Referer\"] = http_referer\n", " if app_title:\n", " headers[\"X-Title\"] = app_title\n", "\n", " payload = {\n", " \"model\": model,\n", " \"messages\": messages,\n", " \"temperature\": temperature,\n", " }\n", "\n", " # OpenRouter uses an OpenAI-compatible path.\n", " url = \"https://openrouter.ai/api/v1/chat/completions\"\n", " resp = requests.post(url, headers=headers, json=payload, timeout=60)\n", " resp.raise_for_status()\n", " return resp.json()\n", "\n", "\n", "# --- Run analysis on recent items ---\n", "init_llm_table()\n", "items = select_items(limit=3)\n", "print(\"Found\", len(items), \"items in DB\")\n", "\n", "MODEL = \"openai/gpt-4o-mini\" # TODO: pick a model you have access to\n", "\n", "for it in items:\n", " prompt = (\n", " \"You are analyzing a collected dataset item.\\n\"\n", " \"Return JSON with keys: summary (string), tags (list of strings), sentiment (one of: pos/neg/neutral).\\n\\n\"\n", " f\"TITLE: {it['title']}\\n\"\n", " f\"URL: {it['url']}\\n\"\n", " f\"TEXT: {it['text'][:2000]}\\n\"\n", " )\n", "\n", " messages = [\n", " {\"role\": \"system\", \"content\": \"You are a precise analyst.\"},\n", " {\"role\": \"user\", \"content\": prompt},\n", " ]\n", "\n", " # Uncomment when OPENROUTER_API_KEY is set:\n", " # response = openrouter_chat(model=MODEL, messages=messages)\n", " # store_llm_run(item_id=it[\"id\"], model=MODEL, prompt=prompt, response=response)\n", "\n", "print(\"Template ready. Next: uncomment the call and store results.\")\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "\"\"\"Debugging template: logging + pdb\n", "\n", "Run this cell, observe logs, then step into the debugger.\n", "Replace the toy bug with a real bug from your pipeline.\n", "\"\"\"\n", "\n", "from __future__ import annotations\n", "\n", "import logging\n", "\n", "logging.basicConfig(\n", " level=logging.INFO,\n", " format=\"%(asctime)s %(levelname)s %(name)s: %(message)s\",\n", ")\n", "log = logging.getLogger(\"capstone\")\n", "\n", "\n", "def buggy_divide(a: int, b: int) -> float:\n", " log.info(\"Dividing a=%s by b=%s\", a, b)\n", " return a / b\n", "\n", "\n", "def run_bug_demo() -> None:\n", " xs = [5, 4, 3, 2, 1, 0]\n", " for x in xs:\n", " try:\n", " y = buggy_divide(10, x)\n", " log.info(\"result=%s\", y)\n", " except ZeroDivisionError:\n", " log.exception(\"Hit division by zero\")\n", " # Uncomment to debug interactively:\n", " # import pdb; pdb.set_trace()\n", "\n", "\n", "run_bug_demo()\n", "\n", "# TODO (E6): pick 3 real bugs and fix them with:\n", "# - reproduction\n", "# - logs\n", "# - debugger\n", "# - a test that prevents regressions\n" ] } ], "metadata": { "language_info": { "name": "python" } }, "nbformat": 4, "nbformat_minor": 2 }