R/ReActAgent.R

Defines functions format_tool_value react_trace empty_react_trace react_system_prompt

#' ReActAgent: An Agent that Reasons and Acts with Tools
#'
#' @description
#' A `ReActAgent` answers a prompt by looping through the ReAct (Reason + Act)
#' cycle until it can give a final answer:
#'
#' 1. **Think**: the LLM states what it knows and what it needs next.
#' 2. **Act**: it calls one or more of its tools.
#' 3. **Observe**: the tool results are sent back to it.
#' 4. Steps 1 to 3 repeat until the LLM answers without calling a tool.
#'
#' It is an [Agent] with tools: it keeps the same budget, memory, streaming,
#' history and cloning behaviour, and can be registered with a [LeadAgent] or
#' used as a [Workflow] station like any other agent. On top of that it
#' records each step of its last run in `$trace`, and stops a run that goes
#' past `max_steps` tool-using steps.
#'
#' The tool calls themselves go through the LLM provider's native tool calling
#' (via ellmer), not through parsed text, so any ellmer chat model that
#' supports tools can drive it.
#'
#' @export
ReActAgent <- R6::R6Class(
  classname = "ReActAgent",
  inherit = Agent,

  public = list(
    #' @description
    #' Creates a new ReActAgent.
    #'
    #' @param name A short identifier for the agent.
    #' @param instruction The agent's role (eg. `"You are a career advisor."`).
    #'   The ReAct guidance 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 (eg. the output of
    #'   `ellmer::chat_openai()`). It must support tool calling.
    #' @param tools A list of `ellmer::tool()` definitions, or a single one.
    #'   More can be added later with `$register_tools()`.
    #' @param max_steps `[integer(1)]` The largest number of tool-using steps
    #'   in one `$invoke()` call. Once reached, further tool calls are refused
    #'   and the LLM is told to answer with what it has; if it keeps calling
    #'   tools, the run stops with an error of class
    #'   `mini007_react_step_limit`. Defaults to 10.
    #' @param budget Budget in US$ for this agent, as in [Agent].
    #' @examples \dontrun{
    #' search_careers <- ellmer::tool(
    #'   function(interests) {
    #'     if (grepl("help", interests)) c("Teacher", "Counselor") else "Data Analyst"
    #'   },
    #'   description = "Search careers that match a person's interests.",
    #'   arguments = list(interests = ellmer::type_string("The person's interests."))
    #' )
    #'
    #' advisor <- ReActAgent$new(
    #'   name = "career_advisor",
    #'   instruction = "You are a career guidance advisor.",
    #'   llm_object = ellmer::chat_openai(model = "gpt-4.1-mini", echo = "none"),
    #'   tools = list(search_careers)
    #' )
    #' advisor$invoke("I love helping people. Which careers fit me?")
    #' advisor$trace
    #' }
    initialize = function(name, instruction, llm_object, tools = list(),
                          max_steps = 10, budget = NA) {
      checkmate::assert_string(instruction)
      checkmate::assert_count(max_steps, positive = TRUE)

      super$initialize(
        name = name,
        instruction = private$.system_prompt(instruction),
        llm_object = llm_object,
        budget = budget
      )

      self$role <- instruction
      self$max_steps <- as.integer(max_steps)
      self$trace <- empty_react_trace()

      if (length(tools) > 0) {
        self$register_tools(tools)
      }
    },

    #' @description
    #' Runs the ReAct loop on a prompt and returns the final answer.
    #'
    #' Takes the same arguments as `Agent$invoke()`. While streaming, tool
    #' calls and results arrive as `"tool_call"` and `"tool_result"` events.
    #' When the run ends (or fails), `$trace` holds its steps.
    #'
    #' @param prompt A character string prompt.
    #' @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 `Agent$invoke()`. The loop runs
    #'   with the tools as usual, then one more call, without tools, turns
    #'   the answer into the structure.
    #' @return The final answer as a character string, or, with `type`, the
    #'   structured data.
    invoke = function(prompt, stream = FALSE, on_event = NULL, type = NULL) {
      if (length(private$.llm_tool_list()) == 0) {
        cli::cli_abort(c(
          "{class(self)[[1]]} {.val {self$name}} has no tools.",
          "i" = "Register tools with {.code $register_tools()} before invoking it."
        ))
      }

      n_turns_before <- length(self$llm_object$get_turns())
      remove_guard <- private$.add_step_guard()

      completed <- FALSE
      on.exit({
        remove_guard()
        turns <- self$llm_object$get_turns()
        new_turns <- turns[seq_along(turns) > n_turns_before]
        self$trace <- react_trace(new_turns)
        # $invoke() syncs these itself, except when the run stopped early.
        if (!completed) {
          try({
            private$.update_cost()
            private$.set_messages_from_turns()
          }, silent = TRUE)
        }
      }, add = TRUE)

      # ellmer warns about refused tool calls as if they had failed; when the
      # refusals come from the step limit, say that instead.
      private$.limit_reached <- FALSE
      out <- withCallingHandlers(
        withVisible(super$invoke(prompt, stream = stream, on_event = on_event, type = type)),
        warning = function(w) {
          if (isTRUE(private$.limit_reached) &&
              grepl("step\\s+limit\\s+is\\s+reached", conditionMessage(w))) {
            invokeRestart("muffleWarning")
          }
        }
      )
      completed <- TRUE
      if (isTRUE(private$.limit_reached)) {
        cli::cli_alert_warning(paste(
          "{self$name} reached {.arg max_steps} = {self$max_steps};",
          "further tool calls were refused and it answered with what it had."
        ))
      }

      # Keep Agent's visibility: a console-streamed answer is returned invisibly.
      if (out$visible) out$value else invisible(out$value)
    },

    #' @description
    #' Updates the agent's role. The ReAct guidance is kept.
    #' @param new_instruction The new role.
    update_instruction = function(new_instruction) {
      checkmate::assert_string(new_instruction)
      self$role <- new_instruction
      super$update_instruction(private$.system_prompt(new_instruction))
    },

    #' @description
    #' Prints the steps of the last run: Think, Act, Observe and the final
    #' answer.
    #' @param max_chars `[integer(1)]` Longest text shown for one entry.
    print_trace = function(max_chars = 300) {
      checkmate::assert_count(max_chars, positive = TRUE)
      trace <- self$trace

      if (nrow(trace) == 0) {
        cli::cli_alert_info("No run recorded yet.")
        return(invisible(self))
      }

      shorten <- function(x) {
        x <- gsub("\\s+", " ", x)
        if (nchar(x) > max_chars) paste0(substr(x, 1, max_chars), "...") else x
      }

      # Printed to stdout, like a print() method, so it also shows in
      # rendered documents.
      current_step <- 0L
      for (i in seq_len(nrow(trace))) {
        row <- trace[i, ]
        if (row$step != current_step) {
          current_step <- row$step
          cat(cli::rule(left = paste("Step", current_step)), "\n", sep = "")
        }
        text <- shorten(row$content)
        line <- switch(
          row$type,
          think = paste("Think:", text),
          act = paste0("Act: ", row$tool, "(", text, ")"),
          observe = if (isTRUE(row$is_error)) {
            paste0("Observe ", row$tool, " (error): ", text)
          } else {
            paste0("Observe ", row$tool, ": ", text)
          },
          answer = paste("Answer:", text)
        )
        cat(line, "\n", sep = "")
      }

      invisible(self)
    },

    #'@field role The agent's role, without the ReAct guidance.
    role = NULL,
    #'@field max_steps The largest number of tool-using steps in one run.
    max_steps = NULL,
    #'@field trace A data frame with one row per Think, Act, Observe and
    #'  answer entry of the last run, with columns `step`, `type`, `tool`,
    #'  `content` and `is_error`.
    trace = NULL
  ),

  private = list(
    .limit_reached = FALSE,

    # The system prompt built from the agent's role.
    .system_prompt = function(role) react_system_prompt(role),

    # Watches tool calls during one run and enforces `max_steps`. ellmer
    # records the assistant turn before running its tool calls, so a change
    # in the number of turns marks a new step (several tool calls from the
    # same turn are one step). Returns the function that removes the guard.
    .add_step_guard = function() {
      chat <- self$llm_object
      max_steps <- self$max_steps
      agent_name <- self$name
      steps <- 0L
      last_n_turns <- -1L

      chat$on_tool_request(function(request) {
        n_turns <- length(chat$get_turns())
        if (n_turns != last_n_turns) {
          last_n_turns <<- n_turns
          steps <<- steps + 1L
        }

        # The LLM already had one refused step to wrap up and kept going.
        if (steps > max_steps + 1L) {
          cli::cli_abort(
            c(
              "ReActAgent {.val {agent_name}} kept calling tools after reaching {.arg max_steps} = {max_steps}.",
              "i" = "Raise {.arg max_steps}, or narrow the prompt. {.field $trace} shows the steps taken."
            ),
            class = "mini007_react_step_limit",
            call = NULL
          )
        }

        if (steps > max_steps) {
          private$.limit_reached <- TRUE
          ellmer::tool_reject(paste(
            "The step limit is reached.",
            "Do not call more tools: give your final answer with the information you have,",
            "and say what is missing."
          ))
        }
      })
    }
  )
)

