Build an AI ad-copy reviewer in Python
A small Python tool that checks ad headlines against your rules, saves a JSON report, and asks a language model to rewrite the worst one.
The checks in front of a streaming chat service: an API key, a token bucket for each user, and a daily token budget, in plain Python you can test.
A chat service that calls a language model needs three gates before it answers: who is asking, how fast, and how much they may spend. This tutorial writes those gates as ordinary Python, so each one can be tested without a web server. The lesson wires them into a FastAPI service that streams its reply.
Python classes and dictionaries, and what an HTTP status code is. It uses only the standard library, so it runs anywhere with Python 3.
The bucket holds up to capacity tokens and gains rate tokens a second. Each request takes one. allow works out how much was refilled since the last request, so nothing runs in the background. retry_after says how long until one whole token is back, which becomes the Retry-After header.
import math class TokenBucket: def __init__(self, capacity, rate, now): self.capacity, self.rate = capacity, rate self.tokens, self.updated = capacity, now def allow(self, now): refill = (now - self.updated) * self.rate self.tokens = min(self.capacity, self.tokens + refill) self.updated = now if self.tokens >= 1: self.tokens -= 1 return True return False def retry_after(self): return max(0.0, (1 - self.tokens) / self.rate)
Three checks, in order. An unknown key is 401. A user who is out of tokens is 429 with the wait in seconds. A user whose day's budget would be passed by this request's prompt and reply tokens is 429 with an hour's wait. Only a request that passes all three is counted against the budget.
def authorize(state, key, now, prompt_tokens, max_tokens): user = state["keys"].get(key) if user is None: return 401, {} bucket = state["buckets"].setdefault( user, TokenBucket(state["burst"], state["rate"], now) ) if not bucket.allow(now): return 429, {"Retry-After": str(max(1, math.ceil(bucket.retry_after())))} cost = prompt_tokens + max_tokens if state["used"].get(user, 0) + cost > state["limit"]: return 429, {"Retry-After": "3600"} state["used"][user] = state["used"].get(user, 0) + cost return 200, {}
In the lesson you write this from a starter, in your browser with nothing to install, and checks tell you what's wrong as you go. A free account opens it and all 575 lessons.
The first call has a known key and a fresh bucket, so it is allowed. The second has a key nobody holds, so it is refused before any bucket is made.
state = {"keys": {"k1": "ana"}, "buckets": {}, "used": {}, "limit": 40,
"burst": 2, "rate": 1.0}
print(authorize(state, "k1", 0.0, 7, 6), authorize(state, "nope", 0.0, 7, 6))(200, {}) (401, {})In the lesson these functions sit behind FastAPI dependencies, a middleware that stamps each reply with a request id, and a route that streams the model's reply as server-sent events.
authorize three times in a row at the same moment, and watch the third answer 429 with a Retry-After.limit of 10 and a request that costs 13.import math class TokenBucket: def __init__(self, capacity, rate, now): self.capacity, self.rate = capacity, rate self.tokens, self.updated = capacity, now def allow(self, now): refill = (now - self.updated) * self.rate self.tokens = min(self.capacity, self.tokens + refill) self.updated = now if self.tokens >= 1: self.tokens -= 1 return True return False def retry_after(self): return max(0.0, (1 - self.tokens) / self.rate) def authorize(state, key, now, prompt_tokens, max_tokens): user = state["keys"].get(key) if user is None: return 401, {} bucket = state["buckets"].setdefault( user, TokenBucket(state["burst"], state["rate"], now) ) if not bucket.allow(now): return 429, {"Retry-After": str(max(1, math.ceil(bucket.retry_after())))} cost = prompt_tokens + max_tokens if state["used"].get(user, 0) + cost > state["limit"]: return 429, {"Retry-After": "3600"} state["used"][user] = state["used"].get(user, 0) + cost return 200, {} state = {"keys": {"k1": "ana"}, "buckets": {}, "used": {}, "limit": 40, "burst": 2, "rate": 1.0} print(authorize(state, "k1", 0.0, 7, 6), authorize(state, "nope", 0.0, 7, 6))
In the lesson you write this from a starter, in your browser with nothing to install, and checks tell you what's wrong as you go. A free account opens it and all 575 lessons.
This is one stage of the AI engineer roadmap: the bigger picture, in order.
A small Python tool that checks ad headlines against your rules, saves a JSON report, and asks a language model to rewrite the worst one.
Build a research agent with tools, an agent loop, citations you can check and an eval, in plain Python with no framework.
Write the loss that language models train on, from scratch with NumPy, along with KL divergence, perplexity and the gradient.
A complete machine learning project with scikit-learn: baselines, a fair model comparison, one honest test, and a decision about who to contact.
Standardize from the training rows only, train a small network with a validation score after every epoch, and compare it fairly with logistic regression.
Write a tiny GPT in PyTorch, train it on a product catalog, and watch it write new descriptions. The whole program is about 70 lines.
Fine-tune a small chat model, test it on held-back products, and use release gates to catch a candidate that looks better but isn't.
A complete to-do tool with subcommands, a SQLite database, clear errors and exit codes, using only the standard library.
Authentication, validation, pagination, idempotency and clean errors, in a working API built with the standard library so you can see how each one works.
A working Model Context Protocol server with tools, resources and prompts, written without an SDK so you can see exactly what goes over the wire.
An agent that reads and edits a project, runs its tests and stops when they pass, with the safety checks that keep it inside the project.
API keys, rate limits, validation, caching, model fallbacks, structured logs and an eval, around a service that classifies support tickets.
A two-layer classifier for trail signs written straight from the formulas: forward pass, cross-entropy, a backward pass, training, an honest test score with its error bar, and next steps in PyTorch.
The core of a typed, tested training package: a config that rejects unknown settings, mini-batches as a generator, a seeded training loop and an evaluation function.
The small functions that decide whether a model ships and stays shipped: a registry gate by slice, a hybrid serving rule, a drift alert, a retrain rule and a model-card check.
Never trained an AI? Teach a small one to write, right in your browser. It takes about 20 seconds and needs no account. Teach it to write