← Other topics

Run ChatGPT in RStudio with chattr

Video Notes

To integrate a ChatGPT chat window directly into RStudio we can use a package called chattr.

ChatGPT window in RStudio

Get OpenAI API key

To get started, you need to get an API key from OpenAI following these steps:

  1. Login at https://platform.openai.com/
  2. Goto Settings (gear icon on top right)
  3. Find API Keys from menu on left
  4. Follow the process to Create new secret key
  5. Copy your secret key (it will only show once so make sure you copy it)

You will need to have some credits loaded on your account in order for chattr to work.

Steps for creating a new OpenAI API key

RStudio setup

Next, run the following conmmands in RStudio to initialize chattr - update your-api-key-here with the API key acquired in the above step.

install.packages("chattr") 

library(chattr) 

# See https://mlverse.github.io/chattr/#available-models for available models
chattr_use("gpt4") 

# Manage keys at https://platform.openai.com/settings/organization/api-keys
Sys.setenv("OPENAI_API_KEY" = "your-api-key-here")

# Setting as_job = TRUE makes the chat app run as a background application, freeing your console up for other work
chattr_app(as_job = TRUE)

After running the above code, you should see a chat window in the Viewer pane where you can issue questions to ChatGPT.

Close up of the Viewer pane in RStudio with ChatGPT via chattr running.

Start Chattr when RStudio loads

If you want to configure RStudio to automatically initialize chatter whenever RStudio is loaded, you can update your .RProfile file.

The .RProfile file is an R startup script that runs every time R or RStudio starts.

To quickly locate/edit the .RProfile file, run the following code:

install.packages("usethis")  # Install if not already installed
usethis::edit_r_profile()

With your .RProfile open, enter this code:

# Load chattr app after RStudio is fully loaded
setHook("rstudio.sessionInit", function(newSession) {
  if (newSession) {
    Sys.sleep(2)  # Wait 2 seconds before starting chattr to ensure RStudio is ready
    tryCatch({
      library(chattr)
      chattr_use("gpt4")
      Sys.setenv("OPENAI_API_KEY" = "your-api-key-here")
      chattr_app(as_job = TRUE)
    }, error = function(e)
      message("Error starting chattr: ", e$message))
  }
}, action = "append")

Save your changes and restart RStudio; after a 2 second delay, you should see the chattr app automatically initializes.

← Other topics