Python for AI Engineers · Part B · Lesson 14 of 26

Python project structure, pyproject.toml and logging for AI services

Lay out a real AI service like a Spring or Node developer would expect: src layout, packages, imports and circular imports, pyproject.toml in depth, ruff and pre-commit, then logging done properly: a logger per module, JSON logs with request ids, and LLM calls logged without secrets or PII.

⏱ 45 min3 exercises that check your codeRuns in your browser

By the end you can

  • Lay out an AI service with the src layout and one module per job (config, clients, prompts, services, api), and map it to a Maven or Node project
  • Use absolute and relative imports, and explain and fix a circular import
  • Read every part of a real pyproject.toml: dependencies, dev groups, a script entry point and tool settings for ruff and pytest
  • Use the logging module properly: a logger per module, levels, handlers and formats, and never print in services
  • Write structured JSON logs with a request id, log every LLM call (model, tokens, latency) without secrets or PII, and switch all of it by environment
1 / 6

1The layout of a real AI service

Lab code fits in two or three files. A service your team runs for a year does not. Below is the layout used in this lesson: a small support bot with one endpoint, POST /ask, that answers questions with an LLM. Every file in this lesson is a real, working file of that project.

Each module has one job, and the imports only go one way: api uses services, services uses prompts and the client, everything reads config. Nothing imports api. That one rule keeps the code easy to test and, as section 3 shows, keeps circular imports away.

Module Its job Spring Boot equivalent
config.py Read settings once from the environment application.yml + @ConfigurationProperties
logging_setup.py Configure logging once at startup logback-spring.xml
clients.py Build the OpenAI client (URL, key, timeout, retries) a @Bean that builds a RestClient or ChatClient
prompts.py Prompt text and the code that builds messages prompt templates in src/main/resources
services.py The business logic: answer a question a @Service class
api.py HTTP: parse the request, call the service, return JSON a @RestController
support-bot/
support-bot/
├── pyproject.toml            # the project file (section 4)
├── uv.lock                   # exact versions, written by uv
├── .python-version
├── .env.example              # settings template; the real .env is never committed
├── .pre-commit-config.yaml   # checks that run before each git commit (section 5)
├── README.md
├── src/
│   └── support_bot/          # the package: what "import support_bot" finds
│       ├── __init__.py
│       ├── config.py
│       ├── logging_setup.py
│       ├── clients.py
│       ├── prompts.py
│       ├── services.py
│       └── api.py
└── tests/
    ├── test_config.py
    └── test_services.py
  1. The **src layout**: the code lives one folder down, in src/. Python cannot import it just because it is in the current folder, so your tests use the **installed** package (uv installs it for you), exactly like production does. A file you forgot to include shows up as a failing test, not as a crash after deploy.line 8
  2. The project is named support-bot (dashes are fine in a project name), but the package is support_bot: an import name must be a valid Python identifier, so no dashes.line 9
  3. __init__.py makes the folder a **package**. It runs once, the first time anything in the package is imported. Ours only holds __version__. It can be empty.line 10
  4. Not logging.py: a module named like a standard library module (logging, json, types) or a library (openai) **hides** the real one for every import in the project. Pick a different name.line 12
  5. tests/ sits next to src/, not inside the package, so tests are not shipped with the code. Same idea as src/test/java in Maven.line 17
Spring Boot (Maven)
support-bot/
├── pom.xml
└── src/
    ├── main/
    │   ├── java/com/acme/supportbot/
    │   │   ├── SupportBotApplication.java
    │   │   ├── config/AppProperties.java
    │   │   ├── client/LlmClientConfig.java
    │   │   ├── service/ChatService.java
    │   │   └── web/AskController.java
    │   └── resources/
    │       ├── application.yml
    │       ├── application-prod.yml
    │       └── logback-spring.xml
    └── test/java/com/acme/supportbot/
        └── ChatServiceTest.java
Node (TypeScript)
support-bot/
├── package.json
├── package-lock.json
├── tsconfig.json
├── .env.example
├── src/
│   ├── config.ts
│   ├── logger.ts        # pino
│   ├── clients.ts
│   ├── prompts.ts
│   ├── services/chat.ts
│   └── api/server.ts    # express or fastify
└── test/
    └── chat.test.ts

In Java the folder path is the package name (com/acme/supportbot) and every class gets its own file. In Python a file is a module and holds as many functions and classes as belong together, so the tree is flatter. When services.py grows, turn it into a sub-package: a folder services/ with __init__.py, chat.py and rag.py, imported as support_bot.services.chat.

Tip Create this skeleton with uv init --package support-bot. It makes src/support_bot/__init__.py, a [build-system] and a [project.scripts] entry for you (section 4). A plain uv init makes the flat layout the labs use, which is fine for small apps.

2Packages and imports: absolute or relative

Every module has a full dotted name built from its path inside src/: the file src/support_bot/services.py is the module support_bot.services. Inside that module, __name__ holds exactly that string, which is why it is the perfect logger name later.

An absolute import spells out that full path: from support_bot.prompts import SYSTEM. A relative import starts with a dot and means "in my own package": from . import prompts, or from .prompts import SYSTEM (two dots, .., go one package up). Both find the same module, and Python imports each module only once: later imports reuse the copy in sys.modules, like a Node module cache.

The box below builds a tiny package in a temporary folder, so you can watch this happen. The last lines run services.py the wrong way, as a plain script, which is what python src/support_bot/services.py does.

Try it: edit and run
import runpy
import sys
import tempfile
from pathlib import Path

src = Path(tempfile.mkdtemp())          # a throwaway folder that plays the role of src/
pkg = src / "support_bot"
pkg.mkdir()
(pkg / "__init__.py").write_text('__version__ = "0.1.0"\n')
(pkg / "prompts.py").write_text('SYSTEM = "You are the support assistant for Acme Cloud."\n')
(pkg / "services.py").write_text("""
from support_bot.prompts import SYSTEM   # absolute: the full path from the package
from . import prompts                    # relative: the module prompts in my own package


def build(question):
    return [{"role": "system", "content": SYSTEM}, {"role": "user", "content": question}]
""")

