Building AI Agents with Open Source Models
Open Source Track ยท Setup
โฑ 30โ€“40 min ๐Ÿฆ™ Ollama + Mistral-7B
๐Ÿฆ™
Open Source Track โ€” Dev Environment Setup Complete this before starting any hands-on lab. You only need to do this once. After this, every module's code will run with python filename.py โ€” no extra config required. ยท OS Track Index โ†’

Dev Environment Setup

Before you write your first agent, you need four things working: Python, a code editor, a virtual environment, and Ollama running locally. This module walks you through all four โ€” step by step, with checkpoints.

โœ… What You'll Have at the End
  • Python 3.11+ installed and accessible from the terminal
  • VS Code or PyCharm configured with the right extensions and interpreter
  • A project folder with a virtual environment and the openai package installed
  • Ollama running locally with Mistral-7B pulled and ready
  • A working test script that calls Mistral-7B and prints a response
๐Ÿ’ก Why a Virtual Environment?

Imagine every Python project on your machine uses the same toolbox. Project A needs openai==1.2; Project B needs openai==0.28. Both can't be installed at the same time โ€” they conflict. A virtual environment gives each project its own isolated toolbox, invisible to every other project. Before virtual environments existed, Python developers had to manually uninstall and reinstall packages every time they switched projects โ€” hours of pain per week. Now you just source venv/bin/activate and your isolated toolbox snaps into place.

๐Ÿ“ Concepts in This Module

Virtual environment โ€” an isolated copy of Python with its own installed packages. Lives inside your project folder. Activating it makes python and pip point to that isolated copy instead of your system Python.

Ollama โ€” a local inference server. Think of it as Docker for LLMs: you pull a model once (ollama pull mistral), and Ollama runs it as a local HTTP server on port 11434. Your Python code calls http://localhost:11434/v1 using the standard OpenAI SDK โ€” no API key, no internet required after the initial download.

1 ยท Install Python 3.11+

All code in this course requires Python 3.11 or later. Python 3.12 is recommended โ€” it has better error messages and faster startup.

Download the installer from python.org/downloads. On the first screen, check "Add Python to PATH" before clicking Install โ€” this is the most common mistake beginners make. Without it, python won't be recognized in PowerShell.

PowerShell โ€” verify installation
python --version       # Should print: Python 3.11.x or 3.12.x
python -m pip --version  # Should print: pip 24.x from ...
โš ๏ธ Common Issue

If python opens the Microsoft Store instead of running Python, go to Settings โ†’ Apps โ†’ App execution aliases and disable the Python aliases. Then re-run the installer.

The recommended method is Homebrew. Homebrew is a package manager for macOS that keeps Python up to date easily. If you don't have Homebrew, install it first from brew.sh.

Terminal
# Install Python 3.12
brew install python@3.12

# Verify (may need to restart terminal first)
python3 --version     # Python 3.12.x
python3 -m pip --version

On macOS, use python3 and pip3 instead of python and pip to avoid using the system Python 2.7.

Most Linux distributions ship with Python 3. Check what version you have, and upgrade if needed using your package manager.

Terminal (Ubuntu/Debian)
python3 --version     # Check current version

# Install 3.12 if needed
sudo apt update && sudo apt install python3.12 python3.12-venv python3-pip

# Verify
python3.12 --version
โœ…
Checkpoint 1 โ€” Python installedRunning python --version (Windows) or python3 --version (Mac/Linux) prints Python 3.11.x or higher. If not, re-run the installer and ensure "Add to PATH" is checked.

2 ยท Choose Your IDE

For this course you'll use either VS Code or PyCharm Community (both free). Both work equally well โ€” pick the one you prefer or already have installed.

๐Ÿ”ท VS Code Recommended

  • Lightweight, fast startup
  • Excellent Python extension
  • Built-in terminal panel
  • Great Jupyter notebook support
  • Works well for all 12 modules

Best for: beginners, lightweight usage, all OS

๐ŸŸฆ PyCharm Community

  • Deeper Python intelligence
  • Built-in venv management
  • Excellent debugger
  • Heavier on RAM (~400MB)
  • More setup steps initially

Best for: Python-first learners, heavy debugging

The next two sections cover setup for each. Skip the one you're not using.

