Connection with OpenAI Client using Python

Learn how to load your OpenAI API key from an environment using Python built-in dotenv and os libraries. This example also includes creating a client instance and handling authentication errors using the OpenAI package.

This notebook was created with MLJAR Studio

MLJAR Studio is Python code editior with interactive code recipes and local AI assistant.
You have code recipes UI displayed at the top of code cells.

Documentation

All of the required packages are imported automatically by MLJAR Studio:

# import packages
import os
from dotenv import load_dotenv
from openai import OpenAI, AuthenticationError

Create OpenAI client connection using following recipe:

# load .env file
load_dotenv()

# get api key from environment
api_key = os.environ["OPENAI_KEY"]

# create OpenAI client
def create_client(api_key):
    try:
        client = OpenAI(api_key=api_key)
        client.models.list()
        return client
    except AuthenticationError:
        print("Incorrect API")
    return None

client = create_client(api_key)

Conclusions

The first and the most important step is already behind you. Now, you can do plenty of operations using OpenAI. Let's discover them together!

Recipes used in the python-client-openai.ipynb

All code recipes used in this notebook are listed below. You can click them to check their documentation.

Packages used in the python-client-openai.ipynb

List of packages that need to be installed in your Python environment to run this notebook. Please note that MLJAR Studio automatically installs and imports required modules for you.

openai>=1.35.14

python-dotenv>=1.0.1