R/lang-use.R

Defines functions lang_use_impl lang_use

Documented in lang_use

#' Specifies the LLM provider and model to use during the R session
#' @description
#' Specifies the back-end provider and model to use during the current
#' R session. The target language is not processed by the function, as in
#' converting "english" to "en" for example. The value is passed directly to
#' the LLM, and it lets the LLM interpret the target language.
#' @param backend "ollama" or an `ellmer` `Chat` object. If using "ollama",
#' `lang` provides built-in support via the `ollamar` package. Defaults to
#' "ollama".
#' @param model The name of model supported by the back-end provider
#' @param ... Additional arguments that this function will pass down to the
#' integrating function. In the case of Ollama, it will pass those arguments to
#' `ollamar::chat()`.
#' @param .cache Character path where translations are cached. Set to `""` to
#' disable caching. When `NULL`, the current session value is kept unchanged.
#' Defaults to a temporary folder.
#' @param .lang Target language to translate to. This will override values found
#' in the LANG and LANGUAGE environment variables.
#' @param .context_size Maximum number of words for the context summary
#' included with each translation request. Set to `0` to disable context-aware
#' translation. Defaults to `100`.
#' @param .silent Boolean flag that controls whether there is output to the
#' console. Defaults to FALSE.
#' @returns Invisibly returns `NULL`. Prints the current configuration to the
#' console.
#'
#' @examples
#' \dontrun{
#' # Requires an interactive session with Ollama or another LLM provider
#' library(lang)
#'
#' # Using an `ellmer` chat object
#' lang_use(ellmer::chat_openai(model = "gpt-4o"))
#'
#' # Using Ollama directly
#' lang_use("ollama", "llama3.2", seed = 100)
#'
#' # Turn off cache by setting `.cache` to ""
#' lang_use("ollama", "llama3.2", seed = 100, .cache = "")
#'
#' # Use `.lang` to set the target language to translate to,
#' # it will be set for the current R session
#' lang_use("ollama", "llama3.2", .lang = "spanish")
#'
#' # Use `.silent` to avoid console output
#' lang_use("ollama", "llama3.2", .lang = "spanish", .silent = TRUE)
#'
#' # To see current settings, simply call the function
#' lang_use()
#' }
#'
#' @export
lang_use <- function(
  backend = NULL,
  model = NULL,
  .cache = NULL,
  .lang = NULL,
  .context_size = NULL,
  .silent = FALSE,
  ...
) {
  lang_use_impl(
    backend = backend,
    model = model,
    .cache = .cache,
    .is_internal = FALSE,
    .lang = .lang,
    .context_size = .context_size,
    .silent = .silent,
    ... = ...
  )
}

lang_use_impl <- function(
  backend = NULL,
  model = NULL,
  .cache = NULL,
  .is_internal = FALSE,
  .lang = NULL,
  .context_size = NULL,
  .silent = FALSE,
  ...
) {
  args <- list(...)
  ca <- .lang_env$session
  if (!.is_internal && !is.null(getOption(".lang_chat"))) {
    cli_warn(c(
      "Option `.lang_chat` is no longer supported",
      "Use `lang::lang_use([backend])` in your .RProfile file instead"
    ))
  }
  ca[["backend"]] <- backend %||% ca[["backend"]]
  ca[["model"]] <- model %||% ca[["model"]]
  temp_lang <- tempfile("_lang_cache")
  ca[[".cache"]] <- .cache %||% ca[[".cache"]] %||% temp_lang
  ca[[".lang"]] <- .lang %||% ca[[".lang"]]
  ca[["context_size"]] <- .context_size %||% ca[["context_size"]] %||% 100L
  if (length(args) > 0) {
    ca[["args"]] <- args
  }
  .lang_env$session <- ca
  backend_str <- NULL
  model_str <- NULL
  if (.is_internal) {
    return(ca)
  }
  # Pre-warm the subprocess for string backends (e.g. "ollama", "simulate_llm").
  # Chat objects are skipped: they can't be serialized to the subprocess and
  # will be configured lazily on the first help() call via lang_rs_get().
  if (!is.null(ca[["backend"]]) && !inherits(ca[["backend"]], "Chat")) {
    rs <- .lang_env$rs
    if (!is.null(rs) && rs$is_alive()) {
      if (rs$get_state() == "starting") {
        rs$poll_process(10000L)
      }
      if (rs$get_state() == "idle") {
        lang_rs_refresh(rs)
        .lang_env$rs_hash <- lang_rs_hash()
      }
    } else {
      lang_rs_get()
    }
  }
  if (!.silent) {
    backend <- ca[["backend"]]
    if (inherits(backend, "Chat")) {
      provider <- backend$get_provider()
      backend_str <- provider@name
      model_str <- provider@model
    } else {
      if (is.null(backend)) {
        backend_str <- NULL
      } else if (backend == "ollama") {
        backend_str <- "Ollama"
      } else {
        backend_str <- backend
      }
      model_str <- ca[["model"]]
    }
    if (ca[[".cache"]] == "") {
      cache_str <- "[Disabled]"
    } else {
      cache_str <- ca[[".cache"]]
    }
    current_lang <- which_lang(.lang, choose = TRUE)
    if (!is.null(model_str) && !is.null(backend_str)) {
      cli_inform("{.field Model:} {model_str} {.field via} {backend_str}")
    } else {
      cli_inform("{.field Model not set}")
    }
    cli_inform("{.field Lang: } {current_lang}")
    if (path_dir(ca[[".cache"]]) != path_dir(temp_lang)) {
      cli_inform("{.field Cache:} {cache_str}")
    }
  }
  invisible()
}

Try the lang package in your browser

Any scripts or data that you put into this service are public.

lang documentation built on June 5, 2026, 5:08 p.m.