How to Launch Your First AI Project Using Python and OpenAI API
Written on
Are you eager to create your first AI project but unsure where to begin? For those stepping into the field of AI Engineering, the initial stages can often feel daunting. I remember how challenging it was to set up my project, and I aim to simplify that process for you with this guide. This article highlights three essential steps for initiating any project using the OpenAI API in Python:
- Setting up a Python environment.
- Generating an OpenAI API secret key.
- Loading the key to utilize the OpenAI library.
I have thoroughly tested each step outlined here.
Note: At the end of this guide, you'll find a link to a GitHub repository that contains all the scripts and setups.
# Step 1: Setting Up a Python Environment
Let’s kick off by preparing a Python virtual environment. I assume you already have Python installed on your machine. First, create a project folder:
mkdir folder-name
cd folder-name
Now, we can create a Python environment in four different ways using:
- Python venv
- Anaconda
- Pipenv
- Poetry
Note: Choose one method and proceed to Step 2.
Let’s dive into the options.
Option 1: Using Python Venv
This method is highly recommended for beginners as it is straightforward and does not require additional installations (assuming Python is already on your machine).
Create a virtual environment. With venv, it's as easy as:
python -m venv venv
Activate the virtual environment. This step varies depending on your operating system:
On macOS and Linux:
python3 -m venv myenv
source myenv/bin/activate
On Windows:
python -m venv myenv
.myenvScriptsactivate
Upgrade pip (optional but recommended) to ensure you're using the latest stable version:
pip install --upgrade pip
Install the openai API package:
pip install openai
Alternatively, if you clone the GitHub repository with the scripts, you can install them directly from requirements.txt:
pip install -r requirements.txt
Option 2: Using Anaconda
Anaconda is commonly used by Data Scientists and Machine Learning Engineers. It requires slightly more technical knowledge than the simple venv method from Option 1, but it is highly convenient.
- Install Anaconda. Instead of detailed instructions, here are links for installation on each system:
- For Windows.
- For macOS.
- For Linux.
Create a new Conda environment. Open your terminal and type:
conda create --name openai_env python=3.9
You should see a list of new packages to be installed. To proceed, press Enter or type "y" and hit Enter.
Activate the new Conda environment:
conda activate openai_env
Install the openai library. Add conda-forge to your channels:
conda config --add channels conda-forge
conda config --set channel_priority strict
Once enabled, you can install openai with:
conda install openai
Option 3: Using Poetry
Poetry is a modern tool that emphasizes simplicity and ease of use, creating lock files for reproducible installations.
Install Poetry. For details, I’ll provide a link to the installation guide.
Initialize Poetry for your project:
poetry init
Poetry will prompt you with several questions, but you can just press Enter for defaults. You’ll know the project environment is set up when you see the pyproject.toml file.
Activate the Poetry environment:
poetry shell
Install the openai library:
poetry add openai
This command updates your pyproject.toml and creates the poetry.lock file.
Option 4: Using Pipenv
Pipenv manages a virtual environment automatically and also uses lock files for reproducible installations.
Install pipenv using pip:
pip install pipenv
Initialize pipenv and create a virtual environment:
pipenv install
You’ll know this step was successful when you see Pipfile and Pipfile.lock in your project folder.
Activate the pipenv virtual environment:
pipenv shell
Install the openai library:
pipenv install openai
Optionally deactivate the pipenv shell with:
exit
Summary of Step 1
Great job! You’ve successfully set up your Python environment. However, to access OpenAI models in Python, you need an OpenAI API secret key. Let's learn how to create one!
# Step 2: Generate an OpenAI API Key
First, navigate to the OpenAI platform. Log in or sign up:
Once logged in, go to the API keys section to see:
Click on “Create new secret key”.
Give it a name if desired and click “Create secret key”.
Now, your secret key is generated. Ensure you copy it before proceeding to the next step.
Important: Once you click “Done,” you won’t be able to copy the key again. Ensure you complete the next step first!
# Step 3: Loading Your OpenAI API Key
For this step, consider the most common methods:
- Using environment variable files.
- Using environment variables.
- Using configuration files.
Similar to Step 1, select only one option.
Option 1: Using Environment Variables
- Set an environment variable:
On Windows:
setx OPENAI_API_KEY "your_openai_api_key_from_step2"
On macOS & Linux:
export OPENAI_API_KEY="your_openai_api_key_here"
Access the environment variable in Python:
import os
openai_api_key = os.getenv('OPENAI_API_KEY')
if not openai_api_key:
raise ValueError("No API key found in environment variables")
Utilize the API Key. You can now use the openai_api_key variable in your code as necessary.
Option 2: Using a Configuration File
Create a configuration file, e.g., config.yaml.
Add the secret key to the config.yaml file:
openai:
api_key: "your_openai_api_key_here"
Exclude the configuration file from version control using the .gitignore file:
# .gitignore
config.yaml
Important: This step is crucial when sharing your project online (e.g., GitHub). If others gain access to your secret key, you will be charged for its usage.
Refer to the “Deleting the secret key” section later in this article for instructions on how to revoke your secret keys.
Access the API key in Python from the config.yaml file. First, install the pyyaml package:
pip install pyyaml
Then, use this Python code:
import yaml
with open("config.yaml", "r") as config_file:
config = yaml.safe_load(config_file)
openai_api_key = config['openai']['api_key']
- Utilize the API Key. You can use the openai_api_key variable in your code as needed.
Option 3: Using an Environment Variable File
This approach merges the previous two options by using an environment variable stored in a .env file, which I personally prefer for loading secret keys.
Create a .env file and write:
# .env
OPENAI_API_KEY="your_openai_api_key_from_step2"
Exclude the .env file from version control using the .gitignore file:
# .gitignore
.env
Important: This step is critical when sharing your project online (e.g., GitHub). If others access your secret key, you will incur charges for its usage.
Load environment variables in Python. First, install the python-dotenv package:
pip install python-dotenv
Then, load the .env in your Python script:
from dotenv import load_dotenv
import os
load_dotenv()
openai_api_key = os.getenv('OPENAI_API_KEY')
if not openai_api_key:
raise ValueError("No API key found in .env file")
- Utilize the API Key. You can now use the openai_api_key variable in your code as needed.
# Bonus: Managing Your API Key
After copying your API key from Step 2 and clicking “Done,” you should see this:
Revoking Your Secret Key
To revoke your secret key, click the red “garbage” icon to the right.
Important: Never share your API keys with anyone! If someone else uses your secret key, you will incur charges. Immediately revoke any API keys you accidentally pushed to GitHub!
# Step 4: Execute and Test
Here’s a simple script to verify if your project has been set up correctly:
import os
from openai import OpenAI
openai_api_key = os.getenv("OPENAI_API_KEY")
if not openai_api_key:
raise ValueError("No API key found in environment variables")client = OpenAI(api_key=openai_api_key)
completion = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{
"role": "system",
"content": "You specialize in concisely explaining complex topics to a 12-year-old.",
},
{
"role": "user",
"content": "What's an artificial neural network?",
},
],
)
print(completion.choices[0].message.content)
Important: I adjusted the code to load the OpenAI API Key using Option 1: Using Environment Variable. If you choose a different method, please modify the code accordingly.
To execute this code, type the following in your terminal (assuming your script is named chat.py):
python chat.py
You should see the results of your prompt without any errors.
# Step 5: Your Turn!
If you're keen to advance in AI, start developing your projects. With the setup you just learned, you can easily begin using LangChain and LlamaIndex as well.
In this article, I demonstrated how to utilize LangChain and LlamaIndex with GPT-4o Mini!
How to run GPT-4o Mini with OpenAI API, LlamaIndex, and LangChain.
A straightforward guide for GPT-4o Mini using Python.
[ai.gopubby.com](https://ai.gopubby.com)
If you're interested in my approach to quickly become an AI Engineer, you'll appreciate this article:
If I started learning AI Engineering in 2024, here's my plan.
The exact path I would take.
[ai.gopubby.com](https://ai.gopubby.com)
# Conclusion
That’s a wrap! We covered various methods for setting up a Python project with the OpenAI API. I hope this guide helps you kick-start your next endeavor!
If you found this article helpful, please give a clap and follow me. This will help Medium show it to others who may find it valuable!
References
- GitHub Repository with all relevant materials from this article.