tests/testthat/test-as-tool.R

library(testthat)
library(mini007)

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

setClass("Provider", slots = c(name = "character", model = "character"))
token_provider <- function() new("Provider", name = "tokenco", model = "token-model")

# Every assistant turn uses 1000 input and 500 output tokens: with the price
# registered by local_token_price() (US$1 per million), 0.0015 per turn.
assistant_turn <- function(contents) {
  ellmer::Turn("assistant", contents, tokens = c(1000, 500, 0))
}

# An expert: answers "<name> says: <prompt>", or fails when `fail` is set.
ExpertChat <- R6::R6Class(
  "Chat",
  public = list(
    system_prompt = "", turns = list(), tools = list(), provider = NULL,
    label = NULL, fail = FALSE,
    initialize = function(label) {
      self$label <- label
      self$provider <- token_provider()
    },
    chat = function(prompt) {
      if (isTRUE(self$fail)) stop("expert unavailable")
      answer <- paste(self$label, "says:", prompt)
      self$turns <- c(self$turns, list(
        ellmer::Turn("user", list(ellmer::ContentText(prompt))),
        assistant_turn(list(ellmer::ContentText(answer)))
      ))
      answer
    },
    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)
    },
    register_tools = function(tools) { self$tools <- tools },
    get_tools = function() self$tools,
    set_tools = function(tools) { self$tools <- tools },
    get_provider = function() self$provider
  )
)

