Reference an API key by the name of the environment variable that holds it,
so the secret never appears in your R code or saved objects. Store the key in
your shell profile or in ~/.Renviron (e.g. OPENAI_API_KEY=sk-...).
Arguments
- var
Name of the environment variable (e.g., "OPENAI_API_KEY"). A character vector is also accepted; the variables are tried in order and the first one that is set wins, which is convenient when a key may live under more than one name (e.g.,
c("GROQ_API_KEY", "GROQ_KEY")).- required
If TRUE, a missing variable raises an authentication error at call time. If FALSE, a missing variable resolves to an empty key, which is appropriate for providers that do not require authentication (e.g., a local Ollama server).
- default
Optional default used if the environment variable is not set.
Value
A secret handle to pass as api_key = llm_api_key_env("VARNAME") in
llm_config().
Details
Best practice is to not pass a key explicitly at all: llm_config() already
looks up the standard variable for each provider (<PROVIDER>_API_KEY, then
<PROVIDER>_KEY). Use llm_api_key_env() only when your variable has a
non-standard name.
Examples
cfg <- llm_config(
"openai", "gpt-4o-mini",
api_key = llm_api_key_env("MY_OPENAI_KEY")
)