tests/testthat/test-architect-agent.R

library(testthat)
library(mini007)

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

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

# Chat mock: $chat_structured() returns queued replies and records prompts;
# $chat() answers with the model name and records the prompt it was given.
ArchChat <- R6::R6Class(
  "Chat",
  public = list(
    system_prompt = NULL,
    turns = list(),
    tools = list(),
    provider = NULL,
    replies = list(),
    prompts = list(),

    initialize = function(model = "v0") {
      self$provider <- new("Provider", name = "dummy", model = model)
    },
    chat_structured = function(prompt, type) {
      self$prompts[[length(self$prompts) + 1L]] <- prompt
      if (length(self$replies) == 0L) stop("no reply queued")
      out <- self$replies[[1L]]
      self$replies <- self$replies[-1L]
      out
    },
    chat = function(prompt) {
      self$prompts[[length(self$prompts) + 1L]] <- prompt
      paste0("[", self$provider@model, "] done")
    },
    get_cost = function() 0.1,
    set_system_prompt = function(value) { self$system_prompt <- value },
    get_system_prompt = function() self$system_prompt,
    set_turns = function(turns) { self$turns <- 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 },
    on_tool_request = function(callback) function() invisible(NULL),
    get_provider = function() self$provider
  )
)

new_architect <- function(replies = list(), ...) {
  llm <- ArchChat$new("architect-model")
  architect <- ArchitectAgent$new(
    name = "architect",
    llm_object = llm,
    models = list(cheap = ArchChat$new("small"), strong = ArchChat$new("large")),
    ...
  )
  architect$llm_object$replies <- replies
  architect
}

# Answers questions from a queue, recording what was asked.
scripted_ask <- function(answers) {
  env <- new.env()
  env$asked <- list()
  env$fn <- function(question, options) {
    env$asked[[length(env$asked) + 1L]] <- list(question = question, options = options)
    answer <- answers[[1L]]
    answers <<- answers[-1L]
    answer
  }
  env
}

question <- function(text, options = character()) {
  list(done = FALSE, question = text, options = options)
}
finished <- list(done = TRUE, question = "", options = character())

# What ellmer returns for an array of objects: a data frame, with list
# columns for nested arrays.
three_agents <- function(model_writer = "strong") {
  agents <- data.frame(
    name = c("Historian", "geographer", "writer"),
    instruction = c("You know Algerian history.", "You know Algerian geography.", "You write travel guides."),
    task = c("Summarise the history.", "Describe the landscape.", "Write the guide."),
    model = c("cheap", "cheap", model_writer),
    effort = c("low", "low", "high"),
    budget = c(0, 0, 0.5),
    reason = c("Simple lookup.", "Simple lookup.", "Synthesis needs care."),
    stringsAsFactors = FALSE
  )
  agents$depends_on <- list(character(), character(), c("historian", "geographer"))
  list(
    name = "Wilaya Guide",
    summary = "Writes a travel guide for an Algerian wilaya.",
    priority = "balanced",
    rationale = "Two cheap researchers in parallel, one strong writer.",
    agents = agents
  )
}

# ── Initialization ────────────────────────────────────────────────────────────

test_that("ArchitectAgent defaults its models to its own llm_object", {
  architect <- ArchitectAgent$new("architect", ArchChat$new("solo"))
  expect_s3_class(architect, "Agent")
  expect_named(architect$models, "solo")
})

test_that("ArchitectAgent checks its models and notes", {
  llm <- ArchChat$new()
  expect_error(ArchitectAgent$new("a", llm, models = ArchChat$new()), "named list")
  expect_error(ArchitectAgent$new("a", llm, models = list(x = "not a chat")), "not an ellmer chat")
  expect_error(
    ArchitectAgent$new("a", llm, models = list(x = ArchChat$new()), model_notes = c(y = "fast")),
    "not in"
  )
})

# ── Interview ─────────────────────────────────────────────────────────────────

test_that("interview asks until the architect is done and records answers", {
  architect <- new_architect(list(
    question("What matters most?", c("cost", "reliability")),
    question("How many agents?"),
    finished
  ), model_notes = c(cheap = "fast and cheap"))
  ask <- scripted_ask(list("cost", ""))

  architect$interview("Write guides for Algerian wilayas.", ask = ask$fn)

  expect_length(ask$asked, 2)
  expect_equal(ask$asked[[1]]$options, c("cost", "reliability"))
  expect_length(architect$transcript, 3)
  expect_equal(architect$transcript[[1]]$answer, "Write guides for Algerian wilayas.")
  expect_equal(architect$transcript[[2]]$answer, "cost")
  expect_match(architect$transcript[[3]]$answer, "decide yourself")

  first_prompt <- architect$llm_object$prompts[[1]]
  expect_match(first_prompt, "Algerian wilayas", fixed = TRUE)
  expect_match(first_prompt, "- cheap: dummy small", fixed = TRUE)
  expect_match(first_prompt, "fast and cheap", fixed = TRUE)
  expect_match(architect$llm_object$prompts[[2]], "Answer: cost", fixed = TRUE)
})

