Skip to content

Define an R function for use by a chatbot. The function will always be run in the current R instance.

Learn more in vignette("tool-calling").

Usage

tool(
  .fun,
  .description,
  ...,
  .name = NULL,
  .convert = TRUE,
  .annotations = list()
)

Arguments

.fun

The function to be invoked when the tool is called. The return value of the function is sent back to the chatbot.

Expert users can customize the tool result by returning a ContentToolResult object.

.description

A detailed description of what the function does. Generally, the more information that you can provide here, the better.

...

Name-type pairs that define the arguments accepted by the function. Each element should be created by a type_*() function.

.name

The name of the function.

.convert

Should JSON inputs be automatically convert to their R data type equivalents? Defaults to TRUE.

.annotations

Additional properties that describe the tool and its behavior. Usually created by tool_annotations(), where you can find a description of the annotation properties recommended by the Model Context Protocol.

Value

An S7 ToolDef object.

See also

Other tool calling helpers: tool_annotations(), tool_reject()

Examples


# First define the metadata that the model uses to figure out when to
# call the tool
tool_rnorm <- tool(
  rnorm,
  "Drawn numbers from a random normal distribution",
  n = type_integer("The number of observations. Must be a positive integer."),
  mean = type_number("The mean value of the distribution."),
  sd = type_number("The standard deviation of the distribution. Must be a non-negative number."),
  .annotations = tool_annotations(
    title = "Draw Random Normal Numbers",
    read_only_hint = TRUE,
    open_world_hint = FALSE
  )
)
chat <- chat_openai()
#> Using model = "gpt-4.1".
# Then register it
chat$register_tool(tool_rnorm)

# Then ask a question that needs it.
chat$chat("
  Give me five numbers from a random normal distribution.
")
#>  [tool call] rnorm(n = 5L, mean = 0L, sd = 1L)
#>  #> [-1.4,0.2553,-2.4373,-0.0056,0.6216]
#> Here are five numbers drawn from a random normal distribution with 
#> mean 0 and standard deviation 1:
#> 
#> -1.4, 0.2553, -2.4373, -0.0056, 0.6216

# Look at the chat history to see how tool calling works:
# Assistant sends a tool request which is evaluated locally and
# results are send back in a tool result.