panhandlefamily.com

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).

  1. Create a virtual environment. With venv, it's as easy as:

    python -m venv venv

  2. 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

  1. Upgrade pip (optional but recommended) to ensure you're using the latest stable version:

    pip install --upgrade pip

  2. 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.

  1. Install Anaconda. Instead of detailed instructions, here are links for installation on each system:
  • For Windows.
  • For macOS.
  • For Linux.
  1. 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.

  1. Activate the new Conda environment:

    conda activate openai_env

  2. 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.

  1. Install Poetry. For details, I’ll provide a link to the installation guide.

  2. 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.

  1. Activate the Poetry environment:

    poetry shell

  2. 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.

  1. Install pipenv using pip:

    pip install pipenv

  2. 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.

  1. Activate the pipenv virtual environment:

    pipenv shell

  2. Install the openai library:

    pipenv install openai

  3. 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

  1. 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"

  1. 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")

  2. Utilize the API Key. You can now use the openai_api_key variable in your code as necessary.

Option 2: Using a Configuration File

  1. Create a configuration file, e.g., config.yaml.

  2. Add the secret key to the config.yaml file:

    openai:

    api_key: "your_openai_api_key_here"

  3. 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.

  1. 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']

  1. 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.

  1. Create a .env file and write:

    # .env

    OPENAI_API_KEY="your_openai_api_key_from_step2"

  2. 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.

  1. 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")
  1. 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

  1. GitHub Repository with all relevant materials from this article.

Share the page:

Twitter Facebook Reddit LinkIn

-----------------------

Recent Post:

Achieving Financial Stability in the Music Industry: A Guide

Learn how musicians can navigate financial risks and achieve stability in their careers while maintaining artistic integrity.

Embracing Guitar Lessons Earlier: A Personal Journey to Mastery

A reflection on the importance of starting guitar lessons sooner for better skill development.

Empathetic Listening: A Leader's Path to Genuine Engagement

Discover the transformative power of empathetic listening in leadership and how it fosters genuine connections and engagement.

Unlocking Your Full Potential: Strategies for Hard Work Success

Explore effective strategies to enhance your work ethic and achieve personal success through hard work and smart planning.

Rediscovering Fulfillment: A Journey Through Disconnection

A deep exploration of the struggle for fulfillment amidst societal expectations and personal disconnection.

Discovering My Writing Journey: From Childhood to Resurgence

A personal account of my writing evolution, including challenges and triumphs that shaped my passion.

Unlocking the Transformative Power of Reading in Your Life

Discover how reading can reshape your life and success by cultivating a habit of continuous learning.

Unlocking the Process: Your Path to Unparalleled Success

Discover how embracing the power of process can lead to extraordinary achievements in your life.