sys.path.insert(0, str(src))            # what installing the project (uv sync) does for you
for name in [m for m in sys.modules if m.startswith("support_bot")]:
    del sys.modules[name]               # forget an earlier run of this box

import support_bot
from support_bot import services

print(support_bot.__version__)
print(services.__name__)                # the module's full dotted name
print(services.build("Reset my password")[1])
print(services.prompts.SYSTEM is services.SYSTEM)   # one module, imported once

try:
    runpy.run_path(str(pkg / "services.py"))        # like: python src/support_bot/services.py
except ImportError as e:
    print("ImportError:", e)
Expected output
0.1.0
support_bot.services
{'role': 'user', 'content': 'Reset my password'}
True
ImportError: attempted relative import with no known parent package

What the key lines do

  • sys.path is Python's search path for imports, like the Java classpath. In a real project you never touch it: uv sync installs your package into .venv, so import support_bot works from anywhere, tests included.

  • services.__name__ is support_bot.services: the dotted name, not the file name.

  • services.prompts.SYSTEM is services.SYSTEM is True: the absolute and the relative import gave the same module object.

  • runpy.run_path runs a file as a top-level script. A script has no parent package, so from . import prompts fails with the error you saw. The absolute import on the line above still worked, because the package can be found on sys.path.

Which to use? Absolute imports are the safer default: they read the same in every file, survive copy and paste, and work however the module is started. Relative imports are fine inside one package and make renaming the top package easier. Pick one style per project; this lesson uses absolute imports.

To run a module inside a package, use its module name with -m: uv run python -m support_bot.services. That sets up the package first, so both kinds of import work.

Watch out Never fix an import error by adding sys.path.insert(...) to your code. It hides a real problem (the package is not installed, or you started a file the wrong way) and breaks as soon as someone runs the code from another folder. Run uv sync, start code with uv run, and use -m for modules.

3Circular imports: why they happen and how to fix them

An import runs the module, top to bottom, the first time. While it runs, the half-built module already sits in sys.modules. If module A imports B, and B imports a name from A before A has defined it, B gets a partially initialized A, and the name is not there yet.

The classic way to get there: services.py defines a TIMEOUT and imports make_client from clients.py, and clients.py needs that TIMEOUT, so it imports from services.py. Run the box to see the exact error, then the fix.

Try it: edit and run
import importlib
import sys
import tempfile
from pathlib import Path

src = Path(tempfile.mkdtemp())
pkg = src / "bot"
pkg.mkdir()
sys.path.insert(0, str(src))


def write(name, code):                  # write one module of the package "bot"
    (pkg / name).write_text(code)
    importlib.invalidate_caches()       # tell Python files changed while it runs
    for m in [m for m in sys.modules if m.startswith("bot")]:
        del sys.modules[m]              # start each import from scratch


write("__init__.py", "")
write("clients.py", """
from bot.services import TIMEOUT        # clients needs something from services...

def make_client():
    return f"client(timeout={TIMEOUT})"
""")
write("services.py", """
from bot.clients import make_client     # ...and services needs something from clients

TIMEOUT = 30

def answer(q):
    return f"{make_client()} answers {q!r}"
""")

try:
    import bot.services
except ImportError as e:
    print("ImportError:", str(e).replace(str(src), "..."))

# The fix: move what both need into a module that imports neither of them
write("config.py", "TIMEOUT = 30\n")
write("clients.py", """
from bot.config import TIMEOUT

def make_client():
    return f"client(timeout={TIMEOUT})"
""")
write("services.py", """
from bot.clients import make_client

def answer(q):
    return f"{make_client()} answers {q!r}"
""")

import bot.services
print(bot.services.answer("hi"))
Expected output
ImportError: cannot import name 'TIMEOUT' from partially initialized module 'bot.services' (most likely due to a circular import) (.../bot/services.py)
client(timeout=30) answers 'hi'

Step by step: import bot.services starts running services.py. Its first line imports bot.clients, so Python pauses services.py and runs clients.py. That file asks bot.services for TIMEOUT, but services.py stopped on its first line and has not reached TIMEOUT = 30 yet. (The .replace(...) in the box only shortens the temporary folder name in the message to ....)

Fixes, best first:

  1. Move the shared piece down into a module that imports neither side, as in the box (config.py, or a models.py for shared data classes). This is almost always the right fix, and it is what the layout in section 1 gives you for free: arrows only point one way.

  2. Import the module, not the name: from bot import services and then use services.TIMEOUT inside a function. The attribute is read when the function runs, by which time both modules have finished loading.

  3. Import only for type hints: when you need a class just for an annotation, put the import under if TYPE_CHECKING: (from typing). Editors and type checkers see it; at run time it never runs.

  4. Import inside the function that needs it. It works, but it hides the dependency; use it as a last resort.

Java resolves classes lazily, so two classes that use each other compile and run fine, and a Spring bean cycle is reported at startup by the container. Node with CommonJS require hands you a half-finished module too, but silently: you get undefined instead of an error. Python at least tells you "most likely due to a circular import".

4pyproject.toml in depth

Lesson 1 showed the small pyproject.toml that uv init writes. Here is the full one of the support bot, after uv init --package support-bot, uv add fastapi openai python-dotenv uvicorn and uv add --dev pytest ruff, plus the tool settings added by hand. One file holds what Maven spreads over pom.xml and its plugins, and Node over package.json, .eslintrc and jest.config.js.

Run
uv sync
uv run support-bot
You should see
Resolved 30 packages in 2ms
Checked 28 packages in 0.27ms
2026-11-28 20:58:32,078 INFO    support_bot.api [-] app ready
2026-11-28 20:58:32,081 INFO    uvicorn.error [-] Started server process [17774]
2026-11-28 20:58:32,081 INFO    uvicorn.error [-] Waiting for application startup.
2026-11-28 20:58:32,081 INFO    uvicorn.error [-] Application startup complete.
2026-11-28 20:58:32,082 INFO    uvicorn.error [-] Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
pyproject.toml
[project]
name = "support-bot"
version = "0.1.0"
description = "A small AI support service"
readme = "README.md"
requires-python = ">=3.12"
dependencies = [
    "fastapi>=0.165",
    "openai>=3.60",
    "python-dotenv>=1.2",
    "uvicorn>=0.55",
]

