Setting Up Your Python Environment
Install the OpenAI Python SDK, create a virtual environment, store your API key securely using environment variables, and verify everything works with a health check.
Why Virtual Environments Matter
AI projects pull in lots of packages, and they clash over versions. A virtual environment gives each project its own isolated Python so nothing collides. The code sets one up.
# Create and activate a virtual environment
# Run these commands in your terminal
python3 -m venv .venv # create environment in .venv/ folder
source .venv/bin/activate # activate on macOS/Linux
# .venv\Scripts\activate # activate on Windows
python --version # verify you are using the right PythonInstalling the OpenAI Python SDK
The official OpenAI Python SDK is how you talk to the API — it handles auth, retries, and parsing. Install it inside your active environment, as the code shows.
# Install the OpenAI SDK
pip install openai
# For production projects, pin the version:
pip install 'openai>=1.30.0,<2.0.0'
# Save your dependencies to requirements.txt:
pip freeze > requirements.txt
# Install from requirements.txt on a new machine:
pip install -r requirements.txtAll lessons in this course
- Setting Up Your Python Environment
- The Chat Completions Endpoint
- Controlling Model Behavior with Parameters
- Error Handling and Rate Limits