test_that("interview stops at max_questions or when the user says done", {
  architect <- new_architect(list(question("Q1?"), question("Q2?"), question("Q3?")))
  architect$interview(max_questions = 2, ask = function(q, o) "fine")
  expect_length(architect$transcript, 2)

  architect <- new_architect(list(question("Q1?"), question("Q2?")))
  architect$interview(ask = function(q, o) "done")
  expect_length(architect$transcript, 1)
  expect_match(architect$transcript[[1]]$answer, "ended the interview")
})

# ── Blueprint ─────────────────────────────────────────────────────────────────

test_that("draft_blueprint needs an interview first", {
  expect_error(new_architect()$draft_blueprint(), "nothing to design")
})

test_that("draft_blueprint normalizes the design and computes parallel stages", {
  architect <- new_architect(list(finished, three_agents()))
  architect$interview("Guides", ask = function(q, o) stop("no question expected"))
  bp <- architect$draft_blueprint()

  expect_s3_class(bp, "mini007_blueprint")
  expect_equal(bp$name, "wilaya_guide")
  expect_named(bp$agents, c("historian", "geographer", "writer"))
  expect_equal(bp$stages, list(c("historian", "geographer"), "writer"))
  expect_equal(bp$agents$writer$depends_on, c("historian", "geographer"))
  expect_equal(bp$agents$writer$budget, 0.5)
  expect_true(is.na(bp$agents$historian$budget))
  expect_match(architect$llm_object$prompts[[2]], "Design rules", fixed = TRUE)
  expect_output(print(bp), "Stage 1 \\(parallel\\)")
  expect_output(print(bp), "writer [strong, high effort, budget $0.5, uses historian, geographer]", fixed = TRUE)
})

test_that("normalize_blueprint rejects unknown models and cycles", {
  expect_error(
    mini007:::normalize_blueprint(three_agents("gpt-99"), c("cheap", "strong")),
    class = "mini007_invalid_blueprint"
  )

  cyclic <- three_agents()
  cyclic$agents$depends_on <- list("writer", character(), "historian")
  expect_error(
    mini007:::normalize_blueprint(cyclic, c("cheap", "strong")),
    class = "mini007_invalid_blueprint"
  )
})

test_that("normalize_blueprint renames reserved names and drops unknown dependencies", {
  raw <- three_agents()
  raw$agents$name[[1]] <- "intake"
  raw$agents$depends_on <- list(character(), "ghost", "intake")
  expect_warning(
    bp <- mini007:::normalize_blueprint(raw, c("cheap", "strong")),
    "unknown agent"
  )
  expect_true("intake_agent" %in% names(bp$agents))
  expect_equal(bp$agents$geographer$depends_on, character())
  expect_equal(bp$agents$writer$depends_on, "intake_agent")
})

# ── Build ─────────────────────────────────────────────────────────────────────

test_that("build wires the agents into a runnable workflow", {
  architect <- new_architect(list(finished, three_agents()))
  architect$interview("Guides", ask = function(q, o) "")
  architect$draft_blueprint()

  wf <- suppressMessages(architect$build(parallel = FALSE))
  expect_s3_class(wf, "Workflow")
  expect_named(architect$built_agents, c("historian", "geographer", "writer"))

  writer <- architect$built_agents$writer
  expect_equal(writer$model_name, "large")
  expect_equal(writer$budget, 0.5)
  expect_match(writer$instruction, "step by step", fixed = TRUE)
  expect_match(architect$built_agents$historian$instruction, "briefly", fixed = TRUE)

  out <- suppressMessages(wf$run("Tamanrasset"))
  expect_equal(out, "[large] done")

  writer_prompt <- writer$llm_object$prompts[[1]]
  expect_match(writer_prompt, "## Request\nTamanrasset", fixed = TRUE)
  expect_match(writer_prompt, "Write the guide.", fixed = TRUE)
  expect_match(writer_prompt, "### historian\n[small] done", fixed = TRUE)
  expect_match(writer_prompt, "### geographer\n[small] done", fixed = TRUE)

  historian_prompt <- architect$built_agents$historian$llm_object$prompts[[1]]
  expect_false(grepl("Results from earlier steps", historian_prompt, fixed = TRUE))
})

