Tutorial #0: OpenAI API Setup
Configure Your AI Workbench in 20 Minutes
โ CORE MISSION OF THIS TUTORIAL
By the end of this tutorial, the reader will be able to:
- โ Create an OpenAI account and get your API key
- โ Securely configure environment variables for API access
- โ Install the OpenAI Python package
- โ Make your first successful API test call
- โ Understand API costs, rate limits, and usage monitoring
This tutorial prepares your development environment for all Technician Track AI experiments.
โ ๏ธ SAFETY BOUNDARY REMINDER
This tutorial performs analysis only.
It must never be connected to:
- Live PLCs
- Production deployment pipelines
- Safety-rated controllers
- Motion or power systems
> All outputs are advisory-only and always require explicit human approval before any real-world action.
๐ VENDOR-AGNOSTIC ENGINEERING NOTE
This tutorial uses:
- โธ OpenAI API (GPT-4, GPT-4o, GPT-4o-mini models)
- โธ Works on Windows, macOS, Linux
- โธ Python 3.8+ required
- โธ No automation hardware needed
- โธ Pay-as-you-go pricing model
Future tutorials will show how to use other AI providers (Anthropic, local models), but OpenAI is the standard starting point.
โน๏ธ About Our API Approach
Technician Track uses the OpenAI Python SDK v1.x with straightforward synchronous calls. This is the current stable, production-ready approach used by thousands of companies.
We're intentionally keeping the API patterns simple so you can focus on agentic concepts rather than API complexity.
What's next: Developer Track (Track 2) will introduce advanced patterns like structured outputs, async operations, streaming responses, and the new OpenAI Responses API. For now, master the fundamentals.
๐ Prerequisites
Before starting this tutorial, you should have:
- โข Python 3.8+ installed (from Tutorial T0: Python Readiness)
- โข A valid email address
- โข A credit/debit card for API billing setup
1๏ธโฃ Create Your OpenAI Account
Step-by-Step Instructions
- 1.
Go to https://platform.openai.com/signup
This is the OpenAI Platform (for developers), not ChatGPT
- 2. Sign up with your email or Google/Microsoft account
- 3. Verify your email address
- 4.
Verify your phone number (required for API access)
This prevents abuse and is required for all API users
Note: New accounts receive $5 in free credits valid for 3 months. This is enough for all Technician Track tutorials.
2๏ธโฃ Set Up Billing (Required)
Add Payment Method
- 1. Navigate to Settings โ Billing
- 2. Click "Add payment method"
- 3. Enter your credit/debit card information
- 4.
Set a monthly usage limit (recommended: $10-20 for learning)
This prevents accidental overspending during experiments
Important: Even with free credits, you must add a payment method to access the API. Your card will only be charged after free credits are exhausted.
3๏ธโฃ Generate Your API Key
Creating Your First API Key
- 1. Go to API Keys in the left sidebar
- 2. Click "Create new secret key"
- 3.
Give it a descriptive name (e.g.,
"technician-track-learning") - 4.
COPY THE KEY IMMEDIATELY โ you cannot view it again!
It will look like:
sk-proj-abc123...
โ ๏ธ Critical Security Warning
Never do this:
- โ Commit API keys to Git repositories
- โ Share keys in Discord, Slack, or public forums
- โ Hardcode keys in Python files like
api_key = "sk-..." - โ Email keys or store them in plain text files
If a key is exposed:
- 1. Revoke it immediately in the OpenAI dashboard
- 2. Generate a new key
- 3. Check your usage logs for unauthorized activity
4๏ธโฃ Configure Your API Key (3 Methods)
You have three options for storing your API key. We'll show all three, but Method A is strongly recommended for security.
Quick Comparison
| Method | Security | Setup | Use Case |
|---|---|---|---|
| A: System Environment | ๐ข Most Secure | One-time setup | Production & learning |
| B: .env File | ๐ก Good (if Git-ignored) | Per-project | Development projects |
| C: Hardcoded | ๐ด Insecure | Immediate | Quick tests only |
โ Method A: System Environment Variables (RECOMMENDED)
Store your API key in your operating system's environment. This is the most secure method and works across all your Python projects.
๐ช Windows
Open PowerShell and run:
[System.Environment]::SetEnvironmentVariable('OPENAI_API_KEY', 'sk-proj-YOUR_KEY_HERE', 'User') Restart your terminal after setting
๐ macOS
Add to ~/.zshrc:
export OPENAI_API_KEY='sk-proj-YOUR_KEY_HERE' Run: source ~/.zshrc
๐ง Linux
Add to ~/.bashrc:
export OPENAI_API_KEY='sk-proj-YOUR_KEY_HERE' Run: source ~/.bashrc
Verification: After setting the variable, verify it's set correctly:
# Windows PowerShell
echo $env:OPENAI_API_KEY
# macOS/Linux
echo $OPENAI_API_KEY Python usage:
from openai import OpenAI
# Automatically reads OPENAI_API_KEY from environment
client = OpenAI() ๐ก Method B: .env File with python-dotenv
Store your API key in a .env file in your project directory. Good for managing different keys across multiple projects.
Step 1: Install python-dotenv
# Install python-dotenv package
pip install python-dotenv Step 2: Create a .env file in your project folder
# .env
OPENAI_API_KEY=sk-proj-YOUR_KEY_HERE Step 3: Load it in your Python script
from dotenv import load_dotenv
from openai import OpenAI
# Load environment variables from .env file
load_dotenv()
# Now OpenAI() can read OPENAI_API_KEY
client = OpenAI() .env file to Git.
๐ด Method C: Hardcoded in Script (NOT RECOMMENDED)
โ ๏ธ SECURITY WARNING: This method is insecure and should ONLY be used for:
- โข Quick throwaway tests
- โข Scripts that will NEVER be committed to Git
- โข Learning exercises in a private, local environment
You can pass the API key directly to the OpenAI client, but this is dangerous if you accidentally commit the code or share it.
from openai import OpenAI
# โ NOT RECOMMENDED - Easy to leak!
client = OpenAI(api_key="sk-proj-YOUR_ACTUAL_KEY_HERE") Why this is risky:
- โข Easy to accidentally commit to Git
- โข Visible in code reviews and screen shares
- โข Can't easily rotate keys without editing code
- โข No separation between dev/test/prod environments
Which Method Should You Use?
For this tutorial series: Use Method A (System Environment Variables). It's the most secure, works everywhere, and is industry standard.
For larger projects later: Method B (.env files) becomes useful when managing multiple API keys or different environments.
Method C: Only use for throwaway test scripts. Never for production or shared code.
5๏ธโฃ Install OpenAI Python Package
Install the official OpenAI Python library:
pip install openai Verify installation:
pip show openai Expected output:
You should see version 1.x.x or higher. As of December 2024, the latest version is 1.55.3.
6๏ธโฃ Make Your First API Call
๐งช Experiment 1: Test API Connection
Objective
Verify that your API key works and you can successfully call the OpenAI API.
Python Code
from openai import OpenAI
# Client automatically reads OPENAI_API_KEY from environment
client = OpenAI()
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{
"role": "user",
"content": "Respond with exactly: 'API connection successful.'"
}
],
max_tokens=10
)
print(response.choices[0].message.content) Expected Output
API connection successful.
7๏ธโฃ Understanding API Costs & Usage
Pricing by Model (December 2024)
| Model | Input | Output | Use Case |
|---|---|---|---|
gpt-4o-mini | $0.15 / 1M tokens | $0.60 / 1M tokens | Testing, learning, simple tasks |
gpt-4o | $2.50 / 1M tokens | $10.00 / 1M tokens | Production, complex reasoning |
gpt-4-turbo | $10.00 / 1M tokens | $30.00 / 1M tokens | Advanced tasks, high quality |
What is a Token?
Roughly:
- โข 1 token โ 4 characters
- โข 100 tokens โ 75 words
- โข 1000 tokens โ 750 words
A typical tutorial experiment uses 500-2000 tokens (~$0.001-0.005 with gpt-4o-mini)
Monitoring Usage
Track your spending:
- 1. Go to Usage in dashboard
- 2. View daily breakdown by model
- 3. Set up usage alerts
- 4. Review monthly totals
All Technician Track tutorials cost <$5 total if using gpt-4o-mini
Cost Optimization Tip:
Always start with gpt-4o-mini for learning.
Only upgrade to gpt-4o or gpt-4-turbo when you need higher quality outputs.
8๏ธโฃ Common Issues & Troubleshooting
โ Error: "Invalid API key"
Causes:
- โข Environment variable not set correctly
- โข Typo when copying the API key
- โข Key was revoked in dashboard
Fix: Verify your environment variable is set. Regenerate the key if needed.
โ Error: "You exceeded your current quota"
Causes:
- โข Free credits exhausted
- โข Monthly usage limit reached
- โข Payment method declined
Fix: Check billing dashboard. Add credits or update payment method.
โ Error: "Rate limit exceeded"
Causes:
- โข Too many requests in short time
- โข Free tier rate limits (3 RPM, 200 RPD)
Fix: Wait 60 seconds and retry. Add payment method for higher limits.
โ ModuleNotFoundError: No module named 'openai'
Causes:
- โข Package not installed
- โข Wrong Python environment
Fix: Run pip install openai. Check you're using the correct Python interpreter.
9๏ธโฃ Official Documentation & Resources
For more detailed information about the OpenAI API, consult the official documentation:
๐ OpenAI Platform Documentation โ
Complete API reference, guides, and examples
https://platform.openai.com/docs/introduction ๐ค Chat Completions Guide โ
How to use the chat API (what we'll use most)
https://platform.openai.com/docs/guides/text-generation โ๏ธ API Reference โ
Detailed parameter documentation and examples
https://platform.openai.com/docs/api-reference/chat ๐ Usage & Rate Limits โ
View your current rate limits and usage tier
https://platform.openai.com/account/limits ๐งญ Engineering Posture
This tutorial reinforced:
- โ Security first โ API keys in environment variables, never in code
- โ Cost awareness โ Understanding pricing and setting limits
- โ Testing before production โ Start with mini models, verify setup
- โ Monitoring usage โ Track spending and rate limits
- โ Documentation literacy โ Know where to find official resources
API Setup Complete!
You're now ready to start building AI-powered industrial automation tools.
Next Tutorial
Tutorial #1: Agentic vs Automation โ