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
ToolDef(fun, name, description, arguments = list(), ...)
ToolArg(type, description, required = TRUE, ...)
Arguments
- fun
The function to be invoked when the tool is called.
- name
The name of the function.
- description
Description of argument as free text.
- arguments
A named list of arguments that the function accepts. Should be a named list of objects created by
ToolArg()
.- ...
Additional provider specific JSON Schema properties (e.g.
properties
,enum
,pattern
).For example, OpenAI supports a
strict
parameter that whenTRUE
enables Structured Output mode, which comes with a number of additional requirements.- type
Argument type (
"null"
,"boolean"
,"object"
,"array"
,"number"
, or"string"
).- required
Is the argument required?
Examples
if (FALSE) { # elmer:::openai_key_exists()
# First define the metadata that the model uses to figure out when to
# call the tool
tool_rnorm <- ToolDef(
rnorm,
description = "Drawn numbers from a random normal distribution",
arguments = list(
n = ToolArg(
type = "integer",
description = "The number of observations. Must be a positive integer."
),
mean = ToolArg(
type = "number",
description = "The mean value of the distribution."
),
sd = ToolArg(
type = "number",
description = "The standard deviation of the distribution. Must be a non-negative number."
)
)
)
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.
chat
}