R/code_mode.R

Defines functions run_r_code code_tool_signature code_tool_description code_tool strip_code_mode_prompt

# Code mode: instead of calling its tools one at a time, the LLM writes one R
# script that calls them as R functions and combines their results (loops,
# conditions, data frames). One tool call can then do the work of many, which
# saves round trips and tokens. Turned on with Agent$set_code_mode().

# Added to the system prompt while code mode is on: without it, models tend
# to make one run_r_code call per item, as they would with plain tools.
code_mode_prompt <- paste0(
  "\n\nCode mode: you act by writing R code with the run_r_code tool. Its ",
  "functions are your tools: call them from the code. Do the whole task in ",
  "one run_r_code call when you can (loop over the items, then combine and ",
  "print the results), instead of one call per item. Make another call only ",
  "to fix an error or to use what the first call printed."
)

strip_code_mode_prompt <- function(prompt) {
  if (endsWith(prompt, code_mode_prompt)) {
    substr(prompt, 1L, nchar(prompt) - nchar(code_mode_prompt))
  } else {
    prompt
  }
}

# The `run_r_code` tool. `tools` are the agent's tools, callable in the code
# under their own names; `envir` is where the code runs, kept between calls so
# that variables persist; `timeout` is the time limit of one call, in seconds.
code_tool <- function(tools, envir, timeout) {
  force(envir)
  force(timeout)
  for (tool in tools) assign(tool@name, tool, envir = envir)

  run <- function(code) run_r_code(code, envir, timeout)

  ellmer::tool(
    run,
    name = "run_r_code",
    description = code_tool_description(tools, timeout),
    arguments = list(
      code = ellmer::type_string("The R code to run.")
    )
  )
}

code_tool_description <- function(tools, timeout) {
  functions <- ""
  example <- ""
  if (length(tools)) {
    functions <- paste0(
      "\n\nFunctions you can call in the code:\n",
      paste(vapply(tools, code_tool_signature, character(1)), collapse = "\n")
    )
    example <- paste0(
      " For example, to use ", tools[[1]]@name, " on several items, loop over ",
      "them in one call, eg. `results <- lapply(items, function(x) ",
      tools[[1]]@name, "(x))`, then compute and print the answer from `results`."
    )
  }
  paste0(
    "Run R code in a persistent R session and get back what it prints. ",
    "Do all the work in as few calls as possible, ideally one: call the ",
    "functions below from the code, like any R function, and combine their ",
    "results with R (loops, conditions, vectors, data frames). Never make one ",
    "run_r_code call per function call.", example, " ",
    "Variables are kept between calls. The printed output and the value of ",
    "the last expression are returned: print() what you need to see. A call ",
    "is stopped after ", timeout, " seconds.",
    functions
  )
}

# "- name(arg1, arg2 = 2): description" followed by the arguments.
code_tool_signature <- function(tool) {
  args <- tryCatch(tool@arguments@properties, error = function(e) list())
  defaults <- formals(tool)
  shown <- vapply(names(args), function(arg) {
    # A formal without a default is the empty symbol, which cannot be
    # stored in a variable: test it in place.
    if (!arg %in% names(defaults) || identical(defaults[[arg]], quote(expr = ))) {
      return(arg)
    }
    paste(arg, "=", paste(deparse(defaults[[arg]]), collapse = " "))
  }, character(1))
  line <- paste0("- ", tool@name, "(", paste(shown, collapse = ", "), "): ",
                 tool_description(tool))
  details <- vapply(names(args), function(arg) {
    description <- tryCatch(args[[arg]]@description, error = function(e) NULL)
    if (!is.character(description) || !length(description) || !nzchar(description)) return("")
    paste0("    ", arg, ": ", one_line(description))
  }, character(1))
  details <- details[nzchar(details)]
  paste(c(line, details), collapse = "\n")
}

# Runs `code` in `envir`, like the console would: each expression in turn,
# printing the visible values. Returns the printed output, messages and
# warnings as one string. An error stops the code: it is raised with the
# output printed so far, so that the LLM sees both and can fix the code.
run_r_code <- function(code, envir, timeout, max_chars = 8000L) {
  output <- character()
  con <- textConnection("output", "w", local = TRUE)
  sink(con)
  sink_open <- TRUE
  close_sink <- function() {
    if (sink_open) {
      sink()
      close(con)
      sink_open <<- FALSE
    }
  }
  on.exit(close_sink(), add = TRUE)

  notes <- character()
  error <- NULL

  setTimeLimit(elapsed = timeout, transient = TRUE)
  on.exit(setTimeLimit(elapsed = Inf), add = TRUE)

  tryCatch(
    withCallingHandlers(
      {
        exprs <- parse(text = code, keep.source = FALSE)
        for (expr in exprs) {
          res <- withVisible(eval(expr, envir))
          if (res$visible) print(res$value)
        }
      },
      message = function(m) {
        cat(conditionMessage(m))
        invokeRestart("muffleMessage")
      },
      warning = function(w) {
        cat("Warning:", conditionMessage(w), "\n")
        invokeRestart("muffleWarning")
      }
    ),
    error = function(e) {
      message <- conditionMessage(e)
      if (grepl("elapsed time limit", message, fixed = TRUE)) {
        message <- sprintf("The code ran for more than %s second%s and was stopped.",
                           timeout, if (timeout == 1) "" else "s")
      }
      error <<- message
    }
  )
  setTimeLimit(elapsed = Inf)
  close_sink()

  text <- paste(output, collapse = "\n")
  if (nchar(text) > max_chars) {
    text <- paste0(substr(text, 1L, max_chars),
                   "\n[... output cut: print less, or summarise it in the code]")
  }
  if (!is.null(error)) {
    stop(paste0(
      if (nzchar(text)) paste0("Output before the error:\n", text, "\n\n") else "",
      "Error: ", error
    ), call. = FALSE)
  }
  if (!nzchar(text)) "(The code ran and printed nothing.)" else text
}

Try the mini007 package in your browser

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

mini007 documentation built on Dec. 3, 2026, 5:10 p.m.