01B.10 Logging, Debugging and Packaging: Putting the Toolkit Together

FoundationsLesson 10 of 1112,657 words5 parts
Module 01B · 0 of 11 lessons done
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11

Lessons 01B.1 to 01B.9 gave you the toolkit: a reproducible uv project, typed settings and secrets, async Python, bounded concurrency, httpx, Pydantic models, a FastAPI service, pytest tests and a resilience layer. This lesson does three things with it. First, it teaches logging for services — the difference between print() and a logging pipeline that survives production: handlers, formatters, filters, levels, JSON output, request IDs, redaction and async-safe logging. Second, it teaches debugging — the ladder from print-debugging to breakpoint(), async-aware debugging, post-mortem crashes, HTTP debugging and profiling. Third, it teaches packaging and CLIs — what makes a directory a package, how pyproject.toml turns it into an installable distribution, and how to give it a command-line interface. It closes by assembling every module from the last nine lessons into one runnable aitoolkit project and giving you a readiness check for applying it in Modules 02–03.

What you'll learn

  • The logging architecture — loggers, handlers, filters, formatters, levels and propagation — and how to configure it once, correctly, with dictConfig
  • Structured JSON logging with a stdlib formatter you write yourself, plus when to reach for python-json-logger or structlog
  • Correlation/request IDs with contextvars, and redaction filters that keep secrets and PII out of log lines
  • Debugging: breakpoint() and pdb, VS Code launch configs, debugging async code, post-mortem debugging, faulthandler, -X dev, reproducing bugs in tests, HTTP debugging with httpx event hooks and curl -v, and profiling with cProfile, pstats, tracemalloc and py-spy
  • Command-line interfaces: argparse in depth, typer/click awareness, exit codes, stdin, __main__.py, python -m, console-script entry points, rich and tqdm awareness
  • Packaging: modules vs packages vs distributions, wheels and sdists, pyproject.toml [build-system] (including uv_build), uv build, editable installs, versioning, publishing awareness, and why LLM apps ship as applications rather than libraries
  • The complete aitoolkit project: every module consolidated, the tests layout, README, .env.example, .gitignore, an end-to-end walkthrough, and how to swap the fake backend for a real provider SDK
  • A readiness self-check — a checklist and a 20-question quiz — plus a map of which 01B skill each later module leans on

What you don't need

  • API keys or any provider account. Every runnable example uses the Python standard library only; the consolidated project needs no key because its backend is fake.
  • Deep knowledge of the earlier 01B lessons. Each is summarised where this lesson builds on it, and linked where it doesn't.
  • Production infrastructure. Logging pipelines, log aggregation, tracing backends and deployment platforms are covered as awareness with links to the lessons that own them (03.10, 11A.1, 11C.1).

Setup

No API key needed. Most of this lesson runs on the standard library alone — check your interpreter first:

bash
python3 --version    # needs 3.11+; 3.13+ recommended, 3.14 is fine

If you work inside the module's aitoolkit project from 01B.1, run snippets with uv run python file.py; otherwise python3 file.py works. The consolidated project at the end needs the packages earlier lessons added — one uv add line brings them all in:

bash
uv add httpx pydantic pydantic-settings \
       "fastapi[standard]" uvicorn pytest \
       tenacity python-dotenv
# or: pip install the same package names (quote "fastapi[standard]" so the shell keeps the brackets)

Samples that need third-party libraries (fastapi, httpx, pydantic, tenacity, typer, rich…) are written from the official documentation, and any output they print is labelled illustrative. Output labelled Output: comes from standard-library Python that runs exactly as shown.


What you must be able to do after this lesson#

  • Configure the logging module once with dictConfig
  • Write structured JSON logs with a request ID from contextvars
  • Redact secrets from log lines
  • Debug a failing program with breakpoint and pdb
  • Build a command-line tool with argparse and a console-script entry point
  • Build a wheel with uv build
  • Run the complete aitoolkit project end to end

Why this matters for an AI engineer#

An LLM application fails in ways a CRUD app rarely does: the model returns plausible-but-wrong text, a provider times out after 30 seconds, a retry loop multiplies cost, and "it worked yesterday" stops being an answer. When that happens at 2 a.m., your only tools are the logs, the debugger and the tests — and the quality of all three was decided months earlier, when you chose print over logging, skipped exc_info, and let secrets ride along in URLs. This lesson is where the toolkit either becomes operable or stays a demo.

You'll hear... You'll understand it after...
"Check the logs — what request ID was that?" 1.7 Correlation IDs
"Why is the API key in the log aggregator?" 1.8 Redaction filters
"Our logs are unstructured — can we alert on them?" 1.6 JSON logging
"The service hangs and nothing is logged." 2.4 Debugging async, 2.5 faulthandler
"It fails in Docker but not on my laptop." 2.9 Debugging in containers
"How do I profile where the time goes?" 2.8 Profiling
"Ship it as a library so other teams can use it." 4.6 Apps vs libraries
"What does uv sync actually install?" 4.2–4.3 Build systems and installs
"Is my env ready for Modules 02–03?" Part 5: The readiness check

Part 1: Logging for services#

1.1 From print() to logging#

01A.8 introduced the logging module: loggers, levels, handlers, formatters and logger.exception(). This part assumes you know getLogger(__name__), logger.info/warning/error, and that print() is for humans while logging is for machines. What 01A.8 could not cover — because it was teaching the language, not running a service — is everything that makes logging work in production: configuring it once for a whole application, emitting machine-readable records, attaching context like request IDs, scrubbing secrets, and doing it safely from async code.

The gap between "I called logging.basicConfig()" and "these logs are operable" is the subject of this part.

1.2 The logging architecture#

Python's logging is a small publish/subscribe pipeline. Understanding the five moving parts once makes every later section obvious:

flowchart LR
    subgraph app ["Your application code"]
        L["logger.info('request done', extra={...})"]
    end
    subgraph pipeline ["The logging pipeline"]
        LG["Logger<br/>(named, hierarchical)"] --> FIL["Filters<br/>(drop or mutate records)"]
        LG --> H1["Handler 1<br/>(console)"]
        LG --> H2["Handler 2<br/>(file / JSON / network)"]
        H1 --> F1["Formatter<br/>(record -> text)"]
        H2 --> F2["Formatter<br/>(record -> JSON line)"]
    end
    F1 --> OUT1["stdout / stderr"]
    F2 --> OUT2["log file / aggregator"]
  • A logger is a named channel ("aitoolkit.http", "uvicorn.access"). Loggers form a tree by dotted name; a record logged to "aitoolkit.http" is also offered to "aitoolkit" and then to the root logger — this is propagation.
  • A handler decides where a record goes: console, file, socket, HTTP. A logger with no handlers still works because records propagate to ancestors that have them.
  • A filter can drop a record or mutate it (attach a request ID, redact a secret) before formatting.
  • A formatter turns the LogRecord into bytes: plain text for humans, JSON for machines.
  • A level (DEBUG < INFO < WARNING < ERROR < CRITICAL) is a threshold: a handler at INFO drops DEBUG records entirely.

1.3 Configuring logging once, with dictConfig#

logging.basicConfig() is fine for a ten-line script. It has three production problems: it only configures the root logger, it can only be called meaningfully once (later calls are no-ops unless force=True), and it can't express "this library is noisy, keep it at WARNING" without extra code.

logging.config.dictConfig() takes a plain dictionary — declarative, reviewable in a diff, and testable. Here is a complete, realistic configuration for aitoolkit:

python
# aitoolkit/logging_setup.py — the logging config, in one place
import logging.config
import logging.handlers
import os


def configure_logging(level: str = "INFO", json_logs: bool = False) -> None:
    """Configure logging for the whole application. Call once, at start-up."""
    logging.config.dictConfig({
        "version": 1,
        "disable_existing_loggers": False,  # don't silence libraries that already configured
        "formatters": {
            "brief": {
                "format": "%(asctime)s %(levelname)-8s %(name)s %(message)s",
                "datefmt": "%Y-%m-%dT%H:%M:%S%z",
            },
            "json": {"()": "aitoolkit.logging_setup.JsonFormatter"},
        },
        "handlers": {
            "console": {
                "class": "logging.StreamHandler",
                "formatter": "json" if json_logs else "brief",
                "level": "DEBUG",  # handler passes everything; loggers decide
            },
        },
        "loggers": {
            # our package: INFO and up; records propagate to root's console handler
            "aitoolkit": {"level": level},
            # noisy third parties: keep them quiet unless debugging
            "httpx": {"level": "WARNING"},
            "httpcore": {"level": "WARNING"},
            "uvicorn.access": {"level": "WARNING"},
        },
        "root": {"handlers": ["console"], "level": "WARNING"},
    })

Run for real — a minimal version of the same idea, with deterministic output:

python
# dictconfig_demo.py
import logging.config

CONFIG = {
    "version": 1,
    "disable_existing_loggers": False,
    "formatters": {
        "brief": {"format": "%(levelname)-8s %(name)s %(message)s"},
    },
    "handlers": {
        "console": {"class": "logging.StreamHandler", "formatter": "brief", "level": "DEBUG"},
    },
    "loggers": {
        "aitoolkit": {"handlers": ["console"], "level": "INFO", "propagate": False},
        "aitoolkit.http": {"level": "DEBUG"},  # inherit handlers, louder level
    },
    "root": {"handlers": ["console"], "level": "WARNING"},
}

logging.config.dictConfig(CONFIG)

log = logging.getLogger("aitoolkit")
log.info("service starting")
log.debug("this debug line is filtered out by the aitoolkit level")
logging.getLogger("aitoolkit.http").debug("per-request detail visible at DEBUG")
logging.getLogger("some_library").warning("library warnings still reach root at WARNING+")
Output3 lines
INFO     aitoolkit service starting
DEBUG    aitoolkit.http per-request detail visible at DEBUG
WARNING  some_library library warnings still reach root at WARNING+

Three things to notice. First, aitoolkit's INFO level dropped its own log.debug(...) line, but aitoolkit.http at DEBUG still emitted — child loggers can be more verbose than their parents because each logger's level is checked independently before propagation. Second, propagate: False on aitoolkit is what prevents its records from also being printed by the root handler — without it you'd see every line twice. Third, disable_existing_loggers: False matters: the default is True, which silently disables any logger a library configured before your dictConfig ran — a classic "my logs disappeared after adding config" bug.

1.4 Levels: what to log at which level#

Levels are a volume dial, not a severity score. The question to ask of every log call is "who acts on this, and at what verbosity should they see it?"

Level Use for Example in an AI service
DEBUG Detail you need only when reproducing a bug; expensive to produce Full request/response bodies (redacted), per-chunk progress, cache hit/miss internals
INFO The lifecycle of the service and each unit of work "service started", "request completed", one line per LLM call with model/latency/tokens
WARNING Something degraded but the request succeeded Retried once, fell back to a cheaper model, rate-limit header near cap, deprecated code path
ERROR A unit of work failed; the service continues Provider 500 after retries, validation failure on one item in a batch, a job that died mid-run
CRITICAL The service itself is in trouble Database pool exhausted, config invalid at start-up, unrecoverable state

Rules of thumb that survive contact with production:

  • One line per request at INFO, not per internal step. If a single HTTP request produces 40 log lines, the signal-to-noise ratio is already lost.
  • WARNING should be actionable. If nobody would ever look at it, it's DEBUG. If someone must look now, it's ERROR.
  • Never log secrets at any level — see 1.8.
  • Lazy formatting: logger.debug("payload: %s", huge_dict) evaluates huge_dict's str() only if the record survives the level check; an f-string evaluates it always. Use %-style args (or logger.debug("...", extra={...})) in hot paths.

1.5 Exceptions: logger.exception, exc_info and tracebacks#

When you catch an exception, you have three options, and choosing wrong is the most common logging bug:

python
try:
    result = await client.complete(prompt)
except ProviderError as exc:
    logger.error("completion failed: %s", exc)          # message only — WHERE did it fail?
    logger.error("completion failed", exc_info=True)    # traceback attached — verbose but complete
    logger.exception("completion failed")              # same as exc_info=True, inside except
    raise                                             # log AND propagate — usually correct
  • logger.exception(msg) is logger.error(msg, exc_info=True) and only works correctly inside an except block (it captures sys.exc_info()). Outside one it logs NoneType: None.
  • exc_info=True accepts an exception instance too (since Python 3.5): logger.error("failed", exc_info=exc) — handy when logging from a distance (e.g., inside a TaskGroup wrapper that received an ExceptionGroup).
  • logger.opt(exception=exc) is a Loguru-ism (Loguru is a third-party logging library); in stdlib logging the equivalent is exc_info.

Run it — the two traceback idioms side by side (both write to stderr, so the lines are interleaved as shown):

python
# traceback_demo.py
import logging
import traceback

log = logging.getLogger("demo")
handler = logging.StreamHandler()                    # stderr by default
handler.setFormatter(logging.Formatter("%(levelname)s %(name)s %(message)s"))
log.addHandler(handler)                              # formatters belong to handlers, not loggers
log.setLevel(logging.INFO)


def divide(a: float, b: float) -> float:
    return a / b


try:
    divide(10, 0)
except ZeroDivisionError:
    traceback.print_exc()          # prints to stderr, returns None
    log.exception("division failed")  # ERROR level + same traceback via logging
Example output · illustrative15 lines
Traceback (most recent call last):
  File "traceback_demo.py", line 17, in <module>
    divide(10, 0)
  File "traceback_demo.py", line 13, in divide
    return a / b
           ~~^~~
ZeroDivisionError: division by zero
ERROR demo division failed
Traceback (most recent call last):
  File "traceback_demo.py", line 17, in <module>
    divide(10, 0)
  File "traceback_demo.py", line 13, in divide
    return a / b
           ~~^~~
ZeroDivisionError: division by zero

traceback.print_exc() is for you while developing; logger.exception() is for the log pipeline — it carries level, logger name and (with a JSON formatter) structured fields. In service code, prefer the logger.

1.6 Structured JSON logs#

Text logs are for humans; structured logs — one JSON object per line, same keys every time — are for everything else: jq queries, log aggregators (Loki, CloudWatch, Datadog), alerting rules and the trace viewers of 11A.1. The format matters less than the consistency: every record should carry ts, level, logger, msg, plus your domain fields (request_id, model, latency_ms, tokens).

You can write a JSON formatter in twenty lines of stdlib. Run for real:

python
# json_formatter.py — a stdlib JSON formatter
import json
import logging
import time


class JsonFormatter(logging.Formatter):
    """One JSON object per line: what log aggregators ingest."""

    def __init__(self) -> None:
        super().__init__()
        self.converter = time.gmtime  # UTC, no local timezone surprises

    def format(self, record: logging.LogRecord) -> str:
        payload = {
            "ts": self.formatTime(record, "%Y-%m-%dT%H:%M:%SZ"),
            "level": record.levelname,
            "logger": record.name,
            "msg": record.getMessage(),
        }
        if record.exc_info:
            payload["exc"] = self.formatException(record.exc_info)
        # fields attached via extra={"k": v} land as record attributes
        standard = set(logging.makeLogRecord({}).__dict__) | {"message", "asctime"}
        for key, value in record.__dict__.items():
            if key not in standard:
                payload[key] = value
        return json.dumps(payload, default=str)


handler = logging.StreamHandler()
handler.setFormatter(JsonFormatter())
logger = logging.getLogger("demo")
logger.addHandler(handler)
logger.setLevel(logging.INFO)
logger.propagate = False

# Craft records with a fixed timestamp so this demo's output is reproducible.
rec = logging.LogRecord("demo", logging.INFO, "app.py", 12, "server started", (), None)
rec.created = 1_700_000_000.0
rec.port = 8080
print(handler.format(rec))

# Raise and catch inside exec'd code so the traceback's filename is "<string>"
# and this demo's output is byte-for-byte reproducible.
ns = {}
exec("import sys\ntry:\n    {}['missing']\nexcept KeyError:\n    exc_info = sys.exc_info()", ns)
rec2 = logging.LogRecord("demo", logging.ERROR, "app.py", 20, "lookup failed", (),
                         ns["exc_info"])
rec2.created = 1_700_000_000.0
rec2.request_id = "req-42"
print(handler.format(rec2))
Output2 lines
{"ts": "2023-11-14T22:13:20Z", "level": "INFO", "logger": "demo", "msg": "server started", "port": 8080}
{"ts": "2023-11-14T22:13:20Z", "level": "ERROR", "logger": "demo", "msg": "lookup failed", "exc": "Traceback (most recent call last):\n  File \"<string>\", line 3, in <module>\nKeyError: 'missing'", "request_id": "req-42"}

The extra={"k": v} mechanism is the key detail: logger.info("done", extra={"latency_ms": 812}) puts latency_ms on the record, and the loop above picks it up automatically — no formatter changes needed for new fields. Two caveats: extra keys must not collide with LogRecord's own attributes (name, msg, levelname…), or logging raises KeyError: "Attempt to overwrite 'name' in LogRecord"; and anything non-JSON-serialisable needs default=str (as above) or an explicit encoder.

1.7 Correlation IDs with contextvars#

When a request fails, the first question is always "which log lines belong to this request?" The answer is a correlation/request ID — one UUID per incoming request, attached to every log record produced while serving it, and propagated to downstream calls (provider headers, traceparent for OpenTelemetry — see 11A.1).

