tests/testthat/test-cost-and-parallel.R

library(testthat)
library(mini007)

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

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

# A chat whose every reply uses 1000 input and 500 output tokens. With the
# price registered below (US$1 per million tokens), each call costs 0.0015.
TokenChat <- R6::R6Class(
  "Chat",
  public = list(
    system_prompt = "",
    turns = list(),
    tools = list(),
    provider = NULL,
    fail = FALSE,
    initialize = function(model = "token-model") {
      self$provider <- new("Provider", name = "tokenco", model = model)
    },
    chat = function(prompt) {
      if (isTRUE(self$fail)) stop("provider down")
      answer <- paste("Answer to:", prompt)
      self$turns <- c(self$turns, list(
        ellmer::Turn("user", list(ellmer::ContentText(prompt))),
        ellmer::Turn("assistant", list(ellmer::ContentText(answer)), tokens = c(1000, 500, 0))
      ))
      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 },
    set_tools = function(tools) { self$tools <- tools },
    get_provider = function() self$provider
  )
)

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)
}

token_agent <- function(name = "a", budget = NA) {
  Agent$new(name, "Answer briefly.", TokenChat$new(), budget = budget)
}

# ── Cost ──────────────────────────────────────────────────────────────────────

test_that("the cost keeps full precision", {
  local_token_price()
  agent <- token_agent()
  agent$invoke("hi")
  expect_equal(agent$cost, 0.0015)
  set_prices("token-model", input = 0.01, output = 0.01, provider = "tokenco")
  agent$invoke("again")
  expect_equal(agent$cost, 0.000030)
})

test_that("editing the history does not erase what was spent", {
  local_token_price()
  agent <- token_agent()
  agent$invoke("one")
  agent$invoke("two")
  expect_equal(agent$cost, 0.003)

  suppressMessages(agent$reset_conversation_history())
  expect_equal(agent$get_usage_stats()$estimated_cost, 0.003)

  agent$invoke("three")
  expect_equal(agent$cost, 0.0045)

  suppressMessages(agent$keep_last_n_messages(2))
  expect_equal(agent$get_usage_stats()$estimated_cost, 0.0045)

  agent$messages <- agent$messages[1]
  agent$invoke("four")
  expect_equal(agent$cost, 0.006)
})

test_that("resetting the history no longer bypasses the budget", {
  local_token_price()
  agent <- token_agent(budget = 0.004)
  agent$invoke("one")
  suppressMessages(agent$reset_conversation_history())
  agent$invoke("two")
  suppressMessages(agent$reset_conversation_history())
  agent$invoke("three")
  suppressMessages(agent$reset_conversation_history())
  expect_error(agent$invoke("four"), "exceeded its budget")
})

test_that("the warn_at notice is given once per budget", {
  local_token_price()
  agent <- token_agent(budget = 1)
  suppressMessages(agent$set_budget_policy("warn", warn_at = 0))
  notices <- 0
  count <- function(m) {
    if (grepl("nearing limit", conditionMessage(m))) notices <<- notices + 1
    invokeRestart("muffleMessage")
  }
  withCallingHandlers({
    agent$invoke("one"); agent$invoke("two"); agent$invoke("three")
  }, message = count)
  expect_equal(notices, 1)

  withCallingHandlers({
    agent$set_budget(2)
    agent$invoke("four")
  }, message = count)
  expect_equal(notices, 2)
})

test_that("the budget must be one non-negative number", {
  expect_error(Agent$new("a", "i", TokenChat$new(), budget = -1))
  expect_error(Agent$new("a", "i", TokenChat$new(), budget = c(1, 2)))
  expect_error(Agent$new("a", "i", TokenChat$new(), budget = "5"))
  expect_true(is.na(Agent$new("a", "i", TokenChat$new())$budget))
})

test_that("a LeadAgent takes a budget and enforces it on its own calls", {
  local_token_price()
  lead <- LeadAgent$new("lead", TokenChat$new(), budget = 0.001)
  expect_equal(lead$budget, 0.001)
  suppressMessages(lead$register_agents(list(token_agent("worker"))))

  # Spend past the budget, then planning is refused.
  lead$llm_object$chat("warm up")
  expect_error(suppressMessages(lead$generate_plan("Do something.")), "exceeded its budget")
  expect_equal(lead$cost, 0.0015)
})

# ── Parallel ──────────────────────────────────────────────────────────────────

