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")
.
tool(
.fun,
.description,
...,
.name = NULL,
.convert = TRUE,
.annotations = list()
)
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.
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.
The name of the function.
Should JSON inputs be automatically convert to their
R data type equivalents? Defaults to TRUE
.
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.
An S7 ToolDef
object.
Other tool calling helpers:
tool_annotations()
,
tool_reject()
if (FALSE) { # has_credentials("openai")
# 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()
# 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.
")
# 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.
}