
Reproducible AI Development Environments. Every AI project starts with an environment, and a project that only runs on one laptop is a project nobody can trust. This lecture explains why reproducibility matters and how to set up Python environments that behave the same on every machine.
We begin with the common failures. A library updates and quietly changes behavior, a teammate has a different Python version, or a notebook works only because of packages installed months ago. In AI work these differences can change numerical results, break model loading and make experiments impossible to compare.
You will learn the practical toolkit: choosing a Python version, creating isolated virtual environments, declaring dependencies in a requirements or project file, pinning exact versions and recording how to recreate the setup from scratch. We also cover keeping secrets and API keys out of source code, organizing a project folder and writing a short readme so that another person can run your work.
The lecture connects environment discipline to the rest of the course, where you will train models, call language models and deploy services. Each of those depends on knowing exactly what software produced a result.
We also discuss simple checks, such as printing versions and running a smoke test, that confirm an environment is healthy before you start work.
By the end of this lecture you will be able to explain why reproducibility matters, create an isolated Python environment and document it so that others can rebuild it.
Day 1: Python Development Setup — Build a command-line environment checker. On your first day you set up your tools and build a small utility that checks whether a machine is ready for AI engineering work. It is a gentle project that proves your setup works and introduces habits you will use for the next hundred days.
The steps I would expect you to follow are these. First, create a project folder with a virtual environment and a clear structure. Second, install the required tools and pin the versions in a requirements file. Third, write a Python script that reports the Python version, the operating system, the installed packages and whether the expected versions are present. Fourth, add command-line arguments so the user can choose a quiet or detailed report. Fifth, return clear messages and a meaningful exit code when something is missing, so the checker can be used in automation. Sixth, write a short readme describing how to run it.
The project introduces functions, string formatting, reading package metadata and basic command-line interfaces, all in a small, achievable scope.
Use only your own machine and no private data. Save your work in version control from the first day.
By the end of this project you will have a working environment checker, a clean project template and a daily routine of building, testing and documenting small tools.
Token Budgets and Inference Cost. Language models charge by the token, and uncontrolled usage can turn a small prototype into a surprising bill. This lecture introduces tokens, context limits and the arithmetic of inference cost, using basic Python concepts you are about to practice.
A token is a small chunk of text, often a piece of a word. Models measure both what you send and what they generate in tokens, and each model has a maximum context size and a price per unit of input and output. Because output tokens are usually priced higher than input tokens, long answers cost more than long questions.
We work through simple calculations. Given the average prompt length, the expected response length, the number of requests per day and the price per thousand tokens, you can estimate daily and monthly cost. We discuss how retries, long conversation history and large documents increase usage, and why cost estimates should include a safety margin.
You will see how variables, numeric types and functions make these calculations reusable, and why careful handling of units and rounding matters when money is involved.
We also introduce the idea of a budget as a design constraint, which will appear again when you build monitoring dashboards and rate limits later in the course.
By the end of this lecture you will be able to estimate token usage and cost for a workload and explain the factors that drive it.
Day 2: Variables, Types, and Functions — Build an AI usage cost calculator. Today you turn the cost arithmetic from the previous lecture into a small, reliable calculator. The project practices variables, numeric types and functions while solving a real engineering problem.
The steps I would expect you to follow are these. First, define the inputs, such as model name, input price, output price, prompt tokens, response tokens and requests per day. Second, write small functions, one for the cost of a single request, one for daily cost and one for monthly projection, each with clear parameters and return values. Third, handle units carefully, converting prices per million tokens into per token values. Fourth, add type hints and docstrings so that each function explains itself. Fifth, build a simple command-line interface that accepts the inputs and prints a readable summary. Sixth, test with a few hand-calculated examples to confirm the answers.
You will also practice avoiding common mistakes, such as mixing integers and floats carelessly, hiding magic numbers in code and writing one giant function.
Use illustrative prices, since real prices change, and keep the prices in a configuration dictionary that is easy to update.
By the end of this project you will have a tested cost calculator and a stronger grasp of functions, types and clean, readable Python.
Data Identity and Deduplication. The same customer, document or event can appear many times in different forms, and AI systems that ignore this learn the wrong lessons. This lecture explains data identity and deduplication using the core Python collections you are about to use.
Identity answers a simple question: when are two records the same thing? Sometimes a stable identifier exists, such as a customer number. Often it does not, and records differ by spelling, spacing, capitalization or formatting. Deciding what makes two records equivalent is a design decision, not a technical accident.
We discuss why duplicates cause harm. They inflate counts, bias statistics, leak between training and test sets and waste storage and cost in downstream processing. We introduce the strategies: exact matching on normalized keys, matching on combinations of fields and flagging near-duplicates for review rather than deleting them automatically.
You will see how lists preserve order, dictionaries provide fast lookup by key and sets handle uniqueness and membership efficiently, and how to choose among them. We also discuss normalization steps such as trimming whitespace and standardizing case, and the importance of keeping an audit record of what was merged.
Careful deduplication should be reversible and explainable, because mistaken merges can damage data quality.
By the end of this lecture you will be able to define record identity, choose appropriate collections and reason about safe deduplication.
Day 3: Lists, Dictionaries, and Sets — Build a customer-record deduplication tool. Today you build a practical tool that finds duplicate customer records, using lists, dictionaries and sets together. The project uses synthetic data, so no real personal information is involved.
The steps I would expect you to follow are these. First, create a sample dataset of customer records with deliberate duplicates, such as extra spaces, different capitalization and slightly different formatting of emails or phone numbers. Second, write normalization functions that produce a clean comparison key. Third, use a dictionary to group records by key and a set to track seen identifiers. Fourth, decide which record to keep in each group, for example the most complete or the most recent, and document the rule. Fifth, output a report listing the groups, the chosen record and the discarded ones, rather than silently deleting anything. Sixth, write tests for edge cases such as empty fields and records with identical names but different emails.
Pay attention to efficiency. Looking up a key in a dictionary is much faster than scanning a list, which matters when datasets grow.
Keep the sample data, the merge rule and the report together in your project folder, so that you can rerun the tool later, explain every decision it made and adjust the rule without guessing.
By the end of this project you will have a working deduplication tool, a clear merge policy and practical fluency with Python collections.
AI Dataset Formats and Serialization. Before a model can learn from data, the data must be stored, exchanged and loaded reliably. This lecture explains common dataset formats and serialization, the process of turning in-memory objects into files and back.
We compare the formats you will meet constantly. CSV is simple and widely supported, but it has no types and struggles with commas, quotes and line breaks inside values. JSON preserves nested structure and is the standard for APIs and configuration, but large files are awkward to process. JSON Lines stores one record per line, which suits streaming and very large datasets. Binary formats can be faster and smaller, but are less human readable.
You will learn the questions that guide the choice: who consumes the data, how large it is, whether it has nested fields, whether types must be preserved and whether it must be appended to over time. We also cover encodings, since text files that look fine on one system can be corrupted on another, and why you should always state the encoding explicitly.
Serialization has risks. Loading untrusted files with unsafe mechanisms can be dangerous, so prefer simple, well-defined formats for data exchange.
Finally, we discuss validating data after loading, since a successful parse does not prove the content is correct.
By the end of this lecture you will be able to choose a format, read and write it safely and explain the tradeoffs.
Day 4: Files, JSON, and CSV — Build a dataset format converter. Today you build a tool that converts datasets between CSV, JSON and JSON Lines, practicing file handling and careful data handling at the same time.
The steps I would expect you to follow are these. First, create small sample files in each format using synthetic records, including awkward cases such as commas inside values, missing fields, nested objects and non-English characters. Second, write reader functions for each format that return a common list of dictionaries. Third, write writer functions that output each format with explicit encoding. Fourth, build a command-line interface that takes an input path, an output path and a target format. Fifth, add safeguards: refuse to overwrite existing files by default, report how many records were converted and warn about fields that cannot be represented, such as nested data in CSV. Sixth, write tests that convert a file through every format and confirm that the content survives the round trip.
Use context managers for files so they always close, and handle encoding errors with clear messages.
Keep the sample files and round-trip tests in your repository, and rerun them whenever you add a format, because conversion bugs usually appear first in small details such as quoting, encoding and empty values.
By the end of this project you will have a reliable converter and solid habits for working with files, JSON and CSV.
Input Validation and Failure Handling. Real data is messy, and real programs fail. This lecture explains how to validate inputs and handle failures so that your AI pipelines behave predictably instead of crashing or silently producing wrong results.
We start with the distinction between errors you can prevent and errors you must handle. Validation checks inputs before using them: types, required fields, ranges, formats and allowed values. Exception handling deals with problems that occur anyway, such as a missing file, a malformed record or a network failure.
You will learn Python's exception model: raising meaningful exceptions, catching specific types rather than everything, using finally and context managers to clean up and creating custom exceptions that carry useful information. We discuss the danger of swallowing errors, which hides problems until they cause bigger ones, and the value of failing fast when continuing would corrupt results.
For data pipelines, a useful pattern is to separate good records from bad ones. Valid records continue, invalid ones go to a rejected collection with a reason, and a summary reports counts. This keeps one bad row from stopping a large job while keeping problems visible.
We also discuss clear error messages that tell the user what happened and what to do next, without exposing sensitive details.
By the end of this lecture you will be able to design validation rules and failure handling that make data code resilient and transparent.
Day 5: Exceptions and Input Validation — Build a resilient data import utility. Today you build an importer that reads messy data, validates every record and reports problems instead of crashing. It is a small version of the tools that keep real pipelines healthy.
The steps I would expect you to follow are these. First, prepare a synthetic input file with deliberate problems, such as missing required fields, wrong types, impossible dates, negative quantities and a corrupted line. Second, define validation rules as small functions that return clear error messages. Third, write the import loop so that each record is validated, and valid and invalid records are collected separately. Fourth, define custom exceptions for different failure types and handle file-level failures, such as a missing file or a bad encoding, with helpful messages. Fifth, write the rejected records to a separate file with the reason for each rejection. Sixth, print a summary with counts of accepted and rejected records and return an exit code that reflects the outcome.
Write tests with both valid and invalid data, and confirm that nothing is silently dropped.
Keep the rejected-records file and the summary output as part of your project, because a clear record of what was refused and why is what makes an importer trustworthy to the people who rely on it.
By the end of this project you will have a resilient import utility and practical skill in exceptions, validation and honest reporting.
Reusable AI Pipeline Components. AI systems are made of many small steps, and the quality of those steps determines whether the whole system can be maintained. This lecture explains how to design reusable pipeline components using Python modules and packages.
A component does one job, takes clear inputs and returns clear outputs. Examples include a text cleaner, a tokenizer wrapper, a validator and a feature builder. When these live in a single large script, they are hard to test, hard to reuse and easy to break. Splitting them into modules, and grouping related modules into packages, gives your project structure.
You will learn how Python finds and imports code, how to organize a package with an init file, how to expose a clean public interface and how to avoid circular imports. We discuss naming, keeping functions pure where possible so that the same input always gives the same output and documenting each component with a short docstring.
We also cover how packaging supports collaboration. When components have stable interfaces, teammates can improve one without breaking the others, and tests can target each piece independently.
Finally, we introduce the idea of installing your own package into your environment so that every project can reuse it consistently.
By the end of this lecture you will be able to organize code into modules and packages and design components that are testable and reusable.
Day 6: Modules and Packages — Package reusable text-cleaning functions. Today you build a small, installable package of text-cleaning functions that you can reuse in later projects, including those that prepare text for language models.
The steps I would expect you to follow are these. First, create a package folder with a clear name and an init file, plus a separate module for each concern, such as whitespace handling, case normalization, punctuation removal and simple tokenization. Second, write each function with type hints and a docstring, keeping them small and free of side effects. Third, expose a clean public interface so that users can import the main functions directly. Fourth, create a project configuration file that allows the package to be installed in editable mode. Fifth, write a small demonstration script that imports your package and cleans sample text. Sixth, add tests for edge cases, such as empty strings, unusual spacing and non-English characters.
Think about order, because cleaning steps can interact, and document the intended sequence.
Use only synthetic or public text for the examples.
Keep a short readme that lists each function, its purpose and an example of its input and output, so that you or a teammate can reuse the package in a later project without rereading the source code.
By the end of this project you will have a reusable package, a clean import structure and the confidence to organize future code into well-defined modules.
Document Identity and State Management. Documents move through pipelines, change over time and need to be tracked reliably. This lecture explains how to model document identity and state using object-oriented Python.
Every document needs a stable identity, such as an identifier that does not change when the title or content is edited, plus attributes that do change, such as version, status and timestamps. Mixing these up causes duplicate entries, lost history and confusing bugs. We discuss how to decide what defines a document and what should be metadata.
Classes let you bundle data and behavior. A document class can hold its content and metadata and offer methods that change state in controlled ways, for example marking a document as processed or archived. A collection class can manage many documents, enforce uniqueness of identifiers and provide search and filtering.
You will learn about initialization, instance and class attributes, properties, special methods such as string representation and equality and the idea of keeping invalid states impossible by validating inside the class. We also discuss composition versus inheritance and when simple data classes are enough.
State management matters in AI pipelines because a document may be new, extracted, chunked, embedded or deleted, and downstream steps need to know which.
By the end of this lecture you will be able to design classes that model documents and their lifecycle safely.
Day 7: Object-Oriented Python — Build a document collection manager. Today you build a manager that stores documents, tracks their state and supports searching and updates, using classes and clear interfaces.
The steps I would expect you to follow are these. First, define a document class with an identifier, title, content, version, status and timestamps, validating inputs when objects are created. Second, add methods for controlled state changes, such as marking a document as reviewed or archived, and prevent invalid transitions. Third, write a collection class that stores documents by identifier, rejects duplicates and supports adding, retrieving, updating and removing items. Fourth, add search and filter methods, such as finding documents by status or by a keyword in the title. Fifth, implement readable string representations to help debugging. Sixth, write tests for normal operations and edge cases, such as updating a missing document or archiving twice.
Persist the collection to a JSON file and reload it, practicing serialization of objects.
Use synthetic documents so that no confidential material is involved.
Keep the tests and the saved JSON file in your repository, and add a short note on the allowed state transitions, so that anyone extending the manager understands which changes are permitted and why.
By the end of this project you will have a working document manager and practical experience with classes, encapsulation and lifecycle modeling.
Streaming Data and Incremental Processing. Many AI datasets are too large to fit in memory, and many data sources never stop producing records. This lecture explains streaming and incremental processing using Python iterators and generators.
When you load an entire file into a list, memory use grows with the file. Streaming reads and processes one record, or one small batch, at a time, so memory use stays small regardless of file size. The same approach works for log files, event feeds, large exports and API responses.
You will learn what iterators are, how the iteration protocol works and how generators let you write lazy pipelines with the yield keyword. Generators can be chained so that each stage handles a record and passes it on, forming a pipeline in which data flows through without being stored in full.
We discuss the tradeoffs. Streaming is memory efficient but you can only pass over the data once unless you reopen it, you must handle partial failures and you need to think about batching for efficiency. Incremental processing also requires remembering where you stopped, so a job can resume after interruption without repeating work.
These ideas return in later sections, when you process large document collections, ingest API data and build monitoring pipelines.
By the end of this lecture you will be able to explain iterators and generators and design memory-efficient streaming pipelines.
Day 8: Iterators and Generators — Build a streaming log processor. Today you build a processor that reads a large log file line by line, filters and transforms the entries and produces summaries without loading the whole file into memory.
The steps I would expect you to follow are these. First, generate a synthetic log file with many lines, including different severity levels, timestamps and a few malformed lines. Second, write a generator that reads the file lazily and yields one line at a time. Third, write further generators that parse each line into a structured record, skip or count malformed lines and filter by severity or time window. Fourth, chain the generators into a pipeline. Fifth, compute running summaries, such as counts per severity and the most frequent messages, while streaming. Sixth, add batching so that results can be written out in groups, and measure memory use compared with a version that loads everything.
Include a checkpoint, such as the line number reached, so that processing can resume after an interruption.
Write tests using small in-memory inputs to verify the logic of each stage.
Keep the sample log generator, the pipeline stages and the memory comparison together, so that you can repeat the measurement later and show concrete evidence of the benefit of streaming over loading everything.
By the end of this project you will have a streaming processor and a practical understanding of generators and lazy evaluation.
Behavioral Testing for AI Components. AI code often fails quietly, producing plausible but wrong output, so testing is a core engineering skill rather than an optional extra. This lecture introduces behavioral testing for AI components and the pytest tool you will use to automate it.
A behavioral test checks what a component does, not how it does it. Given an input, does the validator reject the bad record? Does the cleaner preserve the meaning of the text? Does the function return the expected result for edge cases? Such tests protect you when you refactor or change a dependency.
We cover how to design useful tests: pick representative cases, include boundary values and unusual inputs, test failure paths as carefully as success paths and keep each test small and focused. We discuss fixtures for shared setup, parameterized tests for running the same check over many inputs and temporary files for testing code that touches the disk.
For AI-related components, there are special concerns. Outputs may vary, so tests should check properties, such as format and constraints, instead of exact wording. External services should be replaced with simple fakes so that tests are fast, repeatable and free.
Tests also serve as documentation, showing how a component is meant to be used.
By the end of this lecture you will be able to design behavioral tests and explain how they support safe change.
Day 9: Testing with Pytest — Build a tested data-validation library. Today you build a small validation library and a thorough pytest suite around it, practicing the habit of writing tests alongside code.
The steps I would expect you to follow are these. First, design a small library of validators, such as checks for required fields, numeric ranges, email-like formats, allowed categories and date ordering, each returning a clear result with a message. Second, write tests for every validator, covering valid input, invalid input and boundary values. Third, use parameterized tests to run many cases compactly. Fourth, use fixtures to create reusable sample records and temporary files. Fifth, test that errors are reported with helpful messages and that unusual inputs, such as empty values or unexpected types, do not crash the library. Sixth, run the suite with coverage reporting and look at which lines are untested.
Practice writing a test first for a new behavior, watching it fail and then implementing the code to make it pass.
Use synthetic data only.
Keep the test suite in your repository and run it before every change, since the real value of this project is the habit of letting automated checks tell you whether a modification was safe.
By the end of this project you will have a tested library, a pytest workflow you can reuse and an appreciation of how tests make later AI work safer.
Configuration and Data-Quality Monitoring. Pipelines run for months, and the settings and data around them keep changing. This lecture explains how configuration and logging, together with data-quality checks, keep AI systems understandable and trustworthy.
Configuration separates settings from code. Thresholds, file paths, model names and feature flags belong in configuration files or environment variables, not scattered through the source. Secrets must be handled separately and never committed. Good configuration is validated at startup, so that a missing or invalid value stops the program immediately with a clear message.
Logging records what a program did. You will learn log levels, structured messages, including context such as identifiers and counts, and why print statements are a poor substitute. Logs should help you answer questions later, such as which records were rejected and why, without exposing sensitive content.
Data-quality monitoring turns these ideas into checks on the data itself: counts of missing values, duplicates, out-of-range values, unexpected categories, and changes in distributions compared with a baseline. Reporting these metrics each run reveals problems early, before they reach a model.
We discuss thresholds and alerts, and the need to distinguish a warning that deserves attention from an error that should stop the pipeline.
By the end of this lecture you will be able to design configuration and logging that support reliable, observable data pipelines.
Day 10: Logging and Configuration — Build a configurable dataset quality checker. Today you complete the first section with a tool that reads a dataset, checks its quality according to a configuration file and writes a clear, logged report.
The steps I would expect you to follow are these. First, define a configuration file, in a simple format such as JSON or YAML, that lists required columns, allowed ranges, maximum missing rates and duplicate rules. Second, load and validate the configuration, failing with a clear message when it is invalid. Third, set up logging with levels, timestamps and a log file. Fourth, write checks for missing values, duplicates, out-of-range values and unexpected categories, using the streaming ideas from earlier days where files are large. Fifth, produce a summary report with pass or fail status for each check and an overall result. Sixth, return an exit code suitable for automation and write tests for the main checks.
Use a synthetic dataset with planted problems, so you can confirm that the checker finds each one.
Keep thresholds in configuration instead of code, so that different datasets can use different rules.
By the end of this project you will have a reusable quality checker and a solid foundation of Python habits for the data engineering section.
Feature Scaling and Numerical Stability. Machine learning models consume numbers, and the scale and behavior of those numbers strongly affect results. This lecture introduces feature scaling and numerical stability using NumPy, the array library behind most of the Python AI stack.
Features often live on very different scales. A customer's age might range from 18 to 90, while annual spend might range from zero to millions. Many algorithms, particularly those based on distances or gradients, treat larger numbers as more important, which can distort learning. Scaling puts features on comparable ranges. Common approaches include standardization, which centers values and divides by the standard deviation, and min-max scaling, which maps values into a fixed interval.
You will learn why NumPy arrays are central: they store numbers compactly, support vectorized operations that are far faster than Python loops and allow broadcasting, which applies operations across arrays of different shapes. We discuss shapes, axes, indexing, slicing and aggregation functions.
Numerical stability is the second theme. Computers represent numbers with limited precision, so subtracting nearly equal values, dividing by tiny numbers or exponentiating large values can produce errors, overflow or not-a-number results. We discuss defensive habits such as guarding against zero variance, using stable formulations and checking results for invalid values.
Scaling parameters must be learned from training data and then reused, a point that returns when we discuss leakage.
By the end of this lecture you will be able to apply scaling and recognize numerical pitfalls.
Day 11: NumPy Fundamentals — Build a feature-normalization tool. Today you build a tool that normalizes numeric features using NumPy and can reapply the same transformation to new data.
The steps I would expect you to follow are these. First, create a synthetic numeric dataset with several features on very different scales, including a constant feature and a few missing values. Second, load it into a NumPy array and inspect shapes, data types and summary statistics. Third, implement standardization and min-max scaling using vectorized operations and broadcasting, without Python loops. Fourth, handle edge cases, such as zero variance, by leaving the feature unchanged or flagging it, and decide how to treat missing values. Fifth, store the learned parameters, such as means and standard deviations, so that the same transformation can be applied to new data consistently. Sixth, write tests that confirm scaled features have the expected statistics and that applying the stored parameters to new data behaves correctly.
Compare the speed of your vectorized code with a loop-based version to see the benefit.
Keep the sample data, the saved scaling parameters and the tests together, so that you can reuse the tool on new datasets later and confirm that it still behaves exactly as it did on the first day.
By the end of this project you will have a reusable normalization tool and confidence with NumPy arrays and vectorized thinking.
Customer Features and Aggregation. Raw event tables rarely feed models directly. They must be summarized into features that describe each customer, product or session. This lecture introduces aggregation with Pandas, the main tool for tabular data analysis in Python.
A DataFrame is a table with labeled columns and an index. You will learn how to load data, inspect it, select columns and rows, filter with conditions, create new columns and sort. The central technique is grouping: split the data by a key such as customer, compute summaries such as counts, sums, averages, minimums and maximums, and combine the results into a new table with one row per group.
We discuss how to design useful features. Recency, frequency and monetary value summarize customer behavior. Time windows, such as activity in the last thirty days, capture change. Ratios and rates normalize for size. Each feature should have a clear business meaning and a defined time boundary, to avoid accidentally using information that would not have been available at prediction time.
We also cover merging tables, handling dates and the importance of checking row counts after joins, since a many-to-many join can silently multiply rows and distort totals.
Readable, well-named steps make analyses easier to review and reproduce.
By the end of this lecture you will be able to aggregate event data into meaningful, well-defined customer features.
Day 12: Data Analysis with Pandas — Build a customer activity report. Today you use Pandas to turn raw activity data into a clear report about customers, practicing selection, grouping, merging and summarization.
The steps I would expect you to follow are these. First, generate synthetic customer and event tables, including dates, event types and amounts. Second, load them into DataFrames and inspect types, missing values and basic statistics. Third, clean the data, for example by parsing dates and removing obviously invalid rows. Fourth, compute per-customer features such as number of events, total and average amount, most recent activity and activity in the last thirty days. Fifth, merge the features with customer attributes and verify that the row count matches what you expect. Sixth, produce a report, such as the most active customers, a summary by segment and a short written description of findings, and save it as a CSV and a readable text file.
Add tests or assertions that check totals against hand-computed values on a small sample.
Pay attention to readability by naming intermediate DataFrames clearly and keeping transformations in functions.
Keep the generated report and the script that produced it together in version control, so that anyone can regenerate the numbers from the raw data and confirm that a changed figure reflects a real change.
By the end of this project you will have a reproducible report generator and practical skill with Pandas for feature creation and analysis.
Missing Data and Anomaly Treatment. Missing values and outliers are normal in real datasets, and how you treat them can change a model's behavior. This lecture explains how to understand, handle and document them responsibly.
Missing data comes in different forms. Values may be missing completely at random, may depend on other variables, or may be missing for a reason that itself carries information, such as a customer who never filled in an optional field. Before choosing a treatment, investigate why the data is missing and how much is missing in each column and row.
Common treatments include removing rows or columns, filling with a constant, filling with a statistic such as the median, filling forward in time series and adding an indicator column that records that a value was missing. Each has tradeoffs, and filling can hide patterns or distort relationships. Whatever you choose, learn the fill values from training data only.
Outliers are values far from the rest. Some are errors, such as a negative age, and some are real and important, such as a very large legitimate purchase. We discuss detection with summary statistics, percentile rules and visual inspection, and treatment options such as correction, capping or leaving them in place with a flag.
Every decision should be recorded so that others understand how the data was changed.
By the end of this lecture you will be able to diagnose missing data and outliers and choose defensible treatments.
Day 13: Missing Values and Outliers — Build a data-cleaning pipeline. Today you build a cleaning pipeline that detects and treats missing values and outliers and records every change it makes.
The steps I would expect you to follow are these. First, create a synthetic dataset with planted problems: missing values in several columns, impossible values, extreme but valid values and inconsistent categories. Second, write a profiling function that reports missing counts, percentages and basic statistics for every column. Third, implement treatment functions, such as median filling, indicator columns, capping at percentile limits and correction of impossible values, each configurable. Fourth, assemble them into a pipeline that applies the steps in a defined order and logs what changed, including the number of values affected. Fifth, learn the fill values from a training portion and apply them unchanged to a separate portion. Sixth, write tests confirming that the pipeline fixes the planted problems and leaves valid data intact.
Produce a before-and-after summary that a colleague could review.
Document why you chose each treatment, because the reasoning matters as much as the code.
Keep the before-and-after summary alongside the pipeline, because a clear record of what was changed and why is what allows colleagues to trust and reproduce your cleaning decisions later.
By the end of this project you will have a reusable cleaning pipeline with an audit trail and a careful approach to data quality.
Exploratory Data Analysis. Before building any model, you need to understand the data. This lecture introduces exploratory data analysis, the practice of examining datasets with statistics and visualization to discover structure, problems and questions.
Start with the basics: how many rows and columns, what each column means, what types they have and how much is missing. Then examine distributions of single variables using summaries and histograms, and relationships between variables using scatter plots, grouped comparisons and correlation. Look for skewed distributions, clusters, seasonal patterns, strange spikes and categories that rarely appear.
Visualization is a tool for thinking, not decoration. We discuss choosing the right chart for the question: histograms for distributions, bar charts for category comparisons, line charts for time, scatter plots for relationships and box plots for spread and outliers. Good charts have clear titles, labeled axes with units, sensible scales and minimal clutter. Misleading charts, such as truncated axes or inappropriate aggregation, can cause wrong conclusions.
We also stress healthy skepticism. Correlation does not imply causation, apparent patterns can arise by chance and a dataset may not represent the population you care about. Record observations and open questions as you go.
EDA also feeds modeling decisions about features, transformations and potential leakage.
By the end of this lecture you will be able to conduct a structured exploration and communicate what you found.
Day 14: Data Visualization — Build an exploratory sales dashboard. Today you build a visual exploration of a sales dataset, practicing chart selection and clear communication.
The steps I would expect you to follow are these. First, generate or load a synthetic sales dataset with dates, regions, products, quantities and prices, including a few anomalies. Second, prepare the data by parsing dates, creating revenue and aggregating by time period and category. Third, create a set of charts using a plotting library: revenue over time, a comparison across regions, the distribution of order values, a relationship between price and quantity and a chart that highlights outliers. Fourth, apply good design: titles, labeled axes with units, readable fonts, consistent colors and an appropriate scale. Fifth, arrange the charts into a single report or simple dashboard page and add short written insights under each. Sixth, review your charts critically for misleading elements and revise them.
Save the figures and the script so that the whole dashboard can be regenerated from the data in one command.
Write down two questions that the charts raise but cannot answer.
Keep the figures, the dashboard script and your list of unanswered questions together, since those open questions often become the starting point for the modeling work that follows in the next section.
By the end of this project you will have a reproducible exploratory dashboard and sharper judgment about visual communication.
Relational Data for AI Applications. Much of the world's business data lives in relational databases, and AI engineers need to reach it confidently. This lecture introduces relational data and SQL as a foundation for data preparation.
A relational database organizes data into tables of rows and columns, linked by keys. A primary key uniquely identifies a row, and a foreign key points to a row in another table. Splitting data into related tables avoids duplication and keeps information consistent, such as storing customers once and referring to them from many orders.
You will learn the core SQL operations: selecting columns, filtering with conditions, sorting, limiting results and combining tables with joins. We explain inner joins, which keep only matching rows, and left joins, which keep all rows from one side and fill gaps with nulls. Understanding join behavior is essential, because the wrong join silently drops or duplicates data.
We discuss the idea of grain, meaning what one row in a table represents, and why mixing grains leads to inflated totals. We also introduce good habits: reading query plans at a basic level, using indexes conceptually, writing readable queries with clear aliases and testing with small known examples.
For AI applications, SQL is often the first step in building training datasets and feature tables.
By the end of this lecture you will be able to explain relational structure and write queries that join and filter data correctly.
Day 15: SQL Queries and Joins — Build a customer order analysis database. Today you create a small database and write queries that analyze customers and orders, practicing joins and careful reasoning about grain.
The steps I would expect you to follow are these. First, design a schema with customers, products, orders and order items, defining primary and foreign keys. Second, create the database using a lightweight engine and load synthetic data, including customers without orders and orders with several items. Third, write queries to list customers with their orders, find customers who never ordered, compute revenue per customer and per product and identify the largest orders. Fourth, practice inner and left joins and compare the results to see how each treats missing matches. Fifth, check your totals against hand calculations to confirm that joins did not duplicate rows. Sixth, load query results into Pandas and save a short report.
Use parameterized queries when inputs vary, instead of building SQL strings by hand.
Keep the SQL in files with comments explaining each query and its expected grain.
Keep your queries, schema file and expected results together in the project, so that you can rerun them against fresh data and quickly notice whenever a join starts returning a different number of rows.
By the end of this project you will have a working analysis database, a library of reviewed queries and stronger instincts for correct joins.
Cohort Analysis and Metric Definitions. Business questions often depend on how a metric is defined, and AI teams must be precise about those definitions. This lecture introduces cohort analysis, aggregations and window functions in SQL.
An aggregation summarizes many rows into one using functions such as count, sum and average, grouped by one or more columns. Careful metric definition matters: what counts as an active customer, what time period applies and how are refunds treated? Small differences in definition produce different numbers and sometimes different decisions.
Window functions compute values across related rows without collapsing them. Examples include ranking customers by spend within a region, calculating running totals, comparing each row with the previous one and computing moving averages. They are powerful for time-based features and for retention analysis.
Cohort analysis groups customers by a shared starting point, such as the month of their first purchase, and tracks behavior over time. A retention table shows what share of each cohort remains active in each later period, revealing whether newer cohorts behave differently from older ones.
We discuss pitfalls, such as incomplete recent periods, small cohort sizes and mixing time zones. Document every metric definition so that results are reproducible.
By the end of this lecture you will be able to define metrics precisely and use aggregations and window functions for cohort-style analysis.
Day 16: Aggregations and Window Functions — Build a customer retention report. Today you build a retention analysis that groups customers into cohorts and measures how many return in later periods.
The steps I would expect you to follow are these. First, use the order database or a fresh synthetic one with customer identifiers, order dates and amounts. Second, write a query that finds each customer's first order month, which defines the cohort. Third, compute activity by customer and month, and join it with the cohort information to calculate the number of months since first purchase. Fourth, aggregate to produce a retention table showing, for each cohort and each later month, the number and percentage of customers who ordered. Fifth, use window functions to add running totals and rankings, such as the top customers by spend within each cohort. Sixth, export the table, create a simple heatmap or line chart and write a short interpretation of the findings.
Handle the incomplete final period explicitly, and document the definition of an active customer.
Add checks that cohort sizes sum to the total number of customers.
Keep the query files, exported table and chart together in the project, and record the definition of an active customer in the readme, so that later readers can interpret the percentages correctly.
By the end of this project you will have a clear retention report and practical fluency with grouping and window functions.
External Data Acquisition. AI projects often need data from outside the organization, usually through web APIs. This lecture introduces how HTTP APIs work and how to collect data from them responsibly and reliably.
An API exposes resources at addresses, called endpoints, and clients interact using methods, such as GET to read data. Requests may include parameters, headers and authentication credentials. Responses contain a status code, headers and a body, usually JSON. Status codes tell you what happened: success, a client error, rate limiting or a server problem.
You will learn how to make requests in Python, parse responses and handle errors. Real collectors must deal with pagination, where results arrive in pages, and with rate limits, which require pausing or slowing down. Timeouts prevent a collector from hanging, and retries with increasing delays handle temporary failures.
We discuss responsible use. Read the terms of use and documentation, identify yourself appropriately, respect rate limits and robots rules, avoid collecting personal data you do not need and store credentials safely outside the code.
We also discuss data hygiene: save raw responses before transforming them, record when and from where data was collected and validate what you receive, since external sources change without notice.
By the end of this lecture you will be able to describe HTTP interactions and design a polite, resilient data collector.
Day 17: Working with HTTP APIs — Build a paginated public-data collector. Today you build a collector that retrieves data from a public API across many pages, with careful error handling and respectful behavior.
The steps I would expect you to follow are these. First, choose a public API that does not require sensitive credentials and read its documentation, noting the endpoints, pagination method and rate limits. Second, write a function that makes a request with a timeout, checks the status code and parses the JSON. Third, implement pagination, following the documented mechanism until no more pages remain, with a safety limit on the number of pages. Fourth, add retries with exponential backoff for temporary failures, and pause when the API signals that you are going too fast. Fifth, save the raw responses to disk with timestamps and then transform them into a clean table. Sixth, write tests using recorded or fake responses so that your code can be verified without calling the real service.
Log each request at a suitable level, but never log secrets.
Add a configuration section for the base address, page size and delay.
By the end of this project you will have a dependable data collector and practical habits for working with external services.
Schema and Business-Rule Validation. Data arriving from outside cannot be trusted until it is checked. This lecture explains schema validation and business-rule validation, and how to quarantine bad records instead of letting them contaminate your pipeline.
A schema describes the expected structure: which fields exist, their types, which are required and what values are allowed. Validating against a schema catches structural problems early, such as a missing identifier or a string where a number belongs. Libraries make it easy to declare schemas as typed models and to produce clear error reports.
Business rules go beyond structure. A shipping date should not precede the order date, quantities should be positive, totals should match line items and country codes should come from a known list. These rules encode domain knowledge, and they should be explicit, tested and documented.
When validation fails, the pipeline must choose a response. Rejecting the whole batch is simple but harsh. Dropping bad records silently is dangerous. A better pattern is quarantine: send invalid records to a separate store with the reasons, continue with valid ones and report counts so that owners can fix the source.
We also discuss versioning schemas, tolerating harmless additions and measuring rejection rates over time as a sign of upstream problems.
By the end of this lecture you will be able to design layered validation with a visible quarantine path.
Day 18: Schema Validation — Build an ingestion pipeline that quarantines invalid records. Today you build an ingestion pipeline that validates incoming records, accepts the good ones and quarantines the rest with clear reasons.
The steps I would expect you to follow are these. First, define a schema for incoming records using a validation library, specifying types, required fields and constraints. Second, write business-rule checks, such as date ordering, positive amounts and allowed categories. Third, create a synthetic input file with valid records and a variety of invalid ones. Fourth, implement the pipeline: read records, validate structure, apply the business rules, and route each record to an accepted store or a quarantine store along with the list of reasons. Fifth, produce a run summary with counts by outcome and the most common failure reasons. Sixth, write tests for each rule and for the routing behavior, and confirm that no record disappears without being counted.
Include a way to reprocess quarantined records after they are corrected.
Keep the schema and rules in separate, well-named modules so they are easy to review.
Keep the schema, rules, quarantine output and run summary together, so that data owners can see exactly which records failed, why they failed and how to correct them at the source.
By the end of this project you will have a reliable ingestion pipeline with visible quality control and a reusable validation pattern.
Idempotent Data Pipelines. Pipelines fail halfway, get rerun and receive the same data twice. This lecture explains extract, transform and load processes and the property that makes them safe to repeat: idempotency.
An ETL pipeline extracts data from a source, transforms it into a useful shape and loads it into a destination such as a database. A pipeline is idempotent when running it several times with the same input leaves the destination in the same state as running it once. Without idempotency, a retry after a failure can duplicate rows, double count totals or leave inconsistent partial results.
You will learn the techniques. Use stable unique keys and upserts instead of blind inserts. Load into a staging table and swap or merge in a single transaction. Record which batches or time ranges have been processed. Make transformations deterministic, so that the same input always produces the same output.
We also discuss incremental processing, where each run handles only new or changed data. It requires a reliable cursor, such as a timestamp or an identifier, careful handling of late-arriving records and the ability to backfill when something goes wrong.
Monitoring row counts, run durations and failures turns a pipeline from a script into an operable system.
By the end of this lecture you will be able to design pipelines that can be retried and rerun safely.
Day 19: ETL and Incremental Processing — Build an API-to-database pipeline. Today you build a pipeline that pulls data from an API, transforms it and loads it into a database in a way that is safe to rerun.
The steps I would expect you to follow are these. First, use the collector from earlier or a simulated API that returns records with identifiers and update timestamps. Second, design a destination table with a unique key and columns for the transformed fields and the load time. Third, implement the transformation step as pure functions with tests. Fourth, load using an upsert so that records are inserted or updated by key, wrapped in a transaction. Fifth, store a cursor, such as the latest update timestamp processed, so that each run fetches only newer records, and include a small overlap window to catch late arrivals. Sixth, run the pipeline several times, including after a simulated failure, and verify that the row counts and contents are correct and free of duplicates.
Log counts for fetched, inserted, updated and skipped records.
Provide a way to backfill a specific date range.
Keep the cursor value, the run logs and the tests together, and rehearse a failed run on purpose, because confidence in an incremental pipeline comes from seeing it recover correctly from interruptions.
By the end of this project you will have a working, idempotent pipeline and practical experience with incremental loading.
AI Data Readiness. Models are only as good as the data behind them, and readiness is a measurable property, not a feeling. This lecture explains what it means for data to be ready for AI work and how to assemble it into a trustworthy dataset.
Readiness covers several dimensions. Relevance asks whether the data relates to the question. Quality asks whether values are accurate, complete, consistent and current. Coverage asks whether the data represents the situations the system will meet, including rare ones. Provenance asks where the data came from, under what terms and how it was transformed. Governance asks whether its use is permitted, and whether sensitive fields are protected.
You will learn to build a dataset deliberately. Combine sources with clear keys, document each transformation, track versions of the dataset and keep the code that produced it. Split documentation into a data dictionary describing every field and a datasheet describing purpose, collection, known limitations and appropriate uses.
We also discuss testing the dataset. Compute quality metrics, compare distributions across time and groups, check for leakage of future information and verify that labels are reliable. Where possible, make dataset creation a repeatable pipeline instead of a manual task.
Finally, we discuss privacy, including minimizing personal data, masking and retention.
By the end of this lecture you will be able to assess readiness and describe a dataset so that others can trust and reuse it.
Day 20: Data Pipeline Integration — Build a customer intelligence dataset and quality report. Today you combine the skills of this section into one integrated pipeline that produces a documented, quality-checked dataset ready for machine learning.
The steps I would expect you to follow are these. First, choose sources, such as the synthetic customer and order data and a small API-derived table, and define the target dataset, for example one row per customer with behavioral features. Second, build the pipeline: ingest with validation and quarantine, clean missing values and outliers, aggregate features with Pandas or SQL and join the sources while checking row counts. Third, make the pipeline idempotent, with configuration for paths and thresholds and logging for each stage. Fourth, produce a quality report with missingness, duplicates, distributions and a comparison against expectations. Fifth, write a data dictionary and a short datasheet describing purpose, sources, transformations and limitations. Sixth, add tests for the key transformations and run the whole pipeline twice to confirm the results are identical.
Keep all synthetic data and code in version control.
Keep the pipeline code, configuration, quality report and documentation together in version control, since this dataset becomes the foundation for the machine learning projects in the next section of the course.
By the end of this project you will have a complete, documented data pipeline and a trustworthy dataset to carry into the machine learning section.
Supervised Learning and Baselines. Supervised learning is the foundation of most practical machine learning, and good projects begin with careful problem framing and an honest baseline. This lecture introduces both.
In supervised learning, a model learns from examples that pair inputs, called features, with known outcomes, called labels. If the label is a category, such as churned or not churned, the task is classification. If it is a number, such as delivery time, the task is regression. Framing means deciding exactly what to predict, for whom, at what moment and how the prediction will be used. A vague framing produces a model that is technically correct and practically useless.
A baseline is the simplest reasonable approach, such as always predicting the most common class, predicting the average value or applying a simple rule. Baselines matter because they set the standard a model must beat. A model with ninety percent accuracy sounds impressive until you learn that ninety percent of cases belong to one class.
We discuss choosing metrics that match the goal, defining the label carefully, checking that the label is available when needed and identifying who bears the cost of mistakes.
Documenting assumptions early prevents confusion later.
By the end of this lecture you will be able to frame a supervised problem clearly and establish a baseline to measure against.
Day 21: Problem Framing and Baselines — Build a baseline churn classifier. Today you frame a customer churn problem and build the simplest classifiers to establish a baseline before any sophisticated modeling.
The steps I would expect you to follow are these. First, write a short problem statement describing what churn means, the prediction time, the features available at that time and how the prediction would be used. Second, generate or load a synthetic customer dataset with a churn label and several behavioral features. Third, inspect the label balance. Fourth, build baselines: a classifier that always predicts the majority class and a simple rule-based predictor, such as flagging customers with no recent activity. Fifth, evaluate them with accuracy, precision, recall and a confusion matrix, and observe why accuracy alone can mislead on imbalanced data. Sixth, train a simple logistic regression and compare it with the baselines.
Record the results in a table, together with notes on what each metric tells you.
Keep the data split fixed so that later days can reuse the same evaluation.
Keep the baseline results and the exact data version together in version control, so that every later improvement can be compared against a number you trust.
By the end of this project you will have a framed problem, a set of baselines and an evaluation habit that prevents overconfidence.
Evaluation Splits and Data Leakage. A model that looks excellent in testing but fails in production has usually suffered from data leakage. This lecture explains evaluation splits and how to prevent leakage.
We divide data into training, validation and test sets. The training set is used to fit the model, the validation set to compare choices and tune settings and the test set to estimate final performance, used sparingly. Splits must reflect how the model will be used. For time-dependent problems, train on the past and test on the future. For grouped data, such as several records per customer, keep each group entirely on one side of the split.
Leakage occurs when information that would not be available at prediction time influences training or evaluation. Examples include features computed using the whole dataset, labels hidden inside features, duplicates appearing in both training and test sets, and preprocessing statistics learned from the test data. Leakage produces optimistic scores that vanish in practice.
You will learn to detect warning signs, such as suspiciously high performance, features that perfectly predict the label or results that collapse on new data. We also cover fixing random seeds for reproducibility and stratifying splits to preserve class proportions.
The discipline is to treat the test set as untouchable until the end.
By the end of this lecture you will be able to design leakage-resistant splits and recognize common leakage sources.
Day 22: Dataset Splitting and Leakage — Build a leakage-resistant experiment workflow. Today you build a workflow that splits data correctly, detects leakage and records experiments reproducibly.
The steps I would expect you to follow are these. First, create a synthetic dataset with a time column, repeated customers and a deliberately leaky feature, such as one derived from the outcome. Second, implement random, stratified, grouped and time-based splits, and compare how each distributes classes and customers. Third, write checks that detect leakage symptoms: overlap of identifiers between train and test sets, features with near-perfect correlation to the label and preprocessing fitted on the wrong data. Fourth, train a model with and without the leaky feature and observe the difference in scores. Fifth, record each experiment with its random seed, split method, features, parameters and metrics in a log file. Sixth, write tests confirming that the splits do not share groups and that the time split respects order.
Write a short note explaining which split suits the problem and why.
Write down which columns were excluded and why, and keep that note beside the experiment records, so that a teammate can repeat your reasoning without asking you.
By the end of this project you will have a reusable experiment workflow and a practical sense of how leakage inflates results.
Feature Preprocessing Pipelines. Raw columns rarely suit a model directly. Numbers need scaling, categories need encoding and missing values need handling. This lecture explains how to build preprocessing pipelines that are consistent and leakage-safe.
Different column types need different treatments. Numeric columns may be imputed and scaled. Categorical columns may be encoded as one-hot indicators or ordinal codes, with a plan for categories unseen during training. Text columns need vectorization. Date columns can be expanded into useful parts. Treating each type with the right transformer keeps the process organized.
A pipeline chains these steps with the model, so that fitting and prediction apply the same sequence every time. The crucial property is that transformations are learned from training data only and then applied unchanged to validation, test and production data. When you wrap preprocessing and the model in one object, cross-validation automatically refits the transformations inside each fold, which prevents leakage.
You will learn column transformers, handling of unknown categories, feature names after encoding and saving the fitted pipeline as a single artifact. We also discuss keeping the logic simple and inspectable, so that you can explain why the model sees what it sees.
Pipelines reduce training and serving mismatches, a common source of production bugs.
By the end of this lecture you will be able to design unified preprocessing and model pipelines.
Day 23: Feature Preprocessing — Build a preprocessing and prediction pipeline. Today you assemble a pipeline that prepares mixed numeric and categorical features and produces predictions through one consistent object.
The steps I would expect you to follow are these. First, create or reuse a synthetic dataset with numeric, categorical and date columns and some missing values. Second, split the data before any fitting. Third, define transformers: imputation and scaling for numeric columns, imputation and one-hot encoding for categorical columns and date-part extraction for dates, with handling for unknown categories. Fourth, combine them using a column transformer and attach a model to form a single pipeline. Fifth, fit on the training set, predict on the test set and inspect the transformed feature names. Sixth, save the fitted pipeline, reload it and confirm that it produces identical predictions, then test it on a record containing a category it has never seen.
Compare the result with a manual approach that fits transformations on all the data, and explain why the manual approach is risky.
Add tests for the shape and content of the transformed data.
Keep the fitted pipeline and its configuration together, so that training and prediction can never drift apart without anyone noticing.
By the end of this project you will have a robust preprocessing pipeline and a clear understanding of how it prevents leakage.
Regression and Prediction Error. Many business questions ask how much or how long, which are regression problems. This lecture explains regression models and how to measure and interpret prediction error.
Linear regression predicts a number as a weighted combination of features and is a strong, interpretable starting point. Regularized versions add a penalty on large weights to reduce overfitting. Tree-based models capture nonlinear relationships and interactions at the cost of some interpretability. Which model suits a problem depends on data size, relationships and the need to explain results.
Error metrics describe how wrong predictions are. Mean absolute error reports the average size of mistakes in the original units, which is easy to explain. Mean squared error and its root penalize large errors more heavily. R-squared describes the share of variation explained, but can mislead when used alone. Choose metrics that reflect the cost of errors in the real setting: being late by an hour may matter more than being early.
We discuss examining residuals, which are the differences between predictions and actual values, to find patterns such as larger errors for certain groups, curved relationships the model missed or outliers that dominate training.
Always compare against a baseline, such as predicting the average, and report uncertainty honestly.
By the end of this lecture you will be able to choose regression models, evaluate them with suitable metrics and analyze errors.
Day 24: Regression Models — Build a delivery-time estimator. Today you build a model that estimates delivery times and analyze how and where it makes mistakes.
The steps I would expect you to follow are these. First, create a synthetic dataset of deliveries with distance, package weight, time of day, weather category, courier experience and the actual delivery duration, including some noise and a few extreme cases. Second, split the data and establish a baseline that predicts the average duration. Third, build a preprocessing pipeline and train a linear regression and a tree-based model. Fourth, evaluate with mean absolute error, root mean squared error and R-squared, and compare against the baseline. Fifth, analyze residuals: plot errors against predicted values and against key features, and identify groups with larger errors. Sixth, write a short report explaining which model you would choose, how large the typical error is in minutes and what limitations users should know.
Include a prediction function that returns an estimate with a simple error range based on validation results.
Review the largest errors by hand and note any pattern you see, because those examples often reveal missing features or data problems that a single score hides.
By the end of this project you will have a tested estimator and practical skill in evaluating regression models.
Text Classification. Much valuable information arrives as text, and turning text into predictions is a classic machine learning task. This lecture introduces text classification, from simple representations to evaluation.
Models need numbers, so text must be converted into numerical features. Bag-of-words representations count how often each word appears. Term frequency weighting emphasizes words that are distinctive for a document instead of common across all documents. Character n-grams capture spelling patterns and help with misspellings. Later in the course you will meet embeddings, which represent meaning more richly.
A linear classifier trained on weighted word counts is a surprisingly strong baseline for tasks such as routing support tickets, tagging documents or detecting topics. It is fast, inexpensive and relatively interpretable, since you can inspect which words push predictions toward each class.
We discuss the practical details: cleaning and tokenization choices, handling rare and common words, dealing with imbalanced categories, evaluating with per-class precision and recall and examining confusion between classes. Always read misclassified examples, since they reveal label noise, ambiguous categories and missing data.
Labels deserve scrutiny. Inconsistent human labeling limits what any model can achieve, and categories should have clear definitions.
By the end of this lecture you will be able to build, evaluate and interpret a baseline text classifier.
Day 25: Classification Models — Build a support-ticket priority classifier. Today you build a classifier that assigns priority levels to synthetic support tickets and evaluate it with care.
The steps I would expect you to follow are these. First, create a synthetic set of support tickets with text, a product area and a priority label of low, medium or high, including some ambiguous cases. Second, split the data in a stratified way. Third, build a text pipeline using term-frequency weighting and a linear classifier, and compare it with a majority-class baseline. Fourth, evaluate with per-class precision, recall and a confusion matrix, and discuss which mistakes are most costly, for example missing a high-priority ticket. Fifth, inspect the most influential words for each class and read a sample of misclassified tickets to understand the errors. Sixth, try class weighting and compare the effect on recall for the high-priority class.
Write a short note describing the model's limitations and how a person would remain in the loop.
Use only synthetic ticket text, with no real customer content.
Look at the confusion between neighboring priority levels separately from larger mistakes, since an error of one level usually costs far less than an error of three.
By the end of this project you will have a working text classifier and a more critical way of reading classification results.
Decision Thresholds and Error Costs. A classifier usually outputs a score, and a threshold turns that score into a decision. This lecture explains how thresholds, error costs and business goals determine what a good model means.
Most classifiers estimate a probability or a score. With a threshold of one half, a case is flagged when the score exceeds that value. Lowering the threshold catches more true cases but also raises false alarms. Raising it reduces false alarms but misses more true cases. The trade-off is captured by precision, which asks how many flagged cases were correct, and recall, which asks how many true cases were found.
Different applications weigh errors differently. Missing a fraud case may cost far more than reviewing a false alarm. Flagging too many customers for outreach may waste budget. Therefore, the best threshold depends on costs, capacity and risk tolerance, not on a default number.
You will learn precision-recall curves, receiver operating characteristic curves and how to choose a threshold by minimizing expected cost or meeting a recall target. We discuss calibration, which asks whether a score of eighty percent really corresponds to being right about eighty percent of the time, and why it matters for decisions.
Communicate trade-offs to stakeholders in plain language, using examples and counts.
By the end of this lecture you will be able to select thresholds that match business goals.
Day 26: Business-Aligned Evaluation — Build a decision-threshold comparison tool. Today you build a tool that compares thresholds using costs that reflect a business scenario.
The steps I would expect you to follow are these. First, choose a scenario, such as flagging transactions for review, and define the costs: the cost of reviewing a flagged case, the cost of missing a true case and the benefit of catching one. Second, train a classifier on synthetic data and obtain predicted probabilities on a validation set. Third, evaluate many thresholds, computing precision, recall, counts of each error type and the total expected cost at each. Fourth, plot precision-recall trade-offs and the cost curve, and mark the threshold with the lowest cost and the threshold that meets a minimum recall requirement. Fifth, check calibration by comparing predicted probabilities with observed frequencies. Sixth, write a recommendation that explains the chosen threshold, the expected number of reviews and the cases that will still be missed.
Make the tool configurable so the costs can be changed and the recommendation recalculated.
Record the cost assumptions you used beside each result, so that a reader can change those numbers later and understand exactly why the preferred threshold moved.
By the end of this project you will have a decision-support tool and a business-oriented view of model evaluation.
Cross-Validation and Hyperparameter Selection. A single train and validation split can be misleading, especially with small datasets. This lecture explains cross-validation and hyperparameter selection as ways to compare models more reliably.
In k-fold cross-validation, the data is divided into k parts. The model is trained on k minus one parts and evaluated on the remaining one, repeating so that each part serves once as validation. The average score and its spread give a more stable estimate of performance and reveal how sensitive the result is to the split. Stratified and grouped versions preserve class proportions and keep related records together.
Hyperparameters are settings chosen before training, such as the strength of regularization or the depth of a tree. Search methods, such as grid search and randomized search, try combinations and select the best by cross-validated score. This should always happen inside the training data, with a separate test set held back for the final estimate, since tuning on the test set makes the estimate optimistic.
We discuss the risks of overfitting to the validation process, the cost of extensive searches, the importance of comparing against simple baselines and the value of choosing simpler models when scores are similar.
Record every comparison so that results can be reproduced.
By the end of this lecture you will be able to use cross-validation and tuning responsibly.
Day 27: Cross-Validation and Tuning — Build a model comparison report. Today you build a report that compares several models fairly using cross-validation and systematic tuning.
The steps I would expect you to follow are these. First, select a dataset, such as the churn data from earlier, and hold out a final test set. Second, define a set of candidate models, including a baseline, a regularized linear model and a tree-based ensemble, each inside a pipeline that includes preprocessing. Third, evaluate each with stratified cross-validation, recording the mean and standard deviation of several metrics. Fourth, tune key hyperparameters with a randomized or grid search inside cross-validation. Fifth, compare the results in a table and a chart that show both average performance and variability, and note training time. Sixth, evaluate only the chosen model on the test set and report the result, along with a discussion of whether differences between candidates are meaningful.
Fix random seeds and save the configuration so the experiment can be repeated.
Write a short recommendation that considers accuracy, interpretability and cost.
Keep the random seeds and the fold definitions recorded with each result, so that a colleague repeating the comparison gets the same numbers and can trust the ranking.
By the end of this project you will have a reproducible comparison report and a disciplined approach to model selection.
Unsupervised Learning and Clustering. Not all data comes with labels. Unsupervised learning looks for structure without them. This lecture introduces clustering and how to use and evaluate it responsibly.
Clustering groups similar items together. K-means partitions data into a chosen number of groups around centers, and works best with roughly round, similarly sized clusters on scaled features. Hierarchical clustering builds a tree of merges that can be cut at different levels. Density-based methods find groups of arbitrary shape and treat sparse points as noise. Each method embeds assumptions about what similar means.
Preparing data matters greatly. Features must be scaled so that no single feature dominates distance, irrelevant features can obscure structure and categorical variables need suitable handling. Dimensionality reduction can help visualize results.
Evaluation is difficult because there is no single correct answer. Internal measures, such as silhouette scores, describe how well separated the groups are. Stability checks ask whether clusters persist across samples and settings. The most important test is usefulness: do the groups make sense, are they distinguishable in meaningful ways and do they support a decision?
We discuss choosing the number of clusters, naming and profiling segments and the danger of reading too much into groups that may be artifacts.
By the end of this lecture you will be able to apply clustering and judge whether the result is meaningful.
Day 28: Clustering — Build a customer segmentation explorer. Today you build a tool that segments customers into groups and helps people explore what distinguishes each group.
The steps I would expect you to follow are these. First, use the customer features from earlier days or a synthetic dataset with behaviors such as frequency, spend, recency and product variety. Second, scale the features and examine their distributions. Third, run k-means for several values of k, and compare inertia and silhouette scores, then examine hierarchical clustering as an alternative. Fourth, check stability by repeating with different random seeds and subsets. Fifth, profile each cluster by computing average feature values and sizes, give each a descriptive name and visualize the groups with a two-dimensional projection. Sixth, write a short guide explaining how each segment might be treated differently by the business, while noting that segments are a simplification.
Package the exploration as a script or notebook that lets a user change the number of clusters and see the profiles update.
Use synthetic data with no real personal information.
Try more than one number of groups and compare how stable the segments remain between runs, because groups that change with every run are rarely worth acting upon.
By the end of this project you will have a segmentation explorer and a realistic understanding of the strengths and limits of clustering.
Anomaly Scores and Human Review. Some of the most important cases are rare and unusual. Anomaly detection aims to find them, and in most real systems a person ultimately decides what to do. This lecture covers scores, thresholds and review workflows.
Anomaly detection methods learn what normal looks like and score how far each case deviates. Statistical approaches flag values far from the mean or outside percentile ranges. Isolation-based methods find points that are easy to separate from the rest. Distance and density methods compare each point with its neighbors. Reconstruction-based methods flag cases a model cannot reproduce well.
Anomalous does not mean bad. An unusual purchase might be fraud, or a legitimate special event. Therefore scores should prioritize cases for review instead of making final decisions. The threshold determines how many cases reviewers receive, so it must reflect their capacity and the cost of misses.
Evaluation is difficult because labeled anomalies are scarce. Use whatever labels exist, plant synthetic anomalies to test detection and measure how many reviewers' findings turn out to be useful. Monitor drift, since what is normal changes over time.
We discuss explanations that help reviewers, such as which features were unusual, and feedback loops that let reviewers' decisions improve the system.
By the end of this lecture you will be able to design anomaly scoring integrated with human review.
Day 29: Anomaly Detection — Build an unusual-transaction review tool. Today you build a tool that scores transactions for unusualness and presents the most suspicious ones to a reviewer with explanations.
The steps I would expect you to follow are these. First, generate a synthetic transaction dataset with amounts, times, merchant categories and customer histories, and plant a number of known anomalies. Second, engineer features that capture unusualness relative to each customer's history, such as amount compared with the customer's average. Third, apply two methods, for example a statistical rule and an isolation-based model, and produce anomaly scores. Fourth, choose a threshold based on a review capacity, such as fifty cases per day, and measure how many planted anomalies appear in the review queue. Fifth, create a review report listing each flagged transaction with its score and the features that contributed most. Sixth, simulate reviewer feedback by marking cases as confirmed or dismissed and compute the review precision.
Discuss what the tool should not do, such as taking automatic action against customers.
Use only synthetic transactions.
Keep a short log of reviewer decisions about each flagged item, so that you can later measure how often the highest scores led to genuinely useful findings.
By the end of this project you will have a scoring and review workflow and a practical understanding of anomaly detection limits.
Model Artifacts and Batch Inference. A trained model is only useful when it can be saved, loaded and applied reliably. This lecture explains model artifacts, versioning and batch inference.
A model artifact includes the fitted preprocessing and model, plus metadata: the training data version, feature list and order, library versions, parameters, evaluation results and creation date. Saving only the model without its preprocessing is a classic cause of production errors. Saving a whole pipeline as one object avoids mismatches.
You will learn to serialize pipelines, store them with version identifiers and verify after loading that predictions match the original. We discuss security, because loading serialized objects from untrusted sources can execute harmful code, so only load artifacts you created or trust, and prefer safe formats where available.
Batch inference applies a model to many records at once, such as scoring all customers nightly. A good batch job validates the input schema, handles missing or unexpected values, produces outputs with identifiers and timestamps, records the model version used and logs counts and failures. Outputs should be reproducible and traceable back to the model and data that created them.
We also cover monitoring, such as score distributions over time, which can reveal data drift or pipeline problems.
By the end of this lecture you will be able to package models and run dependable batch predictions.
Day 30: Model Persistence and Inference — Build a batch prediction application. Today you finish the machine learning section by packaging a trained model and building an application that scores a file of new records safely.
The steps I would expect you to follow are these. First, train a pipeline on synthetic data and evaluate it. Second, save it with a metadata file describing the model version, training date, feature names, library versions and evaluation metrics. Third, write a command-line application that loads the artifact, reads a CSV file of new records, validates the schema and values, and produces predictions with probabilities. Fourth, handle invalid rows by writing them to a rejected file with reasons. Fifth, write an output file containing identifiers, predictions, scores, the model version and a timestamp, and log summary counts. Sixth, test the application with valid data, missing columns, unexpected categories and an empty file, and confirm that results match those from the original session.
Add a simple check that compares the distribution of new scores with the training distribution and warns about large shifts.
Keep the saved model, its version and a short usage note together so that a colleague can run it without guessing.
By the end of this project you will have a complete, traceable batch prediction application and a solid base for the deep learning section.
Neural Networks and Nonlinear Representations. Linear models draw straight boundaries, but many real problems are not that tidy. This lecture introduces neural networks as a way to learn nonlinear patterns by stacking simple computations, and it sets the foundation for everything from image models to language models later in the course.
A neuron computes a weighted sum of its inputs, adds a bias and passes the result through an activation function. On its own that is just a linear model with a bend. The power comes from layers: the outputs of one layer become the inputs of the next, so the network can build intermediate representations. Early layers might capture simple combinations of features, while later layers combine those into more abstract signals useful for the final prediction.
We discuss why activation functions matter. Without a nonlinearity, any number of stacked layers collapses into a single linear transformation. Common choices such as ReLU, sigmoid and tanh behave differently, and we look at where each is useful and what problems they can cause, such as saturation.
You will also learn the vocabulary of inputs, hidden layers, outputs, weights, parameters and loss, and how a forward pass turns an input into a prediction. We discuss how output layers and loss functions differ for regression and classification, and why small networks on tabular data are a sensible place to begin.
By the end of this lecture you will be able to explain how a neural network represents nonlinear patterns and describe the parts of a simple network.
Day 31: Neural Network Fundamentals — Build a neural classifier for tabular data. Today you build and train a small neural network on a synthetic tabular dataset and compare it honestly with a simpler baseline.
The steps I would expect you to follow are these. First, create a synthetic classification dataset with a nonlinear pattern, such as two interleaved groups that a straight line cannot separate, and split it into training, validation and test portions. Second, build a baseline using a linear model and record its score. Third, define a small neural network with one or two hidden layers, choose an activation function and select a loss function appropriate for classification. Fourth, train it for a modest number of epochs, printing the training and validation loss as you go. Fifth, evaluate it on the held-out test portion and compare it with the baseline using the same metrics. Sixth, visualize the decision boundary for the two-feature case, so you can see what the network learned that the linear model could not.
Experiment with the number of hidden units and observe how capacity changes the result. Set random seeds so your runs are reproducible.
Keep the dataset generator, the training script and the recorded scores together, so that you can rerun the comparison whenever you change the network.
By the end of this project you will have trained your first neural classifier and understand when it beats a simple baseline and when it does not.
Optimization and Generalization Diagnostics. Training a neural network is an optimization problem, and a network that fits its training data perfectly can still fail on new data. This lecture explains how learning actually proceeds and how to diagnose whether a model is learning something useful.
We begin with gradient descent. The loss measures how wrong the predictions are, the gradient shows which direction in parameter space increases that loss, and the optimizer takes small steps in the opposite direction. The learning rate controls the step size: too large and training oscillates or diverges, too small and progress is painfully slow. We look at mini-batches, epochs and common optimizers such as stochastic gradient descent with momentum and Adam, and discuss what each adds.
Next we turn to generalization. Plotting training and validation loss over time is the most useful diagnostic you have. When both are high, the model is underfitting. When training loss keeps falling while validation loss rises, the model is overfitting. We discuss remedies, including more data, simpler models, regularization such as weight decay and dropout, and early stopping.
We also cover practical failure signs, such as loss that becomes not-a-number, loss that never moves and unstable gradients, along with the first things to check in each case.
By the end of this lecture you will be able to read training curves and choose sensible remedies for common training problems.
Day 32: Training Loops and Diagnostics — Build a training performance dashboard. Today you write a training loop that records what happens during learning and turn those records into a simple dashboard.
The steps I would expect you to follow are these. First, reuse a small synthetic dataset and a simple neural network from the previous day. Second, write an explicit training loop that processes mini-batches, computes the loss, updates parameters and tracks metrics for each epoch. Third, record training loss, validation loss, a task metric and the learning rate in a structured log file. Fourth, add early stopping that halts training when validation loss stops improving and restores the best parameters. Fifth, build a dashboard that plots the curves and summarizes the run, including the best epoch and final scores. Sixth, run several experiments with different learning rates and regularization settings, and use the dashboard to explain which runs overfit, which underfit and which are healthy.
Add a check that warns when the loss becomes not-a-number so that a broken run is noticed immediately rather than after an hour of wasted computing.
Keep each run's configuration and log together, so that you can reproduce any chart later and compare experiments fairly.
By the end of this project you will have a reusable training loop and a dashboard that makes training behavior visible and easier to reason about.
Transfer Learning for Computer Vision. Training an image model from scratch needs enormous amounts of data and computing power. Transfer learning lets you start from a model that has already learned useful visual features and adapt it to your own task with far fewer examples.
Convolutional networks and related vision models learn hierarchies of features. Early layers detect edges and textures, middle layers detect parts and shapes, and later layers detect task-specific concepts. Because the early and middle features are general, they transfer well to new problems. A pretrained model, trained on a large public image collection, therefore offers a strong starting point.
We discuss the two main strategies. In feature extraction, you freeze the pretrained layers and train only a new final layer on your own classes. In fine-tuning, you also update some or all of the pretrained layers using a small learning rate. We discuss when each is appropriate, depending on how much data you have and how similar it is to the original training data.
You will learn about preparing images, including resizing, normalization to match the pretrained model and data augmentation to add variety. We also discuss evaluation, class imbalance and the importance of checking the license and intended use of any pretrained model.
By the end of this lecture you will be able to adapt a pretrained vision model to a small custom image task.
Day 33: Image Transfer Learning — Build an image classifier with a pretrained model. Today you adapt a pretrained vision model to classify a small set of images using synthetic or openly licensed sample data.
The steps I would expect you to follow are these. First, prepare a small image dataset organized into one folder per class, using generated shapes or openly licensed pictures, and split it into training, validation and test portions. Second, load a pretrained vision model and replace its final layer with one that matches your number of classes. Third, apply the preprocessing the pretrained model expects, and add light augmentation to the training images. Fourth, train first with the pretrained layers frozen, then optionally fine-tune with a lower learning rate. Fifth, evaluate on the test images, produce a confusion matrix and inspect examples that were misclassified. Sixth, compare your result with a tiny model trained from scratch to see the benefit of transfer.
Write down the model name, version and license you used, since pretrained models carry terms of use that matter later.
Keep the class list, the preprocessing settings and the saved model together, so that predictions remain consistent when you reload the classifier in a later project.
By the end of this project you will have a working image classifier built on a pretrained model and a clear sense of why transfer learning is so effective.
Pretrained Language Models. Modern language technology rests on models that have already read enormous quantities of text. This lecture explains how pretrained language models work at a practical level and how you can reuse them for tasks such as classification without training anything from scratch.
Text must first become numbers. A tokenizer splits text into tokens, which may be words or pieces of words, and maps each to an identifier. A model then converts those identifiers into vectors and processes them using transformer layers, whose attention mechanism lets every token consider the others in the sequence. During pretraining, the model learns general language patterns by predicting missing or next tokens across vast text collections.
We discuss the main families. Encoder models are well suited to understanding tasks, such as classification and similarity, and decoder models are well suited to generating text. We look at how a pretrained encoder with a small classification layer can label sentiment, topics or intent with limited data.
You will learn about model hubs, model cards, licenses and sizes, and how to trade accuracy against speed and cost. We also discuss limitations, including bias inherited from training data, sensitivity to the domain of the text and the importance of evaluating on your own examples rather than trusting a benchmark.
By the end of this lecture you will be able to choose and apply a pretrained language model for a text task.
Day 34: Pretrained Text Classification — Build a sentiment-analysis application. Today you use a pretrained language model to classify the sentiment of synthetic product reviews and wrap it in a small application.
The steps I would expect you to follow are these. First, create a synthetic set of short product reviews labeled positive, negative or neutral, including some tricky cases such as sarcasm, negation and mixed opinions. Second, load a pretrained text classification model and run it on a few examples to inspect its raw outputs and confidence scores. Third, evaluate it on your labeled reviews, reporting accuracy and per-class results, and examine the errors. Fourth, build a small command-line or web application that accepts text and returns a label with a confidence score. Fifth, handle edge cases, such as empty input, very long text and unexpected characters. Sixth, decide on a confidence threshold below which the application reports that it is unsure rather than guessing.
Discuss in your notes where the model is likely to be unreliable, such as domain-specific language or text that differs from its training data.
Keep the evaluation set, the model name and the application code together, so that you can rerun the same checks whenever you change models.
By the end of this project you will have a sentiment application and a realistic view of what pretrained text models can and cannot do.
Embeddings and Vector Similarity. Embeddings turn text, images or other content into lists of numbers in which similar meanings end up close together. They are the foundation of semantic search, recommendation and retrieval-augmented generation, which you will build later in this course.
An embedding model maps an input to a vector with hundreds or thousands of dimensions. Each dimension has no simple human meaning, but the overall geometry is informative. Sentences about related topics tend to lie near each other, even when they share no words. This is what lets a search for refund policy find a document about returning purchases.
We discuss how to measure closeness. Cosine similarity compares the angle between vectors and is widely used because it ignores length. Dot product and Euclidean distance are alternatives, and we explain when each is appropriate and why normalizing vectors can make them equivalent.
You will learn practical points, including that you must use the same embedding model for documents and queries, that embeddings are tied to a specific model version and must be regenerated if you change it, and that long texts are usually split into smaller pieces before embedding. We also discuss cost, batching, caching and the limits of similarity, which captures topical closeness but not necessarily correctness.
By the end of this lecture you will be able to generate embeddings and compare them meaningfully.
Day 35: Text Embeddings — Build a sentence similarity explorer. Today you build a tool that embeds sentences and lets a user explore which ones are most similar to a query.
The steps I would expect you to follow are these. First, assemble a small collection of synthetic sentences covering several topics, including near-duplicates, paraphrases and sentences that share words but differ in meaning. Second, generate an embedding for each sentence using an embedding model, and store the vectors with their text and an identifier. Third, implement cosine similarity and a function that ranks all sentences against a query. Fourth, build a simple interface that accepts a query and displays the top matches with their scores. Fifth, test tricky cases, such as negation, synonyms and unrelated sentences, and note where similarity helps and where it misleads. Sixth, reduce the vectors to two dimensions and plot them, so you can see clusters of related sentences.
Cache the embeddings so that repeated runs do not recompute them, and record the model name alongside the saved vectors.
Keep the sentence collection, the cached vectors and your notes about surprising results together, since they will make a useful test fixture for the search projects that follow.
By the end of this project you will have a working similarity explorer and a practical feel for how embeddings behave.
Semantic Retrieval. Keyword search matches the words you type, while semantic retrieval matches the meaning behind them. This lecture shows how embeddings are combined with a document collection to build search that understands intent, and where it can go wrong.
The basic pipeline has two phases. During indexing, documents are divided into passages, each passage is embedded and the vectors are stored along with the original text and metadata. During querying, the user's question is embedded with the same model, the most similar passage vectors are found and the matching passages are returned in ranked order.
We discuss the main design decisions. Passage size matters: tiny passages lose context, while huge ones blur several topics together. The number of results to return, often called top-k, trades coverage against noise. A similarity cutoff can prevent the system from returning weak matches when nothing relevant exists.
You will learn about typical failure modes. Semantic search can retrieve text that sounds related but does not answer the question, can miss exact identifiers such as product codes and can behave differently across languages. We also look at how to inspect results and why showing the source of every result builds trust.
By the end of this lecture you will be able to explain a semantic retrieval pipeline and identify its strengths and limitations.
Day 36: Semantic Search — Build a searchable FAQ collection. Today you build a search application over a synthetic collection of frequently asked questions and answers.
The steps I would expect you to follow are these. First, write or generate a collection of synthetic FAQ entries about a fictional service, including several that are closely related and a few that are deliberately unrelated. Second, embed each entry and store the vectors with the original text and an identifier. Third, implement a search function that embeds a query, ranks entries by similarity and returns the top results with scores. Fourth, add a similarity cutoff so that the application says no good match was found when a query is far from everything in the collection. Fifth, prepare a list of test queries, including paraphrases, typos and questions with no answer, and record what the application returns. Sixth, present the results in a simple interface that shows the matching question, its answer and its score.
Review the failures honestly and consider whether better wording, different passage design or a different cutoff would help.
Keep the FAQ data, the test queries and the expected results together, so that you can rerun them as a regression check when you improve the search.
By the end of this project you will have a working semantic search application and a small test set that measures its quality.
Vector Index Lifecycle. A pile of vectors in a file is not yet a search system. This lecture covers how vector indexes are built, stored, updated and maintained so that retrieval stays fast, accurate and consistent as the underlying content changes.
At small scale you can compare a query with every vector, which is simple and exact. As collections grow, this becomes too slow, so indexes use approximate nearest-neighbor methods that trade a little accuracy for large speed gains. We discuss the general ideas behind graph-based and clustering-based indexes, and the parameters that control the balance between speed, memory and recall.
The lifecycle matters as much as the algorithm. Documents are added, changed and removed, so the index needs a plan for inserts, updates and deletions. Embeddings must be regenerated when the embedding model changes, which usually means building a new index and switching over once it is ready. Each vector should carry an identifier, a source reference and a version so that you can trace results and clean up stale entries.
We also discuss persistence, backups, concurrency and how to confirm that an index is healthy, using counts, sample queries and recall checks against exact search.
By the end of this lecture you will be able to describe how a vector index is created and maintained over time and choose sensible settings for a small project.
Day 37: Vector Indexing — Build a persistent document search index. Today you build an index that survives restarts and can be updated as documents change.
The steps I would expect you to follow are these. First, prepare a small synthetic document collection with identifiers, titles, text and a version number for each document. Second, split the documents into passages and embed them, storing each vector with its document identifier, passage position and content hash. Third, build an index using a vector store or library and save it to disk. Fourth, write a loading routine that restores the index on startup and confirms that the stored counts match what you expect. Fifth, implement updates, so that a changed document replaces its old passages, and deletions, so that removed documents disappear from results. Sixth, compare the approximate search results with exact search on a sample of queries to estimate how much accuracy you are trading for speed.
Add a rebuild command for the case where you change the embedding model, and record the model name inside the index metadata.
Keep the build script, the stored index and the check results together, so that anyone can recreate the index from the source documents and confirm that it matches.
By the end of this project you will have a persistent, updatable search index and the habits needed to keep it trustworthy.
Retrieval Eligibility and Metadata Filters. Similarity alone is not enough to decide what a search should return. A result might be the closest match yet be out of date, belong to another department or be something the user is not allowed to see. This lecture shows how metadata filters make retrieval relevant and safe.
Every stored passage can carry metadata, such as department, document type, language, date, status and an owner or access group. At query time, filters restrict which passages are eligible before or during the similarity search. This lets you answer questions such as finding only current policies for a given team or excluding drafts and archived material.
We discuss where filtering belongs. Applying filters inside the search is generally better than retrieving results first and removing them afterward, because the latter can leave you with too few results. We discuss the difficulty of combining strict filters with approximate indexes and how to verify that the filtered results still make sense.
Eligibility is also a governance matter. Access rules must be enforced by the system, not left to the user's request or to a language model's judgment. You will learn how to design metadata consistently, validate it at ingestion time and test that filters really exclude what they should.
By the end of this lecture you will be able to design metadata and apply filters that make retrieval both more relevant and more controlled.
Day 38: Metadata Filtering — Build a department-filtered search application. Today you extend your search index with metadata and build an application that returns only results the chosen department is eligible to see.
The steps I would expect you to follow are these. First, create a synthetic document collection for a fictional company, with documents assigned to departments such as finance, engineering and human resources, plus a few shared documents and some marked as draft or archived. Second, validate the metadata at ingestion, rejecting records with missing or unexpected values. Third, store the metadata with each passage in the index. Fourth, implement search that accepts a query and a department, applying the filter during retrieval rather than afterward. Fifth, write tests with queries designed to tempt the search into returning another department's material, and confirm that none appears. Sixth, add a check for the case where the filter leaves no eligible results, so that the application says so clearly instead of showing weak matches.
Log which filters were applied to each search so that behavior can be audited later.
Keep the test queries and expected exclusions together with the code, so that every future change to the index is checked against them automatically.
By the end of this project you will have a filtered search application and a repeatable test proving that its restrictions actually work.
Hybrid Search and Rank Fusion. Semantic search and keyword search have complementary strengths. Semantic methods understand meaning but may miss exact terms, while keyword methods match precise words, names and codes but miss paraphrases. Hybrid search combines both, and this lecture explains how.
On the keyword side, we introduce lexical ranking methods such as BM25, which score documents by how often query terms appear, how rare those terms are across the collection and how long the document is. These are fast, transparent and excellent for identifiers, error messages and specialized vocabulary.
The challenge is combining two ranked lists whose scores are on different scales. Adding raw scores is unreliable. Rank fusion methods such as reciprocal rank fusion avoid the problem by using only each result's position in each list, giving a high combined score to items that appear near the top of both. We also discuss weighted blending after normalization and how to tune the weights.
You will learn how to decide when hybrid search is worth the extra complexity, how to examine which retriever contributed each result and how to avoid duplicates when the same passage appears in both lists. We also discuss the importance of testing on queries that reflect real usage.
By the end of this lecture you will be able to explain and design a hybrid retrieval approach.
Day 39: Hybrid Retrieval — Build combined keyword and vector search. Today you combine a keyword ranker with your vector search and merge their results.
The steps I would expect you to follow are these. First, use a synthetic document collection that includes exact identifiers, such as invented product codes, alongside natural-language descriptions. Second, implement a keyword search using a lexical ranking method, and confirm that it finds exact codes easily. Third, reuse your vector search and confirm that it handles paraphrased questions well. Fourth, implement reciprocal rank fusion to merge the two ranked lists, removing duplicates and keeping track of which retriever found each result. Fifth, prepare a set of queries of three kinds, namely exact-term, paraphrased and mixed, and compare keyword-only, vector-only and hybrid results for each. Sixth, experiment with the fusion constant and with weighting, and record how the results change.
Display the contribution of each retriever beside every result so that the ranking can be explained to someone else.
Keep the queries, the expected best results and the comparison table together, because they form a benchmark that you will extend in the next project.
By the end of this project you will have a working hybrid search and evidence of where it outperforms either method alone.
Retrieval Evaluation. A search system that feels good in a demonstration may still fail on real questions. This lecture explains how to measure retrieval quality objectively, so that improvements are real and regressions are caught before users notice them.
The starting point is an evaluation set: a collection of realistic queries, each paired with the passages or documents that should be returned. Building it takes effort, but it is the most valuable asset in any retrieval project. Good sets include easy, hard and unanswerable questions, and cover the variety of ways people phrase a need.
We introduce the standard metrics. Recall at k asks whether a relevant item appears in the top k results. Precision at k asks how many of the top k are relevant. Mean reciprocal rank rewards placing the first relevant result high, and normalized discounted cumulative gain handles graded relevance. We discuss what each metric tells you and which fits which use case.
You will also learn to compare strategies fairly, using the same queries and settings, and to inspect failures one by one rather than relying only on averages. We discuss avoiding overfitting to a small evaluation set and keeping a held-out portion.
By the end of this lecture you will be able to design an evaluation set and compute and interpret retrieval metrics.
Day 40: Search Evaluation — Build a retrieval strategy benchmark. Today you finish the search section by building a benchmark that compares your retrieval strategies on the same questions.
The steps I would expect you to follow are these. First, extend the synthetic collection from the previous projects and write a set of queries with the passages that should be returned, including some questions that have no answer in the collection. Second, implement functions for recall at k, precision at k and mean reciprocal rank. Third, run keyword search, vector search, hybrid search and filtered search against the same queries and collect the results in a single table. Fourth, produce a report that shows each metric for each strategy and highlights the queries where the strategies disagree. Fifth, inspect the worst failures by hand and categorize them, for example as vocabulary mismatch, poor passage boundaries or missing metadata. Sixth, make one improvement, rerun the benchmark and confirm that the numbers moved in the direction you expected.
Hold back a portion of the queries so that you do not tune only to the examples you have been looking at.
Keep the evaluation set, the benchmark script and the saved reports together, so that you can compare future versions of your search against today's results.
By the end of this project you will have a repeatable retrieval benchmark and the discipline of improving search with evidence rather than impressions.
LLM Inference and Model Abstraction. Large language models are used through a simple-looking interaction, yet a production application needs more than a single call to a vendor library. This lecture introduces what happens during inference and why you should place a thin abstraction between your application and any specific model provider.
At inference time, you send a request containing messages, instructions and settings, and the model returns generated text along with usage information. Important settings include the model name, the maximum number of output tokens, and sampling controls such as temperature, which changes how varied the output is. We discuss what each setting does and why lower randomness is usually preferable for tasks that need consistency.
The risk of calling a provider directly from everywhere in your code is that every change, such as a new model, a different vendor or a changed response format, ripples through the whole application. A model client interface solves this. Your application asks for a completion through one internal function, and the client handles authentication, request formatting, response parsing, errors and logging.
We also introduce mock mode. A fake client returns predictable responses, so you can develop, test and demonstrate without network access, cost or variability. This makes automated tests fast and repeatable.
By the end of this lecture you will be able to explain the pieces of an inference request and design a model client with a mock option.
Day 41: Model Clients — Build a configurable model client with a mock mode. Today you build the interface your later projects will use to talk to language models.
The steps I would expect you to follow are these. First, define a small request and response structure that includes messages, model name, temperature, output limit, the generated text and token usage. Second, create a client interface with a single method for generating a response. Third, implement a real client that reads its settings and credentials from environment variables, never from source code. Fourth, implement a mock client that returns deterministic canned responses, including the ability to simulate an error, so that tests can exercise failure handling. Fifth, add configuration that selects the client, with the mock chosen by default so that the project runs without any credentials. Sixth, write tests that confirm both clients return the same response structure and that missing credentials produce a clear error message.
Make sure that logs never print secret values, and keep a sample environment file that lists variable names without real values.
Keep the interface, both clients and the tests together, since every later project in this section will import this client rather than calling a provider directly.
By the end of this project you will have a reusable, testable model client that works with or without a real provider.
Prompt Design and Instruction Boundaries. A prompt is the main way you control a language model, and a carelessly written one produces inconsistent or unsafe behavior. This lecture covers how to structure prompts clearly and how to keep your instructions separate from untrusted content.
A well-designed prompt states the role, the task, the constraints and the expected output format. Specific instructions beat vague ones. Telling the model who the audience is, what to include, what to avoid and how long the answer should be removes much of the guesswork. We discuss using delimiters or labeled sections to separate instructions from the material the model should work on.
That separation leads to the idea of an instruction boundary. Text from users, documents and web pages may itself contain instructions, which a model could mistakenly follow. Treat all such material as data to be processed, not as commands to be obeyed. We discuss labeling untrusted content clearly, restating the real task after it and never granting that content the authority of your system instructions.
You will also learn to version prompts, keep them in files rather than scattered in code and test them against a fixed set of examples, so that edits are measured rather than guessed.
By the end of this lecture you will be able to write structured prompts and explain why untrusted text must be treated as data.
Day 42: Prompt Structure and Instructions — Build a support-response drafting tool. Today you build a tool that drafts replies to synthetic customer messages while keeping instructions and customer text clearly separated.
The steps I would expect you to follow are these. First, create a set of synthetic customer messages covering billing questions, delivery problems, complaints and a few unusual messages, including one that tries to give the assistant new instructions in harmless, obvious wording. Second, write a prompt template with sections for the role, the policy, the tone, the output format and a clearly delimited area for the customer message. Third, store the template in a file with a version identifier. Fourth, build the drafting function that fills the template and calls your model client, using mock mode first. Fifth, run all the sample messages and check that the drafts follow the policy and format, and that the instruction-like message is treated as customer content rather than obeyed. Sixth, revise the template, rerun the same messages and compare the results.
Record each prompt version beside the outputs it produced so that changes are traceable.
Keep the templates, the sample messages and a short evaluation checklist together, so that every future edit to the prompt is tested against the same cases.
By the end of this project you will have a structured drafting tool and a repeatable method for improving prompts.
Structured Outputs and Semantic Validation. Applications cannot do much with free-form paragraphs. They need data in predictable shapes, such as fields for a date, an amount and a category. This lecture explains how to obtain structured output from a language model and how to check it before using it.
The first step is to define a schema describing the fields, their types, allowed values and which are required. Many model interfaces can be told to return JSON conforming to a schema, and libraries such as Pydantic allow you to parse and validate the result in Python. If the response fails to parse, you can retry with the error message or report a controlled failure.
Syntactic validity is only half of the story. A response can match the schema and still be wrong. A date may be in the future when it cannot be, a total may not equal the sum of the line items, or a category may be plausible but unsupported by the source text. This is semantic validation, and it means writing explicit rules that check the content against business logic and against the original input.
We discuss designing fields that allow the model to say unknown, rather than forcing it to invent a value, and how to measure extraction accuracy on labeled examples.
By the end of this lecture you will be able to design a schema, validate model output and add semantic checks.
Day 43: Structured Outputs — Build an invoice information extractor. Today you build a tool that extracts fields from synthetic invoice text and validates them before accepting the result.
The steps I would expect you to follow are these. First, generate a set of synthetic invoices as plain text in several layouts, with invented vendor names, dates, line items and totals, and include a few that are incomplete or inconsistent. Second, define a schema with fields such as vendor, invoice number, date, line items, currency and total, allowing unknown where a value is absent. Third, write an extraction prompt and call your model client, using the mock client with canned responses during development. Fourth, parse the output with a validation library and handle parse failures with a limited retry. Fifth, add semantic checks, such as confirming that line items add up to the total and that dates are sensible, and flag the invoices that fail. Sixth, compare the extracted values with the known correct values and report accuracy for each field.
Keep a record of which invoices needed review and why, since this review queue is the practical output of the tool.
Keep the sample invoices, the schema, the validation rules and the accuracy report together, so that you can measure any later change against them.
By the end of this project you will have an extractor that does not merely produce data but checks it.
Few-Shot Learning in Context. Sometimes the most efficient way to teach a model a task is to show it examples directly inside the prompt. This lecture explains few-shot prompting, its benefits and its pitfalls, and how it compares with other ways of adapting a model.
In zero-shot prompting you describe the task and nothing else. In few-shot prompting you add several input and output examples, which demonstrate the format, tone and decision boundaries you want. Examples are especially valuable when the task is subtle, when labels have specific meanings in your organization or when the output must follow an unusual format.
Example choice matters a great deal. Examples should be representative, cover the main categories and include tricky boundary cases. Their order can influence the answer, and an unbalanced set can bias the model toward the most common label. We discuss selecting examples dynamically, by retrieving the most similar labeled cases for each new input.
Few-shot prompting also costs tokens on every request, and it uses part of the available context window. We discuss when it is better to improve instructions, when fine-tuning becomes worthwhile and how to evaluate prompts with and without examples on a held-out set.
By the end of this lecture you will be able to design few-shot prompts and measure whether the examples really help.
Day 44: Few-Shot Examples — Build and evaluate a ticket classifier. Today you build a classifier for synthetic support tickets and measure how different example sets change its accuracy.
The steps I would expect you to follow are these. First, create a labeled set of synthetic support tickets across several categories, including ambiguous ones, and divide it into an example pool and an evaluation set. Second, write a zero-shot prompt that defines the categories and asks for a label in a structured output. Third, build a few-shot version that includes a small number of examples from the pool. Fourth, run both versions on the evaluation set using your model client and compute accuracy and a confusion matrix. Fifth, experiment with the number of examples, their order and a balanced selection versus a random one, recording each result. Sixth, examine the tickets that were misclassified and decide whether the issue lies in unclear category definitions, a poor example choice or genuinely ambiguous tickets.
Use the mock client during development to confirm the pipeline works, then switch to a real model only if you have access.
Keep the example pool, the evaluation set and the results table together, so that you can show exactly which design choices improved the outcome.
By the end of this project you will have a classifier and an evidence-based view of when few-shot examples are worth their cost.
Conversation State and Context Budgets. A language model does not remember earlier turns by itself. Every request must include whatever history the model should consider, and that history competes for a limited amount of space. This lecture explains how to manage conversation state responsibly.
A chat application stores messages, usually as a list of roles and contents, and sends some or all of them with each new request. As conversations grow, they approach the context window limit and become more expensive and slower. We discuss strategies for staying within budget. You can keep only the most recent messages, summarize older ones, keep important facts in a separate structure or retrieve relevant earlier content when needed.
Each approach has trade-offs. Truncating old messages is simple but forgets instructions or key facts. Summaries save space but can lose detail or introduce errors. We discuss pinning system instructions so that they are never dropped and counting tokens so that you know the size of a request before sending it.
State also raises privacy and correctness questions. Decide how long histories are stored, who can access them and what is removed on request. Keep conversations separate per user and per session so that content never leaks between them.
By the end of this lecture you will be able to design bounded conversation memory with clear rules for what is kept.
Day 45: Conversation State — Build an assistant with bounded conversation history. Today you build a chat assistant that keeps its memory within a fixed budget without losing the essentials.
The steps I would expect you to follow are these. First, create a conversation manager that stores messages for each session identifier, keeping sessions strictly separate. Second, implement a token counter, even an approximate one, and define a budget for the history portion of each request. Third, pin the system instructions so that they always remain in the request. Fourth, implement a trimming strategy that removes the oldest messages when the budget is exceeded, and then a second strategy that replaces older messages with a short summary. Fifth, write a scripted conversation in which an important fact is stated early, and test which strategy preserves it when the conversation grows long. Sixth, add a command to clear a session, and confirm that the data is really gone.
Use your mock client so the tests are deterministic, and print the size of each request so that you can watch the budget at work.
Keep the manager, the scripted conversations and the test results together, since they document the trade-offs you chose and make later changes safer.
By the end of this project you will have a chat assistant whose memory is bounded, predictable and easy to inspect.
Autoregressive Generation and Streaming UX. Language models generate text one token at a time, each token depending on those before it. Understanding this process explains many of their behaviors and makes it possible to build interfaces that feel fast, even when the full answer takes several seconds.
We begin with how generation works. The model predicts a probability distribution over the next token, a token is chosen according to the sampling settings and the process repeats until the output ends or a limit is reached. This explains why output length affects latency and cost, why small changes early in a response can send it in a different direction and why the model cannot revise earlier words.
Streaming returns tokens to the client as they are produced, rather than waiting for the full reply. The user sees text appearing almost immediately, which greatly improves perceived responsiveness. We discuss how streaming is delivered, using server-sent events or similar mechanisms, and the practical issues that follow.
Those issues include handling partial output, which might break structured formats, supporting cancellation when the user stops generation, dealing with connection drops and deciding when to run validation. We also discuss showing progress, preserving formatting and recording the final text for logs.
By the end of this lecture you will be able to explain autoregressive generation and design a streaming experience.
Day 46: Streaming Responses — Build a streaming chat interface. Today you build an interface that displays a model's reply as it is generated and lets the user stop it.
The steps I would expect you to follow are these. First, extend your model client with a streaming method that yields pieces of text as they arrive, and give the mock client a streaming mode that emits a prepared reply in small chunks with short delays. Second, build a small server endpoint that streams those chunks to a browser or terminal. Third, build the interface so that it appends text as it arrives and shows a clear indicator while generation is in progress. Fourth, add a stop button that cancels the request cleanly and keeps the partial text visible. Fifth, handle errors partway through a response, such as a dropped connection, by showing a clear message and allowing a retry. Sixth, record the time to the first chunk and the total time, so that you can see the benefit of streaming compared with waiting for the complete answer.
Test with an empty reply, a very long reply and a reply that fails halfway, to confirm that the interface always returns to a usable state.
Keep the streaming client, the server, the interface and the tests together so that later projects can reuse the same pattern.
By the end of this project you will have a streaming chat interface that feels responsive and recovers gracefully from interruptions.
Tool Calling and Argument Validation. A language model alone can only produce text. Tool calling lets it request that your application perform an action, such as looking up a record or calculating a price, and then use the result in its answer. This lecture explains how it works and how to keep it safe.
You describe each available tool to the model with a name, a purpose and a schema for its arguments. When the model decides a tool is needed, it returns a structured request naming the tool and supplying arguments. Your code, not the model, executes the tool and sends the result back, after which the model continues. This division is essential: the model proposes, and your application decides.
Because the model's arguments are generated text, they must never be trusted blindly. Validate every call against the schema, check types and ranges, confirm that the tool exists and verify that the requested action is permitted for the current user. Reject invalid calls with a clear error that the model can use to correct itself.
We also discuss clear tool descriptions, keeping tools narrow and single-purpose, limiting the number of tool rounds in a conversation and logging every call with its arguments and result for later review.
By the end of this lecture you will be able to design tools with strict schemas and a safe execution loop.
Day 47: Tool Calling — Build an assistant with a quotation calculator. Today you build an assistant that calls a pricing tool to produce quotations for a fictional product catalog.
The steps I would expect you to follow are these. First, create a small synthetic catalog with product names, unit prices and quantity discount rules. Second, write a quotation tool that accepts a product identifier and a quantity and returns a calculated price, and define its argument schema precisely. Third, describe the tool to the model and implement the loop that detects a tool request, validates the arguments, runs the tool and returns the result. Fourth, use the mock client to script a conversation in which the model requests the tool, so that the whole path can be tested without a real model. Fifth, test invalid requests, such as an unknown product, a negative quantity or a missing field, and confirm that clear errors are returned rather than crashes. Sixth, set a limit on the number of tool rounds, so a confused model cannot loop forever.
Log each tool call with its validated arguments and the result, which gives you an audit trail.
Keep the catalog, the tool, the loop and the tests together so that you can add further tools later using the same safe pattern.
By the end of this project you will have an assistant that performs real calculations through a validated tool rather than guessing numbers.
Bounded Retries and Idempotency. Calls to model providers and other services fail in many ordinary ways: networks time out, servers are briefly overloaded and rate limits are reached. A robust application expects these failures and responds to them in a controlled, bounded way.
We begin by classifying errors. Some are transient, such as timeouts and temporary server problems, and are worth retrying. Others are permanent, such as invalid credentials or malformed requests, and retrying only wastes time. Rate-limit responses often tell you how long to wait, and respecting that guidance is both polite and effective.
Retries must be bounded. We discuss exponential backoff, which increases the delay between attempts, and jitter, which adds randomness so that many clients do not retry at the same moment. Every call needs a timeout, and the whole operation needs an overall deadline, so that failures cannot hang a user indefinitely.
Idempotency is the second theme. If an operation changes something, such as creating an order or sending a message, a retry might perform it twice. An idempotency key lets the receiving side recognize a repeated request and return the original result instead of repeating the action. We also discuss fallbacks, circuit breakers and presenting a helpful message to the user when all attempts fail.
By the end of this lecture you will be able to design retries that are safe, bounded and respectful of the services you call.
Day 48: Timeouts, Retries, and Failures — Build a resilient model-request wrapper. Today you build a wrapper that adds timeouts, bounded retries and clear failure reporting to any model client.
The steps I would expect you to follow are these. First, extend your mock client so that it can simulate several failures on demand, including a timeout, a temporary server error, a rate limit with a wait hint and a permanent authentication error. Second, define error categories in your code, separating retryable from non-retryable problems. Third, write the wrapper so that it applies a timeout to each attempt, retries only the retryable errors with exponential backoff and jitter, and stops after a maximum number of attempts or an overall deadline. Fourth, add an idempotency key to requests that change state, and show how a repeated key returns the original result. Fifth, write tests for each failure scenario, confirming the number of attempts and the final outcome. Sixth, produce a readable error that tells the user what happened without revealing internal details.
Replace real waiting with a controllable clock in tests so that the suite runs quickly.
Keep the wrapper, the failure simulator and the tests together, since every later project that calls a model should pass through this layer.
By the end of this project you will have a resilient wrapper that turns unpredictable failures into predictable behavior.
Inference Observability and Cost Accounting. A language model application can work correctly and still become slow, expensive or unreliable without anyone noticing. This lecture explains what to measure about model calls and how to turn those measurements into decisions.
For every request, record a structured event. Useful fields include a request identifier, the feature that made the call, the model name, the prompt version, the number of input and output tokens, the latency, the outcome and any error category. Time to first token is valuable for streaming interfaces, and total duration matters for batch work.
Token counts allow you to calculate cost. Multiply input and output tokens by the price for the chosen model, and aggregate by feature, user group or day. This shows which parts of the application are costly and where optimizations such as shorter prompts, caching or smaller models would pay off. We discuss setting budgets and alerts so that a runaway loop is detected early.
Privacy deserves attention. Logs should not casually store full prompts and responses, which may contain personal or confidential data. We discuss logging metadata by default, redacting sensitive content, limiting retention and controlling access.
We finish by discussing sampling traces for quality review and connecting these measurements to dashboards.
By the end of this lecture you will be able to define the events and metrics needed to monitor model calls and their cost.
Day 49: Usage, Latency, and Cost — Build an LLM monitoring dashboard. Today you record structured events from your model client and summarize them in a dashboard.
The steps I would expect you to follow are these. First, define an event structure that includes a request identifier, feature name, model, prompt version, input and output tokens, latency, outcome and error category. Second, wrap your model client so that each call records an event to a file or small database, without storing full prompts by default. Third, create a price table for synthetic models and write a function that calculates the cost of each call. Fourth, generate a realistic batch of traffic using the mock client, including slow calls, failures and an unusually expensive burst. Fifth, build a dashboard that shows request counts, average and high-percentile latency, error rates, token totals and cost by feature and by day. Sixth, add a simple alert rule, for example when the daily cost exceeds a budget, and demonstrate it firing on your synthetic burst.
Confirm that redaction works by searching the stored events for the sample personal details in your test prompts.
Keep the event schema, the wrapper, the price table and the dashboard together, so that new features can adopt the same monitoring from the start.
By the end of this project you will have a dashboard that makes the behavior and cost of your model calls visible.
Day 50: Support Copilot Integration — Build a copilot with human review. Today you bring together the whole section by building a support copilot that drafts replies and requires a person to approve them.
The steps I would expect you to follow are these. First, create a synthetic set of customer tickets and a small knowledge base of policies for a fictional company. Second, use your model client, prompt templates, structured outputs and conversation state to classify each ticket and draft a reply. Third, add a tool for looking up synthetic order details, with validated arguments and an audit log. Fourth, wrap everything in the resilient request layer and record usage events for monitoring. Fifth, build a review interface in which a person sees the ticket, the draft, the information used and a confidence indicator, and can approve, edit or reject the draft. Sixth, ensure that nothing is sent to a customer without approval, and record every decision with a timestamp and the reviewer.
Test the complete flow using the mock client, including a failing model call, an invalid tool request and a draft that the reviewer rejects.
Keep the code, the sample tickets, the policies and the test results together, since this copilot becomes a starting point for the knowledge assistant and agent projects that follow.
By the end of this project you will have an end-to-end copilot with human oversight, built from the pieces of the entire section.
Document Ingestion and Provenance. A retrieval system is only as good as the documents it contains, and those documents arrive in messy forms: PDFs with odd layouts, Markdown files, web exports and spreadsheets. This lecture explains how to turn such sources into clean, trackable text that later stages can rely on.
Ingestion has several steps. You discover files, identify their type, extract text and structure such as headings, tables and page numbers, and normalize the result. Extraction is rarely perfect. Scanned pages may need text recognition, multi-column layouts can scramble reading order, and headers and footers can pollute every page. We discuss inspecting samples by hand and measuring extraction quality instead of assuming it.
Provenance is the second theme. Every piece of text should carry information about where it came from: the source file, its location, the version or modification date, a content hash and the time of ingestion. This allows you to cite sources, detect changes, remove outdated material and investigate wrong answers.
We also discuss metadata such as owner, department, sensitivity and effective dates, handling duplicates, rejecting files that fail validation and recording errors in a report rather than silently skipping them.
By the end of this lecture you will be able to design an ingestion pipeline that produces clean, traceable documents.
Day 51: Document Ingestion — Build a PDF and Markdown ingestion pipeline. Today you build a pipeline that reads documents in two formats and produces clean records with provenance.
The steps I would expect you to follow are these. First, create a small synthetic collection of documents about a fictional company, including Markdown files and generated PDFs with headings, tables and repeated headers and footers, plus one corrupt file and one duplicate. Second, write extractors for each format that return text, headings and page or line locations. Third, add cleaning steps that remove repeated headers and footers, normalize whitespace and preserve meaningful structure. Fourth, attach provenance to each record, including the source path, a content hash, the modification date and the ingestion time. Fifth, validate each record, rejecting empty or corrupt documents and flagging duplicates by their hashes. Sixth, produce an ingestion report that lists accepted, rejected and duplicate files with reasons.
Review a sample of the extracted text against the original documents to confirm that nothing important was lost.
Keep the sample documents, the extractors, the cleaned output and the report together, since the next projects build directly on them.
By the end of this project you will have a dependable ingestion pipeline whose output you can trace and trust.
Chunking and Evidence Boundaries. Language models and retrieval systems cannot work with entire document libraries at once, so documents are divided into chunks. How you divide them decides what can be found and what can be quoted, which makes chunking one of the most influential choices in any retrieval system.
Chunks that are too small lose context. A sentence saying the limit is fifty may be meaningless without the heading that says what is limited. Chunks that are too large blur multiple topics, dilute similarity scores and consume the model's context budget. We discuss common strategies, including fixed-size windows, splitting by sentences or paragraphs, splitting by headings and structure-aware methods that keep tables and lists intact.
Overlap between neighboring chunks can protect ideas that cross a boundary, though it increases storage and duplicates. We discuss attaching context, such as the document title and section path, to each chunk so that it makes sense by itself.
Chunks also define evidence boundaries. When the assistant cites a source, the cited unit should be small enough to verify yet large enough to support a claim. We discuss recording the start and end positions of every chunk so that citations can point back to the exact place.
By the end of this lecture you will be able to compare chunking strategies and choose one with a clear rationale.
Day 52: Chunking Strategies — Build a chunking comparison tool. Today you implement several chunking methods and compare how they affect retrieval on the same documents.
The steps I would expect you to follow are these. First, use the cleaned synthetic documents from the previous project and write a set of questions whose answers appear in known places, including some that span a section boundary. Second, implement fixed-size chunking with and without overlap, paragraph-based chunking and heading-based chunking. Third, for each chunk, record its document identifier, start and end positions, section path and size. Fourth, embed the chunks from each strategy into separate indexes. Fifth, run your question set against every index and compute whether the right passage appears in the top results. Sixth, produce a comparison report showing the number of chunks, average size and retrieval success for each strategy, and highlight the questions that each approach gets wrong.
Look at specific failures, such as an answer split in two or a chunk with no context, and describe what change would fix them.
Keep the chunkers, the question set and the report together, so that you can rerun the comparison when your documents change.
By the end of this project you will be able to choose a chunking strategy using evidence instead of habit.
Incremental Embedding and Index Maintenance. Document collections change constantly, and recomputing every embedding after each change is slow and expensive. This lecture explains how to keep a search index current by processing only what has changed.
The foundation is change detection. Each chunk stores a content hash, so that when a document is re-ingested you can compare hashes and see which chunks are new, which are changed, which are unchanged and which have disappeared. Only new and changed chunks need fresh embeddings. Disappeared chunks must be removed from the index, or the system will keep citing text that no longer exists.
We discuss how to structure the update process. Work is split into small batches with a record of progress, so that a failure halfway does not leave the index in an unknown state. Operations should be idempotent, meaning that repeating them is harmless, which makes retries safe. We also discuss handling rate limits and embedding costs.
Some changes require a full rebuild, such as switching the embedding model or altering the chunking strategy. A common approach is to build a new index alongside the old one, check it and then switch over.
Finally, we cover monitoring, including counts, freshness and sample queries that confirm the index reflects the latest documents.
By the end of this lecture you will be able to design an update process that is efficient, safe and verifiable.
Day 53: Embedding and Index Updates — Build an incremental indexing service. Today you build a service that keeps a vector index synchronized with a changing document folder.
The steps I would expect you to follow are these. First, reuse your synthetic documents and chunking code, and store a manifest listing each chunk's identifier, source, hash and embedding model. Second, write a synchronization routine that ingests the folder, compares hashes with the manifest and sorts chunks into new, changed, unchanged and removed. Third, embed only the new and changed chunks, using batches, and update the index. Fourth, delete the removed chunks from both the index and the manifest. Fifth, record progress after each batch, so that if the process stops midway it can resume without duplicating work. Sixth, test the service by adding a file, editing a file and deleting a file, then confirming that searches immediately reflect each change and that only the necessary embeddings were computed.
Add a command that reports index health, such as total chunks, the embedding model and the time of the last successful run.
Keep the service, the manifest format and the tests together, so that the behavior is documented and any later change remains safe.
By the end of this project you will have an indexing service that is efficient, resumable and easy to inspect.
Retrieval-Augmented Generation. Language models know a great deal, but they do not know your private documents, they cannot reliably recall precise facts and their knowledge stops at a training date. Retrieval-augmented generation, usually shortened to RAG, addresses this by giving the model relevant text at the moment it answers.
The flow is straightforward. A user asks a question, the system retrieves the most relevant chunks from an index, and it places them in the prompt together with instructions to answer using that material. The model then writes a response grounded in the supplied text. This reduces invented answers, allows knowledge to be updated by changing documents rather than retraining and makes it possible to show sources.
We discuss the main components: ingestion, chunking, embedding, retrieval, prompt assembly and generation, and how each can fail. Poor retrieval means the right text never reaches the model. Poor prompting means the model ignores or misreads it. Too much context buries the useful part among distractions.
You will learn to write a grounding prompt that tells the model to rely only on the provided passages, to quote or reference them and to say when they are insufficient. We also discuss selecting the number of chunks and managing the context budget.
By the end of this lecture you will be able to describe a RAG pipeline and identify where it can break.
Day 54: RAG Pipeline Fundamentals — Build a document question-answering assistant. Today you build your first complete retrieval-augmented pipeline over a synthetic document collection.
The steps I would expect you to follow are these. First, reuse the indexed synthetic documents about a fictional company, and write a set of questions with known answers, including some that the documents cannot answer. Second, implement retrieval that returns the top passages for a question. Third, write a grounding prompt that contains the question, the numbered passages and clear instructions to answer only from them. Fourth, call your model client, using the mock client at first, and return the answer together with the passages that were supplied. Fifth, build a simple interface that shows the answer and expandable source passages. Sixth, run your question set and inspect each result, noting whether the failure came from retrieval, from the prompt or from generation.
Experiment with the number of passages and observe the effect on answer quality and cost.
Keep the pipeline, the question set and your failure notes together, because the following projects improve this system step by step and you will want a baseline to compare against.
By the end of this project you will have a working question-answering assistant and a clear understanding of how its parts interact.
Grounding and Citation Verification. An answer that sounds confident is not necessarily supported by the documents. Grounding means that every claim traces back to supplied evidence, and citations are how users and developers verify that. This lecture explains how to produce citations and, just as important, how to check them.
We begin with how to request citations. Passages are given stable identifiers in the prompt, and the model is told to attach those identifiers to each claim. The output is structured so that answer text and citation lists can be separated and processed. Quoting short excerpts alongside identifiers makes verification easier for readers.
Models can still make citation mistakes. They may cite a passage that does not support the claim, invent an identifier or attribute a claim to the wrong source. Verification therefore happens in code. Confirm that every cited identifier exists in the supplied set, check that quoted excerpts really occur in the cited passage and, where practical, assess whether the passage supports the statement.
We discuss presenting citations to users, linking to the exact location in the original document and handling answers that have claims without any citation. We also discuss measuring citation accuracy as part of evaluation.
By the end of this lecture you will be able to generate and verify citations that users can rely on.
Day 55: Source Attribution — Build answers with verifiable citations and excerpts. Today you extend your RAG assistant so that every claim points to a passage and every citation is checked.
The steps I would expect you to follow are these. First, give each retrieved passage a stable identifier and include its document name and location in the prompt. Second, define a structured output with the answer text, a list of claims and, for each claim, the supporting passage identifiers and a short quoted excerpt. Third, implement verification that confirms every identifier was actually supplied and that each quoted excerpt appears in the cited passage. Fourth, mark any claim that fails verification and decide on a policy, such as removing the claim, regenerating once or warning the reader. Fifth, display the final answer with numbered citations that open the source passage at the correct location. Sixth, test with prepared cases, including a fabricated identifier, an altered quote and a claim with no citation, and confirm each is caught.
Report the percentage of claims that pass verification across your test questions.
Keep the schema, the verifier and the failure cases together, so that the checks can run automatically whenever you change prompts or models.
By the end of this project you will have an assistant whose answers can be checked by the people who read them.
Conversational Query Rewriting. People rarely ask perfectly complete questions. In a conversation they say things like what about the second one, or how much does it cost, which depend entirely on earlier turns. If such a message goes straight to the retriever, the search finds nothing useful. This lecture explains how to rewrite follow-ups into standalone queries.
The idea is to take the recent conversation and the latest message and produce a self-contained search query. A language model can do this with a carefully written prompt that resolves pronouns, adds the missing subject and preserves important constraints such as a product name or a date. The rewritten query is used for retrieval, while the user's original message is still shown in the conversation.
We discuss risks. Rewriting can add details the user never intended, drop important qualifiers or change the meaning. We discuss keeping the rewrite short, logging both versions, comparing retrieval results from original and rewritten queries and falling back to the original when the rewrite looks unreliable.
Some systems generate several alternative queries to improve coverage and merge the results. We discuss the cost and latency of such methods.
We also discuss evaluating rewriting with conversations whose follow-up questions have known intended meanings.
By the end of this lecture you will be able to design and test a query rewriting step for conversational search.
Day 56: Query Rewriting — Build retrieval for conversational follow-up questions. Today you add a rewriting step so that your assistant handles follow-ups that depend on earlier turns.
The steps I would expect you to follow are these. First, write a set of synthetic conversations, each with an opening question and one or two follow-ups that use pronouns or omit the subject, and record for each follow-up the standalone question it should become. Second, implement retrieval without rewriting and measure how often the right passage is returned for the follow-ups. Third, write a rewriting prompt that receives the recent history and the latest message and returns a standalone query. Fourth, add the rewriting step before retrieval, logging the original and rewritten queries together. Fifth, rerun the measurement and compare the two approaches, listing the cases where rewriting helped and where it harmed. Sixth, add a safeguard that falls back to the original query when the rewrite is empty, extremely long or very different from the original.
Use the mock client with scripted rewrites during development so that your tests are deterministic.
Keep the conversations, the expected rewrites and the comparison results together, so that you can evaluate any later prompt change on the same examples.
By the end of this project you will have a conversational retrieval step and evidence about its effect.
Retrieve-Then-Rerank Pipelines. The first retrieval step is designed to be fast, scanning many candidates and selecting a rough shortlist. It often places the best passage near the top but not always first. A reranker examines the shortlist more carefully and reorders it, improving the quality of what the model finally sees.
We discuss why two stages work well. Embedding-based retrieval compares precomputed vectors, which is cheap but approximate, since the query and the passage are encoded separately. A cross-encoder reranker reads the query and a candidate together, allowing it to judge relevance more precisely, though at a higher cost per candidate. That is why it is applied only to a small set, such as the top thirty.
You will learn how to choose the sizes of the candidate list and the final list, how to measure the benefit using retrieval metrics and how to weigh improved quality against added latency and cost. We also discuss language models used as rerankers, along with their risks of inconsistency.
Practical issues include handling ties, preserving the original scores for debugging, caching results for repeated queries and falling back gracefully if the reranker is unavailable.
By the end of this lecture you will be able to add a reranking stage and judge whether it is worthwhile.
Day 57: Reranking — Build and evaluate a reranking pipeline. Today you add a second stage that reorders retrieved candidates and measure whether it improves results.
The steps I would expect you to follow are these. First, use the evaluation questions and indexed synthetic documents from earlier projects, and compute baseline retrieval metrics. Second, modify retrieval to return a larger candidate list, for example thirty passages. Third, implement a reranker, either a pretrained cross-encoder or a scoring function that you can swap out, and apply it to the candidates. Fourth, return the top few passages after reranking and keep both the original and new scores for each. Fifth, recompute the metrics and compare them with the baseline, also recording the extra time the reranker adds. Sixth, examine examples where reranking improved the order and where it made it worse, and describe the patterns you see.
Add a fallback so that if the reranker fails, the pipeline returns the original order and records a warning.
Keep the pipeline, the metrics and the comparison table together so that you can test the effect of other candidate sizes and rerankers.
Record the candidate size, the reranker name and the measured delay next to every result, so that a later change can be judged against a known starting point.
By the end of this project you will have a reranking stage backed by measurements that show its value and its cost.
Answerability and Abstention. A trustworthy assistant knows when it does not know. If the retrieved passages do not contain the answer, the correct response is to say so, not to produce a plausible guess. This lecture covers how to detect insufficient evidence and how to respond to it well.
Abstention can be triggered at several points. At retrieval time, weak similarity scores or an empty result set suggest that nothing relevant exists. At generation time, the prompt instructs the model to state clearly when the passages are insufficient. After generation, a verification step can check whether the answer is actually supported by the cited text.
Each signal is imperfect. A cutoff that is too strict makes the assistant refuse answerable questions, while one that is too lenient lets weak evidence through. We discuss calibrating thresholds using labeled examples that include both answerable and unanswerable questions, and measuring both wrongly refused and wrongly answered cases.
How the assistant declines matters as much as when. A useful response explains what was searched, states that the documents do not cover the question, suggests how to rephrase or offers to route the question to a person. We also discuss partial answers, where some parts of a question are supported and others are not.
By the end of this lecture you will be able to design abstention behavior that is accurate and helpful.
Day 58: Answerability and Abstention — Build an assistant that identifies insufficient evidence. Today you teach your RAG assistant to decline gracefully when the documents do not contain an answer.
The steps I would expect you to follow are these. First, extend your question set with a balanced mix of answerable and unanswerable questions, including ones that are close to the topic of the documents without being covered. Second, add a retrieval-based check using the best similarity score and the number of results above a cutoff. Third, update the prompt so that the model must return a structured result stating whether the evidence is sufficient. Fourth, add a verification step that checks that an answer's cited passages actually support it. Fifth, write the response logic that produces a clear message when the evidence is insufficient, explaining what was searched and suggesting what to try next. Sixth, measure how often the assistant answers when it should abstain and how often it abstains when it could have answered, then tune the thresholds.
Show the trade-off as a small table of results for several threshold settings.
Keep the question set, the thresholds and the measurements together so that any later retrieval change can be checked for effects on abstention.
By the end of this project you will have an assistant that is honest about the limits of its evidence.
RAG Quality Evaluation. A RAG system can fail in several different places, and a single overall score hides where. This lecture explains how to evaluate retrieval, answer quality and citation quality separately, so that you know what to fix.
For retrieval, use the metrics from earlier lessons, such as recall at k and mean reciprocal rank, against passages known to contain the answers. For generation, evaluate faithfulness, which asks whether the answer is supported by the retrieved text, and relevance, which asks whether it addresses the question. For citations, evaluate whether cited passages exist, whether they support the claims and whether important claims are cited at all.
Some checks can be automated with code, such as identifier validation and excerpt matching. Others need judgment. A language model can act as a grader against a clear rubric, but graders are imperfect and can be biased, so we discuss calibrating them against human-labeled examples and sampling outputs for manual review.
A good evaluation set contains easy, hard, multi-passage and unanswerable questions, and it is versioned alongside the code. We discuss running the suite automatically on every change, tracking results over time and setting thresholds that prevent regressions.
By the end of this lecture you will be able to build an evaluation suite that points directly to the weak part of a RAG system.
Day 59: RAG Evaluation — Build a retrieval, answer, and citation evaluation suite. Today you build an automated suite that scores your RAG assistant at every stage.
The steps I would expect you to follow are these. First, assemble an evaluation set from your earlier questions, storing for each the expected passages, a reference answer or key facts, and whether it is answerable. Second, compute retrieval metrics for each question. Third, implement answer checks, including whether required key facts appear, whether the assistant correctly abstained and, optionally, a rubric-based grader using your model client. Fourth, implement citation checks that confirm identifiers exist, quotes match and claims are cited. Fifth, produce a report with scores per stage, a list of the worst failures and a categorized summary of what went wrong. Sixth, add a command that compares two runs and fails when any key metric drops by more than an allowed margin.
Sample some graded results by hand to see whether your automated grader agrees with your own judgment.
Keep the evaluation set, the scoring code and the saved reports together, so that results from different dates can be compared.
Store each report with the date and the version of the assistant it describes, so that you can see at a glance whether quality is rising or falling over time.
By the end of this project you will have an evaluation suite that turns improvements and regressions into visible numbers.
RAG Application Lifecycle. A RAG demonstration is a pipeline, but a RAG product is a system that must be operated over months. This lecture looks at the whole lifecycle of such an application, from the arrival of a new document to the retirement of an old one, and at the responsibilities that come with it.
Content lifecycle comes first. Documents have owners, effective dates and statuses such as draft, approved and archived. Only approved, current material should be searchable, and the system must react when a document is replaced or withdrawn, removing old passages and recording the change. We discuss review workflows for sensitive content and the importance of accurate metadata.
Next is the application lifecycle. Prompts, models, chunking settings and retrieval parameters all change over time, and each change can affect quality. We discuss versioning these components together, testing changes against the evaluation suite before release and rolling back safely when a change disappoints.
Operational concerns follow, including monitoring query volume, latency, cost, abstention rates and user feedback. We discuss collecting thumbs-up and thumbs-down signals, turning them into new evaluation cases and handling reported errors through a clear process.
By the end of this lecture you will be able to describe how to keep a RAG application accurate, current and accountable over time.
Day 60: Knowledge Assistant Integration — Build a RAG application with document lifecycle management. Today you finish the section by integrating ingestion, retrieval, answering and evaluation into one application.
The steps I would expect you to follow are these. First, assemble the synthetic documents with metadata for owner, status and effective dates, and run ingestion with provenance. Second, connect incremental indexing so that approved documents are indexed, and withdrawn or archived ones are removed. Third, assemble the answering path with query rewriting, retrieval, reranking, grounded generation, citation verification and abstention. Fourth, build an interface that shows answers, citations and a feedback control, and a small administrative view that lists documents and their status. Fifth, run the evaluation suite, and record the scores as the release baseline. Sixth, simulate a lifecycle event, such as replacing a policy document and withdrawing another, then confirm that the assistant's answers and citations change accordingly.
Capture feedback from the interface in a file and turn at least two examples into new evaluation cases.
Keep the application, the configuration, the evaluation set and the baseline results together, so that the agent projects in the next section can reuse this knowledge assistant as a trusted tool.
By the end of this project you will have a complete, evaluated and maintainable RAG application.
Deterministic Workflows and AI Agents. Not every problem that involves a language model needs an agent. This lecture draws a clear line between deterministic workflows, in which your code decides every step, and agents, in which a model decides what to do next, and explains how to choose between them.
A workflow is a fixed sequence or a set of branches that you define in advance. A model may be called at some steps, for example to classify a message or draft a summary, but the order of operations never changes unpredictably. Workflows are easier to test, cheaper to run, simpler to debug and more predictable for users. Many valuable applications are best built this way.
An agent, by contrast, is given a goal and a set of tools and decides for itself which tool to use and when to stop. This flexibility suits open-ended tasks in which the necessary steps cannot be known beforehand, such as researching an unfamiliar topic. The cost is variability, since the same request may take different paths, and greater difficulty in testing and controlling behavior.
We discuss a practical rule: start with the simplest design that works, use a workflow where the path is known and add agentic freedom only where it creates real value. We also discuss hybrid designs that embed a bounded agent inside a deterministic process.
By the end of this lecture you will be able to decide whether a task needs a workflow or an agent.
Day 61: Workflows and Agents — Build a rule-based task router. Today you build a deterministic router that sends synthetic requests to the right handler, which gives you a baseline to compare with agents later.
The steps I would expect you to follow are these. First, create a set of synthetic requests of several kinds, such as questions about orders, requests for summaries, calculations and messages that fit none of the categories. Second, define a handler for each kind, and keep each one small and testable. Third, implement the router using clear rules, such as keywords and patterns, and add a model-based classification step that can be swapped in through your mock client. Fourth, define the behavior for unrecognized requests, which should produce a polite explanation or a handoff, not a guess. Fifth, log which route each request took and why. Sixth, test the router on all your requests and report how many were routed correctly, then list the borderline cases that a rule-based approach handles poorly.
Write a short note describing which of these borderline cases might justify an agent and which are better solved with improved rules.
Keep the router, the handlers, the requests and the results together, since you will compare them with an agent in the next project.
By the end of this project you will have a predictable router and a practical sense of where workflows are enough.
Agent Execution Loops. At the center of every agent is a loop: observe the situation, decide on an action, perform it, observe the result and repeat until the goal is met. This lecture explains that loop, how to implement it safely and why it must always have limits.
In each iteration, the application sends the model the goal, the history of previous steps and the list of available tools. The model replies either with a request to use a tool or with a final answer. The application validates the request, runs the tool, appends the result to the history and continues. The model proposes and the application disposes, which is the key to staying in control.
Loops need boundaries. Set a maximum number of steps, a maximum total time and a budget for tokens or cost. Detect repetition, for example the same tool called with the same arguments several times, and stop or change course. Decide what the agent returns when it runs out of budget, which should be a clear statement of progress and what remains, not silence.
We discuss recording every step in a trace, including the reasoning summary, the tool, the arguments and the result, which is essential for debugging and for later evaluation.
By the end of this lecture you will be able to implement a bounded agent loop with a trace.
Day 62: Agent Execution Loops — Build a tool-using agent with a step limit. Today you build a small agent that uses tools to answer questions, and make sure it can never run away.
The steps I would expect you to follow are these. First, define two or three simple tools over synthetic data, such as a document lookup, a calculator and a clock, each with a clear schema. Second, write the loop that sends the goal, history and tool list to your model client, parses the response, validates the requested tool call and executes it. Third, use the mock client with scripted responses to reproduce several scenarios, including a normal success, a request for a tool that does not exist and a model that keeps repeating the same call. Fourth, add limits for steps, elapsed time and token budget, and define a clear final message when any limit is reached. Fifth, add repetition detection that stops the loop when identical calls recur. Sixth, write a trace file that records every step, then write tests confirming that each scenario ends in the expected state.
Review a trace by hand and describe in your own words what the agent did and why.
Keep the loop, the tools, the scripted scenarios and the traces together, so that later agent projects can build on the same foundation.
By the end of this project you will have a safe, observable agent loop.
Tool Contracts and Execution Guardrails. Agents become useful and risky at the same moment, when they are given tools. This lecture explains how to define tools precisely and how to place guardrails around their execution so that mistakes are contained.
A tool contract describes what a tool does, what it accepts, what it returns, what errors it can raise and what side effects it has. The input schema should be strict, with types, ranges and allowed values, and the output should be predictable. Clear descriptions help the model choose the right tool, but they do not replace enforcement, because the model can still make mistakes or be misled by content it reads.
Guardrails live in your code. Validate arguments, check that the current user and task are permitted to use the tool, and apply limits such as maximum rows returned or maximum file size. Classify tools by risk. Read-only tools may run freely, while tools that change data or contact other people need extra checks or approval. Give each tool the minimum permissions it needs.
We discuss timeouts, sandboxing and returning concise errors, which the model can use to adjust. We also discuss a registry that keeps all tool definitions, versions and risk levels in one reviewed place.
By the end of this lecture you will be able to write strict tool contracts and enforce them in code.
Day 63: Tool Contracts and Validation — Build a validated tool registry. Today you build a central registry that defines tools, validates every call and applies risk-based rules.
The steps I would expect you to follow are these. First, define a tool description structure that includes a name, a purpose, an input schema, an output description, a risk level and the permissions it requires. Second, create several synthetic tools, such as a read-only record lookup, a calculation and a tool that updates a record in a sandbox database. Third, implement a registry that stores them, exposes their descriptions to the model and rejects unknown names. Fourth, write a validation layer that checks each call's arguments against the schema, enforces limits and checks permissions for the current user. Fifth, add risk rules so that read-only tools run directly while state-changing tools are flagged for approval. Sixth, write tests with invalid types, missing fields, out-of-range values and unauthorized users, confirming that each produces a clear and safe rejection.
Record every call, including rejected ones, in an audit log that contains the user, the tool, the arguments and the outcome.
Keep the registry, the tools, the tests and the audit log format together, so that every future tool must pass through the same checks.
By the end of this project you will have a registry that makes tool use deliberate and controlled.
Planning and Task Dependencies. Some goals cannot be achieved in a single step. They require breaking a task into parts, deciding the order and handling the fact that some parts depend on the results of others. This lecture introduces planning in agents.
A plan is a list of steps, each with a description, the tools it might need and the steps it depends on. Dependencies form a graph, and a valid order must respect them. Some steps can run independently, while others must wait. We discuss representing plans as structured data, so that your code can inspect, validate and track them rather than treating them as loose text.
Plans must be allowed to change. Early results often reveal that a step is unnecessary, that a new step is needed or that an assumption was wrong. We discuss replanning, in which the agent revises the remaining steps in light of new information, and the importance of keeping a record of why the plan changed.
Planning has costs and limits. Elaborate plans can be wrong, and models may produce steps that are vague or impossible. Validate that every step is concrete, uses available tools and fits the budget. We discuss showing the plan to the user for review before execution when the stakes are high.
By the end of this lecture you will be able to represent, validate and revise plans for agent tasks.
Day 64: Planning and Execution — Build a research planning agent. Today you build an agent that creates a structured plan for a research question, then carries it out over a synthetic document set.
The steps I would expect you to follow are these. First, define a plan structure with steps, descriptions, required tools, dependencies and statuses such as pending, running, done and failed. Second, write a planning prompt that asks the model for a plan in that structure, and use the mock client to supply sample plans during development. Third, validate each plan, checking that dependencies refer to real steps, that the graph has no cycles and that every tool exists. Fourth, implement an executor that runs steps in dependency order, records results and marks statuses. Fifth, add replanning, so that when a step fails or returns surprising information, the agent can revise the remaining steps while the changes are logged. Sixth, compile the results into a short report that cites which steps provided which information.
Test with a plan that contains a cycle, a plan that uses an unknown tool and a step that fails, and confirm that each is handled sensibly.
Keep the plan structure, the validator, the executor and the test cases together, so that you can reuse them in the checkpoint and approval projects.
By the end of this project you will have an agent that plans visibly and executes under control.
State Machines and Durable Checkpoints. Agent tasks can take minutes or hours, and processes crash, deploy and restart. If an agent keeps its progress only in memory, every interruption means starting over, or worse, repeating actions that already happened. This lecture explains how to make agent work durable.
We begin with the state machine view. A task moves through well-defined states, such as created, planning, running, waiting for approval, completed and failed, and transitions between them follow explicit rules. Making states and transitions explicit prevents impossible situations and makes behavior easy to reason about and test.
Checkpoints save the state at meaningful moments, typically after each completed step. A checkpoint includes the goal, the plan, the results so far, the next step and enough information to resume. Storing it in a database or file lets a new process pick up where the previous one stopped.
Resumption introduces a subtle problem. If a crash occurs after a side effect but before the checkpoint, the step might run twice. We discuss idempotency keys, recording intent before acting and checking whether an action has already been performed.
We also discuss versioning stored state, cleaning up old tasks and viewing the history of a task for debugging.
By the end of this lecture you will be able to design agent tasks that survive interruptions without repeating actions.
Day 65: State and Checkpoints — Build a resumable document-processing agent. Today you build an agent that processes a batch of synthetic documents and can continue from where it stopped after an interruption.
The steps I would expect you to follow are these. First, create a folder of synthetic documents and define the task, such as classifying each document and extracting a short summary. Second, define a task state structure with the list of documents, their statuses, the results and the current position, and define the allowed transitions between task states. Third, save a checkpoint to disk after each document, writing it safely so that a crash cannot leave a half-written file. Fourth, implement a resume command that loads the latest checkpoint and continues with the unfinished documents. Fifth, record an idempotency marker for each completed document so that nothing is processed twice. Sixth, test by deliberately interrupting the run partway, then resuming, and confirm that the final results are identical to those of an uninterrupted run.
Add a command that shows the history of the task, including every transition and when it occurred.
Keep the state definitions, the checkpoint code and the interruption tests together, since durable state is needed for the approval and recovery projects that follow.
By the end of this project you will have an agent that is safe to stop and restart.
Human-in-the-Loop Approval. Some actions should never happen without a person's agreement: sending a message to a customer, changing a record, spending money or deleting data. This lecture explains how to build approval into agent workflows so that autonomy never outruns accountability.
The pattern is simple. When the agent wants to perform a sensitive action, it does not execute it. Instead, it creates an approval request containing the proposed action, the exact arguments, the reason and the relevant evidence, and then pauses. A person reviews the request and approves, rejects or edits it. Only after approval does the application execute the action, and it records who decided and when.
Design details matter. The reviewer must see what will really happen, not a vague summary, and the action that runs must be exactly the one that was approved, which means binding the approval to the specific arguments and expiring it after a time. We discuss risk tiers, where low-risk actions proceed automatically, medium-risk ones need one approver and high-risk ones need more.
We also discuss avoiding approval fatigue, in which reviewers click through requests without reading, by keeping requests clear and rare. Rejected requests must feed back to the agent so that it can adapt. Durable checkpoints make the waiting period safe.
By the end of this lecture you will be able to design approval gates that are clear, binding and auditable.
Day 66: Human Approval — Build an agent with approval-gated actions. Today you extend your agent so that risky actions pause for a person to approve, reject or edit them.
The steps I would expect you to follow are these. First, define a small set of synthetic actions with risk levels, such as drafting a note, updating a record in a sandbox database and sending a message to a fictional customer. Second, implement the approval request structure, including the action, the exact arguments, the explanation, the evidence, a request identifier and an expiry time. Third, update the agent so that risky actions create a request, save a checkpoint and pause. Fourth, build a simple review interface or command that lists pending requests and lets a reviewer approve, reject or edit them. Fifth, make the executor run only the approved arguments, verify that the approval has not expired and record the decision in an audit log. Sixth, feed rejections back to the agent so that it can choose another route, and test approval, rejection, editing and expiry.
Confirm that an approval for one set of arguments cannot be used to run a different action.
Keep the approval structures, the review tool and the tests together, since later projects reuse this gate for every sensitive operation.
By the end of this project you will have an agent that cannot take consequential actions without a person's consent.
Agent Memory and Privacy. Memory lets an agent remember preferences, earlier results and facts across sessions, which makes it more useful and more personal. It also creates a store of data about people that must be handled with care. This lecture covers how to design memory that is useful, limited and respectful of privacy.
We distinguish several kinds of memory. Short-term memory is the working context of the current task. Long-term memory persists across tasks and may hold user preferences, summaries of past work and learned facts. Each kind needs rules about what may be stored, how it is retrieved and how long it lives.
Not everything should be remembered. Define what is worth saving, avoid storing sensitive details unless there is a clear purpose and consent, and prefer summaries to raw transcripts. Memory entries should have an owner, a source, a creation date and an expiry. Retrieval should return only entries that belong to the current user and are relevant to the current task.
Users deserve control. Provide a way to inspect what the agent remembers, to correct wrong entries and to delete them, and make deletion complete. We also discuss the risk of wrong or poisoned memories, in which incorrect information is saved and later trusted, and how to mitigate it with provenance and review.
By the end of this lecture you will be able to design agent memory with clear scope, limits and user control.
Day 67: Memory and Privacy — Build inspectable, editable, and deletable agent memory. Today you build a memory store for an agent that users can examine and control.
The steps I would expect you to follow are these. First, define a memory entry structure with an identifier, an owner, the content, its source, a creation time, an optional expiry and a category. Second, create a store that saves entries and retrieves relevant ones for a task, filtered strictly by owner. Third, write rules for what the agent may remember, rejecting entries that contain sensitive categories of synthetic data, such as invented account numbers or health details, and prefer short summaries. Fourth, integrate the store with your agent so that it consults memory at the start of a task and proposes new entries at the end. Fifth, build commands that let a user list, correct and delete their entries, and make sure deletion removes all copies, including any search index entries. Sixth, test that one user can never retrieve another user's memories and that expired entries disappear.
Log every memory read and write with the reason, so that behavior can be audited.
Keep the store, the rules, the commands and the isolation tests together, since they establish the privacy behavior that your agent depends on.
By the end of this project you will have an agent memory that is useful, bounded and under the user's control.
Agent Failure Recovery. Agents fail in more ways than ordinary programs. Tools time out, models produce invalid arguments, plans turn out to be impossible, information is missing and the agent can drift into unproductive loops. This lecture explains how to plan for failure so that the agent recovers where it can and escalates where it cannot.
We begin by classifying failures. Transient failures, such as network errors, can be retried with limits. Invalid requests from the model can be returned to it with a clear error so it can correct itself, but only a bounded number of times. Missing permissions or missing information often require asking the user. Some failures, such as repeated tool errors or contradictory results, indicate that the agent should stop.
Recovery strategies include retrying, trying an alternative tool, replanning around a failed step, falling back to a simpler approach and returning a partial result with a clear account of what was and was not completed. Each has limits, to prevent endless recovery attempts.
Escalation is a designed behavior, not a defeat. When the agent cannot proceed safely, it should hand over to a person with a concise summary, the steps taken, the error encountered and the suggested next action. We also discuss recording failures to guide improvements.
By the end of this lecture you will be able to design recovery and escalation behavior that is predictable and helpful.
Day 68: Failure Recovery — Build an agent with recovery and escalation behavior. Today you teach your agent to cope with failures in an orderly way and to ask for help when it should.
The steps I would expect you to follow are these. First, extend your mock tools so they can simulate a range of failures, such as a timeout, an invalid argument error, a permission denial, an empty result and contradictory results. Second, define failure categories and a policy for each, including whether to retry, replan, ask the user, return a partial result or escalate. Third, implement the recovery logic in the agent loop, with a strict limit on recovery attempts for every step and overall. Fourth, build the escalation message, which includes the goal, the completed steps, the failure and a recommended next action. Fifth, make sure that partial results are labeled clearly and never presented as complete. Sixth, test each failure scenario, confirming the expected recovery, the number of attempts and the final outcome.
Add a summary of failures by category from your traces, to show where the agent struggles most often.
Keep the failure simulator, the policies and the scenario tests together, so that you can extend them whenever you discover a new failure in practice.
By the end of this project you will have an agent that fails gracefully and communicates honestly.
Multi-Agent Coordination. Sometimes one agent is not the best structure. A task may benefit from separate roles, such as one agent gathering information and another reviewing it. This lecture explains when multiple agents help, how they coordinate and the risks they introduce.
The most common pattern pairs a worker with a reviewer. The worker produces a draft or analysis, and the reviewer, with different instructions and possibly different tools, checks it against criteria and returns feedback. Other patterns include an orchestrator that assigns subtasks to specialists and a pipeline in which each agent handles one stage. These designs can improve quality by separating production from critique and by keeping each agent's context focused.
Coordination has costs. Every additional agent adds latency, cost and failure points, and messages between agents can lose information or amplify mistakes. We discuss defining clear interfaces between agents, using structured messages, limiting the number of rounds and deciding who has the final say.
Safety matters too. An agent should not gain authority simply because another agent asked. Permissions belong to tools and users, not to messages. We discuss tracing all interactions and testing whether the multi-agent design truly beats a single well-prompted agent.
By the end of this lecture you will be able to decide when to use multiple agents and design their coordination safely.
Day 69: Multi-Agent Coordination — Build a researcher-and-reviewer workflow. Today you build two cooperating agents, one that drafts an answer from sources and one that reviews it.
The steps I would expect you to follow are these. First, choose a task, such as answering a question from a synthetic document set, and write separate instructions for a researcher and a reviewer. Second, define a structured message format for the researcher's draft, with claims and sources, and for the reviewer's feedback, with approved items, problems and requested changes. Third, implement the coordination loop in which the researcher drafts, the reviewer critiques and the researcher revises, with a strict limit on the number of rounds. Fourth, give the reviewer a different set of tools, such as a citation checker, and make sure it has no ability to change the sources. Fifth, decide how the process ends, for example when the reviewer approves or when the round limit is reached with the unresolved issues clearly stated. Sixth, compare the result with a single agent attempt on the same questions, and record whether the extra cost produced better answers.
Trace every message between the agents so that you can review how a conclusion was reached.
Keep the agents, the message formats, the comparison results and the traces together, since the final project in this section evaluates exactly this kind of behavior.
By the end of this project you will have a coordinated workflow and evidence about when it is worthwhile.
Agent Trajectory Evaluation. Judging an agent only by its final answer misses much of what matters. Two agents might reach the same answer, one by a sensible path and the other by wasteful or risky steps. This lecture explains how to evaluate the whole trajectory, meaning every step the agent took.
A trajectory consists of the sequence of model decisions, tool calls, results and the final outcome. Evaluation looks at several dimensions. Task success asks whether the goal was achieved. Tool correctness asks whether the right tools were chosen with valid arguments. Efficiency considers the number of steps, time and cost. Safety asks whether the agent respected approvals, permissions and limits, and recovery asks how it behaved when things went wrong.
We discuss building a benchmark of tasks with defined success criteria, including tasks that should end in refusal, escalation or a request for approval. Deterministic checks can verify many properties, such as whether a forbidden tool was ever called. Rubric-based grading with a model can assess softer qualities, though it must be calibrated against human judgment.
Agents are variable, so run each task several times and look at rates, not single outcomes. We discuss comparing versions, setting regression thresholds and examining failing traces to find root causes.
By the end of this lecture you will be able to design a trajectory-based evaluation for agents.
Day 70: Agent Evaluation — Build a task success and tool correctness benchmark. Today you finish the agent section by building a benchmark that scores your agent's behavior, not just its answers.
The steps I would expect you to follow are these. First, define a set of synthetic tasks with clear success criteria, including normal tasks, tasks that should trigger an approval request, tasks that should be refused and tasks designed to cause tool failures. Second, define the expected properties of each trajectory, such as required tools, forbidden tools, a maximum number of steps and whether approval is required. Third, run the agent on each task several times using the mock client with scripted behaviors, and save every trace. Fourth, write checkers that read the traces and score success, tool correctness, efficiency, safety and recovery. Fifth, produce a report with rates for each dimension and a list of the worst traces for manual review. Sixth, make one deliberate improvement to the agent, rerun the benchmark and confirm which numbers changed.
Add a regression check that fails when the safety score falls below an agreed threshold.
Keep the task definitions, the checkers and the saved reports together, so that every future version of the agent can be compared with the ones before it.
By the end of this project you will have a repeatable benchmark that makes agent quality measurable.
MCP Architecture and Transport. Every agent needs tools, and every tool used to need custom glue code for every application. The Model Context Protocol, usually called MCP, is an open standard that defines one common way for AI applications to discover and use tools, data and prompts offered by separate servers. This lecture explains its architecture.
MCP has three roles. A host is the AI application, such as an assistant or an editor, that the user interacts with. Inside it, one or more clients each maintain a connection to a single server. A server is a program that exposes capabilities, which come in three main kinds: tools that perform actions, resources that provide data and prompts that offer reusable templates. The protocol messages use JSON-RPC, a simple request and response format.
We discuss transports, which carry those messages. A local transport runs the server as a child process and communicates through standard input and output, which is simple and suits development tools. A remote transport uses HTTP, optionally with streaming, which suits shared services and requires proper authentication.
You will learn about the connection lifecycle, in which client and server negotiate versions and capabilities before exchanging requests. We also discuss why a standard matters: servers become reusable across hosts, and your application gains tools without rewriting integrations.
By the end of this lecture you will be able to describe the roles, messages and transports of MCP.
Day 71: MCP Architecture — Build a calculator MCP server. Today you build your first MCP server, exposing a few simple tools, and test it from a client.
The steps I would expect you to follow are these. First, set up a project with the official MCP software development kit for Python, and create a server with a clear name and version. Second, define tools for addition, subtraction, multiplication and division, each with typed parameters and a short description. Third, handle the awkward cases deliberately, such as division by zero and values that are not numbers, returning a clear error rather than crashing. Fourth, run the server over the local standard input and output transport. Fifth, test it using an inspector tool or a short script that connects, lists the tools and calls each one, checking the results against known values. Sixth, write automated tests that start the server, exercise every tool and confirm the error behavior.
Read the messages exchanged between the client and server, and note the initialization steps and the tool listing, since seeing the protocol makes later debugging much easier.
Keep the server, the test script and a short usage note together, as the following projects extend this foundation.
By the end of this project you will have a working MCP server and a clear picture of how clients talk to it.
Typed Tools and Machine-Readable Schemas. A tool is only as useful as the model's understanding of it, and only as safe as the checks around it. In MCP, every tool publishes a machine-readable description, including a name, a human-readable purpose and a JSON Schema that defines its inputs. This lecture explains how to write those definitions well.
A good tool does one clear thing. Its name states the action, its description explains when to use it and when not to, and its input schema lists each parameter with a type, a description, constraints and which are required. Constraints such as minimum and maximum values, allowed options, string patterns and maximum lengths turn vague hopes into enforceable rules.
Python type hints and validation libraries can generate schemas automatically, keeping code and description aligned. The schema is advisory to the model, but the server must still validate every call, because a client may send anything. Reject invalid input with an informative message that tells the caller what to change.
We discuss output design too. Return structured results that are concise and predictable, avoid dumping huge payloads into the model's context and distinguish clearly between a successful result and an error. We also discuss versioning, since changing a schema can break clients, and testing descriptions by observing how a model chooses between similar tools.
By the end of this lecture you will be able to write typed tool definitions with strict validation.
Day 72: Tool Schemas — Build validated unit-conversion tools. Today you build tools that convert between units and reject anything outside their defined rules.
The steps I would expect you to follow are these. First, choose several unit families, such as length, mass and temperature, and define the supported units for each as an explicit list of allowed values. Second, write conversion functions with precise formulas, and test them against known reference values. Third, expose them as MCP tools with typed parameters for the value, the source unit and the target unit, with descriptions that explain valid combinations. Fourth, add validation so that unknown units, mismatched families, non-numeric values and values below physical limits, such as a temperature below absolute zero, return clear errors. Fifth, return structured results that include the converted value, the units and the formula used. Sixth, inspect the generated schemas, confirm that they describe the constraints accurately and write tests that send both valid and invalid requests.
Ask yourself whether each error message would let a model correct its next attempt, and rewrite those that would not.
Keep the tools, the schemas, the reference values and the tests together so that you can add new conversions with confidence.
By the end of this project you will have precisely defined tools that fail safely.
MCP Resources and Reusable Prompts. Tools perform actions, but much of what an assistant needs is simply information and well-crafted instructions. MCP therefore defines two further capabilities: resources, which expose data, and prompts, which expose reusable templates. This lecture explains both and when to use each.
A resource is a piece of read-only content identified by a URI, such as a document, a configuration summary or a table description. Servers can list resources and offer templates for families of them, for example a document by name. Clients read them and decide how to present them to a model or a user. Resources are application-controlled, which means the host usually decides what to include rather than the model choosing freely.
A prompt is a named template with parameters, such as a code review request or an incident summary. The server publishes it, and the user typically selects it, for example through a menu. This keeps good instructions consistent and shareable and separates prompt content from application code.
We discuss design guidance. Keep resources focused and sized for use within a context window. Provide clear metadata, such as a title, description and media type. Treat resource contents as untrusted data, because they might contain instructions. Apply access control, since a resource can expose sensitive information.
By the end of this lecture you will be able to choose between tools, resources and prompts and design each well.
Day 73: Resources and Prompts — Build a project documentation MCP server. Today you build a server that exposes synthetic project documents as resources and offers prompt templates built around them.
The steps I would expect you to follow are these. First, create a folder of synthetic documentation for a fictional project, including a readme, an architecture note, a changelog and a troubleshooting guide. Second, expose each document as an MCP resource with a URI, a title, a description and a media type, and add a resource template that retrieves a document by name. Third, restrict access strictly to the documentation folder and test that attempts to read outside it are refused. Fourth, define two or three prompts, such as a release-notes summary and an onboarding guide request, each with typed arguments. Fifth, test with a client that lists and reads the resources and fetches the prompts, and confirm that missing documents give clear errors. Sixth, set a size limit on resources and verify that oversized documents are handled gracefully.
Check that your server never returns content from outside the intended folder, and write a test that proves it.
Keep the server, the sample documents and the tests together, because the next project builds a client that discovers and uses these capabilities.
By the end of this project you will have a server that shares knowledge safely and consistently.
MCP Discovery and Invocation. A server is useful only when a client can find out what it offers and call it correctly. This lecture looks at the client side of MCP, covering how a host connects to servers, discovers their capabilities and invokes them on behalf of a model and a user.
The client begins by launching or connecting to a server and performing the initialization handshake, in which both sides declare their protocol version and supported features. The client then lists the available tools, resources and prompts. These listings may change during a session, and servers can notify clients when they do, so a robust client refreshes its view.
To use tools with a model, the host converts the server's tool descriptions into the format the model expects, lets the model request a call, executes it through the protocol and returns the result. The host remains the decision maker. It can show the call to the user, ask for confirmation, apply policy and decline.
We discuss practical issues, including timeouts, cancellation, progress notifications, large results and reconnecting after a failure. We also discuss handling multiple servers at once, which raises the issue of name collisions between tools and the need to namespace them. Finally, we discuss logging every invocation for troubleshooting and audit.
By the end of this lecture you will be able to build a client that discovers and invokes server capabilities reliably.
Day 74: MCP Clients — Build a client that discovers and invokes server capabilities. Today you write a client that connects to the servers you built earlier and calls their tools.
The steps I would expect you to follow are these. First, use the MCP software development kit to write a client that launches a server over standard input and output and completes the handshake. Second, list the tools, resources and prompts the server offers, and print them in a readable summary that includes descriptions and parameter names. Third, write a function that converts tool definitions into the format your model client expects, so that a model can request them. Fourth, build the invocation path, so that when a tool request arrives, the client validates it, calls the server, handles errors and timeouts and returns the result. Fifth, connect to two servers at once, namespace their tools to avoid name collisions and confirm that requests reach the correct server. Sixth, add a confirmation step that asks the user before any tool call is made, and log each invocation with its arguments and result.
Test what happens when a server crashes mid-session, and make sure that the client reports it clearly and recovers or stops cleanly.
Keep the client, the configuration listing the servers and the tests together, since later projects reuse this client as the bridge between assistants and tools.
By the end of this project you will have a dependable client that works with more than one server.
Database Tools and Least Privilege. Letting an assistant query a database is powerful and hazardous. A careless design can expose private data, run destructive commands or overwhelm the system. This lecture explains how to offer database access through MCP while following the principle of least privilege.
Start with the credentials. The server should connect with a database account that can do only what the tool requires, typically read access to a few specific tables or views. Even if everything else fails, the database itself then refuses dangerous operations. Never share an administrator account with an assistant.
Next, shape the interface. Rather than accepting arbitrary query text, prefer narrow tools with typed parameters, such as finding orders by customer and date range. These can use parameterized queries, which keep input separate from the command and prevent injection. If you must accept a query, validate it strictly, allow only a restricted read-only form, apply timeouts and row limits and run it on a replica or sandbox.
We discuss limiting returned data. Return only the needed columns, mask or omit sensitive fields and cap the number of rows. Record each query, with the caller and the outcome, for audit. We also discuss testing with synthetic data and confirming that forbidden requests are denied.
By the end of this lecture you will be able to design database tools that expose useful data while limiting risk.
Day 75: Database Integration — Build a read-only business-query MCP server. Today you build a server that answers business questions from a synthetic database using narrow, read-only tools.
The steps I would expect you to follow are these. First, create a small local database with synthetic tables for customers, orders and products, filled with invented data that includes a column of fictional sensitive values. Second, create a separate read-only database user or connection mode, and confirm that it cannot modify anything. Third, define narrow tools, such as listing orders by date range, summarizing sales by product and looking up a single order, each using parameterized queries with typed arguments. Fourth, apply limits, including a maximum number of rows, a query timeout and omission of the sensitive column from all outputs. Fifth, test with a client, including requests for too many rows, invalid dates and attempts to ask for the omitted column. Sixth, record every query in an audit log with the tool name, arguments and number of rows returned.
Verify that the database refuses a write operation attempted through the read-only connection, to prove that protection exists below your application code.
Keep the server, the schema, the synthetic data and the tests together, so that you can reuse the pattern for other data sources.
By the end of this project you will have a database server that is useful, narrow and restricted.
Document Search Through MCP. Many assistants need to search the documents of an organization, and MCP gives a clean way to offer that as a shared service. This lecture shows how to expose document search as a tool, while keeping retrieval quality, citations and access control intact.
The server wraps the retrieval pipeline built earlier in the course. A search tool accepts a query and optional filters and returns a short list of passages, each with a title, an excerpt, a source location, a score and an identifier. A separate read tool may fetch a full passage or a document section by identifier. Keeping these two tools apart lets the model search broadly and then read selectively, saving context space.
Access control must live inside the server. The caller's identity determines which documents are eligible, and filters are applied before results are returned. The model should not be able to widen its own access through the arguments it supplies. We discuss passing identity from the host to the server securely.
Results are untrusted text, since a document may contain instructions or misleading content. We discuss labeling returned content clearly as data, and returning excerpts without active formatting.
We also discuss pagination, ranking transparency, handling empty results, caching and keeping the index fresh as documents change.
By the end of this lecture you will be able to design a document search service that is useful, citable and permission-aware.
Day 76: Document Integration — Build an MCP document search service. Today you wrap your retrieval pipeline in an MCP server that other assistants can use.
The steps I would expect you to follow are these. First, reuse the synthetic documents and the index from the earlier retrieval projects, including metadata for department and status. Second, create a search tool that takes a query, an optional number of results and optional filters, and returns passages with identifiers, titles, excerpts, locations and scores. Third, create a read tool that returns a specific passage or section by identifier, with a length limit. Fourth, apply access rules inside the server, using a caller identity that determines which departments and statuses are visible. Fifth, label all returned text as document content and strip any markup that could be mistaken for instructions. Sixth, test with a client for normal queries, empty results, requests for restricted material and oversized requests, and confirm each is handled correctly.
Write a test that tries to read a restricted passage by guessing its identifier, and confirm that the server refuses it.
Keep the server, the index configuration and the tests together, so that any assistant can rely on the same service and its behavior stays verified.
By the end of this project you will have a reusable document search service that respects the permissions of whoever is asking.
External Tools and Idempotent Actions. Reading information is one thing, but assistants also need to act on other systems, such as creating a ticket, scheduling a meeting or posting a message. These actions change the world and cannot easily be undone, so they need extra care. This lecture explains how to connect to external services responsibly.
Begin with the credentials and scope. Use tokens that grant only the permissions the tool needs, store them in a secrets manager or environment, never in code or prompts, and rotate them. Prefer a sandbox or test environment during development, so that mistakes affect nothing real.
Next, design the tools around clear actions with strict arguments. Separate preview from commit where possible, so that the user or the system can see what will happen before it does. Mark tools that change state, so that the host can request confirmation.
Idempotency is vital. Network failures and retries can cause the same request to be sent twice. Supplying an idempotency key lets the external service recognize a duplicate and return the original result instead of creating a second ticket. We discuss designing keys, storing outcomes and checking for existing resources before creating new ones.
We also discuss rate limits, timeouts, translating external errors into helpful messages and logging every action for audit.
By the end of this lecture you will be able to build external action tools that are safe to retry and easy to audit.
Day 77: External API Integration — Build a sandbox issue-tracker connector. Today you build an MCP server that creates and updates issues in a fake issue tracker running on your own machine.
The steps I would expect you to follow are these. First, build or use a tiny local mock issue-tracker service with endpoints to create, read, update and list issues, and make it enforce a token for access. Second, create an MCP server with tools for searching issues, reading an issue, creating an issue and adding a comment, each with typed arguments and limits on text length. Third, load the token from the environment, and make the server refuse to start with a clear message if it is missing. Fourth, add a preview mode for the creation tool that shows what would be created without doing it. Fifth, implement idempotency keys so that repeating the same creation request returns the existing issue instead of a duplicate. Sixth, test error handling by making the mock service time out, return an error and reject the token, and confirm that each produces a clear, safe message.
Mark the state-changing tools in their descriptions so that a client can ask for confirmation before using them.
Keep the mock service, the server and the tests together, since the next projects add authorization and security checks around this connector.
By the end of this project you will have an external connector that can be retried safely and audited afterward.
Identity and Tool Authorization. A server that exposes tools must know who is calling and what that caller may do. Without this, anyone who can reach the server can use every tool. This lecture explains authentication and authorization for MCP servers and the assistants that use them.
Authentication establishes identity. For remote servers, MCP builds on OAuth, in which a user signs in with an identity provider and the client obtains an access token that it presents with each request. The server validates the token, including its signature, issuer, audience and expiry. Tokens must be scoped to the particular server, which prevents a token meant for one service from being accepted by another.
Authorization decides what the authenticated caller may do. Define permissions for each tool and resource, such as read documents or create issues, and map users or roles to them. Check permissions on every call, inside the server, not only in the host's interface. Deny by default, and give new tools no access until it is explicitly assigned.
We discuss several pitfalls. Do not pass tokens through to other services without proper exchange. Do not let tool arguments override the caller's identity. Keep tokens out of logs and prompts. We also discuss consent, in which users see which permissions an assistant requests, and revocation, so that access can be withdrawn quickly.
By the end of this lecture you will be able to design authentication and per-tool authorization for MCP.
Day 78: Authentication and Authorization — Build permission checks for an MCP server. Today you add identity checks and per-tool permissions to a server that you built earlier.
The steps I would expect you to follow are these. First, choose a server with several tools of different sensitivity, such as your issue-tracker connector, and define permissions like read, comment and create. Second, define roles in a configuration, such as viewer, contributor and maintainer, and map each to a set of permissions. Third, implement token validation using locally generated test tokens that carry a user, a role, an audience and an expiry, and reject tokens that are expired, intended for another audience or incorrectly signed. Fourth, add a check at the start of every tool that confirms the caller holds the necessary permission, defaulting to denial. Fifth, ensure that the caller's identity comes only from the validated token and never from tool arguments. Sixth, write tests for every role and every tool, including expired and wrongly addressed tokens, and confirm that denials return clear messages without revealing internal details.
Log each decision with the caller, the tool and the result, so that access can be reviewed later.
Keep the configuration, the validation code and the permission tests together, since the next project builds on them.
By the end of this project you will have a server that knows who is calling and what each caller may do.
Prompt Injection and Integration Security. When an assistant reads content from documents, web pages, tickets or tool results, that content may contain text written to steer the model into doing something its user never intended. This is called prompt injection, and it becomes serious when the assistant holds powerful tools. This lecture explains the risk and the defenses, at a conceptual level.
The core problem is that models do not reliably distinguish instructions from data. Anything placed in the context might influence behavior. The danger is greatest when three conditions meet: the assistant can read untrusted content, it can access private information and it can take external actions. Removing any one of these narrows the risk considerably.
Defense relies on layers. Treat all retrieved and tool-provided content as untrusted data, and label it clearly. Limit what tools can do through least privilege, so that even a misled model has little power. Require confirmation for consequential actions and show the person exactly what will happen. Validate tool arguments in code and restrict where data may be sent. Isolate sensitive data from tools that communicate externally.
We also discuss unauthorized access risks, such as confused deputy problems, in which a server acts with more authority than the caller deserves. We discuss logging, monitoring for unusual tool sequences and testing your own system regularly in a sandbox using harmless markers.
By the end of this lecture you will be able to explain injection risks and apply layered defenses.
Day 79: Integration Security — Build adversarial and unauthorized-access tests. Today you build a defensive test suite that checks, in your own sandbox, whether your integrations resist misuse. Everything here is authorized testing of systems you built yourself, using harmless markers and synthetic data.
The steps I would expect you to follow are these. First, set up an isolated sandbox containing your own MCP servers, a fake issue tracker and synthetic documents, with no real credentials and no network access beyond your machine. Second, create test documents that contain a harmless marker phrase presented as an instruction, such as a request to include a specific nonsense word in the reply, and check whether the assistant treats it as data or obeys it. Third, write access tests that call each tool with identities lacking the required permission, expired tokens and arguments that try to name another user, and confirm every attempt is denied. Fourth, test that a restricted document cannot be read by guessing its identifier. Fifth, check that tools requiring approval cannot run without it. Sixth, record each test's expected and actual result in a report, mark any failure as a defect to fix and rerun after the fix.
Keep these tests inside the sandbox only, and never point them at systems that you do not own or have permission to test.
Keep the test suite, the marker documents and the reports together, so that the checks run again after every change.
By the end of this project you will have a repeatable defensive suite that shows whether your integration controls actually work.
Multi-Server Tool Orchestration. Real assistants rarely rely on one server. A single request might require searching documents, querying a database and creating a ticket, each handled by a different MCP server. This lecture explains how to orchestrate several servers coherently and safely.
The host maintains a client connection to each server and presents the combined set of tools to the model. Because different servers may use the same tool name, the host namespaces them, so that each is identified as belonging to a particular server. It also decides which tools to expose for a given task. Offering fewer, relevant tools improves the model's choices and reduces risk.
Orchestration includes sequencing calls, passing results from one server into another and handling partial failure. If the document search succeeds but the ticket creation fails, the assistant should report that accurately and avoid repeating the successful steps. We discuss tracing a request across servers with a shared identifier.
Security needs special attention. Servers differ in trust levels, and content from a less trusted one should not be allowed to drive actions on a more sensitive one without checks. We discuss separating data flows, enforcing policies in the host and applying consistent identity and permissions across servers.
Finally, we discuss performance, running independent calls in parallel, timeouts for slow servers and graceful behavior when a server is unavailable.
By the end of this lecture you will be able to design a host that coordinates multiple servers with clear boundaries.
Day 80: Enterprise Assistant Integration — Build an assistant connected to multiple tool servers. Today you finish the integration section by connecting an assistant to your document, database and issue-tracker servers.
The steps I would expect you to follow are these. First, gather the servers from earlier projects and define a configuration that lists each server, its transport and its trust level. Second, build a host that connects to them all, namespaces their tools and exposes only the tools relevant to a given task. Third, connect the host to your model client and agent loop, with step limits and tracing from the previous section. Fourth, apply permissions consistently by passing the same caller identity to every server, and require approval before any state-changing tool runs. Fifth, create several scenarios, such as finding a policy, summarizing recent orders and opening an issue about a problem, and script the mock model to follow them. Sixth, test failure cases, including one server being unavailable, one tool returning an error and a request that the caller is not permitted to make, and confirm the assistant reports each honestly.
Add a shared request identifier to every log line, so that a whole conversation can be traced across servers.
Keep the host, the configuration, the scenarios and the traces together, since this assistant becomes part of the application you will deploy in the next section.
By the end of this project you will have an assistant that uses several tools under consistent control.
Model Serving Through Typed APIs. Until now your AI code has run in scripts and notebooks. To be used by a product, a team or other systems, it must be offered through an interface that other programs can call reliably. This lecture introduces FastAPI, a Python framework for building web APIs, and explains why typed interfaces matter so much for AI applications.
An API defines endpoints, each with a method, a path, an expected input and a promised output. FastAPI uses Python type hints and Pydantic models to describe those inputs and outputs. The framework validates each incoming request automatically, rejects malformed ones with clear errors and generates interactive documentation from your code. This keeps documentation and behavior aligned.
We discuss designing endpoints for AI features. Requests should carry only what is needed, such as a question and optional settings, with sensible limits on length. Responses should be structured, including the answer, citations, identifiers and usage information, and errors should follow a consistent format. Separate the web layer from the model logic, so that your pipeline can be tested without running a server.
You will also learn about dependency injection, which supplies shared resources such as clients and settings, about health endpoints that report whether the service is ready and about versioning an API so that changes do not break existing callers.
By the end of this lecture you will be able to design a typed, documented API around an AI capability.
Day 81: FastAPI Fundamentals — Build a typed AI application API. Today you wrap an AI feature in a web service with validated requests and structured responses.
The steps I would expect you to follow are these. First, create a FastAPI project and choose a feature from earlier work, such as the question-answering assistant or the ticket classifier, running with your mock client. Second, define request and response models with Pydantic, including length limits, required fields and a structured error shape. Third, write the endpoint that validates the input, calls your pipeline and returns the structured result, including a request identifier and token usage. Fourth, add a health endpoint that reports readiness, and a version prefix on your paths. Fifth, use dependency injection to supply settings and the model client, so that tests can substitute the mock. Sixth, write tests using the framework's test client that cover valid requests, missing fields, oversized input and an internal failure, confirming the response format each time.
Open the generated documentation page, try your endpoints from it and check that the descriptions make sense to someone who has not seen the code.
Keep the application, the models and the tests together, since all later projects in this section extend this service.
By the end of this project you will have a typed and tested API for an AI feature.
Asynchronous AI Workloads. Some AI tasks take far longer than a web request should wait. Ingesting a large set of documents, generating embeddings, running an evaluation or processing a batch of files can take minutes. This lecture explains how to move such work into the background while keeping users informed.
The pattern is to accept a request, create a job record with a unique identifier and a status, return that identifier immediately and process the work separately. The client then checks the job's status, or receives a notification, and retrieves the result when it is ready. Typical statuses include queued, running, succeeded, failed and cancelled, with progress information where possible.
Execution can happen in several ways. Simple background tasks run in the same process, which is easy but loses work if the process restarts. A task queue with separate workers is more durable and scalable. We discuss when each is appropriate, and the need to store job state in a database rather than in memory.
Reliability matters. Jobs should be idempotent, so that a retry does not duplicate effects. Failures should be recorded with a clear reason, retries should be limited and stuck jobs should time out. We also discuss concurrency limits, so that a flood of jobs cannot exhaust resources, and cancellation.
By the end of this lecture you will be able to design background jobs with visible status and safe recovery.
Day 82: Background Jobs — Build asynchronous document ingestion with job status tracking. Today you add a job system to your API so that large ingestion tasks run in the background while users watch their progress.
The steps I would expect you to follow are these. First, define a job record with an identifier, type, status, progress, timestamps, a result summary and an error field, and store it in a small database. Second, create an endpoint that accepts a batch of synthetic documents, creates a job and returns its identifier immediately. Third, write a worker that picks up queued jobs, runs your ingestion and indexing steps, updates progress after each document and records the final outcome. Fourth, create a status endpoint that returns the current state, and a cancellation endpoint that stops a running job cleanly. Fifth, make the processing idempotent and record per-document results, so that a retry skips what is already done. Sixth, test normal completion, a failure partway through, a cancellation and a restart of the worker, confirming the job states each time.
Add a limit on how many jobs can run at once and a timeout for jobs that make no progress.
Keep the job model, the worker, the endpoints and the tests together, so that other long-running tasks can reuse the same machinery.
By the end of this project you will have a background job system with clear status and dependable recovery.
Application Authentication and Authorization. A web API that exposes an AI feature needs to know who is calling and what they are allowed to do. This lecture covers authentication, which establishes identity, and authorization, which decides permissions, for AI applications built with FastAPI.
Authentication commonly relies on tokens. A user signs in through an identity provider, receives a signed token and presents it with each request. The API verifies the signature, issuer, audience and expiry, then extracts the user's identity and attributes. Passwords, if handled at all, must be stored only as strong salted hashes, though using an established identity provider is usually wiser than building your own.
Authorization is a separate step. Define roles, such as viewer, analyst and administrator, and map them to permissions, such as asking questions, uploading documents or viewing audit logs. Check permissions on every endpoint, using reusable dependencies, so that no route is accidentally left open. Deny by default.
AI features raise additional questions. Which documents may this user retrieve? Which tools may the assistant call on their behalf? The user's identity must flow through the whole pipeline into retrieval filters and tool permissions. We discuss protecting administrative functions, rate limiting by user and recording security-relevant events for audit.
By the end of this lecture you will be able to add authentication and role-based authorization to an AI API.
Day 83: Authentication and User Roles — Build a role-aware AI API. Today you secure your service so that every request has an identity and every endpoint checks permissions.
The steps I would expect you to follow are these. First, define several synthetic users and roles, such as viewer, analyst and administrator, and a table of permissions for each role. Second, implement token validation using locally generated test tokens that carry a subject, a role and an expiry, and reject tokens that are missing, expired or malformed. Third, write a reusable dependency that extracts the current user, and another that requires a specific permission. Fourth, apply them to your endpoints, so that viewers may ask questions, analysts may upload documents and only administrators may view audit logs and manage users. Fifth, pass the user's identity into the retrieval step, so that results depend on what the user may see. Sixth, write tests for every role and endpoint, including missing tokens, expired tokens and attempts to reach administrative routes with an ordinary role.
Confirm that error responses are consistent and reveal nothing about internal structure, and log every denied request with the user and the endpoint.
Keep the token helpers, the dependencies, the permission table and the tests together, so that new endpoints inherit the same protection.
By the end of this project you will have an API that knows its callers and enforces what each may do.
Tenant Isolation Across AI Data Paths. Many AI products serve several customers, called tenants, from the same system. Each tenant must see only its own data, and a failure of that rule is among the most serious mistakes a multi-tenant product can make. This lecture explains how to keep tenants separate across every place data can travel.
Isolation must be considered along the entire path. Documents are stored with a tenant identifier. Chunks and embeddings inherit it. Vector index queries must apply a tenant filter, or use a separate index or namespace per tenant. Caches need tenant-aware keys. Prompts and conversation histories must never combine material from different tenants. Logs, traces and evaluation sets also contain data and need the same care.
The tenant identity should come from the authenticated token, not from a request parameter that a caller could change. Enforce it at a low level, for example in a data access layer that adds the filter automatically, so that individual developers cannot forget it. Defense in depth, with several independent checks, reduces the chance that one mistake becomes a leak.
We discuss testing isolation directly, by creating two synthetic tenants with overlapping content and confirming that queries never cross over. We also discuss tenant-specific deletion, backups, limits that prevent one tenant from starving others and monitoring for anomalies.
By the end of this lecture you will be able to design and test tenant isolation across storage, retrieval and generation.
Day 84: Tenant Isolation — Build tenant-scoped storage and retrieval. Today you add tenant boundaries to your service and prove that they hold.
The steps I would expect you to follow are these. First, create two or three synthetic tenants with distinct users and overlapping documents, including one pair of nearly identical passages in different tenants. Second, add a tenant identifier to every stored document, chunk, embedding, cache entry and job record. Third, derive the tenant from the authenticated token and write a data access layer that applies the tenant filter automatically to every query, so that endpoint code cannot omit it. Fourth, make retrieval, caching and conversation history tenant-aware, and confirm that prompts only ever contain one tenant's content. Fifth, write tests in which a user from one tenant asks questions designed to match the other tenant's material, and confirm that nothing from it appears in any result, citation, cache or log. Sixth, test a deletion request for one tenant and confirm that its data disappears from every store while the others remain intact.
Add a startup or scheduled check that scans stored records for missing tenant identifiers and reports them.
Keep the data access layer, the synthetic tenants and the isolation tests together, since they should run on every future change.
By the end of this project you will have evidence that your service keeps tenants apart.
AI Interface State and Evidence. A good AI interface is more than a text box. It must show what the system is doing, let people see the evidence behind an answer and collect feedback that improves quality. This lecture covers the design of interfaces for AI features and the state they must manage.
Responses arrive gradually when streaming is used, so the interface needs states for waiting, receiving, completed, stopped and failed. Each state should be visible and recoverable. Users need a way to stop generation, retry after an error and edit a previous question. We discuss handling partial text, maintaining scroll position and keeping the interface responsive during long responses.
Evidence is central to trust. Show citations next to the claims they support, allow users to open the cited passage in context and distinguish clearly between what the documents say and what the model inferred. When the assistant abstains, explain why and suggest next steps. Display confidence cautiously, since numbers can mislead.
Feedback closes the loop. Simple controls such as helpful and unhelpful, with an optional comment, produce data that can become evaluation cases. Store feedback with the question, answer, sources and versions, taking privacy into account.
We also discuss accessibility, safe rendering of model output, which may contain markup that must not run as code, and clear labeling so people know they are interacting with an AI.
By the end of this lecture you will be able to design an AI interface that is transparent, recoverable and useful.
Day 85: AI User Interfaces — Build an interface with streaming, citations, and feedback. Today you build a browser interface for your assistant that shows live answers, verifiable sources and a way to give feedback.
The steps I would expect you to follow are these. First, create a simple web page, using plain pages or a lightweight framework, that calls your streaming endpoint. Second, implement interface states for idle, waiting, streaming, stopped, complete and error, and display each clearly. Third, append text as it arrives and add a stop button and a retry option. Fourth, render the answer safely, escaping any markup so that model output can never run as code in the page. Fifth, display numbered citations beside the answer, and let the user open the cited excerpt with its document name and location. Sixth, add helpful and unhelpful buttons with an optional comment, sending the feedback along with the question, answer, sources and version identifiers to a feedback endpoint that stores it.
Test with a very long answer, an abstention, a dropped connection and an answer with no citations, and confirm that the page always remains usable.
Check the interface using only the keyboard and confirm that labels are meaningful for people who use screen readers.
Keep the page, the endpoint and the feedback store together, since the stored feedback will help you build further evaluation cases.
By the end of this project you will have an interface that makes AI answers visible, verifiable and improvable.
Reproducible AI Deployment Environments. An application that works on your machine but fails elsewhere is not ready for users. Containers solve much of this problem by packaging code, dependencies and runtime settings into a portable unit that behaves the same wherever it runs. This lecture introduces containers for AI applications.
A container image is built from a recipe, usually a Dockerfile, that starts from a base image, installs dependencies, copies the code and defines the start command. Good practice includes pinning versions so that builds are repeatable, using small base images, ordering steps to benefit from caching, running as a non-root user and excluding unnecessary files, especially secrets and local data.
AI applications bring particular issues. Model files can be large, so decide whether to bake them into the image or download them at startup into a mounted volume. Some workloads need graphics hardware, which affects the base image and the hosting environment. Vector stores and databases usually run as separate containers, and a composition file describes how the pieces connect.
Configuration should come from environment variables or mounted files, not from the image. We discuss separate settings for development, testing and production, health checks, resource limits and scanning images for known vulnerabilities.
By the end of this lecture you will be able to package an AI application and its supporting services reproducibly.
Day 86: Containers and Configuration — Containerize an AI application and its services. Today you package your API and its supporting services so that the whole system starts with a single command.
The steps I would expect you to follow are these. First, write a Dockerfile for your API using a small, pinned base image, installing dependencies in a cacheable step, running as a non-root user and defining a clear start command. Second, add an ignore file so that secrets, local data and caches are never copied into the image. Third, write a composition file that starts the API together with a database and a vector store, with named volumes for persistent data and a network that connects them. Fourth, move all settings into environment variables, provide a sample environment file with placeholder values and confirm that the application refuses to start with a clear message when a required setting is missing. Fifth, add health checks and make the API wait until its dependencies are ready. Sixth, start the whole stack from scratch, run your test requests against it and confirm that data survives a restart.
Inspect the built image to confirm that it contains no secrets, and run a vulnerability scan if one is available.
Keep the Dockerfile, the composition file and the sample environment together, so that anyone can reproduce the environment from a fresh checkout.
By the end of this project you will have a repeatable, configurable container setup for the entire application.
Continuous Evaluation and Integration. Software teams rely on automated pipelines that check every change before it is accepted. AI applications need the same discipline, with an additional challenge: their behavior can degrade without any code failing. This lecture explains continuous integration for AI systems, including automated quality evaluation.
A pipeline typically runs on every proposed change. It installs dependencies, checks formatting and style, runs static analysis and executes unit tests. It builds the container image and may run integration tests against the composition stack. Fast checks run first, so that developers get quick feedback, and slower ones follow.
AI-specific checks come next. Tests that use the mock client confirm the logic of your pipeline deterministically. Evaluation suites measure retrieval quality, answer faithfulness, citation accuracy, abstention and safety against a stored dataset. The pipeline compares scores with a baseline and fails if they fall below agreed thresholds. Because real model calls cost money and vary, we discuss using small, fixed evaluation sets, caching and running full evaluations on a schedule rather than for every commit.
We also discuss securing the pipeline itself. Keep secrets in the platform's secret store, grant minimal permissions, pin the versions of third-party actions and scan dependencies for known vulnerabilities. Finally, we discuss publishing artifacts, such as images and evaluation reports, with version information attached.
By the end of this lecture you will be able to design a pipeline that guards both code correctness and AI quality.
Day 87: Continuous Integration — Build an automated test and build pipeline. Today you create a pipeline that tests, evaluates and builds your application on every change.
The steps I would expect you to follow are these. First, write a pipeline definition for your preferred platform that triggers on every proposed change and on merges to the main branch. Second, add stages for installing dependencies with caching, checking style, running static analysis and running the unit tests with the mock client. Third, add a stage that runs your retrieval and answer evaluation suite on a small fixed dataset, compares the results with a stored baseline and fails when any key metric drops beyond an allowed margin. Fourth, add a stage that builds the container image and runs a smoke test by starting it and calling the health endpoint. Fifth, add a dependency vulnerability scan and make high-severity findings fail the build. Sixth, publish the evaluation report and the image tag with the commit identifier as pipeline outputs.
Deliberately introduce a small regression, such as a change that breaks citation formatting, and confirm that the pipeline catches it.
Keep the pipeline definition, the baseline file and a short description of the thresholds together, so that the reasons for each check are clear to future contributors.
By the end of this project you will have an automated gate that protects both your code and your answer quality.
Deployment Readiness and Secrets. Moving an AI application into a real environment raises questions that do not appear on a laptop: where do credentials live, how do you know the service is healthy and how do you release a new version without disrupting users? This lecture covers deployment readiness.
Secrets, such as model provider keys, database passwords and signing keys, must never appear in source control, images or logs. Use a secrets manager or the hosting platform's secret facility, inject values at runtime, grant each service only the secrets it needs and rotate them on a schedule and after any suspected exposure. Separate secrets for each environment so that a development mistake cannot affect production.
Health checks tell the platform whether to send traffic. A liveness check confirms the process is running, while a readiness check confirms that dependencies such as the database and the index are reachable. Startup should fail fast with a clear message when configuration is wrong.
Release strategies reduce risk. Rolling updates replace instances gradually. Blue-green deployments keep the old version ready for instant rollback. Canary releases send a small share of traffic to the new version first. Database and index changes need migration plans that work with both versions during the transition.
We also discuss configuration per environment, resource limits, autoscaling considerations and documenting runbooks for common operations.
By the end of this lecture you will be able to prepare an AI service for a safe and reversible release.
Day 88: Deployment and Secrets — Deploy an AI service with health checks. Today you deploy your containerized application to a test environment with proper secret handling and a rollback plan.
The steps I would expect you to follow are these. First, choose a deployment target available to you, such as a local orchestrator, a small virtual machine or a managed container platform, and keep it a non-production test environment. Second, store configuration values and credentials in the platform's secret facility, inject them at runtime and confirm that they appear in neither the image nor the logs. Third, add liveness and readiness endpoints, and configure the platform to use them. Fourth, deploy the service and run a smoke test against the public address. Fifth, release a second version using a rolling or blue-green approach, verify that requests keep succeeding during the change and practice rolling back to the earlier version. Sixth, write a short runbook describing how to deploy, check health, rotate a secret and roll back.
Rotate one secret deliberately and confirm that the service continues to work after a restart with the new value.
Keep the deployment definitions, the runbook and the smoke tests together, so that the process is repeatable by someone else on your team.
By the end of this project you will have a deployed service with a tested release and rollback routine.
AI Observability and Telemetry Privacy. Once an AI application is live, you need to see what it is doing. Observability means collecting logs, metrics and traces so that you can understand behavior, find faults and control cost. For AI systems it also means doing so without collecting more personal or confidential information than necessary.
Logs record events, metrics measure quantities over time, and traces follow a request across components. A single question may pass through authentication, query rewriting, retrieval, reranking, generation and verification. A trace with a span for each stage, tagged with timing, outcome and version identifiers, shows where time and money are spent and where failures originate.
Useful AI metrics include request volume, latency percentiles, error rates, token usage, cost, retrieval hit rates, abstention rates, citation verification failures and user feedback. Alerts on sudden changes help you notice problems before users report them. We discuss dashboards that different people can use, from engineers to product owners.
Privacy needs deliberate design. Prompts, retrieved passages and answers can contain sensitive information. Log identifiers and metadata by default, redact or hash sensitive fields, restrict who may view stored content, set retention limits and honor deletion requests. When detailed traces are required for debugging, sample them and protect them carefully.
By the end of this lecture you will be able to design useful telemetry for an AI service that respects privacy.
Day 89: Observability — Build tracing, error monitoring, and cost reporting. Today you instrument your service so that you can follow a request through every stage and see what it costs.
The steps I would expect you to follow are these. First, add structured logging with a request identifier, user and tenant identifiers, endpoint, duration and outcome, and confirm that no prompts or personal data appear by default. Second, add tracing with a span for each pipeline stage, recording timing and version identifiers for the prompt, model and index. Third, collect metrics for request counts, latency percentiles, error rates, token usage, estimated cost, abstentions and citation failures. Fourth, generate synthetic traffic that includes slow requests, failures and a cost spike, and view the results in a dashboard or report. Fifth, add error monitoring that groups similar errors, and alert rules for high error rates and cost above a budget. Sixth, add redaction for sensitive fields, and write tests that search stored telemetry for the synthetic personal details used in your requests.
Practice following one slow request from the dashboard down to the stage that caused the delay.
Keep the instrumentation code, the redaction tests and the dashboard definitions together, so that every new feature adopts the same standards.
By the end of this project you will have visibility into your service's behavior and cost without exposing private content.
Reliability and Graceful Degradation. Production AI services depend on model providers, vector stores and other components that will sometimes be slow, limited or unavailable. Reliability engineering is the practice of making the application behave well when that happens. This lecture covers the main techniques.
Rate limiting protects your service and your budget. Limit requests per user and per tenant, return clear responses when limits are exceeded and apply separate limits to expensive operations. Timeouts and bounded retries, introduced earlier, prevent slow dependencies from tying up resources. Circuit breakers stop calling a failing dependency for a short while, giving it time to recover and keeping your own service responsive.
Graceful degradation means providing a reduced but useful experience when something fails. If the reranker is unavailable, return the original ranking. If the primary model is overloaded, fall back to a smaller one, with a notice where quality may differ. If generation fails but retrieval works, show the relevant passages. If everything fails, return an honest message and a way to try again later.
We discuss caching to absorb repeated requests, queues that smooth bursts, load shedding that rejects low-priority work first and idempotency for safe retries. We also discuss defining service level objectives, testing failure modes deliberately and writing incident procedures so that responses are calm and practiced.
By the end of this lecture you will be able to design an AI service that stays useful when its dependencies falter.
Day 90: Reliability Engineering — Build rate limits, fallbacks, and graceful degradation. Today you make your service resilient, and prove it by breaking its dependencies on purpose.
The steps I would expect you to follow are these. First, add rate limiting per user and per tenant, with a stricter limit on expensive endpoints, and return a clear response that states when the caller may try again. Second, add a circuit breaker around the model client and the reranker, so that repeated failures pause calls for a short period. Third, implement fallbacks, such as the original ranking when reranking fails, a smaller model when the main one is overloaded and a passages-only response when generation is unavailable. Fourth, add a cache for repeated questions, with tenant-aware keys and a short lifetime. Fifth, build a failure simulator that makes each dependency slow, error-prone or unavailable, and run your test requests under each condition. Sixth, record what the user sees in each case, confirm that every response is honest about the reduced service and measure the effect on latency and error rate.
Define a service level objective for availability and latency, and check your measurements against it.
Keep the limiter, the breaker, the fallbacks and the failure scenarios together, so that you can rerun these experiments after every significant change.
By the end of this project you will have a service that degrades gracefully and a record showing how it behaves under stress.
AI Problem Discovery and Success Metrics. Many AI projects fail not because the technology is weak but because nobody agreed on the problem. This lecture explains how to begin an enterprise AI engagement by understanding the customer's real need and turning it into measurable goals.
Discovery starts with people and processes. Interview the users who will rely on the system, the managers who are accountable for the results and the specialists who hold the rules. Ask what the work looks like today, where time is lost, which mistakes are costly and what a good outcome would be. Map the current process step by step, noting the documents, systems and decisions involved.
Next, decide whether AI is appropriate at all. Some problems need a better form, a simple rule or a clean report, not a model. Where AI is suitable, define the task precisely: what goes in, what comes out, who reviews it and what happens when the system is unsure.
Success must be measurable. Define metrics such as time saved, answer accuracy on a reference set, the percentage of answers with valid citations, escalation rate and user satisfaction, and set a baseline from the current process. Agree on thresholds that count as acceptable, and on limits, such as data that must not be used.
We also discuss recording assumptions, risks and constraints in a brief that every stakeholder can review.
By the end of this lecture you will be able to turn a vague request into a scoped problem with measurable criteria.
Day 91: Customer Discovery — Create a discovery brief and measurable success criteria. Today you begin your capstone by studying a fictional customer and writing the brief that guides the rest of the project.
The steps I would expect you to follow are these. First, choose a fictional company and a realistic problem, such as helping employees find and apply internal policies, and write a short profile of the company, its teams and its systems. Second, invent interview notes from three or four roles, including a frontline user, a manager, a compliance specialist and a technology owner, and record their needs and worries. Third, map the current process, listing steps, documents, delays and common errors. Fourth, decide what the assistant will do and what it will not do, including the data it may use and the actions it may never take. Fifth, define success criteria with baselines and thresholds, for example answer accuracy, citation validity, time saved and escalation rate. Sixth, list assumptions, risks and open questions, and give each a proposed way to resolve it.
Review the brief by asking whether a stranger could judge from it, without any opinion, whether the finished system succeeded.
Keep the profile, the interview notes, the process map and the brief together, because every later capstone project refers back to them.
By the end of this project you will have a discovery brief with criteria that can actually be measured.
AI Solution Architecture. Once the problem is clear, you must design a system that solves it and can be built, operated and defended. This lecture explains how to move from requirements to an architecture that a team and a customer can understand and review.
Start with the main building blocks: the interface, the API, the identity and permission layer, the ingestion and indexing pipeline, the retrieval and generation components, the tools and integrations, storage, background processing and observability. For each block, state its responsibility, its inputs and outputs and what it depends on. Draw the main flows, including how a question travels to an answer and how a document travels to the index.
Architecture is a series of trade-offs. Choose between hosted and self-managed models, between one general service and several specialized ones and between speed, cost and quality. Record important decisions in short decision records that state the context, the options considered, the choice and the consequences, so that later readers understand why.
Quality attributes need explicit attention. Define targets for latency, availability, scalability, security, privacy and cost, and describe how the design meets each. Identify the riskiest assumptions and plan early experiments to test them.
We also discuss building a thin end-to-end skeleton first, so that integration problems appear early.
By the end of this lecture you will be able to produce and defend an architecture for an enterprise AI application.
Day 92: Solution Architecture — Build a service skeleton and architecture proposal. Today you turn the discovery brief into a working skeleton and a written design.
The steps I would expect you to follow are these. First, reread your discovery brief and list the functional needs and the quality targets, such as latency, availability, privacy and cost. Second, draw the architecture, showing components, data stores, trust boundaries and the main flows for asking questions and ingesting documents. Third, write decision records for at least four important choices, such as the model provider, the vector store, the way tenants and users are separated and the deployment target. Fourth, create a service skeleton with the project structure, configuration, health endpoint, placeholder modules for each component and the mock model client. Fifth, add a simple end-to-end path that accepts a question and returns a canned answer through every layer, so that integration is proven early. Sixth, write the architecture proposal, covering the design, the risks, the open questions and a delivery plan with milestones.
Ask a colleague, or imagine a skeptical reviewer, to challenge the weakest part of the design, and record the answer.
Keep the diagrams, the decision records, the skeleton and the proposal together in the repository, since they will evolve as the capstone grows.
By the end of this project you will have a runnable skeleton and a design that explains itself.
AI Data Governance and Retention. An enterprise AI system handles documents, questions and answers that may be confidential, regulated or personal. Governance is the set of rules and mechanisms that decide what data may enter the system, how it is protected and when it must be removed. This lecture explains how to build those rules into the design.
Begin by classifying data. Identify categories such as public, internal, confidential and personal, and decide which may be ingested, which need redaction and which must stay out. Record the source, owner, sensitivity and permitted purpose for every document, so that the rules can be applied automatically rather than depending on memory.
Sensitive-data handling includes detection of personal identifiers, masking or removing them where the purpose does not require them, and keeping them out of logs and prompts. Access to stored content should follow least privilege, and data should be encrypted in transit and at rest.
Retention and deletion are equally important. Decide how long documents, embeddings, conversation histories, logs and feedback are kept, and make deletion complete. Removing a source document must also remove its chunks, vectors, caches and any derived summaries. We discuss deletion requests, legal holds and proof that deletion occurred.
We also discuss vendor questions, such as whether a model provider keeps submitted data, and keeping an audit trail of governance decisions.
By the end of this lecture you will be able to design data handling rules that are enforced by the system.
Day 93: Data Governance — Build ingestion with sensitive-data handling and deletion workflows. Today you add governance to the capstone's ingestion pipeline, using only synthetic data.
The steps I would expect you to follow are these. First, create synthetic source documents with metadata for owner, sensitivity and retention period, and include invented personal details such as fictional names, email addresses and account numbers. Second, write a classifier or rule set that assigns a sensitivity level and decides whether each document is accepted, redacted or rejected. Third, implement redaction that replaces the invented personal details with labeled placeholders before indexing, and confirm that the originals do not appear in chunks, embeddings metadata or logs. Fourth, store a governance record for each document, including decisions and timestamps. Fifth, implement a deletion workflow that, given a document identifier, removes the document, its chunks, vectors, caches and derived summaries, and produces a deletion receipt. Sixth, test retention by marking a document as expired and confirming that a scheduled job removes it completely.
Search every store for the synthetic personal details after processing, to prove that the rules truly hold.
Keep the rules, the governance records, the deletion workflow and the tests together, so that the behavior can be reviewed by someone who is not a developer.
By the end of this project you will have ingestion that handles sensitive data deliberately and deletes completely.
Authorization-Aware Enterprise RAG. In an enterprise, not everyone may read everything. A retrieval assistant that ignores this will happily summarize a confidential document for someone who should never see it. This lecture explains how to build retrieval that respects permissions at every step.
Permissions are attached to documents as metadata, such as owning department, allowed groups, sensitivity level and status. At query time, the system obtains the caller's identity and group memberships from the authenticated token or a directory, and converts them into a filter applied during retrieval. Filtering must occur before passages reach the model, because anything placed in the prompt may appear in the answer.
Several details deserve care. Permissions change, so the index must be updated when a document's access rules change, or the filter must consult an up-to-date source. Inherited permissions from folders or teams must be resolved consistently. Caches and conversation histories must not carry content from one user's permitted set into another's. Citations and excerpts must also respect the rules.
We discuss testing authorization directly, using synthetic users with different access and queries designed to tempt the system into retrieving restricted material. We also discuss behavior when access is missing, which should resemble a no-answer response, not reveal that a restricted document exists.
By the end of this lecture you will be able to design and verify permission-aware retrieval.
Day 94: Enterprise Retrieval — Build a permission-aware knowledge assistant. Today you build the capstone's question-answering core so that answers depend on what each user may see.
The steps I would expect you to follow are these. First, create synthetic users in different departments and groups, and documents with access metadata, including shared, department-only and restricted ones. Second, derive the caller's groups from the authenticated token and convert them into a retrieval filter. Third, build the answering path with query rewriting, filtered retrieval, reranking, grounded generation, citation verification and abstention, using your mock client. Fourth, make caches and conversation histories user-aware, and confirm that no content crosses between users. Fifth, write tests in which each user asks the same questions, and confirm that the answers, citations and excerpts differ exactly as their permissions require, with restricted documents never mentioned. Sixth, test a permission change, such as removing a user from a group, and confirm that results update correctly.
Make sure that when the only relevant document is restricted, the assistant gives a normal no-answer response without hinting that it exists.
Keep the permission model, the synthetic users and the authorization tests together, since they become part of the release evaluation later.
By the end of this project you will have an assistant whose answers respect the boundaries of every user.
Approval-Gated Business Agents. An assistant that can only answer questions is useful, but an assistant that can also do work, such as opening a ticket, preparing a purchase request or updating a record, offers much more. Doing work creates responsibility. This lecture explains how to design business agents whose actions are controlled by approvals.
Begin by listing the candidate actions and assigning risk levels. Preparing a draft is low risk, notifying a colleague is moderate and changing a financial record or contacting a customer is high. For each level, define the controls: automatic execution, a single approval, approval by a specific role or approval by two people. Define who is allowed to approve and who is not, since requesters should not approve their own requests.
An approval request should show exactly what will happen, with the arguments, the reasoning, the supporting evidence and the expected effect. The approved action must be the one executed, so bind the approval to the arguments and give it an expiry. Record the requester, approver, time and outcome in an audit trail.
We discuss presenting a preview, supporting edits before approval, handling rejections and designing the agent to continue sensibly after refusal. We also discuss limits on the number and value of actions, and emergency stop controls.
By the end of this lecture you will be able to design business agents that act only within controlled authority.
Day 95: Business Workflow Automation — Build an approval-gated business-action assistant. Today you give the capstone assistant the ability to prepare actions in a sandbox, with a person approving each consequential step.
The steps I would expect you to follow are these. First, define a small set of synthetic business actions, such as drafting a purchase request, opening a support ticket and updating a record in a sandbox system, and assign each a risk level and approval rule. Second, extend your agent so that it can propose these actions with the arguments, a reason and its supporting evidence. Third, implement the approval request, bound to the exact arguments and an expiry, and prevent the requester from approving their own request. Fourth, build a review screen where an authorized approver can approve, reject or edit, and make the executor run only the approved version. Fifth, add limits on how many actions may be proposed and on their value, and an emergency switch that disables all actions. Sixth, test approval, rejection, editing, expiry, self-approval attempts and limit breaches, confirming each outcome and audit entry.
Verify that the sandbox system receives exactly the approved action and nothing more.
Keep the actions, the approval logic, the review screen and the tests together, since they are examined again during the release evaluation.
By the end of this project you will have an assistant that prepares work and leaves authority with people.
Enterprise Integration Boundaries. Enterprise assistants must connect to the systems where work happens, such as document stores, ticketing tools, databases and messaging platforms. Each connection extends the assistant's reach and also the potential harm of a mistake. This lecture explains how to draw clear boundaries around integrations.
Start with an inventory. For every external system, record what the assistant needs from it, which operations are involved, which data crosses the boundary and who owns the system. Choose the narrowest possible access: read-only where reading is enough, specific resources rather than whole systems and separate credentials for each integration.
MCP and similar connectors give a standard way to offer these capabilities, but standardization does not remove the need for judgment. Each connector should validate inputs, enforce permissions on its own side, apply limits and timeouts, return concise results and record an audit trail. Treat content returned from connected systems as untrusted data.
Trust levels differ between systems. Information from a low-trust source should not trigger actions in a high-trust system without checks. We discuss isolating credentials, network restrictions, separate environments for development and production and a sandbox for testing every connector before it touches real data.
We also discuss agreements, such as service limits and ownership of incidents, and a plan for disabling an integration quickly if something goes wrong.
By the end of this lecture you will be able to define and enforce boundaries for enterprise integrations.
Day 96: Enterprise Integrations — Connect sandbox business systems through MCP. Today you connect the capstone assistant to simulated enterprise systems using MCP servers with strict boundaries.
The steps I would expect you to follow are these. First, create sandbox versions of two or three systems, such as a document store, a ticketing service and a customer database, with synthetic data and test credentials only. Second, write an inventory that lists each system, the operations needed, the data crossing the boundary and the owner. Third, build an MCP server for each, with narrow typed tools, separate least-privilege credentials, input validation, limits, timeouts and audit logging. Fourth, connect them to your host through the client from earlier projects, namespacing the tools and applying the same caller identity to every server. Fifth, label all returned content as untrusted data, and require approval for any tool that changes state. Sixth, test normal use, an unavailable server, an expired credential and a request that the caller has no permission to make, confirming that each is handled clearly and recorded.
Practice the emergency step of disabling one connector, and confirm that the assistant continues to work with the others and reports what it cannot do.
Keep the inventory, the servers, the configuration and the tests together, so that the integration boundaries are documented as well as enforced.
By the end of this project you will have connected systems that remain narrow, audited and controllable.
Release Evaluation and Adversarial Testing. Before an enterprise AI system reaches users, it must be examined against the quality targets agreed with the customer and against realistic misuse. This lecture explains how to build a release evaluation that covers both, at a conceptual and defensive level, within systems you own.
Quality evaluation reuses the suites from earlier lessons. Measure retrieval, answer faithfulness, citation validity, abstention behavior and agent trajectories on a versioned dataset that reflects the customer's real questions. Compare the results with the thresholds in the discovery brief, and record the system versions that were tested.
Adversarial testing asks how the system behaves when someone does not cooperate. In a sandbox, using synthetic data and harmless markers, you check whether instructions hidden in documents are treated as data, whether users can reach material beyond their permissions, whether approval gates can be bypassed and whether sensitive information appears in logs. Each test has an expected safe behavior, and any deviation is recorded as a defect.
Such testing is authorized, scoped and contained. Never run it against systems or data that you do not own or have permission to test. Document the scope and the rules before you begin.
We also discuss triaging findings by severity, fixing and retesting, and reporting residual risks honestly.
By the end of this lecture you will be able to plan a release evaluation that covers quality and safety.
Day 97: Quality and Security Evaluation — Build a capstone release evaluation suite. Today you assemble a repeatable suite that checks the quality and safety of your finished assistant in your own sandbox.
The steps I would expect you to follow are these. First, collect the evaluation sets from earlier projects into one versioned dataset covering answerable, unanswerable, permission-sensitive and action-related cases, with expected behaviors. Second, run retrieval, answer, citation and abstention checks, and agent trajectory checks, saving every result. Third, add defensive security cases that run only inside your sandbox, such as documents containing a harmless marker phrase presented as an instruction, users requesting material outside their permissions, approval requests altered after review and searches of logs for the synthetic personal details. Fourth, define the expected safe outcome for each case, and have the suite report passes, failures and defects with severity. Fifth, compare the totals with the thresholds from your discovery brief, and produce a release report that states what was tested and which version it applied to. Sixth, fix at least one defect, rerun the suite and confirm that it is resolved without causing others.
Record the scope of testing clearly, and keep the suite pointed only at your own sandbox.
Keep the dataset, the checks and the saved reports together, so that every future release can be compared with this one.
By the end of this project you will have a release gate based on evidence.
Operational Readiness and Recovery. A system that passes its evaluation can still fail in operation, through heavy load, a failing dependency, a corrupted index or a mistaken deployment. Operational readiness means you have prepared for these events and rehearsed your response. This lecture explains what to prepare.
Begin with capacity. Estimate expected traffic and peaks, then run load tests to find where latency rises and where errors begin. Identify the bottleneck, whether the model provider, the vector store or the database, and decide on limits, scaling and queues. Confirm that rate limits and graceful degradation behave as designed under pressure.
Recovery planning follows. Define what must be backed up, such as databases, indexes and configuration, how often and how restoration will be tested. State objectives for how much data you can afford to lose and how long you can afford to be down. A backup that has never been restored is only a hope.
Operations also need documentation. A runbook lists routine procedures such as deployment, secret rotation and rollback, and troubleshooting steps for common alerts. Define roles for incidents, a communication path and a habit of reviewing incidents without blame.
We discuss monitoring and alerts that map to the objectives, so that people are told about problems that matter and not about noise.
By the end of this lecture you will be able to prepare an AI service for dependable operation.
Day 98: Production Readiness — Run load and recovery exercises and create a runbook. Today you test how your capstone behaves under pressure and write the guide that others would use to operate it.
The steps I would expect you to follow are these. First, state your expected traffic and your objectives for latency, error rate, availability, data loss and recovery time. Second, write a load test that sends a realistic mix of requests with the mock model client, increases traffic in stages and records latency and errors, then identify the first bottleneck. Third, confirm that rate limits and fallbacks activate as designed, and that the service returns to normal when the load drops. Fourth, perform a backup of your databases and index, deliberately damage a copy, restore from the backup and verify the data with sample queries and counts. Fifth, rehearse an incident, for example a failing dependency, by following your own procedures and noting any steps that were unclear. Sixth, write the runbook covering deployment, rollback, secret rotation, backup and restoration, common alerts and their responses, and escalation contacts.
Record the actual recovery time and compare it with your objective.
Keep the load scripts, the results, the restoration evidence and the runbook together, since they form part of the evidence you present to the customer.
By the end of this project you will have shown, not merely claimed, that your service can be operated and recovered.
Customer Acceptance and Evidence-Based Demonstration. A project is finished when the customer agrees that it meets their needs, and agreement depends on evidence. This lecture explains how to prepare for acceptance and how to give a demonstration that is honest and persuasive.
Acceptance begins with the criteria from the discovery brief. For each success metric, gather the measured result, the method used and the version of the system that produced it. Present the results against the thresholds, including those that were missed, with an explanation and a plan. Customers trust teams that report limitations plainly.
A demonstration should follow a story that matches the customer's work. Walk through realistic tasks from start to finish: asking a question and checking the citations, seeing how a restricted document is handled, requesting an action and watching the approval, and observing how the system behaves when a dependency fails. Use synthetic or approved data, and prepare for questions about cost, security, privacy and maintenance.
Avoid overclaiming. Do not describe the system as more accurate, more autonomous or more secure than your evidence shows. State what was tested, what was not and what remains uncertain. Offer a list of known limitations and recommended next steps.
We also discuss recording customer feedback, agreeing on any follow-up work and obtaining a clear sign-off decision.
By the end of this lecture you will be able to prepare acceptance evidence and deliver an honest demonstration.
Day 99: Customer Acceptance and Demonstration — Create an acceptance report and demonstration plan. Today you prepare the evidence and the walkthrough that you would present to your fictional customer.
The steps I would expect you to follow are these. First, return to your discovery brief and list every success criterion with its threshold and baseline. Second, gather the measured result for each from your release evaluation, load tests and quality reports, noting the method and the system version, and highlight any criterion that was not met with an explanation and a plan. Third, write an acceptance report with a summary, the results table, the known limitations, the residual risks and recommended next steps. Fourth, plan a demonstration that follows the customer's real tasks, including a cited answer, a permission-restricted case, an approved action and a dependency failure, and prepare synthetic data for each. Fifth, write answers to the likely questions about cost, security, privacy, maintenance and support. Sixth, rehearse the demonstration from beginning to end, timing it and noting anything that could fail on the day.
Check every statement in your report against the saved evidence and remove any claim that you cannot support.
Keep the report, the demonstration script, the data and the rehearsal notes together, since they feed the final release project.
By the end of this project you will have an honest acceptance package that stands up to scrutiny.
Reproducible Release and Responsible Portfolio Claims. The final step of an engineering project is to release it in a form that others can inspect, reproduce and trust, and to describe your own contribution accurately. This lecture covers both the technical release and the way you present your work.
A reproducible release means a tagged version of the code, a built container image, pinned dependencies, documented configuration with placeholder values, a clean installation guide and sample data that lets anyone run the application. Include architecture notes, decision records, the evaluation results and the runbook. Check that no secrets, personal data or proprietary material are anywhere in the repository history, and choose a license deliberately.
Responsible portfolio claims matter just as much. Describe what you built and what you measured, using the real numbers from your evaluations and naming the data as synthetic where it was. State the limits: the system was tested on synthetic data, in a sandbox, with a mock or particular model. Avoid language that suggests production deployment, real customers or guarantees you cannot show.
A strong portfolio entry has a short summary, an architecture diagram, a demonstration recording or walkthrough, evaluation highlights and a section on trade-offs and lessons. We also discuss acknowledging third-party tools, models and datasets, and keeping the project maintained.
By the end of this lecture you will be able to release a project reproducibly and describe it honestly.
Day 100: Capstone Release and Portfolio — Publish the application, documentation, and portfolio summary. Today you finish the course by packaging your capstone and presenting it truthfully.
The steps I would expect you to follow are these. First, clean the repository by removing generated files, confirming that no secrets or personal data appear anywhere in the history, and choosing and adding a license. Second, tag a release, pin dependencies and build the container image, then test the installation from a fresh checkout by following your own guide. Third, write the documentation, including an overview, the architecture, the setup instructions with placeholder configuration, the evaluation results, the runbook and the known limitations. Fourth, prepare sample data and a script so that a visitor can run the assistant locally in mock mode within a few minutes. Fifth, write the portfolio summary describing the problem, your design, the measured results, the trade-offs and what you would do next, stating clearly that the data was synthetic and the environment a sandbox. Sixth, ask someone to follow your instructions without your help, and fix every point where they struggle.
Check every number in your summary against the saved reports, and acknowledge the tools, models and datasets that you used.
Keep the release, the documentation and the summary together as the lasting record of your work.
By the end of this project you will have a published, reproducible capstone and an honest account of what you achieved.
This course contains the use of artificial intelligence.
Build practical AI engineering skills through 100 days of structured, hands-on learning. This course connects essential concepts with daily projects, guiding you from Python foundations to integrated AI applications.
Start with Python, data processing, SQL, APIs, validation, and automated testing. Learn to prepare reliable datasets, build reusable pipelines, and diagnose common failures. Then explore machine learning through regression, classification, clustering, anomaly detection, and model evaluation.
Develop your understanding of neural networks, pretrained models, embeddings, semantic search, and vector indexes. Build LLM applications with effective prompts, structured outputs, conversation history, streaming responses, and validated tool calls.
Create retrieval-augmented generation workflows that ingest documents, retrieve evidence, and produce answers with citations. Practice query rewriting, reranking, abstention, and evaluation to understand where these systems succeed and fail.
Move into agents and controlled workflows using planning, checkpoints, memory, human approvals, and failure recovery. Connect tools and business systems through MCP while exploring authentication, authorization, and integration security.
Finally, bring these skills together through APIs, user interfaces, deployment practices, observability, reliability exercises, and an enterprise AI capstone.
With guided labs, reference code, lessons, and assessments, this course helps aspiring AI engineers and developers build, explain, evaluate, and document projects they can refine for their portfolios.