test_that("daemons are shared: a second object resizes the pool instead of failing", {
  skip_on_cran()
  w1 <- Workflow$new("W1")
  w2 <- Workflow$new("W2")
  on.exit(suppressMessages(w2$set_daemons(0)), add = TRUE)

  suppressMessages(w1$set_daemons(2))
  expect_no_error(suppressMessages(w2$set_daemons(3)))
  expect_equal(mirai::status()$connections, 3L)

  suppressMessages(w1$set_daemons(0))
  expect_equal(mirai::status()$connections, 0L)
})

test_that("a failing parallel station fails the workflow with its error", {
  skip_on_cran()
  wf <- Workflow$new("W", use_cache = FALSE)
  suppressMessages({
    wf$add_station("start", identity)
    wf$add_station("ok", function(x) "fine")
    wf$add_station("boom", function(x) stop("station exploded"))
    wf$set_daemons(2)
    wf$add_parallel_group("start", c("ok", "boom"))
  })
  on.exit(suppressMessages(wf$set_daemons(0)), add = TRUE)

  err <- tryCatch(suppressMessages(wf$run("go")), error = function(e) e)
  expect_s3_class(err, "mini007_parallel_error")
  expect_match(conditionMessage(err), "boom: station exploded", fixed = TRUE)
})

test_that("agents run in parallel get their conversation and cost back", {
  skip_on_cran()
  local_token_price()
  historian <- token_agent("historian")
  writer <- token_agent("writer")
  make_handler <- function(agent) function(x) agent$invoke(paste("Write about", x))

  wf <- Workflow$new("W", use_cache = FALSE)
  suppressMessages({
    wf$add_station("start", identity)
    wf$add_station("history", historian)
    wf$add_station("writing", make_handler(writer))
    wf$set_daemons(2)
    wf$add_parallel_group("start", c("history", "writing"))
  })
  on.exit(suppressMessages(wf$set_daemons(0)), add = TRUE)

  out <- suppressMessages(wf$run("Timgad"))
  expect_match(out, "Answer to: Timgad", fixed = TRUE)
  expect_match(out, "Answer to: Write about Timgad", fixed = TRUE)

  expect_length(historian$messages, 3)
  expect_equal(historian$cost, 0.0015)
  expect_length(writer$messages, 3)
  expect_equal(writer$cost, 0.0015)

  suppressMessages(wf$run("Djemila"))
  expect_length(historian$messages, 5)
  expect_equal(historian$cost, 0.003)
})

test_that("an agent's spend in a failed parallel station is kept", {
  skip_on_cran()
  local_token_price()
  spender <- token_agent("spender")
  wf <- Workflow$new("W", use_cache = FALSE)
  suppressMessages({
    wf$add_station("start", identity)
    wf$add_station("spend", function(x) { spender$invoke(x); stop("failed after paying") })
    wf$add_station("other", function(x) "ok")
    wf$set_daemons(2)
    wf$add_parallel_group("start", c("spend", "other"))
  })
  on.exit(suppressMessages(wf$set_daemons(0)), add = TRUE)

  expect_error(suppressMessages(wf$run("x")), class = "mini007_parallel_error")
  expect_equal(spender$cost, 0.0015)
})

test_that("budgets are enforced across parallel runs", {
  skip_on_cran()
  local_token_price()
  capped <- token_agent("capped", budget = 0.002)
  wf <- Workflow$new("W", use_cache = FALSE)
  suppressMessages({
    wf$add_station("start", identity)
    wf$add_station("capped", capped)
    wf$add_station("free", function(x) "ok")
    wf$set_daemons(2)
    wf$add_parallel_group("start", c("capped", "free"))
  })
  on.exit(suppressMessages(wf$set_daemons(0)), add = TRUE)

  suppressMessages(wf$run("one"))
  suppressMessages(wf$run("two"))
  expect_error(suppressMessages(wf$run("three")), "exceeded its budget")
})

test_that("a parallel broadcast brings the agents' conversation and cost back", {
  skip_on_cran()
  local_token_price()
  a1 <- token_agent("poet")
  a2 <- token_agent("chef")
  lead <- LeadAgent$new("lead", TokenChat$new())
  suppressMessages({
    lead$register_agents(list(a1, a2))
    lead$set_daemons(2)
  })
  on.exit(suppressMessages(lead$set_daemons(0)), add = TRUE)

  responses <- suppressMessages(lead$broadcast("couscous", parallel = TRUE))
  expect_equal(responses[[1]]$response, "Answer to: couscous")
  expect_length(a1$messages, 3)
  expect_equal(a2$cost, 0.0015)

  a2$llm_object$fail <- TRUE
  expect_error(
    suppressMessages(lead$broadcast("again", parallel = TRUE)),
    class = "mini007_parallel_error"
  )
})

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.