Create your OpenAI key

Tutorial
Setup
Instructions to create an API key for OpenAI and store it using Renviron.
Modified

November 18, 2024

We will use OpenAI’s API to programmatically interact with LLMs. To do this, you will need to generate an API key and store it in a secure location.

  1. Create an OpenAI account. I have invited all students to join our OpenAI organization. It is just for students in this class and your accounts will be deactivated at the end of the semester. Look for an email from OpenAI to your Cornell email account inviting you join. Follow the instructions to create and activate your account through OpenAI’s website.

  2. Generate an API key. Once you have an account, log in to OpenAI and navigate to the API keys. Make sure you are viewing the dashboard under our “INFO classes” organization and the “Default project”. If that is not the default setting, use the dropdown menus to adjust this. You will see a button on the right side of the screen to generate an API key. Click the button.

    Give your key a name and make sure you have selected the “Default project”. This is the only way to ensure your API usage is charged to the course and not you individually. Click “Create secret key”.

  3. Save your key. You will see a screen with your API key. It is a long string of characters. Copy this key to your clipboard.

    From your R console, run

    usethis::edit_r_environ()

    This will open your .Renviron file in RStudio. Add a line to this file that looks like this:

    OPENAI_API_KEY="YOUR-OPENAI-TOKEN"

    Replace YOUR-OPENAI-TOKEN with the copied token from OpenAI. Save the file and restart your R session. You should now be able to access your API key in R by running

    Sys.getenv("OPENAI_API_KEY")