[project.scripts]
support-bot = "support_bot.api:run"

[dependency-groups]
dev = [
    "pytest>=9",
    "ruff>=0.17",
]

[build-system]
requires = ["uv_build>=0.11,<0.12"]
build-backend = "uv_build"

[tool.ruff]
line-length = 100

[tool.ruff.lint]
select = ["E", "F", "I", "B", "UP", "T20"]

[tool.ruff.lint.per-file-ignores]
"tests/**" = ["T20"]

[tool.pytest.ini_options]
testpaths = ["tests"]
addopts = "-q"
  1. [project] is the standard table (PEP 621) that every Python tool reads: name, version, Python version and dependencies. Like the top of package.json, or groupId/artifactId/version in a pom.line 1
  2. The lowest Python version this code supports. uv picks an interpreter that matches, and ruff uses it to decide which syntax upgrades to suggest.line 6
  3. Runtime dependencies, installed everywhere, production included. >= is a minimum; the exact versions live in uv.lock, like package-lock.json.line 7
  4. **Entry points**: each line becomes a command. support-bot = "support_bot.api:run" means "import the module support_bot.api and call its function run()". Like "bin" or "scripts": {"start": ...} in package.json, or the Main-Class of a Spring Boot jar.line 14
  5. Dependency **groups** (PEP 735) are for development only: tests, linters. uv sync installs the dev group by default; uv sync --no-dev (for example in a Docker image) leaves it out. Like devDependencies, or Maven's <scope>test</scope>.line 17
  6. [build-system] says which tool turns src/support_bot into an installable package. It is what lets uv sync install your own project into .venv, so imports and the support-bot command work. uv writes a range for the uv version you have; hatchling or setuptools work the same way.line 23
  7. Every [tool.<name>] table belongs to one tool, which reads only its own. This is how one file replaces a pile of config files.line 27
  8. ruff's formatter and line-length check use 100 columns (the default is 88, like Black). ruff also reads requires-python, so it knows the target is 3.12.line 28
  9. The lint rule families: E style errors, F real bugs such as unused imports and undefined names (Pyflakes), I import sorting, B likely bugs (flake8-bugbear), UP modern syntax for your Python version, and T20, which reports every print().line 31
  10. print is allowed in tests, nowhere else. That turns "never print in services" (section 6) from a code-review comment into a failing check.line 34
  11. pytest settings: look for tests in tests/ and always run with -q. With this table, plain uv run pytest is enough.line 36

uv sync installs the dependencies and your own package into .venv. Then uv run support-bot finds the command that [project.scripts] created and calls run() in api.py, which starts the web server. The counts and times in the first two lines depend on your machine; press Ctrl+C to stop the server. These three lines are all of run():

def run() -> None:
    """Entry point for the `support-bot` command (see [project.scripts])."""
    uvicorn.run(create_app(), host="127.0.0.1", port=8000, log_config=None, access_log=False)

log_config=None tells uvicorn not to set up its own log format, so its lines go through ours (section 7). access_log=False drops uvicorn's one line per request, because our middleware logs a better one.

Entry points versus if __name__ == "__main__":. In a single script you end the file with that if so the code runs only when the file is started directly, not when it is imported (__name__ is "__main__" only in the file you started). In a package, prefer [project.scripts]: the command has a real name, works from any folder, and the module stays import-safe because nothing runs on import. If you also want python -m support_bot, add a __main__.py file to the package that calls the same function.

Tip Use uv add and uv remove for dependencies instead of editing the list by hand: they update pyproject.toml and uv.lock together. The [tool.*] tables are yours to edit.

5ruff: lint and format in one fast tool

ruff is a linter (it finds bugs and bad patterns, like ESLint or Checkstyle/SpotBugs) and a formatter (it rewrites layout, like Prettier or Spotless) in one program. It is written in Rust and checks a whole project in milliseconds, so you can run it on every save and every commit.

Here is a draft file with five problems a reviewer would catch: an unused import, unsorted imports, an old-style List type, the mutable default from lesson 4, and a print:

# src/support_bot/draft.py
import os
import logging
from typing import List

log = logging.getLogger(__name__)


def answer(question: str, history: List[str] = []) -> str:
    print("asking the model:", question)
    history.append(question)
    return "ok"

Run the three commands below in the project folder. ruff check reports problems; --fix repairs the ones that are safe to repair automatically; ruff format rewrites the layout of every file. --output-format concise prints one line per problem; without it ruff also shows the code around each problem and the suggested change.

Run
uv run ruff check --output-format concise
uv run ruff check --fix --output-format concise
uv run ruff format
You should see
src/support_bot/draft.py:1:1: I001 [*] Import block is un-sorted or un-formatted
src/support_bot/draft.py:1:8: F401 [*] `os` imported but unused
src/support_bot/draft.py:3:1: UP035 `typing.List` is deprecated, use `list` instead
src/support_bot/draft.py:8:36: UP006 [*] Use `list` instead of `List` for type annotation
src/support_bot/draft.py:8:48: B006 Do not use mutable data structures for argument defaults
src/support_bot/draft.py:9:5: T201 `print` found
Found 6 errors.
[*] 3 fixable with `--fix` (2 unsafe fixes available with `--fix --unsafe-fixes`).
src/support_bot/draft.py:6:48: B006 Do not use mutable data structures for argument defaults
src/support_bot/draft.py:7:5: T201 `print` found
Found 5 errors (3 fixed, 2 remaining).
2 unsafe fixes available with `--fix --unsafe-fixes`.
11 files left unchanged
.pre-commit-config.yaml
repos:
  - repo: https://github.com/astral-sh/ruff-pre-commit
    rev: v0.17.6
    hooks:
      - id: ruff-check
        args: [--fix]
      - id: ruff-format
  1. The hooks come from ruff's official pre-commit repository. pre-commit downloads them into its own cache, separate from your .venv.line 2
  2. The exact release to use. Keep it equal to the ruff version in uv.lock, so the hook and uv run ruff agree. uvx pre-commit autoupdate moves it to the newest release.line 3
  3. Runs ruff check --fix on the Python files you are committing.line 5
  4. Runs ruff format on them.line 7

