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.
- 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
openaipackage installed - Ollama running locally with Mistral-7B pulled and ready
- A working test script that calls Mistral-7B and prints a response
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.
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.
python --version # Should print: Python 3.11.x or 3.12.x
python -m pip --version # Should print: pip 24.x from ...
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.
# 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.
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
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.
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.
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.
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.
# 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
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.
# 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)
(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.
# 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:
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.
pip freeze > requirements.txt
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.
Download and run the installer from ollama.ai. It installs Ollama as a Windows service that starts automatically. After installation, open PowerShell and run:
# 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.
# 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
# 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
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.
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 โ 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")
python hello_mistral.py
--------------------------------------------------
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.
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.
Create the folder structure now
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
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
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:
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?
.\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?
http://localhost:8080/v1http://localhost:11434/v1http://127.0.0.1:5000/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?
pip install groq) and rewrite all API callsbase_url to Groq's endpoint and set api_key to your Groq key โ code logic stays the samebase_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?
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?
~/.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.