# A caller 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",
  inherit = ExpertChat,
  public = list(
    script = NULL, position = 0L,
    initialize = function(script) {
      super$initialize("caller")
      self$script <- script
    },
    chat = function(prompt) {
      user <- ellmer::Turn("user", list(ellmer::ContentText(prompt)))
      repeat {
        self$position <- self$position + 1L
        assistant <- assistant_turn(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
    },
    on_tool_request = function(callback) invisible(function() invisible()),
    register_tools = function(tools) {
      for (tool in tools) self$tools[[tool@name]] <- tool
    }
  )
)

local_token_price <- function(env = parent.frame()) {
  clear_prices()
  set_prices("token-model", input = 1, output = 1, provider = "tokenco")
  do.call(on.exit, list(quote(mini007::clear_prices()), add = TRUE), envir = env)
}

expert <- function(name, budget = NA) {
  Agent$new(name, paste("You are an expert on", name, "."), ExpertChat$new(name), budget = budget)
}

ask <- function(id, tool, request) {
  ellmer::ContentToolRequest(id = id, name = tool, arguments = list(request = request))
}

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

test_that("as_tool() makes an ellmer tool that takes a request", {
  historian <- expert("historian")
  tool <- historian$as_tool("Answers questions about Algerian history.")
  expect_true(inherits(tool, "ellmer::ToolDef"))
  expect_equal(tool@name, "historian")
  expect_equal(tool@description, "Answers questions about Algerian history.")
  expect_named(tool@arguments@properties, "request")
})

test_that("the name is made valid and the description has a default", {
  agent <- Agent$new("Heritage guide (Oran)", "You know Oran's monuments.", ExpertChat$new("g"))
  tool <- agent$as_tool()
  expect_equal(tool@name, "Heritage_guide_Oran")
  expect_match(tool@description, "Heritage guide (Oran)", fixed = TRUE)
  expect_match(tool@description, "You know Oran's monuments.", fixed = TRUE)
  expect_equal(agent$as_tool(name = "oran")@name, "oran")
})

test_that("calling the tool invokes the agent, which keeps its history", {
  historian <- expert("historian")
  tool <- historian$as_tool("History.")
  expect_equal(tool(request = "Who founded Timgad?"), "historian says: Who founded Timgad?")
  tool(request = "When?")
  expect_length(historian$messages, 5)
})

test_that("with fresh = TRUE the agent forgets the earlier requests", {
  historian <- expert("historian")
  tool <- historian$as_tool("History.", fresh = TRUE)
  tool(request = "Who founded Timgad?")
  tool(request = "When?")
  expect_length(historian$messages, 3)
  expect_equal(historian$messages[[2]]$content, "When?")
})

test_that("a ReActAgent calls agents as tools, and each keeps its own cost", {
  local_token_price()
  historian <- expert("historian")
  geographer <- expert("geographer")
  guide <- ReActAgent$new(
    "guide", "You plan trips in Algeria.",
    ScriptedChat$new(list(
      list(
        ask("1", "historian", "Who founded Constantine?"),
        ask("2", "geographer", "Where is Constantine?")
      ),
      list(ellmer::ContentText("Visit Constantine, an ancient city in the east."))
    )),
    tools = list(historian$as_tool("History."), geographer$as_tool("Geography."))
  )

  answer <- suppressMessages(guide$invoke("Plan a day in Constantine."))
  expect_equal(answer, "Visit Constantine, an ancient city in the east.")

  observed <- guide$trace[guide$trace$type == "observe", ]
  expect_equal(observed$tool, c("historian", "geographer"))
  expect_equal(observed$content[[1]], "historian says: Who founded Constantine?")

  expect_equal(historian$cost, 0.0015)
  expect_equal(geographer$cost, 0.0015)
  # The guide's two turns, without the experts' calls.
  expect_equal(guide$cost, 0.003)
})

test_that("a failing agent is reported to the caller, which carries on", {
  local_token_price()
  historian <- expert("historian", budget = 0.001)
  historian$invoke("warm up")
  guide <- ReActAgent$new(
    "guide", "You plan trips in Algeria.",
    ScriptedChat$new(list(
      list(ask("1", "historian", "Who founded Constantine?")),
      list(ellmer::ContentText("I could not reach the historian."))
    )),
    tools = list(historian$as_tool("History."))
  )
  answer <- suppressMessages(guide$invoke("Plan a day in Constantine."))
  expect_equal(answer, "I could not reach the historian.")
  observed <- guide$trace[guide$trace$type == "observe", ]
  expect_true(observed$is_error)
  expect_match(observed$content, "exceeded its budget")
})

# ── Other classes ─────────────────────────────────────────────────────────────

test_that("a LeadAgent and a RouterAgent describe their team by default", {
  lead <- LeadAgent$new("lead", ExpertChat$new("lead"))
  suppressMessages(lead$register_agents(list(expert("historian"), expert("geographer"))))
  expect_match(lead$as_tool()@description, "(historian, geographer)", fixed = TRUE)

  router <- RouterAgent$new("desk", ExpertChat$new("desk"))
  suppressMessages(router$register_agents(list(expert("historian"))))
  expect_match(router$as_tool()@description, "among: historian", fixed = TRUE)
})

test_that("a ReActAgent's default description uses its role", {
  agent <- ReActAgent$new("coder", "You look up wilaya codes.", ExpertChat$new("c"),
                          tools = list(expert("historian")$as_tool("History.")))
  expect_match(agent$as_tool()@description, "Its role: You look up wilaya codes.$")
})

test_that("a WorkflowAgent can be used as a tool", {
  wf <- Workflow$new("pipeline", use_cache = FALSE)
  suppressMessages({
    wf$add_station("upper", function(x) toupper(x))
    wf$add_station("exclaim", function(x) paste0(x, "!"))
    wf$add_route("upper", "exclaim")
  })
  tool <- wf$as_agent("shouter", "Shouts the input.")$as_tool()
  expect_equal(tool@name, "shouter")
  expect_match(tool@description, "Shouts the input.", fixed = TRUE)
  expect_equal(suppressMessages(tool(request = "oran")), "ORAN!")
})

# ── Parallel runs ─────────────────────────────────────────────────────────────

test_that("agents used as tools are found for parallel runs", {
  historian <- expert("historian")
  guide <- ReActAgent$new("guide", "You plan trips.", ExpertChat$new("guide"),
                          tools = list(historian$as_tool("History.")))
  found <- getFromNamespace("find_agents", "mini007")(guide)
  expect_setequal(names(found), c(guide$agent_id, historian$agent_id))
})

test_that("an agent called as a tool in a parallel station gets its cost back", {
  skip_on_cran()
  local_token_price()
  historian <- expert("historian")
  guide <- ReActAgent$new(
    "guide", "You plan trips in Algeria.",
    ScriptedChat$new(list(
      list(ask("1", "historian", "Who founded Constantine?")),
      list(ellmer::ContentText("Done."))
    )),
    tools = list(historian$as_tool("History."))
  )
  wf <- Workflow$new("W", use_cache = FALSE)
  suppressMessages({
    wf$add_station("start", identity)
    wf$add_station("guide", guide)
    wf$add_station("other", function(x) "ok")
    wf$set_daemons(2)
    wf$add_parallel_group("start", c("guide", "other"))
  })
  on.exit(suppressMessages(wf$set_daemons(0)), add = TRUE)

  suppressMessages(wf$run("Constantine"))
  expect_equal(historian$cost, 0.0015)
  expect_length(historian$messages, 3)
  expect_equal(guide$cost, 0.003)
})

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.