Validating LLM JSON with Pydantic: repair fixed 26 of 51 bad outputs, 2 silently wrong
Strict Pydantic accepted 2 of 51 malformed LLM outputs; a 40-line repair step plus lax mode recovered 26 and returned 2 wrong values without an error.
BM25 from scratch in Python: 27 lines, score-identical to rank_bm25 and up to 1.7x faster
A from-scratch BM25 matched rank_bm25 on 500 queries (max score difference 1.8e-13) and ran 1.7x faster on short queries. The idf formula changed 14 top-1 results.
Build an MCP server in Python for your docs: stdio and HTTP, with measured payload sizes
A working MCP docs server (mcp 2.3.0, 2 tools) over stdio and HTTP: a k=5 search returns 1,818 bytes of text, but the full result is 2.19x larger.
FastAPI headers: read, validate and set them (and the underscore trap)
Read request headers in FastAPI with Header(), handle repeated headers, group them in a Pydantic model, require API keys and set response headers. All tested.
OpenAI Responses API vs Chat Completions: what changes in your code
Side-by-side Python for the Responses API and Chat Completions: inputs, output_text, state with previous_response_id, tools, structured output and streaming.
FastAPI: API design & OpenAPI
Code can be refactored in an afternoon. A public API cannot: other teams, mobile apps already in users' pockets, and partners' scripts depend on every field name…
FastAPI: async def vs def: the concurrency model
FastAPI runs async def endpoints on the event loop , one thread juggling every request, and plain def endpoints in a thread pool . Both can be fast.
FastAPI: Authentication: passwords, JWTs & API keys
Authentication answers 'who is this?'; authorization (part 18) answers 'may they do this?'.
FastAPI: Background work & task queues
Some work should not make the client wait: sending an email, calling a webhook, generating a report.
FastAPI: Request bodies & Pydantic v2
A request body is declared as a Pydantic model . FastAPI reads the JSON, Pydantic validates it against the model, and your function receives a typed object, or the…
FastAPI: Pagination, concurrency & migrations
Four patterns show up in every serious API. Cursor pagination stays fast and consistent on huge tables. Safe filtering and sorting never puts user input into SQL.
FastAPI: Dependency injection in depth
A dependency is a function (or any callable) that FastAPI runs before your endpoint and whose result it passes in: the current user, a database session, pagination…
FastAPI: Deployment & graceful shutdown
A deployment replaces running processes that are in the middle of serving customers.
FastAPI: Errors & a consistent error contract
Out of the box, FastAPI answers failures in three different shapes : {'detail': '...'} for HTTPException , {'detail': [...]} for validation errors, and a plain-text…
FastAPI: Lifespan, state & shared resources
Some things should exist exactly once per process: the database engine and its connection pool, an HTTP client with keep-alive connections, a loaded ML model, a…
FastAPI: Middleware
Middleware wraps the whole application: it sees every request on the way in and every response on the way out, including 404s and errors.
FastAPI: Logging, metrics & tracing
At 2 a.m. the alert says 'orders API error rate 8%'. Can you tell which endpoint, since when, for which customers, and why? That depends entirely on what you built…
FastAPI: Path, query & header parameters
Every value in a URL or header arrives as text . FastAPI decides where each function parameter comes from and what type it should be from the signature: a name that…
FastAPI: Performance & scaling
'FastAPI is fast' is true of the framework overhead, which is rarely your bottleneck.
FastAPI: The production pitfalls checklist
Experience is mostly a list of mistakes you no longer make. This part collects thirty that FastAPI teams have paid for in production, grouped by area, each with…
FastAPI: Project: a production-grade orders API
Every part of this guide, in one service a senior team would be comfortable putting in front of customers.
FastAPI: Responses & serialization
What your endpoint returns and what the client receives are not the same thing.
FastAPI: Authorization & API security
Most API breaches are not clever cryptography attacks. Someone changes /orders/1042 to /orders/1043 and gets another customer's order.
FastAPI: Configuration with pydantic-settings
The same code runs on a laptop, in CI, in staging and in production. Only configuration differs: database URLs, secrets, feature flags, allowed origins.
FastAPI: Setup, tooling & the dev loop
A productive FastAPI setup is small: a virtual environment, fastapi with a server, auto-reload while you code, the interactive docs at /docs , and a test client so…
FastAPI: Databases with async SQLAlchemy 2.0
Most FastAPI services are a thin layer over a database, and most of their production incidents come from how that database is used: sessions shared between…
FastAPI: Streaming, SSE, WebSockets & files
Not every response is a small JSON document produced all at once. Exports have millions of rows, LLM answers arrive token by token, dashboards want live updates…
FastAPI: Routers, layers & project structure
Tutorials put everything in main.py . Real services outgrow that within weeks.
FastAPI: Testing FastAPI apps
FastAPI is unusually easy to test: the app is a callable, clients run it in-process, and dependency overrides replace any collaborator.
FastAPI: What FastAPI really is
FastAPI is a thin, clever layer on top of two other libraries. Starlette provides the web toolkit: routing, requests, responses, middleware, WebSockets.
OpenAI SDK: The OpenAI Agents SDK
In part 07 you wrote the tool loop by hand. The Agents SDK ( pip install openai-agents ) packages that loop with a few primitives: an Agent (instructions + tools…
OpenAI SDK: Async client & concurrency
Each API call spends almost all its time waiting for the model. Classifying 1,000 support tickets one at a time at 1.5 s each takes 25 minutes, and your CPU is idle…
OpenAI SDK: Built-in tools
Function tools (part 07) run in your code. Built-in (hosted) tools run on OpenAI's side within the same request: web search , file search over your uploaded…
OpenAI SDK: Conversation state & memory
The model is stateless (part 01), so a chat must supply earlier turns on every call.
OpenAI SDK: Cost & latency optimisation
LLM costs scale with tokens × price × requests, and latency scales mostly with output length and model size.
OpenAI SDK: Embeddings & semantic search
An embedding is a list of numbers (a vector) that represents the meaning of a piece of text.
OpenAI SDK: Errors, retries & timeouts
Network calls fail. Rate limits are hit, servers have bad minutes, requests are malformed, keys expire.
OpenAI SDK: Files, vector stores & managed retrieval
To answer questions from your own documents (policies, manuals, contracts), the model needs the relevant passages in its input.
OpenAI SDK: Function calling: the tool loop
A model cannot query your database or call your API. What it can do is ask you to . You describe functions (name, purpose, JSON Schema for the arguments).
OpenAI SDK: How the OpenAI API works
Under every chatbot, agent and 'AI feature' is the same exchange: your code sends an HTTP request containing a model name and some input, and gets back output plus…
OpenAI SDK: Models, parameters & tokens
Which model you call decides quality, speed and cost more than any prompt trick.
OpenAI SDK: Images, files & audio
Current models read images and PDFs as naturally as text: a receipt photo, a chart screenshot, a 40-page contract.
OpenAI SDK: Project: retail analyst assistant
Ask 'which category earned the most from completed orders?' in plain English and get a correct answer, with the numbers, the SQL that produced them, and caveats…
OpenAI SDK: Realtime & voice
A voice assistant built from three calls (transcribe → think → speak, part 09) works, but each hop adds latency, and conversation feels stilted.
OpenAI SDK: Responses API vs Chat Completions
OpenAI has two APIs for generating text. Chat Completions ( client.chat.completions.create ) is the older, widely copied format: a list of messages in, one message…
OpenAI SDK: Safety, moderation & data handling
An LLM feature has a new kind of attack surface: text . Users can type instructions, documents and web pages can contain hidden instructions, and the model's output…
OpenAI SDK: Setup, keys & your first call
Setup takes five minutes: a virtual environment, the openai package, and an API key in an environment variable .
OpenAI SDK: Streaming responses
A model generates output one token at a time. Without streaming you wait for the whole answer, perhaps 8 seconds for a long reply, and see nothing meanwhile.
OpenAI SDK: Structured outputs with Pydantic
Most application code does not want prose. It wants data : a category, an extracted invoice, a list of action items.
OpenAI SDK: Testing & evaluating LLM code
LLM features need two different kinds of checking. Tests check your code : does the tool loop pass the right call_id back, handle a 429, parse the schema, refuse an…