Build Your First AI Agent from Scratch - Part 1: Development Environment Setup

Ad Space
Build Your First AI Agent from Scratch - Part 1: Development Environment Setup
Welcome to the first part of our comprehensive tutorial series on building AI agents from scratch! In this series, you'll learn everything you need to know to create, deploy, and maintain intelligent AI agents that can perform real-world tasks.
What You'll Learn in This Series
By the end of this 5-part tutorial series, you'll have:
- ✅ A complete development environment for AI agent development
- ✅ A fully functional AI agent with memory and context handling
- ✅ Integration with external APIs and tools
- ✅ Testing and debugging strategies
- ✅ Production deployment knowledge
Series Overview
- Part 1: Development Environment Setup (This tutorial)
- Part 2: Creating the Basic Agent Structure
- Part 3: Adding Memory and Context Handling
- Part 4: Implementing Tool Usage and API Integrations
- Part 5: Testing, Debugging, and Deployment
Prerequisites
Before we begin, make sure you have:
- Basic familiarity with command line/terminal
- A text editor or IDE (VS Code recommended)
- Administrator access on your computer
- Stable internet connection for downloading packages
Estimated Time: 15-20 minutes
Step 1: Installing Python
AI agents are commonly built with Python due to its rich ecosystem of AI/ML libraries. We'll use Python 3.9 or higher.
Windows Installation
-
Download Python:
- Visit python.org
- Download Python 3.11 or later
- Important: Check "Add Python to PATH" during installation
-
Verify Installation:
python --version # Should output: Python 3.11.x pip --version # Should output pip version information
macOS Installation
-
Using Homebrew (Recommended):
# Install Homebrew if you haven't already /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" # Install Python brew install python@3.11
-
Verify Installation:
python3 --version pip3 --version
Linux Installation
# Ubuntu/Debian
sudo apt update
sudo apt install python3.11 python3.11-pip python3.11-venv
# CentOS/RHEL/Fedora
sudo dnf install python3.11 python3.11-pip
Step 2: Setting Up Virtual Environments
Virtual environments isolate your project dependencies, preventing conflicts between different projects.
Create Project Directory
# Create and navigate to your project directory
mkdir ai-agent-tutorial
cd ai-agent-tutorial
Create Virtual Environment
# Create virtual environment
python -m venv ai-agent-env
# Activate virtual environment
# Windows:
ai-agent-env\Scripts\activate
# macOS/Linux:
source ai-agent-env/bin/activate
You'll know it's activated when you see (ai-agent-env)
in your terminal prompt.
Verify Virtual Environment
# Check Python location (should point to your virtual environment)
which python # macOS/Linux
where python # Windows
# Should output something like:
# /path/to/ai-agent-tutorial/ai-agent-env/bin/python
Step 3: Installing Essential Libraries
Now we'll install the core libraries needed for AI agent development.
Create Requirements File
Create a requirements.txt
file in your project directory:
# Core AI/ML Libraries
openai==1.6.1
langchain==0.1.0
langchain-openai==0.0.2
langchain-community==0.0.10
# HTTP and API Libraries
requests==2.31.0
httpx==0.25.2
aiohttp==3.9.1
# Data Processing
pandas==2.1.4
numpy==1.24.3
pydantic==2.5.2
# Environment and Configuration
python-dotenv==1.0.0
pyyaml==6.0.1
# Development and Testing
pytest==7.4.3
pytest-asyncio==0.21.1
black==23.12.1
flake8==6.1.0
# Logging and Monitoring
structlog==23.2.0
rich==13.7.0
Install Dependencies
# Upgrade pip first
pip install --upgrade pip
# Install all dependencies
pip install -r requirements.txt
This may take a few minutes. You should see output showing each package being installed.
Step 4: Setting Up Development Tools
Install VS Code Extensions (Recommended)
If you're using VS Code, install these helpful extensions:
- Python - Microsoft's official Python extension
- Pylance - Advanced Python language support
- Python Docstring Generator - Auto-generate docstrings
- GitLens - Enhanced Git capabilities
- Thunder Client - API testing tool
Configure Python Formatter
Set up automatic code formatting:
# Create VS Code settings directory
mkdir .vscode
# Create settings.json
cat > .vscode/settings.json << EOF
{
"python.defaultInterpreterPath": "./ai-agent-env/bin/python",
"python.formatting.provider": "black",
"python.formatting.blackArgs": ["--line-length=88"],
"python.linting.enabled": true,
"python.linting.flake8Enabled": true,
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.organizeImports": true
}
}
EOF
Step 5: Environment Configuration
Create Environment Variables File
Create a .env
file for storing sensitive configuration:
# Create .env file
cat > .env << EOF
# OpenAI Configuration
OPENAI_API_KEY=your_openai_api_key_here
OPENAI_MODEL=gpt-4
# Development Settings
DEBUG=true
LOG_LEVEL=INFO
# Agent Configuration
AGENT_NAME=MyFirstAgent
AGENT_DESCRIPTION=A helpful AI agent built from scratch
EOF
Create .gitignore File
Prevent sensitive files from being committed to version control:
cat > .gitignore << EOF
# Environment variables
.env
.env.local
.env.*.local
# Virtual environment
ai-agent-env/
venv/
env/
# Python cache
__pycache__/
*.pyc
*.pyo
*.pyd
.Python
# IDE files
.vscode/settings.json
.idea/
*.swp
*.swo
# Logs
*.log
logs/
# OS files
.DS_Store
Thumbs.db
# Testing
.pytest_cache/
.coverage
htmlcov/
# Distribution
dist/
build/
*.egg-info/
EOF
Step 6: Project Structure Setup
Create a well-organized project structure:
# Create directory structure
mkdir -p {src,tests,docs,examples,data}
mkdir -p src/{agents,tools,memory,utils}
# Create initial Python files
touch src/__init__.py
touch src/agents/__init__.py
touch src/tools/__init__.py
touch src/memory/__init__.py
touch src/utils/__init__.py
touch tests/__init__.py
Your project structure should now look like this:
ai-agent-tutorial/
├── .env
├── .gitignore
├── requirements.txt
├── .vscode/
│ └── settings.json
├── ai-agent-env/
├── src/
│ ├── __init__.py
│ ├── agents/
│ │ └── __init__.py
│ ├── tools/
│ │ └── __init__.py
│ ├── memory/
│ │ └── __init__.py
│ └── utils/
│ └── __init__.py
├── tests/
│ └── __init__.py
├── docs/
├── examples/
└── data/
Step 7: Verification and Testing
Let's verify everything is working correctly.
Create Test Script
Create test_setup.py
:
#!/usr/bin/env python3
"""
Setup verification script for AI Agent Tutorial
"""
import sys
import subprocess
import importlib
from pathlib import Path
def check_python_version():
"""Check if Python version is compatible"""
version = sys.version_info
if version.major == 3 and version.minor >= 9:
print(f"✅ Python {version.major}.{version.minor}.{version.micro} - Compatible")
return True
else:
print(f"❌ Python {version.major}.{version.minor}.{version.micro} - Requires Python 3.9+")
return False
def check_virtual_environment():
"""Check if virtual environment is active"""
if hasattr(sys, 'real_prefix') or (hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix):
print("✅ Virtual environment is active")
return True
else:
print("❌ Virtual environment is not active")
return False
def check_required_packages():
"""Check if required packages are installed"""
required_packages = [
'openai',
'langchain',
'requests',
'pandas',
'numpy',
'pydantic',
'python-dotenv'
]
missing_packages = []
for package in required_packages:
try:
importlib.import_module(package.replace('-', '_'))
print(f"✅ {package} - Installed")
except ImportError:
print(f"❌ {package} - Missing")
missing_packages.append(package)
return len(missing_packages) == 0
def check_project_structure():
"""Check if project structure is correct"""
required_dirs = [
'src',
'src/agents',
'src/tools',
'src/memory',
'src/utils',
'tests'
]
required_files = [
'.env',
'.gitignore',
'requirements.txt'
]
all_good = True
for directory in required_dirs:
if Path(directory).exists():
print(f"✅ Directory {directory} - Exists")
else:
print(f"❌ Directory {directory} - Missing")
all_good = False
for file in required_files:
if Path(file).exists():
print(f"✅ File {file} - Exists")
else:
print(f"❌ File {file} - Missing")
all_good = False
return all_good
def main():
"""Run all verification checks"""
print("🔍 Verifying AI Agent Development Environment Setup\n")
checks = [
("Python Version", check_python_version),
("Virtual Environment", check_virtual_environment),
("Required Packages", check_required_packages),
("Project Structure", check_project_structure)
]
all_passed = True
for check_name, check_func in checks:
print(f"\n📋 Checking {check_name}:")
if not check_func():
all_passed = False
print("\n" + "="*50)
if all_passed:
print("🎉 All checks passed! Your environment is ready for AI agent development.")
print("\n📚 Next Steps:")
print("1. Get your OpenAI API key from https://platform.openai.com/api-keys")
print("2. Add it to your .env file")
print("3. Proceed to Part 2 of the tutorial series")
else:
print("❌ Some checks failed. Please review the output above and fix any issues.")
return all_passed
if __name__ == "__main__":
success = main()
sys.exit(0 if success else 1)
Run Verification
python test_setup.py
You should see output showing all checks passing.
Step 8: Getting Your OpenAI API Key
To build AI agents, you'll need access to language models. We'll use OpenAI's API:
-
Sign up for OpenAI:
- Visit platform.openai.com
- Create an account or sign in
-
Generate API Key:
- Go to API Keys section
- Click "Create new secret key"
- Copy the key (you won't see it again!)
-
Add to Environment:
# Edit your .env file nano .env # or use your preferred editor # Replace 'your_openai_api_key_here' with your actual API key OPENAI_API_KEY=sk-your-actual-api-key-here
-
Test API Connection:
# Create test_api.py from openai import OpenAI from dotenv import load_dotenv import os load_dotenv() client = OpenAI(api_key=os.getenv('OPENAI_API_KEY')) try: response = client.chat.completions.create( model="gpt-3.5-turbo", messages=[{"role": "user", "content": "Hello! This is a test."}], max_tokens=50 ) print("✅ OpenAI API connection successful!") print(f"Response: {response.choices[0].message.content}") except Exception as e: print(f"❌ API connection failed: {e}")
python test_api.py
Troubleshooting Common Issues
Issue: "python: command not found"
Solution: Python isn't in your PATH. Reinstall Python and ensure "Add to PATH" is checked.
Issue: "pip: command not found"
Solution:
# Download get-pip.py
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
python get-pip.py
Issue: Virtual environment not activating
Solution:
# Recreate virtual environment
rm -rf ai-agent-env
python -m venv ai-agent-env
Issue: Package installation fails
Solution:
# Upgrade pip and try again
pip install --upgrade pip setuptools wheel
pip install -r requirements.txt
Issue: OpenAI API errors
Common causes:
- Invalid API key
- Insufficient credits
- Rate limiting
- Network connectivity
What's Next?
Congratulations! You've successfully set up a complete development environment for building AI agents. Your setup includes:
- ✅ Python 3.9+ with virtual environment
- ✅ Essential AI/ML libraries installed
- ✅ Development tools configured
- ✅ Project structure organized
- ✅ Environment variables configured
- ✅ OpenAI API connection tested
In Part 2, you'll learn:
- Creating your first AI agent class
- Implementing basic conversation handling
- Setting up logging and error handling
- Building a simple command-line interface
- Testing your agent's basic functionality
Quick Reference Commands
# Activate virtual environment
source ai-agent-env/bin/activate # macOS/Linux
ai-agent-env\Scripts\activate # Windows
# Install new packages
pip install package-name
pip freeze > requirements.txt
# Run verification
python test_setup.py
# Test API connection
python test_api.py
Additional Resources
- OpenAI Documentation: platform.openai.com/docs
- LangChain Documentation: python.langchain.com
- Python Virtual Environments: docs.python.org/3/tutorial/venv.html
- VS Code Python Tutorial: code.visualstudio.com/docs/python
Ready to build your first AI agent? Continue to Part 2: Creating the Basic Agent Structure to start coding your intelligent agent!
This tutorial is part of our comprehensive AI Agent Development series. If you found this helpful, consider subscribing to our newsletter for more in-depth tutorials and AI development insights.
Ad Space
Recommended Tools & Resources
* This section contains affiliate links. We may earn a commission when you purchase through these links at no additional cost to you.
📚 Featured AI Books
OpenAI API
AI PlatformAccess GPT-4 and other powerful AI models for your agent development.
LangChain Plus
FrameworkAdvanced framework for building applications with large language models.
Pinecone Vector Database
DatabaseHigh-performance vector database for AI applications and semantic search.
AI Agent Development Course
EducationComplete course on building production-ready AI agents from scratch.
💡 Pro Tip
Start with the free tiers of these tools to experiment, then upgrade as your AI agent projects grow. Most successful developers use a combination of 2-3 core tools rather than trying everything at once.
🚀 Join the AgentForge Community
Get weekly insights, tutorials, and the latest AI agent developments delivered to your inbox.
No spam, ever. Unsubscribe at any time.