
Checking Your Isolated Python Environment. Every AI project depends on libraries, and different projects often need different versions of the same library. If they all share one installation, an upgrade for one project can quietly break another. This lecture shows how to confirm that your work happens in an isolated environment and why that matters before you write any AI code.
We begin with the idea of a virtual environment, a private folder that holds its own Python interpreter and its own installed packages. You will learn how to tell whether you are inside one. We check the interpreter path, compare the active prefix with the base prefix and print the Python version, and we explain what each value tells you. A script that reports these details gives you a quick, repeatable check you can run at the start of any session.
You will also see the problems that isolation prevents. Installing packages globally can require administrator rights, pollute the system's Python and make a project impossible to reproduce on another computer. We discuss recording dependencies in a requirements file so that a colleague can rebuild the same environment with a single command.
We cover the common mistakes, such as installing a package into one environment and running the code with another, and how to spot the mismatch. We also discuss selecting the right interpreter inside your code editor.
By the end of this lecture you will be able to verify that your Python environment is isolated, report its details and explain why reproducibility matters in AI engineering.
Reading Configuration from Environment Variables. AI applications need settings such as the model name, a base address, a timeout and a credential. Hard-coding these values into source files makes code inflexible and, for credentials, dangerous. Environment variables offer a standard way to supply settings from outside the program, and this lecture shows how to use them well.
You will start with the os module and learn how to read a variable. We compare reading with square brackets, which raises an error when the variable is missing, with the get method, which returns a default. Each has its place. A required value should fail early with a clear message, while an optional one can fall back to a sensible default.
Next we deal with types. Environment variables are always text, so a timeout of thirty arrives as the string thirty, and a flag such as debug arrives as text, not as a boolean. We write small helper functions that convert values to integers, floats and booleans and report a readable error when a conversion fails.
We then gather all settings into one place, a small configuration object created at start-up. This makes the program's requirements visible, keeps the rest of the code free from scattered lookups and allows tests to supply different values.
We discuss good habits: use clear, consistent names, document every variable and never print secrets.
By the end of this lecture you will be able to read, convert and validate configuration from environment variables.
Loading Secrets from a .env File Without Leaking Them. Setting environment variables by hand every time you open a terminal is tedious, so developers keep local settings in a file named .env and load them automatically. The convenience brings a real risk: a secret committed to a repository is difficult to withdraw. This lecture shows how to use a .env file safely.
We begin with the format, which is simple lines of names and values. You will install a loading library and call it at the start of your program so that its values appear in the environment, after which the code from the previous lecture reads them as usual. We discuss the loading order, in which real environment variables should take precedence over the file, so that a deployment can override local values.
The central lesson is preventing leaks. You will add the file to the ignore list of your version control system before creating it, and you will create a sample file, with the variable names and placeholder values, that is safe to commit and tells colleagues what to supply. We discuss how to check that the real file is not tracked.
You will also learn about other leaks, including printing a key in a log message, including it in an error, echoing it in a traceback and returning it from a function. We write a helper that masks all but the last few characters when a value must be displayed.
Finally, we discuss what to do if a secret does leak: revoke it and replace it at once.
By the end of this lecture you will be able to load secrets from a .env file while keeping them out of version control and logs.
Building an AI Service Request as a Dry Run. Calling a language model costs money, takes time and depends on a network, which makes it a poor way to test code. A dry run builds the complete request but stops before sending it, so that you can inspect exactly what would be sent. This lecture creates that habit, and it becomes the foundation of the API lessons later in the course.
We start by defining what a request contains: an address, headers including an authorization value, and a body with the model name, the messages and the settings. You will write a function that assembles these pieces from your configuration and returns them as a dictionary. Because nothing is sent, the function can be tested instantly and without a key.
You will learn to print the request in a safe form. The authorization header is masked, so that logs and screenshots never reveal the credential, while everything else remains visible. We check the structure, confirm the required fields are present and validate values such as a temperature range.
We also add a switch that controls whether a request is sent or only displayed. In dry-run mode the function returns the prepared request, and in live mode a later lecture will send it. Using one code path for both keeps the dry run honest.
We discuss the benefits: faster tests, no cost, easier debugging and a record of exactly what the application intended to do.
By the end of this lecture you will be able to build, inspect and validate an AI service request without sending it.
Creating and Inspecting NumPy Arrays. NumPy is the foundation of nearly every numerical library in the AI ecosystem, from Pandas to scikit-learn and PyTorch. Learning its array type well pays off throughout this course. This lecture introduces arrays and the tools for examining them.
You will begin by creating arrays from Python lists and with helper functions that make arrays of zeros, ones, evenly spaced numbers and ranges. We then inspect them. The shape tells you the size along each dimension, the ndim gives the number of dimensions, the size gives the total count and the dtype reports the type of the stored numbers. Seeing these attributes becomes a reflex, because most errors in numerical code are shape or type problems.
We explain why arrays are not simply lists. They store numbers of one type compactly in a continuous block of memory, which makes operations far faster, and they support operations on whole arrays at once. We compare the time taken by a loop over a list with a single array operation to make the difference concrete.
You will learn indexing and slicing for one-dimensional and two-dimensional arrays, selecting rows, columns and sections. We also cover reshaping an array to a new arrangement and the rule that the total number of elements must stay the same.
We discuss common pitfalls, such as integer types silently truncating decimals.
By the end of this lecture you will be able to create arrays, inspect their shape and type, and select parts of them confidently.
Vectorized Math and Boolean Masking. The real power of NumPy comes from doing arithmetic on whole arrays without writing loops. This lecture teaches vectorized math, and a closely related technique, boolean masking, which lets you select data by a condition.
We begin with arithmetic. Adding, subtracting, multiplying and dividing arrays works element by element, and operations with a single number apply to every element. You will also use functions for sums, means, minimums, maximums and standard deviations, and learn the axis argument that chooses whether the calculation runs down columns or across rows. We introduce broadcasting, the rule that lets arrays of different shapes combine, such as subtracting a column mean from every row, and explain when it works and when it produces a shape error.
Next comes masking. A comparison such as greater than a threshold produces an array of true and false values, one for each element. Using that array to index the original selects exactly the elements that satisfy the condition. We use it to find scores above a cutoff, to replace invalid values and to count how many items meet a rule. We combine conditions with the and and or operators, noting the need for parentheses.
We discuss why avoiding Python loops matters for speed and clarity, and we show how a normalization step, central to machine learning, is written in a single line.
By the end of this lecture you will be able to compute on whole arrays and select data using boolean conditions.
Building DataFrames and Selecting Data. Real datasets are tables with named columns of different types, and Pandas is the standard Python tool for working with them. This lecture introduces the DataFrame and the main ways of selecting data from it.
You will create a DataFrame from a dictionary of lists and from a list of records, and see how Pandas assigns an index to each row. We inspect it using head, info, describe and the shape and dtypes attributes, and explain what each reveals about the data's size, types and distribution. Learning to read this overview quickly is the first step of any analysis.
Selection is the core skill. You will pick a single column, which gives a Series, and several columns, which gives a smaller DataFrame. You will learn loc, which selects by label, and iloc, which selects by position, and why confusing them is a classic source of mistakes. We also use boolean conditions to select rows, for example customers whose spending exceeds a value, and combine conditions with the and and or operators.
We add new columns computed from existing ones, rename columns and sort by one or more columns. We discuss the difference between a view and a copy, and the warning that appears when you modify a slice, and how to avoid the problem.
We finish by loading a small data file into a DataFrame, which prepares the way for the cleaning lecture that follows.
By the end of this lecture you will be able to build DataFrames, inspect them and select rows and columns precisely.
Cleaning Missing Values and Duplicates. Data used for machine learning is almost never clean. Values are missing, records appear twice and entries are inconsistent, and a model trained on such data learns the mess. This lecture covers the first steps of cleaning, using Pandas.
We begin by finding the problems. The isna method marks missing values, and combined with sum it counts them for each column. The duplicated method marks repeated rows. You will examine the extent of the problem before deciding what to do, because the right action depends on how much data is affected and why it is missing.
For missing values, we compare the main options. Dropping rows is simple but wastes information and can bias the data if the missing rows differ from the rest. Filling with a constant, the mean, the median or the most frequent value keeps the rows but adds assumptions. We discuss which suits numeric and category columns and why the median resists the effect of extreme values. You will also learn to add an indicator column that records which values were filled, since the absence itself can carry meaning.
For duplicates, we use drop_duplicates and the option to consider only certain columns. We discuss deciding which copy to keep.
We emphasize an important principle for machine learning: statistics used to fill values should be calculated from the training data only, to avoid leaking information from the test data.
By the end of this lecture you will be able to detect and handle missing values and duplicate records responsibly.
Grouping and Summarizing Data. Individual rows rarely answer the questions that matter. You want to know the average by category, the total by month or the count by customer. Grouping lets you split data into parts, calculate a summary for each and combine the results. This lecture teaches that pattern in Pandas.
We start with groupby, which divides a DataFrame according to the values in one or more columns. By itself it does nothing visible, so we explain that it is a recipe waiting for an operation. You will apply simple summaries, such as count, sum, mean, minimum and maximum, and see the result as a table indexed by the group.
Next we use agg to apply several summaries at once, and to apply different ones to different columns, naming the output columns clearly. We group by two columns to produce a multi-level result and learn to turn the index back into ordinary columns with reset_index, which makes the output easier to use.
You will learn related tools. The value_counts method gives quick frequency tables, pivot tables arrange a summary with one factor down the side and another across the top, and sorting the results shows the top and bottom groups.
We discuss why summaries matter for machine learning. They reveal imbalanced classes, unusual groups and features worth creating, such as the average spend per customer. We also warn about small groups, whose averages are unreliable.
By the end of this lecture you will be able to group data and produce clear summaries that reveal patterns.
Splitting Data into Training and Test Sets. A model that is judged on the same data it learned from will look better than it really is, because it can simply memorize the examples. The remedy is to hold back part of the data for testing. This lecture introduces the train and test split, one of the most important ideas in machine learning.
We begin with the reasoning. The goal of a model is to perform well on data it has never seen, so we need an honest estimate of that performance. You will learn to use the train_test_split function from scikit-learn to divide features and labels into a training portion and a test portion, and to choose the proportion, commonly around twenty to thirty percent for testing.
We discuss two settings that matter. A random state makes the split reproducible, so that results can be compared between runs and shared with colleagues. Stratification keeps the proportion of each class the same in both portions, which is essential when one class is rare. We demonstrate what happens without it on an imbalanced sample.
You will also learn the discipline that accompanies splitting. The test set should be used only at the end, and every preprocessing step that learns from data, such as scaling or filling values, must be fitted on the training portion only. Otherwise information leaks from the test set and the estimate becomes optimistic.
By the end of this lecture you will be able to split data correctly and explain why the test set must remain untouched.
Fitting and Predicting with a Classifier. With the data split, we can finally train a model. This lecture walks through the basic cycle of supervised learning in scikit-learn: create an estimator, fit it to training data and use it to predict. The same three steps apply to almost every model you will meet.
We use logistic regression, a simple and widely used classifier, on a small labeled dataset. You will import the class, create an instance with its settings, call fit with the training features and labels and then call predict on the test features. We explain what happens during fitting. The model searches for the parameters that best separate the classes, and for logistic regression those are weights on each feature.
You will learn the difference between predict, which returns class labels, and predict_proba, which returns the probability of each class. Probabilities are more informative, because they show how confident the model is, and they allow you to choose your own decision threshold. We look at the learned coefficients and discuss what they suggest about the influence of each feature, along with the caution needed when features are on different scales.
We discuss preparing features. Models such as logistic regression benefit from scaling, so we introduce a scaler and the rule that it must be fitted on the training data only. We also mention a pipeline, which chains steps together safely.
Finally, we compare predictions with the true test labels by eye, setting up the metrics lectures that follow.
By the end of this lecture you will be able to train a classifier and use it to make predictions and probabilities.
Measuring Accuracy and the Confusion Matrix. Once a model produces predictions, you need to measure how good they are. This lecture introduces the most familiar metric, accuracy, and then shows why it can mislead and how the confusion matrix gives a fuller picture.
Accuracy is the fraction of predictions that are correct. You will compute it with the scikit-learn function and by hand to confirm that you understand it. It is simple and often useful, but it hides a serious problem when classes are imbalanced. If ninety-five percent of messages are legitimate, a model that always predicts legitimate scores ninety-five percent while detecting nothing. We build that useless model on purpose to see the effect.
The confusion matrix reveals what accuracy conceals. It is a table that counts, for each true class, how many examples were predicted as each class. For a two-class problem it holds four numbers: true positives, true negatives, false positives and false negatives. You will generate it with the library function and read each cell carefully, learning to say in plain language what each number means.
We discuss that the cost of the two kinds of error is rarely equal. Missing a fraud case is different from flagging a legitimate payment, and the matrix lets you see which error your model makes more often.
We also show how to display the matrix with labels, which makes it easy to share.
By the end of this lecture you will be able to compute accuracy, build a confusion matrix and explain why accuracy alone is not enough.
Understanding Precision, Recall, and F1 Score. The confusion matrix contains the raw counts, and precision, recall and the F1 score condense them into numbers that answer specific questions. This lecture explains each metric, what it rewards and how to choose among them.
Precision asks, of all the examples the model labeled positive, how many really were? It is the true positives divided by all predicted positives, and a high value means few false alarms. Recall asks, of all the examples that really were positive, how many did the model find? It is the true positives divided by all actual positives, and a high value means few misses. You will calculate both by hand from a confusion matrix and then with the scikit-learn functions to build intuition.
These two measures pull against each other. Lowering the decision threshold finds more positives, which raises recall, but it also admits more false alarms, which lowers precision. We demonstrate this by changing the threshold on predicted probabilities and watching the numbers move.
The F1 score is the harmonic mean of precision and recall, and it is high only when both are reasonably high. We discuss why the harmonic mean is used instead of the ordinary average. We introduce the classification report, which shows all the metrics for every class at once, and the meaning of macro and weighted averages.
We finish with guidance on choosing a metric according to the cost of errors in the problem.
By the end of this lecture you will be able to compute and interpret precision, recall and F1 and select the right one for a task.
Cross-Validation for Reliable Model Evaluation. A single train and test split gives one estimate of performance, and that estimate depends on which examples happened to land in each part. A lucky split can flatter a model, and an unlucky one can make it look worse. Cross-validation reduces this dependence by repeating the evaluation several times. This lecture explains how.
In k-fold cross-validation, the data is divided into k equal parts, called folds. The model is trained k times, each time using k minus one folds for training and the remaining fold for validation. The k scores are then averaged. You will use cross_val_score to do all of this in one line, and read the individual scores as well as the mean and standard deviation. The spread tells you how stable the model is, which a single number cannot.
We discuss choosing k, with five and ten being common, and the trade-off between more reliable estimates and longer training time. We introduce stratified folds, which keep class proportions consistent, and explain why they are the default for classification. We also mention shuffling and the caution needed with data that has a time order, where a random split would leak the future into the past.
You will see how to use cross-validation to compare models fairly, by evaluating each on the same folds.
We also stress that cross-validation belongs inside the training data, and that a final test set should still be kept aside.
By the end of this lecture you will be able to apply cross-validation and interpret both the average score and its variability.
Tuning Hyperparameters with Grid Search. Models have settings that you choose before training, called hyperparameters, such as the regularization strength of logistic regression or the number of trees in a forest. The best values depend on the data, and finding them by hand is slow and unreliable. Grid search automates the process, and this lecture shows how to use it properly.
We begin by separating parameters, which the model learns from the data, from hyperparameters, which you set. You will define a grid, a dictionary that lists the candidate values for each hyperparameter, and pass it to GridSearchCV together with the model, the scoring metric and the number of folds. The search trains and cross-validates every combination and records the results.
You will learn to read the outcome. The best_params_ attribute gives the winning combination, best_score_ gives its cross-validated score and cv_results_ holds the details of every combination, which you can load into a DataFrame and sort. We discuss choosing a scoring metric that matches your goal, such as F1 for imbalanced classes, and not simply relying on accuracy.
We discuss the cost. The number of combinations grows quickly as you add values and hyperparameters, so we keep grids small and mention randomized search as a cheaper alternative. We also warn about overfitting to the validation folds when you search too aggressively.
Finally, we evaluate the best model once on the untouched test set, which gives an honest final estimate.
By the end of this lecture you will be able to tune a model with grid search and report its performance honestly.
Creating and Inspecting PyTorch Tensors. PyTorch is one of the leading frameworks for deep learning, and its central object is the tensor, a multi-dimensional array similar to a NumPy array but able to run on accelerators and track gradients. This lecture introduces tensors and the tools for inspecting them.
You will create tensors from Python lists and from NumPy arrays, and with helper functions that produce zeros, ones, random values and ranges. We inspect them using shape, dtype and device, and explain why each matters. A shape mismatch is the most frequent error in deep learning code, and a type mismatch, such as mixing integers and floats, is the second. Developing the habit of printing these attributes will save you many hours.
We practice the operations you will use constantly: arithmetic between tensors, matrix multiplication, reshaping with view and reshape, adding and removing dimensions and indexing and slicing. We explain broadcasting, which works much as it does in NumPy, and how to convert between tensors and arrays.
You will learn the concept of a device. Tensors live on the processor or on a graphics unit, and operations require that all tensors share a device. We show how to check availability and move tensors, noting that no special hardware is needed for the exercises in this course.
We also discuss data types, since neural networks usually expect 32-bit floats, and how to convert.
By the end of this lecture you will be able to create, inspect and manipulate PyTorch tensors confidently.
Automatic Differentiation with Autograd. Neural networks learn by adjusting their parameters in the direction that reduces an error, and that direction is given by gradients. Computing gradients by hand for a large network is impractical, and PyTorch does it automatically. This lecture introduces autograd, the engine behind the learning you will perform later.
We begin with a small intuition. A gradient tells you how much the output changes when an input changes slightly. You will create a tensor with requires_grad set to true, build a simple expression from it, such as a square plus a multiple, and call backward on the result. The gradient then appears in the tensor's grad attribute, and you can verify it against the derivative that you compute by hand.
We explain what happens behind the scenes. PyTorch records each operation in a graph as you perform it, and backward walks the graph in reverse, applying the chain rule. We extend the example to several variables and to a small expression resembling a loss, so that you can see gradients for each input.
You will learn the practical rules. Gradients accumulate by default, so they must be cleared between steps. Tracking can be turned off with a no_grad context when you only need predictions, which saves memory and time. The detach method separates a tensor from the graph.
We discuss common errors, such as calling backward on a value that is not a single number.
By the end of this lecture you will be able to compute gradients automatically and explain how they will be used to train models.
Building a Neural Network with nn.Module. Writing every weight and operation by hand quickly becomes unmanageable. PyTorch offers the nn.Module class as the standard way to define a network, and this lecture shows how to build one in an organized and reusable way.
We begin with the idea of a layer. A linear layer multiplies its input by a weight matrix and adds a bias, and an activation function such as ReLU adds the nonlinearity that allows a network to learn complex patterns. You will stack these into a small network for classification of tabular data.
To create the model, you define a class that inherits from nn.Module. In its constructor you create the layers, and in the forward method you describe how data flows through them. We explain why the constructor must call the parent's constructor, how the layers are registered automatically and how PyTorch finds all learnable parameters. You will print the model to see its structure and count its parameters.
We also introduce nn.Sequential for simple chains of layers, and compare it with a custom class, which offers more flexibility for networks with branches or custom logic.
You will run a batch of random inputs through the untrained network and check the output shape, which is an excellent way to catch dimension errors early. We discuss choosing the sizes of the input and output layers from the data and the task.
By the end of this lecture you will be able to define a neural network as a module and verify its structure.
Understanding Loss Functions and Optimizers. A network needs two more ingredients before it can learn: a measure of how wrong its predictions are, and a method for improving them. These are the loss function and the optimizer, and this lecture explains both.
The loss function converts predictions and true targets into a single number, where smaller means better. For regression, mean squared error measures the average squared difference. For classification, cross-entropy measures how much probability the model assigned to the correct class, and it penalizes confident mistakes heavily. You will compute several losses by hand on small examples and with PyTorch's built-in functions. We also explain a frequent point of confusion: some loss functions expect raw scores, called logits, while others expect probabilities, and using the wrong combination quietly harms training.
The optimizer uses the gradients to update the parameters. You will meet stochastic gradient descent, which moves each parameter a small step against its gradient, and Adam, which adapts the step size for each parameter and is a popular default. The learning rate controls the step size. We show what happens when it is too large, producing unstable or diverging loss, and when it is too small, producing painfully slow progress.
We perform a single update by hand: compute the loss, call backward, step the optimizer and clear the gradients, then confirm that the loss decreased.
By the end of this lecture you will be able to choose a loss function and an optimizer and explain how they work together.
Writing the Complete Neural Network Training Loop. This lecture brings the earlier pieces together into the loop that trains a network. The structure you write here is the same one used to train models of every size, so it is worth learning carefully.
We start by preparing the data. You will convert features and labels to tensors and wrap them in a dataset and a data loader, which serves shuffled mini-batches. Training on batches, instead of the whole dataset at once, is faster and helps the optimization.
The loop has a precise rhythm. For each epoch and for each batch, you clear the old gradients, run the forward pass to get predictions, compute the loss, call backward to compute the gradients and step the optimizer to update the parameters. We explain why each line is needed and what goes wrong if one is missing, such as forgetting to clear gradients, which makes updates accumulate.
You will track the average loss for each epoch and print it, watching it fall. We add an evaluation step on held-out data, switching the model into evaluation mode and disabling gradient tracking, and we compare training and validation results to spot overfitting.
We discuss practical choices, such as the number of epochs, the batch size and the learning rate, and how to set a random seed for reproducibility. We also save and load the trained weights.
By the end of this lecture you will be able to write a complete training loop and judge from the loss curves whether learning is healthy.
Structuring API Requests with System and User Messages. Large language models accept input as a list of messages, each with a role. Understanding the roles, and how to structure the list, is the foundation of every LLM application. This lecture explains the message format and how to use it well.
The system message sets the behavior and boundaries for the whole conversation: the persona, the tone, the rules and the expected output format. The user message carries the actual request. Assistant messages contain earlier model replies, and including them lets the model see the conversation so far. You will build a request body in code, with a model name, a list of messages and optional settings, and print it as it would be sent, reusing the dry-run approach from the first section.
We discuss writing effective system messages. Be specific about the task, state constraints, describe the output format and say what to do when the request cannot be fulfilled. We compare a vague instruction with a precise one and consider the likely effect on the output.
You will learn about keeping instructions separate from user-supplied content. Text from users or documents may contain instructions of its own, so we treat it as data, label it clearly and never grant it the authority of the system message.
We also discuss managing conversation history. Each request must carry the history the model should consider, which consumes tokens and has a cost, so we look at trimming strategies.
By the end of this lecture you will be able to structure a well-formed message list for an LLM request.
Calling an LLM REST Endpoint with Authorization. With a request prepared and inspected, it is time to send it. This lecture takes the dry-run request from the first section and sends it to a language model's REST endpoint, covering authorization, error handling and reading the reply.
We begin with the shape of the call. An HTTP request has a method, an address, headers and a body. For most model services, you send a POST request with a JSON body and include an authorization header that carries your key as a bearer token, along with a content type header. You will use the requests library, or a similar HTTP client, to send it, setting a timeout so that the program never waits indefinitely.
The key comes from the environment, as in earlier lectures, and is never written in the code or printed. We add a safeguard that refuses to send anything if the key is missing and reports a clear message.
Next we read the response. You will check the status code before using the body, because an error response has a different structure from a successful one. We parse the JSON, navigate to the generated text and read the usage information, which reports how many tokens were consumed. We write a function that returns the text and raises a descriptive error for failures such as a rejected key, a rate limit or a server problem.
For learning without cost, we show how to point the same code at a local mock service. Live exercises may incur provider charges.
By the end of this lecture you will be able to call an LLM endpoint securely and handle its responses and errors.
Controlling LLM Outputs with Model Parameters. The same prompt can produce very different replies depending on the settings sent with it. This lecture explains the main model parameters, what each one does and how to choose values for different tasks.
Temperature controls randomness. A low value, near zero, makes the model choose the most likely words almost every time, giving consistent and focused answers suited to extraction, classification and code. A higher value allows more variety, which suits brainstorming and creative writing, but it also raises the chance of mistakes. You will send the same prompt several times at different temperatures and compare the results.
Top-p, also called nucleus sampling, limits the choice to the smallest group of likely words whose combined probability reaches a chosen value. We discuss why you usually adjust either temperature or top-p, not both at once. The maximum tokens setting limits the length of the reply, which controls cost and latency but can cut an answer off mid-sentence, and we show how to detect that from the reason the model stopped.
We also cover stop sequences, which end generation when a particular string appears, and, where supported, penalties that discourage repetition and a seed that makes output more repeatable.
You will learn to treat parameters as part of your application's configuration, to record the values used with each result and to test the effect of changes on a fixed set of examples.
By the end of this lecture you will be able to select and justify model parameters for a given task.
Streaming LLM Responses Chunk by Chunk. A model may take several seconds to produce a long reply. Waiting for the whole answer makes an application feel slow, while streaming shows the text as it is generated, which feels immediate. This lecture shows how to request and process a streamed response.
We begin with how streaming works. Instead of returning one complete response, the server keeps the connection open and sends a series of small events, each carrying a few new tokens, followed by a final event that signals completion. You will enable streaming in the request and read the response incrementally, using the HTTP library's support for iterating over lines.
Each event arrives in a defined text format. You will learn to strip the prefix from each line, ignore keep-alive blank lines, detect the end marker, parse the JSON in each chunk and extract the piece of text. We write a generator function that yields the pieces one at a time, which makes it easy to print them as they arrive and to join them into the full answer at the end.
We discuss the practical issues. A chunk may be empty or contain only metadata. A connection can drop partway, so the code should handle errors and keep the partial text. Usage information may appear only in the last chunk, or may need to be requested. If the output must be valid JSON, you cannot parse it until the stream is complete.
We also measure the time to the first chunk and compare it with the full response time.
By the end of this lecture you will be able to consume a streamed LLM response and assemble the result reliably.
Requesting and Validating Structured JSON Outputs. Applications cannot do much with a free-form paragraph. They need data in a predictable shape, such as fields for a category, a score and a list of reasons. This lecture shows how to ask a model for JSON and, just as important, how to check what comes back.
We begin with the request. You will write instructions that describe the exact fields and their types, give an example of the desired format and say that only JSON should be returned. Where the service supports a JSON mode or a schema-constrained mode, we use it, since it greatly improves reliability. We keep the temperature low for consistency.
Reading the reply is the next step. You will parse it with the json module and handle the failure cases. The model may wrap the JSON in extra text or in code fences, so we write a helper that extracts the JSON portion. If parsing still fails, we retry once with a message describing the problem, and then give up with a clear error.
Parsing is only half of validation. A reply can be valid JSON and still be wrong. You will write checks, using plain Python or a validation library such as Pydantic, that confirm required fields exist, types are correct, values lie in allowed sets and numbers fall in sensible ranges. We discuss allowing an unknown value so that the model is not forced to guess.
We finish by treating all model output as untrusted input to your program.
By the end of this lecture you will be able to request structured output and validate it before using it.
Representing Text as Embedding Vectors. Computers cannot compare meanings directly, but they can compare numbers. An embedding converts a piece of text into a list of numbers, a vector, positioned so that texts with similar meanings end up close together. This lecture introduces embeddings, the foundation of semantic search and retrieval-augmented generation.
We begin with the intuition. Keyword matching treats the words refund and money back as unrelated, while an embedding places sentences about returning purchases near one another, even without shared words. You will see this for yourself by embedding a handful of short sentences and examining the results.
We discuss how to obtain embeddings. A service accepts text and returns a vector of hundreds or thousands of numbers, and we show the request and the response structure. To keep the exercises free and repeatable, we also provide a simple local approach that builds small vectors, so that the downstream code can be tested without a key. We examine the vector's length, also called its dimension, and explain that all vectors from one model have the same dimension, and that vectors from different models are not comparable.
You will learn practical points. Text is usually embedded in pieces of a manageable size. The same model must be used for documents and queries. Embeddings can be cached, since the same text always yields the same vector, which saves cost and time. We store them in a NumPy array for convenient processing.
By the end of this lecture you will be able to describe what an embedding is and generate and store embeddings for a set of texts.
Measuring Similarity with Cosine Similarity. Once text has become vectors, you need a way to measure how close two of them are. Cosine similarity is the most common choice for embeddings, and this lecture explains how it works and how to compute it.
The idea is geometric. Each vector is an arrow, and cosine similarity measures the angle between two arrows. Arrows pointing the same way have a similarity of one, perpendicular arrows score zero and opposite arrows score minus one. Because it depends on direction and not on length, it is not distorted by differences in text length or scale, which makes it well suited to comparing meaning.
You will write the calculation yourself using NumPy. The dot product of two vectors is divided by the product of their lengths, where the length of a vector is its norm. We test the function on simple two-dimensional vectors where you can verify the answer by drawing, then apply it to real embeddings of sentences, confirming that related sentences score higher than unrelated ones.
We discuss edge cases. A zero vector would cause a division by zero, so we guard against it. We show that normalizing vectors to unit length first makes cosine similarity equal to a simple dot product, which allows efficient calculation for many vectors at once with a single matrix multiplication.
We also compare cosine similarity with Euclidean distance and explain when they agree.
By the end of this lecture you will be able to compute cosine similarity and interpret the scores.
Ranking Documents Against a User Query. Semantic search answers a user's question by finding the documents whose meaning is closest to it. This lecture builds that ranking step, using the embeddings and the similarity function from the previous lectures.
The procedure is short. You embed the query with the same model that was used for the documents, compute its similarity to every document vector and sort the documents from highest to lowest score. We write a function that does exactly this and returns the top results as a list of records containing the document text, an identifier and the score. A matrix multiplication calculates all the similarities at once, which is far faster than a loop.
You will work with a small collection of invented documents, such as short policy notes, and test the search with several queries, including one that shares no words with the best answer, which demonstrates the benefit of semantic matching. We use argsort to order results and slice to keep the top k, discussing how to choose k.
We examine the results critically. The scores are not probabilities, and the top result is not always the right one. We look at cases in which the ranking is surprising, such as a document that mentions the same topic but does not answer the question, and discuss how to investigate them.
We also discuss presenting results clearly, with scores and identifiers, so that a person can judge them.
By the end of this lecture you will be able to rank documents against a query and return the best matches.
Filtering Results with Similarity Thresholds. A ranking always returns something, even when nothing in the collection is relevant. The top result for an unrelated question is simply the least bad match, and presenting it as an answer is misleading. A similarity threshold lets your system recognize when nothing is close enough. This lecture shows how to apply and choose one.
We begin by demonstrating the problem. You will ask a question that the document collection cannot answer and observe that the search still returns documents with confident-looking order. Then you add a minimum score, discarding results below it, and an empty result list becomes a meaningful outcome that the application can handle by saying that no relevant information was found.
The difficult part is choosing the value. We examine the score distributions for a set of queries with known answers and for a set of unanswerable queries, and look for a gap between them. You will compute how many relevant results are lost, and how many irrelevant ones are accepted, for several candidate thresholds, and see the trade-off. A strict threshold avoids bad matches but rejects some good ones, while a lenient one does the opposite.
We discuss that thresholds depend on the embedding model and the data, so they must be revisited when either changes. We also combine the threshold with a maximum number of results.
We write the logic as a reusable function and test it with boundary cases.
By the end of this lecture you will be able to filter search results with a justified threshold and handle the case of no match.
Splitting Documents into Fixed-Size Chunks. Retrieval-augmented generation begins with a practical problem: documents are too long to embed or place into a prompt as a whole. The solution is to split them into chunks, and this lecture shows how to do it with fixed-size pieces.
We start with why chunking matters. Embedding a whole document produces one vector that blurs every topic in it, so a question about one detail matches weakly. Models also have limited context windows, and every token placed in a prompt costs money. Smaller chunks allow precise retrieval and efficient prompts.
You will write a function that takes a text and a chunk size, measured in characters or words, and returns a list of consecutive pieces. We discuss the choice of unit. Characters are simple, words avoid cutting through a word and tokens match what the model counts. We practice with words, and mention how to count tokens with a tokenizer library.
We examine the problems with the naive approach. A fixed boundary can slice through a sentence or separate a heading from its content, and the final chunk may be tiny. You will see these defects on a sample document and learn to handle the remainder sensibly.
We add metadata to each chunk, including the source document, the position and the start and end offsets. This lets you cite sources later and trace an answer back to its origin.
We discuss choosing a size, with a few hundred words common, and testing it on real questions.
By the end of this lecture you will be able to split a document into fixed-size chunks that carry useful metadata.
Overlapping Chunks to Preserve Context. Fixed-size chunks have a weakness at their edges. An idea that begins at the end of one chunk and finishes at the start of the next is split in two, and neither half contains the whole thought. Overlap addresses this by repeating a portion of the end of each chunk at the beginning of the next. This lecture shows how to implement and tune it.
We start by demonstrating the failure. You will write a sample document in which an important sentence straddles a boundary, split it without overlap and search for the sentence's content. The retrieval misses it, because neither chunk holds the full meaning.
Then you extend the chunking function with an overlap parameter. Each new chunk starts a fixed number of words before the previous one ended, so the step between chunks is the size minus the overlap. We write the loop carefully, handling the final chunk and ensuring that the step is always positive, because an overlap equal to or larger than the size would cause an endless loop. We test with small numbers where the result can be checked by eye.
We discuss the trade-offs. More overlap protects context but increases the number of chunks, the storage, the embedding cost and the chance of retrieving near-duplicates. A modest overlap, around ten to twenty percent of the chunk size, is a common starting point.
We also look at smarter boundaries, such as splitting on sentences or paragraphs, and compare retrieval before and after.
By the end of this lecture you will be able to chunk with overlap and justify the settings you choose.
Building an In-Memory Vector Index. With chunks created, we need a place to store their embeddings and a way to search them. This lecture builds a simple in-memory vector index, which is enough to understand how every vector store works and is perfectly adequate for small collections.
The index holds three things in parallel: the matrix of embeddings, the list of chunk texts and the list of metadata. We create a class with an add method that embeds chunks and appends them, and a search method that embeds a query, calculates cosine similarity against all stored vectors and returns the best matches with their metadata. Normalizing the vectors when they are added makes the search a single matrix multiplication.
You will design the interface carefully. Methods have clear names, check for an empty index and return results in a consistent structure. We add the option of a threshold and a limit on the number of results, reusing the ideas from the previous section.
We discuss persistence. Everything in memory disappears when the program ends, so we save the matrix and the metadata to files and load them again, which avoids paying to embed the same documents repeatedly. We also discuss tracking which embedding model was used, because vectors from different models cannot be mixed.
We then explain how this simple design relates to production vector databases, which add approximate search for speed, filtering, updates and scale, but follow the same principle.
By the end of this lecture you will be able to build, query and save a simple vector index.
Answering Questions with Retrieved Context. Retrieval alone returns passages, but users want answers. Retrieval-augmented generation combines both. It retrieves relevant chunks, places them in a prompt and asks a model to answer using only that material. This lecture builds the answering step.
We begin with the prompt. A grounded prompt has a system message that states the rules: answer only from the provided context, quote or refer to the sources and say clearly when the context does not contain the answer. The user portion contains the numbered chunks followed by the question. We write a function that assembles this prompt from retrieved results, labeling each chunk with an identifier so that the model can refer to it.
You will connect the pieces. The function takes a question, searches the index, applies the threshold, builds the prompt and sends it to the model, using the API code from earlier or a simulated model for free testing. It returns the answer together with the sources that were supplied.
We discuss why this approach reduces invented answers. The model has the relevant facts in front of it and a clear instruction not to go beyond them. It is not a guarantee, so we also discuss checking that cited identifiers exist and that the answer is consistent with the context.
We discuss the context budget, choosing how many chunks to include and trimming when they would exceed the limit. We also treat retrieved text as data and not as instructions.
By the end of this lecture you will be able to build a question-answering function that is grounded in retrieved context.
Describing AI Agent Tools with JSON Schema. An AI agent is a model that can use tools, such as a calculator, a database lookup or a search function, to accomplish tasks that text alone cannot. For a model to use a tool, it must know the tool exists and how to call it. This lecture shows how to describe tools using JSON Schema.
A tool description has a name, a plain-language explanation of what the tool does and a schema for its parameters. The schema is a JSON structure that lists each parameter, its type, its description, any allowed values and which ones are required. You will write descriptions for several tools, such as a function that returns the weather for a city and one that performs arithmetic.
We discuss how the quality of a description shapes the model's behavior. The model decides whether and how to call a tool from the description alone, so a vague one leads to wrong choices. We compare weak and strong descriptions, and explain that a good one says when to use the tool, what it returns and what it does not do.
You will learn useful schema features, including enumerations that restrict a value to a fixed set, minimum and maximum values, default values and nested objects. We write a function that checks arguments against a schema, since the model's output is untrusted.
We also place the descriptions in a request, in the format the API expects, and look at a response in which the model asks for a tool.
By the end of this lecture you will be able to write clear tool definitions with strict parameter schemas.
Parsing Tool Calls from Model Responses. When a model decides to use a tool, it does not run anything. It returns a structured request that names the tool and supplies arguments, and your code must read it. This lecture shows how to parse such responses reliably.
We begin by examining a response that contains a tool call. Instead of ordinary text, the message carries a list of calls, each with an identifier, a function name and an arguments field. Notably, the arguments arrive as a string containing JSON, so they must be decoded. You will write a function that extracts every call from a response and returns them as simple Python records.
Robustness is the main concern, because model output is untrusted. The arguments may be malformed JSON, a required field may be missing, a value may have the wrong type or the model may name a tool that does not exist. For each case we write a clear error, and we discuss reporting the problem back to the model so that it can try again.
A response may also contain several calls at once, or text together with a call, or no call at all, in which case it is the final answer. We write code that distinguishes these situations cleanly.
We practice with a simulated model that returns prepared responses, so the parsing logic can be tested without any network use. We write tests for normal and broken cases.
By the end of this lecture you will be able to parse and validate tool calls from model responses safely.
Dispatching Tool Calls to Python Functions. Having parsed a tool call, the next step is to execute it. Dispatching connects the name that the model chose to a real Python function, passes the arguments and captures the result. This lecture shows how to do that in a way that is flexible and safe.
We begin with a registry, a dictionary that maps tool names to functions. The registry is the only set of actions that the model can trigger, which is an important safety boundary. A name that is not in the registry is rejected. You will write several small tools, such as a calculator with a restricted set of operations and a lookup in a sample data dictionary, and register them.
The dispatcher takes a parsed call, looks up the function, validates the arguments against the tool's schema and calls it with those arguments. We discuss converting the result into text, which is what the model receives, and keeping the result concise. We catch exceptions raised by the tool and convert them into an error message that the model can understand and react to, since a crash would end the whole session.
Safety deserves attention. Never evaluate arbitrary code from the model, never build file paths or database commands directly from its arguments without validation and limit what each tool can do. We add a time limit and log every call with its arguments and outcome.
We test the dispatcher with valid calls, unknown tools and invalid arguments.
By the end of this lecture you will be able to execute model-requested tool calls safely through a registry.
Building an AI Agent Execution Loop. We now have the parts of an agent: a model, tool descriptions, a parser and a dispatcher. The execution loop joins them into a system that can pursue a goal through several steps. This lecture builds that loop and, crucially, the limits that keep it under control.
The loop follows a simple cycle. Send the conversation and the tool descriptions to the model. If the response contains tool calls, execute them, append the results to the conversation as tool messages and send everything back. If the response is plain text, that is the final answer and the loop ends. You will implement this cycle and trace it on an example that needs two tool calls, such as looking up a value and then calculating with it.
An unbounded loop is dangerous, so we add limits. A maximum number of steps prevents endless repetition, a cap on the total time and tokens controls cost and we detect repeated identical calls, which usually mean the model is stuck. When a limit is reached, the agent returns a clear message describing what it accomplished and what remained.
We record a trace of every step, including the calls, results and timing, which is essential for debugging. We use a simulated model with scripted responses so that the loop can be tested repeatably.
We also discuss what an agent should not do without confirmation, such as actions with real-world consequences.
By the end of this lecture you will be able to build a bounded agent loop with tracing.
Scoring Model Outputs with an Exact-Match Evaluation Dataset. You cannot improve what you cannot measure, and AI applications are no exception. Impressions from a few trials are unreliable. An evaluation dataset gives you a repeatable measurement. This lecture builds the simplest useful kind, based on exact matching.
An evaluation dataset is a collection of inputs, each paired with the expected output. For tasks with short, well-defined answers, such as classifying a message into a category or extracting a value, you can compare the model's answer to the expected one directly. You will create a small dataset in a JSON or CSV file with a handful of cases that include easy, hard and edge cases.
You will write an evaluation function that runs each input through your application, normalizes both the answer and the expected value, for example by trimming whitespace and ignoring case, compares them and records the result. It reports the accuracy and lists every failure with its input, expected output and actual output. Reading the failures is where most of the learning happens.
We discuss the limits of exact matching. It works poorly for open-ended answers where many wordings are correct, and we introduce alternatives briefly, such as checking for required key facts or using a rubric. We also discuss dataset quality, the danger of tuning only to the examples you can see and keeping some cases aside.
We make the evaluation deterministic, using a simulated model or a low temperature, and run it before and after each change.
By the end of this lecture you will be able to build and run a repeatable exact-match evaluation.
Implementing Guardrails, Retries, and Exponential Backoff. AI applications face two kinds of trouble: the model may produce unacceptable output, and the services it depends on may fail. This lecture adds defenses against both, using guardrails for the first and retries with exponential backoff for the second.
Guardrails are checks placed around the model. Input guardrails can reject empty or overlong requests and detect obviously unsuitable content before spending money on a call. Output guardrails validate the response, checking its format, its length, the presence of required fields and the absence of forbidden content, such as secrets or personal data that should not appear. You will write a guardrail function that returns a decision and a reason, and decide what to do on failure: retry, fall back to a safe response or refuse politely.
Retries handle temporary failures such as timeouts, rate limits and server errors. We classify errors, because retrying a rejected key is pointless while retrying a timeout is sensible. Exponential backoff increases the wait between attempts, for example doubling each time, and jitter adds a small random amount so that many clients do not retry together. We respect any wait time the service suggests, and we set a maximum number of attempts and an overall deadline.
You will implement a reusable wrapper and test it with a simulated service that fails a set number of times. We use a controllable clock so that tests do not actually wait.
By the end of this lecture you will be able to build resilient AI calls with guardrails, bounded retries and backoff.
Integrating Document Retrieval and Grounded Prompts into an Answer Function. The capstone begins with the central function of the assistant: given a question, return a trustworthy answer with its sources. This lecture integrates the chunking, indexing, retrieval and prompting work from earlier sections into a single, well-tested function.
We start with the design. The function takes a question and returns a structured result with the answer text, the list of sources used, a flag showing whether enough evidence was found and some diagnostic information. A structured result is much easier to expose through an API and to test than a bare string.
You will build the pipeline in stages. A set of invented documents is chunked with overlap and indexed. At question time, the function embeds the query, retrieves the top chunks, applies the similarity threshold and, if nothing passes, returns a clear message that the documents do not contain the answer. Otherwise it assembles a grounded prompt with numbered sources and sends it to a simulated language model, which keeps the project free and deterministic. The simulated model can be replaced by a real one through configuration.
We add citations by returning the identifiers and excerpts of the chunks that were used, and we verify that any citation the model mentions actually exists in the supplied set.
We write tests for an answerable question, an unanswerable one and an empty input, and we apply the guardrails from the previous section.
By the end of this lecture you will be able to assemble a complete, grounded question-answering function.
Serving the AI Assistant as a REST API with FastAPI. A function in a script is useful to you, but other applications and users need a service they can call. In this final lecture we expose the assistant as a REST API using FastAPI, and test it as a client would.
We begin with a short introduction to FastAPI. You define an application object and decorate functions to create endpoints, and the framework uses Python type hints to validate input and generate documentation. We create a request model with a question field, with a limit on its length, and a response model that matches the structured result from the previous lecture: the answer, the sources and the evidence flag.
You will write a post endpoint that accepts a question, calls the answer function and returns the result, and a health endpoint that reports whether the service is running. We discuss status codes and error handling, returning a clear message for invalid input and a safe message for internal failures without exposing internal details. The assistant is created once at start-up and shared by requests.
You will run the service with a development server and open the automatically generated documentation page to try the endpoints in a browser. We then test with the framework's test client, writing checks for a valid question, an unanswerable one, an empty one and an overlong one.
We close with practical advice on configuration through environment variables, protecting the endpoint and ideas for extending the assistant.
By the end of this lecture you will be able to serve and test an AI assistant as a REST API.
This course contains the use of artificial intelligence.
Are you ready to build the skills needed to become an AI Engineer and develop intelligent applications using the latest Artificial Intelligence, Machine Learning, Deep Learning, Generative AI, and Agentic AI technologies?
Welcome to the AI Engineer Bootcamp: From Machine Learning to AI Agents, a comprehensive, hands-on course designed to help developers, software engineers, data scientists, and technology professionals master the essential concepts, tools, and techniques of modern AI engineering.
Unlike courses that focus exclusively on theoretical concepts or prompt engineering, this bootcamp takes a practical, implementation-driven approach. With 10 comprehensive sections, 41 practical lessons, hands-on coding exercises, and an end-to-end capstone project, you will progressively develop the skills required to build intelligent AI applications.
Master Python, Machine Learning, and Deep Learning
Begin your journey by setting up a secure Python development environment, managing API credentials, and understanding AI service integration. Learn how to process, clean, transform, and analyze data using NumPy and Pandas, two essential libraries for AI engineering and data science.
Explore Machine Learning with Scikit-learn, including classification, logistic regression, training and testing datasets, confusion matrices, precision, recall, F1 scores, cross-validation, and hyperparameter optimization.
Dive into Deep Learning with PyTorch, where you will work with tensors, automatic differentiation, neural network architectures, loss functions, optimizers, and complete neural network training loops.
Build Generative AI and Large Language Model Applications
Discover how to integrate Large Language Models (LLMs) into Python applications using REST APIs, system messages, user prompts, model parameters, streaming responses, and structured JSON outputs.
Develop a practical understanding of Prompt Engineering, LLM API Integration, Embeddings, Vector Search, and Semantic Search. Learn how to represent text as numerical vectors, calculate cosine similarity, rank documents, and implement intelligent information retrieval systems.
Master Retrieval-Augmented Generation and AI Agents
Explore Retrieval-Augmented Generation (RAG), one of the most important architectural patterns in modern Generative AI development. Learn document chunking, overlapping chunks, vector indexing, context retrieval, and grounded prompt construction to build more context-aware AI applications.
Take your skills further with Agentic AI, AI Agents, Tool Calling, Function Calling, JSON Schema, and Agent Execution Loops. Understand how AI agents interact with external tools, execute Python functions, process tool responses, and complete tasks through iterative workflows.
You will also explore AI Evaluation, AI Safety, AI Guardrails, Output Validation, Error Handling, Retry Mechanisms, and Exponential Backoff to improve the reliability of AI-powered applications.
Build an End-to-End AI Engineering Project
Apply everything you have learned by developing a Document Question-Answering AI Assistant. Combine semantic search, document retrieval, grounded prompts, source citations, and a simulated LLM component into a functional prototype exposed through a FastAPI REST API.
Who Should Take This Course?
This bootcamp is ideal for aspiring AI Engineers, Machine Learning Engineers, Generative AI Developers, Data Scientists, Python Developers, Software Engineers, AI Consultants, and Technology Professionals looking to expand their technical expertise.
Whether you are transitioning into artificial intelligence or upgrading your existing development skills, this course provides a structured pathway to understanding and implementing modern AI systems.
Start your journey into AI Engineering, Machine Learning, Generative AI, LLM Development, RAG, and Agentic AI today, and turn theoretical knowledge into practical, real-world AI development skills.
Enroll now and take the next step toward becoming a skilled AI Engineer!