Building AI Agents and Tool-Calling Workflows / Start Here

Set up Python and check readiness

Lesson 3 of 37. Open to read. No account needed.

What You Will Build

You will create the folder the whole course works in, give it its own Python environment with the four libraries the course uses, and run a readiness script that checks every part of your setup, ending with a real tool call from the model. You will also try a few short tasks that confirm the Python this course assumes. You will:

  • create ~/agents-practice with its data folder and an exercise folder;
  • create and activate the course environment, ~/agents-practice/.venv;
  • install the pinned libraries and check them;
  • run check_ready.py and explain what each check proves;
  • diagnose a failing run from the evidence it prints.

Before you start, you need the previous lesson's result: Ollama running with granite4.1:3b. You also need Python 3.12, 3.13, 3.14 or 3.15. Check in a terminal:

Model output shown in this lesson is illustrative: the author's runs with granite4.1:3b on Ollama 0.40.7, with the settings in the code shown. Your wording, ids and times can differ; the text after each output says what should match.

python3 --version

On Windows, use py --version. If you have no suitable Python, install one from python.org (on Windows, tick the option that installs the py launcher) or from your Linux distribution's packages. The course was tested with Python 3.12.7 and 3.13.0; Python 3.14 and 3.15 have not been tested yet. Allow about 45 minutes.

Step 1: Create the Practice Folder

Every exercise in the course lives under one folder in your home folder, agents-practice. Its layout grows like this:

agents-practice/
  .venv/              the course environment (Step 2)
  data/               shared practice data, created by later lessons
  readiness-check/    this lesson's exercise folder
  ...                 one folder per exercise

Exercises never share files with each other except through data, and each lesson ends by removing its own exercise folder only. The terminal commands in this step are the ones the course uses everywhere: cd to change folder, mkdir to make one, and pwd (print working directory) to see where you are.

On macOS or Linux:

cd ~
mkdir -p agents-practice/data agents-practice/readiness-check
cd agents-practice/readiness-check
pwd

On Windows (PowerShell):

cd ~
mkdir agents-practice\data, agents-practice\readiness-check
cd agents-practice\readiness-check
pwd

pwd prints the folder you are in, for example /Users/you/agents-practice/readiness-check or C:\Users\you\agents-practice\readiness-check. Now a first terminal task: open your editor, save a file in exactly this folder, run it, and find the file it writes.

Save this as write_note.py in ~/agents-practice/readiness-check:

from pathlib import Path

note = Path("note.txt")
note.write_text("The practice folder works.\n", encoding="utf-8")
print(f"Wrote {note.resolve()}")

Run it with the Python you checked above (on Windows, py instead of python3), then list the folder:

python3 write_note.py
ls

On Windows, dir lists the folder. The program prints the full path of note.txt, and the listing shows note.txt beside write_note.py. If Python says it cannot open the file, the editor saved it somewhere else: compare the folder in the editor's title or Save dialog with what pwd prints.

Step 2: Create the Course Environment

A virtual environment is a folder holding its own copy of the Python interpreter's settings and its own installed libraries. Installing into it cannot break other Python programs on your computer, and the course's library versions stay fixed even if you use other versions elsewhere. The course uses one environment for every lesson, at ~/agents-practice/.venv.

On macOS or Linux:

cd ~/agents-practice
python3 -m venv .venv
source .venv/bin/activate

On Windows:

cd ~/agents-practice
py -m venv .venv
.venv\Scripts\Activate.ps1

After activation your prompt starts with (.venv), and python now means the environment's interpreter. Activation lasts for that terminal only: every time you open a new terminal for the course, go to ~/agents-practice and activate again. To leave the environment, type deactivate.

Two problems are common here:

  • Windows refuses to run Activate.ps1, with a message that running scripts is disabled on this system. PowerShell's execution policy blocks local scripts by default. Allow scripts you create yourself, for your account only, then activate again:

    Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
    
  • Debian or Ubuntu says ensurepip is not available. The venv module is a separate package there. Install it with sudo apt install python3-venv, delete the half-made .venv folder, and create the environment again.

Step 3: Install the Pinned Libraries

With the environment active, install the four libraries at the exact versions the course was tested with:

