tests/testthat/test-ask-human.R

library(testthat)
library(mini007)

# ── Helpers ───────────────────────────────────────────────────────────────────

setClass("Provider", slots = c(name = "character", model = "character"))

# A chat that plays a scripted tool loop the way ellmer does: each $chat()
# plays assistant turns from `script` until one has no tool request; the
# registered tools really run and their results form the next user turn.
ScriptedChat <- R6::R6Class(
  "Chat",
  public = list(
    system_prompt = "", turns = list(), tools = list(), provider = NULL,
    script = NULL, position = 0L,
    initialize = function(script) {
      self$script <- script
      self$provider <- new("Provider", name = "dummy", model = "v0")
    },
    chat = function(prompt) {
      user <- ellmer::Turn("user", list(ellmer::ContentText(prompt)))
      repeat {
        self$position <- self$position + 1L
        assistant <- ellmer::Turn("assistant", self$script[[self$position]])
        self$turns <- c(self$turns, list(user, assistant))
        requests <- Filter(function(ct) inherits(ct, "ellmer::ContentToolRequest"), assistant@contents)
        if (length(requests) == 0) break
        results <- lapply(requests, function(request) {
          tryCatch(
            ellmer::ContentToolResult(
              value = do.call(self$tools[[request@name]], request@arguments),
              request = request
            ),
            error = function(e) ellmer::ContentToolResult(error = e, request = request)
          )
        })
        user <- ellmer::Turn("user", results)
      }
      assistant@text
    },
    get_cost = function(include = "all") NA_real_,
    set_system_prompt = function(value) { self$system_prompt <- value },
    get_system_prompt = function() self$system_prompt,
    set_turns = function(turns) {
      self$turns <- Filter(function(turn) !identical(turn@role, "system"), turns)
    },
    get_turns = function(include_system_prompt = FALSE) {
      if (!include_system_prompt) return(self$turns)
      c(list(ellmer::Turn("system", list(ellmer::ContentText(self$system_prompt)))), self$turns)
    },
    on_tool_request = function(callback) invisible(function() invisible()),
    register_tools = function(tools) {
      for (tool in tools) self$tools[[tool@name]] <- tool
    },
    get_tools = function() self$tools,
    set_tools = function(tools) { self$tools <- tools },
    get_provider = function() self$provider
  )
)

ask_call <- function(id, question, options = NULL) {
  arguments <- list(question = question)
  if (!is.null(options)) arguments$options <- options
  ellmer::ContentToolRequest(id = id, name = "ask_user", arguments = arguments)
}

# An `ask` function that records what it was asked and gives set answers.
recorder <- function(answers) {
  asked <- new.env()
  asked$questions <- list()
  ask <- function(question, options) {
    asked$questions[[length(asked$questions) + 1L]] <- list(question = question, options = options)
    answers[[length(asked$questions)]]
  }
  list(ask = ask, asked = asked)
}

# ── The tool ──────────────────────────────────────────────────────────────────

test_that("ask_human_tool() makes a tool with a question and optional options", {
  tool <- ask_human_tool(ask = function(question, options) "yes")
  expect_true(inherits(tool, "ellmer::ToolDef"))
  expect_equal(tool@name, "ask_user")
  expect_named(tool@arguments@properties, c("question", "options"))
  expect_false(tool@arguments@properties$options@required)
  expect_match(tool@description, "cannot go on without the user's input")

  custom <- ask_human_tool(ask = function(q, o) "x", name = "ask traveller", description = "Ask the traveller.")
  expect_equal(custom@name, "ask_traveller")
  expect_equal(custom@description, "Ask the traveller.")
})

test_that("the question and options are passed to ask, and its answer returned", {
  r <- recorder(list("History.", "Small."))
  tool <- ask_human_tool(ask = r$ask)
  answer <- tool(question = "Beaches or history?", options = list("Beaches", "History"))
  expect_equal(answer, "History.")
  expect_equal(r$asked$questions[[1]]$question, "Beaches or history?")
  expect_equal(r$asked$questions[[1]]$options, c("Beaches", "History"))

  # Without options, ask gets an empty character vector.
  tool(question = "Your budget?")
  expect_identical(r$asked$questions[[2]]$options, character())
})

test_that("an empty answer tells the agent to decide on its own", {
  tool <- ask_human_tool(ask = function(question, options) "   ")
  expect_match(tool(question = "Budget?"), "The user gave no answer. Decide on your own")
})

test_that("answers that are not a single string are pasted together", {
  tool <- ask_human_tool(ask = function(question, options) c("Oran", "Tlemcen"))
  expect_equal(tool(question = "Which cities?"), "Oran\nTlemcen")
})

test_that("without ask, a non-interactive session tells the agent no one can answer", {
  skip_if(interactive())
  tool <- ask_human_tool()
  expect_match(tool(question = "Budget?"), "No one can answer questions in this session")
})

test_that("ask must be a function", {
  expect_error(ask_human_tool(ask = "console"))
})

# ── In a ReActAgent ───────────────────────────────────────────────────────────

test_that("a ReActAgent asks the user mid-run and uses the answer", {
  r <- recorder(list("History, on a small budget."))
  planner <- ReActAgent$new(
    "planner", "You plan trips in Algeria.",
    ScriptedChat$new(list(
      list(ask_call("1", "Beaches or history?", list("Beaches", "History"))),
      list(ellmer::ContentText("Visit the Santa Cruz fort, then the old town."))
    )),
    tools = list(ask_human_tool(ask = r$ask))
  )

  answer <- suppressMessages(planner$invoke("Plan a weekend in Oran."))
  expect_equal(answer, "Visit the Santa Cruz fort, then the old town.")
  expect_equal(r$asked$questions[[1]]$question, "Beaches or history?")

  observed <- planner$trace[planner$trace$type == "observe", ]
  expect_equal(observed$tool, "ask_user")
  expect_equal(observed$content, "History, on a small budget.")
})

test_that("when no one can answer, the agent is told and carries on", {
  skip_if(interactive())
  planner <- ReActAgent$new(
    "planner", "You plan trips in Algeria.",
    ScriptedChat$new(list(
      list(ask_call("1", "Beaches or history?")),
      list(ellmer::ContentText("I assumed you like history."))
    )),
    tools = list(ask_human_tool())
  )
  answer <- suppressMessages(planner$invoke("Plan a weekend in Oran."))
  expect_equal(answer, "I assumed you like history.")
  observed <- planner$trace[planner$trace$type == "observe", ]
  expect_false(observed$is_error)
  expect_match(observed$content, "No one can answer")
})

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.