In this tutorial, you will learn all the tricks of the trade for working with the OpenAI API in R. After this article, a world will open up for you, and you’ll be able to start your own AI projects! Don’t worry, we’ll explain step by step how to get access and how to get started with a few simple, quick steps. After reading this article, you’ll be ready to get started with the GPT-4o or o1 models even explore audio models like Whisper. In other words, we’ll show you all the benefits of the API for content generation, translation, and code creation, simply put everything you need to build your own customized AI tool. Exciting, right? Let’s start with the basics so you can immediately begin making your first API request in R by calling the GPT-4o model.
If Python is your preferred language, then check out this article: HERE.
Requirements:
To get started the following installations are required, don’t worry our colleagues will help you through all the steps.
- 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 important 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-4o-mini
in this case) and simulates a conversation between a user and the assistant. Here’s what’s happening inside the create()
method:
model="gpt-4o-mini"
: Specifies the model to use for the text generation. In this case, “gpt-4o-mini” 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-4o-mini",
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-4o-mini",
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 use via the create_image
function.
create_image("a hyper photo realistic monkey and a cat getting married inside a luxury house")
Conclusion
In short, in this tutorial we went through all the steps necessary to get access to the OpenAI API and did our first use case! You even used the GPT-4o-mini model and created an image using R code. So feel free to get started and use our examples and code as a starting point