Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/samterfa/openai

This R package provides an SDK to the Open AI API
https://github.com/samterfa/openai

Last synced: about 1 month ago
JSON representation

This R package provides an SDK to the Open AI API

Awesome Lists containing this project

README

        

---
output: github_document
---

```{r, include = FALSE}
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](https://platform.openai.com/docs/api-reference/). In order to get started you will need to sign up for an account at [https://openai.com/](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](https://github.com/samterfa/openai) with:

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

## Set Up

API calls are authenticated using your [API keys](https://beta.openai.com/account/api-keys). The environment variables set below are consulted while making each call.

```{r, eval=F}
Sys.setenv(openai_organization_id = {your_organization_id})
Sys.setenv(openai_secret_key = {your_secret_key})
```

More details on authentication can be found [here](https://platform.openai.com/docs/api-reference/authentication).

## Examples

#### Retrieve the currently available models used to generate text.

```{r}
library(openai)

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

#### Create a completion request using the davinci engine.

```{r, tidy=TRUE, tidy.opts=list(width.cutoff=60)}
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.

```{r}
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.

```{r}
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.

![](addin_demo_1.gif)

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