
Every AI application you build in this course is a Python program, and Python itself changes between versions. Some libraries need a recent release, and some behave differently on older ones. In this opening lab you will check your Python version from a script, which is the first line of defence against confusing environment problems.
You will begin with the sys module. You will read sys.version and sys.version_info, and see that the second one is a named tuple that you can compare directly with another tuple, such as three and ten, to decide whether the interpreter is recent enough. You will also print the executable path and the platform so that you know exactly which Python is running.
Next you will write a small function that enforces a minimum version. It takes the required version as a tuple, compares it with the running one and either returns quietly or raises a clear error that names both the required and the installed version and tells the user what to do. You will call it at the top of a script so that an old interpreter fails immediately with a helpful message, instead of crashing later with a confusing syntax error.
You will test the function by passing different required versions, including one that is deliberately too high, and read the output. You will also use platform.python_version for a short text form.
You will discuss why this matters for AI work, where packages with native code are sensitive to the interpreter version.
By the end of this lab you will be able to read and compare the Python version in code and fail early with a clear message.
Virtual environments keep each project's packages separate. Normally you create one from the command line, but you can also do it from Python itself, which is useful for setup scripts. In this lab you will create a virtual environment in code.
You will begin with a quick reminder of why isolation matters. Without it, installing a package for one project can break another, and it becomes impossible to say which versions a project really needs. A virtual environment is a folder that holds its own interpreter link and its own packages.
Next you will use the standard venv module. You will import it and call venv.create with a folder name, and learn the useful options, such as with_pip to include pip and clear to replace an existing environment. You will inspect the folder that results, find the scripts or bin directory and the pyvenv.cfg file, and read what the configuration records.
You will then write a function that creates the environment only if it does not already exist, using pathlib to check, and returns the path to the interpreter inside it for the current operating system. You will handle the differences between Windows and other systems in how the interpreter path is laid out.
You will run the interpreter from inside the new environment using subprocess with an argument list, check its version and confirm that it is separate.
You will remove the environment safely at the end of the exercise.
By the end of this lab you will be able to create and locate a virtual environment from a Python script.
A common cause of mystery errors is running a script outside the virtual environment you meant to use. Packages seem to be missing, or the wrong versions appear. In this lab you will detect whether a virtual environment is active.
You will begin with how Python records it. Inside a virtual environment, sys.prefix points to the environment folder, while sys.base_prefix points to the original installation. Outside one, they are the same. You will print both values in two situations, with and without activation, and compare them to see the difference.
Next you will write a function, named something like in_virtualenv, that returns a boolean based on that comparison. You will also read the VIRTUAL_ENV environment variable and discuss why it is a weaker signal, since it is set by an activation script and not by Python, so a script run with the environment's interpreter directly may not have it.
You will use the function to protect your tools. A helper called require_virtualenv raises a clear error with instructions if the environment is not active, and you will place it at the start of a script. You will add an option to bypass the check for cases where it is genuinely not needed, such as inside a container.
You will test by running the script both ways and reading the messages. You will also record the result in a small environment report dictionary that includes the interpreter path and version.
By the end of this lab you will be able to detect virtual environments reliably and guard scripts against running in the wrong place.
A project that works on your computer needs a way to describe its dependencies so that others, and your future self, can recreate the setup. The standard way is a requirements.txt file. In this lab you will write and read one in code.
You will begin with the format. Each line names a package, optionally followed by a version specifier such as double equals and a number, a minimum version with greater-than-or-equal or a compatible release with a tilde. Comments begin with a hash, and blank lines are ignored.
Next you will write a function that creates the file from a dictionary of package names and versions, sorts the entries so that the file is stable and writes them with pathlib. You will then write the reading function. It opens the file, skips comments and blank lines, splits each line into a name and a specifier with a regular expression and returns a list of small records. You will handle unusual lines, such as extras in square brackets or environment markers, by reporting them clearly and not crashing.
You will compare the file with the installed packages using importlib.metadata, and report which are missing or at a different version. You will also discuss pinned and unpinned requirements and why pinning gives repeatable results for AI projects, where small library changes can alter behaviour.
You will test the reader with a sample file that contains tricky lines.
By the end of this lab you will be able to write, parse and check a requirements file programmatically.
AI applications need settings such as model names, API keys and limits. Writing them directly into code is a mistake, since the code gets shared and the values differ between machines. Environment variables are the standard solution. In this lab you will read configuration from environment variables.
You will begin with os.environ, a dictionary-like object that holds the variables of the running process. You will read a value by indexing, and see the KeyError when it is absent, then with the get method and a default. You will explain when a missing value should be an error and when a default is acceptable.
Next you will write a small configuration function. It reads a list of required variables, collects any that are missing and raises one error that names all of them, which is friendlier than failing on the first. It also handles optional settings with defaults, and converts types, such as turning a text value into an integer or a boolean, with clear messages for invalid input, since environment variables are always strings.
You will build a configuration data class with fields for the model name, a timeout, a debug flag and a placeholder key. You will fill it from the environment, and print it with the secret hidden.
You will set variables for a single run on your operating system, and from Python using a copy of the environment passed to a subprocess, without changing your own.
You will use placeholder values only, never real keys.
By the end of this lab you will be able to read, validate and convert settings from the environment.
Many projects keep their settings in a file named .env, with one name and value per line. Libraries exist to read it, but writing a parser by hand teaches you exactly what they do. In this lab you will parse a .env file by hand.
You will begin with the format. Each line has a name, an equals sign and a value. Lines starting with a hash are comments, blank lines are ignored, values may be wrapped in single or double quotation marks and a line may begin with the word export so that it works in a shell.
Next you will write the parser. You will read the file with pathlib, loop over its lines and strip whitespace. You will skip comments and blanks, split each line once on the first equals sign using partition so that values containing equals signs are preserved, and remove matching quotes from around the value. You will validate names with a regular expression, allowing letters, digits and underscores, and report the line number of any problem.
You will handle trailing comments carefully. A hash inside quotes is part of the value, while a hash after an unquoted value starts a comment, which requires a little more logic. You will return a dictionary and write tests with assert for many tricky lines.
You will discuss the limits of a hand-written parser, such as multi-line values and variable expansion, and why mature libraries are used in production.
You will use only placeholder values in the sample file.
By the end of this lab you will be able to parse a simple configuration file and test it against tricky input.
Parsing a .env file gives you a dictionary, but your program reads settings from the environment, not from a dictionary. The next step is to load the values into the process environment. In this lab you will load .env values into the environment.
You will begin with the target. The os.environ object can be modified, and the changes apply to the running process and to any child processes it starts. You will set a variable, read it back and observe that the change disappears when the program ends, and does not affect your terminal.
Next you will write a loader that uses your parser from the previous lab and copies each value into os.environ. You will decide on a policy for conflicts. By convention, variables that already exist in the real environment should win over the file, because deployment systems set real values, so you will use setdefault, with an override option for cases where you want the file to win.
You will print a summary of what was loaded, taking care to show only the names and not the values, and log the count at the debug level. You will handle a missing file gracefully, since the file is optional in production.
You will then combine this with the configuration reader from earlier, so that settings come from the real environment first, then from the file and then from defaults. You will write tests that use a temporary file and restore the environment afterwards, to avoid leaking changes between tests.
You will discuss the order of precedence and its benefits.
By the end of this lab you will be able to load file-based settings into the environment safely.
Secrets leak most often through version control. A key committed to a repository is public to everyone who can read it, and removing it later does not remove it from the history. In this lab you will keep secrets out of Git with a .gitignore file.
You will begin with what .gitignore does. It is a text file that tells Git which files and folders to leave out of the repository. You will learn the pattern syntax, including names, wildcards, folders with a trailing slash, negation with an exclamation mark and comments. You will write a file that excludes the .env file, virtual environment folders, caches, logs and output folders.
Next you will write Python code that checks a project. It reads the .gitignore file, converts its patterns into checks with the fnmatch module, and tests whether a list of sensitive file names would be ignored. You will report any sensitive file that is not covered, such as an .env file in a project without the right rule.
You will also scan project files for strings that look like keys, using a regular expression, and report the file and line number without printing the value. You will run it on a practice folder that contains invented placeholder keys.
You will discuss good practice. You should commit a template file, such as .env.example, with placeholders. You should treat any key that was ever committed as exposed and rotate it, and you should consider using a secret scanning tool or a pre-commit hook.
By the end of this lab you will be able to write ignore rules and check a project for exposed secrets.
Even with careful storage, a key can leak through a print statement or a log. Masking hides most of a secret while keeping enough to recognise it. In this lab you will mask API keys before printing.
You will begin with the problem. A debug message that prints the whole configuration is useful until it ends up in a shared log, a screenshot or a support ticket. A masked value, such as the first few characters followed by asterisks, still lets you check that the right key is in use without exposing it.
Next you will write a masking function. It takes a string and shows only a small number of characters at the start and end, replacing the rest with a fixed-length run of asterisks, so that the length of the secret is not revealed. You will handle short values by masking them completely, since showing characters from a very short secret would reveal most of it, and handle empty values and None.
You will then apply masking to structures. A function walks a dictionary, including nested ones, and masks the values of keys that look sensitive, such as those containing key, token, secret or password, ignoring case. You will use it when printing the configuration data class.
You will extend it to scan free text with a regular expression and replace anything that looks like a key, which is useful for log messages and error output, and test it with placeholder values.
You will discuss that masking is a second line of defence and not a replacement for keeping secrets out of logs.
By the end of this lab you will be able to mask secrets in values, dictionaries and text.
Language model APIs communicate through requests that follow a standard shape. Before calling anything, you should be able to build one and understand each part. In this lab you will build a chat request payload.
You will begin with the structure of a typical chat request. It contains the name of the model, a list of messages and optional settings. Each message is a dictionary with a role, such as system, user or assistant, and its content. You will see how the list represents a conversation in order.
Next you will write a function, build_chat_request, that takes a model name, a list of messages and keyword options such as temperature and a maximum number of tokens. It assembles a dictionary, includes the optional settings only when they are provided and returns it. You will convert it to JSON with json.dumps and print it with indentation to see what would be sent over the network.
You will add checks. The model name must be a non-empty string, the messages must be a non-empty list of dictionaries with allowed roles and string content and numeric options must lie in valid ranges. You will raise a ValueError with a specific message for each problem, and test them.
You will also use a data class to represent a message, with a method to convert it to a dictionary, and compare it with using plain dictionaries.
No network call is made in this lab. You are only building and inspecting the data.
By the end of this lab you will be able to build and validate a chat request payload.
It is time to make a model call, but without a network, a key or any cost. A stub client stands in for the real service, with the same interface and a predictable answer. In this lab you will make your first model call with a stub client.
You will begin with the reason for stubs. Developing against a real service is slow and costs money, and results vary from run to run, which makes testing hard. A stub lets you write and test all your application logic first, and swap in the real client afterwards.
Next you will design the interface. A client class has a method, such as chat, that accepts the request dictionary you built in the previous lab and returns a response dictionary with the same shape as a real one, including a list of choices, each with a message, a finish reason and a usage section with token counts. You will write the stub so that it returns a canned reply, perhaps echoing part of the last user message, and records every request it receives.
You will write a function that sends a request, reads the reply text from the nested response and prints it, and use the recorded requests in an assert to confirm that the right payload was sent. You will also write a second class with the same method, which shows how a real client would plug in, without implementing the network part.
You will discuss that code which depends on the interface, not on a specific class, is easier to test.
By the end of this lab you will be able to define a client interface, write a stub and make your first call.
A model has no memory of previous calls. To have a conversation, your program must send the earlier turns every time. In this lab you will keep conversation history.
You will begin with the idea. Each request includes the full list of messages so far, and the model produces the next assistant message. The application is responsible for storing the history and adding to it after each turn. You will write a small data structure to do this.
Next you will create a Conversation class that holds a list of messages. It has methods to add a user message, add an assistant message and return a copy of the history for sending, so that callers cannot accidentally change the internal list. You will use the stub client from the previous lab to run a few turns. You will verify that the history grows by two messages for each turn and that the order is correct.
You will explore design choices. You will decide whether the system message is stored with the history or added separately when building the request, and write the code to keep it at the start. You will add a method to clear the history and one to save and load it as JSON, so that a conversation can be resumed later.
You will look at the cost of growth. Because the whole history is sent each time, requests become larger, and you will measure the size in characters, which prepares for the token counting lessons that follow.
By the end of this lab you will be able to maintain and persist a conversation across several turns.
A system message tells the model how to behave throughout a conversation, such as its role, its tone and its rules. It is the most important tool for steering an application. In this lab you will steer the model with a system message.
You will begin with where the system message goes. It is the first message in the list, with the role system, and the model treats it as instructions from the application rather than as a statement from the user. You will compare the same user question with and without a system message, using your stub to show how the request differs.
Next you will write system messages for several purposes, such as a concise assistant that answers in two sentences, a helper that always responds in a particular format and an assistant limited to a topic. You will learn what makes a good instruction. It is specific, it states what to do rather than only what not to do and it gives a clear fallback for requests outside the scope.
You will integrate it with your Conversation class so that the system message is set once, always comes first and is preserved when the history is trimmed or cleared. You will write a function that updates it and tests that confirm the order.
You will discuss the limits. A system message is guidance, and it does not guarantee that the model will comply, particularly when a user tries to override it, so important rules must also be enforced by code that checks the output.
By the end of this lab you will be able to write effective system messages and manage them in a conversation.
Sending a malformed request wastes time and may cost money, and the error from a remote service is often vague. It is better to catch problems before sending. In this lab you will validate messages before sending.
You will begin with the kinds of problems that occur in practice. A message might have an unsupported role, empty or non-string content, an extra or missing key, or be in the wrong place, such as an assistant message at the start or two user messages in a row for services that require alternation. A conversation might also be empty.
Next you will write a validation function. It receives the list of messages and returns a list of problem descriptions, each including the position of the message, and an empty list means that everything is valid. You will check the type of every item, the presence of role and content, the set of allowed roles, the type and non-emptiness of the content and any ordering rules that you decide to enforce.
You will then write a wrapper that raises a single error containing all the problems, and use it inside your client's send method. You will test with a range of broken inputs using assert and confirm the messages are helpful.
You will consider optional strictness. Some checks, such as a maximum length, are policy and should be configurable, so you will add parameters for them.
You will discuss why returning all problems at once is better for the developer than stopping at the first.
By the end of this lab you will be able to validate conversations and report every problem clearly.
Language models do not read words. They read tokens, which are pieces of text. Understanding tokens is essential for managing limits and costs. In this lab you will learn what a token is.
You will begin with the idea in plain terms. A tokenizer splits text into pieces from a fixed vocabulary. A common word may be a single token, a rare word may be several and punctuation and spaces are often separate tokens or attached to others. Numbers and code can produce many tokens. Different models use different tokenizers, so the same text can have different counts.
Next you will build a simple tokenizer to see the process. You will write a function that splits text into words and punctuation with a regular expression, and another that breaks long words into fixed-size pieces, to imitate the subword idea. You will see how the number of tokens differs from the number of characters and words. You will estimate the common rule of thumb that, in English, a token is about four characters, and test its accuracy on several samples.
You will explain why tokens matter. Models have a limit on the number of tokens they can handle in one request, which includes both the prompt and the reply, and providers charge by the token. You will look at how text in other languages or full of symbols can use more tokens than expected.
You will note that real counting must use the tokenizer of the specific model, and that your estimate is only an approximation.
By the end of this lab you will be able to explain tokens and estimate counts from text.
A conversation is a list of messages, and every one of them counts toward the limit. To manage a long chat, you need to count tokens across all the messages. In this lab you will count tokens across a conversation.
You will begin with a counting function from the previous lab, which can be a simple estimate or the exact tokenizer of a library if one is available. You will write it as a function that takes a string and returns an integer, so that it can be swapped for a better one without changing the rest of your code.
Next you will count a whole conversation. You will loop over the messages, count the tokens in the content and add a small overhead for each message, since the chat format adds some tokens for roles and separators. You will make the overhead a parameter, because it varies between models, and add a few tokens for the reply priming at the end. You will return both the total and a breakdown by message.
You will use the function to print a table showing each message's role, token count and running total, which makes it clear where the budget is going. You will compare the totals with a context limit and compute how much room is left for the reply.
You will test the function with assert on simple, hand-calculated cases, and with an empty list. You will discuss that counts are approximations and that you should leave a safety margin.
By the end of this lab you will be able to count and display the tokens used by a conversation.
A model's reply can be short or very long, and a long reply costs more and takes longer. The max_tokens setting puts a ceiling on the length. In this lab you will limit reply length with max_tokens.
You will begin with what the parameter does. It tells the service to stop generating after a certain number of tokens, whatever the state of the answer. This protects your budget and your response time, but it can cut a reply off in the middle of a sentence.
Next you will add max_tokens to your request builder as an optional setting with validation. It must be a positive integer, and, together with the prompt tokens, it must fit within the model's context window, which you will check using your token counting function. You will write a function that calculates the largest allowed value for a given conversation and context limit.
You will use your stub to show the effect. You will make the stub respect max_tokens by truncating its canned reply to that many tokens and setting the finish reason to length when it was cut. You will compare the output for a few limits and see how truncated text looks.
You will discuss good practice. Choose a limit that matches the task, such as a small value for a classification label and a larger one for an essay. Ask the model to be brief in the prompt as well, since the limit alone does not make the answer shorter, it only cuts it off, and check the finish reason in your code.
By the end of this lab you will be able to set and validate max_tokens and handle truncated replies.
A response contains more than the text. It tells you how many tokens were used and why the model stopped. Reading this information is essential for reliable applications. In this lab you will read usage and finish reason.
You will begin with the structure of a response from your stub, modelled on real ones. It has a list of choices, each with a message and a finish_reason, and a usage section with prompt_tokens, completion_tokens and total_tokens. You will print the structure with json.dumps and indentation to see the nesting.
Next you will learn the meaning of the common finish reasons. A value such as stop means that the model finished naturally, length means that it reached the limit and was cut off, and others indicate a tool call or a content filter. Each requires different handling. You will write a function that interprets the reason and returns a plain-language status, and one that raises or warns when the reply is incomplete.
You will then handle the usage. You will extract the three counts, check that the total equals the sum of the other two, and keep a running total across several calls in a small tracker object. You will use it to report the average tokens per request.
You will write defensive code that deals with missing fields, since fields can be absent, and with unexpected values, by using get with defaults and logging a warning.
You will test with several stub responses, including a truncated one.
By the end of this lab you will be able to extract and interpret usage figures and finish reasons.
Running an AI application costs money, and the amount depends on the tokens used. Estimating the cost before and after a request lets you budget and spot problems early. In this lab you will estimate the cost of a request.
You will begin with how pricing works. Providers publish a price per million tokens, with different prices for input and output tokens, and sometimes different prices for different models. You will create a price table as a dictionary that maps model names to a pair of prices, and use invented prices that are clearly labelled as examples, since real prices change.
Next you will write a function that takes the number of prompt tokens, completion tokens and a model name, and returns the cost. You will use the Decimal type from the decimal module instead of floats, to avoid rounding errors in money calculations, and format the result to a sensible number of decimal places. You will handle an unknown model with a clear error.
You will use the function in two ways. Before sending, it estimates the cost from the counted prompt tokens and the maximum reply length, which gives an upper bound. After the response, it computes the actual cost from the usage section. You will compare them, and keep a running total in the tracker from the previous lab.
You will then add a budget check that refuses to send a request if the projected total would exceed a limit, and test it with several scenarios.
By the end of this lab you will be able to estimate costs accurately and enforce a simple budget.
As a conversation grows, it eventually exceeds the context window, or becomes expensive. You must decide what to keep. In this lab you will trim history to a token budget.
You will begin with the strategies. The simplest is to drop the oldest messages until the conversation fits. More careful approaches keep the system message always, keep the most recent turns and sometimes summarise the older content. You will implement the first two and discuss the third.
Next you will write a trimming function. It takes the messages, a maximum number of tokens and your counting function. It separates the system message, then works backwards from the newest message, adding messages while the total fits within the budget, and finally returns the system message followed by the retained messages in their original order. You will make sure the budget leaves room for the reply.
You will handle subtle problems. A conversation should not start with an assistant message after trimming, if your service requires it, so you will drop leading assistant messages. A single message that is larger than the budget needs a policy, such as truncating its content or raising an error.
You will test with conversations of different lengths and budgets, checking that the system message is kept, that the order is preserved and that the total never exceeds the limit.
You will integrate the function with your Conversation class and run a long simulated chat with the stub.
By the end of this lab you will be able to trim a conversation to fit a budget while preserving the system message.
Waiting for a long reply to finish before showing anything feels slow. Streaming delivers the reply in small pieces as it is generated, so that users see text appear immediately. In this lab you will stream a reply with a generator.
You will begin with the idea of streaming. Instead of one response, the service sends a series of small chunks, each with a few tokens of text, followed by a final chunk with the finish reason. Your code receives them one at a time and can display each one at once.
Next you will recall generators. A function that uses yield produces values lazily, one per iteration, which is a natural way to represent a stream. You will write a stub streaming method that yields the words of a canned reply as chunks, each shaped like a real streaming event, with a small delta containing the new text, and a final chunk with a finish reason. You will add an optional delay with time.sleep so that you can watch the effect in the terminal.
You will consume the stream with a for loop, printing each piece with end set to an empty string and flush set to true, so that it appears as it arrives. You will handle chunks that have no text, such as the first one that carries only the role, and the final one.
You will also show that a generator can be stopped early, for example when a user cancels, by breaking out of the loop and closing it.
By the end of this lab you will be able to produce and consume a streamed reply with a generator.
A stream is useful for display, but your program often needs the complete answer as well, for logging, validation or saving. In this lab you will assemble a streamed response into a final result.
You will begin with the problem. Each chunk contains only a fragment, and the full text, the finish reason and the usage appear in different chunks. You must combine them correctly and handle surprises such as a missing final chunk or an interrupted stream.
Next you will write a function that takes any iterable of chunks and builds a complete response in the same shape as a non-streaming one. It accumulates the text pieces in a list, which is more efficient than repeated string joining in a loop, and joins them at the end. It records the finish reason when it appears and the usage if the final chunk includes it. If the stream ends without a finish reason, it marks the response as incomplete.
You will make it display text as it arrives by accepting an optional callback function that is called for each piece, which separates the display from the assembly. You will test by passing a stub stream and a callback that collects pieces, and confirm that the combined text equals the non-streaming result.
You will test failures too. A stream that raises an exception halfway should return the partial text with an error status, rather than losing everything.
You will discuss why partial results matter in real applications.
By the end of this lab you will be able to assemble streamed chunks into a complete, validated response.
A system prompt sets the standing instructions for a conversation, and in real applications it is one of the most reused pieces of text you will write. Treating it as a named constant, rather than a string buried in a function call, makes it easy to find, review and change. In this lab you will build a system prompt as a constant.
You will begin by defining a module-level constant in capital letters, using a triple-quoted string so the prompt can span several lines. You will keep the text short and specific: who the assistant is, what it should do and how it should format its answers. You will then print the constant and check its length in characters so you have a rough sense of its size.
Next you will place the constant in a messages list as the first entry with the system role, followed by a user message, and pass the list to a stub client. You will see that changing the constant in one place changes every call that uses it, which is exactly why constants beat copied strings.
You will also look at small hygiene points, such as stripping leading and trailing whitespace with strip or textwrap.dedent so that indentation in your source code does not leak into the prompt. You will compare the dedented and raw versions side by side.
You will finish by moving the constant into its own small module and importing it from a second script.
By the end of this lab you will be able to define, clean and reuse a system prompt as a single named constant.
A prompt that only says "be helpful" leaves the model to guess what you want. Giving it a clear role and a short list of rules makes behaviour more predictable and easier to test. In this lab you will write a role-and-rules system prompt and wire it into a request.
You will begin with the role. You will write one or two sentences that say who the assistant is and who it is talking to, such as a patient tutor for beginner Python programmers. You will discuss why a concrete audience helps the model choose vocabulary and level of detail.
Next you will add rules as a numbered list. You will write rules about scope, such as answering only questions about Python, rules about format, such as keeping answers under a set number of sentences, and rules about uncertainty, such as saying so when the answer is not known. You will keep each rule to one clear sentence and avoid rules that contradict each other.
You will then build the prompt in code by joining the role and the rules from Python lists, so the rules can be edited or counted without touching the surrounding text. You will print the final prompt and send it with a user question to a stub client.
You will review common mistakes, including vague wording, too many rules and rules that restate the obvious, and trim your prompt accordingly.
By the end of this lab you will be able to write a compact role-and-rules system prompt and assemble it from structured parts.
Hard-coding every question into a prompt does not scale. Most real prompts are templates with a few slots that are filled in at run time, such as the user's text, a target language or a tone. In this lab you will fill prompt templates with variables.
You will begin with the simplest tool, str.format. You will write a template with named placeholders in curly braces, fill it with keyword arguments and print the result. You will then see what happens when a placeholder is missing, which raises a KeyError that you will learn to read.
Next you will try the standard library's string.Template, which uses a dollar sign syntax. You will compare it with str.format and learn why it can be more comfortable when your text contains many literal curly braces, for example when a prompt includes a JSON example.
You will then write a small function called render_prompt that takes a template and a dictionary of values and returns the finished text. You will add a safe default for optional values using dict.get, and make sure that extra keys do not cause errors.
You will use the function to build several prompts from one template, such as summarise, translate and explain, and print them for comparison.
You will also discuss keeping templates in constants or files so that they are separate from logic.
By the end of this lab you will be able to build reusable prompt templates and fill them safely with variables.
A template is only as good as the values you put into it. An empty string, a missing field or an enormous paste can silently produce a broken prompt and a wasted request. In this lab you will validate prompt variables before sending anything to the model.
You will begin by listing what can go wrong. Values can be missing, empty, of the wrong type, too long or full of stray whitespace. You will write a short test for each case so that you can see the failure before you fix it.
Next you will write a function called validate_variables that takes the template's required names and a dictionary of values. It checks that every required name is present, that each value is a string, that it is not blank after stripping and that it stays under a maximum length. You will return a clean dictionary on success and raise a ValueError with a precise message on failure.
You will learn to collect all the problems in a list and report them together, instead of stopping at the first one, so the caller can fix everything in one pass. You will use string.Formatter().parse to discover the placeholder names in a template automatically rather than keeping a second list by hand.
You will connect the validator to render_prompt from the previous lab, and run a set of good and bad inputs through the combined pipeline.
By the end of this lab you will be able to check prompt variables before sending and give clear, complete error messages.
Showing the model a few worked examples is often more effective than describing the task in words. In chat-style interfaces these few-shot examples are usually written as message pairs: a user message with the input and an assistant message with the ideal output. In this lab you will build few-shot examples as message pairs.
You will begin with a small task, such as classifying short customer comments as positive, negative or neutral. You will write the instruction in a system message and then add three examples, each as a user message followed by an assistant message that contains only the label.
You will print the whole messages list and read it as the model would, noticing how the pattern of alternating roles establishes the expected format. You will then add the real input as the final user message and send the list to a stub client.
Next you will discuss what makes good examples. They should be varied, cover the edge cases that matter, use exactly the output format you want and avoid accidentally teaching a bias, such as showing only positive examples first. You will reorder your examples and talk about why order can matter.
You will also compare this approach with putting all the examples inside one big user message, and see why message pairs are cleaner to build and easier to change.
By the end of this lab you will be able to create few-shot prompts as alternating user and assistant messages.
Writing few-shot examples by hand works for a demo, but real projects keep examples in data so that they can be reviewed, extended and tested. In this lab you will generate few-shot messages from a list of records.
You will begin by storing your examples as a list of dictionaries, each with an input and an output key. You will keep the data in a Python list first and then move it to a small JSON file that you load with the json module, so that someone who does not write Python could edit it.
Next you will write a function called build_few_shot that takes the system prompt, the examples and the new input and returns the full messages list. Inside it you will loop over the examples and append a user and an assistant message for each. You will check that the function handles an empty examples list, which should produce a plain zero-shot request.
You will add an optional limit argument so that only the first few examples are used, and see how that lets you compare zero-shot, one-shot and few-shot prompts using the same data. You will print the number of messages in each case to confirm the structure.
You will also validate the data, making sure every record has both keys and that no output is blank, using the habits from the earlier validation lab.
By the end of this lab you will be able to turn stored example data into correct few-shot message lists with one reusable function.
Every example you add to a prompt costs tokens, and tokens cost money and time. They also take up room in the context window that you might need for the real input. In this lab you will count the token cost of your few-shot examples.
You will begin with a quick reminder of what a token is and why a rough estimate is useful even without a real tokenizer. You will write a simple estimator that divides the character count by four, and compare it with a word-count-based estimate to see how they differ on short and long texts.
Next you will write a function called estimate_message_tokens that goes through a messages list, estimates each message's content and adds a small fixed overhead per message for the role and formatting. You will print the cost of the system prompt, of each example pair and of the final user input in a small table.
You will then use the function to answer practical questions. How many tokens does adding two more examples cost? How many examples fit if the budget for the prompt is five hundred tokens? You will write a loop that adds examples until the next one would exceed the budget, and then stops.
You will discuss why you should treat these numbers as estimates, and leave a safety margin when you work close to a limit.
By the end of this lab you will be able to estimate prompt cost and choose how many examples fit a token budget.
Temperature is one of the most talked-about settings in language model work, and it is simply a number in the request. It controls how adventurous the model is when it picks the next token. In this lab you will treat temperature as a request parameter.
You will begin with the idea. A low temperature, near zero, makes the model choose the most likely tokens and produces steadier, more repeatable answers. A higher temperature spreads the choices and produces more varied and creative output. You will discuss which tasks suit each setting, such as extraction and classification at the low end and brainstorming at the higher end.
Next you will build a request dictionary in Python with a model name, a messages list and a temperature value. You will write a small function called make_request that accepts temperature as an argument, with a sensible default, and checks that it lies within the allowed range, raising a ValueError otherwise.
You will see how the parameter sits alongside others, such as max_tokens, in the same dictionary, and print the request as formatted JSON to see exactly what would be sent.
You will test the validation with values that are too low, too high and of the wrong type, such as a string, and read the errors.
You will finish by noting that the model may not be perfectly repeatable even at zero, and that you should design tests accordingly.
By the end of this lab you will be able to set and validate temperature in a request.
Reading about temperature is helpful, but seeing its effect makes the idea stick. Because this course uses stub clients with no real network calls, you will build a small stub that mimics how temperature changes variety. In this lab you will compare temperatures with a stub client.
You will begin by writing a stub class called FakeClient with a complete method. It holds a short list of possible replies. At temperature zero it always returns the first reply. As temperature rises, it uses the random module with a fixed seed to choose from a wider portion of the list. You will explain clearly that this is a teaching model and not how a real model works internally.
Next you will write a loop that sends the same prompt five times at several temperatures, such as zero, half and one, and collects the replies. You will count the number of distinct replies at each setting with a set and print a small table.
You will see that low temperature gives one answer every time, while higher values give more variety. You will use the seed to make the output the same on every run, which is a good habit for any example that involves randomness.
You will discuss what this means for your own tests, and why you should lower temperature when you need steady output.
By the end of this lab you will be able to compare temperature settings and explain their effect on repeatability.
The max_tokens parameter puts a hard ceiling on how long a reply can be, but it does not teach the model to write shorter answers. If the limit is reached mid-sentence, the reply is simply cut off. In this lab you will pair max_tokens with matching instructions in the prompt.
You will begin by building a request with a small max_tokens value and a prompt that asks for a long explanation. You will use a stub client that truncates its reply at the limit and reports a finish reason of length rather than stop. You will print both so you can see what a clipped answer looks like.
Next you will rewrite the prompt to ask for a specific size, such as two sentences or three bullet points, and set max_tokens a little above what that answer needs. You will see that the stub now finishes naturally and reports stop.
You will write a helper called was_truncated that checks the finish reason and returns a boolean, and use it to warn the user or retry with a larger limit. You will also discuss how to choose a sensible limit from your estimate of the expected answer size, leaving some headroom.
You will review why the two controls work together: the instruction shapes the answer, and the limit protects your budget and your latency.
By the end of this lab you will be able to combine length instructions with max_tokens and detect truncated replies.
By now you have several generation settings that you pass with nearly every request. Repeating them in each call invites mistakes, and different tasks need different combinations. In this lab you will create a reusable generation settings preset.
You will begin by listing the settings you have used, such as temperature, max_tokens and perhaps a stop sequence or a top_p value. You will group them into a plain dictionary and discuss why one named object is easier to review than several loose arguments.
Next you will define a few presets as constants, such as PRECISE for extraction, BALANCED for general chat and CREATIVE for brainstorming. Each preset is a dictionary with its own sensible values. You will print them side by side to compare.
You will then write a function called build_request that takes messages, a preset and optional overrides. It copies the preset, applies any overrides and validates the result using your earlier checks. You will see why copying matters, by showing what happens if you accidentally change a shared preset in place.
You will test the function with no overrides, with one override and with an invalid override, and print the final request each time.
You will finish by using a dataclass to give the preset a clear type, and compare it with the plain dictionary approach.
By the end of this lab you will be able to define named presets, apply overrides safely and build consistent requests.
Programs cannot do much with free-form prose, but they can do a great deal with structured data. The most common way to get structure from a language model is to ask it for JSON. In this lab you will write prompts that ask the model for JSON and see what makes the request reliable.
You will begin with a small task, such as extracting a name, a date and a priority from a short note. You will write a first prompt that simply says "give me JSON" and look at the kind of reply a stub client returns, which includes friendly sentences around the data. You will discuss why that is a problem for a program that expects to parse the reply directly.
Next you will improve the prompt step by step. You will state that the reply must be a single JSON object and nothing else, list the exact keys, describe the type of each value and say what to use when information is missing, such as null. You will include one short example of the expected output.
You will compare the replies from the weak and the strong prompt using the stub, and print them one after the other.
You will also discuss why you should never assume the model obeys perfectly, which sets up the parsing and validation labs that follow.
By the end of this lab you will be able to write clear prompts that ask for JSON with exact keys and types.
Once you have a reply that should be JSON, you need to turn it into Python objects. The standard library does this with json.loads. In this lab you will parse model replies with it and work with the result.
You will begin by calling json.loads on a simple string and checking what comes back. You will see how JSON objects become dictionaries, arrays become lists, and true, false and null become True, False and None. You will print the types to make the mapping concrete.
Next you will parse a stub reply that represents a model's answer and read values from it with square brackets and with dict.get. You will discuss why get is safer when a key might be missing, and how to supply a default.
You will then compare json.loads with json.dumps and use dumps with indent to print parsed data neatly. You will also try the sort_keys option and see why it helps when you compare outputs in tests.
You will write a function called parse_reply that takes the reply text, calls json.loads and returns the result, and you will use it on several sample replies, including nested objects and lists of objects. You will loop over a list of items from the reply and print one field from each.
You will end by noting that real replies are not always valid, which leads directly to the next lab.
By the end of this lab you will be able to parse JSON text into Python data and read it safely.
Language models sometimes produce text that looks like JSON but is not. A trailing comma, single quotes, a missing bracket or a sentence before the data will all break the parser. In this lab you will catch malformed JSON and respond sensibly.
You will begin by collecting a handful of broken examples in a list. They include a missing closing brace, single-quoted keys, a trailing comma, a comment and plain prose. You will pass each to json.loads inside a try block and watch it raise json.JSONDecodeError.
Next you will read the error object closely. It carries a message, the position in the text, and the line and column numbers. You will print these and use the position to show a short snippet of the text around the problem, which makes the failure much easier to diagnose.
You will then write a function called safe_parse that returns a pair: the parsed data and an error message. On success the message is None, and on failure the data is None. You will explain why this style is more convenient than letting exceptions travel far from the cause.
You will run all your broken examples through safe_parse and print a tidy report. You will also decide what a caller should do on failure, such as retry, repair or report, and note that those choices are built later in this section.
By the end of this lab you will be able to detect invalid JSON, read the error details and return a clean failure result.
Even when a model produces valid JSON, it often wraps it in a markdown code fence, with three backticks and sometimes the word json, because that is how it has seen code displayed. Your parser does not expect that. In this lab you will clean code fences from replies before parsing.
You will begin by looking at several typical replies: a bare object, an object inside a fence, an object inside a fence labelled json and an object with a sentence before and after it. You will confirm that json.loads fails on all but the first.
Next you will write a function called strip_fences. You will start with a simple approach that trims whitespace and removes a leading fence line and a trailing fence line. You will then improve it with a regular expression from the re module that captures the content between the fences, whatever the label.
You will add a fallback for replies with surrounding prose, which finds the first opening brace and the last closing brace and takes the text between them. You will discuss the limits of this trick and why it should come after the careful steps rather than replace them.
You will combine the cleaner with safe_parse from the previous lab into a function called extract_json, and test it on all your samples, printing which ones now succeed.
By the end of this lab you will be able to remove code fences and surrounding text so that valid JSON can be parsed.
Valid JSON is not the same as correct data. A reply can parse perfectly and still be missing the field your program needs. In this lab you will check that required keys are present before using the data.
You will begin with a small example in which a program reads the key "priority" from a parsed reply and crashes with a KeyError because the model left it out. You will use this to explain why checking at the boundary is better than crashing deep inside your code.
Next you will write a function called missing_keys that takes a dictionary and a list of required keys and returns the names that are absent. You will use set operations to do this compactly, and compare that with a loop so you understand both ways. You will print the result for complete and incomplete replies.
You will then write check_required, which raises a ValueError listing every missing key in one message, or returns the data unchanged if all are present. You will also handle the case where the parsed value is not a dictionary at all, such as a list or a string, and give a separate, clear error for it.
You will extend the function to optionally reject unexpected extra keys, and discuss when strict checking helps and when it is too fussy.
You will test it on a mix of good and bad replies and print a summary.
By the end of this lab you will be able to verify required keys and report all missing ones at once.
Having the right keys is only half of validation. The values must also be of the right type, because a priority that arrives as the string "high" cannot be compared with a number, and a date that arrives as an integer will break formatting. In this lab you will check field types.
You will begin with a mapping that describes the expected type for each key, such as a string for name, an integer for count, a boolean for urgent and a list for tags. You will keep it as a plain dictionary so that it reads like documentation.
Next you will write a function called check_types that loops through the mapping and uses isinstance to compare each value with its expected type. You will meet an important Python quirk, which is that a boolean counts as an integer, and write a small rule so that True is not accepted where a number is required.
You will allow some fields to be optional or nullable by letting the mapping accept a tuple of types that includes type None. You will also check the type of items inside a list, for example that every tag is a string.
You will collect all the type problems and report them together in a single error message that names each field, the expected type and the actual type found.
You will run it on good replies and on replies with the wrong types and print the results.
By the end of this lab you will be able to validate field types, including optional fields and list items.
Your checks for keys and types are most useful when they come from one place. If the required keys are listed in the prompt, in the key check and in the type check, three copies will drift apart. In this lab you will describe a schema as data and drive everything from it.
You will begin by designing a simple schema format using plain dictionaries. Each field gets an entry that holds its type, whether it is required and a short description. You will write the schema for the note-extraction example from earlier and print it as JSON.
Next you will write a function called validate_against that takes data and a schema and returns a list of problems. It checks for missing required fields, wrong types and unexpected keys, reusing the ideas from the previous labs, but now reading its rules from the schema rather than from fixed code. You will see that adding a field means editing only the schema.
You will also add optional constraints, such as a list of allowed values for a field like priority, and a minimum and maximum for numbers. You will test each constraint with a failing example.
You will discuss how this relates to the formal JSON Schema standard and to libraries that implement it, and why a small hand-built version is a good way to understand what those tools do.
By the end of this lab you will be able to describe expected output as a schema and validate data against it.
A schema is useful for checking replies, but it is even more useful when the model can see it. If the prompt describes the same fields that your validator checks, the model is far more likely to produce a matching reply. In this lab you will put the schema into the prompt.
You will begin by reusing the schema dictionary from the previous lab. You will write a function called schema_to_text that turns it into a short, readable description for the model, listing each field, its type, whether it is required and what it means. You will discuss why plain, compact wording often works as well as raw JSON Schema.
Next you will write build_extraction_prompt, which combines a system instruction, the schema text, a short example of a correct reply and the user's input. You will print the whole prompt and review it for clarity, length and contradictions.
You will then connect the pieces. You will send the prompt to a stub client, run the reply through your fence cleaner, parser and validator, and print whether the reply passed. You will check that changing the schema changes both the prompt and the validation without any other edit.
You will measure the added cost of including the schema using your token estimate from the previous section, and discuss how to keep the description brief.
By the end of this lab you will be able to generate prompt text from a schema so the model and the validator agree.
Even with a clear prompt and a good validator, some replies will fail. A common and effective response is to try again. In this lab you will retry a request when the output is invalid.
You will begin by writing a stub client that fails in a controlled way. It returns a broken reply on the first call, another on the second and a valid one on the third, so that your retry code has something to do. You will count the calls it receives.
Next you will write a function called get_valid_output that runs a loop for at most a fixed number of attempts. On each attempt it calls the client, cleans and parses the reply, validates it and returns the data if it passes. If an attempt fails, it records the reason and tries again. If all attempts fail, it raises a clear error that includes the list of reasons.
You will discuss why the maximum number of attempts matters, since every retry costs time and money, and why an unbounded loop is a serious bug. You will add a short pause between attempts using time.sleep, and see how a growing delay is a common pattern.
You will also log each attempt with its outcome and print a summary at the end. You will test the function with a client that succeeds immediately and with one that never succeeds.
By the end of this lab you will be able to build a bounded retry loop that stops on success or after a limit.
A plain retry sends the same request again and hopes for a better result. A smarter retry tells the model what went wrong, so the second attempt can correct the exact problem. In this lab you will feed validation errors back to the model.
You will begin by looking at what your validator already produces: a list of precise problems, such as a missing key or a field of the wrong type. You will discuss why these messages are valuable to the model as well as to a human reader.
Next you will extend get_valid_output from the previous lab. After a failed attempt, it appends two messages to the conversation: the assistant's invalid reply and a new user message that says the answer was not valid, lists the problems and asks for a corrected JSON object only. You will print the growing messages list after each failure so you can see the conversation develop.
You will use a stub client that checks for the error message in the conversation and returns a corrected reply only when it sees one. This lets you demonstrate that the feedback is what fixes the problem, without any real calls.
You will discuss the cost of longer conversations, why you should keep the error message short and why you should still limit the number of attempts. You will also decide what to do when the problem is clearly in the input and not in the model.
By the end of this lab you will be able to build a self-correcting loop that uses validation errors as feedback.
Search, recommendations and retrieval-augmented generation all rest on one idea: turning text into a list of numbers so that a computer can measure how similar two pieces of text are. That list of numbers is called an embedding. In this lab you will look at what an embedding actually looks like.
You will begin with a tiny, hand-made example. You will represent a few words as short lists of numbers, such as three values each, and place related words close together and unrelated words far apart. You will print them and discuss what each position might loosely stand for, while being clear that real models learn their dimensions rather than having named ones.
Next you will inspect the shape of an embedding. You will write code to report its length, which is the number of dimensions, and show the first few values. You will discuss that real embedding models return hundreds or thousands of numbers, and that every text, whether a word or a paragraph, is turned into a vector of the same length.
You will use a stub embedder that returns fixed vectors for a few sample sentences, so no network calls are needed. You will store them in a dictionary keyed by the text and print the dimensions.
You will end by comparing two vectors by eye, and see why we need a precise measure of similarity, which the next labs provide.
By the end of this lab you will be able to describe an embedding as a fixed-length vector and inspect its shape in Python.
To practise vector search you need an embedder that you can run anywhere and understand completely. A real embedding model is large and opaque, but a simple deterministic one is enough to learn the mechanics. In this lab you will build a bag-of-words embedder.
You will begin by building a vocabulary. You will lower-case a small collection of sentences, split them into words with a regular expression, and collect the unique words into a sorted list. Each word gets a fixed position in the vector.
Next you will write a function called embed that takes a text and returns a list of counts, one per vocabulary word. You will go through an example by hand first, then check that your code agrees. You will handle words that are not in the vocabulary by ignoring them, and discuss what that means for new text.
You will confirm that the function is deterministic, so the same text always gives the same vector, which makes tests dependable. You will also print the vector for two similar sentences and two unrelated ones and see that the similar ones share many nonzero positions.
You will discuss the limits of this approach honestly. It knows nothing about meaning or synonyms, only about shared words. Real embedding models capture much more, but the code that uses vectors stays the same.
By the end of this lab you will be able to build a deterministic embedder and use it to turn text into vectors.
Before you can compare vectors you need two basic operations: the dot product and the length. Almost every similarity measure is built from these two. In this lab you will implement both in plain Python.
You will begin with the dot product. You will multiply the numbers at each position of two vectors and add the results. You will write it first as a loop and then as a one-line version using zip and sum, and check that both give the same answer on a small example worked out by hand.
Next you will implement the length of a vector, also called its magnitude or norm. You will square each value, add them and take the square root with math.sqrt. You will connect this to the idea of distance from the origin in two dimensions, which you can picture easily, and then note that it works the same way in many dimensions.
You will see the relationship between the two operations, since the dot product of a vector with itself equals its length squared, and you will verify that with code.
You will also handle error cases, such as vectors of different lengths, by raising a clear ValueError, and the zero vector, whose length is zero and which will cause trouble in the next lab.
You will write several small tests with assert statements and run them.
By the end of this lab you will be able to compute dot products and vector lengths and test your functions.
Cosine similarity is the standard way to measure how alike two embeddings are. It ignores how long the vectors are and looks only at the angle between them, so a short text and a long text about the same topic can still match. In this lab you will implement cosine similarity.
You will begin with the formula in words: take the dot product of the two vectors and divide it by the product of their lengths. You will use the functions from the previous lab, so the new function is only a few lines long.
Next you will test it on simple vectors with known answers. Two identical vectors give one. Two vectors that point in opposite directions give minus one. Two vectors at right angles give zero. You will print these and check that the numbers match the picture in your head.
You will then apply it to your bag-of-words embeddings. You will compare one sentence with several others and print a ranked list of scores, and see that sentences sharing important words score higher.
You will deal with the edge case of a zero vector, which would cause a division by zero, and decide to return zero similarity in that case, with a note explaining the choice. You will also discuss rounding, and why you should compare floating-point values with a tolerance and not with exact equality.
By the end of this lab you will be able to compute cosine similarity and interpret its range.
Once you can score how similar each item is to a query, you need to pick the best few. Almost every search system returns the top results, not everything. In this lab you will rank results with top-k selection.
You will begin with a list of documents and their similarity scores. You will pair each document with its score in a list of tuples and sort it using sorted with a key function and reverse set to True. You will print the ranked list and read it from the top.
Next you will write a function called top_k that takes the scored items and a number k and returns the best k. You will use slicing for the simple version and discuss what happens if k is larger than the number of items, or zero, or negative, and make the function behave sensibly in each case.
You will then learn about the heapq module and its nlargest function, which finds the top k without sorting everything, and compare it with sorting on a larger list. You will time both with time.perf_counter and discuss when the difference matters.
You will handle ties, where two items have the same score, by adding a second sort key so that results come out in a stable, predictable order, which is important for repeatable tests.
You will print the final ranked results with their positions, starting from one.
By the end of this lab you will be able to select and order the best k results reliably.
A vector index is the structure that stores your documents together with their embeddings so that you can search them. Large systems use specialised databases, but the idea can be built in a few lines. In this lab you will build an in-memory vector index.
You will begin by defining what each entry holds: an identifier, the original text, its embedding and optionally some metadata. You will model the entry as a dictionary first, then as a small dataclass, and discuss the benefits of the typed version.
Next you will write an index class called VectorIndex. It keeps a list of entries and offers an add method that takes a text, calls the embedder and stores the entry. You will make the identifier automatic using a counter and return it so the caller can refer to the item later.
You will add a method to report the number of items, a method to fetch an entry by its identifier and a method to remove one. You will discuss what should happen when an identifier is not found, and decide between raising an error and returning None.
You will fill the index with a dozen short sentences on a few topics, using your deterministic embedder, and print its size.
You will talk about why real indexes use approximate search structures for millions of items, while an exact scan like yours is fine for thousands.
By the end of this lab you will be able to build a small vector index that stores texts with their embeddings.
With an index and a similarity function, you can now build the feature people actually want: search by meaning. In this lab you will write a semantic search function that takes a question and returns the closest documents.
You will begin with the steps in order. Embed the query with the same embedder used for the documents, compare it with every stored vector using cosine similarity, sort the results and return the top few. You will stress that the query and the documents must use the same embedder, otherwise the numbers are not comparable.
Next you will add a search method to your VectorIndex class. It accepts a query string and a value for k, and returns a list of result objects that each hold the identifier, the text and the score. You will make the results easy to read when printed.
You will run several queries against your small index and print the results, checking that the top answers make sense. You will also try a query that uses words not found in any document and see what the scores look like.
You will discuss why results should include the score, since later steps will use it to decide whether a match is good enough, and why returning plain tuples becomes awkward as the data grows.
You will write a few assertions that check that the best match for a known query is the expected document.
By the end of this lab you will be able to run a semantic search over an index and return scored results.
Search always returns something, even when nothing in the index is relevant. If you pass those results on without checking, an application can present unrelated text as if it were an answer. In this lab you will apply a similarity threshold and handle the case where nothing matches.
You will begin by running a query that has no real match in your index and printing the top results with their scores. You will see that the best score is low but the function still returns items, and explain why that is dangerous.
Next you will add a min_score parameter to your search method. Any result below the threshold is dropped before the list is returned. You will try several threshold values, such as zero, one tenth and one third, with a set of good and bad queries, and print how many results survive each time.
You will discuss that there is no universal threshold. The right value depends on the embedder, the data and the cost of a wrong answer, so it should be chosen by testing on examples and kept in configuration.
You will then design how a caller learns that nothing matched. You will compare returning an empty list with raising an exception, and choose the empty list, with a helper that produces a friendly message such as "No relevant results found."
You will test the behaviour with assertions for both matching and non-matching queries.
By the end of this lab you will be able to filter weak matches with a threshold and handle empty results cleanly.
Sometimes semantic similarity alone is not enough. A user may only want documents from a certain category, language, year or product. Filtering on metadata before the similarity step makes results both faster and more relevant. In this lab you will filter by metadata before search.
You will begin by attaching metadata to each entry when you add it, such as a topic, a source and a year, stored in a dictionary. You will add a dozen entries across two or three topics and print them as a table.
Next you will write a small function called matches_filter that takes an entry's metadata and a filter dictionary and returns True only if every filter key equals the entry's value. You will extend it to accept a list of allowed values, so that a filter such as topic in a given set works, and discuss how to deal with entries that lack the key.
You will then add an optional where argument to your search method. It filters the entries first and runs the similarity ranking only on those that remain. You will compare results with and without the filter for the same query and see how irrelevant items disappear.
You will count how many similarity calculations are performed in each case, and discuss why filtering first saves work as the index grows.
You will also test the edge case where the filter removes everything, and make sure the search returns an empty list without errors.
By the end of this lab you will be able to restrict a search with metadata filters and explain why they help.
Building an index takes time, and in real applications you do not want to rebuild it every time the program starts. Saving it to disk and loading it again is a basic requirement. In this lab you will save and reload your index.
You will begin by deciding what to store: the entries with their identifiers, texts, metadata and embeddings, and enough information to rebuild the embedder, such as the vocabulary. You will explain why the vocabulary matters, since a query embedded with a different vocabulary would not be comparable.
Next you will write a save method that converts the index to a plain dictionary and writes it to a JSON file with the json module and a context manager. You will choose indent for readability and discuss the size trade-off. You will use pathlib to build the file path and create the folder if needed.
You will then write a load class method that reads the file, rebuilds the entries and returns a working index. You will run a search before saving and again after loading, and check with an assertion that the results are identical.
You will add a version field to the file so that future changes can be detected, and raise a clear error when the file is missing, corrupted or of an unknown version.
You will discuss when JSON is enough and when a binary format or a database is a better fit.
By the end of this lab you will be able to persist an index to JSON and load it back safely.
Language models can only read a limited amount of text at once, and retrieval works best on small, focused pieces. So before you index a long document, you split it into chunks. In this lab you will split text into fixed-size chunks.
You will begin with a long sample passage and a question: how do you cut it up? You will start with the simplest answer, which is to slice the string every fixed number of characters. You will write a function called chunk_by_chars that takes the text and a size and returns a list of chunks, using a loop with range and a step.
You will print the chunks with their lengths and see the first problem, which is that cuts land in the middle of words and sentences. You will count the chunks and check that no text is lost by joining them again and comparing with the original.
Next you will switch to chunking by words, which avoids breaking a word. You will split the text, group a fixed number of words and join them back with spaces. You will compare the two approaches on the same passage.
You will handle edge cases, such as an empty string, text shorter than the chunk size and a size of zero, with clear behaviour for each.
You will discuss why chunk size is a trade-off between precision and context.
By the end of this lab you will be able to split text into fixed-size chunks by characters or words.
Fixed-size chunks have a weakness: an idea that sits across a boundary gets cut in half, and neither piece makes full sense on its own. Overlapping chunks reduce that problem by repeating a little text at each boundary. In this lab you will build overlapping chunks.
You will begin by showing the problem with an example sentence that straddles two chunks, and search for a question about it to see the result get worse. You will explain the idea of overlap in a simple picture, where each chunk starts a little before the previous one ended.
Next you will extend your word-based chunker with an overlap parameter. The step between chunk starts becomes the size minus the overlap, and you will write the loop carefully so it neither skips text nor runs forever. You will add a check that overlap is smaller than size, and raise a ValueError if it is not.
You will print the chunks with their start positions and see the shared words at each boundary. You will verify, by rebuilding the text from the non-overlapping parts, that nothing is missing.
You will discuss the cost of overlap, since it increases the number of chunks and the storage and search work, and how to choose a modest value such as ten to twenty percent of the size.
You will test the function with several sizes and overlaps and print the number of chunks each time.
By the end of this lab you will be able to create overlapping chunks and choose sensible overlap values.
Cutting at fixed positions is easy but crude. Text already has natural boundaries, such as sentences and paragraphs, and chunks that respect them are easier to read and often retrieve better. In this lab you will chunk on sentence and paragraph boundaries.
You will begin with paragraphs. You will split the text on blank lines with a regular expression and strip the pieces, dropping any that are empty. You will print the result and notice that paragraph lengths vary widely.
Next you will split into sentences. You will write a simple regular expression that breaks after a full stop, question mark or exclamation mark followed by a space and a capital letter. You will test it on tricky inputs, such as abbreviations and decimal numbers, and discuss honestly that rule-based splitting is imperfect.
You will then build a chunker that packs whole sentences into a chunk until adding the next one would exceed a maximum size, then starts a new chunk. You will handle the case of a single sentence that is longer than the limit by splitting it by words as a fallback.
You will combine this with paragraph boundaries, so that a chunk never crosses a paragraph unless it has to. You will compare the number and the size of chunks from the three strategies on the same document and print a short comparison.
By the end of this lab you will be able to chunk text on natural boundaries while respecting a size limit.
A retrieved chunk is much more useful if you know where it came from. Without that information you cannot cite it, link to it or debug a poor answer. In this lab you will attach source metadata to chunks.
You will begin by deciding what to record. You will choose a document name or path, a chunk number, the character or word range the chunk covers and perhaps a title or section heading. You will explain how each field helps later, for example in a citation or in a reprocessing step.
Next you will represent a chunk as a dataclass with a text field and a metadata dictionary, or as separate typed fields. You will write a function called make_chunks that takes a document's text and name, runs your chunker and returns a list of these objects with the metadata filled in.
You will create a stable identifier for each chunk, such as the document name plus the chunk number, and discuss why stable identifiers matter when a document is updated. You will also compute a short hash of the text with hashlib to detect whether a chunk has changed.
You will process two or three small documents, collect all their chunks into one list and print a compact table of identifiers, sources and the first words of each text.
You will write assertions that check that every chunk has the required metadata.
By the end of this lab you will be able to produce chunks that carry reliable source information.
With chunks and an index in hand, you can now put them together so that a whole document collection becomes searchable. In this lab you will index chunks for retrieval.
You will begin with a small folder of sample text files that you create in the lab, each about a different topic. You will use pathlib to list the files, read each one with the right encoding and handle any file that cannot be read with a clear message instead of a crash.
Next you will write an ingest function that runs the full pipeline for each file: read the text, split it into chunks, build the chunk objects with metadata and add each one to the vector index with its metadata. You will have it return a short report with the number of files, chunks and any problems.
You will think about duplicates. If the same file is ingested twice, you would get duplicate entries, so you will use the stable chunk identifiers from the previous lab to skip or replace what is already present.
You will then run a few test searches over the finished index and check that the results come back with their source names and chunk numbers. You will save the index with the method from the earlier lab so that ingestion does not have to be repeated.
You will print a summary showing the time taken and the number of chunks per file.
By the end of this lab you will be able to ingest documents into a searchable chunk index.
Retrieval is the step in which a question finds the chunks most likely to contain its answer. It sits between your index and the language model. In this lab you will retrieve the top chunks for a question.
You will begin by writing a function called retrieve that takes the index, a question and a value for k. It embeds the question, searches the index and returns result objects that hold the chunk text, its score and its source metadata. You will print the results in a readable format, with the rank, score, source and a short preview.
Next you will run a set of test questions whose answers you know are in your sample documents. You will check whether the correct chunk appears in the top results, and count how often it does. This simple measure is often called a hit rate, and you will compute it with a short loop.
You will experiment with the value of k. You will see that a very small k can miss the answer, while a large k adds noise and costs more tokens later. You will print the hit rate for several values and discuss how to choose.
You will also look at failures. For each missed question you will print the question and the top results and try to understand why, for example because the question uses different words from the document, which a bag-of-words embedder cannot bridge.
By the end of this lab you will be able to retrieve relevant chunks for a question and measure how well retrieval works.
Retrieval always returns k results, whether or not they are any good. Passing weak matches to the model adds noise, wastes tokens and can lead it to build an answer from unrelated text. In this lab you will filter weak matches.
You will begin by running questions of two kinds: ones that are answered in your documents and ones that are not. You will print the scores for each and look for a pattern. Good matches tend to have clearly higher scores than the rest, though the exact numbers depend on your embedder.
Next you will add a minimum score to the retrieve function, as you did for the index search, and apply it after ranking. You will also add a relative rule, which keeps only results whose score is within a given fraction of the best score. You will discuss when each rule is useful and try them separately and together.
You will decide what happens when nothing survives the filters. You will return an empty list and make the calling code produce a clear "I do not have enough information" answer, rather than sending an empty context to the model.
You will test your settings against both kinds of question and count the correct accepts and the correct rejections, then adjust the values until the balance looks reasonable. You will write down the chosen values in a configuration dictionary.
By the end of this lab you will be able to filter retrieval results with absolute and relative score rules.
After retrieval, the chunks need to be presented to the language model in a form it can use and that you can later cite. A numbered context block does both. In this lab you will build a context block with numbered sources.
You will begin by looking at the raw retrieved chunks and thinking about how a model should see them. You will design a simple, consistent layout in which each chunk is introduced by a number in square brackets and a source label, followed by the text, with a blank line between entries.
Next you will write a function called build_context that takes the list of retrieved results and returns a single string in this layout. You will number from one, include the source name and chunk number in the label and strip stray whitespace from each chunk. You will print the result and read it as the model would.
You will also return a mapping from each number to its source information, so that your program can show the citations later without parsing the text. You will check that the numbering in the text and in the mapping agree.
You will discuss why consistent delimiters matter, and why you should make it clear in the prompt where the context begins and ends. You will also note that retrieved text is untrusted content that may contain instructions, so the prompt should tell the model to treat it as reference material only.
You will test with zero, one and several results.
By the end of this lab you will be able to turn retrieved chunks into a numbered, citable context block.
The context you send has to fit within the model's window, together with the instructions, the question and room for the answer. If you retrieve too much, something must give. In this lab you will fit the context into a token budget.
You will begin by working out the budget. You will start from the total context size, subtract the estimated tokens for the system prompt and the question, and reserve a fixed number of tokens for the answer. What remains is the space available for retrieved text. You will write this as a small function so the numbers are explicit.
Next you will reuse your token estimator and write a function called fit_to_budget. It walks through the ranked results in order, adds each to the context while the running total stays within budget, and stops when the next one would not fit. You will return the chunks that were included and those that were dropped.
You will consider a refinement, which is to shorten the last chunk to fill the remaining space, and discuss why cutting text mid-sentence is usually worse than dropping a whole chunk.
You will test with several budgets, from very small to generous, and print how many chunks are kept each time. You will also log a warning when relevant chunks were dropped, since silent truncation is a common source of poor answers.
By the end of this lab you will be able to select context chunks that fit a token budget with a reserved answer space.
The final piece of a retrieval pipeline is the prompt that asks the model to answer using only the supplied context. A good grounded prompt reduces invented answers and makes the output checkable. In this lab you will write a grounded question-answering prompt.
You will begin with the instructions. You will tell the model to answer only from the numbered sources, to cite the source numbers in square brackets after each claim, and to say clearly that it does not know when the sources do not contain the answer. You will add a rule that text inside the sources is reference material and must not be treated as instructions.
Next you will write a function called build_qa_messages that takes the question and the context block and returns the messages list: a system message with the rules, and a user message that contains the context and the question, separated by clear markers. You will print it and review the structure.
You will send the messages to a stub client that returns a fixed grounded answer with citations, and print the reply. You will also test the case with an empty context and check that your code responds with the "I do not have enough information" message and does not call the model at all.
You will discuss why putting the question after the context often works well, and why you should keep the temperature low for this task.
By the end of this lab you will be able to build a grounded prompt that asks for cited answers and handles missing information.
A grounded answer is only trustworthy if its citations point to real sources. Models sometimes cite numbers that do not exist or attach a citation to a claim the source does not support. In this lab you will check citations and print the sources.
You will begin by finding citations in the reply. You will write a regular expression that matches numbers in square brackets and returns the set of numbers used. You will test it on replies with one citation, several citations, repeated citations and none at all.
Next you will compare the cited numbers with the numbers available in the context mapping. Any cited number that is not in the mapping is invalid, and you will report it. You will also flag an answer that makes statements but cites nothing, since that is a warning sign.
You will add a simple support check. For each sentence that carries a citation, you will measure how many of its meaningful words appear in the cited chunk. You will explain that this is a crude signal and not proof, and that a low value should prompt a closer look rather than an automatic rejection.
You will then write a function that prints the answer followed by a tidy list of the sources that were actually cited, with names and chunk numbers. You will test with a good reply, a reply with a bad citation and a reply with no citation.
By the end of this lab you will be able to validate citations and present the sources behind an answer.
A language model cannot run code, but it can ask your program to run code for it. That is the idea behind tool use, and it starts with something very ordinary: a Python function. In this lab you will describe a tool as a Python function and prepare it to be called by a model.
You will begin by writing a simple function, such as get_weather_report that reads from a small dictionary of sample cities, or add_numbers that returns a sum. You will give it clear parameter names, type hints and a return value that is easy to turn into text. You will call it directly a few times to confirm it works.
Next you will discuss what makes a function a good tool. It should do one thing, have a small number of well-named parameters, return predictable results and fail with understandable errors. You will compare a good example with a poor one that takes a single vague argument called data.
You will add a docstring that explains in plain language what the function does and what each parameter means, and explain why that text matters, since the model will rely on a description built from it when deciding whether to use the tool.
You will also keep side effects in mind. You will make your first tools read-only and safe, and talk about why tools that change things need extra care and confirmation.
By the end of this lab you will be able to write a small, well-documented Python function that is suitable to expose as a tool.
Before a model can use a tool, it has to be told that the tool exists and how to call it. That description is called a tool schema, and it is just structured data. In this lab you will build a tool schema by hand.
You will begin with the parts. A schema names the tool, describes it in a sentence or two and lists its parameters. Each parameter has a name, a type, a description and a flag for whether it is required. You will write these as a Python dictionary that follows the common JSON Schema style used by many model interfaces.
Next you will write the schema for the function you built in the previous lab. You will set the type of the parameters to object, list the properties with their types, such as string and number, and add a required list. You will also try an enumeration for a parameter that accepts only certain values, such as a unit that is either celsius or fahrenheit.
You will print the dictionary as formatted JSON with json.dumps and read it as the model would. You will check that the names in the schema match the function's parameter names exactly, since a mismatch is a classic source of errors.
You will discuss why good descriptions matter. A vague one makes the model guess when to use the tool and what to send.
By the end of this lab you will be able to write a complete tool schema for a function.
Writing schemas by hand is useful for learning but tedious and error-prone, because the schema and the function can drift apart. Python can read a function's signature, so you can generate the schema from it. In this lab you will generate schemas from function signatures.
You will begin with the inspect module. You will call inspect.signature on a function and loop through its parameters, printing each name, its annotation and its default value. You will also use inspect.getdoc to retrieve the docstring.
Next you will write a mapping from Python types to JSON Schema type names, covering str, int, float, bool, list and dict. You will write a function called schema_from_function that builds the tool dictionary. The tool name comes from the function name, the description from the first line of the docstring, the properties from the annotations and the required list from the parameters that have no default.
You will test it on several functions, including one with optional parameters and one with a type that is not in your mapping, and decide how to respond to the unsupported case with a clear error rather than a silent guess.
You will compare the generated schema with your hand-written one and confirm they agree. You will discuss the benefit of having a single source of truth, since changing the function now changes the schema automatically.
By the end of this lab you will be able to generate tool schemas from type-hinted functions.
As soon as you have more than one tool, you need a place to keep them and find them by name. A registry does exactly that. In this lab you will build a tool registry.
You will begin with the simplest version, a dictionary that maps a tool name to its function. You will register a few tools by hand and look them up. You will note the problem that the schema and the function are stored separately.
Next you will write a class called ToolRegistry. It holds entries that combine the function and its generated schema. You will give it a register method and then turn that method into a decorator, so that adding the line @registry.register above a function adds it to the registry. You will explain how a decorator works in a simple way, as a function that takes a function and returns it, after doing something on the way.
You will add methods to list the available tools, return all the schemas in the form the model needs and get a tool by name. You will raise a clear error for an unknown name and refuse duplicate names so that a later registration cannot silently replace an earlier one.
You will register three or four sample tools, print the schema list and call a tool through the registry.
By the end of this lab you will be able to manage tools in a registry that keeps functions and schemas together.
When a model decides to use a tool, it does not run anything. It returns a structured message that names the tool and supplies the arguments. Your program must read that message correctly. In this lab you will read a tool call from the model.
You will begin by examining the shape of a typical tool call reply. It contains an identifier, the name of the tool and the arguments, often given as a JSON string. You will write a stub client that returns such a reply so that you can work without real calls.
Next you will write a function called parse_tool_call. It finds the tool call in the reply, extracts the name and the identifier, and decodes the arguments with json.loads. You will meet the common surprise that the arguments arrive as a string and not as a dictionary, and handle it.
You will also handle replies that contain no tool call, because the model decided to answer directly, and replies that contain several calls. You will decide on a clean return type, such as a list of ToolCall dataclass objects that may be empty.
You will test with a normal call, a call with malformed argument text, a call with no arguments and a reply with plain text only. For each, you will print what your function returns.
You will discuss why you should treat everything in the reply as untrusted input that needs checking before use.
By the end of this lab you will be able to extract tool names and arguments from a model reply safely.
The model chooses the arguments for a tool, and it can get them wrong. It might omit a required one, send a string where a number is needed or invent a parameter. Running the tool with bad arguments could crash your program or, worse, do something unintended. In this lab you will validate tool arguments.
You will begin by looking at examples of bad calls and what happens when you pass them straight to a function. You will see TypeError messages and unexpected results, and use them to explain why validation should happen first.
Next you will write a function called validate_arguments that takes the tool's schema and the parsed arguments. It checks that all required parameters are present, that no unknown ones were supplied, that each value has the expected type and that values for enumerated parameters are among the allowed options. You will reuse ideas from the validation labs in the structured output section.
You will return a list of problems, and when the list is not empty you will use it to build a short error message. You will also apply sensible limits, such as a maximum string length, and discuss why they protect your system.
You will test with a valid call, a missing parameter, a wrong type, an unknown parameter and an invalid enumeration value, and print the results.
You will also talk about the principle that validation belongs in your code and not in the prompt, since a prompt can only request good behaviour, while code can enforce it.
By the end of this lab you will be able to validate tool arguments against a schema before running anything.
Once a tool call is parsed and validated, your program needs to run the right function with the right arguments. This step is called dispatching. In this lab you will dispatch a tool call.
You will begin by writing the simplest dispatcher, which looks up the function in your registry by name and calls it with the arguments unpacked using double asterisks. You will run it with a few valid calls and print the results.
Next you will wrap this in a function called run_tool_call that takes a ToolCall object and the registry. In order, it checks that the tool exists, validates the arguments, calls the function and returns the result. You will make the return value a small structure that records the tool name, the call identifier, whether it succeeded and either the result or an error message.
You will discuss why you should never use eval or look up names from arbitrary strings in other ways. Only functions you registered deliberately may be called. You will test this with a call to a tool name that does not exist and one that tries a name such as a built-in function, and check that both are refused.
You will also time each call with time.perf_counter and record the duration, which is useful for later monitoring. You will print a short log line for each dispatch.
You will handle several calls in one reply by looping through them in order.
By the end of this lab you will be able to dispatch validated tool calls safely through a registry.
Running the tool is not the end of the exchange. The model has asked a question and is waiting for the answer, so you must send the result back in the form it expects. In this lab you will feed tool results back to the model.
You will begin by reviewing the message sequence. The conversation so far contains the user's question and the assistant's message with the tool call. You will now add a new message with the role tool, the identifier of the call it answers and the result as text. You will explain why the identifier is needed to link each result to its call.
Next you will write a function called result_to_message that turns the result of a dispatch into such a message. You will convert dictionaries and lists to JSON text with json.dumps, since the content is usually a string, and keep the output compact to save tokens. You will set a maximum length for results and truncate very long ones with a clear note that the text was shortened.
You will build the complete message list by hand for a one-tool example, print it and then send it to a stub client that returns a final answer that mentions the tool result.
You will test with a call that returns a number, one that returns a list and one that returns nothing, and make sure each becomes valid text.
You will discuss the order of messages and what happens if you leave one out.
By the end of this lab you will be able to return tool results to the model in the right message format.
Tools fail. A network may be down, an input may be invalid or a file may be missing. How your program handles failure decides whether the whole application stops or the model gets a chance to recover. In this lab you will handle tool errors gracefully.
You will begin by writing a tool that raises exceptions on purpose, such as a division by zero or a lookup of an unknown record. You will call it through your dispatcher and watch the program crash, which shows why errors must be caught at the boundary.
Next you will wrap the call in a try and except block that catches exceptions and turns them into an error result. You will catch specific exceptions first, such as ValueError and KeyError, and use a general Exception only as a last resort. You will include the exception type and a short message in the result, and keep stack traces out of what you send to the model.
You will send the error back to the model as a tool message, and use a stub client that responds sensibly, for example by correcting the argument and calling again, or by explaining the problem to the user. You will compare this with the behaviour when you hide the error.
You will discuss which details are safe to share. Messages should help the model recover without exposing file paths, secrets or internal structure.
You will also add a timeout idea, and talk about limiting how many errors are allowed before giving up.
By the end of this lab you will be able to catch tool failures and report them to the model in a safe, useful way.
You now have every part needed for tool use: schemas, a registry, parsing, validation, dispatch, result messages and error handling. In this lab you will join them into the complete tool-calling loop.
You will begin by writing the loop in plain language. Send the messages and the tool schemas to the model. If the reply contains no tool calls, you are done and return its text. If it contains tool calls, run each one, append the assistant message and the tool result messages, and send the conversation again. Repeat until the model answers or a limit is reached.
Next you will write a function called run_with_tools that implements this. You will include a maximum number of rounds, because a model can keep asking for tools forever, and decide what to return when the limit is reached. You will keep a trace of each round, listing the tool names, arguments and results.
You will test with a scripted stub client that first asks for one tool, then for a second based on the first result and finally gives an answer. You will print the trace and the final message, and check the order of the messages in the conversation.
You will also test the paths in which the model asks for an unknown tool, supplies bad arguments or reaches the round limit, and make sure each ends cleanly.
You will review the whole design and note where logging, timeouts and permissions would fit.
By the end of this lab you will be able to build and test a complete tool-calling loop with safe limits.
An agent is a program that repeatedly decides what to do next, does it and looks at the result, until the task is finished. The core of it is a loop. In this lab you will write the agent loop skeleton.
You will begin by describing the cycle in four words: observe, decide, act and repeat. You will explain how this differs from the tool-calling loop you wrote earlier, which handled one request. An agent's loop is meant to work toward a goal across several steps and may need to choose between answering and acting.
Next you will write a function called run_agent that takes a goal and a maximum number of steps. Inside a for loop it builds a prompt from the goal and what has happened so far, asks a stub model for the next move and records the move. For now it will do nothing with the move except print it.
You will define the two possible outcomes of a step, which are a request to take an action and a final answer, and make the loop stop when it sees the final one. You will also stop when the step limit is reached and return a message that says so.
You will run the skeleton with a scripted stub that takes three steps and finishes, and then with one that never finishes, and print the step numbers.
By the end of this lab you will be able to write a bounded agent loop with clear stopping conditions.
For an agent loop to work, your program must understand what the model has decided. If the reply is loose text, that is difficult. A strict, simple decision format makes it reliable. In this lab you will parse the agent's decision.
You will begin by defining the format. Each step, the model must reply with a JSON object that has a type field with the value action or final. An action also carries the name of a tool and its arguments, and a final answer carries the answer text. You will add an optional thought field that explains the choice, and say that it is for logging and not for decisions.
Next you will write parse_decision using the cleaning and validation tools from the structured output section. It removes code fences, parses the JSON, checks the type field and the keys that belong to each type and returns a Decision dataclass. You will report any problem with a precise message.
You will add a prompt snippet that explains the format to the model with one example of each type, and print the full step prompt.
You will test with valid actions, a valid final answer, a reply with an unknown type, a missing tool name and text that is not JSON. You will decide what the loop should do when parsing fails, such as asking once more with the error message.
By the end of this lab you will be able to define and parse a strict decision format for an agent.
The agent now understands each decision, so it can finally act. In this lab you will run tools inside the loop, connecting the decision parser to the registry and the dispatcher you built earlier.
You will begin by extending run_agent. When the decision is an action, the loop calls your dispatcher with the tool name and arguments, using the same validation and error handling as before. When it is a final answer, the loop returns it.
Next you will record each step. You will keep a list of step records that hold the step number, the decision, the tool result or error and the time taken. You will print them as the loop runs so that you can follow what the agent is doing, which is the most important debugging habit for agents.
You will feed the result of each action back into the next prompt, as a short observation line, such as "Observation: the tool returned 42". You will limit the length of observations so that large results do not flood the prompt.
You will use a scripted stub model that asks to look up a value, then asks to use that value in a calculation and finally gives the answer. You will run it and check that the chain of results is passed correctly.
You will also test an invalid tool name and check that the error becomes an observation the agent can react to, without crashing the loop.
By the end of this lab you will be able to execute tools from within an agent loop and record each step.
Without memory, an agent forgets what it did a moment ago and may repeat the same action again and again. The simplest memory is a scratchpad, a running record of steps and observations that is kept in the program. In this lab you will build short-term memory as a scratchpad.
You will begin by explaining the need with a failure example. A stub agent that sees only the goal asks for the same lookup in every step, because nothing tells it that the lookup was done. You will run it and watch the repetition.
Next you will write a Scratchpad class. It holds a list of entries, each with a kind such as thought, action or observation, and a text. You will give it an add method, a method to return the entries and a method to clear it. You will use a dataclass for entries so that they are easy to print and test.
You will update the agent loop to add to the scratchpad after each step and to pass it to the model on each turn. You will run the same stub again and see that, now, it can avoid the repeated action because the history is visible.
You will discuss what to store and what to leave out. Short, factual entries are better than long ones, and secrets or irrelevant details should not go in at all.
By the end of this lab you will be able to give an agent a simple scratchpad memory that is updated at every step.
Memory in your program is not useful until the model can see it. The scratchpad has to be turned into text and placed in the prompt in a clear, consistent way. In this lab you will render memory into the prompt.
You will begin by looking at the raw list of scratchpad entries and thinking about what the model needs. It needs the order of events, the difference between what it decided and what happened, and a clear sign of which entry is the latest.
Next you will write a function called render_scratchpad that converts the entries into text lines, such as "Step 1 action: search with query ...", "Step 1 observation: ...". You will use a fixed format and number the steps, so that the model can refer to them. You will print an example and read it carefully.
You will then write build_agent_prompt, which assembles the system rules, the goal, the available tools in short form, the rendered scratchpad and a final instruction that asks for the next decision in the agreed JSON format. You will print the complete prompt for a mid-run state.
You will check how the prompt grows with each step and measure its estimated token size at steps one, five and ten using your estimator.
You will discuss the order of the sections and why you should repeat the output format instruction near the end.
By the end of this lab you will be able to render agent memory into a clear, consistent prompt.
A scratchpad that grows with every step will eventually fill the context window, slow every request and raise its cost. Agents need a limit on how much they remember. In this lab you will bound memory size.
You will begin by running your agent for many steps with a stub and printing the estimated token size of the prompt after each one. You will see the steady growth and decide on a budget for the memory section.
Next you will implement the simplest strategy, which is to keep only the most recent entries. You will use collections.deque with a maximum length, or slice a list, and show that old entries disappear. You will discuss the risk, which is that the agent may lose the goal or an important early result.
You will improve it by keeping a pinned section that never gets dropped, such as the goal and any key facts, and a rolling section of recent steps. You will write the code so that the pinned part is stored separately and always rendered first.
You will then add a size limit based on estimated tokens and not on entry count, so that one long observation cannot use up the budget. You will shorten long observations and mark the cut with an ellipsis note.
You will test with a long run and confirm that the prompt size stays below the budget.
You will mention summarising older steps as a further technique.
By the end of this lab you will be able to keep agent memory within a fixed size while preserving the essentials.
Agents that decide only one step at a time can wander. For tasks with several parts, it helps to make a plan first. In this lab you will add a planning step to your agent.
You will begin by describing what a plan is in this context: a short, ordered list of steps that the agent expects to take to reach the goal. You will explain that the plan is a guide and not a promise, and that it can change as results arrive.
Next you will design the planning request. You will write a prompt that gives the goal and the list of available tools and asks for a JSON array of step descriptions, each with a short text and an optional tool name. You will parse and validate the reply with the same tools you used for decisions, and put an upper limit on the number of steps.
You will write a function called make_plan that returns a list of Step dataclass objects with an index, a description and a status, which starts as pending. You will use a stub model that returns a plan for a sample goal, such as finding two figures and comparing them, and print the plan as a numbered list.
You will store the plan in the agent's state and render it into the prompt, next to the scratchpad.
You will test with a goal that needs only one step and with an unclear goal, and decide what the planner should do in each case.
By the end of this lab you will be able to generate, parse and store a short plan before an agent starts acting.
A plan only helps if the agent follows it and keeps track of progress. Otherwise it is just text at the start of the prompt. In this lab you will follow and track the plan during the run.
You will begin by extending the Step objects with statuses such as pending, in progress, done and failed. You will write helper methods to find the next pending step, mark a step as done with a short result and mark one as failed with a reason.
Next you will update the agent loop. At each turn, it shows the model the plan with its current statuses and asks it to work on the first unfinished step. After an action succeeds, the loop marks the matching step as done. You will let the model indicate which step its action belongs to, by adding a step field to the decision format, and check that the number is valid.
You will render the plan with symbols or words for statuses, such as "[done]" and "[pending]", and print it after every turn to see the progress move forward.
You will add a rule that the agent may finish only when all steps are done or when it explains why some could not be completed. You will test this with a stub that tries to finish early and make sure the loop pushes back with a message.
You will also count the steps and compare the number of actual actions with the plan.
By the end of this lab you will be able to track plan progress through step statuses and keep the agent aligned with it.
Plans meet reality. A tool may fail, return nothing useful or reveal that an assumption was wrong. A capable agent responds by changing its plan. In this lab you will replan after a failure.
You will begin by creating a failing scenario with a stub. The plan says to look up a record and use it, but the lookup tool returns a not-found error. You will run the agent without replanning and watch it get stuck or give a poor answer.
Next you will add a replanning step. When a plan step fails, the loop marks it as failed, records the reason and asks the model for a revised plan. The new request includes the goal, the steps already finished, the failed step and its error message, and asks for the remaining steps only. You will parse the answer with make_plan and merge it with the finished steps.
You will limit the number of replans, such as two per run, to avoid endless changes, and decide what happens when the limit is reached, such as ending with an honest explanation of what could not be done.
You will run the scenario again with a stub that offers a different approach after the failure, for example searching by another field, and print the plan before and after.
You will discuss when replanning is the wrong response, for example when the error means the whole goal is impossible, or when the user must provide missing information.
By the end of this lab you will be able to detect failure and revise a plan with a bounded number of replans.
This lab brings together everything in the agent section. You will run a complete agent that has several tools, a plan, memory and limits, and watch it solve a small multi-step task from start to finish.
You will begin by assembling the parts. You will register three or four safe tools, such as a lookup of product prices from a small dictionary, a calculator that handles simple arithmetic without using eval, a function that formats a short report and a tool that returns the current date from a fixed value for repeatable output. You will print the tool schemas.
Next you will wire up the agent: the planner, the decision parser, the dispatcher, the scratchpad with bounded size and the replanning rule. You will set sensible limits for steps, replans and observation length, and keep them in a configuration object.
You will then write a scripted stub model that plays a realistic run. It plans the task, calls the lookup tool twice, uses the calculator, hits one error that causes a replan and finally produces an answer. You will run the agent and print a readable trace of each step, with its decision, observation and plan status.
You will review the trace for problems, such as wasted steps or confusing observations, and discuss what you would change.
You will end with a short checklist for agent safety, which covers limits, validation, read-only tools by default and logging.
By the end of this lab you will be able to assemble and run a complete multi-tool agent with planning, memory and safeguards.
Multimodal applications receive files, and a file's name is a poor guide to what it contains. Someone can rename a PNG image to end in .txt, or upload a document with no extension at all. A safer check looks at the first few bytes of the file, which usually carry a signature known as magic bytes. In this lab you will identify files by their magic bytes.
You will begin by creating small sample files in a temporary folder using synthetic content, including a tiny PNG, a JPEG header, a WAV header, a ZIP archive and a plain text file. You will open each in binary mode with open and the mode rb, read the first sixteen bytes and print them in hexadecimal with the bytes.hex method.
Next you will write a table that maps known signatures to file types. A PNG begins with a fixed eight-byte sequence, a JPEG with two specific bytes, a PDF with the text %PDF, a ZIP with the letters PK and a WAV file with RIFF followed by WAVE. You will write a function called detect_type that compares the start of the data with each signature and returns a label, or unknown.
You will test it on correctly named files, wrongly named files and an empty file, and print a comparison of extension against detected type.
You will discuss why DOCX files are detected as ZIP archives and how to look further inside.
By the end of this lab you will be able to detect common file types from their first bytes and spot mismatched extensions.
Before sending an image to a model, you often need to know its size, because large images cost more and may exceed limits. You do not need a heavy imaging library to find it out for a PNG. The dimensions are stored in a fixed place near the start of the file. In this lab you will read image size from a PNG header.
You will begin by looking at the structure of a PNG. It starts with an eight-byte signature, followed by chunks that each have a length, a type name, data and a checksum. The first chunk is always IHDR, and its data begins with the width and the height, each stored as a four-byte number.
Next you will use the struct module. You will learn the format string for big-endian unsigned integers and call struct.unpack on the right slice of the bytes to extract the width and height. You will write a function called png_size that opens the file, checks the signature, checks that the first chunk is IHDR and returns the pair.
You will generate a small valid PNG in code, using zlib and struct, so that you have a safe synthetic sample with a known size. You will check that the function returns the expected numbers.
You will also test error cases such as a truncated file, a non-PNG file and an empty file, and raise a ValueError with a clear message for each.
By the end of this lab you will be able to read binary headers with struct and extract image dimensions safely.
Many model interfaces accept images as text, encoded in a format called base64, usually wrapped in a data URL. Knowing how to convert a file to that form and back is a basic multimodal skill. In this lab you will encode and decode base64 and build data URLs.
You will begin with the idea. Base64 turns any bytes into a string made of letters, digits and a few symbols, which can travel safely inside JSON. You will encode a short piece of text first, using base64.b64encode, and decode it again with b64decode, remembering that both work with bytes and not strings.
Next you will encode a small synthetic image file. You will read it in binary mode, encode it, decode the result with decode ascii to get a string and print its length. You will check that the size has grown by about one third and explain why.
You will then build a data URL. It has the form data, a colon, the media type, a semicolon, the word base64, a comma and the encoded text. You will write a function called to_data_url that takes a path, detects the media type with your magic-byte function from the first lab, and returns the full string.
You will write the reverse function that parses a data URL, validates it and returns the bytes and the type, and test it with a round trip and with malformed input.
You will discuss the size limits of requests.
By the end of this lab you will be able to convert files to and from base64 data URLs.
A multimodal message does not carry a single string of text. Its content becomes a list of parts, and each part is either text or an image. In this lab you will build image content parts in a message.
You will begin by looking at the difference between the two shapes. A plain message has a content field that is a string. A multimodal one has a content field that is a list of dictionaries, each with a type, such as text or image_url, and the corresponding data. You will print both and compare them.
Next you will write helper functions called text_part and image_part. The first returns a dictionary for a piece of text. The second takes a data URL, or a web address, and returns the dictionary for an image, with an optional detail setting that tells the service how closely to look at it. You will explain that the exact field names depend on the service, and that you are using a common convention.
You will build a user message with a question and one image, then one with two images and a comparison question. You will print the messages as formatted JSON, shortening the long encoded strings so the output stays readable.
You will validate a message before sending it, checking that the list is not empty, that every part has a known type and that the total number of images stays below a limit.
You will send the message to a stub client that reports how many parts it received.
By the end of this lab you will be able to compose messages that mix text and images.
Images use tokens just like text, and the cost depends on their size and on the detail setting. Without an estimate, a request with several large images can be a surprise on the bill and may not fit within the limits. In this lab you will estimate image token cost.
You will begin with the general principle that many services divide an image into tiles, and charge a fixed amount per tile plus a base amount. You will state clearly that the exact formula varies between providers and changes over time, so the one you write is a teaching model that you should replace with the official figures for the service you use.
Next you will write a function called estimate_image_tokens that takes a width, a height and a detail setting. For low detail, it returns a small fixed number. For high detail, it first scales the image down to fit within a maximum size, then counts the tiles of a fixed pixel size and returns a base value plus a per-tile amount. You will use math.ceil to count partial tiles.
You will test with several sizes, such as a thumbnail, a photo and a very wide banner, and print the estimates in a table. You will read the sizes from your PNG helper from the earlier lab.
You will use the estimate to decide whether to downscale an image before sending it, and write a function that returns a recommended maximum size.
By the end of this lab you will be able to estimate and compare image token costs and plan for them.
Audio is a major input for AI applications, such as meeting notes, voice commands and call analysis. Before you send audio anywhere, you should check what it is. The WAV format is simple enough to read with the standard library. In this lab you will read WAV audio metadata.
You will begin by generating a short synthetic WAV file in code, using the wave module and a list of sample values for a sine wave built with math.sin. This gives you a safe test file with known properties, such as one second at sixteen thousand samples per second. You will write it with wave.open in write mode.
Next you will open the file in read mode and call methods such as getnchannels, getframerate, getsampwidth and getnframes. You will calculate the duration by dividing the number of frames by the frame rate, and print all the properties in a tidy summary.
You will write a function called wav_info that returns these values in a dictionary, and a second function that checks them against requirements, such as a maximum duration, a minimum sample rate and mono audio. You will return a list of problems in the same style as your earlier validators.
You will test it on your sample, on a file with different settings and on a file that is not a WAV, and make sure the last case produces a clear error and not a crash.
You will discuss why many speech services prefer certain sample rates.
By the end of this lab you will be able to inspect and validate WAV files using the wave module.
Speech-to-text is the step that turns audio into text a language model can work with. In this course you will not call a real transcription service. Instead you will write a stub client that has the same shape, so the pipeline you build can later use a real one. In this lab you will build a stub transcription client.
You will begin by deciding on the interface. A transcription function takes audio bytes or a path and returns a result that holds the text, the language, the duration and perhaps a list of segments with start and end times. You will define this result as a dataclass.
Next you will write a class called StubTranscriber with a transcribe method. It first checks the input using your WAV validation from the previous lab, and then returns a fixed transcript chosen by a simple rule, such as the length of the audio, so that tests are repeatable. You will make it clear in the code and comments that it does not listen to the audio.
You will add behaviour that real services show, such as rejecting files that are too long and raising an error for unsupported formats. You will also include segments with timestamps, and write a function that formats them as lines of text with the time at the start.
You will then pass the transcript into a prompt as text, as an example of combining audio and language steps.
You will test the success path and each failure path.
By the end of this lab you will be able to design a transcription interface and test audio pipelines without real services.
Many valuable documents arrive as Word files. A DOCX file looks like a single file, but it is actually a ZIP archive that holds several XML files. That makes it possible to extract its text with the standard library alone. In this lab you will extract text from DOCX files.
You will begin by creating a small synthetic DOCX in code. You will use the zipfile module to write a minimal archive with the required content types file, the relationships file and a word/document.xml file that holds a few paragraphs. You will open the result with zipfile.ZipFile and list its contents, which shows that it is just a ZIP.
Next you will read word/document.xml and parse it with xml.etree.ElementTree. You will learn about XML namespaces and use the correct one when searching. You will find each paragraph element, collect the text of the run elements inside it and join them.
You will write a function called read_docx that returns the paragraphs as a list of strings, and a second one that returns the whole text with blank lines between paragraphs. You will handle files that are not valid ZIP archives, archives without a document part and paragraphs with no text.
You will discuss what this simple approach misses, such as tables, headers, images and tracked changes, and when a dedicated library is a better choice.
You will add a size limit check before reading, to guard against very large or deliberately oversized archives.
By the end of this lab you will be able to read paragraph text from DOCX files safely using the standard library.
PDF is the most common format for documents, and also one of the most difficult to read. A real PDF may use compression, fonts and layout tricks. A very simple PDF, however, stores its text in a readable way, and working with one teaches you what text extraction involves. In this lab you will extract text from a simple PDF.
You will begin by generating a minimal synthetic PDF in code, with a header, one page and a content stream that draws a few lines of text using the Tj operator. You will write it as bytes, and print the raw content to see that the text is visible between parentheses.
Next you will write a function called read_simple_pdf. It reads the bytes, checks the signature with your magic-byte function, finds the content streams, and uses regular expressions to collect the text from the show-text operators. You will decode escape sequences such as a escaped parenthesis and a newline.
You will test it on your sample and then explain honestly why it does not work on most real-world PDFs. They commonly compress streams, use embedded fonts and split text in complicated ways, and scanned PDFs contain only images and would need optical character recognition.
You will write a clear error for these cases, such as reporting that no extractable text was found, and recommend that production systems use a maintained PDF library or an OCR service.
By the end of this lab you will be able to extract text from a simple PDF and recognise the limits of that approach.
Each file type gives you something different. A text file gives text, a DOCX gives paragraphs, a PDF gives pages, an image gives pixels and metadata. Downstream code does not want to care. In this lab you will normalise everything into document records.
You will begin by designing a common record. It holds an identifier, the source name, the detected kind, the extracted text, a list of warnings and a metadata dictionary. You will define it as a dataclass and add a method that returns a short, printable summary.
Next you will write one reader function per type that returns such a record: a plain text reader, a DOCX reader, a simple PDF reader and a WAV reader that uses your stub transcriber. For images, you will return a record with no text, a note that the content needs a vision model and the dimensions in the metadata.
You will write a dispatcher called load_document that detects the type from the first bytes, chooses the right reader, wraps errors into a warning and returns a record in every case, even when the file cannot be read. You will explain why a failed file should produce a record with a warning and not stop the whole batch.
You will run it on a folder of mixed sample files and print a table of the results.
By the end of this lab you will be able to convert varied inputs into a single, consistent record format.
This lab joins the whole section into one multimodal pipeline. You will take a folder of mixed files and turn them into a grounded answer, using the readers, the chunker, the index and the question-answering prompt you built earlier in the course.
You will begin by drawing the flow in a few lines: detect and load each file, turn the records into chunks with source metadata, index the chunks, retrieve for a question, build the context, ask the model and check the citations. You will list the module that provides each step.
Next you will write a function called ingest_folder that runs the first part and returns the index plus a report. The report counts the files by kind, the chunks created and the warnings, such as an unreadable file or an image with no text. You will print it as a short table.
You will then write answer_question, which takes the index and a question and runs retrieval, context building, the grounded prompt, the stub model and the citation check. You will return the answer, the sources and any warnings together in one result object.
You will run it with several questions, including one that is answered by a DOCX file, one by a transcript and one that cannot be answered, and print the results. You will check that the unanswerable question produces an honest refusal.
You will discuss where a real vision model and a real transcription service would replace your stubs, and how little of the rest would need to change.
By the end of this lab you will be able to assemble a complete pipeline from mixed files to a cited answer.
You cannot improve what you do not measure, and with language models the first thing to measure with is a test set. A test set is a collection of inputs together with the answers you expect. In this lab you will build a test set of prompt and expected pairs.
You will begin by choosing a small task from earlier in the course, such as classifying comments or extracting fields from notes. You will write ten to fifteen cases by hand as a list of dictionaries, each with an identifier, the input, the expected output and optional tags such as easy, edge or tricky.
Next you will discuss what makes a good test set. It should cover typical cases, awkward ones and cases where the right answer is to refuse or to say there is no information. It should be balanced, so one label does not dominate, and it should be written independently of the prompt you are testing, otherwise you may unknowingly tune to it.
You will save the cases to a JSON Lines file, one case per line, using json.dumps, and write a loader that reads them back with a check for required keys and duplicate identifiers. You will print a short summary, such as the count per tag.
You will talk about keeping a held-out portion that you do not look at while improving the prompt, and about growing the set over time by adding every real failure you meet.
By the end of this lab you will be able to create, store and load a small, well-structured evaluation set.
With a test set in hand you need a way to score each output. The simplest and most dependable method is exact match: the output either equals the expected value or it does not. In this lab you will score outputs with exact match.
You will begin by writing a function called exact_match that takes a predicted value and an expected value and returns True or False. You will test it on a few simple pairs and see that it is strict about everything, including capital letters and spaces.
Next you will write an evaluation loop. For each case in your test set it builds the prompt, calls a stub model that returns scripted outputs, scores the result and stores a record that holds the case identifier, prediction, expected answer and score. You will print each line as it runs.
You will compute the accuracy, which is the number of correct cases divided by the total, and show it as a percentage with one decimal place. You will also compute accuracy per tag, so you can see whether the model fails mainly on tricky cases.
You will look at failures by printing the cases that scored zero next to what was expected. You will notice that some failures are really formatting differences and not wrong answers, which prepares the ground for the next lab.
You will discuss when exact match is the right choice, such as labels, numbers and identifiers, and when it is too harsh, such as for free-form text.
By the end of this lab you will be able to run an evaluation loop and report accuracy overall and by tag.
Exact match is clear but unforgiving. A model that answers "Positive." when the expected label is "positive" has done nothing wrong, yet it scores zero. For many tasks you need a more forgiving score. In this lab you will score with normalisation and keywords.
You will begin by writing a normalise function that lowercases the text, strips whitespace, removes surrounding punctuation and collapses repeated spaces. You will use string methods and the re module and test it on messy inputs. You will then define normalised_match, which applies it to both sides before comparing.
Next you will add keyword scoring for answers that are longer than a label. You will write a function that takes the output and a list of required keywords and returns the fraction found, after normalisation. You will add an optional list of forbidden phrases that cause a score of zero, such as an answer that claims to know something it should not.
You will combine these into a function that returns a score between zero and one, and keep the details of how it was reached, so that a human can understand a result. You will print the scores for a set of sample outputs.
You will compare the accuracy of exact match and the forgiving score on the same outputs, and discuss the risk of making scoring so lenient that it accepts wrong answers. You will test with deliberately wrong outputs that contain the right keywords by accident.
By the end of this lab you will be able to build flexible, transparent scoring functions and understand their trade-offs.
When a task asks for structured output, correctness has two parts: the structure must be valid and the content must be right. You already built a validator in the structured output section. In this lab you will use it inside your evaluation to score structured outputs.
You will begin by defining the scoring rules. A reply earns nothing if it cannot be parsed, and nothing if it fails schema validation. If it passes, you compare each field with the expected value and give partial credit for each correct one. You will write these rules down in a short comment before coding them.
Next you will write evaluate_structured. For each case it calls the stub model, runs the output through your cleaning, parsing and validation functions and then compares fields. It returns a result with separate flags for parsed, valid and correct, and a per-field score.
You will run the evaluation on scripted outputs that include perfect replies, replies in code fences, replies missing a key, replies with a wrong type and replies with correct structure but wrong content. You will print a table with a column for each stage.
You will compute summary figures, such as the parse rate, the valid rate and the field accuracy, and explain why separating them helps you find the cause of a problem. A low parse rate points to the prompt format, while a low field accuracy points to the content.
By the end of this lab you will be able to evaluate structured outputs with separate checks for parsing, validity and correctness.
Evaluation results are most useful when you can compare them over time. If you change a prompt and the score drops, you want to know immediately. In this lab you will build evaluation reports and regression checks.
You will begin by designing a report. It records the date, a name or version for the prompt, the settings used, the overall score, the scores per tag and the list of failed case identifiers. You will build it as a dictionary and write it to a JSON file whose name includes the version.
Next you will write a function called compare_reports that loads two reports, a baseline and a new one, and prints the change in each score. It also lists the cases that passed before and fail now, called regressions, and those that failed before and pass now, called fixes. You will explain why the list of regressions is often more informative than the average.
You will then add a gate. You will define rules such as that the overall score must not fall by more than a small tolerance and that no case tagged critical may regress. You will write check_gate to return a pass or a fail with the reasons, and make the script exit with a non-zero status when it fails, using sys.exit, so that automated systems can react.
You will test with a baseline and two candidate reports, one better and one worse, and print the results.
You will discuss the importance of keeping runs repeatable, with fixed settings and seeds.
By the end of this lab you will be able to produce evaluation reports and block changes that cause regressions.
A function that answers questions is useful in a script, but most applications reach users through a service. The first step toward that is to wrap your AI function in a request handler, a function that takes a request and returns a response. In this lab you will wrap an AI function in a request handler.
You will begin by defining the request and response shapes as plain dictionaries or dataclasses. A request holds a question and optional settings. A response holds a status code, a body and optionally an error message. You will keep them independent of any web framework so that the logic can be tested without a server.
Next you will write handle_ask. It parses the request body from JSON, validates it by checking that the question exists, is a string and is not too long, calls your answering function and builds the response. You will return a status of 400 for bad input, 500 for unexpected errors and 200 for success, and explain what each means.
You will add basic safeguards, such as a maximum input size and a clear separation between user input and system instructions, so the handler does not trust what it receives. You will make sure error responses never include internal details such as stack traces.
You will add a request identifier and log a line for each call with the identifier, the status and the time taken.
You will test the handler directly with good requests, missing fields, wrong types and oversized input.
By the end of this lab you will be able to write a framework-independent request handler with validation and clean error responses.
A real service offers more than one operation. It might answer questions, report its health and describe itself. Each operation has its own address, and something must send each request to the right handler. This is called routing. In this lab you will route requests to endpoints.
You will begin with a request model that includes a method, such as GET or POST, and a path, such as slash ask or slash health. You will write the dispatch logic in its simplest form with if statements and see how it becomes untidy as endpoints are added.
Next you will build a small Router class. It keeps a dictionary that maps a pair of method and path to a handler function, and offers a route decorator so that you can register handlers with a single line above each function. You will register your ask handler, a health handler and a version handler.
You will write the dispatch method, which finds the handler, calls it and returns its response. For an unknown path it returns a 404 response, and for a known path with the wrong method it returns a 405 response with a list of the allowed methods. You will explain why these distinctions help the people who use your service.
You will also add a catch-all error handler, so that an unexpected exception in a handler becomes a safe 500 response and not a crash.
You will test the router with a set of sample requests, including unknown paths and wrong methods, and print each status.
By the end of this lab you will be able to build a small router that maps methods and paths to handlers with correct error statuses.
So far, your service has been tested only by calling functions. A real service listens on a network port and answers requests over HTTP. The standard library includes http.server, which is enough for learning and for small internal tools. In this lab you will serve the API with http.server and test it in-process.
You will begin by writing a request handler class that inherits from BaseHTTPRequestHandler. In do_GET and do_POST you will read the path, the headers and the body, using the Content-Length header to know how many bytes to read, and pass them to your router. You will then send the status, the headers and the JSON body of the response back.
Next you will create the server with HTTPServer, bound to the loopback address 127.0.0.1 and a port. You will explain why binding to the loopback address keeps the service reachable only from your own machine, which is the safe choice for a lab. You will use port zero to let the system choose a free port and read it back from the server object.
You will then test it without leaving the program. You will start the server in a background thread, send requests with urllib.request from the main thread, check the status codes and bodies, and then shut the server down cleanly with shutdown and server_close.
You will test good, bad and unknown requests, and check the response headers.
You will discuss why http.server is not meant for production, and what a proper server would add.
By the end of this lab you will be able to serve a handler over HTTP on loopback and test it automatically in one script.
A service that works on your machine is not necessarily ready to run somewhere else. Before it starts, it should check that its configuration is complete, and once it is running, other systems should be able to ask whether it is healthy. In this lab you will add deployment readiness checks and a health endpoint.
You will begin with configuration. You will read settings from environment variables with os.environ, for example the model name, the maximum input length, the index file path and a log level. You will write a Config dataclass with sensible defaults and a function that builds it, converting types and rejecting invalid values with a clear message.
Next you will write a readiness check function that runs a list of small checks and returns each result with a name, a pass or fail flag and a note. The checks look at whether the index file exists and loads, whether required settings are present and whether the evaluation gate result from the previous lab is a pass. You will explain that secrets such as keys must never be printed in these messages.
You will add two endpoints to your router. The health endpoint says that the process is running. The readiness endpoint runs the checks and returns 200 or 503. You will explain the difference between the two and why systems use both.
You will write the application so that it refuses to start when the configuration is invalid, failing fast with an understandable message.
You will test the endpoints with a good and a broken configuration.
By the end of this lab you will be able to validate configuration at startup and expose health and readiness endpoints.
This capstone lab brings together the whole course into one finished project: a grounded question-and-answer API that will only start serving when its own evaluation passes. You will assemble the pieces you built, run the checks and demonstrate the result.
You will begin with a short design review. The project has an ingestion step that chunks documents and builds an index with source metadata, a retrieval step with a score threshold, a context builder that respects a token budget, a grounded prompt with citations, a validator for the answer, a router with ask, health and readiness endpoints and an evaluation set with a regression gate.
Next you will put the code into a small package with sensible modules, and write a main script. It loads the configuration, builds or loads the index, runs the evaluation set against the pipeline with a stub model, writes a report, applies the gate and exits with an error if the gate fails. Only when it passes does the script start the server on the loopback address.
You will then exercise the running service in-process. You will send a question that your documents can answer, check that the reply includes valid citations, send one they cannot answer and check for an honest refusal, and send invalid input and check for a 400 status.
You will make the evaluation fail on purpose, for example by weakening the retrieval threshold, and confirm that the service refuses to start, which proves the gate works.
You will finish by reviewing what to change to use a real model, real embeddings and a production web server, and by listing the lessons of the course.
By the end of this lab you will be able to assemble, evaluate and run a complete grounded Q&A API with an automated quality gate.
This course contains the use of artificial intelligence.
Are you ready to move beyond using AI tools and start building your own intelligent applications? Welcome to 100 Days of AI Development with Python, a comprehensive, hands-on course designed to help you develop practical skills in Artificial Intelligence, Generative AI, Large Language Models (LLMs), Agentic AI, and Python Programming.
With 105 hands-on labs across 10 comprehensive modules, this course provides a structured learning journey that takes you from foundational AI development concepts to building, evaluating, and serving intelligent applications using Python.
Unlike traditional AI courses that focus heavily on theory, this course emphasizes hands-on learning, practical coding exercises, AI application development, and project-based learning. Every lesson introduces practical concepts that help you understand how modern AI systems work.
Begin your journey by setting up a secure Python development environment, managing virtual environments, configuring dependencies, protecting API keys, and understanding model request and response structures.
Explore Large Language Models (LLMs) and learn how to manage conversation history, system messages, token limits, context windows, streaming responses, and AI usage cost estimation. Develop essential Prompt Engineering skills using few-shot prompting, reusable prompt templates, temperature settings, and generation parameters.
Discover how to create reliable AI applications using Structured Outputs, JSON Parsing, Schema Validation, Error Handling, and Automated Retry Mechanisms. Learn techniques for improving response consistency and handling malformed AI-generated content.
Dive into AI Embeddings, Vector Search, Semantic Search, Cosine Similarity, Vector Indexing, Metadata Filtering, and Similarity Ranking. Understand how information can be represented, indexed, and retrieved efficiently within intelligent applications.
Master the fundamentals of Retrieval-Augmented Generation (RAG) by implementing document chunking, context retrieval, relevance filtering, token budgeting, grounded question answering, and source citation validation.
Take your AI development skills further with AI Agents, Agentic AI, Tool Calling, Function Calling, Tool Registries, and Intelligent Automation. Build loop-based agents capable of planning tasks, maintaining short-term memory, executing tools, tracking progress, handling failures, and completing multi-step workflows.
Explore Multimodal AI by processing images, audio recordings, PDF documents, and DOCX files. Learn about binary file processing, Base64 encoding, image token estimation, audio metadata, transcription patterns, document extraction, and unified multimodal pipelines.
Develop essential LLM Evaluation, AI Testing, AI Quality Assurance, Regression Testing, and Automated Evaluation skills. Learn how to measure response quality, validate structured outputs, identify regressions, and establish quality gates.
Finally, explore AI API Development, Python Web Services, REST API Fundamentals, Endpoint Routing, Deployment Readiness, and Health Monitoring. Bring everything together through a comprehensive capstone project combining retrieval, grounded question answering, source citations, API development, and automated evaluation.
This course is ideal for Python Developers, AI Engineers, Software Engineers, Machine Learning Engineers, Data Scientists, Backend Developers, AI Consultants, Technology Professionals, and aspiring Generative AI Developers.
The core exercises use lightweight, simulated model clients, allowing you to explore AI development patterns without requiring expensive GPUs, paid AI subscriptions, or advanced machine learning knowledge.
Whether you want to pursue a career in AI Engineering, develop AI-powered applications, explore Generative AI development, build intelligent AI agents, or strengthen your Python programming skills, this course provides a practical foundation for your journey.
Build consistently. Experiment confidently. Learn by doing.
Enroll today and begin your 100 Days of AI Development with Python journey!