# The agent's role followed by the ReAct guidance. Kept free of run-specific
# values (no step counts, no dates) so the system prompt stays the same
# across calls and providers can cache it.
react_system_prompt <- function(role) {
  paste0(
    role,
    "\n\n",
    "Work in a loop of Thought, Action and Observation until you can answer:\n",
    "- Thought: every message in which you call tools must start with one or ",
    "two short sentences of plain text saying what you know so far and what ",
    "you need to find out next. Never call a tool without writing this first. ",
    "Write it as plain sentences, without labels such as 'Thought:' or 'Action:'.\n",
    "- Action: in the same message, call the tool or tools that get that ",
    "information. Lookups that don't depend on each other can be made together.\n",
    "- Observation: read the tool results. If a tool returns an error, fix the ",
    "arguments or try another way.\n",
    "Repeat until you have enough to answer well, then give the final answer ",
    "without calling a tool. Base it on what the tools returned and do not ",
    "invent facts they did not return; if something could not be found, say so."
  )
}

empty_react_trace <- function() {
  data.frame(
    step = integer(0),
    type = character(0),
    tool = character(0),
    content = character(0),
    is_error = logical(0),
    stringsAsFactors = FALSE
  )
}

# Build the Think / Act / Observe / answer table from the ellmer turns of one
# run. Each assistant turn is one step: its text is a Thought when it also
# calls tools and the final answer otherwise; tool results, which ellmer
# stores in the following user turn, are the step's Observations.
react_trace <- function(turns) {
  rows <- list()
  add_row <- function(step, type, content, tool = NA_character_, is_error = FALSE) {
    rows[[length(rows) + 1L]] <<- data.frame(
      step = step,
      type = type,
      tool = tool,
      content = content,
      is_error = is_error,
      stringsAsFactors = FALSE
    )
  }

  step <- 0L
  for (turn in turns) {
    contents <- turn@contents

    if (identical(turn@role, "assistant")) {
      step <- step + 1L
      calls_tools <- any(vapply(
        contents, inherits, logical(1), "ellmer::ContentToolRequest"
      ))

      for (ct in contents) {
        if (inherits(ct, "ellmer::ContentToolRequest")) {
          add_row(step, "act", format_tool_value(ct@arguments), tool = ct@name)
        } else if (inherits(ct, "ellmer::ContentThinking")) {
          if (nzchar(trimws(ct@thinking))) add_row(step, "think", trimws(ct@thinking))
        } else if (inherits(ct, "ellmer::ContentText")) {
          text <- trimws(paste(ct@text, collapse = "\n"))
          if (nzchar(text)) add_row(step, if (calls_tools) "think" else "answer", text)
        } else if (inherits(ct, "ellmer::ContentJson")) {
          add_row(step, "answer", content_json_text(ct))
        }
      }
    } else if (identical(turn@role, "user")) {
      for (ct in contents) {
        if (!inherits(ct, "ellmer::ContentToolResult")) next
        error <- ct@error
        tool <- if (!is.null(ct@request)) ct@request@name else NA_character_
        if (!is.null(error)) {
          message <- if (inherits(error, "condition")) conditionMessage(error) else as.character(error)
          add_row(step, "observe", paste(message, collapse = "\n"), tool = tool, is_error = TRUE)
        } else {
          add_row(step, "observe", format_tool_value(ct@value), tool = tool)
        }
      }
    }
  }

  if (length(rows) == 0) return(empty_react_trace())
  do.call(rbind, rows)
}

# Tool arguments and results as one readable string: JSON when possible.
format_tool_value <- function(value) {
  if (is.character(value) && length(value) == 1L) return(value)
  tryCatch(
    as.character(jsonlite::toJSON(value, auto_unbox = TRUE, null = "null", na = "null")),
    error = function(e) paste(utils::capture.output(utils::str(value)), collapse = "\n")
  )
}

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.