The mechanism is contextvars: a context-local variable that behaves like thread-local storage but works correctly across await points — exactly what async services need. A filter copies it onto every record; a formatter prints it.

python
# reqid_demo.py — one request id on every log line, via contextvars
import contextvars
import logging

_request_id: contextvars.ContextVar[str] = contextvars.ContextVar("request_id", default="-")


class RequestIdFilter(logging.Filter):
    def filter(self, record: logging.LogRecord) -> bool:
        record.request_id = _request_id.get()  # type: ignore[attr-defined]
        return True


fmt = logging.Formatter("%(request_id)s %(levelname)-5s %(name)s %(message)s")
handler = logging.StreamHandler()
handler.setFormatter(fmt)
handler.addFilter(RequestIdFilter())
log = logging.getLogger("api")
log.addHandler(handler)
log.setLevel(logging.INFO)
log.propagate = False


def handle(request_id: str, ticket: str) -> None:
    token = _request_id.set(request_id)
    try:
        log.info("fetching ticket %s", ticket)
        log.info("ticket %s -> 200 OK", ticket)
    finally:
        _request_id.reset(token)


handle("req-1042", "T-7781")
handle("req-1043", "T-9912")
log.info("outside any request")
Output5 lines
req-1042 INFO  api fetching ticket T-7781
req-1042 INFO  api ticket T-7781 -> 200 OK
req-1043 INFO  api fetching ticket T-9912
req-1043 INFO  api ticket T-9912 -> 200 OK
- INFO  api outside any request

In a FastAPI app, the same pattern plugs into middleware: generate or read X-Request-ID, _request_id.set(...), await call_next(request), reset in finally — and echo the ID back in the response header so users can quote it in bug reports. 11C.1 §2.11 shows exactly this middleware for the production llm_service, and 03.10 §4.4 covers propagating the ID to the provider so provider-side logs join yours.

1.8 Redaction filters: secrets and PII#

Logs are the most common place credentials leak: a URL with ?api_key=..., a repr() of a settings object, an exception message echoing a request body. Defence in depth has three layers, and this lesson covers the middle one:

  1. Don't put secrets in log calls — the real fix. Review every extra={...} and every %s argument.
  2. A redaction filter/formatter — the safety net for the accidents that remain.
  3. Access control + retention on the log store — owned by 12.4 and 11A.1 Part 7.

Run for real — a filter that scrubs both secret-shaped strings and email addresses before formatting:

python
# redact_demo.py — scrub secrets/PII out of every record before formatting
import logging
import re

SECRET_RE = re.compile(r"(api[_-]?key|token|password|secret)(\s*[=:]\s*)\S+", re.I)
EMAIL_RE = re.compile(r"[\w.+-]+@[\w-]+\.[\w.]+")


class RedactionFilter(logging.Filter):
    def filter(self, record: logging.LogRecord) -> bool:
        msg = record.getMessage()
        msg = SECRET_RE.sub(r"\1\2<redacted>", msg)
        msg = EMAIL_RE.sub("<email>", msg)
        record.msg, record.args = msg, ()
        return True


handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter("%(levelname)s %(message)s"))
handler.addFilter(RedactionFilter())
log = logging.getLogger("api")
log.addHandler(handler); log.setLevel(logging.INFO); log.propagate = False

log.info("calling upstream with api_key=sk-live-abc123 for %s", "sam@acme.io")
log.info("password: hunter2 rejected")
Output2 lines
INFO calling upstream with api_key=<redacted> for <email>
INFO password: <redacted> rejected

1.9 Async logging and "libraries log, apps configure"#

Two production concerns remain.

Logging from async code. logging is thread-safe but not async-aware: a StreamHandler or FileHandler performs blocking I/O on the event loop thread. For console output the cost is microseconds and usually fine; for file/network handlers under load it can stall the loop. The stdlib answer is logging.handlers.QueueHandler + QueueListener: the application puts records on an in-memory queue (non-blocking), and a background thread runs the real handlers. Overflow policy matters: QueueHandler.enqueue uses put_nowait, so with a bounded queue a full queue raises queue.Full, the record is dropped and handleError reports it on stderr. That is the right default for telemetry (drop, never apply backpressure to request handling); subclass enqueue if you want to count the drops as a metric. 11A.1 §4.2 applies the same fail-open, bounded-queue design to traces.

Who configures logging? The rule is libraries log, applications configure. Your modules call logging.getLogger(__name__) and emit records; they never call basicConfig/dictConfig at import time. If aitoolkit is imported by a notebook, a test suite or another service, it must not hijack the host's logging. Configuration lives in the entry point (service.py's lifespan/start-up, the CLI's main(), pytest's conftest.py), exactly once. This is also why tests can capture logs with caplog (a pytest fixture that attaches its own handler) without your code fighting it.

1.10 What to log for LLM calls (and the observability horizon)#

The preview, owned properly by 03.10 Part 4 and 11A.1: one structured record per model call carrying request_id, provider, model, latency_ms, ttft_ms for streams, input_tokens, output_tokens, finish_reason, attempt (retry count), estimated_cost_usd, and status. Never log prompt or completion bodies by default — they routinely contain PII, secrets pasted by users, and confidential documents; if you must, gate it behind a flag, redact it, sample it, and restrict retention (03.10 §4.5, 12.4).

Beyond logs sits tracing: spans with parent/child timing across your pipeline (retrieve → rerank → generate → cite), which is what actually answers "where did the 9 seconds go?" Structured logs and traces are complementary — logs are the searchable event stream, traces are the latency breakdown. 11A.1 Part 3 covers OpenTelemetry and its GenAI semantic conventions; the OTel Python SDK can also emit logs, so your logging pipeline and your tracer share the same request_id context.

1.11 The aitoolkit/logging_setup.py deliverable#

Putting 1.3–1.10 together, this is the logging module the rest of aitoolkit uses. It is stdlib-only except for the optional JSON path:

python
# aitoolkit/logging_setup.py — logging config, request IDs, redaction, JSON option
import contextvars
import json
import logging
import logging.config
import re
import time

_request_id: contextvars.ContextVar[str] = contextvars.ContextVar("request_id", default="-")

SECRET_RE = re.compile(r"(api[_-]?key|token|password|secret|authorization)(\s*[=:]\s*)\S+", re.I)


class JsonFormatter(logging.Formatter):
    """One JSON object per line — the format log pipelines ingest."""

    def __init__(self) -> None:
        super().__init__()
        self.converter = time.gmtime

    def format(self, record: logging.LogRecord) -> str:
        payload = {
            "ts": self.formatTime(record, "%Y-%m-%dT%H:%M:%SZ"),
            "level": record.levelname,
            "logger": record.name,
            "msg": record.getMessage(),
        }
        if record.exc_info:
            payload["exc"] = self.formatException(record.exc_info)
        standard = set(logging.makeLogRecord({}).__dict__) | {"message", "asctime"}
        for key, value in record.__dict__.items():
            if key not in standard:
                payload[key] = value
        return json.dumps(payload, default=str)


class RequestIdFilter(logging.Filter):
    def filter(self, record: logging.LogRecord) -> bool:
        record.request_id = _request_id.get()  # type: ignore[attr-defined]
        return True


class RedactionFilter(logging.Filter):
    """Last line of defence: scrub credential-shaped text from the final message."""

    def filter(self, record: logging.LogRecord) -> bool:
        msg = SECRET_RE.sub(r"\1\2<redacted>", record.getMessage())
        record.msg, record.args = msg, ()
        return True


def configure_logging(level: str = "INFO", json_logs: bool = False) -> None:
    """Configure logging for the whole application. Call once, at start-up."""
    filters = ["request_id", "redact"]
    logging.config.dictConfig({
        "version": 1,
        "disable_existing_loggers": False,
        "filters": {
            "request_id": {"()": RequestIdFilter},
            "redact": {"()": RedactionFilter},
        },
        "formatters": {
            "brief": {
                "format": "%(asctime)s %(levelname)-8s %(name)s [%(request_id)s] %(message)s",
                "datefmt": "%Y-%m-%dT%H:%M:%S",
            },
            "json": {"()": JsonFormatter},
        },
        "handlers": {
            "console": {
                "class": "logging.StreamHandler",
                "formatter": "json" if json_logs else "brief",
                "filters": filters,
                "level": "DEBUG",
            },
        },
        "loggers": {
            # our package: level gate only; records propagate to root's console
            # handler so every record passes through the same filters once.
            "aitoolkit": {"level": level},
            "httpx": {"level": "WARNING"},
            "httpcore": {"level": "WARNING"},
            "uvicorn.access": {"level": "WARNING"},
        },
        "root": {"handlers": ["console"], "level": "WARNING"},
    })


def set_request_id(request_id: str):
    """Set the correlation id for the current context; returns a reset token."""
    return _request_id.set(request_id)


def reset_request_id(token) -> None:
    _request_id.reset(token)


def current_request_id() -> str:
    return _request_id.get()

Two design notes. Filters attach to the handler, not the logger, so every handler gets the same redaction and request-ID treatment — put redact on every handler that leaves the process boundary (file, socket, HTTP), and it's fine to leave it off a local debug console if you want to see raw values while developing. And configure_logging is called from the entry point — service.py's start-up, the CLI's main() — never at module import.


Part 2: Debugging#

2.1 The debugging ladder#

Debugging is a ladder; each rung is slower but more powerful. Climb only as far as the bug requires:

Rung Tool Best for
1 Read the traceback and the code Most bugs — Python tracebacks are excellent
2 print() / logging.debug() "What value is this actually?" in a running system
3 breakpoint() / pdb State inspection: locals, step-through, evaluate expressions
4 Reproduce in a test Bugs that only happen sometimes — make them deterministic
5 HTTP debugging (event hooks, curl -v, proxy) "What actually went over the wire?"
6 Profilers (cProfile, tracemalloc, py-spy) "Where does the time/memory go?"
7 Tracing/observability (11A.1) Production: which span, which request, which model call

01A.8 covered rungs 1–2 and the basics of reading tracebacks; 03.10 Part 1 applies the whole ladder to LLM code specifically. This part fills in rungs 3–6.

2.2 breakpoint() and pdb#

breakpoint() (added in Python 3.7) drops you into the debugger at that line — no import needed:

python
def reconcile_totals(invoice: dict) -> float:
    subtotal = sum(line["amount"] for line in invoice["lines"])
    breakpoint()                      # debugger stops here
    return subtotal * (1 + invoice["tax_rate"])

At the (Pdb) prompt the commands that matter:

Command What it does
n / next Step over the next line (don't enter calls)
s / step Step into the next call
c / continue Run until the next breakpoint or exit
until N Run until line N of the current frame
p expr / pp expr Print an expression (pp = pretty)
w / u / d Where am I / up a frame / down a frame
l List source around the current line
b file:line / b func Set a breakpoint
tbreak Breakpoint that deletes itself after firing
display expr Re-print an expression at every stop
interact Drop into a full Python REPL in this frame's namespace
q / quit Quit the debugger (the program exits)
!stmt Run a Python statement (!x = 5 assigns)

PYTHONBREAKPOINT controls what breakpoint() calls: PYTHONBREAKPOINT=ipdb.set_trace() swaps in ipdb (0.13.13 as of November 2026 — IPython-powered pdb with tab completion and syntax highlighting); PYTHONBREAKPOINT=0 disables all breakpoints (useful in CI). In Python 3.14, breakpoint() and pdb.set_trace() always use pdb's new sys.monitoring backend (lower overhead than the older sys.settrace machinery, which a plain pdb.Pdb() instance still defaults to), and await pdb.set_trace_async() — also new in 3.14 — lets you stop inside a coroutine and await expressions at the prompt (as of November 2026, per the pdb docs). On 3.11–3.13, plain breakpoint() works in async code too; you just can't await at the prompt.

2.3 Debug configurations: VS Code launch.json#

The GUI equivalent of python -m pdb is your editor's debugger. For VS Code, a .vscode/launch.json covers the three things you'll debug constantly — a script, pytest, and the FastAPI service:

json
{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Debug pytest",
      "type": "debugpy",
      "request": "launch",
      "module": "pytest",
      "args": ["tests/", "-x", "--tb=short"],
      "justMyCode": false,
      "console": "integratedTerminal"
    },
    {
      "name": "Debug FastAPI (uvicorn)",
      "type": "debugpy",
      "request": "launch",
      "module": "uvicorn",
      "args": ["aitoolkit.service:app", "--reload", "--port", "8000"],
      "justMyCode": false,
      "console": "integratedTerminal"
    },
    {
      "name": "Debug current file",
      "type": "debugpy",
      "request": "launch",
      "program": "${file}",
      "console": "integratedTerminal",
      "justMyCode": false
    }
  ]
}

Three details that matter: "module": "pytest" (not program) makes the debugger treat pytest as __main__, which it requires; "justMyCode": false lets breakpoints inside library code (Pydantic validators, FastAPI internals, httpx) actually bind — leave it true for everyday speed; and "console": "integratedTerminal" keeps input()/prompts working. The debugpy backend ships with the Python and Microsoft Python extensions; other editors (PyCharm, Neovim+debugpy, Emacs realgud) offer equivalent attach/launch configs — the concepts transfer.

2.4 Debugging async code#

Async code breaks debugger assumptions twice: the loop juggles many tasks, and a naive breakpoint freezes everything while you inspect one task. The tools:

  • PYTHONASYNCIODEBUG=1 (or -X dev, below) turns on asyncio's debug mode: slow callback warnings, "coroutine never awaited" detection, and better exception context. Cheap, always worth it in development.
  • asyncio.all_tasks() — from a breakpoint or a signal handler, lists every live task with its coroutine and stack. Invaluable when "the service hangs": which tasks exist, which are stuck awaiting what.
  • asyncio.Task.get_stack() / task.print_stack() — the stack of a specific task, which a plain traceback won't show you.
  • aiomonitor (0.7.1 as of November 2026) — with aiomonitor.start_monitor(loop): gives you a telnet/web console into a running asyncio app: ps lists tasks, where/stacktrace prints their stacks, cancel kills one, console opens an async REPL in the loop. Awareness level: it's the right tool for a hung production-ish process; for development the debugger plus PYTHONASYNCIODEBUG covers most cases.
  • pdb.set_trace_async() (Python 3.14+) — await pdb.set_trace_async() works inside a coroutine, where plain breakpoint() historically confused pdb's await handling.
python
# hung_service_debug.py — what asyncio.all_tasks() buys you
import asyncio


async def stuck_worker() -> None:
    await asyncio.sleep(3600)  # "stuck" — waiting on something that never returns


async def main() -> None:
    worker = asyncio.create_task(stuck_worker(), name="invoice-worker")
    await asyncio.sleep(0.1)
    # Simulate "it's hung — what's alive?"
    for task in asyncio.all_tasks():
        print(f"{task.get_name()}: done={task.done()} cancelled={task.cancelled()}")
    worker.cancel()
    await asyncio.gather(worker, return_exceptions=True)

asyncio.run(main())

Run for real — output:

text
Task-1: done=False cancelled=False
invoice-worker: done=False cancelled=False

2.5 Post-mortem crashes, faulthandler and dev mode#

Three tools for "the process died and I have nothing":

Post-mortem debugging. python -m pdb script.py doesn't just debug from the start — if the program exits abnormally, pdb drops you into the crashed frame automatically, and -c runs commands first (useful for continue in scripted repros). python -m pdb -p PID (new in Python 3.14) attaches to a running process — the poor man's remote debugger. Inside a crashed REPL/session, pdb.pm() or import pdb; pdb.post_mortem() re-enters the last exception. One surprise: when the program finishes (or crashes), python -m pdb restarts it with your breakpoints and other state preserved — "why is it running again?" is the debugger offering another pass, not a bug. For pytest, pytest --pdb starts pdb on the first failure (combine with --pdbcls=IPython.terminal.debugger:Pdb for ipdb).

faulthandler dumps tracebacks on demand: python -X faulthandler script.py, PYTHONFAULTHANDLER=1, or in code faulthandler.dump_traceback_later(30) (dump all thread stacks if the process hangs >30 s — the single most useful "it's stuck in production" tool), faulthandler.enable() for fatal signals (SIGSEGV, SIGABRT, SIGFPE). It also dumps on SIGUSR1 if you call faulthandler.register(signal.SIGUSR1) — send the signal, read the stacks, process keeps running.

Run it:

python
# faulthandler_demo.py
import faulthandler
import time

faulthandler.dump_traceback_later(1, exit=True)
print("dumping stacks in 1s, then exiting")
time.sleep(5)
Example output · illustrative3 lines
Timeout (0:00:01)!
Thread 0x00000001fce0d300 (most recent call first):
  File "/path/to/faulthandler_demo.py", line 7 in <module>

Dev mode. python -X dev (or PYTHONDEVMODE=1; uv run inherits it, so PYTHONDEVMODE=1 uv run uvicorn ... works too) enables Python's development mode: faulthandler on fatal errors, asyncio debug, SyntaxWarning/ResourceWarning visibility, and extra checks that are too expensive for production. Make it the default for development: PYTHONDEVMODE=1 uv run uvicorn ... or a Makefile/just task. The warnings dev mode surfaces — unclosed files, unawaited coroutines, deprecated APIs — are exactly the bugs that become incidents.

