To integrate a ChatGPT chat window directly into RStudio we can use a package called chattr.
To get started, you need to get an API key from OpenAI following these steps:
You will need to have some credits loaded on your account in order for chattr to work.
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.
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.