This tutorial will show you in less than 5 minutes how you can access the OpenAI API in R. OpenAI offers an API that provides access to all of its AI models, ranging from GPT-3.5, and GPT-4 to Dall-e-3 and Whisper. This allows you to enjoy benefits like content generation, language translation, code generation and even building your own customized AI tools. In this tutorial, we will show the basics, so you can immediately start with making your first API request in R by calling the GPT-3.5 model.
For a beginner’s guide on how to access the OpenAI API within Python, check out our tutorial HERE.
Requirements:
- R and preferably Rstudio is installed on your computer. Check out this article from Tilburg Science Hub for a tutorial on this.
Setting up your environment
1. Create or Log Into Your OpenAI Account:
Visit OpenAI’s API documentation website and either sign in with an existing account or create a new one. This step is crucial as it grants you access to the API keys required for authentication.
2. Generate an API Key:
- Navigate to the API keys section within your OpenAI account dashboard.
- Create a new API key. Remember to copy this key immediately, as it won’t be visible again once you navigate away from the page.
3. Secure Your API Key Using Environmental Variables:
MacOS
- Open your terminal or command prompt.
- Run the command
nano ~/.zshrc
to open your bash profile in the nano editor. (Note: for older MacOS versions, you might need to run nano~/.bash_profile
instead). - You can edit the file by pressing control + O and then enter.
- Add the line
export OPENAI_API_KEY='your-api-key'
at the end of the file, replacingyour-api-key
with the actual key you obtained earlier. - Save the file by pressing
Ctrl + X
,y
and then hitEnter
. - Apply the changes by running
source ~/.zshrc
or restart your terminal.
Windows
- Right-click on ‘This PC’ or ‘My Computer’ on your desktop or in File Explorer, and select ‘Properties’.
- Click on ‘Advanced system settings’ on the left side of the System window.
- In the System Properties window, click the ‘Environment Variables’ button near the bottom of the Advanced tab.
- In the Environment Variables window, under the ‘System variables’ section, click ‘New…’ to create a new system variable.
- In the New System Variable dialog, enter
OPENAI_API_KEY
as the variable name and your actual API key as the variable value. - Click ‘OK’ to close the New System Variable dialog. Then, click ‘OK’ again to close the Environment Variables window, and click ‘OK’ once more to close the System Properties window.
4. Verifying Your API Key:
- In the terminal, run
echo $OPENAI_API_KEY
. - This command should return your API key, confirming it has been correctly set up as an environmental variable.
Integrating OpenAI API with R
1. Install the OpenAI R Package
Start by opening Rstudio and creating a new R file. Then install the OpenAI R package. You can do so by running install.packages("openai")
.
2. Import Required Library
After you have completed the installation of the package you need to import it as a library and load the package for interacting with the OpenAI API:
install.packages("openai")
library(openai)
3. Initialize your API Key in R:
Use the following code snippet to initialize the API key you made before inside R:
Sys.setenv(
OPENAI_API_KEY = 'YOUR_API_KEY'
)
4. Example use cases
Text generation
You can now generate text completions by calling the create_chat_completion()
function. This function specifies the model (gpt-3.5-turbo
in this case) and simulates a conversation between a user and the assistant. Here’s what’s happening inside the create()
method:
model="gpt-3.5-turbo"
: Specifies the model to use for the text generation. In this case, “gpt-3.5-turbo” is chosen. For more alternative models you can check this overview.messages
: This is a list of messages that simulate a conversation between a user and the assistant. Each message is a dictionary with two keys: role and content. The role can be either “system”, “user”, or “assistant”, indicating the sender of the message. Here’s a basic example:
answer = create_chat_completion(
model = "gpt-3.5-turbo",
temperature = 0,
messages = list(
list(
"role" = "system",
"content" = "You are a professional translator that helps me translate into other languages."
),
list(
"role" = "user",
"content" = "Please translate this text in to French: I invite you to come to my birthday party on 23 of april, let me know if you can make it!"
)
)
)
- Display the Generated Text: To display the result you can use the following code snippet:
answer$choices$message.content
[1] "Je t'invite à venir à ma fête d'anniversaire le 23 avril, fais-moi savoir si tu peux venir!"
- Here is the full R code to be able to copy it all at once:
install.packages("openai")
library(openai)
Sys.setenv(
OPENAI_API_KEY = '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'
)
answer = create_chat_completion(
model = "gpt-3.5-turbo",
temperature = 0,
messages = list(
list(
"role" = "system",
"content" = "You are a professional translator that help me translate into other languages."
),
list(
"role" = "user",
"content" = "Please translate this text in to French: I invite you to come to my birthday party on 23 of april, let me know if you can make it!"
)
)
)
answer$choices$message.content
Creating images
Another use case is generating images using the Dall·E API. Calling the DALL·E API endpoint can be simplified and efficiently executed using the create_image
function.
create_image("a hyper photo realistic monkey and a cat getting married inside a luxury house")
Conclusion
In summary, this guide has walked you through the necessary steps to access and use the OpenAI API inside R, particularly focusing on generating text with the GPT-3.5 model. While this guide focuses on text generation with GPT-3.5, OpenAI’s API encompasses a wide range of models, including those for image generation (DALL-E) and audio transcription (Whisper). The examples and code provided here serve as a starting point.