tests/testthat/test-code-mode.R

library(testthat)
library(mini007)

# QueueChat is defined in helper-queue-chat.R.

population <- ellmer::tool(
  function(wilaya, year = 2008) c(Oran = 1584607, Annaba = 609499)[[wilaya]],
  name = "wilaya_population",
  description = "Population of an Algerian wilaya.",
  arguments = list(
    wilaya = ellmer::type_string("The wilaya, eg. 'Oran'."),
    year = ellmer::type_integer("The census year.", required = FALSE)
  )
)

new_agent <- function() {
  suppressMessages(Agent$new("analyst", "You answer questions about wilayas.", QueueChat$new()))
}

# ── run_r_code() ──────────────────────────────────────────────────────────────

test_that("run_r_code() returns what the code prints, like the console", {
  env <- new.env()
  out <- run_r_code("x <- c(3, 1, 2); sort(x); invisible(9); message('sorted')", env, 5)
  expect_match(out, "[1] 1 2 3", fixed = TRUE)
  expect_match(out, "sorted", fixed = TRUE)
  expect_false(grepl("9", out))
  expect_equal(env$x, c(3, 1, 2))
})

test_that("run_r_code() reports warnings and says when nothing was printed", {
  env <- new.env()
  expect_match(run_r_code("as.integer('Oran')", env, 5), "Warning: NAs introduced", fixed = TRUE)
  expect_equal(run_r_code("y <- 1", env, 5), "(The code ran and printed nothing.)")
})

test_that("run_r_code() raises errors with the output printed before them", {
  env <- new.env()
  expect_error(run_r_code("print('Tlemcen'); stop('no data')", env, 5),
               "Output before the error:\n[1] \"Tlemcen\"\n\nError: no data", fixed = TRUE)
  expect_error(run_r_code("x <- (", env, 5), "unexpected end of input")
})

test_that("run_r_code() stops code that runs too long", {
  expect_error(run_r_code("repeat { z <- 1 }", new.env(), 0.5),
               "ran for more than 0.5 seconds and was stopped", fixed = TRUE)
  expect_error(run_r_code("repeat { z <- 1 }", new.env(), 1), "1 second and", fixed = TRUE)
  # The time limit is lifted afterwards.
  expect_equal(run_r_code("Sys.sleep(0.6); 'done'", new.env(), 5), "[1] \"done\"")
})

test_that("run_r_code() cuts long output", {
  out <- run_r_code("cat(strrep('a', 100))", new.env(), 5, max_chars = 40L)
  expect_match(out, "output cut", fixed = TRUE)
  expect_lt(nchar(out), 120L)
})

# ── code_tool() ───────────────────────────────────────────────────────────────

test_that("code_tool() makes the tools callable from the code, and keeps variables", {
  env <- new.env(parent = globalenv())
  tool <- code_tool(list(population), env, 5)
  expect_equal(tool@name, "run_r_code")
  expect_match(tool@description, "wilaya_population(wilaya, year = 2008): Population of an Algerian wilaya.", fixed = TRUE)
  expect_match(tool@description, "wilaya: The wilaya, eg. 'Oran'.", fixed = TRUE)
  expect_match(tool@description, "stopped after 5 seconds", fixed = TRUE)

  out <- tool("total <- wilaya_population('Oran') + wilaya_population('Annaba'); total")
  expect_match(out, "2194106", fixed = TRUE)
  expect_match(tool("total * 2"), "4388212", fixed = TRUE)
  expect_false(exists("total", envir = globalenv(), inherits = FALSE))
})

test_that("code_tool() without tools runs plain R code", {
  tool <- code_tool(list(), new.env(), 5)
  expect_false(grepl("Functions you can call", tool@description, fixed = TRUE))
  expect_match(tool("nchar('Ghardaia')"), "8", fixed = TRUE)
})

# ── Agent$set_code_mode() ─────────────────────────────────────────────────────

test_that("set_code_mode() swaps the tools for run_r_code and back", {
  agent <- new_agent()
  suppressMessages(agent$register_tools(list(population)))
  expect_equal(names(agent$llm_object$tools), "wilaya_population")

  expect_message(agent$set_code_mode(timeout = 10), "code mode on")
  expect_equal(names(agent$llm_object$tools), "run_r_code")
  expect_equal(agent$code_mode, list(enabled = TRUE, timeout = 10))
  # Registered tools still list as the agent's tools.
  expect_equal(agent$list_tools(), "wilaya_population")

  # A tool registered later is callable from the code too.
  later <- ellmer::tool(function() "ok", name = "ping", description = "Ping.")
  suppressMessages(agent$register_tools(list(later)))
  expect_match(agent$llm_object$tools$run_r_code@description, "- ping(): Ping.", fixed = TRUE)

  expect_message(agent$set_code_mode(FALSE), "code mode off")
  expect_setequal(names(agent$llm_object$tools), c("wilaya_population", "ping"))
})

test_that("set_code_mode() runs the code in the environment given, kept across changes", {
  env <- new.env()
  agent <- new_agent()
  suppressMessages(agent$set_code_mode(envir = env))
  agent$llm_object$tools$run_r_code("visited <- 'Biskra'")
  expect_equal(env$visited, "Biskra")

  suppressMessages(agent$register_tools(list(population)))
  agent$llm_object$tools$run_r_code("visited <- c(visited, 'Oran')")
  expect_equal(env$visited, c("Biskra", "Oran"))
  expect_true(is.function(env$wilaya_population))
})

test_that("set_code_mode() checks its arguments", {
  agent <- new_agent()
  expect_error(agent$set_code_mode("yes"))
  expect_error(agent$set_code_mode(timeout = 0))
  expect_error(agent$set_code_mode(envir = list()))
})

test_that("removed tools are taken away from the LLM", {
  agent <- new_agent()
  suppressMessages(agent$register_tools(list(population)))
  suppressMessages(agent$remove_tools("wilaya_population"))
  expect_length(agent$llm_object$tools, 0L)
})

test_that("code mode adds its paragraph to the system prompt, and keeps it", {
  agent <- new_agent()
  role <- "You answer questions about wilayas."
  suppressMessages(agent$set_code_mode())
  expect_match(agent$llm_object$get_system_prompt(), "Code mode: you act by writing R code", fixed = TRUE)
  expect_true(startsWith(agent$llm_object$get_system_prompt(), role))
  expect_equal(agent$messages[[1]]$content, agent$llm_object$get_system_prompt())

  suppressMessages(agent$update_instruction("You answer questions about the Sahara."))
  expect_match(agent$llm_object$get_system_prompt(), "^You answer questions about the Sahara.\n\nCode mode:")

  suppressMessages(agent$set_code_mode(FALSE))
  expect_equal(agent$llm_object$get_system_prompt(), "You answer questions about the Sahara.")
  expect_equal(agent$messages[[1]]$content, "You answer questions about the Sahara.")
})

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.