R/RouterAgent.R

Defines functions one_line route_description is_routable

#' RouterAgent: Send Each Request to the Right Agent
#'
#' @description
#' A `RouterAgent` classifies each request and hands it, unchanged, to the one
#' registered agent best suited to it. Unlike a [LeadAgent], it never splits
#' the request into subtasks: its LLM only picks a route, and the chosen
#' agent writes the whole answer.
#'
#' Each registered agent is one route. The route's label is the agent's name,
#' and its description, which the LLM reads when choosing, is the agent's
#' instruction (the role, for a [ReActAgent]) unless another description is
#' given to `$register_agents()`.
#'
#' Choosing a route takes one structured LLM call: the LLM must return one of
#' the route labels, or `"none"` when no route fits, along with a short
#' reason. A `"none"` goes to the fallback agent set with `$set_fallback()`,
#' and is an error of class `mini007_no_route` when there is none.
#'
#' @details
#' The routing calls go through the router's own `llm_object`, so they add
#' to its turn history and its cost. That history lets the router route a
#' follow-up such as "and how do I pay for it?" in the light of the previous
#' requests.
#'
#' A `RouterAgent` is an [Agent]: it can itself be registered with a
#' [LeadAgent] or used as a [Workflow] station.
#'
#' @export
RouterAgent <- R6::R6Class(
  classname = "RouterAgent",
  inherit = Agent,

  public = list(

    #' @field agents The registered agents, one per route.
    agents = list(),
    #' @field fallback Name of the agent that handles requests no route fits,
    #'   or `NULL`. Set via \code{$set_fallback()}.
    fallback = NULL,
    #' @field routing_history One entry per routed request: the `prompt`, the
    #'   `agent_name` and `agent_id` it went to, the LLM's `reason`, whether
    #'   the `fallback` was used, the `response` and a `timestamp`.
    routing_history = list(),

    #' @description
    #' Creates a new RouterAgent.
    #' @param name A short name for the router (eg. `"router"`).
    #' @param llm_object The LLM object generated by ellmer (eg. the output of
    #'   `ellmer::chat_openai()`). It must support structured output.
    #' @param budget Budget in US$ for the routing calls, as in [Agent].
    #' @examples \dontrun{
    #' llm <- ellmer::chat("openai/gpt-4.1-mini", echo = "none")
    #'
    #' career <- Agent$new("career", "You recommend careers that fit a person.", llm)
    #' training <- Agent$new("training", "You recommend schools, bootcamps and courses.", llm)
    #' funding <- Agent$new("funding", "You explain scholarships, grants and loans.", llm)
    #'
    #' router <- RouterAgent$new(name = "router", llm_object = llm)
    #' router$register_agents(list(career, training, funding))
    #'
    #' router$invoke("Which scholarships can help me pay for a nursing degree?")
    #' router$last_route()
    #' }
    initialize = function(name, llm_object, budget = NA) {
      super$initialize(
        name = name,
        instruction = router_system_prompt,
        llm_object = llm_object,
        budget = budget
      )
    },

    #' @description
    #' Registers one or more agents, each as a route.
    #'
    #' @param agents An `Agent` (or [ReActAgent], [WorkflowAgent], ...) or a
    #'   list of them. Any object with a `name` and an `$invoke(prompt)`
    #'   method works. Agent names are the route labels, so they must be
    #'   unique and cannot be `"none"`.
    #' @param descriptions Optional character vector, one per agent, telling
    #'   the router when to pick each one. Defaults to each agent's
    #'   instruction (its role, for a [ReActAgent]).
    #' @return The router, invisibly.
    register_agents = function(agents, descriptions = NULL) {
      if (is_routable(agents)) agents <- list(agents)
      checkmate::assert_list(agents, min.len = 1)

      for (agent in agents) {
        if (!is_routable(agent)) {
          cli::cli_abort(paste(
            "Every agent must have a {.field name} and an {.fn invoke} method,",
            "like an {.cls Agent} or a {.cls WorkflowAgent}."
          ))
        }
      }

      if (!is.null(descriptions)) {
        checkmate::assert_character(
          descriptions, len = length(agents), any.missing = FALSE, min.chars = 1
        )
      }

      new_names <- vapply(agents, function(agent) agent$name, character(1))
      all_names <- c(self$route_names(), new_names)
      if ("none" %in% new_names) {
        cli::cli_abort("{.val none} is reserved for requests that no route fits; rename that agent.")
      }
      if (anyDuplicated(all_names)) {
        cli::cli_abort(c(
          "Agent names are route labels and must be unique.",
          "x" = "Duplicated: {.val {unique(all_names[duplicated(all_names)])}}."
        ))
      }

      for (i in seq_along(agents)) {
        agent <- agents[[i]]
        self$agents[[length(self$agents) + 1L]] <- agent
        private$.descriptions[[agent$name]] <- if (!is.null(descriptions)) {
          descriptions[[i]]
        } else {
          route_description(agent)
        }
      }

      cli::cli_alert_success("Registered route{?s}: {.val {new_names}}")
      invisible(self)
    },

    #' @description
    #' Removes routes by agent name.
    #' @param agent_names Names of the agents to remove.
    #' @return The router, invisibly.
    remove_agents = function(agent_names) {
      checkmate::assert_character(agent_names, any.missing = FALSE)
      self$agents <- Filter(function(agent) !agent$name %in% agent_names, self$agents)
      private$.descriptions[agent_names] <- NULL
      if (!is.null(self$fallback) && self$fallback %in% agent_names) {
        self$fallback <- NULL
      }
      invisible(self)
    },

    #' @description
    #' Removes every route, and the fallback.
    #' @return The router, invisibly.
    clear_agents = function() {
      self$agents <- list()
      self$fallback <- NULL
      private$.descriptions <- list()
      invisible(self)
    },

    #' @description
    #' The route labels: the names of the registered agents.
    #' @return A character vector.
    route_names = function() {
      vapply(self$agents, function(agent) agent$name, character(1))
    },

    #' @description
    #' Sets the agent that handles requests no route fits.
    #' @param agent_name The name of a registered agent, or `NULL` to make an
    #'   unroutable request an error again.
    #' @return The router, invisibly.
    set_fallback = function(agent_name = NULL) {
      if (!is.null(agent_name)) {
        checkmate::assert_string(agent_name)
        if (!agent_name %in% self$route_names()) {
          cli::cli_abort("No registered agent is named {.val {agent_name}}.")
        }
      }
      self$fallback <- agent_name
      invisible(self)
    },

    #' @description
    #' Chooses the route for a request without running it.
    #' @param prompt The request.
    #' @return A list with `agent_name`, `agent_id` (`NA` for agents without
    #'   one), `reason`, and `fallback` (`TRUE` when no route fitted and the
    #'   fallback agent was chosen).
    route = function(prompt) {
      checkmate::assert_string(prompt)

      if (length(self$agents) == 0L) {
        cli::cli_abort(c(
          "RouterAgent {.val {self$name}} has no routes.",
          "i" = "Register agents with {.code $register_agents()}."
        ))
      }

      if (!is.na(self$budget)) {
        private$.check_budget()
      }

      decision <- private$.classify(prompt)

      private$.update_cost()
      private$.set_messages_from_turns()

      used_fallback <- identical(decision$route, "none")
      if (used_fallback) {
        if (is.null(self$fallback)) {
          cli::cli_abort(
            c(
              "RouterAgent {.val {self$name}} found no route for this request.",
              "i" = "Reason given: {decision$reason}",
              "i" = "Register an agent that covers it, or set one with {.code $set_fallback()}."
            ),
            class = "mini007_no_route",
            call = NULL
          )
        }
        decision$route <- self$fallback
      }

      agent <- private$.agent_named(decision$route)
      list(
        agent_name = agent$name,
        agent_id = if (is.null(agent$agent_id)) NA_character_ else agent$agent_id,
        reason = decision$reason,
        fallback = used_fallback
      )
    },

    #' @description
    #' Routes a request to one agent and returns that agent's answer.
    #'
    #' While streaming, a `"route_selected"` event (with `agent` and
    #' `reason` in its `data`) comes first, then the chosen agent's own
    #' events, each tagged with `agent`, then a `"router_output"` event.
    #'
    #' @param prompt The request.
    #' @param stream `[logical(1)]` Whether to stream the chosen agent's
    #'   response.
    #' @param on_event `[function | NULL]` Callback receiving each
    #'   `mini007_event`; supplying it implies `stream = TRUE`.
    #' @return The chosen agent's response as a character string.
    invoke = function(prompt, stream = FALSE, on_event = NULL) {
      checkmate::assert_string(prompt)
      on_event <- resolve_on_event(stream, on_event)

      decision <- self$route(prompt)
      agent <- private$.agent_named(decision$agent_name)

      emit_event(on_event, new_event(
        "route_selected", self$name,
        agent = decision$agent_name,
        reason = decision$reason,
        fallback = decision$fallback
      ))

      response <- invoke_with_events(
        agent, prompt, forward_events(on_event, agent = decision$agent_name)
      )
      response <- paste(as.character(response), collapse = "\n")

      self$routing_history[[length(self$routing_history) + 1L]] <- list(
        prompt = prompt,
        agent_name = decision$agent_name,
        agent_id = decision$agent_id,
        reason = decision$reason,
        fallback = decision$fallback,
        response = response,
        timestamp = Sys.time()
      )

      emit_event(on_event, new_event(
        "router_output", self$name, text = response, agent = decision$agent_name
      ))

      # Already printed token by token: don't print it a second time.
      if (is_console_handler(on_event)) {
        return(invisible(response))
      }
      response
    },

    #' @description
    #' The most recent routing decision.
    #' @return The last entry of `routing_history`, or `NULL`.
    last_route = function() {
      n <- length(self$routing_history)
      if (n == 0L) return(NULL)
      self$routing_history[[n]]
    }
  ),

  private = list(

    # Default description when the router is used as a tool.
    .tool_description = function() {
      routes <- self$route_names()
      paste0(
        "Ask '", self$name, "', who sends each request to the right agent",
        if (length(routes)) paste0(" among: ", paste(routes, collapse = ", ")) else "",
        "."
      )
    },
    .descriptions = list(),

    # One structured call: the LLM gives a short reason, then a route label
    # constrained to the registered names or "none".
    .classify = function(prompt) {
      labels <- self$route_names()
      routes <- paste0(
        "- ", labels, ": ",
        vapply(labels, function(label) one_line(private$.descriptions[[label]]), character(1)),
        collapse = "\n"
      )

      type <- ellmer::type_object(
        reason = ellmer::type_string(
          description = "One short sentence on what the request is mainly about and why that route fits."
        ),
        route = ellmer::type_enum(
          values = c(labels, "none"),
          description = "The label of the route that should handle the request, or 'none' if no route fits."
        )
      )

      result <- tryCatch(
        self$llm_object$chat_structured(
          paste0("Routes:\n", routes, "\n\nRequest:\n", prompt),
          type = type
        ),
        error = function(e) {
          cli::cli_abort(
            c(
              "RouterAgent {.val {self$name}} could not choose a route.",
              "x" = conditionMessage(e)
            ),
            parent = e,
            call = NULL
          )
        }
      )

      route <- trimws(as.character(result$route))
      if (length(route) != 1L || !route %in% c(labels, "none")) {
        cli::cli_abort("RouterAgent {.val {self$name}}: the LLM returned an unknown route {.val {route}}.")
      }

      list(route = route, reason = trimws(paste(as.character(result$reason), collapse = " ")))
    },

    .agent_named = function(name) {
      self$agents[[match(name, self$route_names())]]
    }
  )
)

router_system_prompt <- paste(
  "You are a request router. You receive a list of routes, each with a label",
  "and a description, followed by a request. Decide what the request is mainly",
  "about and choose the single route whose description fits it best. Do not",
  "answer the request yourself. Choose 'none' only when no route fits at all."
)

is_routable <- function(x) {
  is.environment(x) && is.character(x$name) && length(x$name) == 1L &&
    is.function(x$invoke)
}

# What the router reads about a route: the agent's role when it has one (a
# ReActAgent's instruction also carries its ReAct guidance), else its
# instruction.
route_description <- function(agent) {
  for (field in c("role", "instruction")) {
    value <- tryCatch(agent[[field]], error = function(e) NULL)
    if (is.character(value) && length(value) == 1L && nzchar(value)) return(value)
  }
  agent$name
}

one_line <- function(x) trimws(gsub("\\s+", " ", x))

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.