Nothing
#' ArchitectAgent: An Agent that Designs and Builds Multi-Agent Workflows
#'
#' @description
#' An `ArchitectAgent` interviews you about what you need, then designs and
#' builds the agents and the [Workflow] that does it. It works in three steps:
#'
#' 1. **Interview** (\code{$interview()}): it asks one question at a time
#' about the task and the prompts the workflow will receive, the expected
#' output, what matters most (low cost, reliability, speed or a balance),
#' which of your models it may use, how many agents you want, a budget,
#' whether a review step is wanted and whether steps may run in parallel.
#' It skips what you have already answered and stops once it knows enough.
#' 2. **Blueprint** (\code{$draft_blueprint()}): it designs the agents. Each
#' one gets a name, a system prompt, its task in the workflow, one of your
#' models, an effort level (`"low"`, `"medium"` or `"high"`), its tools
#' and the agents whose results it needs. Agents that do not depend on
#' each other are put in the same stage and can run in parallel. When no
#' tool you gave fits a need, it proposes a new one.
#' 3. **Build** (\code{$build()}): it writes the R code of the new tools,
#' creates the agents (a [ReActAgent] for each agent with tools, an
#' [Agent] otherwise) and wires them into a [Workflow], stage by stage.
#'
#' \code{$design()} runs the three steps in a row. It shows you the
#' blueprint, and then the code of any new tool, before building, so you can
#' ask for changes first.
#'
#' @details
#' **Models.** The architect can only assign the models you give it in
#' `models`, a named list of ellmer chat objects; the names are the labels it
#' chooses from. It reads each model's provider, name and price (from
#' [set_prices()] or ellmer's price table) to weigh cost against capability,
#' plus any note you give in `model_notes`.
#'
#' **Effort.** An agent's effort level shapes its system prompt: a `"low"`
#' effort agent is told to answer directly and briefly, a `"high"` effort
#' agent to reason step by step and check its work. Effort also guides the
#' choice of model: when cost matters most, the architect favours cheap
#' models and low effort; when reliability matters most, strong models and
#' high effort for the critical steps. To also set a provider-level
#' reasoning effort, pass the same model several times with different
#' `params`, eg. `"gpt-5-mini (low)" = ellmer::chat_openai(model =
#' "gpt-5-mini", params = ellmer::params(reasoning_effort = "low"))`, and
#' describe them in `model_notes`.
#'
#' **Tools.** The architect assigns the ellmer tools you give it in
#' `toolbox`, reading their names, descriptions and arguments. When a task
#' needs a tool that is not there (fetching data, computing, reading a file),
#' it proposes a new one in the blueprint: a name, what it does, its
#' arguments and what it returns. \code{$write_tools()} then writes each new
#' tool's R code, a function wrapped in `ellmer::tool()`, into `$tool_code`.
#' The code only runs when \code{$build()} creates the tools, and
#' \code{$design()} shows it to you and asks first. You can edit
#' `$tool_code` before building. Created tools are added to `$toolbox`, so
#' later designs can reuse them. Set `allow_new_tools = FALSE` to restrict
#' the architect to your `toolbox`.
#'
#' **The built workflow.** Its first station, `"intake"`, receives your
#' request. Every agent is then sent the request, its own task and the
#' results of the agents it depends on, and nothing else. A stage of several
#' agents runs as a parallel group (between a `"fork_<n>"` and a
#' `"join_<n>"` station) when `parallel = TRUE`, and one agent after another
#' otherwise. The workflow's result is the last stage's output. It is built
#' with `use_cache = FALSE`, since each agent reads the current request
#' rather than only its station input.
#'
#' The interview and design calls go through the architect's own
#' `llm_object`, so they add to its turn history and its cost, like any
#' [Agent]'s.
#'
#' @export
ArchitectAgent <- R6::R6Class(
classname = "ArchitectAgent",
inherit = Agent,
public = list(
#' @field models Named list of ellmer chat objects the architect may
#' assign to the agents it designs.
models = list(),
#' @field model_notes Named character vector of notes about the models
#' (eg. `"fast but weak at reasoning"`), keyed by model label.
model_notes = character(),
#' @field toolbox Named list of ellmer tools the architect may assign,
#' including the new tools it created.
toolbox = list(),
#' @field allow_new_tools Whether the architect may propose and write new
#' tools.
allow_new_tools = TRUE,
#' @field tool_code Named character vector: the R code of each new tool,
#' written by \code{$write_tools()}.
tool_code = character(),
#' @field transcript The interview so far: a list of question/answer
#' pairs, each with `question`, `options` and `answer`.
transcript = list(),
#' @field blueprint The latest design, a `mini007_blueprint`, or `NULL`.
blueprint = NULL,
#' @field workflow The latest [Workflow] built by \code{$build()}, or
#' `NULL`.
workflow = NULL,
#' @field built_agents Named list of the [Agent]s created by the latest
#' \code{$build()}.
built_agents = list(),
#' @description
#' Creates a new ArchitectAgent.
#' @param name A short name for the architect (eg. `"architect"`).
#' @param llm_object The ellmer chat object the architect itself uses to
#' interview and design. It must support structured output.
#' @param models A named list of ellmer chat objects that the designed
#' agents may use. Each name is the label the architect sees and
#' assigns. Defaults to `llm_object` alone, labelled with its model
#' name.
#' @param model_notes Optional named character vector of notes about the
#' models, keyed by label: strengths, limits, speed, reasoning effort.
#' @param toolbox Optional list of ellmer tools (`ellmer::tool()`) the
#' designed agents may use, or a single one.
#' @param allow_new_tools `[logical(1)]` Whether the architect may
#' propose new tools and write their code. Defaults to `TRUE`.
#' @param budget Budget in US$ for the architect's own calls, as in
#' [Agent].
#' @examples \dontrun{
#' architect <- ArchitectAgent$new(
#' name = "architect",
#' llm_object = ellmer::chat_openai(model = "gpt-4.1", echo = "none"),
#' models = list(
#' "gpt-4.1-mini" = ellmer::chat_openai(model = "gpt-4.1-mini", echo = "none"),
#' "gpt-4.1" = ellmer::chat_openai(model = "gpt-4.1", echo = "none")
#' ),
#' toolbox = list(
#' ellmer::tool(
#' function(wilaya) paste("Population data for", wilaya),
#' name = "wilaya_population",
#' description = "Population of an Algerian wilaya.",
#' arguments = list(wilaya = ellmer::type_string("The wilaya's name."))
#' )
#' )
#' )
#'
#' # Asks its questions in the console, shows the blueprint and the code of
#' # any new tool, then builds it
#' wf <- architect$design(
#' "Write a short, well-sourced travel guide for any Algerian wilaya."
#' )
#' wf$visualize()
#' wf$run("Tamanrasset, with a focus on the Hoggar mountains")
#' }
initialize = function(name, llm_object, models = NULL, model_notes = NULL,
toolbox = NULL, allow_new_tools = TRUE, budget = NA) {
super$initialize(
name = name,
instruction = architect_system_prompt,
llm_object = llm_object,
budget = budget
)
if (is.null(models)) {
models <- stats::setNames(list(llm_object), self$model_name)
}
self$models <- check_model_catalog(models)
if (!is.null(model_notes)) {
checkmate::assert_character(model_notes, any.missing = FALSE, names = "unique")
unknown <- setdiff(names(model_notes), names(self$models))
if (length(unknown)) {
cli::cli_abort("{.arg model_notes} names models that are not in {.arg models}: {.val {unknown}}.")
}
self$model_notes <- model_notes
}
checkmate::assert_flag(allow_new_tools)
self$allow_new_tools <- allow_new_tools
if (!is.null(toolbox)) self$add_tools(toolbox)
},
#' @description
#' Adds ellmer tools to the toolbox the architect assigns from.
#' @param tools An ellmer tool (`ellmer::tool()`) or a list of them.
#' @return The architect, invisibly.
add_tools = function(tools) {
if (inherits(tools, "ellmer::ToolDef")) tools <- list(tools)
checkmate::assert_list(tools)
for (tool in tools) {
if (!inherits(tool, "ellmer::ToolDef")) {
cli::cli_abort("Every tool in {.arg toolbox} must be made with {.fn ellmer::tool}.")
}
if (!length(tool@name) || !nzchar(tool@name)) {
cli::cli_abort("Every tool in {.arg toolbox} needs a {.arg name}.")
}
self$toolbox[[tool@name]] <- tool
}
invisible(self)
},
#' @description
#' Runs the whole design: interviews you, drafts a blueprint, shows it
#' and, once you approve it, builds the workflow.
#'
#' After showing the blueprint, it asks whether to build it. Answer
#' `"yes"` to build, `"cancel"` to stop without building, or describe the
#' changes you want and it revises the blueprint and asks again. When the
#' blueprint has new tools, it then writes their code, shows it and asks
#' again in the same way before running it.
#' @param goal Optional description of what the workflow should do. When
#' `NULL`, the interview starts by asking for it.
#' @param max_questions `[integer(1)]` The largest number of interview
#' questions. Defaults to 8.
#' @param ask `[function | NULL]` How questions are put to you: a
#' \code{function(question, options)} returning the answer as a string.
#' `options` is a character vector of suggested answers, possibly empty.
#' Defaults to a console prompt, which needs an interactive session.
#' @param confirm `[logical(1)]` Whether to show the blueprint and the
#' code of new tools, and ask before building. With `FALSE`, the new
#' tools' code runs without review. Defaults to `TRUE`.
#' @param parallel `[logical(1)]` Passed to \code{$build()}.
#' @return The built [Workflow], or `NULL` (invisibly) when cancelled.
design = function(goal = NULL, max_questions = 8, ask = NULL,
confirm = TRUE, parallel = TRUE) {
checkmate::assert_flag(confirm)
ask <- ask %||% console_ask
self$interview(goal = goal, max_questions = max_questions, ask = ask)
self$draft_blueprint()
while (confirm) {
print(self$blueprint)
answer <- trimws(as.character(ask(
"Build this workflow? Answer yes, cancel, or describe what to change.",
c("yes", "cancel")
)))
if (tolower(answer) %in% c("yes", "y", "build", "ok")) break
if (tolower(answer) %in% c("cancel", "no", "n", "stop", "")) {
cli::cli_alert_info("Design cancelled; the blueprint is kept in {.field $blueprint}.")
return(invisible(NULL))
}
self$revise(answer)
}
if (confirm && length(private$.tools_to_create(self$blueprint))) {
self$write_tools()
repeat {
private$.print_tool_code()
answer <- trimws(as.character(ask(
"Create these tools and build the workflow? Answer yes, cancel, or describe what to change in the code.",
c("yes", "cancel")
)))
if (tolower(answer) %in% c("cancel", "no", "n", "stop", "")) {
cli::cli_alert_info("Design cancelled; the code is kept in {.field $tool_code}.")
return(invisible(NULL))
}
if (!tolower(answer) %in% c("yes", "y", "build", "ok")) {
self$write_tools(feedback = answer)
next
}
# Code that fails to run is rewritten with the error, and shown again.
failed <- private$.create_tools(self$blueprint)
if (is.null(failed)) break
cli::cli_alert_warning("Tool {.val {failed$tool}} failed: {failed$error}. Rewriting it.")
private$.write_tool(
self$blueprint$new_tools[[match(failed$tool, vapply(self$blueprint$new_tools, `[[`, "", "name"))]],
paste("Running the code failed with this error:", failed$error)
)
}
}
self$build(parallel = parallel)
},
#' @description
#' Interviews you about the workflow you need, one question at a time,
#' until the architect knows enough or `max_questions` is reached. Answer
#' `"done"` to stop early; an empty answer leaves that choice to the
#' architect. Calling it again continues the same interview.
#' @param goal Optional description of what the workflow should do.
#' @param max_questions `[integer(1)]` The largest number of questions.
#' @param ask `[function | NULL]` See \code{$design()}.
#' @return The transcript (a list of question/answer pairs), invisibly.
interview = function(goal = NULL, max_questions = 8, ask = NULL) {
if (!is.null(goal)) checkmate::assert_string(goal, min.chars = 1)
checkmate::assert_count(max_questions)
ask <- ask %||% console_ask
checkmate::assert_function(ask)
if (!is.na(self$budget)) private$.check_budget()
if (!is.null(goal)) {
private$.record("What should the workflow do?", character(), goal)
}
prompt <- paste0(
"Interview the user to design their workflow. ",
"You may ask at most ", max_questions, " questions.\n\n",
"Models the agents may use:\n", private$.model_catalog(), "\n\n",
private$.tool_catalog(), "\n\n",
transcript_text(self$transcript)
)
asked <- 0L
while (asked < max_questions) {
step <- private$.structured(prompt, interview_type(), "interview the user")
question <- trimws(paste(as.character(step$question), collapse = " "))
if (isTRUE(as.logical(step$done)) || !nzchar(question)) break
options <- as.character(unlist(step$options))
options <- options[!is.na(options) & nzchar(trimws(options))]
answer <- trimws(paste(as.character(ask(question, options)), collapse = " "))
asked <- asked + 1L
if (tolower(answer) %in% c("done", "stop", "enough")) {
private$.record(question, options, "(The user ended the interview here.)")
break
}
if (!nzchar(answer)) answer <- "(No answer: decide yourself.)"
private$.record(question, options, answer)
prompt <- paste0(
"Answer: ", answer, "\n\n",
"Questions left: ", max_questions - asked, "."
)
}
private$.sync_cost()
invisible(self$transcript)
},
#' @description
#' Designs the agents and their stages from the interview.
#' @return The blueprint, a `mini007_blueprint`: a list with `name`,
#' `summary`, `priority`, `rationale`, `agents` (one list per agent,
#' with `name`, `instruction`, `task`, `model`, `effort`, `budget`,
#' `tools`, `depends_on` and `reason`), `new_tools` (one list per tool
#' to create, with `name`, `description`, `arguments` and `returns`) and
#' `stages` (a list of character vectors
#' of agent names; the agents of one stage can run in parallel).
draft_blueprint = function() {
if (!length(self$transcript)) {
cli::cli_abort(c(
"ArchitectAgent {.val {self$name}} has nothing to design from yet.",
"i" = "Run {.code $interview()} first, or {.code $design()}."
))
}
if (!is.na(self$budget)) private$.check_budget()
prompt <- paste0(
"Design the workflow now.\n\n",
"Models the agents may use:\n", private$.model_catalog(), "\n\n",
private$.tool_catalog(), "\n\n",
transcript_text(self$transcript), "\n\n",
private$.rules()
)
private$.set_blueprint(private$.structured(prompt, private$.blueprint_type(), "design the workflow"))
},
#' @description
#' Revises the blueprint following your feedback (eg. `"use only two
#' agents"` or `"put the reviewer on the strongest model"`).
#' @param feedback What to change, in plain words.
#' @return The revised blueprint.
revise = function(feedback) {
checkmate::assert_string(feedback, min.chars = 1)
if (is.null(self$blueprint)) {
cli::cli_abort("There is no blueprint to revise yet; run {.code $draft_blueprint()} first.")
}
if (!is.na(self$budget)) private$.check_budget()
private$.record("What should change in the blueprint?", character(), feedback)
prompt <- paste0(
"Revise this blueprint following the user's feedback. Keep what the ",
"feedback does not ask to change.\n\n",
"Current blueprint:\n", blueprint_text(self$blueprint), "\n\n",
"Feedback: ", feedback, "\n\n",
"Models the agents may use:\n", private$.model_catalog(), "\n\n",
private$.tool_catalog(), "\n\n",
private$.rules()
)
private$.set_blueprint(private$.structured(prompt, private$.blueprint_type(), "revise the blueprint"))
},
#' @description
#' Writes the R code of the blueprint's new tools into `$tool_code`,
#' without running it. Each tool is a function wrapped in
#' `ellmer::tool()`. Tools already in `$toolbox` are skipped.
#' @param feedback Optional changes to make to the code already written,
#' in plain words. All the new tools are then rewritten.
#' @return `$tool_code`, invisibly.
write_tools = function(feedback = NULL) {
if (!is.null(feedback)) checkmate::assert_string(feedback, min.chars = 1)
if (is.null(self$blueprint)) {
cli::cli_abort("There is no blueprint yet; run {.code $draft_blueprint()} first.")
}
if (!is.na(self$budget)) private$.check_budget()
for (tool in private$.tools_to_create(self$blueprint)) {
if (is.null(feedback) && tool$name %in% names(self$tool_code)) next
private$.write_tool(tool, feedback)
}
invisible(self$tool_code)
},
#' @description
#' Creates the blueprint's agents and wires them into a [Workflow].
#'
#' New tools are created first: their code is written with
#' \code{$write_tools()} if it has not been yet, then run, and each tool
#' is added to `$toolbox`. When a tool's code fails to run, the
#' architect is given the error and rewrites it, up to twice. Agents with
#' tools are built as [ReActAgent]s.
#' @param blueprint The blueprint to build. Defaults to `$blueprint`.
#' @param parallel `[logical(1)]` Whether a stage of several agents runs
#' as a parallel group. If so, daemons are started (one per agent of
#' the widest stage) unless the session already has enough; shut them
#' down with \code{wf$set_daemons(0)}. With `FALSE`, its agents run one after
#' another. Defaults to `TRUE`.
#' @return The [Workflow]. The agents are in `$built_agents`.
build = function(blueprint = self$blueprint, parallel = TRUE) {
checkmate::assert_flag(parallel)
if (is.null(blueprint)) {
cli::cli_abort("There is no blueprint to build; run {.code $design()} or {.code $draft_blueprint()} first.")
}
if (!inherits(blueprint, "mini007_blueprint")) {
cli::cli_abort("{.arg blueprint} must be a {.cls mini007_blueprint}.")
}
for (attempt in 0:2) {
failed <- private$.create_tools(blueprint)
if (is.null(failed)) break
if (attempt == 2L) {
cli::cli_abort(
c(
"Could not create tool {.val {failed$tool}}.",
"x" = failed$error,
"i" = "Fix {.code $tool_code[[\"{failed$tool}\"]]}, or ask for new code with {.code $write_tools(feedback = ...)}."
),
call = NULL
)
}
cli::cli_alert_warning("Tool {.val {failed$tool}} failed: {failed$error}. Rewriting it.")
tool <- blueprint$new_tools[[match(failed$tool, vapply(blueprint$new_tools, `[[`, "", "name"))]]
private$.write_tool(tool, paste("Running the code failed with this error:", failed$error), blueprint)
}
ctx <- new.env(parent = emptyenv())
ctx$request <- ""
ctx$outputs <- list()
agents <- list()
for (spec in blueprint$agents) {
llm <- self$models[[spec$model]]
if (is.null(llm)) {
cli::cli_abort("Agent {.val {spec$name}} uses the unknown model {.val {spec$model}}.")
}
missing_tools <- setdiff(spec$tools, names(self$toolbox))
if (length(missing_tools)) {
cli::cli_abort("Agent {.val {spec$name}} uses unknown tool{?s} {.val {missing_tools}}.")
}
instruction <- with_effort(spec$instruction, spec$effort)
agents[[spec$name]] <- quietly(if (length(spec$tools)) {
ReActAgent$new(
name = spec$name,
instruction = instruction,
llm_object = llm,
tools = unname(self$toolbox[spec$tools]),
budget = spec$budget
)
} else {
Agent$new(
name = spec$name,
instruction = instruction,
llm_object = llm,
budget = spec$budget
)
})
}
wf <- Workflow$new(blueprint$name, description = blueprint$summary, use_cache = FALSE)
quietly(wf$add_station(
"intake",
function(input) {
ctx$request <- input
ctx$outputs <- list()
input
},
description = "Receives the request"
))
quietly(wf$set_entry("intake"))
widest <- max(lengths(blueprint$stages))
if (parallel && widest > 1L) {
# The daemons are shared by the session: reuse a big enough pool.
if (running_daemons() >= widest) {
wf$n_daemons <- running_daemons()
} else {
quietly(wf$set_daemons(widest))
}
}
prev <- "intake"
for (k in seq_along(blueprint$stages)) {
stage <- blueprint$stages[[k]]
for (agent_name in stage) {
spec <- blueprint$agents[[agent_name]]
quietly(wf$add_station(
agent_name,
stage_handler(agents[[agent_name]], spec, ctx),
description = spec$task
))
}
if (parallel && length(stage) > 1L) {
fork <- paste0("fork_", k)
join <- paste0("join_", k)
quietly({
wf$add_station(fork, identity, description = "Starts the parallel stage")
wf$add_station(join, identity, description = "Gathers the parallel results")
wf$add_route(prev, fork)
wf$add_parallel_group(fork, stage, to = join, merge_fn = stage_merger(ctx))
})
prev <- join
} else {
for (agent_name in stage) {
quietly(wf$add_route(prev, agent_name))
prev <- agent_name
}
}
}
self$workflow <- wf
self$built_agents <- agents
cli::cli_alert_success(
"Built workflow {.val {blueprint$name}}: {length(agents)} agent{?s} in {length(blueprint$stages)} stage{?s}."
)
wf
}
),
private = list(
.record = function(question, options, answer) {
self$transcript[[length(self$transcript) + 1L]] <- list(
question = question,
options = options,
answer = answer
)
},
.sync_cost = function() {
private$.update_cost()
private$.set_messages_from_turns()
},
.structured = function(prompt, type, what) {
result <- tryCatch(
self$llm_object$chat_structured(prompt, type = type),
error = function(e) {
cli::cli_abort(
c(
"ArchitectAgent {.val {self$name}} could not {what}.",
"x" = conditionMessage(e)
),
parent = e,
call = NULL
)
}
)
private$.sync_cost()
result
},
.set_blueprint = function(raw) {
if (!self$allow_new_tools) raw$new_tools <- NULL
self$blueprint <- normalize_blueprint(raw, names(self$models), names(self$toolbox))
self$blueprint
},
.rules = function() {
paste(blueprint_rules, tool_rules(self$allow_new_tools), sep = "\n")
},
# New tools of a blueprint that are not in the toolbox yet.
.tools_to_create = function(blueprint) {
Filter(function(tool) !tool$name %in% names(self$toolbox), blueprint$new_tools)
},
# Runs the code of the blueprint's new tools and adds them to the toolbox.
# Returns NULL, or for the first tool that fails, its name and error.
.create_tools = function(blueprint) {
pending <- private$.tools_to_create(blueprint)
if (!length(pending)) return(NULL)
missing_code <- vapply(pending, function(tool) !tool$name %in% names(self$tool_code), logical(1))
if (any(missing_code)) {
for (tool in pending[missing_code]) private$.write_tool(tool, NULL, blueprint)
}
for (tool in pending) {
created <- tryCatch(
eval_tool_code(self$tool_code[[tool$name]], tool$name),
error = function(e) list(tool = tool$name, error = one_line(conditionMessage(e)))
)
if (!inherits(created, "ellmer::ToolDef")) return(created)
self$toolbox[[tool$name]] <- created
cli::cli_alert_success("Created tool {.val {tool$name}}.")
}
NULL
},
# Writes (or, with feedback, rewrites) one new tool's code into
# $tool_code, checking that it parses.
.write_tool = function(tool, feedback = NULL, blueprint = self$blueprint) {
users <- Filter(function(spec) tool$name %in% spec$tools, blueprint$agents)
tasks <- vapply(users, function(spec) paste0("- ", spec$name, ": ", spec$task), character(1))
prompt <- paste0(
"Write the R code of a new tool for the workflow '", blueprint$name, "' (",
blueprint$summary, ").\n\n",
"Tool name: ", tool$name, "\n",
"What it does: ", tool$description, "\n",
"Arguments: ", tool$arguments, "\n",
"Returns: ", tool$returns, "\n",
if (length(tasks)) paste0("Used by:\n", paste(tasks, collapse = "\n"), "\n") else "",
if (!is.null(feedback) && tool$name %in% names(self$tool_code)) {
paste0(
"\nCode written so far:\n", self$tool_code[[tool$name]],
"\n\nChange it following this feedback: ", feedback, "\n"
)
} else "",
"\n", tool_code_rules(tool$name)
)
for (attempt in 1:2) {
result <- private$.structured(prompt, tool_code_type(), paste0("write the tool ", tool$name))
code <- strip_code_fences(text_field(result$code))
problem <- tryCatch({
parse(text = code, keep.source = FALSE)
NULL
}, error = function(e) conditionMessage(e))
if (is.null(problem)) break
if (attempt == 2L) {
cli::cli_abort("The code written for tool {.val {tool$name}} does not parse: {problem}")
}
prompt <- paste0("That code does not parse: ", problem, "\nWrite it again, fixed.")
}
self$tool_code[[tool$name]] <- code
invisible(code)
},
.print_tool_code = function() {
for (tool in private$.tools_to_create(self$blueprint)) {
cat("\n")
cli::cat_rule(paste("Tool:", tool$name))
cat(self$tool_code[[tool$name]], "\n", sep = "")
}
},
.tool_catalog = function() {
if (!length(self$toolbox)) {
return(paste0(
"Tools available: none.",
if (self$allow_new_tools) " You may propose new tools, which will be written in R." else ""
))
}
lines <- vapply(self$toolbox, function(tool) {
args <- names(tool@arguments@properties)
sprintf(
"- %s(%s): %s",
tool@name, paste(args, collapse = ", "), one_line(tool@description)
)
}, character(1))
paste0(
"Tools available:\n", paste(lines, collapse = "\n"),
if (self$allow_new_tools) "\nYou may also propose new tools, which will be written in R." else ""
)
},
.model_catalog = function() {
labels <- names(self$models)
lines <- vapply(labels, function(label) {
llm <- self$models[[label]]
provider <- llm$get_provider()
price <- model_price(provider@name, provider@model)
price_text <- if (is.null(price)) {
"price unknown"
} else {
sprintf("$%s in / $%s out per 1M tokens", format(price$input), format(price$output))
}
note <- if (label %in% names(self$model_notes)) paste0(" Note: ", self$model_notes[[label]]) else ""
sprintf("- %s: %s %s, %s.%s", label, provider@name, provider@model, price_text, note)
}, character(1))
paste(lines, collapse = "\n")
},
.blueprint_type = function() {
type <- ellmer::type_object(
name = ellmer::type_string(
description = "A short snake_case name for the workflow."
),
summary = ellmer::type_string(
description = "One or two sentences on what the workflow does."
),
priority = ellmer::type_enum(
values = c("cost", "reliability", "speed", "balanced"),
description = "What the user said matters most."
),
rationale = ellmer::type_string(
description = "Two or three sentences on the design: why these agents, models and effort levels, and what runs in parallel."
),
agents = ellmer::type_array(
items = ellmer::type_object(
name = ellmer::type_string(
description = "Unique snake_case name, eg. 'researcher'."
),
instruction = ellmer::type_string(
description = "The agent's full system prompt: its role, how it works and what its output looks like."
),
task = ellmer::type_string(
description = "What this agent does in this workflow, in one or two sentences."
),
model = ellmer::type_enum(
values = names(self$models),
description = "The label of the model this agent uses."
),
effort = ellmer::type_enum(
values = c("low", "medium", "high"),
description = "How much care and reasoning this agent should put in."
),
budget = ellmer::type_number(
description = "Budget cap in US dollars for this agent, or 0 for none. Only set one if the user gave a budget."
),
tools = ellmer::type_array(
items = ellmer::type_string(),
description = "Names of the tools this agent uses, from the available tools or the new tools. Empty if it needs none."
),
depends_on = ellmer::type_array(
items = ellmer::type_string(),
description = "Names of the agents whose results this agent needs. Empty if it only needs the request."
),
reason = ellmer::type_string(
description = "One sentence on why this model and effort level."
)
),
description = "The agents, in the order they would run."
)
)
if (self$allow_new_tools) {
type@properties$new_tools <- ellmer::type_array(
items = ellmer::type_object(
name = ellmer::type_string(description = "Unique snake_case name, eg. 'get_wilaya_population'."),
description = ellmer::type_string(description = "What the tool does, precisely, in one or two sentences."),
arguments = ellmer::type_string(description = "Each argument: its name, type and meaning."),
returns = ellmer::type_string(description = "What the tool returns.")
),
description = "Tools to create because no available tool does the job. Empty if none is needed."
)
}
type
}
)
)
#' @export
print.mini007_blueprint <- function(x, ...) {
wrap <- function(text, indent = 0) {
lines <- strwrap(text, width = max(40, cli::console_width() - 2), indent = indent, exdent = indent)
cat(lines, sep = "\n")
}
cli::cat_rule(paste("Blueprint:", x$name))
wrap(x$summary)
cat("Priority: ", x$priority, "\n", sep = "")
if (nzchar(x$rationale)) wrap(paste("Design:", x$rationale))
for (k in seq_along(x$stages)) {
stage <- x$stages[[k]]
label <- if (length(stage) > 1L) " (parallel)" else ""
cat("\n")
cli::cat_rule(paste0("Stage ", k, label), line = 2, width = 30)
for (agent_name in stage) {
spec <- x$agents[[agent_name]]
deps <- if (length(spec$depends_on)) paste0(", uses ", paste(spec$depends_on, collapse = ", ")) else ""
budget <- if (!is.na(spec$budget)) sprintf(", budget $%s", format(spec$budget)) else ""
wrap(sprintf("%s [%s, %s effort%s%s]", spec$name, spec$model, spec$effort, budget, deps))
wrap(spec$task, indent = 2)
if (length(spec$tools)) wrap(paste("Tools:", paste(spec$tools, collapse = ", ")), indent = 2)
if (nzchar(spec$reason)) wrap(paste("Why:", spec$reason), indent = 2)
}
}
if (length(x$new_tools)) {
cat("\n")
cli::cat_rule("New tools to create", line = 2, width = 30)
for (tool in x$new_tools) {
wrap(paste0(tool$name, ": ", tool$description))
if (nzchar(tool$arguments)) wrap(paste("Arguments:", tool$arguments), indent = 2)
if (nzchar(tool$returns)) wrap(paste("Returns:", tool$returns), indent = 2)
}
}
invisible(x)
}
# -- helpers -------------------------------------------------------------------
`%||%` <- function(x, y) if (is.null(x)) y else x
architect_system_prompt <- paste(
"You are a workflow architect. You design teams of LLM agents for a user:",
"how many agents, what each one does, its system prompt, which model it",
"uses, how much effort it puts in, and which agents can run in parallel.",
"",
"First you interview the user, one question at a time. Cover what you do",
"not know yet among: the task and the kind of prompts the workflow will",
"receive (ask for an example), the output they expect (format, length,",
"language), what matters most (low cost, reliability, speed, or a balance),",
"which of the available models may be used, how many agents they want or",
"whether you should decide, the data, files, APIs or computations the agents",
"need (which tools), a budget, whether a review or validation step is",
"wanted, and whether steps may run in parallel. Never ask about something",
"already answered. Keep each question short and offer a few concrete",
"options when they help. Stop as soon as you know enough to design a good",
"workflow; when the user leaves a choice to you, decide it yourself.",
sep = "\n"
)
blueprint_rules <- paste(
"Design rules:",
"- Give each agent one clear responsibility and a complete system prompt.",
"- Respect the number of agents the user asked for; otherwise use as few as the task needs.",
"- An agent depends only on the agents whose results it really needs. Agents that do not need each other's results must not depend on each other, so they can run in parallel.",
"- Exactly one agent, the last, delivers the final answer, and every other agent must lead to it. Its output is handed to the user as is, so it must be the deliverable itself (eg. the finished guide), never a review, critique or plan. A reviewer is never last: it comes before a final agent that applies its feedback.",
"- Assign only the listed models. When cost matters most, prefer the cheapest models and low effort. When reliability matters most, use the strongest models and high effort for the critical steps (planning, synthesis, review). When speed matters most, keep few sequential stages and run work in parallel. For a balance, use cheap models with low effort for simple steps and strong ones for reasoning and synthesis.",
"- Every agent receives the user's request, its task and the results of the agents it depends on.",
sep = "\n"
)
tool_rules <- function(allow_new_tools) {
paste(
"- Give an agent a tool only when its task needs data, a computation or an action that the model cannot do reliably from its own knowledge. Assign tools by their exact names. Agents with tools call them in a loop until they can answer.",
if (allow_new_tools) {
paste(
"- Prefer the available tools. When none fits a need, add a new tool to new_tools and assign it by name: describe precisely what it does, its arguments and what it returns.",
"A new tool cannot call other tools. When an available tool already provides part of what is needed (eg. coordinates), do not repeat that work: give the new tool that output as arguments, and assign both tools to the agent.",
"A new tool is a plain R function, so it can compute, read local files, or call public web APIs that need no key; it must not need an API key or a package the user did not mention. Keep new tools few and simple."
)
} else {
"- Use only the available tools: do not propose new ones."
},
sep = "\n"
)
}
tool_code_type <- function() {
ellmer::type_object(
code = ellmer::type_string(
description = "The R code only: no markdown fences, no explanations."
)
)
}
tool_code_rules <- function(name) {
paste(
"Requirements:",
"1. Define the function, then end with an ellmer::tool() call, which must be the last expression, eg.:",
" wilaya_population <- function(wilaya) {",
" # ...",
" }",
" ellmer::tool(",
" wilaya_population,",
paste0(" name = '", name, "',"),
" description = 'Population of an Algerian wilaya.',",
" arguments = list(wilaya = ellmer::type_string('The name of the wilaya, eg. Oran.'))",
" )",
paste0("2. The tool's name must be '", name, "'."),
"3. `description` is a plain character string. Describe each argument in `arguments` with ellmer::type_string(), type_number(), type_integer(), type_boolean(), type_enum() or type_array(); optional arguments use required = FALSE.",
"4. Use base R where you can. Call any other package as pkg::fun(), and only jsonlite, or a package the user mentioned.",
"5. Return a character string or a small value the LLM can read. On failure, return a message saying what went wrong instead of stopping.",
"6. No side effects at the top level: only the function definition and the ellmer::tool() call.",
sep = "\n"
)
}
strip_code_fences <- function(code) {
code <- gsub("^\\s*```[A-Za-z]*\\s*\n?", "", code)
code <- gsub("\n?\\s*```\\s*$", "", code)
trimws(code)
}
# Runs a tool's code in a fresh environment and returns the ellmer tool that
# its last expression creates.
eval_tool_code <- function(code, name) {
if (!is_string(code) || !nzchar(code)) stop("No code was written for this tool.", call. = FALSE)
env <- new.env(parent = globalenv())
tool <- eval(parse(text = code, keep.source = FALSE), envir = env)
if (!inherits(tool, "ellmer::ToolDef")) {
stop("The code's last expression must be an ellmer::tool() call.", call. = FALSE)
}
if (!identical(tool@name, name)) tool@name <- name
tool
}
interview_type <- function() {
ellmer::type_object(
done = ellmer::type_boolean(
description = "true when you know enough to design the workflow and have no more questions."
),
question = ellmer::type_string(
description = "The next question for the user, or an empty string when done."
),
options = ellmer::type_array(
items = ellmer::type_string(),
description = "Two to five short suggested answers, or an empty array for an open question."
)
)
}
check_model_catalog <- function(models) {
if (inherits(models, "Chat")) {
cli::cli_abort("{.arg models} must be a named list of ellmer chat objects, not a single one.")
}
checkmate::assert_list(models, min.len = 1, names = "unique")
for (label in names(models)) {
if (!inherits(models[[label]], "Chat")) {
cli::cli_abort("Model {.val {label}} in {.arg models} is not an ellmer chat object.")
}
}
models
}
# Price per million tokens: a price registered with set_prices() first, then
# ellmer's own table. NULL when neither knows the model.
model_price <- function(provider, model) {
price <- tryCatch(lookup_price(provider, model), error = function(e) NULL)
if (!is.null(price)) return(price)
table <- tryCatch(get("prices", envir = asNamespace("ellmer")), error = function(e) NULL)
if (!is.data.frame(table) || !all(c("provider", "model", "input", "output") %in% names(table))) {
return(NULL)
}
rows <- table[tolower(table$provider) == tolower(provider) & table$model == model, , drop = FALSE]
if ("variant" %in% names(rows) && nrow(rows) > 1L) {
plain <- rows[is.na(rows$variant) | rows$variant == "", , drop = FALSE]
if (nrow(plain)) rows <- plain
}
if (!nrow(rows)) return(NULL)
list(input = rows$input[[1L]], output = rows$output[[1L]])
}
transcript_text <- function(transcript) {
if (!length(transcript)) return("Nothing is known about the workflow yet.")
qa <- vapply(transcript, function(entry) {
paste0("Q: ", entry$question, "\nA: ", entry$answer)
}, character(1))
paste0("What the user said so far:\n", paste(qa, collapse = "\n\n"))
}
blueprint_text <- function(blueprint) {
agents <- vapply(blueprint$agents, function(spec) {
paste0(
"- ", spec$name, " (model: ", spec$model, ", effort: ", spec$effort,
", budget: ", if (is.na(spec$budget)) 0 else spec$budget,
", tools: ", if (length(spec$tools)) paste(spec$tools, collapse = ", ") else "none",
", depends on: ", if (length(spec$depends_on)) paste(spec$depends_on, collapse = ", ") else "nothing",
")\n Task: ", spec$task,
"\n System prompt: ", spec$instruction
)
}, character(1))
tools <- vapply(blueprint$new_tools, function(tool) {
paste0(
"- ", tool$name, ": ", tool$description,
"\n Arguments: ", tool$arguments, "\n Returns: ", tool$returns
)
}, character(1))
paste0(
"Name: ", blueprint$name, "\nSummary: ", blueprint$summary,
"\nPriority: ", blueprint$priority, "\nAgents:\n", paste(agents, collapse = "\n"),
"\nNew tools:\n", if (length(tools)) paste(tools, collapse = "\n") else "none"
)
}
# ellmer turns an array of objects into a data frame; accept that or a list.
spec_rows <- function(agents) {
if (is.data.frame(agents)) {
lapply(seq_len(nrow(agents)), function(i) {
lapply(as.list(agents[i, , drop = FALSE]), function(col) {
if (is.list(col)) col[[1L]] else col
})
})
} else {
agents
}
}
text_field <- function(x, default = "") {
x <- as.character(unlist(x))
x <- x[!is.na(x)]
if (!length(x)) return(default)
trimws(paste(x, collapse = " "))
}
snake_name <- function(x, fallback) {
x <- tolower(gsub("[^A-Za-z0-9]+", "_", text_field(x)))
x <- gsub("^_+|_+$", "", x)
if (!nzchar(x)) fallback else x
}
# Turns the LLM's design into a checked blueprint: unique station-safe names,
# known models and dependencies, no cycles, and stages computed from the
# dependencies.
normalize_blueprint <- function(raw, model_labels, tool_names = character()) {
new_tools <- normalize_new_tools(raw$new_tools, tool_names)
known_tools <- c(tool_names, names(new_tools))
rows <- spec_rows(raw$agents)
if (!length(rows)) {
cli::cli_abort("The blueprint has no agents.", class = "mini007_invalid_blueprint")
}
reserved <- "^(intake|fork_[0-9]+|join_[0-9]+)$"
raw_names <- vapply(seq_along(rows), function(i) {
snake_name(rows[[i]]$name, paste0("agent_", i))
}, character(1))
agent_names <- ifelse(grepl(reserved, raw_names), paste0(raw_names, "_agent"), raw_names)
agent_names <- make.unique(agent_names, sep = "_")
renamed <- stats::setNames(agent_names, raw_names)
agents <- list()
for (i in seq_along(rows)) {
row <- rows[[i]]
model <- text_field(row$model)
if (!model %in% model_labels) {
cli::cli_abort(
"Agent {.val {agent_names[[i]]}} was given the unknown model {.val {model}}.",
class = "mini007_invalid_blueprint"
)
}
effort <- tolower(text_field(row$effort, "medium"))
if (!effort %in% c("low", "medium", "high")) effort <- "medium"
budget <- suppressWarnings(as.numeric(unlist(row$budget)))
budget <- if (length(budget) && !is.na(budget[[1L]]) && budget[[1L]] > 0) budget[[1L]] else NA_real_
deps <- vapply(as.character(unlist(row$depends_on)), snake_name, character(1), fallback = "")
deps <- unname(ifelse(deps %in% names(renamed), renamed[deps], deps))
deps <- unique(deps[nzchar(deps) & deps != agent_names[[i]]])
unknown <- setdiff(deps, agent_names)
if (length(unknown)) {
cli::cli_warn("Agent {.val {agent_names[[i]]}} depends on unknown agent{?s} {.val {unknown}}; dropped.")
deps <- setdiff(deps, unknown)
}
tools <- unique(as.character(unlist(row$tools)))
tools <- trimws(tools[!is.na(tools)])
tools <- unique(vapply(tools, function(tool) {
if (tool %in% known_tools) tool else snake_name(tool, tool)
}, character(1), USE.NAMES = FALSE))
unknown_tools <- setdiff(tools, known_tools)
if (length(unknown_tools)) {
cli::cli_warn("Agent {.val {agent_names[[i]]}} uses unknown tool{?s} {.val {unknown_tools}}; dropped.")
tools <- setdiff(tools, unknown_tools)
}
agents[[agent_names[[i]]]] <- list(
name = agent_names[[i]],
instruction = text_field(row$instruction, "You are a helpful assistant."),
task = text_field(row$task),
model = model,
effort = effort,
budget = budget,
tools = tools,
depends_on = deps,
reason = text_field(row$reason)
)
}
priority <- text_field(raw$priority, "balanced")
structure(
list(
name = snake_name(raw$name, "designed_workflow"),
summary = text_field(raw$summary),
priority = priority,
rationale = text_field(raw$rationale),
agents = agents,
new_tools = unname(new_tools[names(new_tools) %in% unlist(lapply(agents, `[[`, "tools"))]),
stages = blueprint_stages(agents)
),
class = "mini007_blueprint"
)
}
# The new tools proposed by the LLM, keyed by snake_case name, leaving out
# those that are already in the toolbox.
normalize_new_tools <- function(raw_tools, tool_names) {
rows <- spec_rows(raw_tools)
tools <- list()
for (i in seq_along(rows)) {
row <- rows[[i]]
name <- text_field(row$name)
if (!name %in% tool_names) name <- snake_name(name, paste0("tool_", i))
if (name %in% c(tool_names, names(tools))) next
tools[[name]] <- list(
name = name,
description = text_field(row$description),
arguments = text_field(row$arguments),
returns = text_field(row$returns)
)
}
tools
}
# Groups agents into stages: each stage holds the agents whose dependencies
# are all in earlier stages, so the agents of one stage can run in parallel.
blueprint_stages <- function(agents) {
remaining <- names(agents)
done <- character()
stages <- list()
while (length(remaining)) {
ready <- remaining[vapply(remaining, function(name) {
all(agents[[name]]$depends_on %in% done)
}, logical(1))]
if (!length(ready)) {
cli::cli_abort(
c(
"The blueprint's dependencies form a cycle between {.val {remaining}}.",
"i" = "Ask for a revision with {.code $revise()}."
),
class = "mini007_invalid_blueprint"
)
}
stages[[length(stages) + 1L]] <- ready
done <- c(done, ready)
remaining <- setdiff(remaining, ready)
}
stages
}
with_effort <- function(instruction, effort) {
guidance <- switch(
effort,
low = "Keep the work light: answer directly and briefly, without long deliberation.",
medium = "Work carefully and keep your answer focused.",
high = "Take great care: reason through the problem step by step, check your work for errors and gaps, and be thorough."
)
paste0(instruction, "\n\n", guidance)
}
stage_prompt <- function(request, task, inputs) {
parts <- c(
paste0("## Request\n", request),
paste0("## Your task in this workflow\n", task)
)
if (length(inputs)) {
results <- paste0("### ", names(inputs), "\n", unlist(inputs), collapse = "\n\n")
parts <- c(parts, paste0("## Results from earlier steps\n", results))
}
paste(parts, collapse = "\n\n")
}
# The station handler of one designed agent. It reads the request and the
# results it depends on from `ctx`. A handler run in a parallel daemon works
# on a copy of `ctx`, so the stage's merge function records those results.
stage_handler <- function(agent, spec, ctx) {
force(agent)
force(spec)
# Carried in the closure, so a daemon running an older installed mini007
# still has it.
make_prompt <- stage_prompt
function(input) {
inputs <- ctx$outputs[intersect(spec$depends_on, names(ctx$outputs))]
out <- agent$invoke(make_prompt(ctx$request, spec$task, inputs))
out <- paste(as.character(out), collapse = "\n")
ctx$outputs[[spec$name]] <- out
out
}
}
stage_merger <- function(ctx) {
function(results) {
for (name in names(results)) {
ctx$outputs[[name]] <- paste(as.character(results[[name]]), collapse = "\n")
}
paste0("## ", names(results), "\n\n", unlist(results), collapse = "\n\n")
}
}
quietly <- function(expr) {
suppressMessages(expr)
}
console_ask <- function(question, options) {
if (!interactive()) {
cli::cli_abort(c(
"The architect's questions need an interactive R session.",
"i" = "Pass {.arg ask}, a {.code function(question, options)} that returns the answer."
))
}
console_question(question, options, "Type done to stop the questions.")
}
# Asks a question in the console, with numbered options the user can pick
# by number or replace with their own words.
console_question <- function(question, options = NULL, hint = NULL) {
cli::cli_h3(question)
if (length(options)) {
cli::cli_ol(options)
tip <- paste(c("Type a number, or write your own answer.", hint), collapse = " ")
cli::cli_text("{.emph {tip}}")
}
answer <- readline("> ")
choice <- suppressWarnings(as.integer(answer))
if (length(options) && !is.na(choice) && choice >= 1L && choice <= length(options)) {
return(options[[choice]])
}
answer
}
Any scripts or data that you put into this service are public.
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.