knitr::opts_chunk$set(
  collapse = T,
  comment = "#>",
  fig.path = "man/figures/README-",
  out.width = "100%"
)

openai

The openai package provides R scripts to use the Open AI API. In order to get started you will need to sign up for an account at https://openai.com/. You will also need to set up billing to use the API.

Installation

You can install the development version of openai from GitHub with:

# install.packages("devtools")
devtools::install_github("samterfa/openai")

Set Up

API calls are authenticated using your API keys. The environment variables set below are consulted while making each call.

Sys.setenv(openai_organization_id = {your_organization_id})
Sys.setenv(openai_secret_key = {your_secret_key})

More details on authentication can be found here.

Examples

Retrieve the currently available models used to generate text.

library(openai)

list_models()$data %>% 
  dplyr::bind_rows()

Create a completion request using the davinci engine.

create_chat_completion(
  model = 'gpt-3.5-turbo', 
  messages = 
    list(
      list(role = 'system', content = 'You are a helpful assistant.'),
      list(role = 'user', content = 'Who won the world series in 2020?'),
      list(role = 'assistant', content = 'The Los Angeles Dodgers won the world series in 2020.'),
      list(role = 'user', content = 'Where was it played?')
    )
)$choices[[1]]$message$content

Generate an image based on a prompt.

img_url <-
  create_image(
    model = 'dall-e-3',
    prompt = 'a white siamese cat', 
    n = 1, 
    size = '1024x1024')$data[[1]]$url

knitr::include_graphics(img_url)

NEW! Ask a question about an image.

openai::create_chat_completion(
  model = 'gpt-4-vision-preview',
  messages = list(
    list(role = 'user', 
         content = list(
           list(
             type = 'text',
             text = 'What is this a picture of?'
           ),
           list(
             type = 'image_url',
             image_url = list(
               url = img_url
             )
           )
         )
    )
  ), 
  max_tokens = 1000
)$choices[[1]]$message$content

Use the included addin to code collaboratively with a model.

Access it via the Addins menu, or by Tools -> Addins -> Browse Addins. Search for "openai".



samterfa/openai documentation built on Oct. 9, 2024, 5:18 p.m.