My Python for AI 101 · Chapter 13
The checklists for the next project
The cards, summed up in rules to put in place from the first day of a new Python project for AI. Each project left me its own checklist; I keep them as they are, in the order you put the rules in a new repo. Each rule points to its cards.
From Dev3Pack
- The contract first. The model’s output is a frozen DataclassA class declared by its typed fields; with frozen=True, the object can no longer be changed.See in the glossary →, read by a strict ParserThe code that reads the model's output and rejects it if it doesn't match the schema: format, exact fields, types, bounds.See in the glossary →: no missing field, no extra field (cards 8 and 21).
- One SeamThe single point of contact between the agent and any model: one method, and you switch providers without touching the agent.See in the glossary → per outside service. 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 →, a real client, a fake that records its calls; the 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 → receives the client as a parameter (card 43). - Settings in the environment. A safe default value, a closed list, no key ever printed (card 3).
- Money in integers. Raw unit plus the number of digits after the point;
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 →to read a text;Nonerefused (card 9). - Record the request before acting. A file written once, in
"x"mode, before the action exists (card 41). - Loop exits before the body. Answer, repetition, BudgetThe maximum number of calls an agent loop may make, checked before each call, never after.See in the glossary →, tool error, and always the same receipt (card 27).
- Allowed states in a table. Any missing pair is refused (card 28).
- One ExceptionAn error signal that interrupts the normal flow; you raise it, catch it (except) and turn it into a refusal.See in the glossary → per kind of RefusalAn explicit "I can't answer": no citation, zero confidence, human review. A state, not a crash.See in the glossary →. Turned into a readable sentence that names the field and both values;
raise … fromto keep the cause (cards 16 and 30). - Dangerous shapes as 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 →. Compiled once, tested both ways, applied outside quotations (card 18).
- Every URL goes through the guard, with a time limit. Scheme, host, resolved addresses; a
timeouton every call, a ThreadA parallel thread of execution; join(timeout) lets you wait for an answer for N seconds at most.See in the glossary → if the client has none (cards 48 and 49). - Secrets never leave. Masked in logs with a 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 →, refused at commit time by a scan, keys kept outside the repo (cards 10 and 53).
- Offline tests from day one. Network blocked in
conftest.py, one test per expected refusal; memory copied and kept separate per user (cards 47 and 59).
From AI Support Agent
- 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 → first. Every
@tooltool documents its Args/Returns as a contract: that is the text the model reads, not the function’s name (card 36). - Memory in 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 →, never in the loop. A
HookProviderclass that subscribes to events, not anifadded to the entrypoint (card 44). - Every outside connection under
with. Gateway, sandbox, file: closing guaranteed even on an exception (card 39). - The entrypoint is
async deffrom day one. Even if nothing inside is concurrent yet (card 50). - A local test path before deployment.
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 →to call the entrypoint without waiting for a full deployment (card 2). - Chained
.get()on all outside data. Memory, Gateway, 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 →: never direct bracket access on JSON you don’t control (card 7). - Every outside call has 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 →. A
try/exceptthat degrades the service rather than letting the exception rise to the customer (card 31). - Tool-call proofs are logged in structured form. Name, input, result: not only the model’s final answer (card 22).
- IDs have the right guarantee.
uuid.uuid4Generates a random 128-bit identifier, unique in practice; used for session IDs.See in the glossary →for what must never collide,random.choicesDraws items at random (with replacement) from a sequence; handy for readable demo IDs.See in the glossary →for what only has to be readable (card 11).
From NovaMart
- One entry point, several commands.
test,chat,deploy,servein the same file; imports computed from__file__The path of the Python file being run.See in the glossary →(card 1). - Settings in the environment. A single
config.py, no resource or model ID hard-coded, no network call at import (card 4). - Clients created once. At module level, with the region from the config; one logger per module (card 5).
- Every tool has its contract. Annotated types, a docstring that says when to use it, every argument with an example, the error case described (card 37).
- Tools kept in their builder. With their business constants; a builder returns a single agent (cards 29 and 42).
- Data converted at the boundary.
default=strforDecimal, UTC dates, days computed by the code (card 14). - Shared state is versioned. A conditional write on
version, a bounded retry with Back-offA wait that grows longer with each new attempt after a failure.See in the glossary → (card 13). - The code checks again before writing. Every rule with a real effect checked in the tool, an idempotent write (card 33).
- Errors stay readable. In a tool, return the error as data; in the plumbing, a named exception with the fix (card 32).
- Critical rules in a hook. The prompt announces, the code guarantees; the session’s identity in
agent.stateA Strands agent's key-value storage, invisible to the model, readable by its tools.See in the glossary →, history cleared on every request (cards 42 and 45). - Parallelize the independent, chain the dependent.
ThreadPoolExecutorA pool of threads that runs tasks in parallel, suited to waiting on the network.See in the glossary →+as_completedWalks through futures in the order in which they finish.See in the glossary →+ atryper future; sequential as soon as a step reads the previous one; a lock on every “create if missing” (cards 51 and 52). - TraceThe log of a run: every step (search, model call, tool call, decision) with its arguments and result.See in the glossary → without clutter. A DecoratorA function that receives another one and returns an enriched version of it, written @name above the def.See in the glossary → with
functools.wrapsCopies the original function's name and docstring onto its wrapper.See in the glossary →, a 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 → for everything that opens and closes, per-agent metrics inside atry(cards 38, 40 and 58). - Validate before deploying, authenticate at the entrance. Every variable checked at once; the identity read from a token validated on the server side (cards 54 and 56).
- Measure before tuning. A fixed setA collection with no duplicates; & gives the shared elements, <= checks that one set is contained in another.See in the glossary → of cases, an “expected versus obtained” loop, the reports kept in
evidence/(card 60).