python -m pip install httpx==0.28.1 pydantic==2.14.1 mcp==2.3.0 pytest==9.1.1
python -m pip check

The second command checks that every installed package's own requirements are met, and should print No broken requirements found.

LibraryWhat the course uses it for
httpx 0.28.1Sending HTTP requests to the model server
Pydantic 2.14.1Describing data as classes, producing JSON Schemas and validating what comes back
MCP SDK 2.3.0The Model Context Protocol lessons; it also brings about thirty supporting packages
pytest 9.1.1Testing agent code

Pinning versions (==) makes your environment match the one the lessons were tested in. Libraries change their behaviour between versions; the MCP SDK, for example, renamed and removed parts of its programming interface in version 2.0, so code written for version 1 often does not run with it. Writing python -m pip rather than pip guarantees that the active environment's Python installs the packages.

Step 4: Run the Readiness Script

Save this as check_ready.py in ~/agents-practice/readiness-check:

"""Check that this computer is ready for the course.

Run it with the course environment active, from ~/agents-practice/readiness-check:

    python check_ready.py

Each check prints PASS or FAIL with the value it found, then why the check
matters. The last check asks the model one question with a tool attached and
passes if the model replies with a tool call.
"""
import importlib.metadata
import json
import os
import platform
import sys
from pathlib import Path

PRACTICE = Path.home() / "agents-practice"
PINS = {"httpx": "0.28.1", "pydantic": "2.14.1", "mcp": "2.3.0", "pytest": "9.1.1"}
MODEL = "granite4.1:3b"
TESTED_OLLAMA = "0.40.7"
HOST = os.environ.get("OLLAMA_HOST", "127.0.0.1:11434")
BASE = HOST if HOST.startswith("http") else f"http://{HOST}"
OPENING_HOURS_TOOL = {
    "type": "function",
    "function": {
        "name": "get_opening_hours",
        "description": "Get the rental desk's opening hours for one day of the week.",
        "parameters": {
            "type": "object",
            "properties": {"day": {"type": "string", "enum": ["monday", "tuesday", "wednesday", "thursday",
                                                                "friday", "saturday", "sunday"]}},
            "required": ["day"],
        },
    },
}
failed = []


def report(ok, name, found, why):
    if not ok:
        failed.append(name)
    print(f"{'PASS' if ok else 'FAIL'}  {name}: {found}")
    print(f"      {why}")


def check_python():
    venv = (PRACTICE / ".venv").resolve()
    report(Path(sys.prefix).resolve() == venv, "interpreter", sys.executable,
           f"Scripts must run with the course environment in {venv}, so the pinned libraries are used.")
    report((3, 12) <= sys.version_info[:2] <= (3, 15), "Python version", platform.python_version(),
           "The course supports Python 3.12 to 3.15.")
    report((PRACTICE / "data").is_dir(), "practice folder", f"{PRACTICE} with data: {(PRACTICE / 'data').is_dir()}",
           "Later lessons keep the shared practice database and documents in the data folder.")
    for name, pin in PINS.items():
        try:
            version = importlib.metadata.version(name)
        except importlib.metadata.PackageNotFoundError:
            version = "not installed"
        report(version == pin, f"library {name}", version, f"The lessons were tested with {name} {pin}.")


def check_ollama():
    import httpx

    try:
        version = httpx.get(f"{BASE}/api/version", timeout=10).json()["version"]
    except httpx.HTTPError as error:
        report(False, "Ollama server", f"no answer at {BASE} ({type(error).__name__})",
               "Start Ollama; every lesson sends its requests to this address.")
        return
    note = "" if version == TESTED_OLLAMA else f" (the course was tested with {TESTED_OLLAMA})"
    report(True, "Ollama server", f"version {version} at {BASE}{note}", "The server answers requests.")
    host = httpx.URL(BASE).host
    report(host in ("127.0.0.1", "localhost"), "server address", host,
           "The course keeps the server on your own computer; no other machine should reach it.")

    response = httpx.post(f"{BASE}/api/show", json={"model": MODEL}, timeout=30)
    if response.status_code == 404:
        report(False, "model", f"{MODEL} not found", f"Pull it with: ollama pull {MODEL}")
        return
    response.raise_for_status()
    capabilities = response.json().get("capabilities", [])
    report("tools" in capabilities, "model", f"{MODEL}, capabilities: {', '.join(capabilities)}",
           "The course model must be present and able to call tools.")

    response = httpx.post(f"{BASE}/api/chat", timeout=httpx.Timeout(10.0, read=300.0), json={
        "model": MODEL, "stream": False, "options": {"temperature": 0, "num_ctx": 8192},
        "messages": [{"role": "user", "content": "When does the rental desk open on Saturday?"}],
        "tools": [OPENING_HOURS_TOOL]})
    response.raise_for_status()
    data = response.json()
    calls = data["message"].get("tool_calls") or []
    found = ", ".join(f"{c['function']['name']}({json.dumps(c['function']['arguments'])})" for c in calls)
    seconds = data["total_duration"] / 1e9
    report(bool(calls), "tool call", f"{found or 'no tool call'} in {seconds:.1f} s",
           "The model can ask for a tool, which every agent in the course depends on.")


