This function generates natural language text in a conversational style using the OpenAI API's chat endpoint. It takes a series of chat messages as input, as a data.frame, a chatlog object or a single string, and generates a text completion based on the conversation history and the specified model parameters.
Usage
chat_completion(
msgs,
functions = NULL,
function_call = NULL,
model = default_model(),
temperature = NULL,
max_tokens = NULL,
n = NULL,
stop = NULL,
presence_penalty = NULL,
frequency_penalty = NULL,
best_of = NULL,
logit_bias = NULL,
stream = FALSE,
top_p = NULL,
user = NULL,
tools = NULL,
tool_choice = NULL,
response_format = NULL,
seed = NULL,
max_completion_tokens = NULL,
reasoning_effort = NULL,
extra_body = list()
)Arguments
- msgs
The chat history to generate text from: a data.frame with the columns
roleandcontent(one row per message, at least one row; other columns, such asname, are sent as they are), a chatlog object, or a single character string, which is sent as one user message. Every row needs arole, and acontentunless it is an assistant turn of a log with afunction_callortool_callscolumn. Anything else stops before the request.- functions
Deprecated: use
tools. A list of function definitions (each a list withname,descriptionandparameters). It gives a deprecation warning and is sent astools, each function wrapped aslist(type = "function", function = <definition>). Cannot be combined withtools.- function_call
Deprecated: use
tool_choice."auto","none"orlist(name = "<function>"); it gives a deprecation warning and is sent astool_choice. Cannot be combined withtool_choice.- model
A character string specifying the ID of the model to use. The default,
default_model()(internal, not exported), is the environment variableOPENAI_MODELif it is set and not blank, otherwise "gpt-5.4-mini".- temperature
An optional numeric scalar specifying the sampling temperature to use. It is sent only when given. Support differs by model: the default "gpt-5.4-mini" accepts it when
reasoning_effortis unset or"none"(otherreasoning_effortvalues were not checked), while some reasoning models (e.g. OpenAI's o-series) reject a value other than their default. If the API answers 400 (raised asopenair_api_error), leave it unset for that model.- max_tokens
An optional integer scalar specifying the maximum number of tokens to generate, sent as
max_tokens(it is not translated intomax_completion_tokens). Many OpenAI-compatible providers, and older OpenAI models such as "gpt-4.1-mini", expect this one; the default "gpt-5.4-mini" rejects it (the API answers 400, raised asopenair_api_error) and needsmax_completion_tokensinstead, as do other OpenAI reasoning models. Support differs by model and provider.- n
An optional integer scalar specifying the number of text completions to generate.
- stop
An optional character string or character vector specifying one or more stop sequences to use when generating the text. The default "gpt-5.4-mini" rejects it (the API answers 400, raised as
openair_api_error), and so may other OpenAI reasoning models; support differs by model and provider.- presence_penalty
An optional numeric scalar specifying the presence penalty to use when generating the text. The default value is NULL.
- frequency_penalty
An optional numeric scalar specifying the frequency penalty to use when generating the text. The default value is NULL.
- best_of
Deprecated and ignored:
best_ofbelongs to the legacy completions endpoint, which chat completions does not accept. Supplying it gives a deprecation warning and it is not sent; usenfor several completions. The argument will be removed in a future version.- logit_bias
An optional named numeric vector (or named list of numbers) mapping token ids to a bias between -100 and 100, e.g.
c("50256" = -100)to ban token 50256. It is sent as a JSON object. The default "gpt-5.4-mini" rejects it (the API answers 400, raised asopenair_api_error), and so may other OpenAI reasoning models; support differs by model and provider.- stream
Streaming is not supported yet:
stream = TRUEstops with an error. The default isFALSE.- top_p
An optional numeric scalar specifying the top p sampling ratio. The default value is NULL.
- user
A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse.
- tools
An optional list of tools the model may call, each a list such as
list(type = "function", function = list(name = "get_weather", description = "...", parameters = <JSON schema as a list>)). A single tool may be given on its own; the names of a named list are dropped. When the model calls a tool, the reply has no text content andfinish_reason"tool_calls"; read the calls withtool_calls(). Running the tools is up to you; how to send their results back in a follow-up request is shown in the section "Sending tool results back" oftool_calls().- tool_choice
An optional
"auto","none","required", or a list naming one tool, e.g.list(type = "function", function = list(name = "get_weather")). Atool_choicewithouttoolsgives a warning (the OpenAI API rejects it) but is sent.- response_format
An optional output format:
"json_object"(JSON mode; the messages must ask for JSON),"text", a JSON schema for structured outputs given as a list withnameandschema(and optionallystrict = TRUE), which is sent aslist(type = "json_schema", json_schema = <your list>), or a completeresponse_formatobject (a list with atype), sent as it is.- seed
An optional whole number; the provider tries to return the same reply for the same seed and request (best effort).
- max_completion_tokens
An optional positive whole number, the upper bound on the tokens generated, reasoning tokens included. The default "gpt-5.4-mini" needs this instead of
max_tokens, as do other OpenAI reasoning models. A reply cut off by it hasfinish_reason"length".- reasoning_effort
An optional string such as
"none","low","medium"or"high", for reasoning models. The values differ by model and are listed in its documentation: the default "gpt-5.4-mini" accepts"none","low","medium","high"and"xhigh"but rejects"minimal"(the API answers 400, raised asopenair_api_error).- extra_body
A named list of further request fields, applied to the request body last: it can add any field the provider accepts (e.g.
list(top_k = 40)for a provider that takes it), replace a field set by another argument (as a whole: a list given here is not merged into the field it replaces), or remove one withNULL. The default,list(), changes nothing.
Value
The parsed response, a list with the elements id, object,
created, model, choices (a data.frame whose message column holds the
replies) and usage; see messages(), messages_content(),
tool_calls() and usage(). A reply that calls tools is returned as it
is, its content NA.
Configuration
Three environment variables configure the request; each counts as unset when it is empty or blank:
OPENAI_API_KEY: the API key, sent as a Bearer token. Put it in your~/.Renvironfile (seeopenai_api_key()). It is required forapi.openai.com; for another base URL, e.g. a local server such as Ollama or vLLM, a request without a key is sent without anAuthorizationheader.OPENAI_BASE_URL: the API to talk to, by defaulthttps://api.openai.com/v1. Set it (e.g. tohttps://openrouter.ai/api/v1) to use another OpenAI-compatible provider. A trailing/or/chat/completionsis accepted. A key sent over plainhttp://(or with a URL without a scheme, which is sent ashttp://) to a host other thanlocalhost,127.0.0.1or::1gives a warning, once per host and session.OPENAI_MODEL: the default formodel.
Errors
chat_completion() never returns NULL. An HTTP error raises a condition
of class c("openair_api_error", "openair_error", "error", "condition")
with the fields status (integer), type, code and api_message, taken
from the error object of the JSON body when there is one, and a message
such as OpenAI API error 401 (invalid_api_key): Incorrect API key provided. A transport failure (no connection, DNS, timeout) raises
c("openair_network_error", "openair_error", "error", "condition") with
the original message (the original condition is in its parent field).
A response with status 200 that holds an error object instead of
choices (sent by some OpenAI-compatible providers) is an
openair_api_error too. A 2xx body that is not JSON raises
c("openair_invalid_response", "openair_error", "error", "condition"),
with the body in its body field.
Catch all of them with tryCatch(..., openair_error = function(e) ...).
Timeout and retries
The request is sent with httr2::req_perform(). A response with status
429 (rate limit) or 5xx, or a transport failure, is retried with
exponential backoff (1 s, 2 s, 4 s, ..., at most 30 s between tries). A
Retry-After header, in seconds or as an HTTP date, sets the wait instead,
up to 60 s. Other errors (400, 401, 403, 404, 422, ...) are not retried.
Two options control this:
options(TheOpenAIR.max_tries = 3): the number of tries in total (1 disables retrying), a positive whole number.options(TheOpenAIR.timeout = 120): the time limit in seconds for each try, a positive number.
Any other value stops before the request.
The API key is sent with httr2::req_auth_bearer_token(), so it is
redacted when a request is printed.
Streaming (stream = TRUE) is not supported yet.
See also
https://developers.openai.com/api/reference/overview for more information on the OpenAI API.
Examples
if (FALSE) { # \dontrun{
# needs an API key, see openai_api_key()
msgs_df <- data.frame(
role = c(
"system",
"user",
"assistant",
"user"
),
content = c(
"You are a helpful assistant",
"Who won the world series in 2020?",
"The Los Angeles Dodgers won the World Series in 2020.",
"Where was it played?"
)
)
chat_completion(msgs_df)
# JSON output following a schema (structured outputs)
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 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)
# a field this function has no argument for
chat_completion("Hi", extra_body = list(service_tier = "flex"))
} # }