How to read the output: file:line:column: CODE message. [*] marks problems --fix can repair. --fix sorted the imports, removed os and changed List to list (which also removed the typing import), so the line numbers moved up. The mutable default and the print stay: ruff only calls those fixes "unsafe" because they can change behavior, so you fix them yourself (lesson 4 shows how). Each code has a page in the ruff docs, and uv run ruff rule B006 explains one in your terminal. ruff format found nothing to change, because every file was already formatted.

pre-commit runs checks like these on every git commit, the way Husky with lint-staged does in a Node project. Install the hook once per clone; uvx runs a tool without adding it to the project, like npx:

uvx pre-commit install           # adds the hook to .git/hooks/pre-commit
uvx pre-commit run --all-files   # run every hook on every file now

The second command prints ruff check....Passed and ruff format....Passed (the first run also downloads the hooks, which takes a minute). From then on, a commit with a lint error stops, ruff fixes what it can, and you add the fixed files and commit again.

Tip Run uv run ruff check and uv run ruff format --check in CI as well. A teammate can skip pre-commit (git commit --no-verify), CI cannot be skipped. In VS Code, the Ruff extension formats on save and shows these problems while you type.

6The logging module: one logger per module

print writes a bare line with no level, no time, no module name and no request id. You cannot switch it off for one module, send it somewhere else or search it in a log tool. In a service, use logging from the standard library. It works like SLF4J with Logback in Java, or pino in Node.

The pieces: a logger is what your code calls (log.info(...)); it has a name and a level. A handler decides where lines go (the terminal, a file); a formatter decides what a line looks like. Loggers form a tree by their dotted names: support_bot.services is a child of support_bot, which is a child of the root logger. A record travels up the tree to the root's handlers, so you set up handlers once, at the root, and every logger uses them.

Each module gets its own logger with log = logging.getLogger(__name__), so its name is the module name, support_bot.services. The box writes those names out by hand, because code in this browser box is not a module of any package.

The levels, lowest first: DEBUG (details while developing), INFO (normal events: started, answered), WARNING (something odd, but handled), ERROR (an operation failed), CRITICAL (the app cannot go on). A logger drops records below its level.

Try it: edit and run
import logging
import sys

logging.basicConfig(
    stream=sys.stdout,                  # default is stderr; stdout keeps this demo's output together
    level=logging.INFO,                 # the root logger's level: INFO and above get through
    format="%(levelname)-7s %(name)s: %(message)s",
    force=True,                         # replace any earlier setup, so you can re-run this box
)

log = logging.getLogger("support_bot.services")   # in a real module: logging.getLogger(__name__)
lib = logging.getLogger("openai")                 # a library's logger works the same way
for name in ("support_bot", "openai"):
    logging.getLogger(name).setLevel(logging.NOTSET)   # NOTSET: no level of its own, ask the parent

log.debug("built %d messages", 2)                 # DEBUG is below INFO: dropped
log.info("answering a question of %d chars", 27)
log.warning("model %s is slow: %d ms", "llama3.2:3b", 4200)
lib.info("library chatter")

logging.getLogger("support_bot").setLevel(logging.DEBUG)   # our whole package, and only ours
logging.getLogger("openai").setLevel(logging.WARNING)      # quiet the library
log.debug("built %d messages", 2)                 # now it shows
lib.info("library chatter")                       # now it is dropped
Expected output
INFO    support_bot.services: answering a question of 27 chars
WARNING support_bot.services: model llama3.2:3b is slow: 4200 ms
INFO    openai: library chatter
DEBUG   support_bot.services: built 2 messages
Java (SLF4J)
private static final Logger log =
    LoggerFactory.getLogger(ChatService.class);

log.info("answering a question of {} chars", 27);
// levels per package in application.yml:
// logging.level.com.acme.supportbot: DEBUG
Node (pino)
import pino from "pino";
const log = pino({ name: "services", level: "info" });

log.info("answering a question of %d chars", 27);
log.debug("dropped: below info");

What the key lines do

  • logging.basicConfig(...) sets up the root logger: one handler (here writing to stdout), its format, and the root level. Call it once, in the program's entry point, never inside a library or service module. force=True replaces handlers left by an earlier call; you need it when something already configured logging, as when you run this box twice.

  • In the format, %(levelname)-7s is the level padded to 7 characters, %(name)s the logger name, %(message)s the message. A format can also use %(asctime)s (the time), %(module)s and %(lineno)d.

  • log.info("... %d chars", 27): pass values as arguments instead of building an f-string. logging fills them in only if the line is really written, and the message template stays the same on every call, which makes lines easy to group in a log tool.

  • A new logger has the level NOTSET: it has no level of its own and uses the nearest parent's, here the root's INFO. The for loop sets that explicitly, so the box starts the same way each time you run it.

  • setLevel on support_bot turns on DEBUG for every module under it; openai set to WARNING silences a chatty library. This is the Python form of logging.level.<package> in Spring.

Inside an except block, log.exception("answer failed") logs at ERROR with the full traceback, as lesson 7 showed. In tests, pytest's caplog fixture captures records so you can assert on them (see the pytest lesson).

Watch out Logging that "does nothing" is nearly always one of two things: basicConfig was never called, so only WARNING and above appear (in a bare format, on stderr), or something configured logging first and your later basicConfig was ignored. basicConfig does nothing if the root logger already has a handler, unless you pass force=True.

7Structured JSON logs with a request id

In production, logs are read by tools (Loki, CloudWatch, Datadog, ELK), not by people scrolling a terminal. Write each line as one JSON object and the tool can filter on any field: level = "ERROR", model = "llama3.2:3b", latency_ms > 3000.