2.6 Reproducing bugs in tests#

The strongest debugging tool is a failing test that reproduces the bug deterministically — 01B.8 owns pytest mechanics, but the debugging habit is: when you find a bug, first write the smallest test that fails for the same reason, then fix, then keep the test. This converts "I saw it once" into "it can never silently return". For flaky bugs, control the nondeterminism at its source: inject the clock (01B.9 shows Deadline/fake clocks), seed random, and replace real sleeps with asyncio.Events — 01B.8's async-testing section and 03.10 Part 5 (which reproduces LLM "bad answer" bugs by replaying the exact request) both expand on this.

2.7 HTTP debugging: event hooks, curl -v and proxies#

When "the API call fails" and the error message says nothing useful, look at the wire.

httpx event hooks (verified against the httpx docs): register callables that see every request before it is sent and every response after it arrives — the cleanest way to log method/URL/status/latency for every call your client makes, including SDK-internal retries. httpx.Client(event_hooks={"request": [...], "response": [...]}); with AsyncClient the hooks must be async def. For the provider SDKs, 03.10 §2.3 builds a full wire-logger with secret redaction on top of exactly this mechanism.

python
# wire_debug.py — minimal per-request logging hook for httpx (own code only)
import time
import httpx


def log_request(request: httpx.Request) -> None:
    request.extensions["start"] = time.perf_counter()
    print(f">>> {request.method} {request.url}")


def log_response(response: httpx.Response) -> None:
    elapsed = time.perf_counter() - response.request.extensions["start"]
    print(f"<<< {response.status_code} {response.request.method} "
          f"{response.request.url} ({elapsed * 1000:.0f} ms)")


client = httpx.Client(event_hooks={"request": [log_request], "response": [log_response]})
# client.get("https://example.com")  # would print both lines

curl -v shows the same wire view from the shell — TLS handshake, request headers, status line, response headers — and curl -v --trace-ascii dump.txt captures everything. It's the fastest way to answer "is the problem in my code or in the request?" when you can reproduce with a shell command.

