AI Engineering with Python
Build, evaluate and ship LLM-powered apps.
Learn to build reliable applications on top of large language models: API calls, prompting, embeddings, RAG, tool use and agents, all measured with evals and deployed as real services. Vendor-neutral, using each provider's official SDK docs.
01Foundations
Enough theory and Python to build with confidence.
- How LLMs work: tokens, context windows & samplingA large language model predicts the next token from the tokens before it, one step at a time. Text is split into tokens, the whole conversation must fit in a context window, and sampling settings control how random the choices are.13 min
- The model landscape: hosted vs open-weightYou can call hosted models through a provider's API or run open-weight models on your own hardware. The right choice depends on quality, latency, cost, context size, privacy and licence for your use case.12 min
- Python for AI apps: async, typing & PydanticLLM apps spend most of their time waiting on network calls, so async Python lets you run many at once. Type hints and Pydantic models make data shapes explicit and validate them at runtime.11 min
02Working with LLM APIs
Production-quality calls to any model provider.
- Chat APIs & official SDKsChat APIs take a list of messages with roles and return the model's reply. The official SDK handles authentication and HTTP details; your app keeps the conversation history and resends it each turn.11 min
- Streaming responsesStreaming returns the response as small chunks while the model generates, instead of one block at the end. Users see output almost immediately, which makes apps feel much faster.10 min
- Structured output & JSON schemasStructured output asks the model to return JSON matching a schema instead of free text. Parsing it into Pydantic models gives your code typed, validated objects to work with.11 min
- Errors, retries, rate limits & timeoutsModel APIs fail in ordinary ways: timeouts, rate limits and temporary server errors. Production code adds timeouts, retries with exponential backoff and a fallback so one slow call does not break the app.10 min
- Token counting, cost & latencyLLM cost is mostly input tokens plus output tokens times their prices, and latency grows with output length and model size. Measuring both per request shows where to cut.12 min
03Prompt engineering
Clear instructions beat clever tricks.
- Clear instructions, roles & contextGood prompts read like clear instructions to a smart new colleague: the task, the relevant context, the constraints and the exact output format. Clarity beats clever tricks.12 min
- Few-shot examples & step-by-step reasoningFew-shot prompting shows the model a handful of input and output examples so it copies the pattern. Asking for step-by-step reasoning can improve accuracy on multi-step problems.11 min
- Prompt templates & versioningPrompts change app behaviour as much as code does, so treat them like code. Store them in files, fill them with templates, version them in Git and test every change against evals.10 min
04Embeddings & retrieval
Find the right information before the model answers.
- Embeddings & semantic similarityAn embedding turns text into a list of numbers so that similar meanings land close together. Comparing vectors with cosine similarity lets you find relevant text even when the words differ.12 min
- Vector databases & pgvectorA vector database stores embeddings with metadata and finds the nearest ones to a query vector quickly. pgvector adds this to Postgres, so vectors live alongside your regular data.12 min
- Document loading & chunking strategiesDocuments are split into chunks before embedding, because whole documents are too long and too broad to retrieve precisely. Chunk size and boundaries strongly affect whether retrieval returns useful passages.12 min
- Hybrid search & rerankingVector search finds similar meanings but can miss exact terms like product codes. Hybrid search combines keyword and vector results, and a reranker then reorders the top candidates for precision.13 min
05Retrieval-augmented generation
Answers grounded in your own data.
- Build a RAG pipeline end to endRetrieval-augmented generation finds relevant passages from your documents and puts them in the prompt, so the model answers from your data instead of memory. It has an offline ingest stage and an online query stage.13 min
- Citations & groundingCitations show which sources support each part of an answer, so users can verify it. Grounding instructions keep the model inside the retrieved context and make it refuse when the answer is not there.11 min
- Query rewriting, metadata filters & conversation memoryReal conversations include follow-ups like what about the second one, which retrieve poorly on their own. Query rewriting, metadata filters and conversation memory make retrieval work across a whole chat.11 min
06Tool use & agents
Let models take actions, within limits.
- Function / tool callingTool calling lets a model ask your code to run a function, like searching orders or getting the weather. The model only proposes the call; your app validates the arguments, runs it and returns the result.11 min
- The agent loop: plan, act, observeAn agent repeats a loop: the model decides on an action, your code runs it, and the result goes back to the model until the task is done. Step limits, state tracking and logs keep the loop safe and debuggable.12 min
- Model Context Protocol (MCP)The Model Context Protocol is an open standard for connecting AI applications to tools and data. You write an MCP server once, and any MCP-compatible client can discover and use its tools and resources.11 min
- Safety: prompt injection, data leakage & guardrailsLLM apps face new attacks like prompt injection, where untrusted text tries to override instructions. Because models cannot reliably tell instructions from data, real safety comes from layered guardrails and limited permissions.12 min
07Evaluation & observability
If you can't measure it, you can't improve it.
- Building eval datasetsAn eval dataset is a set of inputs with expected outputs or grading notes that you run your app against. It turns whether it seems better into a measurable score.12 min
- Code checks, LLM-as-judge & human reviewOutputs can be scored by code checks, by an LLM judge using a rubric, or by people. Good eval suites use cheap code checks wherever possible and calibrate LLM judges against human labels.13 min
- Evaluating retrieval & RAG qualityA RAG answer can fail because retrieval missed the right chunk or because generation misused good context. Measuring retrieval and generation separately tells you which part to fix.11 min
- Regression evals in CIRegression evals run your eval suite automatically on every prompt, model or code change. If scores drop below a threshold, the build fails before the change reaches users.12 min
- Tracing, logging & feedbackTracing records every step of a request, such as retrieval, model calls and tool calls, with inputs, outputs, latency and cost. Combined with user feedback, traces show where and why the app fails in production.12 min
08Deployment
From notebook to a service people rely on.
- Serving an LLM app with FastAPIFastAPI turns your Python LLM logic into an HTTP service. Pydantic validates requests, dependencies handle auth, and streaming responses send tokens to clients as they are generated.12 min
- Caching, rate limiting & cost budgetsEvery LLM request costs money, so a public service needs protection. Caching avoids paying twice for the same answer, rate limits stop abuse, and budgets with alerts catch runaway spend early.12 min
- Running open-weight models locallyTools like Ollama and llama.cpp run open-weight models on your own machine. Putting model calls behind one interface lets you swap a local model in for testing, privacy or cost, then compare quality and speed.12 min
- Containerise & deployA Docker image packages your service with its exact Python version and dependencies, so it runs the same everywhere. Secrets come from environment variables at runtime, and health checks let the host restart failed instances.12 min
09Capstone project
An AI app with evidence that it works.
- Scope the app & write the eval set firstBefore writing app code, define the problem, what success looks like and a small eval set. The eval set becomes your scoreboard, so every design choice afterwards can be measured.12 min
- Build a RAG assistant with tools (e.g. docs Q&A or support bot)The capstone is a deployed RAG assistant with citations, at least one tool, an eval suite in CI and documented scores. Build a thin version end to end first, then improve it in measured loops.14 min