The most useful field is a request id: one id per incoming request, on every line that request writes, in every module. When a user reports a bad answer, one search shows the whole story. Passing the id as an argument through every function would be awful. Python's answer is a ContextVar: a variable whose value belongs to the current request, because every thread and every async task sees its own value. It plays the role of SLF4J's MDC in Java, or AsyncLocalStorage in Node.

Three small pieces do the work: a filter on the handler copies the current id onto every record, a formatter turns the record into JSON, and the web middleware sets the id at the start of each request. Extra fields come from extra={...} in the logging call: logging stores each key as an attribute of the record.

Try it: edit and run
import json
import logging
import sys
from contextvars import ContextVar

request_id = ContextVar("request_id", default="-")   # "the current request", per task or thread

# attribute names every LogRecord has; anything else came from extra={...}
STANDARD = set(vars(logging.LogRecord("x", 0, "x", 0, "x", None, None))) | {"request_id"}


class RequestIdFilter(logging.Filter):
    def filter(self, record):
        record.request_id = request_id.get()          # stamp the current id on every record
        return True                                   # True = keep the record


class JsonFormatter(logging.Formatter):
    def format(self, record):
        out = {
            "level": record.levelname,
            "logger": record.name,
            "msg": record.getMessage(),               # the message with its %s values filled in
            "request_id": record.request_id,
        }
        out.update({k: v for k, v in vars(record).items() if k not in STANDARD})
        return json.dumps(out)


handler = logging.StreamHandler(sys.stdout)
handler.addFilter(RequestIdFilter())
handler.setFormatter(JsonFormatter())
logging.basicConfig(level=logging.INFO, handlers=[handler], force=True)
log = logging.getLogger("support_bot.api")


def handle(rid, path):                    # what the web middleware does for each request
    token = request_id.set(rid)
    try:
        log.info("request done", extra={"path": path, "status": 200})
    finally:
        request_id.reset(token)           # put the previous value back


handle("req-7f3a", "/ask")
handle("req-91bc", "/health")
log.info("outside any request")
Expected output
{"level": "INFO", "logger": "support_bot.api", "msg": "request done", "request_id": "req-7f3a", "path": "/ask", "status": 200}
{"level": "INFO", "logger": "support_bot.api", "msg": "request done", "request_id": "req-91bc", "path": "/health", "status": 200}
{"level": "INFO", "logger": "support_bot.api", "msg": "outside any request", "request_id": "-"}
src/support_bot/logging_setup.py (the real file)
"""Logging for the whole app: configured once, at startup."""

import json
import logging
import sys
from contextvars import ContextVar
from datetime import UTC, datetime

# The id of the request being handled right now (each request, thread or task sees its own value)
request_id: ContextVar[str] = ContextVar("request_id", default="-")

# Attributes every LogRecord has; anything else on a record came from extra={...}
_STANDARD = set(vars(logging.LogRecord("x", 0, "x", 0, "x", None, None)))
_STANDARD |= {"message", "request_id", "color_message"}  # uvicorn adds color_message


class RequestIdFilter(logging.Filter):
    def filter(self, record: logging.LogRecord) -> bool:
        record.request_id = request_id.get()
        return True  # keep the record; we only added a field


class JsonFormatter(logging.Formatter):
    def format(self, record: logging.LogRecord) -> str:
        out = {
            "ts": datetime.fromtimestamp(record.created, UTC).isoformat(timespec="milliseconds"),
            "level": record.levelname,
            "logger": record.name,
            "msg": record.getMessage(),
            "request_id": getattr(record, "request_id", "-"),
        }
        out.update({k: v for k, v in vars(record).items() if k not in _STANDARD})
        if record.exc_info:
            out["exc"] = self.formatException(record.exc_info)
        return json.dumps(out, default=str)


def configure_logging(level: str = "INFO", json_logs: bool = False) -> None:
    handler = logging.StreamHandler(sys.stdout)
    handler.addFilter(RequestIdFilter())
    if json_logs:
        handler.setFormatter(JsonFormatter())
    else:
        handler.setFormatter(
            logging.Formatter("%(asctime)s %(levelname)-7s %(name)s [%(request_id)s] %(message)s")
        )
    logging.basicConfig(level=logging.WARNING, handlers=[handler], force=True)  # libraries
    logging.getLogger("support_bot").setLevel(level)  # our own code
    logging.getLogger("uvicorn").setLevel(logging.INFO)  # keep the server's startup lines
src/support_bot/api.py (the real file)
"""HTTP layer: turns requests into service calls. Thin on purpose."""

import logging
import time
import uuid

import uvicorn
from fastapi import FastAPI, HTTPException, Request
from pydantic import BaseModel

from support_bot.clients import make_llm_client
from support_bot.config import Settings, load_settings
from support_bot.logging_setup import configure_logging, request_id
from support_bot.services import ChatService, LLMUnavailable

log = logging.getLogger(__name__)


class Ask(BaseModel):
    question: str


class Answer(BaseModel):
    answer: str


def create_app(settings: Settings | None = None, service: ChatService | None = None) -> FastAPI:
    settings = settings or load_settings()
    configure_logging(settings.log_level, settings.log_json)
    service = service or ChatService(make_llm_client(settings), settings.model)
    app = FastAPI(title="support-bot")

    @app.middleware("http")
    async def with_request_id(request: Request, call_next):
        rid = request.headers.get("x-request-id") or uuid.uuid4().hex[:12]
        token = request_id.set(rid)  # every log line in this request now carries rid
        start = time.perf_counter()
        try:
            response = await call_next(request)
            log.info(
                "request done",
                extra={
                    "path": request.url.path,
                    "status": response.status_code,
                    "ms": round((time.perf_counter() - start) * 1000),
                },
            )
        finally:
            request_id.reset(token)
        response.headers["x-request-id"] = rid
        return response

    @app.post("/ask")
    def ask(body: Ask) -> Answer:
        try:
            return Answer(answer=service.answer(body.question))
        except LLMUnavailable as e:
            raise HTTPException(status_code=503, detail=str(e)) from e

    log.info("app ready", extra={"app_env": settings.app_env, "model": settings.model})
    return app