def main():
    print(f"Readiness check for {MODEL} on {platform.system()} {platform.machine()}\n")
    check_python()
    try:
        check_ollama()
    except ImportError:
        report(False, "Ollama checks", "skipped: httpx is not available to this interpreter",
               "Activate the course environment, or install the libraries in it, and run again.")
    print()
    if failed:
        print(f"NOT READY: {len(failed)} check(s) failed: {', '.join(failed)}")
        sys.exit(1)
    print("READY: every check passed.")


if __name__ == "__main__":
    main()

How the Script Works

  • report() prints one result: PASS or FAIL, the value found, and on the next line why the check matters. It also records failed checks for the summary at the end.
  • check_python(). The interpreter check compares sys.prefix, the environment the running Python belongs to, with ~/agents-practice/.venv. It is the most useful single check, because almost every other library problem comes from running the right script with the wrong Python. Then come the Python version, the data folder, and each library's installed version, read with importlib.metadata without importing the library.
  • check_ollama() imports httpx only inside the function, so the script still runs, and reports clearly, when httpx is missing. It asks /api/version whether a server answers, checks that the address is your own computer, and asks /api/show whether granite4.1:3b is present with the tools capability. A 404 there means the model is not pulled.
  • The tool call. The last check sends a real chat request with one tool, get_opening_hours, and the question "When does the rental desk open on Saturday?". The model cannot know the opening hours, so a working setup replies with a tool call rather than text. The tool is never run: this check only proves that the request reaches the model and a tool call comes back. The read timeout is long (300 seconds) because the first request after the model has been unloaded must wait for it to load.
  • main() runs the Ollama checks only if httpx can be imported, prints a summary and exits with status 1 when anything failed, so other programs can tell success from failure.

Run it from the readiness-check folder, with the environment active:

cd ~/agents-practice/readiness-check
python check_ready.py

This was the output on the author's computer. Your paths, timing and platform line will differ; every line should say PASS:

Readiness check for granite4.1:3b on Darwin arm64

PASS  interpreter: /Users/you/agents-practice/.venv/bin/python
      Scripts must run with the course environment in /Users/you/agents-practice/.venv, so the pinned libraries are used.
PASS  Python version: 3.13.0
      The course supports Python 3.12 to 3.15.
PASS  practice folder: /Users/you/agents-practice with data: True
      Later lessons keep the shared practice database and documents in the data folder.
PASS  library httpx: 0.28.1
      The lessons were tested with httpx 0.28.1.
PASS  library pydantic: 2.14.1
      The lessons were tested with pydantic 2.14.1.
PASS  library mcp: 2.3.0
      The lessons were tested with mcp 2.3.0.
PASS  library pytest: 9.1.1
      The lessons were tested with pytest 9.1.1.
PASS  Ollama server: version 0.40.7 at http://127.0.0.1:11434
      The server answers requests.
PASS  server address: 127.0.0.1
      The course keeps the server on your own computer; no other machine should reach it.
PASS  model: granite4.1:3b, capabilities: completion, tools
      The course model must be present and able to call tools.
PASS  tool call: get_opening_hours({"day": "saturday"}) in 3.7 s
      The model can ask for a tool, which every agent in the course depends on.

READY: every check passed.