A local proxy (mitmproxy, 12.3.1 as of November 2026, or HTTP(S)_PROXY + httpx's trust_env) captures full request/response bodies for any client — powerful and dangerous: it terminates TLS, so it sees credentials and PII in plaintext. Use it on localhost/fake services only, never pointed at production traffic containing real keys, and delete captures afterwards. For provider debugging prefer the SDK hooks above; reach for a proxy only when you need to see what a non-Python client sends.

2.8 Profiling: cProfile, pstats, tracemalloc and py-spy#

When the question is "where does the time/memory go?", guessing is how you optimise the wrong function.

CPU: cProfile + pstats. python -m cProfile -s cumulative script.py profiles the whole run and prints functions sorted by cumulative time; -o out.pstats saves for interactive analysis (python -m pstats out.pstats → sort cumtime, stats 20). For library code, wrap the suspect call: cProfile.runctx("fn()", globals(), locals(), filename="out.pstats") or the profile/cProfile context-manager pattern. Deterministic structure, machine-dependent times — read the ranking, not the milliseconds.

Run it on a tiny target — the call counts and the ranking are stable, the timings vary per machine, so this output is illustrative. (Only slow_sum and the profiler's own disable call appear because the profiler was enabled around just that one call; range is a type, not a profiled function.)

python
# profile_target.py
import cProfile
import pstats


def slow_sum(n: int) -> int:
    total = 0
    for i in range(n):
        total += i * i
    return total


pr = cProfile.Profile()
pr.enable()
slow_sum(2_000_000)
pr.disable()
pstats.Stats(pr).sort_stats("cumulative").print_stats(4)
Example output · illustrative7 lines
         2 function calls in 0.044 seconds

   Ordered by: cumulative time

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.044    0.044    0.044    0.044 profile_target.py:6(slow_sum)
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

Memory: tracemalloc. tracemalloc.start(), take snapshots, compare_to — shows which line allocated the memory, which cProfile can't. Run it (the sizes are stable for this list, but other tracemalloc frames can appear in your top three, so the output is labelled illustrative):

python
# tracemalloc_demo.py
import tracemalloc


def make_rows(n: int) -> list[list[int]]:
    return [[i] * 100 for i in range(n)]


tracemalloc.start()
before = tracemalloc.take_snapshot()
rows = make_rows(2000)
after = tracemalloc.take_snapshot()

for stat in after.compare_to(before, "lineno")[:3]:
    print(stat)
print(f"peak: {tracemalloc.get_traced_memory()[1] / 1024:.0f} KiB")
tracemalloc.stop()
Example output · illustrative3 lines
tracemalloc_demo.py:6: size=1741 KiB (+1741 KiB), count=5717 (+5717), average=312 B
tracemalloc_demo.py:10: size=400 B (+400 B), count=1 (+1), average=400 B
peak: 1744 KiB

Live processes: py-spy (0.4.3 as of November 2026) — py-spy dump --pid PID prints every thread's current stack without stopping or instrumenting the process, and py-spy record -o profile.svg --pid PID produces a flamegraph. This is the production answer to "it's hung and I can't attach a debugger" — it reads the interpreter's memory safely from outside. For CPU-bound Python, also know py-spy top (live view) and that it needs ptrace permissions on Linux (kernel.yama.ptrace_scope).

The poor-man's profiler: a timing decorator. Before reaching for cProfile, a five-line decorator around time.perf_counter answers "is this call the slow part?":

python
# timing_demo.py
import functools
import time


def timed(fn):
    @functools.wraps(fn)
    def wrapper(*args, **kwargs):
        t0 = time.perf_counter()
        try:
            return fn(*args, **kwargs)
        finally:
            print(f"{fn.__name__} took {time.perf_counter() - t0:.4f}s")
    return wrapper


@timed
def work(n: int) -> int:
    return sum(i * i for i in range(n))

work(500_000)
Example output · illustrative1 line
work took 0.0110s

For production latency questions, prefer measuring at the boundary (request middleware timing, per-call latency_ms in the structured log from 1.10) over guessing with profiles.

2.9 Debugging in containers and production#

The same tools, different plumbing: docker exec -it container python -m pdb -p 1 (or py-spy dump --pid 1 inside the container) attaches to PID 1; logs come from docker logs/stdout JSON; PYTHONDEVMODE and PYTHONASYNCIODEBUG must be set in the image env for dev images only. Debug builds of CPython (--with-pydebug) enable extra checks at a performance cost — never in production images. The full deployment debugging story — health checks, canaries, log access — is 11C.1 and 11C.4.

Debugging checklist (steal this for the incident doc):

  1. What changed? (deploy, prompt, model version, data) — 11C.2 covers change management.
  2. Reproduce locally with the exact request — 03.10 Part 5 shows replaying captured requests.
  3. Read the traceback bottom-up; identify the first frame in your code.
  4. Add the narrowest possible logger.debug/breakpoint() — then remove it.
  5. Write the regression test before fixing.
  6. Check the wire (curl -v, event hooks) before blaming the model.
  7. If it's production-only: request ID → logs → traces (11A.1) → py-spy.

Part 3: Command-line interfaces#

Deep-dive

3.1 Why your toolkit needs a CLI#

A package of modules is a library; a package with a CLI is a tool. CLIs matter for AI work more than most domains: batch jobs ("re-run evals on these 500 prompts"), data pipelines (05.9 orchestrates them), ops scripts ("rotate this key", "backfill embeddings"), and CI steps all want aitoolkit <command> from a shell — not python -c "from aitoolkit...". 00.9 framed the whole course around tools that compose; a CLI is how your toolkit composes with other tools (shell pipes, cron, CI, other people's scripts).

Three CLI shapes you'll meet, in order of increasing convenience:

  • python -m aitoolkit ... — no installation needed; works from the repo
  • aitoolkit ... — a console script installed with the package (Part 4)
  • typer/click — frameworks that generate help, validation and shell completion from type hints or decorators

3.2 argparse in depth#

argparse is stdlib and covers ~95% of CLI needs. The pattern that scales: one parser-building function, subparsers per command, set_defaults(func=...) dispatch, and main(argv) taking an injectable argv list so tests can call it without a subprocess. Run for real:

python
# ticket_cli.py — argparse with subcommands; run with explicit argv for tests
import argparse
import json
import sys

TICKETS = {
    "T-1042": {"id": "T-1042", "subject": "Printer offline", "priority": "high"},
    "T-9912": {"id": "T-9912", "subject": "Invoice question", "priority": "low"},
}


def cmd_list(args: argparse.Namespace) -> int:
    items = list(TICKETS.values())[: args.limit]
    print(json.dumps(items, indent=2))
    return 0


def cmd_get(args: argparse.Namespace) -> int:
    try:
        print(json.dumps(TICKETS[args.ticket_id]))
        return 0
    except KeyError:
        print(f"error: unknown ticket {args.ticket_id}", file=sys.stderr)
        return 1


def build_parser() -> argparse.ArgumentParser:
    p = argparse.ArgumentParser(prog="tickets", description="Ticket triage CLI")
    sub = p.add_subparsers(dest="command", required=True)

    pl = sub.add_parser("list", help="list tickets")
    pl.add_argument("--limit", type=int, default=10, help="max rows (default 10)")
    pl.add_argument("--priority", choices=["low", "normal", "high"], default=None)
    pl.set_defaults(func=cmd_list)

    pg = sub.add_parser("get", help="show one ticket")
    pg.add_argument("ticket_id")
    pg.set_defaults(func=cmd_get)
    return p


def main(argv: list[str] | None = None) -> int:
    args = build_parser().parse_args(argv)
    return args.func(args)


if __name__ == "__main__":
    raise SystemExit(main())
Output · --help11 lines
usage: tickets [-h] {list,get} ...

Ticket triage CLI

positional arguments:
  {list,get}
    list      list tickets
    get       show one ticket

options:
  -h, --help  show this help message and exit
Output · list --limit 1 and get8 lines
[
  {
    "id": "T-1042",
    "subject": "Printer offline",
    "priority": "high"
  }
]
{"id": "T-9912", "subject": "Invoice question", "priority": "low"}
Output · errors — argparse's exit codes are the contract5 lines
$ python3 ticket_cli.py get T-0000
error: unknown ticket T-0000        # exit=1 (your code's choice)
$ python3 ticket_cli.py bogus
usage: tickets [-h] {list,get} ...
tickets: error: argument command: invalid choice: 'bogus' (choose from 'list', 'get')   # exit=2 (argparse)

The argparse features worth memorising:

Feature Syntax Effect
Flag --verbose / -v action="store_true" → args.verbose is True
Value --limit 5 type=int converts; bad values exit 2 with a clear message
Choices choices=[...] Rejects invalid values before your code runs
Default default=... Always set one — None vs missing is a classic bug
Required subcommand required=True on add_subparsers aitoolkit with no args shows help instead of crashing
parse_args(argv) pass a list Tests call main(["get", "T-1"]) — no subprocess needed
parse_known_args() returns (args, extras) For forwarding unknown args to another tool

Exit-code convention: 0 success, 1 application error (your return 1), 2 usage error (argparse's). Scripts, CI and shell && chains depend on this — a command that returns 0 on failure is a bug.

3.3 __main__.py, python -m and stdin#

Two ways to run a package as a program:

  • python -m aitoolkit ... — imports aitoolkit, then runs aitoolkit/__main__.py as __main__. The package is importable, so __main__.py can use relative imports and the whole toolkit. This is the pattern to teach and the one Part 4 wires to a console script.
  • python path/to/dir/ — executes dir/__main__.py directly; works for self-contained scripts but without package context, so relative imports fail. Prefer -m.

Run for real:

python
# demo_pkg/__main__.py (with demo_pkg/__init__.py present)
import sys

print("demo_pkg ran as __main__")
print("extra args:", sys.argv[1:])
Output6 lines
$ python3 -m demo_pkg hello world
demo_pkg ran as __main__
extra args: ['hello', 'world']
$ python3 demo_pkg          # also works for a self-contained __main__.py
demo_pkg ran as __main__
extra args: []

stdin/stdout discipline: read piped input with sys.stdin (or for line in sys.stdin), write results to sys.stdout, diagnostics to sys.stderr — never print errors to stdout (it corrupts pipes: aitoolkit export | jq breaks if a warning lands in the JSON stream). argparse types like FileType("r") handle - for stdin/stdout conventions (cmd < input.json, cmd > out.json).

3.4 typer and click: when to switch#

When the CLI grows — nested subcommands, auto-generated help from type hints, shell completion — the frameworks pay off. typer (0.28.0 as of November 2026) builds a CLI from function signatures and type hints; click (8.5.1) is the older decorator-based standard that typer itself is built on (Flask's flask command is another well-known click app).

python
# typer_demo.py — the same "tickets" CLI in ~15 lines
import typer

app = typer.Typer()

TICKETS = {"T-1042": "Printer offline", "T-9912": "Invoice question"}


@app.command()
def get(ticket_id: str) -> None:
    """Show one ticket."""
    if ticket_id not in TICKETS:
        raise typer.BadParameter(f"unknown ticket {ticket_id}")
    typer.echo(TICKETS[ticket_id])


@app.command()
def ls(limit: int = typer.Option(10, "--limit", "-n", help="max rows")) -> None:
    """List tickets."""
    for tid in list(TICKETS)[:limit]:
        typer.echo(tid)


if __name__ == "__main__":
    app()

Illustrative output (written from the typer docs; the box-drawing layout depends on your terminal and your typer and rich versions):

console
$ python typer_demo.py --help
 Usage: typer_demo.py [OPTIONS] COMMAND [ARGS]...
 Try 'typer_demo.py --help' for help.
╭─ Options ───────────────────────────────────────────────────────╮
│ --help          Show this message and exit.                     │
╰─────────────────────────────────────────────────────────────────╯
╭─ Commands ──────────────────────────────────────────────────────╮
│ get   Show one ticket.                                          │
│ ls    List tickets.                                             │
╰─────────────────────────────────────────────────────────────────╯

The trade: typer gives you validation, --help, completion and typed options almost free, at the cost of a dependency and a little magic. For aitoolkit's own CLI (Part 3.5) argparse is the right weight — it's what the consolidated project uses; reach for typer when the command surface gets genuinely complex.

3.5 rich and tqdm: aware, not required#

Two libraries you'll see in every AI CLI: rich (15.0.0 as of November 2026) — tables, panels, progress bars, tracebacks with syntax highlighting, rich.print as a print upgrade; tqdm (4.70.1) — the for x in tqdm(items) progress bar that works in terminals, Jupyter and pipes (python -m tqdm even works as a pipe filter). Both are optional polish: a CLI that emits clean JSON to stdout and human text to stderr composes better than one that decorates everything. Use them for interactive commands (aitoolkit run, dashboards); keep --json/plain modes for scripting — 03.10 §9.2 and 11C.2 make the same point for eval CLIs.

3.6 The aitoolkit/cli.py deliverable#

The consolidated project's CLI — argparse, injectable argv, proper exit codes, a --json output mode, wired to python -m aitoolkit (Part 4 adds the aitoolkit console script that calls the same main()). It uses the real toolkit interfaces: get_settings() from 01B.2, get_backend()/ScriptedBackend from 01B.3 (the factory is added in 5.2) and the Pydantic Completion/Usage wire models from 01B.6:

python
# aitoolkit/cli.py — the aitoolkit command-line interface
import argparse
import asyncio
import json

from . import __version__, logging_setup
from .backend import get_backend
from .models import Completion, Usage
from .settings import get_settings


def _wire_completion(c) -> Completion:
    """Map the backend's Completion dataclass (01B.3) onto the wire model (01B.6)."""
    return Completion(
        text=c.text,
        model=c.model,
        usage=Usage(input_tokens=c.usage.input_tokens,
                    output_tokens=c.usage.output_tokens),
    )


def completion_sync(prompt: str, model: str | None = None) -> Completion:
    """Sync wrapper for the CLI — runs the backend coroutine on a fresh loop.

    asyncio.run() is correct for a one-shot CLI but must never be called from
    inside a running loop — inside FastAPI, await the backend directly.
    """
    c = asyncio.run(get_backend().complete(prompt, model=model))
    return _wire_completion(c)


def cmd_version(_args: argparse.Namespace) -> int:
    print(f"aitoolkit {__version__}")
    return 0


def cmd_config(_args: argparse.Namespace) -> int:
    """Print resolved settings — selected non-secret fields only."""
    s = get_settings()
    print(json.dumps({
        "app_env": s.app_env,
        "log_level": s.log_level,
        "log_json": s.log_json,
        "openai_model": s.openai_model,
        "request_timeout_seconds": s.request_timeout_seconds,
        "connect_timeout_seconds": s.connect_timeout_seconds,
        "max_retries": s.max_retries,
        "max_connections": s.max_connections,
        "service_port": s.service_port,
    }, indent=2))
    return 0


def cmd_complete(args: argparse.Namespace) -> int:
    result = completion_sync(args.prompt, model=args.model)
    if args.json:
        print(json.dumps(result.model_dump(mode="json")))
    else:
        print(result.text)
    return 0


def cmd_health(_args: argparse.Namespace) -> int:
    # Exercises the same path the service's /health uses, without a server.
    print(json.dumps({"status": "ok"}))
    return 0


def build_parser() -> argparse.ArgumentParser:
    p = argparse.ArgumentParser(
        prog="aitoolkit",
        description="AI engineering toolkit: config, service, CLI",
    )
    sub = p.add_subparsers(dest="command", required=True)

    sub.add_parser("version", help="print version").set_defaults(func=cmd_version)
    sub.add_parser("config", help="show resolved config (secrets masked)").set_defaults(func=cmd_config)
    sub.add_parser("health", help="health check without a server").set_defaults(func=cmd_health)

    pc = sub.add_parser("complete", help="run one completion through the backend")
    pc.add_argument("prompt")
    pc.add_argument("--model", default=None, help="model override (default: backend's own)")
    pc.add_argument("--json", action="store_true", help="emit the full Completion as JSON")
    pc.set_defaults(func=cmd_complete)
    return p


def main(argv: list[str] | None = None) -> int:
    # The CLI *is* the entry point: configure logging here, once — never at
    # module import (1.9/1.11). Logs go to stderr, so stdout stays pipe-clean.
    s = get_settings()
    logging_setup.configure_logging(level=s.log_level, json_logs=s.log_json)
    args = build_parser().parse_args(argv)
    return args.func(args)


if __name__ == "__main__":
    raise SystemExit(main())

Two deliberate choices. There is a version subcommand but no --version flag — one way to ask, listed in --help; pick whichever your project prefers, not both. And config prints only non-secret fields on purpose: SecretStr's repr is masked, but a habit of dumping whole settings objects is how keys end up in terminal scrollback and CI logs. complete "..." runs the fake backend and prints the reply text — or the full Completion JSON with --json; --model is forwarded to backend.complete(..., model=...) so the CLI can exercise the same override path /v1/complete uses.


Part 4: Packaging your toolkit#

Deep-dive

4.1 Modules, packages, distributions#

Three words people use interchangeably and shouldn't:

  • A module is one .py file (settings.py).
  • A package is a directory of modules with an __init__.py (or a namespace package without one) — aitoolkit/.
  • A distribution ("dist") is what you build and install: a wheel or sdist containing the package plus metadata — name, version, dependencies, entry points, license. pip install requests installs a distribution that contains the requests package.

The confusion matters because "make it a package" means different things: adding __init__.py makes it importable from the repo root (what uv run already does via the project layout); building a distribution is what makes pip install aitoolkit — or uv pip install ./aitoolkit — work anywhere. This part is about the second one.

4.2 Build systems: wheel, sdist and pyproject.toml#

A wheel (.whl) is a zip of the package plus a .dist-info/ directory (metadata + entry-point scripts + RECORD hashes) — what pip/uv actually installs. An sdist (.tar.gz) is the source archive — what uv build produces alongside the wheel, and what gets uploaded to PyPI for source builds. pyproject.toml is where the build backend is declared; it tells the installer how to turn your source tree into those artifacts.

flowchart LR
    SRC["source tree<br/>pyproject.toml + aitoolkit/"] -->|"uv build"| WHL["aitoolkit-0.1.0-py3-none-any.whl"]
    SRC -->|"uv build"| SDIST["aitoolkit-0.1.0.tar.gz"]
    WHL -->|"uv pip install aitoolkit-0.1.0-*.whl"| VENV[".venv<br/>import aitoolkit + 'aitoolkit' script"]
    SDIST -->|"build from source"| WHL

4.3 pyproject.toml for aitoolkit#

The consolidated project's pyproject.toml — every field explained after. The dependency lists show bare package names; the uv add command in this lesson's Setup names the packages without versions, so uv writes a lower bound such as httpx>=0.28.1 for each one into your own file, and your uv.lock records the exact versions it resolved:

toml
[build-system]
requires = ["uv_build>=0.13.7,<0.14.0"]
build-backend = "uv_build"

[project]
name = "aitoolkit"
version = "0.1.0"
description = "AI engineering toolkit: config, HTTP, models, concurrency, resilience, service, logging, CLI"
readme = "README.md"
requires-python = ">=3.11"                    # this path supports 3.11+; `uv init --python 3.13` would have written ">=3.13"
license = "MIT"                                # PEP 639 SPDX expression — the current form
authors = [{ name = "Your Name" }]
dependencies = [
    "httpx",
    "pydantic",
    "pydantic-settings",
    "fastapi[standard]",
    "uvicorn",
    "tenacity",
    "python-dotenv",
]

[dependency-groups]
dev = [
    "pytest",
    "pytest-asyncio",
    "pytest-cov",
    "pytest-xdist",
    "pytest-socket",
    "respx",
    "hypothesis",
    "time-machine",
    "ruff",
]

[project.scripts]
aitoolkit = "aitoolkit.cli:main"

[tool.pytest.ini_options]                      # the table from 01B.1, as 01B.8 §2.4 and §5.5 leave it
testpaths = ["tests"]
asyncio_mode = "auto"
addopts = "-ra --strict-markers --disable-socket"    # replaced 01B.1's `-q`
markers = [
    "live: calls a real provider API (needs keys; excluded from the default run)",
    "integration: needs a local server or external service",
    "slow: takes more than a second",
]

[tool.uv]
package = true

The [tool.ruff], [tool.ruff.lint] and [tool.ruff.lint.per-file-ignores] tables from 01B.1 stay exactly as they are (they are not repeated here). Field by field:

  • [build-system] — declares the backend. uv init --package (the default for new projects) writes uv_build, uv's own build backend — it reads [project] for metadata and expects the module at src/<package_name>/__init__.py by default (a flat root-level module needs [tool.uv.build-backend] module-root = "" — see the uv build backend docs); that's why the project tree in 5.1 uses src/aitoolkit/, matching what uv init generated in 01B.1. Alternatives: hatchling (1.33.0 as of November 2026 — what most of the ecosystem uses, very flexible) or setuptools (the old standard, setuptools.build_meta). For a uv-managed project, uv_build is the least-friction choice; if you ever need exotic build hooks, hatchling is the escape hatch.
  • [project] — PEP 621 metadata. name is the distribution name (what pip install sees); the import name is whatever directory holds your code. Keep them aligned (aitoolkit/src/aitoolkit/) to avoid the classic "I installed foo but import bar fails". version is PEP 440 (0.1.0, 1.2.3rc1); requires-python is the floor the resolver enforces; license is an SPDX expression per PEP 639 ("MIT", "Apache-2.0") — the older license = { text = "MIT" } table form is deprecated; authors/readme are metadata only.
  • dependencies — the runtime requirements, resolved at install time. The listing above shows bare package names, and this path's uv add commands leave the versions to the lower bounds uv writes and to uv.lock; a deployed application may tighten them to exact pins (uv add httpx --bounds exact), while libraries meant for others usually want floors (>=) — see 4.6.
  • [dependency-groups] — PEP 735 dev groups: uv sync installs dev by default, uv sync --no-dev excludes it. For an application this is the right home for test tooling — it isn't shipped metadata. This group carries the full 01B.8 test toolchain (pytest-cov for coverage, pytest-xdist for -n auto, pytest-socket for --disable-socket, time-machine/hypothesis for the deterministic-time and property tests) plus ruff for the make lint target — without them uv run pytest --cov=... and make lint fail on a fresh uv sync. ([project.optional-dependencies] extras are the mechanism for published libraries — pip install pkg[dev] — which is why 01B.1 chose groups here.)
  • [project.scripts] — the console-script entry point. aitoolkit = "aitoolkit.cli:main" means "install a aitoolkit executable that calls aitoolkit.cli.main()". The function must take no required args (argparse's main(argv=None) qualifies) and its return becomes the exit code via SystemExit semantics — our main returns int, and the console-script wrapper exits with it.
  • [tool.uv] package = true — tells uv this project is a package to build+install into its own venv on uv sync. Without a [build-system] uv treats the project as unpackaged (flat scripts only); uv init --package sets all of this up for you.
  • [tool.pytest.ini_options] — this is the single table from 01B.1, 7.3, edited in place by 01B.8: addopts was "-q" in 01B.1 and 01B.8 replaced it (one key, not two). The suite relies on asyncio_mode = "auto". If you also added the optional coverage flags from 01B.8, 8.1 to addopts, keep them; they do not change anything else here. The ruff tables are not repeated because the consolidation does not change them.

4.4 Building, installing, editable installs#

bash
uv build                  # writes dist/aitoolkit-0.1.0-py3-none-any.whl + .tar.gz
uv pip install dist/aitoolkit-0.1.0-py3-none-any.whl   # install the wheel into .venv
aitoolkit version            # the console script now exists
aitoolkit health

Illustrative output (modelled on the uv build docs; exact lines vary with your uv version):

console
$ uv build
Building source distribution...
Building wheel from source distribution...
Successfully built dist/aitoolkit-0.1.0.tar.gz
dist/aitoolkit-0.1.0-py3-none-any.whl

Editable installs (uv pip install -e . or uv sync for a packaged project) install a link to your source tree instead of copying it: edits to .py files take effect immediately without reinstalling — the right mode for development. The trade-off: the installed metadata (version, deps) is frozen at install time, and -e installs aren't what you ship. uv sync on a package = true project does an editable-style install automatically, which is why uv run aitoolkit ... works in the repo without a separate install step.

4.5 Versioning and importlib.metadata#

Versions answer "which code is running?" in logs, bug reports and support calls. importlib.metadata (stdlib, 3.8+) reads the installed distribution's metadata — the same data PyPI shows:

python
from importlib.metadata import version, metadata

print(version("aitoolkit"))          # "0.1.0" — the installed dist version
meta = metadata("aitoolkit")
print(meta["Name"], meta["Requires-Python"])

Use it for --version output, startup log lines ("aitoolkit 0.1.0 starting"), and support bundles — don't hardcode __version__ strings that can drift from pyproject.toml; either read version("aitoolkit") or have your build generate __init__.py's __version__ (hatchling's [tool.hatch.version] does this; uv_build reads [project] version directly). Single-source the version in pyproject.toml and read it everywhere else.

Changelogs. A version number says that something changed; a changelog says what. Keep one — CHANGELOG.md at the repo root, newest first, grouped Added/Changed/Fixed/Removed/Security (the Keep a Changelog convention is the de-facto standard). Write entries for humans upgrading your code: "Settings gained log_json", not "misc fixes". For an application the changelog is how you answer "what changed between the deploy that worked and the one that didn't" — pair every version bump with an entry, and tag releases (git tag v0.2.0) so version("aitoolkit") in a log line maps to a changelog section. If you publish to PyPI, the changelog also feeds the release notes; most teams generate the GitHub release from it.

4.6 Applications vs libraries#

The most important packaging decision for AI work: are you building an application or a library?

  • Application (the common case for LLM work): deployed as a service/container, run as a CLI, versioned by deploy not by semver, dependencies pinned for reproducibility, never published to PyPI. aitoolkit is an application that happens to be packaged — the packaging exists so the CLI, the service and the tests share one installable unit.
  • Library: consumed by pip install by strangers, needs permissive deps (>= ranges, extras for optional integrations), stable API commitments, docs, semver discipline. This is what Module 03's "provider-agnostic client" pattern (03.11) would become if you productised it.

Shipping an app as a "library" buys you dependency hell (your pins become someone else's conflicts) for no benefit; shipping a library with app-style pins makes it uninstallable. Decide first, then write dependencies accordingly.

4.7 Publishing: awareness only#

If you ever do publish: uv build → uv publish (or python -m build + twine upload) to TestPyPI first, then PyPI; names are unique and squattable, so claim early; trusted publishing (OIDC via GitHub Actions → PyPI, no API tokens in CI) is the current best practice — 11C.2 covers CI mechanics for this course's projects. Private packages go to a private index (Azure Artifacts, AWS CodeArtifact, GitHub Packages) configured via [[tool.uv.index]] or UV_INDEX_URL/UV_EXTRA_INDEX_URL. For this course: build the wheel, install it locally, and stop there — publishing is a Module 14B career/portfolio concern, not a learning requirement.


Part 5: Putting the toolkit together#

5.1 The complete aitoolkit project#

Everything from 01B.2–01B.9 plus this lesson's logging_setup.py and cli.py, in one installable package — in the src/ layout 01B.1 established (uv init aitoolkit --package generates it, and uv_build expects src/<package>/__init__.py by default):

text
aitoolkit/                          # project root
├── pyproject.toml                  # [build-system] uv_build + [project] + [project.scripts]
├── README.md
├── LICENSE                         # MIT text — the license = "MIT" SPDX expression needs the file
├── Makefile                        # task shortcuts (make sync/test/lint/run) — 01B.1 §7.2
├── CHANGELOG.md                    # Keep-a-Changelog entries per version — §4.5
├── .env.example                    # placeholder names only — never real values
├── .gitignore                      # .env*, .venv/, dist/, __pycache__, .pytest_cache/ …
├── .python-version                 # 3.13
├── uv.lock                         # committed — reproducible installs
├── src/
│   └── aitoolkit/                  # the package (src/ layout: tests exercise the install)
│       ├── __init__.py             # __version__ read from the installed metadata (§4.5)
│       ├── __main__.py             # python -m aitoolkit → cli.main()
│       ├── settings.py             # pydantic-settings Settings + get_settings()     (01B.2 §4.13)
│       ├── backend.py              # ScriptedBackend — the fake async backend       (01B.3 Part 7)
│       ├── models.py               # Pydantic models: Ticket, Completion, Usage…   (01B.6 §7.4)
│       ├── concurrency.py          # Ok/Err, bounded_gather, RateLimiter, run_pipeline (01B.4 §10.1)
│       ├── http.py                 # TicketClient/AsyncTicketClient — typed httpx   (01B.5 Part 9)
│       ├── retry_after.py          # parse_retry_after — Retry-After header parser  (01B.9 §4.3)
│       ├── resilience.py           # is_transient, retry_async, Deadline, CircuitBreaker (01B.9 Part 8)
│       ├── service.py              # FastAPI app: /health + /v1/*                   (01B.7 Part 8)
│       ├── logging_setup.py        # dictConfig + JsonFormatter + filters           (this lesson §1.11)
│       └── cli.py                  # argparse CLI                                   (this lesson §3.6)
└── tests/                          # mirrors src/aitoolkit — 01B.8 §9.2
    ├── conftest.py                 # socket guard, settings-cache reset, scripted_backend
    ├── test_settings.py            # env → Settings, SecretStr masking, fail-fast
    ├── test_models.py              # Pydantic validation
    ├── test_concurrency.py         # bounded_gather, RateLimiter (FakeClock), run_pipeline
    ├── test_resilience.py          # is_transient, retry_async, CircuitBreaker, Deadline
    ├── test_http.py                # httpx.MockTransport — no network
    ├── test_service.py             # TestClient — /health, /v1/*, auth, SSE
    ├── test_logging.py             # request-ID + redaction filters                 (this lesson)
    └── test_cli.py                 # main([...]) with argv lists                    (this lesson)

The carried-over modules keep the interfaces their lessons defined — verbatim, below. The consolidated service.py is 01B.7's deliverable plus the logging wiring; its demo auth (DEMO_API_KEYS), its app_env use and its include_router(v1) call after the @v1.* decorators (include_router snapshots routes eagerly) are exactly 01B.7's. What this lesson adds on top: a log_json field on Settings, a get_backend() factory on backend.py, the logging wiring inside service.py's lifespan and middleware, the __main__.py/cli.py entry points, and tests/test_logging.py/test_cli.py.

5.2 Consolidated modules#

src/aitoolkit/settings.py (01B.2 §4.13 verbatim, plus the one field this lesson needs — marked # added):

python
# src/aitoolkit/settings.py — the module every later 01B lesson builds on
"""Typed application settings for aitoolkit.

One Settings object per process, built lazily by get_settings() and cached.
Secrets are SecretStr so they cannot leak through repr/logs/dumps.
Env var names are the field names in UPPER_SNAKE (case-insensitive match),
except where an SDK accepts aliases — see gemini_api_key below.
"""
from functools import lru_cache
from typing import Literal

from pydantic import AliasChoices, Field, SecretStr
from pydantic_settings import BaseSettings, SettingsConfigDict


class Settings(BaseSettings):
    """All configuration, validated once at first use."""

    model_config = SettingsConfigDict(
        env_file=".env",
        env_file_encoding="utf-8",
        extra="forbid",          # a .env line matching no field is a mistake: fail loudly
    )

    # --- environment -------------------------------------------------------
    app_env: Literal["dev", "test", "staging", "prod"] = "dev"
    log_level: Literal["DEBUG", "INFO", "WARNING", "ERROR"] = "INFO"
    debug: bool = False
    log_json: bool = False      # added (01B.10): emit JSON logs — LOG_JSON env var

    # --- provider credentials (all optional: use the providers you need) ----
    openai_api_key: SecretStr | None = None
    anthropic_api_key: SecretStr | None = None
    # google-genai accepts GEMINI_API_KEY or GOOGLE_API_KEY (the latter wins if
    # both are set) — AliasChoices mirrors that precedence. See 4.3b and 5.8.
    gemini_api_key: SecretStr | None = Field(
        default=None,
        validation_alias=AliasChoices("GOOGLE_API_KEY", "GEMINI_API_KEY"),
    )
    openrouter_api_key: SecretStr | None = None

    # --- provider endpoints and models (config, not code) -------------------
    openai_base_url: str | None = None           # proxies, OpenRouter-style gateways
    openai_model: str = "gpt-6-luna"
    anthropic_model: str = "claude-haiku-5-5"
    gemini_model: str = "gemini-3.8-flash"
    openrouter_model: str = "openai/gpt-6-luna"

    # --- HTTP / resilience knobs (used by http.py and resilience.py) --------
    request_timeout_seconds: float = Field(default=60.0, gt=0)
    connect_timeout_seconds: float = Field(default=10.0, gt=0)
    max_retries: int = Field(default=2, ge=0)
    max_connections: int = Field(default=100, ge=1)

    # --- service knobs (used by service.py in 01B.7) -------------------------
    service_port: int = Field(default=8000, ge=1, le=65535)
    cors_origins: list[str] = ["http://localhost:3000"]


@lru_cache(maxsize=1)
def get_settings() -> Settings:
    """The process-wide Settings. Cached: parsed once, reused everywhere."""
    return Settings()

One field is marked added: log_json (this lesson's LOG_JSON switch for configure_logging). Everything else is 01B.2's file untouched — including extra="forbid", which is why the additions had to be real fields rather than bare env vars read with os.environ.

src/aitoolkit/backend.py (the Usage, Completion and ScriptedBackend classes of 01B.3 Part 7 unchanged, apart from two shortened comments and without that lesson's demo main() and its if __name__ == "__main__": guard, which a library module does not need; plus the get_backend() factory this lesson adds at the bottom — the seam 5.5 swaps):

python
# src/aitoolkit/backend.py — the module's canonical fake async backend (01B.3)
import asyncio
import random
import time
from collections.abc import AsyncIterator
from dataclasses import dataclass, field


@dataclass
class Usage:
    input_tokens: int = 0
    output_tokens: int = 0


@dataclass
class Completion:
    text: str
    model: str = "scripted-1"
    usage: Usage = field(default_factory=Usage)
    latency_s: float = 0.0
    raw: dict = field(default_factory=dict)   # what a real SDK might return


class ScriptedBackend:
    """A fake async LLM backend.

    replies: prompt-substring -> canned reply (first match wins).
    default_reply: used when nothing matches.
    latency: seconds of fake "thinking" per call (asyncio.sleep, not time.sleep!).
    stream_delay: per-token delay when streaming.
    fail_first: raise RuntimeError on the first N calls (for retry tests).
    seed: seeds the ±10% latency jitter, so timings stay reproducible.
    """

    def __init__(
        self,
        replies: dict[str, str] | None = None,
        default_reply: str = "(no scripted reply for this prompt)",
        latency: float = 0.05,
        stream_delay: float = 0.01,
        fail_first: int = 0,
        seed: int = 0,
    ) -> None:
        self.replies = replies or {}
        self.default_reply = default_reply
        self.latency = latency
        self.stream_delay = stream_delay
        self.fail_first = fail_first
        self.calls: list[dict] = []          # every call attempt, for assertions
        self._rng = random.Random(seed)      # jitter source — seed makes it reproducible

    def _reply_for(self, prompt: str) -> str:
        for needle, reply in self.replies.items():
            if needle in prompt:
                return reply
        return self.default_reply

    async def _maybe_fail(self, prompt: str) -> None:
        if self.fail_first > 0:
            self.fail_first -= 1
            raise RuntimeError(f"scripted backend failure for: {prompt[:40]!r}")

    async def _sleep(self, base: float) -> None:
        """Fake wait with ±10% jitter — real APIs don't answer on a metronome."""
        await asyncio.sleep(base * self._rng.uniform(0.9, 1.1) if base else 0.0)

    async def complete(self, prompt: str, *, model: str | None = None) -> Completion:
        """One non-streaming call — the shape of client.chat.completions.create()."""
        self.calls.append({"prompt": prompt, "mode": "complete"})  # failed attempts count too
        await self._maybe_fail(prompt)
        start = time.perf_counter()
        await self._sleep(self.latency)       # the "model thinking": pure waiting
        text = self._reply_for(prompt)
        elapsed = time.perf_counter() - start
        return Completion(
            text=text,
            model=model or "scripted-1",
            usage=Usage(input_tokens=len(prompt.split()), output_tokens=len(text.split())),
            latency_s=elapsed,
            raw={"id": "chatcmpl-scripted", "object": "chat.completion"},
        )

    async def stream(self, prompt: str, *, model: str | None = None) -> AsyncIterator[str]:
        """An async generator of text chunks — the shape of an SDK token stream."""
        self.calls.append({"prompt": prompt, "mode": "stream"})  # failed attempts count too
        await self._maybe_fail(prompt)
        await self._sleep(self.latency)
        text = self._reply_for(prompt)
        for token in text.split(" "):
            await self._sleep(self.stream_delay)
            yield token + " "
        yield ""   # trailing marker, like a real stream's finish event


# --- added by 01B.10: the shared factory the CLI (and §5.5's swap) uses -------

_backend: ScriptedBackend | None = None


def get_backend() -> ScriptedBackend:
    """The process-wide fake backend. Swap this one function for a provider SDK
    and every caller — cli.py today, anything you add tomorrow — gets the real
    thing behind the same complete()/stream() interface."""
    global _backend
    if _backend is None:
        _backend = ScriptedBackend(
            replies={
                "hi": "Hello! How can I help you today?",
                "joke": "Why did the model break? It had too many parameters.",
            },
            latency=0.01,
        )
    return _backend

Note the contract the rest of the package relies on (from 01B.3): await backend.complete(prompt, *, model=None) returns the Completion dataclass — .text, .usage.input_tokens, .model, .latency_s — not a bare string and not the Pydantic wire model; backend.stream(...) is an async generator; backend.calls records every attempt. service.py's /v1/complete and cli.py's completion_sync both map that dataclass onto models.Completion at the boundary — that mapping is the "two representations at different layers" pattern 01B.6 §7.4 describes.

src/aitoolkit/models.py (01B.6 §7.4 verbatim — the file warns "keep field names stable"; this is where they stay stable):

python
# src/aitoolkit/models.py — needs: pydantic
"""Shared Pydantic models for the aitoolkit examples.

These are the contracts used across Module 01B: the fake ticket API
(01B.5), the FastAPI service (01B.7) and the fake LLM backend (01B.3).
Keep field names stable — later lessons import these exact models.
"""
from datetime import datetime
from enum import Enum
from typing import Literal

from pydantic import AliasChoices, BaseModel, ConfigDict, Field


class Priority(str, Enum):
    LOW = "low"
    NORMAL = "normal"
    HIGH = "high"
    URGENT = "urgent"


class Status(str, Enum):
    OPEN = "open"
    IN_PROGRESS = "in_progress"
    RESOLVED = "resolved"
    CLOSED = "closed"


class Ticket(BaseModel):
    """A ticket as returned by the fake ticket API (read side)."""

    model_config = ConfigDict(extra="forbid")

    id: int | str = 0      # the API uses ints; tests also build "T-1042"-style ids — 0 = unassigned
    subject: str = Field(validation_alias=AliasChoices("subject", "title"),
                         description="One-line summary of the problem")
    description: str = ""
    priority: Priority = Priority.NORMAL
    status: Status = Status.OPEN
    requester: str | None = None        # the API fills it from the caller's key
    tags: list[str] = Field(default_factory=list, max_length=10)
    votes: int = Field(default=0, ge=0)
    created_at: datetime | None = None
    updated_at: datetime | None = None


class TicketIn(BaseModel):
    """The shape a client POSTs to create a ticket (write side).

    Separate from Ticket: no id/status/votes — the server assigns those.
    extra="forbid" so a typo'd key fails loudly instead of vanishing.
    """

    model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)

    subject: str = Field(validation_alias=AliasChoices("subject", "title"),
                        min_length=3, max_length=200)
    description: str = Field(default="", max_length=10_000)
    priority: Priority = Priority.NORMAL
    requester: str | None = Field(default=None, max_length=120)
    tags: list[str] = Field(default_factory=list, max_length=10)


class CompletionRequest(BaseModel):
    """Request body for the fake backend's /complete endpoint."""

    model_config = ConfigDict(extra="forbid")

    prompt: str = Field(min_length=1, max_length=32_000)
    model: str = "fake-tiny"             # model name is config, not validated against a list
    max_tokens: int = Field(default=256, ge=1, le=8_192)
    temperature: float = Field(default=1.0, ge=0.0, le=2.0)


class Usage(BaseModel):
    """Token accounting — same field names as the backend's dataclass (01B.3)."""

    input_tokens: int = Field(default=0, ge=0)
    output_tokens: int = Field(default=0, ge=0)

    @property
    def total_tokens(self) -> int:
        return self.input_tokens + self.output_tokens


class Completion(BaseModel):
    """Response body for /complete: one canned completion from ScriptedBackend.

    The backend's own dataclass (01B.3) is the internal shape; this is the
    wire shape service.py maps onto — `text` is the reply string.
    """

    model_config = ConfigDict(extra="forbid")

    text: str                              # the canned reply text
    model: str = "fake-tiny"
    usage: Usage = Field(default_factory=Usage)
    finish_reason: Literal["stop", "length"] = "stop"

src/aitoolkit/concurrency.py (01B.4 §10.1 verbatim — Ok/Err/Result, the token-bucket RateLimiter, order-preserving bounded_gather, run_pipeline):

python
# src/aitoolkit/concurrency.py — bounded concurrency toolkit (stdlib only)
"""Concurrency patterns for I/O-bound work: bounded fan-out, rate limiting,
worker-pool pipelines, and a Result type for partial-failure collection.

Everything here is provider-neutral. Lesson 01B.4 teaches the patterns;
lesson 03.9 applies them to real LLM calls.
"""
from __future__ import annotations

import asyncio
import time
from collections.abc import Awaitable, Callable, Iterable
from dataclasses import dataclass
from typing import Generic, TypeVar, Union

T = TypeVar("T")
E = TypeVar("E", bound=BaseException)


# ---------------------------------------------------------------------------
# Result type: Ok(value) | Err(error) — partial-failure collection
# ---------------------------------------------------------------------------

@dataclass(frozen=True)
class Ok(Generic[T]):
    value: T

@dataclass(frozen=True)
class Err(Generic[E]):
    error: E

Result = Union[Ok[T], Err[E]]


# ---------------------------------------------------------------------------
# bounded_gather: gather with a concurrency limit, order preserved
# ---------------------------------------------------------------------------

async def bounded_gather(
    coros: Iterable[Awaitable[T]],
    limit: int,
) -> list[T]:
    """Run awaitables with at most `limit` in flight.

    Results come back in input order (like asyncio.gather). The first
    exception propagates immediately; remaining coroutines are NOT
    cancelled — for continue-on-error semantics use run_pipeline or wrap
    each coro to return a Result.
    """
    sem = asyncio.Semaphore(limit)

    async def guarded(coro: Awaitable[T]) -> T:
        async with sem:
            return await coro

    return list(await asyncio.gather(*(guarded(c) for c in coros)))


# ---------------------------------------------------------------------------
# RateLimiter: token bucket, injectable clock/sleep for deterministic tests
# ---------------------------------------------------------------------------

class RateLimiter:
    """Token-bucket rate limiter: `rate` calls/sec sustained, `burst` max
    instantaneous. Async-safe: concurrent acquires queue fairly enough for
    I/O work.

    `sleep` and `now` are injectable so tests can use a fake clock and run
    instantly; production uses asyncio.sleep / time.monotonic.
    """

    def __init__(
        self,
        rate: float,
        burst: float | None = None,
        *,
        sleep: Callable[[float], Awaitable[None]] = asyncio.sleep,
        now: Callable[[], float] = time.monotonic,
    ) -> None:
        if rate <= 0:
            raise ValueError("rate must be positive")
        self.rate = rate
        self.capacity = float(burst if burst is not None else rate)
        self._tokens = self.capacity
        self._last = now()
        self._sleep = sleep
        self._now = now
        self._lock = asyncio.Lock()

    async def acquire(self, tokens: float = 1.0) -> None:
        if tokens > self.capacity:
            # the bucket can never hold this many tokens: waiting would loop forever
            raise ValueError(f"cannot acquire {tokens} tokens from a bucket of {self.capacity}")
        async with self._lock:
            while True:
                now = self._now()
                self._tokens = min(
                    self.capacity,
                    self._tokens + (now - self._last) * self.rate,
                )
                self._last = now
                if self._tokens >= tokens:
                    self._tokens -= tokens
                    return
                deficit = tokens - self._tokens
                await self._sleep(deficit / self.rate)


# ---------------------------------------------------------------------------
# run_pipeline: worker pool over asyncio.Queue, ordered Results, graceful stop
# ---------------------------------------------------------------------------

async def run_pipeline(
    items: Iterable[T],
    process: Callable[[T], Awaitable[object]],
    *,
    limit: int = 8,
    queue_size: int = 0,
    on_progress: Callable[[int, int, int], None] | None = None,
) -> list[Result]:
    """Process `items` through `process` with `limit` workers.

    Returns a list of Result aligned with input order: Ok(value) or
    Err(exception). `queue_size` bounds the buffer (backpressure);
    `on_progress(done, total, errors)` is called after each item.
    """
    item_list = list(items)
    total = len(item_list)
    n_workers = max(1, min(limit, total))
    queue: asyncio.Queue = asyncio.Queue(maxsize=queue_size)
    out: list[Result] = [None] * total  # type: ignore[list-item]
    stats = {"done": 0, "errors": 0}
    STOP = object()

    async def worker() -> None:
        while True:
            payload = await queue.get()
            try:
                if payload is STOP:
                    return
                index, item = payload
                try:
                    out[index] = Ok(await process(item))
                except Exception as exc:
                    out[index] = Err(exc)
                    stats["errors"] += 1
                stats["done"] += 1
                if on_progress is not None:
                    on_progress(stats["done"], total, stats["errors"])
            finally:
                queue.task_done()

    async with asyncio.TaskGroup() as tg:
        for _ in range(n_workers):
            tg.create_task(worker())
        for i, item in enumerate(item_list):
            await queue.put((i, item))
        for _ in range(n_workers):
            await queue.put(STOP)
        await queue.join()

    return out

src/aitoolkit/http.py (01B.5 Part 9 verbatim — TicketAPIError, _raise_for_api, TicketClient/AsyncTicketClient with cursor pagination):

python
# src/aitoolkit/http.py — configured sync + async clients for the ticket API.
# Pydantic models (Ticket, TicketIn) arrive in 01B.6; retries in 01B.9.
from __future__ import annotations

import httpx

BASE_URL = "https://tickets.example.com/v1"
TIMEOUT = httpx.Timeout(30.0, connect=5.0, pool=10.0)


class TicketAPIError(Exception):
    """Domain error: carries the HTTP status and the API's error code."""
    def __init__(self, status: int, code: str, message: str) -> None:
        super().__init__(f"{status} {code}: {message}")
        self.status = status
        self.code = code


def _raise_for_api(r: httpx.Response) -> None:
    """Map httpx outcomes onto TicketAPIError; 404 stays an exception the
    caller can catch, transport errors propagate as httpx.RequestError."""
    if r.is_success:
        return
    try:
        err = r.json().get("error", {})
        code, message = err.get("code", "http_error"), err.get("message", r.reason_phrase)
    except (ValueError, AttributeError):    # non-JSON body (WAF page) or JSON that isn't an object
        code, message = f"http_{r.status_code}", r.text[:200]
    raise TicketAPIError(r.status_code, code, message)


class TicketClient:
    """Synchronous client. One instance per process; use as a context manager."""

    def __init__(self, token: str, base_url: str = BASE_URL) -> None:
        self._client = httpx.Client(
            base_url=base_url,
            headers={"Authorization": f"Bearer {token}", "Accept": "application/json"},
            timeout=TIMEOUT,
            follow_redirects=False,
        )

    def __enter__(self) -> "TicketClient":
        return self

    def __exit__(self, *exc) -> None:
        self._client.close()

    def _get(self, path: str, **params) -> httpx.Response:
        r = self._client.get(path, params=params)
        _raise_for_api(r)
        return r

    def get_ticket(self, ticket_id: int):
        # In 01B.6 this becomes: return Ticket.model_validate(self._get(f"/tickets/{ticket_id}").json())
        return self._get(f"/tickets/{ticket_id}").json()

    def iter_tickets(self, status: str | None = None):
        """Cursor pagination: yield every ticket across pages."""
        cursor = None
        while True:
            params = {"status": status} if status else {}
            if cursor:
                params["cursor"] = cursor
            page = self._get("/tickets", **params).json()
            yield from page["items"]
            cursor = page.get("next_cursor")
            if not cursor:
                return

    def create_ticket(self, payload: dict):
        r = self._client.post("/tickets", json=payload)
        _raise_for_api(r)
        return r.json()


class AsyncTicketClient:
    """Async twin — same shape, await everywhere, aiter_tickets for pagination."""

    def __init__(self, token: str, base_url: str = BASE_URL) -> None:
        self._client = httpx.AsyncClient(
            base_url=base_url,
            headers={"Authorization": f"Bearer {token}", "Accept": "application/json"},
            timeout=TIMEOUT,
            follow_redirects=False,
        )

    async def __aenter__(self) -> "AsyncTicketClient":
        return self

    async def __aexit__(self, *exc) -> None:
        await self._client.aclose()

    async def _get(self, path: str, **params) -> httpx.Response:
        r = await self._client.get(path, params=params)
        _raise_for_api(r)
        return r

    async def get_ticket(self, ticket_id: int):
        return (await self._get(f"/tickets/{ticket_id}")).json()

    async def aiter_tickets(self, status: str | None = None):
        cursor = None
        while True:
            params = {"status": status} if status else {}
            if cursor:
                params["cursor"] = cursor
            page = (await self._get("/tickets", **params)).json()
            for item in page["items"]:
                yield item
            cursor = page.get("next_cursor")
            if not cursor:
                return

    async def create_ticket(self, payload: dict):
        r = await self._client.post("/tickets", json=payload)
        _raise_for_api(r)
        return r.json()

src/aitoolkit/retry_after.py (01B.9 §4.3 verbatim — resilience.py imports it as .retry_after):

python
# src/aitoolkit/retry_after.py — parse a Retry-After header into seconds-to-wait (stdlib only)
import math
import time
from datetime import timezone
from email.utils import parsedate_to_datetime


def parse_retry_after(value: str | None, *, now: float | None = None) -> float | None:
    """Seconds to wait from a Retry-After header: '30' or an HTTP-date.
    `now` is a POSIX timestamp (time.time()); injectable for tests.
    Returns None when the header is missing or unparseable."""
    if not value:
        return None
    value = value.strip()
    try:
        seconds = float(value)              # delay-seconds (fractional tolerated)
    except ValueError:
        pass
    else:
        # 'inf' and 'nan' parse as floats but aren't real hints — reject them
        return max(0.0, seconds) if math.isfinite(seconds) else None
    try:
        when = parsedate_to_datetime(value)    # HTTP-date
    except (TypeError, ValueError):
        return None
    if when.tzinfo is None:
        when = when.replace(tzinfo=timezone.utc)
    current = time.time() if now is None else now
    return max(0.0, when.timestamp() - current)

src/aitoolkit/resilience.py (01B.9 Part 8 verbatim — is_transient, the retry_async decorator factory, call_with_retry, Deadline, CircuitOpenError, CircuitBreaker):

python
# src/aitoolkit/resilience.py — retries, deadlines and a circuit breaker for aitoolkit.
# Used by http.py (the configured client) and service.py (the FastAPI app).
import asyncio
import logging
import random
import time
from dataclasses import dataclass
from typing import Any, Awaitable, Callable, TypeVar

import httpx
from tenacity import (AsyncRetrying, RetryCallState, before_sleep_log, retry,
                      retry_if_exception, stop_after_attempt, stop_before_delay,
                      wait_random_exponential)
from tenacity.wait import wait_base

log = logging.getLogger("aitoolkit.resilience")
T = TypeVar("T")

# --------------------------------------------------------------------------
# Classification: which failures are worth another attempt?
# --------------------------------------------------------------------------

# 409 is included: most APIs use it for transient state conflicts — but some
# APIs use it for permanent duplicates; drop it from the set if yours does (§1.1).
RETRYABLE_STATUSES = {408, 409, 425, 429, 500, 502, 503, 504}
TRANSIENT_TRANSPORT = (
    httpx.ConnectError, httpx.ConnectTimeout, httpx.ReadTimeout,
    httpx.WriteTimeout, httpx.PoolTimeout, httpx.RemoteProtocolError,
    httpx.ReadError, httpx.WriteError,
)


def is_transient(exc: BaseException) -> bool:
    """True only for failures a retry could plausibly fix.

    - HTTPStatusError: retry only the transient status codes (4xx client errors
      like 400/401/404 are permanent — a retry fails identically).
    - Other httpx errors: transport-level (no response arrived) — transient.
    - Built-in TimeoutError/ConnectionError: same, for non-httpx callables.
    """
    if isinstance(exc, httpx.HTTPStatusError):
        return exc.response.status_code in RETRYABLE_STATUSES
    if isinstance(exc, httpx.HTTPError):
        return isinstance(exc, TRANSIENT_TRANSPORT)
    return isinstance(exc, (TimeoutError, ConnectionError))


# --------------------------------------------------------------------------
# Retry policy: tenacity, configured once, shared everywhere
# --------------------------------------------------------------------------

class wait_retry_after(wait_base):
    """Wait what the server asked for (Retry-After), else full-jitter backoff."""
    def __init__(self, fallback: wait_base) -> None:
        self.fallback = fallback

    def __call__(self, retry_state: RetryCallState) -> float:
        exc = retry_state.outcome.exception() if retry_state.outcome else None
        hint = _retry_after_hint(exc)
        if hint is not None and hint <= 60:               # cap absurd hints
            return hint + random.uniform(0, 0.25)          # "a minimum": add jitter
        return self.fallback(retry_state)


def _retry_after_hint(exc: BaseException | None) -> float | None:
    """Seconds from a Retry-After header on an httpx error response, if any."""
    if exc is None:
        return None
    response = getattr(exc, "response", None)
    if response is None:
        return None
    from .retry_after import parse_retry_after       # the Part 4 parser
    return parse_retry_after(response.headers.get("retry-after"))


def _policy(**overrides: Any) -> dict[str, Any]:
    policy: dict[str, Any] = dict(
        retry=retry_if_exception(is_transient),
        wait=wait_retry_after(wait_random_exponential(multiplier=0.5, max=8)),
        stop=stop_after_attempt(4) | stop_before_delay(30),
        before_sleep=before_sleep_log(log, logging.WARNING),
        reraise=True,                                   # raise the real error
    )
    policy.update(overrides)
    return policy


def retry_async(**overrides: Any):
    """@retry_async() on an `async def` — tenacity's @retry, pre-configured.

    Usage:
        @retry_async()
        async def fetch(client, url):
            resp = await client.get(url)
            resp.raise_for_status()
            return resp.json()
    """
    return retry(**_policy(**overrides))


async def call_with_retry(fn: Callable[..., Awaitable[T]], *args: Any,
                          policy: AsyncRetrying | None = None, **kwargs: Any) -> T:
    """Call an async fn under the shared policy — for callers that can't use
    the decorator (e.g. a function chosen at runtime)."""
    policy = policy or AsyncRetrying(**_policy())
    async for attempt in policy:
        with attempt:
            return await fn(*args, **kwargs)
    raise AssertionError("unreachable")


# --------------------------------------------------------------------------
# Deadline: a total budget shared across retries and sub-calls
# --------------------------------------------------------------------------

@dataclass
class Deadline:
    """A monotonic-clock budget. `remaining()` shrinks as time passes;
    `timeout()` gives an asyncio.timeout for whatever is left."""
    seconds: float
    _end: float = 0.0

    def __post_init__(self) -> None:
        self._end = time.monotonic() + self.seconds

    def remaining(self) -> float:
        return max(0.0, self._end - time.monotonic())

    @property
    def expired(self) -> bool:
        return self.remaining() <= 0

    def timeout(self):
        return asyncio.timeout(self.remaining())


# --------------------------------------------------------------------------
# CircuitBreaker: stop calling a dependency that's down
# --------------------------------------------------------------------------

class CircuitOpenError(Exception):
    """Raised instead of calling the service while the circuit is open."""


class CircuitBreaker:
    """Closed -> open -> half-open -> closed (the Part 6 state machine).

    Async-first (`acall`); `call` covers sync fns. `clock` is injectable so
    tests never really wait. For per-key breakers and sliding-window failure
    rates, see Module 11C's resilience layer.
    """

    CLOSED, OPEN, HALF_OPEN = "closed", "open", "half_open"

    def __init__(
        self,
        *,
        failure_threshold: int = 5,
        reset_timeout: float = 30.0,
        clock: Callable[[], float] = time.monotonic,
        on_state_change: Callable[[str, str], None] | None = None,
    ) -> None:
        # A NaN timeout compares False with everything, so an opened breaker would
        # never half-open; a threshold below 1 would open on the first success.
        if (isinstance(failure_threshold, bool) or not isinstance(failure_threshold, int)
                or failure_threshold < 1 or not 0 <= reset_timeout < float("inf")):
            raise ValueError("failure_threshold must be an int >= 1 and "
                             "reset_timeout a finite number >= 0")
        self.failure_threshold = failure_threshold
        self.reset_timeout = reset_timeout
        self._clock = clock
        self._on_state_change = on_state_change
        self._state = self.CLOSED
        self._failures = 0
        self._opened_at = 0.0
        self._probing = False

    @property
    def state(self) -> str:
        # Reading .state can itself transition open -> half_open: observation
        # mutates. Safe under asyncio (_before_call sets _probing before any
        # await); racy if one breaker is shared across threads.
        if self._state == self.OPEN and self._clock() - self._opened_at >= self.reset_timeout:
            self._transition(self.HALF_OPEN)
        return self._state

    def _transition(self, new: str) -> None:
        old = self._state
        self._state = new
        log.warning("circuit %s -> %s", old, new)
        if self._on_state_change:
            try:
                self._on_state_change(old, new)
            except Exception:    # a broken observer must not mask the call's own result
                logging.getLogger(__name__).exception("on_state_change callback failed")

    def _before_call(self) -> None:
        if self.state == self.OPEN:
            raise CircuitOpenError("circuit open: failing fast")
        if self.state == self.HALF_OPEN:
            if self._probing:
                raise CircuitOpenError("circuit half-open: probe in flight")
            self._probing = True

    def _after_success(self) -> None:
        self._failures = 0
        self._probing = False
        if self._state == self.HALF_OPEN:
            self._transition(self.CLOSED)

    def _after_failure(self) -> None:
        self._probing = False
        self._failures += 1
        if self._state == self.HALF_OPEN or self._failures >= self.failure_threshold:
            self._opened_at = self._clock()
            self._transition(self.OPEN)

    async def acall(self, fn: Callable[..., Awaitable[T]], *args: Any, **kwargs: Any) -> T:
        self._before_call()
        try:
            result = await fn(*args, **kwargs)
        except asyncio.CancelledError:
            # An outer deadline (6.7) can cancel a call mid-flight. That is not a
            # verdict on the dependency, but it must release a half-open probe slot
            # or every later call would be refused as "probe in flight".
            self._probing = False
            raise
        except Exception:
            self._after_failure()
            raise
        self._after_success()
        return result

    def call(self, fn: Callable[..., T], *args: Any, **kwargs: Any) -> T:
        self._before_call()
        try:
            result = fn(*args, **kwargs)
        except Exception:
            self._after_failure()
            raise
        except BaseException:      # KeyboardInterrupt, SystemExit: release a half-open probe
            self._probing = False
            raise
        self._after_success()
        return result

logging_setup.py (shown in full in 1.11) and cli.py (shown in full in 3.6) are reproduced unchanged — cli.py's main() is also the logging entry point per 1.9.

src/aitoolkit/service.py — 01B.7 Part 8's deliverable with four additions marked # 01B.10: logging configured in lifespan (never at import — 1.9), the request-ID contextvars set inside the pure-ASGI middleware (keeping 01B.7's non-buffering design), the middleware now honouring an inbound X-Request-ID header instead of always minting its own (01B.7 always generates one), and the structured log line from 1.10 in /v1/complete (the mapping of the backend's Completion dataclass onto the Pydantic wire model is 01B.7's). Two smaller edits ride along: lifespan awaits the backend's aclose() on shutdown when it has one (ScriptedBackend does not), and a few comments are shortened:

python
# src/aitoolkit/service.py — the FastAPI service: /health, /v1/echo, /v1/complete, /v1/stream
#
# Run:   uv run fastapi dev src/aitoolkit/service.py  (dev, auto-reload)
#        uv run uvicorn aitoolkit.service:app          (or: fastapi run)
# Try:   curl http://127.0.0.1:8000/health
#        curl -X POST http://127.0.0.1:8000/v1/echo -H 'content-type: application/json' \
#             -H 'X-API-Key: demo-key-alice' -d '{"message": "hello"}'
#        curl -N -X POST http://127.0.0.1:8000/v1/stream -H 'content-type: application/json' \
#             -H 'X-API-Key: demo-key-alice' -d '{"prompt": "hi"}'   # -N = no buffering
#
# Demo auth: X-API-Key must match a key in DEMO_API_KEYS below
# (the stand-in for your IdP — 11.9 §2.3 and Module 12 own real auth).
from __future__ import annotations

import logging
import secrets
import time
import uuid
from collections.abc import AsyncIterator, Callable
from contextlib import asynccontextmanager
from typing import Annotated

from fastapi import APIRouter, Depends, FastAPI, HTTPException, Request, Security, status
from fastapi.encoders import jsonable_encoder
from fastapi.exceptions import RequestValidationError
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from fastapi.security import APIKeyHeader
from fastapi.sse import EventSourceResponse, ServerSentEvent
from pydantic import BaseModel, Field

from aitoolkit.backend import ScriptedBackend          # 01B.3: async complete()/stream()
from aitoolkit.logging_setup import (                  # 01B.10
    configure_logging, reset_request_id, set_request_id,
)
from aitoolkit.models import Completion, CompletionRequest, Usage  # 01B.6
from aitoolkit.settings import Settings, get_settings  # 01B.2

log = logging.getLogger("aitoolkit.service")

# ---------------------------------------------------------------------------
# Request/response models (the service-local ones; Completion* come from models.py)
# ---------------------------------------------------------------------------


class EchoIn(BaseModel):
    message: str = Field(min_length=1, max_length=4000)


class EchoOut(BaseModel):
    message: str
    length: int


class HealthOut(BaseModel):
    status: str
    service: str
    env: str


# ---------------------------------------------------------------------------
# Dependencies
# ---------------------------------------------------------------------------

# Demo key map: key -> owner (01B.7 verbatim). Stands in for your IdP/session
# store — production resolves the principal from a verified token (11.9, Module 12).
DEMO_API_KEYS = {
    "demo-key-alice": "alice",
    "demo-key-bob": "bob",
}

api_key_header = APIKeyHeader(name="X-API-Key", auto_error=False)


async def require_api_key(
    api_key: Annotated[str | None, Security(api_key_header)],
) -> str:
    """X-API-Key auth against DEMO_API_KEYS (key -> owner).

    compare_digest: constant-time — `==` on secrets is a timing oracle.
    """
    if not api_key:
        raise HTTPException(status.HTTP_401_UNAUTHORIZED, "missing API key",
                            headers={"WWW-Authenticate": "ApiKey"})
    for valid_key, owner in DEMO_API_KEYS.items():
        if secrets.compare_digest(api_key, valid_key):
            return owner
    raise HTTPException(status.HTTP_401_UNAUTHORIZED, "invalid API key",
                        headers={"WWW-Authenticate": "ApiKey"})


def get_backend(request: Request) -> ScriptedBackend:
    """The shared backend lifespan built — one per worker process."""
    return request.app.state.backend


# ---------------------------------------------------------------------------
# Error envelope: one JSON shape for every failure
# ---------------------------------------------------------------------------


def error_body(code: str, message: str) -> dict:
    return {"error": {"code": code, "message": message}}


def register_error_handlers(app: FastAPI) -> None:
    @app.exception_handler(RequestValidationError)
    async def validation_handler(request: Request, exc: RequestValidationError) -> JSONResponse:
        # jsonable_encoder: error dicts can hold non-JSON values — encode first
        return JSONResponse(status_code=422, content={
            "error": {"code": "validation_error", "message": "request failed validation",
                      "details": jsonable_encoder(exc.errors())}})

    @app.exception_handler(Exception)
    async def unhandled_handler(request: Request, exc: Exception) -> JSONResponse:
        # Log exc + request id server-side; never leak internals to clients.
        # log.exception attaches the traceback; the request id rides along on the
        # record via the contextvar RequestContextMiddleware set for this request.
        log.exception("unhandled error on %s %s", request.method, request.url.path)
        return JSONResponse(status_code=500,
                            content=error_body("internal_error", "something went wrong"))


# ---------------------------------------------------------------------------
# Middleware: pure ASGI — request id + duration on every response.
# No buffering (safe for SSE), passes non-http scopes through untouched.
# 01B.10 adds the contextvars set/reset so log records carry the same id.
# ---------------------------------------------------------------------------


class RequestContextMiddleware:
    def __init__(self, app: Callable) -> None:
        self.app = app

    async def __call__(self, scope, receive, send) -> None:
        if scope["type"] != "http":
            await self.app(scope, receive, send)
            return
        req_headers = dict(scope.get("headers", []))
        # honour an inbound X-Request-ID (proxies/set upstream callers send one),
        # else mint our own — either way it goes on the response and into logs.
        request_id = req_headers.get(b"x-request-id", uuid.uuid4().hex[:12].encode()).decode()
        scope.setdefault("state", {})["request_id"] = request_id
        token = set_request_id(request_id)                    # 01B.10: logging contextvar
        start = time.perf_counter()

        async def send_with_headers(message):
            if message["type"] == "http.response.start":
                headers = dict(message.get("headers", []))
                headers[b"x-request-id"] = request_id.encode()
                # at http.response.start: ~total for buffered responses,
                # time-to-first-byte for streams — hence the name
                headers[b"x-first-byte-ms"] = str(
                    int((time.perf_counter() - start) * 1000)).encode()
                message["headers"] = list(headers.items())
            await send(message)

        try:
            await self.app(scope, receive, send_with_headers)
        finally:
            reset_request_id(token)


# ---------------------------------------------------------------------------
# Lifespan: configure logging once, build the backend once per process
# ---------------------------------------------------------------------------


@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
    # 01B.10: the app configures logging here — once per process, at start-up,
    # never at module import (importing this file must not reconfigure logging).
    s = get_settings()
    configure_logging(level=s.log_level, json_logs=s.log_json)
    app.state.backend = ScriptedBackend()   # real service: provider client, DB pool…
    yield
    aclose = getattr(app.state.backend, "aclose", None)
    if aclose is not None:                  # ScriptedBackend has no aclose; real clients do
        await aclose()


# ---------------------------------------------------------------------------
# The app
# ---------------------------------------------------------------------------

settings = get_settings()                   # lru_cached; read once at import
app = FastAPI(
    title="aitoolkit",
    version="0.1.0",
    lifespan=lifespan,
    docs_url=None if settings.app_env == "prod" else "/docs",       # 01B.10: app_env (01B.2's field)
    redoc_url=None if settings.app_env == "prod" else "/redoc",
)
app.add_middleware(RequestContextMiddleware)
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.cors_origins,   # Settings field (CORS_ORIGINS env); never "*" with credentials
    allow_methods=["GET", "POST"],
    allow_headers=["Authorization", "Content-Type", "X-API-Key", "X-Request-ID"],
)
register_error_handlers(app)


# -- unversioned ops endpoint -------------------------------------------------


@app.get("/health", response_model=HealthOut)
def health(settings: Annotated[Settings, Depends(get_settings)]) -> HealthOut:
    """Liveness for load balancers — cheap, no dependency checks."""
    return HealthOut(status="ok", service="aitoolkit", env=settings.app_env)


# -- versioned API ------------------------------------------------------------
# include_router() snapshots the router's routes eagerly — it must come AFTER
# the @v1.* decorators below, or /v1/* never mounts (404s).

v1 = APIRouter(prefix="/v1", dependencies=[Security(require_api_key)])


@v1.post("/echo", response_model=EchoOut)
def echo(body: EchoIn) -> EchoOut:
    return EchoOut(message=body.message, length=len(body.message))


@v1.post("/complete", response_model=Completion)
async def complete(
    body: CompletionRequest,
    backend: Annotated[ScriptedBackend, Depends(get_backend)],
) -> Completion:
    c = await backend.complete(body.prompt, model=body.model)
    # 01B.10: the structured LLM-call record from 1.10 — fields, never bodies.
    log.info("completion done", extra={
        "model": c.model,
        "latency_ms": int(c.latency_s * 1000),
        "input_tokens": c.usage.input_tokens,
        "output_tokens": c.usage.output_tokens,
    })
    # Map the backend's Completion dataclass onto the Pydantic wire model.
    return Completion(
        text=c.text,
        model=c.model,
        usage=Usage(input_tokens=c.usage.input_tokens,
                    output_tokens=c.usage.output_tokens),
    )


@v1.post("/stream", response_class=EventSourceResponse)
async def stream(
    request: Request,
    body: CompletionRequest,
    backend: Annotated[ScriptedBackend, Depends(get_backend)],
) -> AsyncIterator[ServerSentEvent]:
    """SSE: one `token` event per chunk, then `done`. Stops if the client leaves."""
    try:
        async for token in backend.stream(body.prompt):
            if await request.is_disconnected():
                break
            yield ServerSentEvent(data={"token": token}, event="token")
        yield ServerSentEvent(raw_data="[DONE]", event="done")
    finally:
        pass                                # upstream cleanup goes here (see 6.6)


app.include_router(v1)                     # AFTER the routes — see the note above

src/aitoolkit/__init__.py / __main__.py:

python
# src/aitoolkit/__init__.py
"""aitoolkit — the shared Python toolkit for the AI engineering path."""
from importlib.metadata import PackageNotFoundError, version

# Single source of truth: [project] version in pyproject.toml (see 4.5).
try:
    __version__ = version("aitoolkit")
except PackageNotFoundError:        # running from a bare source tree, not installed
    __version__ = "0.0.0+unknown"
python
# src/aitoolkit/__main__.py — makes `python -m aitoolkit` work
from .cli import main

raise SystemExit(main())

5.3 Tests: one suite for the whole toolkit#

The suite is 01B.8 §9.2's, unchanged — the module-by-module files (test_settings.py, test_models.py, test_concurrency.py, test_resilience.py, test_http.py, test_service.py) run against the consolidated modules above. They were written against exactly these interfaces: Completion has text/model/usage/finish_reason, Ticket's only required field is subject (accepted as title too), and the demo key demo-key-alice is in DEMO_API_KEYS. If a test fails after you edit a module, that is the suite doing its job.

tests/conftest.py (01B.8 §9.2 verbatim — the socket guard, the settings-cache reset, the zero-latency backend):

python
# tests/conftest.py
import socket

import pytest

from aitoolkit.backend import ScriptedBackend
from aitoolkit.settings import get_settings


class NetworkDisabledError(RuntimeError):
    pass


def _blocked(*args, **kwargs):
    raise NetworkDisabledError("network disabled in tests")


@pytest.fixture(autouse=True)
def _no_network(monkeypatch):
    """No test in this directory may open a socket."""
    real_socket = socket.socket

    class GuardedSocket(real_socket):
        def connect(self, address):
            raise NetworkDisabledError(f"connect to {address!r}")
        def connect_ex(self, address):
            raise NetworkDisabledError(f"connect_ex to {address!r}")
        def sendto(self, data, *args):
            raise NetworkDisabledError("sendto")

    monkeypatch.setattr(socket, "socket", GuardedSocket)
    monkeypatch.setattr(socket, "getaddrinfo", _blocked)
    monkeypatch.setattr(socket, "gethostbyname", _blocked)
    monkeypatch.setattr(socket, "gethostbyaddr", _blocked)
    monkeypatch.setattr(socket, "getnameinfo", _blocked)
    yield


@pytest.fixture(autouse=True)
def _reset_settings_cache():
    """get_settings() is lru_cached process-wide: clear it around every test so
    a monkeypatch.setenv in one test can't leak a stale Settings into the next."""
    get_settings.cache_clear()
    yield
    get_settings.cache_clear()


@pytest.fixture
def scripted_backend():
    """A ScriptedBackend with zero fake latency; tests script their own replies."""
    return ScriptedBackend(latency=0, stream_delay=0)

tests/test_cli.py — main([...]) with argv lists; capsys for stdout. complete prints the wire Completion's text; --json dumps model_dump(mode="json") of the Pydantic model (fields text, model, usage, finish_reason).

python
# tests/test_cli.py — the CLI is just main([...]); no subprocess needed
import json

import pytest

from aitoolkit.cli import main


def test_version(capsys):
    assert main(["version"]) == 0
    assert "aitoolkit" in capsys.readouterr().out


def test_config_prints_settings(capsys):
    assert main(["config"]) == 0
    out = json.loads(capsys.readouterr().out)
    assert out["app_env"] == "dev" and "openai_model" in out
    assert "api_key" not in out                     # secrets never printed


def test_complete_text(capsys):
    assert main(["complete", "hi"]) == 0
    assert "Hello" in capsys.readouterr().out       # scripted reply for "hi"


def test_complete_json(capsys):
    assert main(["complete", "hi", "--json"]) == 0
    out = json.loads(capsys.readouterr().out)
    assert out["model"] == "scripted-1"
    assert "Hello" in out["text"]
    assert out["usage"]["input_tokens"] > 0


def test_complete_model_override(capsys):
    assert main(["complete", "hi", "--model", "gpt-6-luna", "--json"]) == 0
    assert json.loads(capsys.readouterr().out)["model"] == "gpt-6-luna"


def test_bad_command_exits_2():
    with pytest.raises(SystemExit) as exc:
        main(["bogus"])
    assert exc.value.code == 2

tests/test_logging.py — new in this lesson. The request-ID tests drive the RequestIdFilter directly (and once through caplog.handler): configure_logging's filters live on the app's handlers, which caplog doesn't run — a subtlety handler-level filtering creates.

python
# tests/test_logging.py
import logging

from aitoolkit import logging_setup


def test_request_id_filter_attaches_id():
    record = logging.LogRecord("t", logging.INFO, __file__, 1, "hello", (), None)
    token = logging_setup.set_request_id("req-test-1")
    try:
        assert logging_setup.RequestIdFilter().filter(record) is True
    finally:
        logging_setup.reset_request_id(token)
    assert record.request_id == "req-test-1"          # type: ignore[attr-defined]


def test_request_id_reaches_caplog_via_handler_filter(caplog):
    """caplog's handler doesn't run configure_logging's filters — add the
    filter to caplog.handler explicitly to see request_id on records."""
    caplog.handler.addFilter(logging_setup.RequestIdFilter())
    token = logging_setup.set_request_id("req-caplog")
    try:
        with caplog.at_level(logging.INFO, logger="aitoolkit"):
            logging.getLogger("aitoolkit").info("hello")
    finally:
        logging_setup.reset_request_id(token)
    assert caplog.records[0].request_id == "req-caplog"  # type: ignore[attr-defined]


def test_redaction_scrubs_key_shape():
    record = logging.LogRecord("t", logging.INFO, __file__, 1,
                               "key api_key=sk-live-abc for a@b.co", (), None)
    assert logging_setup.RedactionFilter().filter(record) is True
    assert "sk-live-abc" not in record.getMessage()
    assert "<redacted>" in record.getMessage()

main() configures logging on every call (it is the entry point), which is safe here: the handlers write to stderr, capsys.readouterr().out only sees stdout, and disable_existing_loggers=False means nothing else breaks. Run the suite:

bash
uv run pytest

5.4 Supporting files and the end-to-end walkthrough#

.env.example — 01B.2's canonical names plus this module's additions; placeholders only:

bash
# .env.example — copy to .env and fill in. NEVER commit .env.
APP_ENV=dev
LOG_LEVEL=INFO
LOG_JSON=false

OPENAI_API_KEY=sk-...                # or ANTHROPIC_/GEMINI_/OPENROUTER_API_KEY
OPENAI_MODEL=gpt-6-luna              # model names are config — never hard-code
OPENAI_BASE_URL=                     # optional: proxy / OpenRouter-style gateway
REQUEST_TIMEOUT_SECONDS=60
CONNECT_TIMEOUT_SECONDS=10
MAX_RETRIES=2
MAX_CONNECTIONS=100

SERVICE_PORT=8000
CORS_ORIGINS='["http://localhost:3000"]'

LICENSE — the SPDX expression license = "MIT" in pyproject.toml only names the licence; the licence text itself belongs in a LICENSE file at the root (what uv build bundles into the wheel's .dist-info/licenses/ and what GitHub detects). For MIT, paste the standard text with "Copyright (c) 2026 Your Name" — swap in the real holder before you publish. Pair it with a README.md badge or line ("MIT © 2026") so humans see it too.

.gitignore — 01B.1's list already covers .env* (with !.env.example), .venv/, __pycache__/, .pytest_cache/, .ruff_cache/; add dist/, *.egg-info/, htmlcov/, .coverage. Verify with git check-ignore -v .env before your first commit (01B.2 §5 owns the ritual).

Makefile — thin wrappers over uv run, per 01B.1 §7.2 (a justfile works identically if you prefer just):

make
.PHONY: sync test lint run service build
test:    ; uv run pytest
lint:    ; uv run ruff check . && uv run ruff format --check .
sync:    ; uv sync
run:     ; uv run aitoolkit health
service: ; uv run uvicorn aitoolkit.service:app --reload
build:   ; uv build

README.md — what it is, quickstart (uv sync, uv run aitoolkit health, uv run uvicorn aitoolkit.service:app --reload), the "no key needed" note (ScriptedBackend), the test command, and links to the module lessons. Keep it under a page; the README is the first thing a reviewer reads.

End-to-end walkthrough (illustrative — needs the third-party deps; every /v1/* route requires the demo X-API-Key):

bash
uv sync                                    # creates .venv, installs deps + aitoolkit itself
uv run pytest                              # the whole suite — no key, no network
uv run aitoolkit version                   # aitoolkit 0.1.0
uv run aitoolkit config                    # resolved settings, secrets never printed
uv run aitoolkit complete "hi"             # Hello! How can I help you today?
uv run aitoolkit complete "hi" --json      # full Completion as JSON
uv run aitoolkit complete "hi" --model gpt-6-luna --json
uv run python -m aitoolkit health          # same as console script
uv run uvicorn aitoolkit.service:app --reload --port 8000
# in another shell:
curl localhost:8000/health                  # {"status":"ok",...} — unversioned, no key
curl -X POST localhost:8000/v1/echo \
     -H 'content-type: application/json' \
     -H 'X-API-Key: demo-key-alice' \
     -d '{"message":"hello"}'               # {"message":"hello","length":5}
curl -X POST localhost:8000/v1/complete \
     -H 'content-type: application/json' \
     -H 'X-API-Key: demo-key-alice' \
     -H 'x-request-id: req-demo-1' \
     -d '{"prompt":"hi"}'                   # Completion JSON; response + logs carry req-demo-1
curl -N -X POST localhost:8000/v1/stream \
     -H 'content-type: application/json' \
     -H 'X-API-Key: demo-key-alice' \
     -d '{"prompt":"hi"}'                   # SSE: event: token … event: done [DONE]
LOG_JSON=true uv run uvicorn aitoolkit.service:app   # same traffic, JSON log lines
uv build                                   # dist/*.whl + *.tar.gz
uv pip install dist/aitoolkit-0.1.0-py3-none-any.whl  # verify the artifact installs clean
aitoolkit health                           # console script from the wheel

5.5 Swapping ScriptedBackend for a real provider#

The seam is the complete(prompt, *, model=None) / stream(prompt, *, model=None) interface plus the construction sites — today there are two: backend.get_backend() (used by cli.py) and the ScriptedBackend() that lifespan builds onto app.state.backend (used by service.py through its get_backend dependency). To go live you write one class — e.g. OpenAICompatBackend using httpx.AsyncClient from 01B.5 with settings.openai_base_url/openai_api_key/openai_model from 01B.2, mapping its response onto the Completion dataclass — then return it from get_backend() and construct it in lifespan. Callers don't change: /v1/complete still maps dataclass → wire model, the CLI still prints result.text. In a real deployment you'd centralise the construction (one factory both sites call) — 03.11 is exactly that consolidation across providers. 03.1 Part 4 builds the OpenAI-SDK version of this seam, 03.11 generalises it with hooks for the logging/cost/metrics of 1.10, and 03.3/03.9 cover streaming and batching on top. Module 03 owns everything provider-specific; this lesson's job was to make sure the shape it plugs into is solid.

5.6 Readiness self-check#

Before you start applying this toolkit in Modules 02–03 (Module 02 is conceptual — the NumPy/pandas data work is 01B.11's, the next lesson), verify the toolkit:

Checklist

  • uv sync succeeds; uv run pytest is green with no API key and no network
  • uv run aitoolkit health / version / config / complete "hi" all work
  • uv run uvicorn aitoolkit.service:app --reload serves /health and the /v1/* routes (which want X-API-Key: demo-key-alice)
  • Logs show request_id on every line during a request; LOG_JSON=true switches format
  • breakpoint() drops into pdb; PYTHONBREAKPOINT=0 disables it
  • python -X dev shows dev-mode warnings during a test run
  • uv build produces a wheel; uv pip install dist/*.whl into a fresh venv works and aitoolkit is on PATH
  • You can explain: logger vs handler vs filter vs formatter; wheel vs sdist; module vs package vs distribution

20-question quiz (answers in <details>):

  1. Why is logging.getLogger(__name__) better than print() in a service?
  2. What does propagate = False prevent, and when would you not set it?
  3. dictConfig defaults disable_existing_loggers to what, and why is False safer?
  4. What's the difference between a logger's level and a handler's level?
  5. Why logger.debug("%s", x) instead of logger.debug(f"{x}")?
  6. logger.exception() outside an except block produces what?
  7. Name the three layers of secret defence and which one this lesson implements.
  8. Why contextvars instead of a module-level global for request IDs?
  9. What does the extra={...} argument do, and what key names must you avoid?
  10. breakpoint() vs python -m pdb script.py — when do you use each?
  11. What does PYTHONBREAKPOINT=0 do and when is it useful?
  12. Why does breakpoint() freeze an entire async service while stopped?
  13. Name two tools for inspecting a running/hung process without stopping it.
  14. cProfile vs tracemalloc — which answers "where does the time go" vs "where does the memory go"?
  15. Why read piped input from sys.stdin and errors to sys.stderr in a CLI?
  16. argparse exit code 2 means what? Who produces it?
  17. python -m pkg vs python pkg/ — what's the difference for imports?
  18. Wheel vs sdist — which does pip/uv actually install?
  19. What does [project.scripts] do, and what must the target function's signature look like?
  20. Application vs library — which describes aitoolkit, and how does that change dependencies?
Answers
  1. Levels, handlers, filters, formatters, propagation — print has none and bypasses the pipeline.
  2. Double-logging when child and ancestor both have handlers; don't set it if you want records to reach a root handler you configured centrally (the usual app pattern attaches handlers at root only).
  3. True; False avoids silently disabling loggers libraries configured at import time.
  4. Logger level gates whether the record is created/handled at all; handler level gates what that handler emits — set handlers low (DEBUG) and control volume at loggers.
  5. f-string evaluates eagerly even when DEBUG is off; % args defer formatting until the record survives.
  6. A NoneType: None "traceback" — there's no active exception; pass exc_info=exc or stay inside except.
  7. Don't log secrets (review), redaction filter (safety net — implemented here), log-store access control/retention (12.4/11.1).
  8. asyncio.Tasks copy the context — each request's tasks get an isolated copy; a global leaks across concurrent requests.
  9. Attaches arbitrary fields to the record for formatters; can't reuse LogRecord attribute names (name, msg, levelname…).
  10. breakpoint() for interactive inspection mid-run; python -m pdb for stepping through a whole script from the start (and auto post-mortem on crash).
  11. Replaces breakpoint()'s target with nothing — breakpoints become no-ops; essential in CI so a stray breakpoint() doesn't hang the pipeline.
  12. pdb stops the whole interpreter; the event loop can't schedule other tasks while you're inspecting one.
  13. py-spy dump --pid, faulthandler.dump_traceback_later/SIGUSR1, aiomonitor's stacktrace.
  14. cProfile = CPU time per function; tracemalloc = allocations per line.
  15. stdout is data (pipes, jq); stderr is diagnostics — mixing them corrupts downstream parsing.
  16. Command-line usage error; argparse produces it (your code returns 1 for app errors, 0 for success).
  17. -m runs pkg/__main__.py with the package importable (relative imports work); python pkg/ runs __main__.py without package context.
  18. Wheel — a ready-to-install zip with .dist-info; sdist is the source archive built into wheels.
  19. Installs a console executable calling module:function; the function takes no required args and its return/SystemExit becomes the exit code.
  20. aitoolkit is an application (deploy-versioned, pinned deps, not published); applications pin ==, libraries use >= floors and extras.

5.7 Module map: which 01B skill each later module leans on#

Later module It assumes you can… 01B skill
02 — How LLMs work Run deterministic Python, read timings 01B.1, 01B.3, 01B.10 §2.8
01B.11 — NumPy & pandas (next lesson) Embeddings as arrays, tabular eval/cost data builds on this toolkit's packaging habits
03 — LLM APIs Configure clients, log calls, debug requests, package the wrapper 01B.5, 01B.10 (all three parts)
04 — Prompt & context Repeatable experiments, versioned prompts 01B.1, 01B.8
05 — Data engineering CLIs for pipelines, structured logs, packaging 01B.10 §3, §4
06 — Embeddings & vector search Async pipelines, bounded concurrency, retries 01B.4, 01B.9
07 — RAG Async pipelines, retries, per-request observability 01B.4, 01B.9, 01B.10 §1.10
08A — Agent foundations Async orchestration, debugging agent loops 01B.4, 01B.10 §2.4
09 — Voice & multimodal HTTP clients, retries, cost logging 01B.5, 01B.9, 01B.10 §1.10
10A — Evaluation foundations pytest suites, CI-friendly CLIs 01B.8, 01B.10 §3
11A — Observability and AgentOps Logging→tracing 01B.10 (whole lesson)
11C — Deployment, reliability and lifecycle Packaging for deploy, CI 01B.10 (whole lesson)
12 — Safety & security Secret handling, redaction, PII in logs 01B.2, 01B.10 §1.8
13B — Capstones The whole toolkit assembled this lesson's aitoolkit
14B — Career appendix Packaged, documented, installable projects 01B.10 §4

Beyond the logging table in 1.11, the failures that cost the most time across debugging, CLIs and packaging:

Symptom Likely cause Fix
Works in repo, ModuleNotFoundError after pip install Package not where uv_build looks — it expects src/<pkg>/__init__.py — or package data not declared src/ layout (or [tool.uv.build-backend] module-root); importlib.resources for data files
aitoolkit command not found after install [project.scripts] missing or function signature wrong aitoolkit = "aitoolkit.cli:main"; main() takes no required args
Every log line printed twice Handler on child logger and root, propagate left on One handler location; or propagate=False on the child
breakpoint() hangs CI Stray breakpoint committed PYTHONBREAKPOINT=0 in CI env; grep before merge
pdb "post-mortem" shows wrong exception Called outside except / stale sys.last_exc python -m pdb script.py (auto post-mortem) or pdb.pm() right after the crash
Async service freezes under debugger pdb stops the whole loop — expected Inspect one task, continue, or use aiomonitor/py-spy for the hung case
CLI prints warnings into piped JSON Diagnostics on stdout Errors/warnings → sys.stderr; data → sys.stdout
argparse exits 2 on valid input required=True subparser with no default command Give a default subcommand or print help
python -m pkg works, python pkg/ ImportError Relative imports need package context Use -m; keep __main__.py self-contained if you need dir-run
Tests pass in repo, fail on installed wheel Tests import from source tree, not installed dist Test the wheel in a clean venv before release
uv sync doesn't create the aitoolkit command package = true missing or no [build-system] Both required; uv init --package sets them
Secret visible in aitoolkit config output Dumping whole Settings object Print selected non-secret fields only

Common misconceptions#

  • "Logging is just print with levels." It's a pipeline — handlers decide destination, filters mutate records, formatters decide representation, propagation decides reach. print bypasses all of it.
  • "More logging = more debuggable." Unstructured, unfiltered, body-logging makes production less debuggable: noise buries signal, PII leaks, cost rises. One structured line per unit of work beats forty text lines.
  • "The debugger is for beginners; seniors read logs." Seniors use both — and reach for py-spy/faulthandler/post-mortem pdb precisely when logs can't answer "where is it stuck right now".
  • "Packaging is for libraries." Applications benefit more: the CLI, service and tests sharing one installable unit is what makes aitoolkit coherent instead of a folder of scripts.
  • "pip install -e . is the same as the wheel." Editable installs mask packaging bugs (data files, entry points, metadata). Always verify the built wheel in a clean environment.
  • "A CLI needs a framework." argparse covers the vast majority; typer/click earn their dependency when the command surface gets genuinely complex.
  • "Contextvars are just globals for async." They're task-local: each asyncio.Task gets a copy, which is exactly the isolation request IDs need — a global would leak across concurrent requests.
  • "Version numbers are cosmetic." They end up in every log line, bug report and --version; single-source them in pyproject.toml and read via importlib.metadata.

Key takeaways#

  • Configure logging once in the entry point with dictConfig, disable_existing_loggers: False, handlers at root (or propagate=False on children), and levels on loggers.
  • Emit structured records — JSON formatter + extra={...} fields + contextvars request IDs — so logs are queryable, not just readable.
  • Treat redaction as a filter on every outbound handler, and never log prompt/response bodies or secret-shaped values by default.
  • Debug on a ladder: traceback → targeted log → breakpoint()/pdb → reproduce-in-test → wire tools (curl -v, httpx hooks) → profilers (cProfile, tracemalloc, py-spy) → tracing (11A.1).
  • Async debugging needs PYTHONASYNCIODEBUG, asyncio.all_tasks(), and (for hung processes) aiomonitor/py-spy — a stopped loop can't be stepped through.
  • CLIs are argparse + main(argv) + __main__.py/python -m + [project.scripts] — injectable argv makes them testable without subprocesses.
  • A distribution is package + metadata; pyproject.toml [build-system] (uv_build by default with uv) turns the tree into wheel/sdist via uv build.
  • aitoolkit is an application: pinned deps, deploy-versioned, packaged for cohesion — not a PyPI library.
  • The readiness check isn't bureaucracy — it's the difference between "I followed lessons" and "I can actually operate what I built" when Modules 02–03 start assuming this foundation.

Where you'll use this in the AI path#

You learned You'll use it in
Structured logging + request IDs 03.10 §4: structured logging of every call, 11A.1 tracing/observability, 11C.1 §2.11 structured logging with request IDs
Redaction + secret handling 12.4 PII/privacy/data leakage, 03.10 §4.5 content in logs
Debugging ladder, pdb, profiling 03.10 Part 1 debugging LLM code, 03.10 Part 5 reproducing problems
HTTP event hooks, curl -v 03.10 §2.3 HTTP event hooks
CLI design, packaging 03.11 provider-agnostic client (packaged wrapper), 05.9 ingestion pipelines (pipeline CLIs), 10A.8 regression CI (eval CLIs in CI)
Async debugging 03.9 async and batch, 08A.14 reliable agents
The whole toolkit 13B capstones, 14B career/portfolio

Terms introduced in this lesson#

  • LogRecord — the object logging passes through filters to formatters; carries message, level, logger name, exception info and any extra fields.
  • Handler — decides where a log record goes (console, file, socket, HTTP).
  • Formatter — converts a LogRecord to output text/bytes (plain, JSON, etc.).
  • Filter — drops or mutates a record before formatting (request-ID injection, redaction).
  • Propagation — a record logged to a.b.c is also offered to a.b, a, and root unless propagate=False.
  • dictConfig — dict-based logging configuration; the production alternative to one-shot basicConfig.
  • Structured logging — one machine-readable record (typically JSON) per event with consistent keys.
  • Correlation/request ID — per-request identifier attached to every log/trace/span for reconstruction.
  • contextvars — context-local variables that follow await into asyncio tasks; the right mechanism for request-scoped state.
  • Redaction filter — a logging.Filter that scrubs secrets/PII from the final message.
  • breakpoint() — builtin that enters the debugger (pdb by default) at that line.
  • Post-mortem debugging — inspecting the crashed frame after an exception (python -m pdb, pdb.pm()).
  • faulthandler — stdlib module dumping thread tracebacks on fatal signals/timeouts.
  • Dev mode (-X dev/PYTHONDEVMODE) — extra runtime checks: faulthandler, asyncio debug, more warnings.
  • cProfile/pstats — deterministic CPU profiler and its stats browser.
  • tracemalloc — stdlib memory allocator tracing; shows which line allocated memory.
  • py-spy — external sampling profiler; dumps/records stacks of a running process without stopping it.
  • Event hooks (httpx) — per-request/response callables for wire-level logging/monitoring.
  • argparse subparsers — nested subcommand support in stdlib CLI parsing.
  • Console script / entry point — [project.scripts] mapping an executable name to module:function.
  • Wheel vs sdist — installable zip vs source archive; uv build produces both.
  • Build backend — the tool (uv_build, hatchling, setuptools) that turns source into distributions.
  • Editable install (-e) — install that links to the source tree for live development.
  • importlib.metadata — stdlib API reading installed distribution metadata (version, deps).
  • Application vs library — deploy-versioned pinned app vs semver'd permissive library; changes how dependencies are written.

Exercises#

  1. Configure once. Add logging_setup.configure_logging() to service.py's start-up and remove any basicConfig calls; verify uvicorn logs still appear.
  2. JSON in production shape. Start the service with LOG_JSON=true and hit /v1/complete twice. The logging handler writes to stderr, so redirect it (2>&1) and pipe it through jq; confirm the log lines of each request share one ID.
  3. Redaction escape test. Write a log call that would leak settings.openai_api_key if logged raw, for example log.info("api_key=%s", key_value); confirm the redaction filter masks it. Then log the bare value with no label and see it slip through (the limits in 1.8). Fix the call site either way.
  4. Request-ID middleware. Send two concurrent /v1/complete requests with different X-Request-ID headers; confirm each response echoes its own ID and logs don't cross.
  5. Debug a planted bug. Insert bug = 1 / (x - x) in a helper, reproduce with python -m pdb, then convert the repro into a test_*.py that fails before the fix.
  6. Profile the pipeline. Wrap run_pipeline in cProfile; identify the top function by tottime vs cumtime and explain the difference.
  7. Memory leak hunt. Use tracemalloc snapshots around run_pipeline on 10k items; find the largest allocation site.
  8. CLI test without subprocess. Write test_cli.py::test_complete_text asserting main(["complete", "hi"]) prints the scripted reply — no subprocess, no server.
  9. Build and install. Run uv build, install the wheel into a fresh venv (uv venv /tmp/verify-venv && uv pip install --python /tmp/verify-venv/bin/python dist/*.whl; on Windows the interpreter is Scripts\python.exe), and run aitoolkit health from it.
  10. Swap the backend. Implement ScriptedBackendV2 returning a different shape, register it behind an env var, and confirm service.py, cli.py and tests all still pass.
  11. Failure injection. Make ScriptedBackend raise httpx.ConnectError 50% of the time (seeded random); watch retry_async + CircuitBreaker behave in logs.
  12. py-spy awareness. Start uvicorn, load it with slow requests, and run py-spy dump --pid $(pgrep -f uvicorn) (or docker exec) — identify which frames dominate.
Solutions (sketches — your implementations will vary)
  1. Move configure_logging(...) into the app factory/lifespan; keep it out of module import so tests and notebooks don't reconfigure.
  2. The request ID travels in the x-request-id response header (echoed by RequestContextMiddleware) and in the server's JSON log lines — the Completion body has no request_id field, so jq .request_id on it yields null. Read the header: curl -si localhost:8000/v1/complete -H 'X-API-Key: demo-key-alice' -H 'x-request-id: r1' -d '{"prompt":"x"}' | grep -i '^x-request-id:' → x-request-id: r1. Or check the server side: LOG_JSON=true uv run uvicorn aitoolkit.service:app 2>&1 | jq -R -r 'fromjson? | select(.request_id != null) | .request_id' prints the same ID on that request's log lines (-R plus fromjson? skips uvicorn's own plain-text lines, which are not JSON and would otherwise make jq stop with a parse error). Two requests → two distinct IDs, each consistent across that request's lines.
  3. The filter keys on labels such as api_key=, so the labelled call is masked and the bare value is not — which is why it is a safety net and not the fix. The fix is to log only what you need, for example log.info("calling %s", settings.openai_base_url), and never the key or the whole settings object.
  4. Middleware sets the contextvar per request; asyncio.Task context-copying keeps concurrent requests isolated — verify with grep on captured logs.
  5. pdb: n/s/p x; test: with pytest.raises(ZeroDivisionError) around the helper — now it fails before the fix and passes after.
  6. cProfile + pstats.Stats(pr).sort_stats("tottime").print_stats(5) — tottime excludes callees, cumtime includes them.
  7. Compare a snapshot taken before the run with one taken after (after.compare_to(before, "lineno")). Expect the Ok/Err objects and the out list in concurrency.py, plus whatever your process function allocates, near the top. There is no leak in run_pipeline; the exercise is reading the ranking.
  8. See tests/test_cli.py above — main([...]) returns int, capsys captures stdout.
  9. uv build && uv venv /tmp/verify-venv && uv pip install --python /tmp/verify-venv/bin/python dist/*.whl && /tmp/verify-venv/bin/aitoolkit health — the command exists only because the wheel's [project.scripts] created it, and the import works because the wheel contains the package (nothing comes from your source tree).
  10. get_backend() reads os.environ.get("BACKEND", "scripted"), and lifespan calls that same factory instead of ScriptedBackend() (the two construction sites from 5.5); keep the complete()/stream() interface unchanged.
  11. Seeded random.Random(0) in the fake; logs show retry attempts (attempt= extra) and circuit opening after threshold.
  12. py-spy dump shows stacks in asyncio/httpx/your handler — the "top" frames tell you where time is spent without stopping the process.

Check yourself#

  1. What's the difference between a handler and a formatter in logging?
  2. Why does dictConfig need disable_existing_loggers: False in an application?
  3. logger.info("x", extra={"request_id": "r1"}) — where does request_id end up, and how does a JSON formatter pick it up?
  4. When would you choose structlog over the stdlib JsonFormatter?
  5. contextvars.ContextVar vs a module global for request IDs — why does the global fail under asyncio?
  6. Name two ways secrets leak into logs and two defences.
  7. breakpoint() vs python -m pdb script.py — pick one for: (a) stepping through a script from line 1, (b) inspecting live state mid-request.
  8. PYTHONBREAKPOINT=0 — what does it do and why would CI want it?
  9. faulthandler.dump_traceback_later(30) — what problem does it solve that breakpoint() can't?
  10. cProfile vs tracemalloc vs py-spy — one-line each: when do you reach for it?
  11. Why does python -m aitoolkit beat python aitoolkit/ for a packaged CLI?
  12. Wheel vs sdist — which do you upload to PyPI, and which do users install?
  13. [project.scripts] aitoolkit = "aitoolkit.cli:main" — what does the installer generate, and what must main's signature be?
  14. uv sync on a package = true project — editable or wheel install, and why does that matter for development?
  15. Application vs library — which is aitoolkit, and how does the choice change dependencies in pyproject.toml?

Further resources#

← 01B.9 — Retries, Timeouts, Backoff and Resilience | Module 01B overview | 01B.11 — NumPy and pandas Essentials for AI Work →

Esc
02.2Tokens and TokenizationHow LLMs Work · 21k wordsLesson
02.3EmbeddingsHow LLMs Work · 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons · Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack — architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation — and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility · 12k wordsLesson
↑ ↓ navigate↵ openesc close