Set up OpenAI API

Install the OpenAI Python library

From the terminal / command line, run:

pip install --upgrade openai

Set up your API key

Create .env file in the root of your project and add your OpenAI API key:

OPENAI_API_KEY=your-api-key

Run the following command to install the python-dotenv package:

pip install python-dotenv

Add the following code to your Python script to load the API key from the .env file:

import os
from dotenv import load_dotenv

load_dotenv()
openai_api_key=os.environ.get("OPENAI_API_KEY")

Test your API key

Create a new Python script and add the following code to test your API key:

from openai import OpenAI

client = OpenAI(
  api_key=os.environ.get("OPENAI_API_KEY")
)

completion = client.chat.completions.create(
  model="gpt-3.5-turbo",
  messages=[
    {"role": "system", "content": "You are a poetic assistant, skilled in explaining complex programming concepts with creative flair."},
    {"role": "user", "content": "Compose a poem that explains the concept of recursion in programming."}
  ]
)

print(completion.choices[0].message)

Last updated