Notice what the last line proves and what it does not. The model chose the right tool and filled in "day": "saturday" from the question, so tool calling works end to end. It does not prove the model will choose well on harder questions; measuring that is a later module's job. If your Ollama version differs from 0.40.7, the server line says so; that is a note, not a failure.

Step 5: Check the Python This Course Assumes

The course does not teach Python itself. These four short tasks confirm the Python it relies on. Save each file in the readiness-check folder, and write down your prediction before running it.

A function over a list of dictionaries. Save this as total_units.py:

def total_units(bookings):
    return sum(booking["units"] for booking in bookings)


bookings = [{"item_id": "tent-2p", "units": 2}, {"item_id": "headlamp", "units": 3},
            {"item_id": "stove-1b", "units": 1}, {"item_id": "mat-air", "units": 1}]
print(total_units(bookings))

Predict the printed number, then run python total_units.py.

Reading a traceback. Save this as broken.py:

bookings = [{"item_id": "tent-2p", "units": 2}, {"item_id": "headlamp", "units": 3}]
total = 0
for booking in bookings:
    total += booking["unit"]
print(total)

Run it. It fails. Read the last line of the error first, find the line it points to, and fix the script so it prints the total.

Exceptions. Save this as handlers.py:

def units_per_day(units, days):
    try:
        result = int(units) / days
    except ValueError:
        return "not a number"
    except ZeroDivisionError:
        return "no days"
    else:
        return result


print(units_per_day("6", 3))
print(units_per_day("six", 3))
print(units_per_day("6", 0))

Predict the three printed lines, then run it.

Nested JSON. Save this as lookups.py:

import json

reply = json.loads("""
{"message": {"role": "assistant",
             "tool_calls": [{"function": {"name": "check_availability",
                                          "arguments": {"item_id": "tent-2p", "start": "2026-11-14"}}}]},
 "done": true, "eval_count": 31}
""")
print(reply["done"])
print(reply["message"]["tool_calls"][0]["function"]["name"])
print(reply["message"]["tool_calls"][0]["function"]["arguments"]["start"])

Predict the three printed lines, then run it. The answers are at the end of the lesson. If two or more of your predictions were wrong, or the traceback puzzled you, spend some time on Python basics before continuing: the course uses these patterns in every lesson without explaining them again.

When the Result Differs

OutputCauseNext step
FAIL interpreter, with a path outside .venvThe environment is not active, or another Python ran the scriptActivate the environment and run python check_ready.py again
FAIL library ...: not installedLibraries were installed into a different PythonActivate the environment, then repeat Step 3
FAIL library ...: 2.x (another version)An unpinned install or a later upgradepython -m pip install with the pinned version
FAIL Ollama server: no answer ... (ConnectError)Ollama is not running, or OLLAMA_HOST points elsewhereStart Ollama; check OLLAMA_HOST (previous lesson)
FAIL model: granite4.1:3b not foundThe model is not on this serverollama pull granite4.1:3b
FAIL tool call: no tool callThe model answered in text insteadRun again; if it repeats, check ollama show granite4.1:3b lists tools
httpx.ReadTimeoutThe model took more than 300 seconds to load and answerCheck ollama ps; close other heavy programs and run again
running scripts is disabled on this systemPowerShell's execution policy (Windows)Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser

Your Turn: Fix a Failing Run

A learner ran the readiness script and got this (shortened; recorded on the author's computer by running the script with Homebrew's Python instead of the course environment):

FAIL  interpreter: /opt/homebrew/opt/python@3.13/bin/python3.13
      Scripts must run with the course environment in /Users/you/agents-practice/.venv, so the pinned libraries are used.
PASS  Python version: 3.13.0
      The course supports Python 3.12 to 3.15.
PASS  practice folder: /Users/you/agents-practice with data: True
      Later lessons keep the shared practice database and documents in the data folder.
FAIL  library httpx: not installed
      The lessons were tested with httpx 0.28.1.
FAIL  library pydantic: not installed
      The lessons were tested with pydantic 2.14.1.
FAIL  library mcp: not installed
      The lessons were tested with mcp 2.3.0.
FAIL  library pytest: not installed
      The lessons were tested with pytest 9.1.1.
FAIL  Ollama checks: skipped: httpx is not available to this interpreter
      Activate the course environment, or install the libraries in it, and run again.

