R/as_tool.R

Defines functions default_tool_description agent_as_tool tool_name_for

# Agents as tools: `$as_tool()` wraps an agent in an ellmer tool, so that
# another agent (usually a ReActAgent) can call it in its tool loop.

# A tool name the LLM providers accept: letters, digits, `_` and `-`.
tool_name_for <- function(name) {
  out <- gsub("[^A-Za-z0-9_-]+", "_", name)
  out <- gsub("^_+|_+$", "", out)
  if (!nzchar(out)) out <- "agent"
  substr(out, 1L, 64L)
}

# Builds the tool. `agent` is any object with `$invoke(prompt)` and
# `$reset_conversation_history()`: an Agent (or subclass) or a WorkflowAgent.
#
# The agent is bound in this function's frame, which the tool function
# closes over, so that parallel runs (see find_agents()) can find it and
# bring its conversation and cost back from the daemons.
agent_as_tool <- function(agent, name, description, fresh) {
  force(agent)
  checkmate::assert_string(name, min.chars = 1)
  checkmate::assert_string(description, min.chars = 1)
  checkmate::assert_flag(fresh)

  run <- function(request) {
    if (fresh) suppressMessages(agent$reset_conversation_history())
    paste(as.character(agent$invoke(request)), collapse = "\n")
  }

  ellmer::tool(
    run,
    name = tool_name_for(name),
    description = description,
    arguments = list(
      request = ellmer::type_string(paste(
        "The question or task for this agent, with all the context it needs:",
        "it does not see your conversation."
      ))
    )
  )
}

# Default description of an agent used as a tool.
default_tool_description <- function(name, role) {
  role <- one_line(paste(role, collapse = " "))
  if (nchar(role) > 500L) role <- paste0(substr(role, 1L, 497L), "...")
  paste0("Ask the agent '", name, "'. Its role: ", role)
}

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.