3 ยท VS Code Setup

Install VS Code

Download from code.visualstudio.com and install it. Run the installer with default settings. On Windows, check "Add to PATH" and "Register as default editor" during install.

Install the Python Extension

Open VS Code. Press Ctrl+Shift+X (Windows/Linux) or Cmd+Shift+X (Mac) to open Extensions. Search for "Python" and install the extension published by Microsoft (it's the first result, 100M+ downloads). This extension adds syntax highlighting, autocomplete, linting, and the ability to select a Python interpreter.

Open Your Project Folder

Go to File โ†’ Open Folder and select (or create) your project folder, e.g. ai-agents-course. VS Code will remember this folder as your workspace.

Terminal โ€” create project folder
mkdir ai-agents-course
cd ai-agents-course

Select Python Interpreter (after creating venv in Step 5)

After creating your virtual environment (next section), press Ctrl+Shift+P and type "Python: Select Interpreter". Choose the one that shows your venv folder path (e.g., ./venv/bin/python). VS Code will use this for running and linting.

๐Ÿ’ก Useful VS Code Settings for This Course

Open Settings (Ctrl+,) and set these:

  • Editor: Format On Save โ†’ enabled (auto-formats Python code)
  • Python โ€บ Linting: Enabled โ†’ enabled (catches bugs as you type)
  • Terminal โ€บ Integrated: Default Profile โ†’ PowerShell (Windows) or bash (Mac/Linux)

4 ยท PyCharm Setup

Install PyCharm Community Edition

Download from jetbrains.com/pycharm/download. Choose Community Edition (it's free โ€” don't accidentally download Professional). Install with default settings.

Create a New Project

On the Welcome screen, click New Project. Set the location to your project folder (e.g., ai-agents-course). Under Python Interpreter, select New environment using Virtualenv. PyCharm will create the virtual environment automatically โ€” you can skip Section 5 for the venv creation step, though you'll still need to install packages manually.

Configure the Terminal

Go to Settings โ†’ Tools โ†’ Terminal. On Windows, set Shell path to powershell.exe. On Mac/Linux it defaults to bash. PyCharm's integrated terminal automatically activates the project's virtual environment when you open it.

Install Packages via Terminal

Open the Terminal panel at the bottom (Alt+F12). You should see (venv) at the start of the prompt โ€” this confirms the virtual environment is active. Then follow Section 6 to install dependencies.

5 ยท Create a Virtual Environment

(Skip this if you used PyCharm's built-in venv creation in Step 2 above.)

Run these commands in your project folder. The venv folder created is about 20MB and contains an isolated Python installation.

Click each box to see what's inside
System Python

Your global Python install. Shared by ALL projects. Version: whatever came with your OS or you installed globally.

venv/ (project-local)

Isolated copy. Only this project sees these packages. Activate it and python points here instead of the system.

System Packages

Packages installed globally. Shared, can conflict. Never pip install into system Python for a project.

Project Packages

openai, chromadb, etc. Only visible when venv is active. Fully version-controlled via requirements.txt.

PowerShell
# Navigate to your project folder first
cd ai-agents-course

# Create the virtual environment
python -m venv venv

# Activate it (you must do this every new terminal session)
.\venv\Scripts\Activate.ps1

# Verify โ€” prompt should show (venv)
python --version
โš ๏ธ If you see "cannot be loaded because running scripts is disabled"

Run this once to fix it: Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser. This allows running local scripts (like the venv activate script) while keeping remote scripts restricted.

Terminal
# Navigate to your project folder first
cd ai-agents-course

# Create the virtual environment
python3 -m venv venv

# Activate it
source venv/bin/activate

# Verify โ€” prompt should show (venv)
python --version   # Note: just "python" now works (not python3)
โœ…
Checkpoint 2 โ€” venv activeYour terminal prompt starts with (venv). Running python --version shows your installed Python version. You should be inside your project folder. If the (venv) prefix disappears, re-run the activate command.

6 ยท Install Dependencies

With your virtual environment active, install the packages needed for this course. The openai package is the primary SDK โ€” it connects to Ollama, Groq, Together AI, and any other OpenAI-compatible server.

Terminal (venv must be active)
# Core package โ€” works with Ollama, Groq, Together AI
pip install openai

# For RAG modules (M09): local embeddings + vector store
pip install sentence-transformers chromadb

# For environment variable management (recommended)
pip install python-dotenv

# Verify everything installed
pip list | grep -E "openai|sentence|chroma|dotenv"

Expected output from pip list:

Expected output
chromadb          0.5.x
openai            1.x.x
python-dotenv     1.x.x
sentence-transformers  3.x.x

Save your dependencies

Run this after installing to create a requirements.txt โ€” anyone else can reproduce your environment exactly with pip install -r requirements.txt.

Terminal
pip freeze > requirements.txt
โœ…
Checkpoint 3 โ€” packages installedRunning python -c "import openai; print(openai.__version__)" prints a version number (e.g., 1.40.0). If you get ModuleNotFoundError, make sure your venv is active (check for the (venv) prefix) and re-run pip install openai.

7 ยท Install Ollama & Pull Mistral-7B

Ollama is the local inference server. Once installed it runs as a background service, exposing a REST API on http://localhost:11434. The Python openai SDK talks to this same URL โ€” Ollama speaks the OpenAI Chat Completions protocol.

Terminal โ€” Ollama Setup
$ curl -fsSL https://ollama.ai/install.sh | sh
>>> Downloading ollama...
>>> Installing ollama to /usr/local/bin
โœ“ ollama installed successfully
$ ollama pull mistral
pulling manifest
pulling 8034d0c26297... 100% โ–•โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ– 4.1 GB
โœ“ success โ€” model pulled: mistral (4.1 GB, 4-bit quantized)
$ ollama serve
โœ“ Listening on http://127.0.0.1:11434 (press Ctrl+C to stop)
$

Download and run the installer from ollama.ai. It installs Ollama as a Windows service that starts automatically. After installation, open PowerShell and run:

PowerShell
# Pull Mistral-7B (4.1 GB download โ€” do this on Wi-Fi)
ollama pull mistral

# Verify the model is available
ollama list

# Test a quick response
ollama run mistral "Say hello in one sentence."

On Windows, Ollama runs as a background service automatically. You don't need to run ollama serve manually โ€” it's already listening on port 11434.

Terminal
# Install via Homebrew (recommended)
brew install ollama

# OR download the macOS app from ollama.ai

# Start the server (runs in background)
ollama serve &

# Pull Mistral-7B
ollama pull mistral

# Verify
ollama list
Terminal
# Install with the official script
curl -fsSL https://ollama.ai/install.sh | sh

# Start the server
ollama serve &

# Pull Mistral-7B (CUDA GPU detected automatically if available)
ollama pull mistral

# Verify
ollama list
curl http://localhost:11434/api/tags   # Should return JSON with model info
๐Ÿ“ Hardware Requirements

Mistral-7B (4-bit quantized) โ€” 5 GB RAM minimum. Runs on CPU if no GPU available (slower, ~3โ€“8 tokens/sec). With a GPU it runs at 20โ€“50 tokens/sec.

No GPU? No problem. For this course, CPU inference is fine for learning. If you want faster responses, sign up for a free Groq API key at console.groq.com and swap base_url to https://api.groq.com/openai/v1 โ€” same code, 10x faster.

Want to try other models? After pulling Mistral, you can pull llama3 (8B), phi3 (3.8B, lower RAM), or mixtral (47B, needs 32GB RAM). Change the model="mistral" parameter in any code example to switch.

โœ…
Checkpoint 4 โ€” Ollama runningRunning curl http://localhost:11434/api/tags (or in Python: import urllib.request; print(urllib.request.urlopen("http://localhost:11434/api/tags").read())) returns JSON that includes "mistral" in the model list. If you get "connection refused", run ollama serve first.

8 ยท Verify Everything Works

Create a new file called hello_mistral.py in your project folder and paste the code below. This is your "all systems go" test.

hello_mistral.py
"""
hello_mistral.py โ€” verify your dev environment is working
Run: python hello_mistral.py
Expected: a one-sentence response from Mistral-7B running locally
"""
from openai import OpenAI

# Connect to Ollama running on localhost
# api_key="ollama" is a placeholder โ€” Ollama doesn't need a real key
client = OpenAI(
    base_url="http://localhost:11434/v1",
    api_key="ollama"
)

print("Connecting to local Mistral-7B via Ollama...")
print("-" * 50)

try:
    response = client.chat.completions.create(
        model="mistral",
        messages=[
            {"role": "system", "content": "You are a helpful assistant. Be concise."},
            {"role": "user", "content": "In exactly one sentence, what is a large language model?"}
        ]
    )
    text = response.choices[0].message.content
    print(f"Mistral says: {text}")
    print("-" * 50)
    print(f"Tokens used โ€” input: {response.usage.prompt_tokens}, output: {response.usage.completion_tokens}")
    print("\nโœ… Setup complete! Your environment is ready for all 12 modules.")

except Exception as e:
    print(f"โŒ Error: {e}")
    print("\nTroubleshooting:")
    print("  1. Is Ollama running? Run: ollama serve")
    print("  2. Is mistral pulled? Run: ollama pull mistral")
    print("  3. Is openai installed? Run: pip install openai")
    print("  4. Is venv active? Check for (venv) in your prompt")
Terminal โ€” run it
python hello_mistral.py
โœ… Expected Output
Connecting to local Mistral-7B via Ollama...
--------------------------------------------------
Mistral says: A large language model is a type of AI trained on massive text datasets to understand and generate human-like language.
--------------------------------------------------
Tokens used โ€” input: 38, output: 24

โœ… Setup complete! Your environment is ready for all 12 modules.
โš ๏ธ Common Errors & Fixes

ConnectionRefusedError / Connection refused โ€” Ollama isn't running. Start it with ollama serve (Mac/Linux) or open the Ollama app (Windows).

ModuleNotFoundError: No module named 'openai' โ€” Your venv isn't active. Run the activate command for your OS (see Section 5) and then pip install openai.

model "mistral" not found โ€” You haven't pulled the model yet. Run ollama pull mistral (this is a one-time 4 GB download).

Very slow response (>30 seconds) โ€” Normal on CPU without a GPU. The first inference is slower as the model loads into RAM. Subsequent calls are faster. Consider using Groq for speed (see Section 7 hardware note).

9 ยท Recommended Project Structure

Organize your work like this from the start. Each module gets its own folder inside labs/. This keeps your files tidy and makes it easy to compare your solution to the reference code.

ai-agents-course/ โ”œโ”€โ”€ venv/ # virtual environment โ€” never edit manually โ”œโ”€โ”€ labs/ โ”‚ โ”œโ”€โ”€ m01-llm-mental-model/ โ”‚ โ”‚ โ”œโ”€โ”€ hello_mistral.py # your first script (already done!) โ”‚ โ”‚ โ””โ”€โ”€ multi_turn_chat.py โ”‚ โ”œโ”€โ”€ m03-prompts/ โ”‚ โ”‚ โ”œโ”€โ”€ zero_shot.py โ”‚ โ”‚ โ””โ”€โ”€ chain_of_thought.py โ”‚ โ”œโ”€โ”€ m05-function-calling/ โ”‚ โ”‚ โ”œโ”€โ”€ weather_tool.py โ”‚ โ”‚ โ””โ”€โ”€ multi_tool.py โ”‚ โ”œโ”€โ”€ m09-rag/ โ”‚ โ”‚ โ”œโ”€โ”€ rag_pipeline.py โ”‚ โ”‚ โ””โ”€โ”€ docs/ # put your documents here โ”‚ โ””โ”€โ”€ ... (one folder per module) โ”œโ”€โ”€ .env # API keys โ€” NEVER commit this file โ”œโ”€โ”€ .gitignore # add venv/ and .env here โ””โ”€โ”€ requirements.txt # pip freeze > requirements.txt

Create the folder structure now

PowerShell
New-Item -ItemType Directory -Force labs/m01-llm-mental-model,labs/m03-prompts,labs/m05-function-calling,labs/m08-conversation,labs/m09-rag,labs/m12-react,labs/m13-planning,labs/m14-multi-agent,labs/m16-guardrails-in,labs/m17-guardrails-out

# Create .gitignore
@"
venv/
.env
__pycache__/
*.pyc
.DS_Store
"@ | Out-File -Encoding utf8 .gitignore

# Create .env template
@"
# Groq (optional โ€” free tier at console.groq.com, faster than local Ollama)
# GROQ_API_KEY=your_key_here

# Together AI (optional)
# TOGETHER_API_KEY=your_key_here
"@ | Out-File -Encoding utf8 .env
Terminal
mkdir -p labs/{m01-llm-mental-model,m03-prompts,m05-function-calling,m08-conversation,m09-rag,m12-react,m13-planning,m14-multi-agent,m16-guardrails-in,m17-guardrails-out}

# Create .gitignore
cat > .gitignore << 'EOF'
venv/
.env
__pycache__/
*.pyc
.DS_Store
EOF

# Create .env template
cat > .env << 'EOF'
# Groq (optional โ€” free tier at console.groq.com)
# GROQ_API_KEY=your_key_here
EOF
๐Ÿ’ก Using Groq Instead of Ollama

If your machine doesn't have enough RAM for Mistral-7B, or you want faster responses, Groq is a free alternative. Sign up at console.groq.com, get a free API key, then change two lines in any code example:

# Change this:
client = OpenAI(base_url="http://localhost:11434/v1", api_key="ollama")

# To this (Groq, same API format):
import os
client = OpenAI(base_url="https://api.groq.com/openai/v1", api_key=os.getenv("GROQ_API_KEY"))
# model: use "llama-3.1-8b-instant" or "mixtral-8x7b-32768" on Groq

Everything else โ€” tool calling, multi-turn history, system prompts โ€” works identically. That's the power of the OpenAI-compatible API standard.

Knowledge Check

Five quick questions to confirm your setup understanding before starting the labs.

1. You open a new terminal window and try to run python hello_mistral.py but get ModuleNotFoundError: No module named 'openai'. What's the most likely cause?

The virtual environment isn't activated in this terminal session
The openai package needs to be reinstalled
Python is not installed correctly
The file has a typo in the import statement
โœ… Correct. Virtual environments must be activated each new terminal session. Run .\venv\Scripts\Activate.ps1 (Windows) or source venv/bin/activate (Mac/Linux) first. The (venv) prefix in the prompt confirms it's active.

2. What port does Ollama use by default, and what URL does your Python code use to reach it?

Port 8080 โ€” http://localhost:8080/v1
Port 11434 โ€” http://localhost:11434/v1
Port 5000 โ€” http://127.0.0.1:5000
Port 443 โ€” Ollama uses HTTPS by default
โœ… Correct. Ollama listens on port 11434. The /v1 path is the OpenAI-compatible endpoint. This is why you set base_url="http://localhost:11434/v1" in the OpenAI SDK client.

3. You want to use Groq instead of local Ollama for faster inference. Which of the following changes is sufficient?

Install a different Python package (pip install groq) and rewrite all API calls
Change base_url to Groq's endpoint and set api_key to your Groq key โ€” code logic stays the same
You can't use Groq โ€” it doesn't support the OpenAI Chat Completions format
Reinstall everything in a new virtual environment configured for Groq
โœ… Correct. Groq implements the same OpenAI Chat Completions API as Ollama. Only the base_url, api_key, and model name change. All your agent logic, tool definitions, and message history handling stays identical.

4. Why should you NEVER run pip install openai without activating a virtual environment first?

It will fail โ€” pip only works inside virtual environments
It installs into the global Python, which can cause version conflicts across all your projects
It will install the wrong version of openai
It requires admin/sudo permissions to install globally
โœ… Correct. Installing into global Python means every project shares the same packages. If Project A needs openai 1.x and Project B needs openai 0.28 (older API), they can't coexist. Venvs solve this by giving each project its own isolated package list.

5. After running ollama pull mistral, Mistral-7B is now on your machine. What happens to the model files if you delete the venv/ folder?

Nothing โ€” Ollama stores model files separately from your Python virtual environment
The model files are deleted too โ€” they're stored inside the venv
The model stops working until you reinstall Ollama
You need to re-pull the model after recreating the venv
โœ… Correct. Ollama stores model files in its own directory (~/.ollama/models on Mac/Linux, %USERPROFILE%\.ollama\models on Windows), completely separate from your Python project. Deleting or recreating the venv only removes Python packages โ€” Ollama and its models are unaffected.