NOT READY: 6 check(s) failed: interpreter, library httpx, library pydantic, library mcp, library pytest, Ollama checks

Their first idea is to run pip install httpx pydantic mcp pytest in the same terminal. Decide what actually went wrong, using the evidence in the output, and give the commands that fix it. Success means your fix makes all eleven checks pass without installing anything outside the course environment.

Clean Up

Remove the exercise folder, and only that folder. The commands check where they are before deleting anything. Keep .venv and data: every later lesson uses them.

On macOS or Linux:

cd ~/agents-practice
[ "$(pwd)" = "$HOME/agents-practice" ] && rm -r readiness-check

On Windows:

cd ~/agents-practice
if ((Get-Location).Path -eq (Join-Path $HOME 'agents-practice')) { Remove-Item -Recurse readiness-check }

The readiness script is short and you can save it again whenever something seems wrong; it is the quickest way to check your setup at the start of a later session.

Check Your Understanding

  1. Output A shows every check passing except FAIL model: granite4.1:3b not found. Output B shows the first seven checks passing and then FAIL Ollama server: no answer at http://127.0.0.1:11434 (ConnectError). For each, which part of the setup is broken, and what is the next safe step?
  2. The readiness script passes. A week later, in a new terminal, a lesson's script fails with ModuleNotFoundError: No module named 'httpx'. What is the most likely cause?

Answer and Reasoning

Your turn

The evidence points at the interpreter, not at missing libraries: the first line shows the script was run by /opt/homebrew/.../python3.13, not by ~/agents-practice/.venv. The libraries are installed in the course environment; this Python simply cannot see them. Running pip install in that terminal would install them into Homebrew's Python instead, leaving two copies at possibly different versions, and the next script would still run with the wrong one. Activate the environment and run the same script again:

cd ~/agents-practice
source .venv/bin/activate
cd readiness-check
python check_ready.py

On Windows, activate with .venv\Scripts\Activate.ps1. In the author's test, the same script passed all eleven checks straight after activation.

Python tasks

  • total_units.py prints 7: 2 + 3 + 1 + 1.
  • broken.py ends with KeyError: 'unit'. The last line names the problem: a dictionary has no key unit. The line above it points to total += booking["unit"]; the key is units. With that fixed, it prints 5.
  • handlers.py prints 2.0, then not a number, then no days. int("6") works and 6 / 3 is 2.0 (division always gives a float), so the else branch returns it; int("six") raises ValueError; 6 / 0 raises ZeroDivisionError.
  • lookups.py prints True (JSON's true becomes Python's True), check_availability and 2026-11-14. The second and third lookups pass through a list, so they need [0] before going deeper.

Check your understanding

  1. A: the server answers, but the model is not on it. Pull it with ollama pull granite4.1:3b and run the script again. B: the Python side is fine and no server answers at the address. Start Ollama (or check that OLLAMA_HOST is unset), confirm with ollama ps, then rerun. In both cases the safe step changes one thing and reruns the check, rather than reinstalling everything.
  2. The environment is not active in the new terminal. Activation lasts for one terminal only, so the script ran with a Python that has no httpx. Go to ~/agents-practice and activate the environment before running course scripts.

References

32 more lessons in the full course

Course access opens every lesson and adds revision notes, the Quick Reference, saved progress, bookmarks and your own notes.

INR 199 plus 18% GST. 90 days of online access. No auto-renewal.

Get the full course

This website is operated by VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED, operating as Vectametric.

Corporate Identity Number (CIN): U85499KA2026OPC229822. GSTIN: 29AAMCV8281D1ZS. Registered office: RS NO/38/2A/1 BASTAND, ROAD MAHANTESH NAGAR, Ramdurg, Ramdurg, Belgaum- 591123, Karnataka.

Queries and grievances: Prajval Honnungar, Grievance Officer and Data Protection Contact.

Telephone: +91 94800 09310. Support: support@vectametric.com. Grievances: support@vectametric.com.

Copyright 2026 VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED. All rights reserved.

Vectametric home · Roadmaps · Vecta IT Exams · Vecta Government Exams · Vecta Banking & Finance Exams · Vecta Entrance Exams · About us · Contact · Privacy Policy · Terms and Conditions · No-Refund Policy