Integrate large language models into your R workflows through the chat completions API of OpenAI or of any OpenAI-compatible provider.
Installation
Install the released version of TheOpenAIR from CRAN:
install.packages("TheOpenAIR")or the development version from GitHub:
# install.packages("remotes")
remotes::install_github("umatter/OpenAIR")Configuration
TheOpenAIR is configured through three environment variables (an empty value counts as unset):
| Variable | Purpose | Default |
|---|---|---|
OPENAI_API_KEY |
Your API key, sent with every request. | none (required for api.openai.com; optional for other providers, e.g. a local server) |
OPENAI_BASE_URL |
The API to talk to: any OpenAI-compatible provider, e.g. https://openrouter.ai/api/v1. |
https://api.openai.com/v1 |
OPENAI_MODEL |
The model used when a call does not name one. | "gpt-5.4-mini" |
Put them in your ~/.Renviron file (for example with usethis::edit_r_environ()) and restart R. This keeps the key out of your scripts and your .Rhistory:
OPENAI_API_KEY=YOUR-API-KEY
OPENAI_MODEL=gpt-5.4-mini
For a single session, openai_api_key() sets the key, best without typing it into the script. In RStudio:
library("TheOpenAIR")
openai_api_key(rstudioapi::askForPassword("OpenAI API key"))rstudioapi::askForPassword() needs RStudio. In a terminal or another editor, use openai_api_key(readline("OpenAI API key: ")) in an interactive session (the pasted key is visible), or ~/.Renviron as above.
A single call can use another model with its model argument, e.g. chat("Hello!", model = "gpt-5.4"); chat(), regenerate() and the helper functions pass it on to chat_completion(). Requests time out after 120 seconds and are tried up to three times (rate limits and server errors are retried, honouring Retry-After); see ?chat_completion for the options that change this.
Usage
The simplest way of interacting with a model is chat(). It keeps the conversation, so a follow-up question can refer to the earlier answers:
chat() is primarily useful in interactive mode. For short scripts and functions built on TheOpenAIR, the infix operator %c% sends a message in the same conversation and says which output you want: "message_to_console", "message" (the reply as a character string) or "response_object" (the full response).
resp <-
"Remove all numeric characters from '5XC-2a09ujnap9o2q0MP'.
In your response, only provide what remains from the string." %c%
"message"
resp
#> [1] "XC-aujnapqMP"(Replies come from the model and vary between calls.)
For full control, chat_completion() sends one request and returns the parsed response; messages_content(), usage() and the other accessors read it. It takes the request fields of the chat completions API, among them structured outputs and tools:
# JSON that follows a schema
city <- list(
name = "city",
strict = TRUE,
schema = list(
type = "object",
properties = list(name = list(type = "string"),
country = list(type = "string")),
required = list("name", "country"),
additionalProperties = FALSE
)
)
resp <- chat_completion("Name the capital of Switzerland.",
response_format = city)
jsonlite::fromJSON(messages_content(resp))
# a tool the model may ask you to call
weather <- list(type = "function", `function` = list(
name = "get_weather",
description = "Current weather in a city",
parameters = list(type = "object",
properties = list(city = list(type = "string")),
required = list("city"))
))
resp <- chat_completion("What is the weather in Bern?", tools = weather)
tool_calls(resp) # id, type, name and arguments (JSON) of each callReasoning models such as the default gpt-5.4-mini take max_completion_tokens and reasoning_effort, and may reject a non-default temperature, which is only sent when you give one. Fields without an argument go in extra_body, e.g. chat_completion("Hi", extra_body = list(service_tier = "flex")). Errors are classed conditions (openair_api_error, openair_network_error, …) that all inherit openair_error.
Beyond chatting, the package has helpers for common tasks, among them python_to_r(), r_to_python(), java_to_r(), refactor(), add_roxygen(), write_test(), nested_to_pipe(), extract_entities() and references_to_bibtex(). Each takes a character string, a file path or a URL. Given a string or a URL, it returns its result. Given a file, most write their result to a new file next to the input and never change the input; the exceptions are write_test(), which writes into tests/testthat/ when the file sits in a package’s R/ directory, and extract_entities(), which writes nothing and returns a tibble. See the function reference.
What’s new
Version 0.2.0 changes a good deal, some of it in ways that break existing code: see NEWS.md.
Code of Conduct
Please note that this project is released with a Contributor Code of Conduct (.github/CODE_OF_CONDUCT.md in the repository, linked under “Community” on openair-lib.org). By participating in this project you agree to abide by its terms.
