Accessing OpenAI’s API Using R and httr2
In this blog post, I will guide you through the process of accessing OpenAI’s GPT-4 API using R and the httr2
package. By the end, you’ll be able to make requests to the API and retrieve responses programmatically.
Prerequisites
Before we start, make sure you have done the following:
Useful Links
Step-by-Step Instructions
Let’s walk through the code to make an API request using R.
Step 1: Install and Load the httr2
Package
First, ensure you have the httr2
package installed and loaded in your R environment:
install.packages('httr2')
library(httr2)
Step 2: Set Up Your API Key
Make sure to set up your API key as an environment variable named OPENAI_API_KEY
. You can do this by adding the following line to your .Renviron
file or setting it directly in your R session:
Sys.setenv(OPENAI_API_KEY = 'YOUR_API_KEY_HERE')
Step 3: Create the Request Function
Here is a function that constructs and sends a request to the GPT-4 API. The function takes a prompt as input and returns the response from the API.
# Request to ChatGPT.
<- function(prompt) {
chatgpt_request
if(!is.character(prompt)) stop('The prompt must be a character string.')
<- Sys.getenv('OPENAI_API_KEY')
api_key
# Create the request
<- request('https://api.openai.com/v1/chat/completions') |>
request req_headers(
Authorization = paste('Bearer', api_key),
`Content-Type` = 'application/json'
|>
) req_body_json(list(
model = 'gpt-4o-2024-05-13',
messages = list(list(role = 'user', content = prompt)),
max_tokens = 150
))
# Perform the request
<- request |>
response req_perform()
# Parse and return the response
resp_body_json(response)
}
Step 4: Make a Request
Use the function to make a request to the API. For example:
<- 'Please create a poem about R, OpenAI, API, and httr2'
prompt <- chatgpt_request(prompt)
response cat(response$choices[[1]]$message$content)
This code will send the prompt ‘Please create a poem about R, OpenAI, API, and httr2’ to the GPT-4 API and print the response.
Here is the response!
In the land of data, vast and wide,
Where secrets in the numbers hide,
A tool arose with power great,
To analyze, to innovate.
R, the language of the wise,
With syntax clear, it did surprise.
From stats to plots, it paved the way,
For insights fresh, both night and day.
But seeking more, the coders yearn,
For AI’s magic, they discern.
OpenAI, with knowledge bright,
Brought forth APIs, pure delight.
With queries swift, and answers neat,
The world of data felt complete.
Conversing with a bot so smart,
Transforming data, artful heart.
Yet bridging these, a task in hand,
To fetch, to send, at our command.
httr.
Conclusion
By following these steps, you can easily access OpenAI’s GPT-4 API using R and the httr2
package. This allows you to integrate powerful language model capabilities into your R applications. For more details on the models and API usage, refer to the OpenAI Models and API Key Usage documentation.