Nothing
#' TaskAgent: An Agent for Long, Multi-Step Tasks
#'
#' @description
#' A `TaskAgent` is a [ReActAgent] built to carry a long task through to the
#' end. On top of the Think / Act / Observe loop and the agent's own tools,
#' it gets:
#'
#' - **A todo list.** For a task with several steps, the agent first writes
#' its todo list (with the built-in `write_todos` tool), then works through
#' it, marking each item `in_progress` and `done`. The list is in `$todos`.
#' - **Rounds until the work is done.** When the agent answers while items of
#' its todo list are not done, it is sent back to work on them, up to
#' `max_rounds` rounds.
#' - **Notes.** The agent saves what it will need later (findings, decisions,
#' intermediate results) with the built-in `save_note` tool and reads it
#' back with `read_note`. Notes are in `$notes`; with a `workspace` folder,
#' they are also saved as Markdown files there and loaded again by the next
#' `TaskAgent` that uses the folder.
#' - **Automatic compaction.** Before each round, when the conversation is
#' longer than `max_context_tokens` (estimated at four characters a token),
#' the older messages are replaced by a summary written by the LLM; the
#' last `keep_recent` messages are kept as they are. Notes and the todo
#' list are not affected.
#' - **Tool approval.** Calls to the tools named in `require_approval` wait
#' for a human's approval: yes, no, or always (do not ask again for this
#' tool). A refused call is reported to the LLM, which carries on without
#' it.
#'
#' Everything else works as with any [Agent]: budget, cost, memory, streaming,
#' structured output, code mode (\code{$set_code_mode()}, where the agent's
#' own tools are called from R code while the todo and note tools stay
#' separate), and use inside a [LeadAgent] or a [Workflow].
#'
#' @export
TaskAgent <- R6::R6Class(
classname = "TaskAgent",
inherit = ReActAgent,
public = list(
#' @description
#' Creates a new TaskAgent.
#'
#' @param name A short identifier for the agent.
#' @param instruction The agent's role. The guidance about todos, notes
#' and the ReAct loop is added to it to form the system prompt; the
#' role alone is kept in `$role`.
#' @param llm_object The LLM object generated by ellmer. It must support
#' tool calling.
#' @param tools A list of `ellmer::tool()` definitions, or a single one.
#' The agent also has its built-in tools (`write_todos`, `save_note`,
#' `read_note`), so it can be created without tools of its own.
#' @param max_steps `[integer(1)]` The largest number of tool-using steps
#' in one round. Defaults to 25.
#' @param max_rounds `[integer(1)]` The largest number of rounds in one
#' \code{$invoke()}. Defaults to 5.
#' @param max_context_tokens `[numeric(1)]` The estimated size of the
#' conversation, in tokens, above which it is compacted before a round.
#' Defaults to 60000. `Inf` turns compaction off.
#' @param keep_recent `[integer(1)]` How many of the latest messages
#' compaction keeps as they are. Defaults to 6.
#' @param workspace `[character(1) | NULL]` A folder where notes are saved
#' as Markdown files, and loaded from when the agent is created. It is
#' created if needed. `NULL` (the default) keeps the notes in memory.
#' @param require_approval `[character]` Names of the tools whose calls
#' need a human's approval, eg. `c("send_email", "run_r_code")`.
#' @param approve `[function | NULL]` How approval is asked: a
#' `function(tool, arguments)` returning `TRUE` (allow this call),
#' `FALSE` (refuse it) or `"always"` (allow it and every later call of
#' this tool). `NULL` (the default) asks in the console.
#' @param budget Budget in US$ for this agent, as in [Agent].
#' @examples \dontrun{
#' monument_info <- ellmer::tool(
#' function(monument) paste("Facts about", monument, "..."),
#' name = "monument_info",
#' description = "Facts about a monument of Algeria.",
#' arguments = list(monument = ellmer::type_string("The monument."))
#' )
#' guide <- TaskAgent$new(
#' name = "guide",
#' instruction = "You write travel guides about Algeria.",
#' llm_object = ellmer::chat("openai/gpt-4.1-mini", echo = "none"),
#' tools = list(monument_info),
#' workspace = "guide-notes"
#' )
#' guide$invoke(paste(
#' "Write a one-day itinerary for Algiers covering the Casbah,",
#' "the Martyrs' Memorial and the Jardin d'Essai, with a fact for each."
#' ))
#' guide$todos
#' guide$notes
#' }
initialize = function(name, instruction, llm_object, tools = list(),
max_steps = 25, max_rounds = 5,
max_context_tokens = 60000, keep_recent = 6,
workspace = NULL, require_approval = character(),
approve = NULL, budget = NA) {
checkmate::assert_count(max_rounds, positive = TRUE)
checkmate::assert_number(max_context_tokens, lower = 1)
checkmate::assert_count(keep_recent, positive = TRUE)
checkmate::assert_string(workspace, null.ok = TRUE)
checkmate::assert_character(require_approval, any.missing = FALSE)
checkmate::assert_function(approve, null.ok = TRUE)
self$max_rounds <- as.integer(max_rounds)
self$max_context_tokens <- max_context_tokens
self$keep_recent <- as.integer(keep_recent)
self$require_approval <- unique(require_approval)
self$approved_tools <- character()
private$.approve <- approve
self$todos <- empty_todos()
self$notes <- list()
if (!is.null(workspace)) {
dir.create(workspace, recursive = TRUE, showWarnings = FALSE)
self$workspace <- normalizePath(workspace, mustWork = TRUE)
self$notes <- read_workspace_notes(self$workspace)
}
super$initialize(
name = name,
instruction = instruction,
llm_object = llm_object,
tools = tools,
max_steps = max_steps,
budget = budget
)
private$.update_llm_tools()
},
#' @description
#' Works on a task until it is done, and returns the final answer.
#'
#' A round is one ReAct loop ([ReActAgent]'s \code{$invoke()}). After a
#' round, if items of the todo list are not done, another round starts,
#' reminding the agent of the task and of what is left, up to
#' `max_rounds` rounds. Before each round, the conversation is compacted
#' if it is too long. The todo list starts empty for each task.
#'
#' While streaming, besides the usual Agent events, `on_event` receives
#' `"round_started"` (with `round`), `"todos_updated"` (with `todos`) and
#' `"context_compacted"` (with `removed`, the number of messages
#' summarised).
#'
#' @param prompt The task.
#' @param stream `[logical(1)]` Whether to stream the response.
#' @param on_event `[function | NULL]` Callback receiving each
#' `mini007_event`; supplying it implies `stream = TRUE`.
#' @param type `[ellmer type | NULL]` To get the final answer as
#' structured data, its shape, as in \code{Agent$invoke()}: once the
#' rounds are over, one more call turns the answer into the structure.
#' @return The final answer, or, with `type`, the structured data. The
#' run is described in `$last_task`, and `$trace` holds the steps of
#' every round, with a `round` column.
invoke = function(prompt, stream = FALSE, on_event = NULL, type = NULL) {
checkmate::assert_string(prompt)
if (!is.null(type)) check_output_type(type, stream, on_event)
on_event <- resolve_on_event(stream, on_event)
# Rebuilt for each task, so that the built-in tools act on this agent
# (and not on the agent it was cloned from).
private$.update_llm_tools()
private$.on_event <- on_event
on.exit(private$.on_event <- NULL, add = TRUE)
remove_approval <- private$.add_approval_guard()
on.exit(remove_approval(), add = TRUE)
self$todos <- empty_todos()
self$last_task <- list(
prompt = prompt, rounds = 0L, compactions = 0L,
todos = self$todos, answer = NA_character_, completed = FALSE,
timestamp = Sys.time()
)
request <- prompt
if (length(self$notes)) {
request <- paste0(
prompt, "\n\n",
"Notes saved earlier (read them with read_note when they help): ",
paste(names(self$notes), collapse = ", "), "."
)
}
# $trace covers every round; ReActAgent's $invoke() resets it to the
# last round's steps, also when a round fails.
trace <- empty_react_trace()
add_round_trace <- function(round) {
steps <- self$trace
if (!nrow(steps)) return(invisible())
steps$step <- steps$step + if (nrow(trace)) max(trace$step) else 0L
steps$round <- rep(round, nrow(steps))
trace <<- rbind(if (nrow(trace)) trace else NULL, steps)
}
round_done <- TRUE
on.exit({
if (!round_done) add_round_trace(self$last_task$rounds)
if (nrow(trace)) self$trace <- trace
}, add = TRUE)
answer <- NULL
for (round in seq_len(self$max_rounds)) {
if (round > 1L) {
request <- continue_prompt(prompt, self$todos)
}
private$.compact_if_needed()
self$last_task$rounds <- round
emit_event(on_event, new_event("round_started", self$name, round = round))
round_done <- FALSE
out <- withVisible(super$invoke(request, on_event = on_event))
add_round_trace(round)
round_done <- TRUE
answer <- out$value
self$last_task$answer <- paste(as.character(answer), collapse = "\n")
self$last_task$todos <- self$todos
if (!any(self$todos$status != "done")) break
}
unfinished <- sum(self$todos$status != "done")
self$last_task$completed <- unfinished == 0L
if (unfinished > 0L) {
cli::cli_alert_warning(paste(
"{self$name} stopped after {self$max_rounds} round{?s} with",
"{unfinished} todo item{?s} not done. See {.field $todos}."
))
}
if (!is.null(type)) {
on.exit(try({
private$.update_cost()
private$.set_messages_from_turns()
}, silent = TRUE), add = TRUE)
return(private$.safe_chat_structured(structured_followup_prompt, type))
}
if (out$visible) answer else invisible(answer)
},
#' @description
#' Prints the todo list.
print_todos = function() {
if (!nrow(self$todos)) {
cli::cli_alert_info("No todo list yet.")
return(invisible(self))
}
marks <- c(pending = "[ ]", in_progress = "[~]", done = "[x]")
cat(paste0(marks[self$todos$status], " ", self$todos$task, "\n"), sep = "")
invisible(self)
},
#' @description
#' Summarises the older messages of the conversation now, whatever its
#' size, keeping the last `keep_recent` messages as they are.
#' @return The agent, invisibly.
compact = function() {
private$.compact(quiet = FALSE)
invisible(self)
},
#' @description
#' Deletes the notes, from `$notes` and from the workspace folder.
#' @param names `[character | NULL]` The notes to delete; `NULL` (the
#' default) deletes them all.
#' @return The agent, invisibly.
clear_notes = function(names = NULL) {
checkmate::assert_character(names, null.ok = TRUE)
if (is.null(names)) names <- names(self$notes)
for (name in intersect(names, names(self$notes))) {
self$notes[[name]] <- NULL
if (!is.null(self$workspace)) {
unlink(note_path(self$workspace, name))
}
}
invisible(self)
},
#' @field todos The todo list of the current or last task: a data frame
#' with columns `task` and `status` (`"pending"`, `"in_progress"` or
#' `"done"`).
todos = NULL,
#' @field notes The notes the agent saved, as a named list of strings.
notes = NULL,
#' @field workspace The folder where notes are saved, or `NULL`.
workspace = NULL,
#' @field max_rounds The largest number of rounds in one task.
max_rounds = NULL,
#' @field max_context_tokens The estimated size above which the
#' conversation is compacted.
max_context_tokens = NULL,
#' @field keep_recent How many of the latest messages compaction keeps.
keep_recent = NULL,
#' @field require_approval The tools whose calls need approval.
require_approval = NULL,
#' @field approved_tools The tools approved for good ("always").
approved_tools = NULL,
#' @field last_task The last task: a list with the `prompt`, the number
#' of `rounds` and `compactions`, the `todos`, the `answer`, whether it
#' `completed` (every todo item done) and a `timestamp`.
last_task = NULL
),
private = list(
.approve = NULL,
.on_event = NULL,
.system_prompt = function(role) task_system_prompt(role),
# The agent's own tools (or its code tool), then the built-in ones.
.llm_tool_list = function() {
c(super$.llm_tool_list(), private$.builtin_tools())
},
.builtin_tools = function() {
list(
ellmer::tool(
function(todos) private$.write_todos(todos),
name = "write_todos",
description = paste(
"Write your todo list for the task, or update it. Always send the",
"whole list, in order, with the status of every item: 'pending',",
"'in_progress' (the item you are working on) or 'done'."
),
arguments = list(
todos = ellmer::type_array(
ellmer::type_object(
task = ellmer::type_string("One thing to do, in a short sentence."),
status = ellmer::type_enum(c("pending", "in_progress", "done"), "Its status.")
),
description = "The whole todo list."
)
)
),
ellmer::tool(
function(name, content) private$.save_note(name, content),
name = "save_note",
description = paste(
"Save a note you will need later: a finding, a decision, an",
"intermediate result. Saving a note with an existing name replaces it.",
"Notes are kept when older messages are summarised."
),
arguments = list(
name = ellmer::type_string("A short name for the note, eg. 'casbah_facts'."),
content = ellmer::type_string("The text of the note.")
)
),
ellmer::tool(
function(name) private$.read_note(name),
name = "read_note",
description = "Read a note saved earlier.",
arguments = list(
name = ellmer::type_string("The name of the note.")
)
)
)
},
.write_todos = function(todos) {
before <- self$todos
self$todos <- as_todos(todos)
dropped <- setdiff(before$task[before$status != "done"], self$todos$task)
emit_event(private$.on_event, new_event("todos_updated", self$name, todos = self$todos))
left <- sum(self$todos$status != "done")
paste0(
"Todo list saved (", nrow(self$todos), " item", if (nrow(self$todos) == 1L) "" else "s",
", ", left, " not done):\n", format_todos(self$todos),
if (length(dropped)) paste0(
"\nThese items were not done and are no longer in the list: ",
paste0("'", dropped, "'", collapse = ", "), ". If they still need doing, ",
"put them back; if they are done, keep them in the list marked 'done'."
)
)
},
.save_note = function(name, content) {
name <- trimws(name)
if (!nzchar(name)) stop("The note needs a name.", call. = FALSE)
self$notes[[name]] <- content
if (!is.null(self$workspace)) {
writeLines(content, note_path(self$workspace, name), useBytes = TRUE)
}
paste0("Note '", name, "' saved.")
},
.read_note = function(name) {
note <- self$notes[[trimws(name)]]
if (is.null(note)) {
available <- names(self$notes)
stop(paste0(
"There is no note called '", name, "'. ",
if (length(available)) paste0("Saved notes: ", paste(available, collapse = ", "), ".") else "No note is saved."
), call. = FALSE)
}
note
},
# Asks for approval before the calls of the tools in `require_approval`.
# Returns the function that removes the guard.
.add_approval_guard = function() {
if (!length(self$require_approval)) return(function() invisible())
approve <- private$.approve %||% console_approval
self$llm_object$on_tool_request(function(request) {
tool <- request@name
if (!tool %in% self$require_approval || tool %in% self$approved_tools) return(invisible())
answer <- approve(tool, request@arguments)
if (identical(answer, "always")) {
self$approved_tools <- union(self$approved_tools, tool)
return(invisible())
}
if (!isTRUE(answer)) {
ellmer::tool_reject(paste(
"A human did not allow this call. Do not try it again;",
"carry on without it, or ask for what you need."
))
}
invisible()
})
},
.compact_if_needed = function() {
if (!is.finite(self$max_context_tokens)) return(invisible(FALSE))
size <- sum(nchar(vapply(self$messages, function(m) m$content, character(1)))) / 4
if (size <= self$max_context_tokens) return(invisible(FALSE))
private$.compact(quiet = TRUE)
},
# Replaces the messages before the last `keep_recent` by a summary. The
# kept part starts with a user message, so that roles still alternate.
.compact = function(quiet = TRUE) {
messages <- self$messages
body <- messages[-1L]
start <- length(body) - self$keep_recent + 1L
while (start > 1L && !identical(body[[start]]$role, "user")) start <- start - 1L
if (start <= 1L) {
if (!quiet) cli::cli_alert_info("{self$name}: the conversation is too short to compact.")
return(invisible(FALSE))
}
older <- body[seq_len(start - 1L)]
recent <- body[start:length(body)]
summary <- private$.summarise(older)
private$._messages <- c(
messages[1L],
list(
list(role = "user", content = paste0(
"Summary of the earlier part of our conversation:\n\n", summary
)),
list(role = "assistant", content = "Noted. I will carry on from there.")
),
lapply(recent, flatten_tool_message)
)
private$.set_turns_from_messages()
private$.update_cost()
if (is.list(self$last_task)) {
self$last_task$compactions <- self$last_task$compactions + 1L
}
emit_event(private$.on_event, new_event(
"context_compacted", self$name, text = summary, removed = length(older)
))
cli::cli_alert_info("{self$name}: {length(older)} older message{?s} summarised.")
invisible(TRUE)
},
# Writes the summary on a blank copy of the chat (no history, no
# tools), so that the older messages are sent once, and adds what it
# cost to the agent's cost.
.summarise = function(messages) {
if (!is.na(self$budget)) private$.check_budget()
summariser <- self$llm_object$clone(deep = TRUE)
summariser$set_turns(list())
suppressMessages(summariser$set_tools(list()))
summary <- tryCatch(
summariser$chat(compaction_prompt(messages)),
error = function(e) {
cli::cli_abort(
c("{self$name} could not summarise its conversation.", "x" = conditionMessage(e)),
parent = e, call = NULL
)
}
)
cost <- llm_cost(summariser)
if (!is.na(cost)) private$.cost_offset <- private$.cost_offset + cost
trimws(paste(as.character(summary), collapse = "\n"))
}
)
)
# The role, then how to work: todos, notes, the ReAct loop.
task_system_prompt <- function(role) {
paste0(
react_system_prompt(role),
"\n\n",
"How to carry out a task:\n",
"- A simple question or a one-step request: answer it directly, without ",
"a todo list and without notes.\n",
"- For a task with several steps, your first action is to write a todo ",
"list with the write_todos tool, before calling any other tool: one item ",
"per part of the task, in order.\n",
"- Work through the list in order. Mark an item 'in_progress' when you ",
"start it and 'done' as soon as it is finished, by sending the updated ",
"list. Add, remove or reword items when you learn something that changes ",
"the plan, but never merge or drop items just to finish the list.\n",
"- Save anything you will need later with save_note (findings, decisions, ",
"intermediate results). Older messages may be summarised; notes are kept ",
"as they are. Use read_note only for notes you saved or that are listed as ",
"saved.\n",
"- Before the final answer, send the list once more with every item ",
"marked 'done', then give the final answer."
)
}
continue_prompt <- function(task, todos) {
paste0(
"Your todo list is not finished:\n", format_todos(todos), "\n\n",
"Carry on with the items that are not done, keeping the list up to date ",
"with write_todos. If some of them are in fact done, mark them 'done'. ",
"When everything is done, give the final answer to the task in full: it ",
"replaces your earlier answer.\n\nThe task:\n", task
)
}
compaction_prompt <- function(messages) {
transcript <- paste(vapply(messages, function(m) {
paste0(m$role, ": ", m$content)
}, character(1)), collapse = "\n\n")
paste0(
"The conversation is getting long, so its older part, below, will be ",
"replaced by a summary. Write that summary, so that the conversation can ",
"go on without the older messages: what the user asked, what was done, ",
"the facts and results found (with exact names, numbers and sources), the ",
"decisions taken and what is left to do. Write only the summary itself, ",
"in a few short paragraphs or bullet points, starting with what the user ",
"asked; do not mention this request. Leave out anything that no longer ",
"matters.\n\n",
"The older part of the conversation:\n\n", transcript
)
}
empty_todos <- function() {
data.frame(task = character(), status = character(), stringsAsFactors = FALSE)
}
# The todo list sent by the LLM (a data frame or a list of items) as a
# data frame with `task` and `status`.
as_todos <- function(todos) {
if (is.data.frame(todos)) {
items <- lapply(seq_len(nrow(todos)), function(i) as.list(todos[i, , drop = FALSE]))
} else if (is.list(todos)) {
items <- todos
} else {
stop("`todos` must be a list of items, each with a task and a status.", call. = FALSE)
}
task <- vapply(items, function(item) {
one_line(paste(as.character(item$task %||% ""), collapse = " "))
}, character(1))
status <- vapply(items, function(item) {
s <- tolower(trimws(paste(as.character(item$status %||% "pending"), collapse = "")))
if (s %in% c("pending", "in_progress", "done")) s else "pending"
}, character(1))
keep <- nzchar(task)
data.frame(task = task[keep], status = status[keep], stringsAsFactors = FALSE)
}
format_todos <- function(todos) {
if (!nrow(todos)) return("(empty)")
paste0("- [", todos$status, "] ", todos$task, collapse = "\n")
}
# A message whose tool requests and results are written as plain text, so
# that the history can be rebuilt from it without the tools.
flatten_tool_message <- function(message) {
content <- message$content
content <- gsub("\\[tool request id=[^]]*\\]:", "[called tool]", content)
content <- gsub("\\[tool result id=[^]]*\\]:", "[tool result]", content)
message$content <- content
message
}
note_path <- function(workspace, name) {
file.path(workspace, paste0(tool_name_for(name), ".md"))
}
read_workspace_notes <- function(workspace) {
files <- list.files(workspace, pattern = "\\.md$", full.names = TRUE)
notes <- lapply(files, function(file) paste(readLines(file, warn = FALSE), collapse = "\n"))
names(notes) <- sub("\\.md$", "", basename(files))
notes
}
# Asks in the console whether a tool call may run.
console_approval <- function(tool, arguments) {
cli::cli_rule(left = "Approval needed")
cli::cli_text("The agent wants to call {.strong {tool}}.")
if (identical(tool, "run_r_code") && is.character(arguments$code)) {
cat(arguments$code, "\n", sep = "")
} else if (length(arguments)) {
cat(format_tool_value(arguments), "\n", sep = "")
}
answer <- tolower(trimws(readline("Allow it? [y]es / [n]o / [a]lways for this tool: ")))
if (answer %in% c("a", "always")) return("always")
answer %in% c("y", "yes")
}
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.