openai is an R wrapper of OpenAI API endpoints. This package covers Models, Completions, Edits, Images, Embeddings, Files, Fine-tunes, Moderations, and legacy Engines endpoints. The latter endpoints, namely Engines, are left for backward compatibility and will be removed soon.
To use the OpenAI API, you need to provide an API key. First, sign up for OpenAI API on this page. Once you signed up and logged in, you need to open this page, click on Personal, and select View API keys in drop-down menu. You can then copy the key by clicking on the green text Copy.
By default, functions of openai will look for
OPENAI_API_KEY environment variable. If you want to set a global environment variable, you can use the following command (where
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx should be replaced with your actual key):
Sys.setenv( OPENAI_API_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' )
Otherwise, you can add the key to the
.Renviron file of the project. The following commands will open
.Renviron for editing:
You can add the following line to the file (again, replace
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx with your actual key):
Note: If you are using GitHub/Gitlab, do not forget to add
Finally, you can always provide the key manually to the functions of the package.
library(openai) create_completion( model = "ada", prompt = "Generate a question and an answer" ) #> $id #>  "cmpl-6MiImjcaCSuQYY6u8UA2Mm0rCdbEo" #> #> $object #>  "text_completion" #> #> $created #>  1670871532 #> #> $model #>  "ada" #> #> $choices #> text #> 1 within 5 minutes, up to an hour depending on how your users are different and #> index logprobs finish_reason #> 1 0 NA length #> #> $usage #> $usage$prompt_tokens #>  7 #> #> $usage$completion_tokens #>  16 #> #> $usage$total_tokens #>  23
Further, one can generate an image using DALL·E text-to-image model with
create_image("An astronaut riding a horse in a photorealistic style")