My Python for AI 101 · Chapter 01
How to read it, and the map
This book collects the Python mechanisms that run my AgentA program that uses a language model to decide what to do (search, call a tool, answer, refuse), in a loop, with stopping rules.See in the glossary →, one per card, with the input, the output and the file where you can read them again. The 68 cards come from four projects: the Dev3Pack bootcamp, two projects of the AWS Nanodegree (AI Support Agent and NovaMart), and my build DRILLS.ai. They are sorted by family, from the layout of the project to the tests. Every card says which project it comes from, and every chapter ends with “In the field”: the chapters of my courses and my projects where these mechanisms are at work.
The pure-Python outputs were replayed on October 22 against the code in the repos. For NovaMart, the ones that go through AWS come from the project’s evidence (evidence/), as the lab account has since been reset. The DRILLS.ai cards (61 to 68) were replayed on October 30 on commit 8f45461, with no network and no model call.
How to read a card
Every card follows the same order: in one sentence, why it matters for an agent, an analogy, the mechanism (the useful piece of code), the real input and output, where to read it again, and what to reuse. Like BAA 101, a card holds for anyone; my own path, step by step, is told in the Dev3Pack and AWS Scholars books.
The code read, and who wrote it
Dev3Pack AI Engineering Bootcamp
| Code read | Who wrote it |
|---|---|
The course package, src/bootcamp_agent/ |
The course. I call it from every notebook. |
My 15 submitted notebooks, submissions/Mialy333/chNN/ |
Me. Since October 2, some TODO(you) cells are written by the assistant (Claude), and the chapter’s log says so. |
The Gecko capstone, my-gecko-buyer/ |
The course for the structure and the examples; the assistant (Claude), at my request, for the TODOs. |
The final assignment, grounded-research-agent/agent.py |
The assistant (Claude), at my request, from the course template. |
“ch06 · cell 13” points to cell 13 of my ch06 notebook. Week 0 (w01 to w12) is not covered: it was not submitted.
AI Support Agent
| Code read | Who wrote it |
|---|---|
starter/: main.py, lambda/, setup_permissions.py |
The skeleton, the DocstringThe text between triple quotes under a def; an agent framework or an MCP server turns it into the tool description the model reads.See in the glossary → and the CLI section come from Udacity. The TODOs (tools, memory HookCode triggered at a precise moment in the agent's life, before or after a call, to enforce a rule the prompt doesn't guarantee.See in the glossary →, agent, TraceThe log of a run: every step (search, model call, tool call, decision) with its arguments and result.See in the glossary → loop) are mine. |
The trace logging in main.py |
Added during the revision the reviewer asked for. |
NovaMart Multi-Agent Support
| Code read | Who wrote it |
|---|---|
The starter’s protected files: config.py, src/agent_observability.py, src/agent_utils.py, src/agentcore_cli.py, src/bedrock_kb_retrieval.py, tests/test_agent.py, infrastructure/ |
Udacity. I read them, I don’t change them. |
src/agent_orchestrator.py |
The stubs and helpers come from the starter. The TODOs and the extras are mine, from the runbook’s excerpts, with the assistant at my request. |
The step 7 extras: scripts/, frontend_proxy/ |
Me, with the assistant, at my request. |
DRILLS.ai
| Code read | Who wrote it |
|---|---|
src/ai_generator/, src/integrations/, api/, tests/ |
Me, with the help of ChatGPT and Codex for design, code and iterations. A project base existed before the hackathon pivot. |
The links
Every path under “Where to read it again” opens the file on GitHub, on the exact line for Python code. The links are pinned to a commit, so they stay right even if the code changes later: 8c4726f for the Dev3Pack course, 77d2a92 for my-gecko-buyer, dc60e44 for grounded-research-agent, 1f7c614 for AI Support Agent, fef122e for NovaMart, 8f45461 for DRILLS.ai. For a notebook, the link opens the submitted file: GitHub cannot point to a cell, so you find it by the function name given.
Where each mechanism sits
A request comes in, an answer or a RefusalAn explicit "I can't answer": no citation, zero confidence, human review. A state, not a crash.See in the glossary → comes out; the numbers point to the cards.
In the Dev3Pack bootcamp
- A question comes in; a Regex (regular expression)A pattern that describes a shape of text rather than an exact word; used by injection guards, redaction and to read a header.See in the glossary → guard (card 18) stops hidden orders.
- RetrievalThe step that searches the corpus for passages useful to a question, before calling the model. Nothing found: refuse without a call.See in the glossary → looks for passages: tokens, setA collection with no duplicates; & gives the shared elements, <= checks that one set is contained in another.See in the glossary →, IDFInverse Document Frequency: a word found in few passages weighs more in the retrieval score.See in the glossary → (card 20). Nothing found: refusal, with no call to the model.
- The model is called through a
ProtocolIn Python, a contract defined by methods: a class meets it as soon as it has those methods, without inheritance.See in the glossary →(card 43), with a time limit (card 49). - Its output goes through strict JSON (card 21) and becomes a DataclassA class declared by its typed fields; with frozen=True, the object can no longer be changed.See in the glossary → (card 8).
- The checks run: ExceptionAn error signal that interrupts the normal flow; you raise it, catch it (except) and turn it into a refusal.See in the glossary → (card 30), exact numbers (card 9). One wrong field: refusal.
- Answer, action or refusal: everything ends up in the trace and the receipt, Dictionary (dict)A collection of values stored under keys; the shape of the trace, the receipts and the JSON answers.See in the glossary → (card 6) written to files (card 41).
In AI Support Agent
- A request comes in through the asynchronous entrypoint (card 50).
- The memory hook injects the customer’s context (card 44).
- The agent picks among its
@tooltools (card 36). - The MCPModel Context Protocol: a standard for exposing tools and data sources to any agent. An MCP tool is discovered by its name, description and schema.See in the glossary → Gateway’s tools open inside a
withblock (card 39); behind it, the Lambda answers with its single contract (card 34). - The calculation goes through the Code InterpreterA service that runs generated code in an isolated environment, to get an exact calculation rather than the model's estimate.See in the glossary →, with a FallbackA back-up code path run when the main call fails, to return a partial result rather than an error.See in the glossary → if the call fails (card 31).
- The tool-call blocks are read for the trace (card 22), then the exchange is saved to memory with
reversedandbreak(card 26); the answer goes out.
In NovaMart
- The request comes from the browser or the terminal, over HTTP with a Cognito token, into
lambda_handlerThe entry point of an AWS Lambda function: it receives (event, context) and returns a dict.See in the glossary →or the Runtime’s entrypoint (card 56). - The configuration is loaded on demand (card 4) and the Strands OrchestratorIn a multi-agent system, the agent that never answers itself: it routes the work to specialist agents.See in the glossary → takes over (card 42).
- Before the invocation, a hook reads the session header with a regex (card 45).
- The
route_to_*tools (cards 37 and 29) read and write the WorkflowState in DynamoDB, under a condition (cards 12 and 13). - The Inventory and Refund workers check the facts (cards 12, 14, 32 and 33); the PolicyAgent queries the three Knowledge baseA set of documents, split and indexed, that the agent queries before answering. An unsynced base returns nothing, with no error.See in the glossary → in parallel (card 51), each search in an X-Ray segment (card 40).
- After the invocation, a hook guarantees rule 6: the CommunicationAgent answers last (card 45). Out comes the answer or the refusal.
- All along, every tool is traced by a DecoratorA function that receives another one and returns an enriched version of it, written @name above the def.See in the glossary → (card 38) and its metrics go to CloudWatch through the logs (card 58).
In DRILLS.ai
- The CV and the posting come in through a strict request, with typed ConsentThe person's explicit agreement before their data goes to a service. Without it, the request is rejected before any call.See in the glossary → (card 61); the MiddlewareA function that wraps every request of a web server, to apply the same rule to every response.See in the glossary → marks every private response (card 64).
- A two-slot SemaphoreA counter that limits how many operations run at the same time. When it is full, the next request is refused or waits.See in the glossary → and a bounded wait frame the operation (card 65).
- A PDF is read in a bounded subprocessThe Python module that launches another program (git, a CLI) and gets back its exit code and output.See in the glossary → (card 67); postings arrive from five sources in parallel (card 66), filtered by regex (card 18).
- The texts are split into windows (card 63), and the model picks IDs in a SchemaThe required shape of a piece of data: its fields, their types, their bounds.See in the glossary → built at runtime (card 62).
- Rejected evidence becomes an error code, never CV text (card 30); out come the assessment or the refusal.
- In the tests, the model is replaced by an
AsyncMockA fake for an async function, in tests: it returns a planned answer and counts its calls.See in the glossary →(card 68).
The map of the 68 cards
Cards 61 to 68 come from DRILLS.ai. They sit in their family, at the end of each chapter, so the other cards keep their numbers.
Chapter 2 · Organizing the project
| # | Notion | The problem it prevents | Project |
|---|---|---|---|
| 1 | One file, several commands | Test code that differs from the deployed code | NovaMart |
| 2 | A local CLI with argparseThe Python module that turns command-line arguments into Python objects.See in the glossary → + asyncio.runStarts and runs an asynchronous function (coroutine) from synchronous code.See in the glossary → |
No way to test an asyncThe keyword that declares a coroutine: a function that can be suspended and resumed (await), to handle several requests without blocking the program.See in the glossary → function locally | AI Support Agent |
| 3 | Configuration and environment | A key in the code | Dev3Pack |
| 4 | Lazy configuration | A hard-coded resource or model ID | NovaMart |
| 5 | Clients and logger at module level | A connection recreated on every Tool callThe model's request to run a tool with specific arguments. That's what you read in the trace, not the final answer.See in the glossary → | NovaMart |
| # | Notion | The problem it prevents | Project |
|---|---|---|---|
| 6 | The dictionary, a light contract | A receipt or an answer with a missing box | Dev3Pack |
| 7 | Chaining .get() |
A crash on an incomplete memory or API answer | AI Support Agent |
| 8 | The frozen dataclass | An intent changed along the way | Dev3Pack |
| 9 | Exact numbers | A rounding error that lets a price through | Dev3Pack |
| 10 | Bytes, base64A way to write bytes as plain text so they can travel; the content does not change.See in the glossary → and Hash (fingerprint)A short, fixed summary of a text (SHA-256): the same text always gives the same fingerprint, without revealing it.See in the glossary → | Signing other bytes than the ones checked | Dev3Pack |
| 11 | Identifiers: random.choicesDraws items at random (with replacement) from a sequence; handy for readable demo IDs.See in the glossary → vs uuid.uuid4Generates a random 128-bit identifier, unique in practice; used for session IDs.See in the glossary → |
A session ID that collides | AI Support Agent |
| 61 | The strict PydanticA Python library that validates data against typed classes; with extra="forbid", an unexpected field is rejected.See in the glossary → model and typed consent | Data sent without agreement, an extra field accepted | DRILLS.ai |
| 62 | A schema built at runtime: create_modelThe Pydantic function that builds a model class at runtime, for example to allow only the IDs of one request.See in the glossary → and LiteralA Python type that only accepts exact values: Literal["fr", "en"], or Literal[True] for a mandatory agreement.See in the glossary → |
An invented evidence ID | DRILLS.ai |
| # | Notion | The problem it prevents | Project |
|---|---|---|---|
| 12 | Reading DynamoDB: composite key, query, sorting |
A KeyError on a missing order |
NovaMart |
| 13 | Writing under a condition: Optimistic lockingEvery write carries the version read just before it; if the version changed in the meantime, the write is refused. Two agents can't silently overwrite each other.See in the glossary → | Two agents overwriting each other | NovaMart |
| 14 | Types at the boundaries: DecimalThe Python type that computes in exact decimal, without the rounding errors of float. DynamoDB returns them, and JSON cannot write them as they are.See in the glossary →, dates, streams |
A tool that crashes while serializing its answer | NovaMart |
| 15 | PaginatorA boto3 object that chains the pages of an API automatically.See in the glossary → and bounded wait | A truncated list, an endless wait | NovaMart |
| # | Notion | The problem it prevents | Project |
|---|---|---|---|
| 16 | f-stringA string prefixed with f where {value} is replaced; an optional format follows the colon (!r, :.2f, :08d).See in the glossary →, and the refusal that names both values | A refusal that says neither what nor why | Dev3Pack |
| 17 | f-strings and format specifiers | Badly sorted keys, a silent error message | NovaMart |
| 18 | Regular expressions | A hidden order obeyed, a secret in a log | Dev3Pack |
| 19 | Validating and unpacking with a regex | An ARNAmazon Resource Name: the unique identifier of an AWS resource, shaped arn:partition:service:region:account:resource.See in the glossary → split badly by hand | AI Support Agent |
| 20 | From words to sets: tokens, set, IDF |
An answer with no source | Dev3Pack |
| 21 | Strict JSON | A model output half accepted | Dev3Pack |
| 22 | Defensive parsing of toolUse / toolResult blocks |
A tool-call proof you can’t show the reviewer | AI Support Agent |
| 63 | Overlapping windows over a text | A sentence cut in two between two excerpts | DRILLS.ai |
| # | Notion | The problem it prevents | Project |
|---|---|---|---|
| 23 | ComprehensionOne line that builds a list, a set or a dict from another collection, with an optional filter.See in the glossary → and iteration tools | An invented CitationThe ID of the document that supports an answer. A correct citation doesn't prove the sentence comes from the document.See in the glossary → that slips through | Dev3Pack |
| 24 | A list comprehension with a filter | A manual loop to filter orders | AI Support Agent |
| 25 | Comprehensions and ** unpacking |
Two GuardrailA filter applied to the model's inputs and outputs: harmful content, personal data, denied topics. It's tested like code, false positives included.See in the glossary → configurations that drift apart | NovaMart |
| 26 | reversed() + early exit |
Scanning the whole history for the last pair of messages | AI Support Agent |
| 27 | The bounded loop: exits first | A loop that keeps running and spending | Dev3Pack |
| 28 | The Transition tableThe list of allowed (state, event) pairs and the state each one leads to. Any missing pair is refused, and the state doesn't move.See in the glossary → | Answering before searching | Dev3Pack |
| 29 | ClosureAn inner function that keeps access to the variables of the function that created it.See in the glossary →: tools packed with their rules | Business constants in global variables | NovaMart |
Chapter 7 · Errors and guardrails
| # | Notion | The problem it prevents | Project |
|---|---|---|---|
| 30 | Exceptions: raise, catch, turn into a refusal | A traceback instead of a refusal | Dev3Pack |
| 31 | try/except with a degraded fallback |
A conversation turn that crashes entirely | AI Support Agent |
| 32 | boto3The AWS SDK for Python. Two interfaces: client (the API's raw format) or resource (objects with Python types).See in the glossary → exceptions | A traceback instead of an answer | NovaMart |
| 33 | The guardrail in the code, and IdempotenceRunning an action again doesn't change the result: a return already started isn't started twice, an existing resource is reused.See in the glossary → | A return granted outside the window, or twice | NovaMart |
| 34 | A single response contract | A Lambda that breaks the API Gateway contract on a forgotten branch | AI Support Agent |
| 35 | State with no side effects | Data leaking from one Lambda invocation to the next | AI Support Agent |
Chapter 8 · Decorators, context and files
| # | Notion | The problem it prevents | Project |
|---|---|---|---|
| 36 | The @tool decorator |
A tool the model doesn’t know how to call properly | AI Support Agent |
| 37 | Types and docstring: the tool’s contract | A tool the model calls wrongly | NovaMart |
| 38 | A home-made decorator, with functools.wrapsCopies the original function's name and docstring onto its wrapper.See in the glossary → |
A traced tool that loses its name and docstring | NovaMart |
| 39 | The with Context managerAn object used with with, which runs code on entering and leaving a block; the resource is closed even if an error occurs.See in the glossary → |
A Gateway connection left open after an error | AI Support Agent |
| 40 | The context manager: open, and always close | A trace segment never closed | NovaMart |
| 41 | Files with pathlibThe Python module that handles file paths as objects (Path, /, glob, read_text).See in the glossary → |
Evidence overwritten | Dev3Pack |
| 64 | Middleware: one rule for every response | A CV kept in a cache | DRILLS.ai |
Chapter 9 · Agents and their interfaces
| # | Notion | The problem it prevents | Project |
|---|---|---|---|
| 42 | The agent is a Python object | A customer who inherits another’s context | NovaMart |
| 43 | Protocol and Dependency injectionPassing a function the object it needs (model, network) instead of creating it inside, so it can be swapped for a fake.See in the glossary → |
Tests that depend on the network | Dev3Pack |
| 44 | HookProvider / HookRegistry, classes as plugins |
Memory logic mixed into the agent’s code | AI Support Agent |
| 45 | Hooks: a rule enforced by the code | An “always” rule the model forgets | NovaMart |
| 46 | Inheriting an interface: SessionRepositoryThe Strands interface to implement to store sessions wherever you want.See in the glossary → |
Session memoryThe history of one conversation, which disappears when it ends.See in the glossary → lost on restart | NovaMart |
| 47 | Copies and per-user memory | Memory leaking from one user to another | Dev3Pack |
Chapter 10 · Network, time and concurrency
| # | Notion | The problem it prevents | Project |
|---|---|---|---|
| 48 | Careful networking: urlsplit, ipaddressThe Python module that reads an IP address and tells whether it is public, private or local.See in the glossary →, urllib |
A tool turned inward (SSRFServer-Side Request Forgery: getting a tool that fetches URLs to call an internal or private address on the attacker's behalf.See in the glossary →) | Dev3Pack |
| 49 | Time, TimeoutA maximum waiting time. Past it, you abandon the call and return a readable refusal, instead of waiting forever.See in the glossary → and ThreadA parallel thread of execution; join(timeout) lets you wait for an answer for N seconds at most.See in the glossary → | An endless wait | Dev3Pack |
| 50 | The asynchronous @app.entrypointThe decorator that makes a function the request handler of the AgentCore Runtime.See in the glossary → |
A runtime that blocks on one request | AI Support Agent |
| 51 | Parallel fan-out: ThreadPoolExecutorA pool of threads that runs tasks in parallel, suited to waiting on the network.See in the glossary → and as_completedWalks through futures in the order in which they finish.See in the glossary → |
Three slow searches one after the other | NovaMart |
| 52 | Lock, per-thread context, Lazy singletonAn object created only once, the first time it is needed, then reused.See in the glossary → | A resource created twice by two threads | NovaMart |
| 65 | The semaphore and the bounded wait | Requests piling up, an endless wait | DRILLS.ai |
| 66 | Async fan-out: asyncio.gatherStarts several coroutines at the same time and returns their results in the order they were given.See in the glossary → |
A source that is down taken for “no postings” | DRILLS.ai |
Chapter 11 · Deploying and tooling
| # | Notion | The problem it prevents | Project |
|---|---|---|---|
| 53 | subprocess: calling another program |
A committed key | Dev3Pack |
| 54 | subprocess and validation before deployment |
A 15-minute deployment that leaves incomplete | NovaMart |
| 55 | Reading code without running it: the astThe Python module that turns source code into a syntax tree you can analyse without running the code.See in the glossary → module |
Running an untrusted file to read its settings | AI Support Agent |
| 56 | HTTP entry points: the Runtime’s entrypoint and Lambda | A customer pretending to be another | NovaMart |
| 57 | The MCP server: a function becomes a tool | A check reserved for a single agent | Dev3Pack |
| 58 | Metrics through the logs (EMFEmbedded Metric Format: a JSON log from which CloudWatch extracts metrics automatically.See in the glossary →) | TelemetryThe usage statistics a piece of software sends to its publisher. Some tools send them by default; you can turn them off.See in the glossary → that needs a missing permission | NovaMart |
| 67 | The bounded subprocess: time, memory, CPU | A booby-trapped PDF that blocks the server | DRILLS.ai |
Chapter 12 · Testing and evaluating
| # | Notion | The problem it prevents | Project |
|---|---|---|---|
| 59 | Tests with pytest | A grade that depends on the wifi | Dev3Pack |
| 60 | Testing the structure, evaluating the behaviour | A guardrail tuned by feel | NovaMart |
| 68 | AsyncMock: replacing an async call |
Tests that cost API credit | DRILLS.ai |