def run() -> None:
    """Entry point for the `support-bot` command (see [project.scripts])."""
    uvicorn.run(create_app(), host="127.0.0.1", port=8000, log_config=None, access_log=False)

What the key lines do

  • vars(record) is the record's attributes as a dict. A dummy LogRecord gives the names every record has, so whatever else is on a real record came from extra=.

  • request_id.set(rid) returns a token, and request_id.reset(token) restores the value from before. The try/finally guarantees the reset, even when the request fails.

  • Outside any request the variable has its default, "-", so startup lines still format.

The real files, next to the box: logging_setup.py adds a UTC timestamp (ts) and the traceback when there is one, and configure_logging chooses JSON or readable text. It also sets the root to WARNING and only our support_bot package to the configured level, so library chatter stays out (uvicorn is kept at INFO for its startup lines). In api.py, the middleware takes the caller's X-Request-ID header or makes a new id, sets the ContextVar around the request, logs one request done line, and sends the id back in the response header, so the caller can quote it in a bug report.

Started with APP_ENV=prod and asked one question, the real service writes these lines (one JSON object per line):

{"ts": "2026-11-28T20:58:39.592+00:00", "level": "INFO", "logger": "support_bot.services", "msg": "llm call", "request_id": "req-7f3a", "model": "llama3.2:3b", "prompt_tokens": 30, "completion_tokens": 7, "latency_ms": 48, "finish_reason": "stop", "question_chars": 27}
{"ts": "2026-11-28T20:58:39.593+00:00", "level": "INFO", "logger": "support_bot.api", "msg": "request done", "request_id": "req-7f3a", "path": "/ask", "status": 200, "ms": 53}

The id was set in api.py and appears on the line written in services.py, without being passed as an argument. That works even though ask is a plain def endpoint, which FastAPI runs on a worker thread: the context is copied to that thread.

Watch out An extra key with the same name as a built-in record attribute (name, msg, args, message, module, filename, lineno and others) raises KeyError: "Attempt to overwrite 'name' in LogRecord". Use specific names such as model_name or user_id.

8Logging LLM calls without leaking secrets or PII

For every model call, log what you need to debug it and to pay for it: the model, prompt and completion tokens (cost), latency, and the finish reason (length means the answer was cut off). Those numbers answer "why is it slow", "why did the bill double" and "which model answered".

Do not log the API key, the full prompt or the full answer by default. Users paste emails, phone numbers, addresses and passwords into chat boxes, and a log line is copied to more systems, kept longer and read by more people than your database. Log the size of the question instead, and keep full transcripts, if you need them, in a separate store with access control and a retention limit.

A safety net helps too: scrub every finished line for things that look like keys and emails, in case a provider error message echoes them back. The box fakes the client with SimpleNamespace, an object you build from keyword arguments (like a JS object literal), shaped like the SDK's reply, and fakes the clock so the latency is the same on every run.

Try it: edit and run
import json
import logging
import re
import sys
from types import SimpleNamespace

KEY = re.compile(r"sk-[A-Za-z0-9_-]{8,}")
EMAIL = re.compile(r"[\w.+-]+@[\w-]+\.[\w.]+")


def scrub(text):
    return EMAIL.sub("<email>", KEY.sub("sk-***", text))


STANDARD = set(vars(logging.LogRecord("x", 0, "x", 0, "x", None, None)))


class JsonFormatter(logging.Formatter):
    def format(self, record):
        out = {"level": record.levelname, "msg": record.getMessage()}
        out.update({k: v for k, v in vars(record).items() if k not in STANDARD})
        return scrub(json.dumps(out))     # the safety net: nothing leaves unscrubbed


handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(JsonFormatter())
logging.basicConfig(level=logging.INFO, handlers=[handler], force=True)
log = logging.getLogger("support_bot.services")


def fake_create(model, messages):         # shaped like client.chat.completions.create(...)
    return SimpleNamespace(
        model=model,
        usage=SimpleNamespace(prompt_tokens=42, completion_tokens=18),
        choices=[SimpleNamespace(finish_reason="stop",
                                 message=SimpleNamespace(content="Use Settings > Security."))],
    )


ticks = iter([100.0, 100.84])             # a fake clock: the call "takes" 0.84 s


def answer(question, model="llama3.2:3b", clock=lambda: next(ticks)):
    start = clock()
    resp = fake_create(model, [{"role": "user", "content": question}])
    log.info("llm call", extra={
        "model": resp.model,
        "prompt_tokens": resp.usage.prompt_tokens,
        "completion_tokens": resp.usage.completion_tokens,
        "latency_ms": round((clock() - start) * 1000),
        "finish_reason": resp.choices[0].finish_reason,
        "question_chars": len(question),  # the size, never the text
    })
    return resp.choices[0].message.content


print(answer("I am asha@example.com, how do I reset my password?"))
log.warning("provider error: %s", "Incorrect API key sk-proj-4f9Xa81bQzL2 for asha@example.com")
Expected output
{"level": "INFO", "msg": "llm call", "model": "llama3.2:3b", "prompt_tokens": 42, "completion_tokens": 18, "latency_ms": 840, "finish_reason": "stop", "question_chars": 50}
Use Settings > Security.
{"level": "WARNING", "msg": "provider error: Incorrect API key sk-*** for <email>"}
src/support_bot/services.py (the real file)
"""Business logic: what the app does. No HTTP and no environment variables in here."""

import logging
import time
from collections.abc import Callable

import openai

from support_bot.prompts import build_messages

log = logging.getLogger(__name__)  # "support_bot.services"


class LLMUnavailable(Exception):
    """The model could not answer right now (timeout, server down)."""