test_that("build runs a stage of several agents as a parallel group", {
  skip_on_cran()
  architect <- new_architect(list(finished, three_agents()))
  architect$interview("Guides", ask = function(q, o) "")
  architect$draft_blueprint()

  wf <- suppressMessages(architect$build(parallel = TRUE))
  on.exit(suppressMessages(wf$set_daemons(0)), add = TRUE)
  expect_equal(wf$n_daemons, 2L)

  out <- suppressMessages(wf$run("Oran"))
  expect_equal(out, "[large] done")
  writer_prompt <- architect$built_agents$writer$llm_object$prompts[[1]]
  expect_match(writer_prompt, "### historian\n[small] done", fixed = TRUE)
  expect_match(writer_prompt, "### geographer\n[small] done", fixed = TRUE)
})

# ── design() ──────────────────────────────────────────────────────────────────

test_that("design revises on feedback and builds once approved", {
  revised <- three_agents()
  revised$agents <- revised$agents[3, ]
  revised$agents$depends_on <- list(character())

  architect <- new_architect(list(
    question("What matters most?", c("cost", "reliability")),
    finished,
    three_agents(),
    revised
  ))
  ask <- scripted_ask(list("reliability", "Use a single agent.", "yes"))

  expect_output(
    wf <- suppressMessages(architect$design("Guides", ask = ask$fn, parallel = FALSE)),
    "Blueprint: wilaya_guide"
  )

  expect_s3_class(wf, "Workflow")
  expect_named(architect$built_agents, "writer")
  expect_match(ask$asked[[2]]$question, "Build this workflow")
  expect_match(architect$llm_object$prompts[[4]], "Feedback: Use a single agent.", fixed = TRUE)
})

test_that("design can be cancelled before building", {
  architect <- new_architect(list(finished, three_agents()))
  expect_output(out <- suppressMessages(architect$design("Guides", ask = function(q, o) "cancel")))
  expect_null(out)
  expect_s3_class(architect$blueprint, "mini007_blueprint")
  expect_null(architect$workflow)
})

# ── Tools ─────────────────────────────────────────────────────────────────────

population_tool <- ellmer::tool(
  function(wilaya) paste(wilaya, "has about 1.5 million people."),
  name = "wilaya_population",
  description = "Population of an Algerian wilaya.",
  arguments = list(wilaya = ellmer::type_string("The wilaya's name."))
)

weather_code <- paste(
  "```r",
  "get_weather <- function(city) paste('Sunny in', city)",
  "ellmer::tool(get_weather, name = 'get_weather', description = 'Weather of a city.',",
  "  arguments = list(city = ellmer::type_string('City name.')))",
  "```",
  sep = "\n"
)

# A blueprint whose researcher uses an existing tool and a new one.
with_tools <- function() {
  raw <- three_agents()
  raw$agents$tools <- list(c("wilaya_population", "Get Weather"), character(), character())
  raw$new_tools <- data.frame(
    name = c("get_weather", "unused_tool"),
    description = c("Current weather of a city.", "Nobody uses this."),
    arguments = c("city: string, the city name", "x: string"),
    returns = c("A short sentence.", "Nothing."),
    stringsAsFactors = FALSE
  )
  raw
}

test_that("the toolbox only takes ellmer tools", {
  expect_error(new_architect(toolbox = list("not a tool")), "ellmer::tool")
  architect <- new_architect(toolbox = population_tool)
  expect_named(architect$toolbox, "wilaya_population")
})

test_that("the interview and design prompts list the tools", {
  architect <- new_architect(list(finished, with_tools()), toolbox = population_tool)
  architect$interview("Guides", ask = function(q, o) "")
  architect$draft_blueprint()
  expect_match(architect$llm_object$prompts[[1]], "- wilaya_population(wilaya): Population", fixed = TRUE)
  expect_match(architect$llm_object$prompts[[2]], "add a new tool to new_tools", fixed = TRUE)
})

test_that("the blueprint keeps assigned tools and the new tools agents use", {
  bp <- mini007:::normalize_blueprint(with_tools(), c("cheap", "strong"), "wilaya_population")
  expect_equal(bp$agents$historian$tools, c("wilaya_population", "get_weather"))
  expect_equal(bp$agents$writer$tools, character())
  expect_length(bp$new_tools, 1)
  expect_equal(bp$new_tools[[1]]$name, "get_weather")
  expect_output(print(bp), "Tools: wilaya_population, get_weather", fixed = TRUE)
  expect_output(print(bp), "New tools to create")

  raw <- with_tools()
  raw$agents$tools[[2]] <- "ghost_tool"
  expect_warning(
    mini007:::normalize_blueprint(raw, c("cheap", "strong"), "wilaya_population"),
    "unknown tool"
  )
})