class ChatService:
    def __init__(
        self, client: openai.OpenAI, model: str, clock: Callable[[], float] = time.perf_counter
    ) -> None:
        self.client = client
        self.model = model
        self.clock = clock

    def answer(self, question: str) -> str:
        start = self.clock()
        try:
            resp = self.client.chat.completions.create(
                model=self.model, messages=build_messages(question)
            )
        except openai.APITimeoutError as e:  # before APIConnectionError: it is a subclass
            log.warning("llm timeout", extra={"model": self.model, "latency_ms": self._ms(start)})
            raise LLMUnavailable("the model timed out") from e
        except openai.APIConnectionError as e:
            log.warning("llm unreachable", extra={"model": self.model, "error": type(e).__name__})
            raise LLMUnavailable("cannot reach the model") from e

        usage = resp.usage
        log.info(
            "llm call",
            extra={
                "model": resp.model,
                "prompt_tokens": usage.prompt_tokens if usage else None,
                "completion_tokens": usage.completion_tokens if usage else None,
                "latency_ms": self._ms(start),
                "finish_reason": resp.choices[0].finish_reason,
                "question_chars": len(question),  # the size, never the text
            },
        )
        return resp.choices[0].message.content or ""

    def _ms(self, start: float) -> int:
        return round((self.clock() - start) * 1000)

What the key lines do

  • KEY matches sk- followed by at least 8 letters, digits, _ or -: the shape of OpenAI-style keys. EMAIL is a rough email pattern. Real projects add patterns for their own secrets (bearer tokens, card numbers).

  • scrub(json.dumps(out)) scrubs the finished line, so it catches a secret in any field, including messages from libraries.

  • clock=lambda: next(ticks) replaces the real clock with a list of fixed times. The real ChatService takes clock=time.perf_counter as a default argument for the same reason: a test can pass a fake one.

In the real file the call goes through the OpenAI client, and the except blocks turn SDK errors into one LLMUnavailable error that api.py returns as HTTP 503. openai.APITimeoutError is caught before openai.APIConnectionError, because it is a subclass of it: the other way round, the timeout branch would never run. When the model server is down, the real service writes {"level": "WARNING", "logger": "support_bot.services", "msg": "llm unreachable", "error": "APIConnectionError", ...} and the caller gets 503 {"detail": "cannot reach the model"}.

These same fields are what tracing tools record for each model call (the tracing and cost lab adds them as OpenTelemetry attributes). Start with good logs; tracing builds on them.

Watch out Scrubbing is a safety net, not a plan. The real protection is not passing prompts, answers, headers or the settings object to the logger at all. log.info("settings: %s", vars(settings)) puts the API key in every log store you have, and repr=False (lesson 10) does not help with vars().

9Configuration per environment

The same code runs on your laptop, in CI and in production, with different settings: readable logs at DEBUG while you develop, quiet logs in tests, JSON at INFO in production, and a real API key only in production. Spring does this with profiles (application-prod.yml, SPRING_PROFILES_ACTIVE=prod), Node with NODE_ENV. Here one variable, APP_ENV, picks a small profile of defaults, and any environment variable you set still wins.

The box is the real config.py minus its .env loading (shown under the box), so it runs here. It takes the environment as a parameter, which lets you try each environment with a plain dict.

Try it: edit and run
from dataclasses import dataclass, field

PROFILES = {
    "dev": {"LOG_LEVEL": "DEBUG", "LOG_JSON": "false"},
    "test": {"LOG_LEVEL": "WARNING", "LOG_JSON": "false"},
    "prod": {"LOG_LEVEL": "INFO", "LOG_JSON": "true"},
}


@dataclass(frozen=True)
class Settings:
    app_env: str
    base_url: str
    model: str
    log_level: str
    log_json: bool
    api_key: str = field(repr=False)              # never printed


def load_settings(env):
    app_env = env.get("APP_ENV", "dev")
    if app_env not in PROFILES:
        raise ValueError(f"APP_ENV must be one of {sorted(PROFILES)}, got {app_env!r}")
    profile = PROFILES[app_env]

    def get(name, default):
        return env.get(name) or profile.get(name, default)  # env var, then profile, then default

    api_key = get("LLM_API_KEY", "ollama")
    if app_env == "prod" and api_key == "ollama":
        raise RuntimeError("LLM_API_KEY must be set when APP_ENV=prod")
    return Settings(
        app_env=app_env,
        base_url=get("LLM_BASE_URL", "http://localhost:11434/v1"),
        model=get("LLM_MODEL", "llama3.2:3b"),
        log_level=get("LOG_LEVEL", "INFO").upper(),
        log_json=get("LOG_JSON", "false").lower() == "true",
        api_key=api_key,
    )


print(load_settings({}))
print(load_settings({"APP_ENV": "prod", "LLM_API_KEY": "sk-real", "LLM_MODEL": "gpt-4.1-mini"}))
print(load_settings({"APP_ENV": "dev", "LOG_LEVEL": "info"}).log_level)

for bad in ({"APP_ENV": "prod"}, {"APP_ENV": "staging"}):
    try:
        load_settings(bad)
    except (RuntimeError, ValueError) as e:
        print(type(e).__name__, "-", e)
Expected output
Settings(app_env='dev', base_url='http://localhost:11434/v1', model='llama3.2:3b', log_level='DEBUG', log_json=False)
Settings(app_env='prod', base_url='http://localhost:11434/v1', model='gpt-4.1-mini', log_level='INFO', log_json=True)
INFO
RuntimeError - LLM_API_KEY must be set when APP_ENV=prod
ValueError - APP_ENV must be one of ['dev', 'prod', 'test'], got 'staging'

What the key lines do

  • get(name, default) is a small function inside load_settings: it looks in the environment first, then in the profile, then uses the default. or moves on when the value is missing or empty, so LOG_LEVEL= with nothing after it counts as unset.

  • The production check makes the app refuse to start without a real key, instead of failing on the first user request. Failing fast at startup is the same idea as Spring's @Validated configuration properties.

  • field(repr=False) keeps the key out of print(settings), which is why it is missing from the output.

The real config.py only adds .env support at the start of load_settings:

def load_settings(env: Mapping[str, str] | None = None) -> Settings:
    if env is None:
        load_dotenv()  # copies .env into os.environ; real environment variables win
        env = os.environ

create_app() in api.py then wires everything in order: load_settings(), configure_logging(settings.log_level, settings.log_json), then the client and the service. Each developer copies .env.example to .env; servers set real environment variables and have no .env file at all:

# .env.example (committed). Copy to .env for local development; never commit .env.
APP_ENV=dev
LLM_BASE_URL=http://localhost:11434/v1
LLM_MODEL=llama3.2:3b
LLM_API_KEY=ollama

Run it both ways and compare: uv run support-bot prints readable lines, APP_ENV=prod LLM_API_KEY=sk-test uv run support-bot prints JSON. (On Windows PowerShell, set the variables first with $env:APP_ENV="prod".)

Tip For bigger services, the pydantic-settings package gives you the same thing as a class: it reads environment variables and .env, converts and validates every type, and offers SecretStr for keys. Keep the rule from this section either way: read settings once, at startup, in one place.

Common mistakes

  • Using print in services. It has no level, time or request id and cannot be switched off. Use log = logging.getLogger(__name__), and let ruff's T20 rules enforce it.
  • Calling logging.basicConfig (or adding handlers) inside library or service modules. Configure logging once, in the entry point, and only get loggers everywhere else.
  • Naming your own module logging.py, json.py or openai.py. It hides the real module for the whole project, and the errors make no sense. Use names like logging_setup.py.
  • Two modules that import names from each other. Move the shared code into a lower module such as config.py, so imports only point one way.
  • Running a file inside a package as a script (python src/support_bot/services.py), then "fixing" the import error with sys.path. Install with uv sync and run with uv run, the entry point, or python -m support_bot.services.
  • Logging full prompts, answers, request headers or the settings object. Log model, tokens, latency and sizes; keep transcripts, if you need them, in a protected store.

Practice

Write the code, then press Check. Your work is saved in this browser.

1From file path to module name

Write module_name(path) that turns a file path inside src/ into the dotted module name Python gives it (the value of __name__ in that file). Drop the leading src/ and the .py ending, join the folders with dots, and remember that __init__.py is its package: src/support_bot/__init__.py is just support_bot.

Exercise
def module_name(path):
    return path.replace("/", ".")


print(module_name("src/support_bot/services.py"))
Hint

Remove the `src/` prefix and the `.py` suffix (`str.removeprefix` and `str.removesuffix`), split on `/`, drop a last part equal to `__init__`, then `".".join(parts)`.

2A JSON formatter

Finish JsonFormatter.format so that every log line is one JSON object with the keys level, logger and msg (the message with its %s values filled in), followed by every field passed with extra={...}. Use the STANDARD set to tell extra fields from the built-in ones.

Exercise
import json
import logging

STANDARD = set(vars(logging.LogRecord("x", 0, "x", 0, "x", None, None)))


class JsonFormatter(logging.Formatter):
    def format(self, record):
        return record.getMessage()   # plain text for now


# try it
import sys
h = logging.StreamHandler(sys.stdout)
h.setFormatter(JsonFormatter())
log = logging.getLogger("demo")
log.handlers = [h]
log.propagate = False
log.warning("slow call: %d ms", 4200, extra={"model": "llama3.2:3b"})
Hint

Build `out = {"level": record.levelname, "logger": record.name, "msg": record.getMessage()}`, then `out.update({k: v for k, v in vars(record).items() if k not in STANDARD})`, and `return json.dumps(out)`.

3A log line for an LLM call

Write llm_log_fields(model, usage, seconds, question) that returns the dict you would pass as extra= after a model call: model, prompt_tokens and completion_tokens (from the usage dict), total_tokens (their sum), latency_ms (seconds as whole milliseconds, rounded) and question_chars (the length of the question). It must never contain the question text itself.

Exercise
def llm_log_fields(model, usage, seconds, question):
    return {"model": model, "question": question}


print(llm_log_fields("llama3.2:3b", {"prompt_tokens": 42, "completion_tokens": 18}, 0.8437, "hi"))
Hint

`round(seconds * 1000)` gives whole milliseconds. Read the token counts with `usage["prompt_tokens"]` and `usage["completion_tokens"]`, and use `len(question)` instead of the question.

Interview questions

Q1How would you structure a Python AI service?

A src layout (src/<package>/) with one module per responsibility: config reads settings once, logging_setup configures logging, clients builds the LLM and database clients, prompts holds prompt text, services holds business logic, and api is a thin HTTP layer. Imports point one way (api → services → clients/prompts → config). pyproject.toml holds dependencies, dev groups, entry points and tool settings; tests live in tests/ and import the installed package.

Q2What causes a circular import in Python and how do you fix it?

Importing a module runs it, and the half-run module is already in sys.modules. If A imports B and B imports a name from A that A has not defined yet, you get "cannot import name ... from partially initialized module". Fix it by moving the shared code into a lower module both can import, by importing the module instead of the name and reading the attribute at call time, by putting type-only imports under if TYPE_CHECKING:, or, last, by importing inside the function.

Q3Absolute or relative imports?

Both resolve to the same module. Absolute imports (from support_bot.config import Settings) are clearer and work however the code is started, so they are the usual default. Relative imports (from .config import Settings) only work inside a package and fail with "no known parent package" when a file is run as a script; they make renaming the top package easier. Pick one style per project.

Q4Why logging.getLogger(__name__) instead of print?

A named logger per module gives every line a level, a time and its module, and the logger tree lets you change levels per package (DEBUG for your code, WARNING for a noisy library) and send output anywhere without touching the code. print has none of that and cannot be switched off. Configure handlers once at the entry point; modules only get loggers.

Q5How do you trace one request through your logs?

Give each request an id (take the caller's X-Request-ID header or generate one) in middleware, store it in a contextvars.ContextVar, and add it to every record with a logging filter. Write JSON lines so the log tool can filter on it, return the id in the response header, and pass it on to downstream calls. It is the Python version of SLF4J's MDC.

Q6What do you log for an LLM call, and what must you never log?

Log the model, prompt and completion tokens, latency, finish reason, a request id and sizes such as the question length. Never log API keys, request headers or settings objects, and do not log full prompts and answers by default because users put personal data in them; keep transcripts, if needed, in a protected store with retention limits. Add a scrubbing step as a safety net.