test_that("write_tools writes code without running it, and retries code that does not parse", {
  architect <- new_architect(list(
    finished, with_tools(),
    list(code = "get_weather <- function(city {"),
    list(code = weather_code)
  ), toolbox = population_tool)
  architect$interview("Guides", ask = function(q, o) "")
  architect$draft_blueprint()
  architect$write_tools()

  expect_named(architect$tool_code, "get_weather")
  expect_false(grepl("```", architect$tool_code[["get_weather"]]))
  expect_false("get_weather" %in% names(architect$toolbox))
  expect_match(architect$llm_object$prompts[[3]], "Tool name: get_weather", fixed = TRUE)
  expect_match(architect$llm_object$prompts[[3]], "- historian: Summarise the history.", fixed = TRUE)
  expect_match(architect$llm_object$prompts[[4]], "does not parse", fixed = TRUE)
})

test_that("build creates the new tools and gives tool users a ReActAgent", {
  architect <- new_architect(list(finished, with_tools(), list(code = weather_code)),
                             toolbox = population_tool)
  architect$interview("Guides", ask = function(q, o) "")
  architect$draft_blueprint()

  wf <- suppressMessages(architect$build(parallel = FALSE))

  expect_true("get_weather" %in% names(architect$toolbox))
  expect_equal(architect$toolbox$get_weather(city = "Biskra"), "Sunny in Biskra")
  historian <- architect$built_agents$historian
  expect_s3_class(historian, "ReActAgent")
  expect_setequal(names(historian$tools), c("wilaya_population", "get_weather"))
  expect_false(inherits(architect$built_agents$writer, "ReActAgent"))
  expect_equal(suppressMessages(wf$run("Biskra")), "[large] done")
})

test_that("build rewrites tool code that fails to run, then gives up", {
  architect <- new_architect(
    list(finished, with_tools(), list(code = "1 + 1"), list(code = weather_code)),
    toolbox = population_tool
  )
  architect$interview("Guides", ask = function(q, o) "")
  architect$draft_blueprint()
  wf <- suppressMessages(architect$build(parallel = FALSE))
  expect_true("get_weather" %in% names(architect$toolbox))
  expect_match(architect$llm_object$prompts[[4]], "Running the code failed with this error", fixed = TRUE)
  expect_match(architect$llm_object$prompts[[4]], "Code written so far:\n1 + 1", fixed = TRUE)

  architect <- new_architect(
    list(finished, with_tools(), list(code = "1 + 1"), list(code = "1 + 1"), list(code = "1 + 1")),
    toolbox = population_tool
  )
  architect$interview("Guides", ask = function(q, o) "")
  architect$draft_blueprint()
  expect_error(suppressMessages(architect$build(parallel = FALSE)), "Could not create tool")
})

test_that("design shows rewritten tool code again after it fails to run", {
  architect <- new_architect(
    list(finished, with_tools(), list(code = "1 + 1"), list(code = weather_code)),
    toolbox = population_tool
  )
  ask <- scripted_ask(list("yes", "yes", "yes"))
  expect_output(
    wf <- suppressMessages(architect$design("Guides", ask = ask$fn, parallel = FALSE)),
    "Tool: get_weather"
  )
  expect_s3_class(wf, "Workflow")
  expect_length(ask$asked, 3)
  expect_match(ask$asked[[3]]$question, "Create these tools")
})

test_that("with allow_new_tools = FALSE the architect only assigns the toolbox", {
  architect <- new_architect(list(finished, with_tools()), toolbox = population_tool,
                             allow_new_tools = FALSE)
  architect$interview("Guides", ask = function(q, o) "")
  expect_warning(bp <- architect$draft_blueprint(), "unknown tool")
  expect_length(bp$new_tools, 0)
  expect_equal(bp$agents$historian$tools, "wilaya_population")
  expect_match(architect$llm_object$prompts[[2]], "do not propose new ones", fixed = TRUE)
})

test_that("design shows the tool code and asks before running it", {
  architect <- new_architect(
    list(finished, with_tools(), list(code = weather_code), list(code = weather_code)),
    toolbox = population_tool
  )
  ask <- scripted_ask(list("yes", "Return the temperature too.", "yes"))
  expect_output(
    wf <- suppressMessages(architect$design("Guides", ask = ask$fn, parallel = FALSE)),
    "Tool: get_weather"
  )
  expect_s3_class(wf, "Workflow")
  expect_match(ask$asked[[2]]$question, "Create these tools")
  expect_match(architect$llm_object$prompts[[4]], "Change it following this feedback: Return the temperature too.", fixed = TRUE)

  architect <- new_architect(list(finished, with_tools(), list(code = weather_code)),
                             toolbox = population_tool)
  ask <- scripted_ask(list("yes", "cancel"))
  expect_output(out <- suppressMessages(architect$design("Guides", ask = ask$fn)))
  expect_null(out)
  expect_named(architect$tool_code, "get_weather")
  expect_false("get_weather" %in% names(architect$toolbox))
})

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.