Skip to contents

Wrap an R function with metadata so Claude can use it as a tool.

Usage

claude_tool(fn, name, desc, ...)

Arguments

fn

Function. The R function to expose to Claude.

name

Character. Tool name (snake_case, no spaces).

desc

Character. What the tool does and when to use it.

...

Named arguments defining tool parameters. Each should be created with ellmer type functions: type_string(), type_integer(), type_number(), type_boolean(), type_enum(), type_array(), type_object().

Value

An ellmer tool object for use with claude_new().

Details

Claude will automatically decide when to call your tool based on the description and parameter definitions. Provide clear, specific descriptions.

Parameter types from ellmer:

  • type_string(desc): Text input

  • type_integer(desc): Whole numbers

  • type_number(desc): Decimal numbers

  • type_boolean(desc): TRUE/FALSE

  • type_enum(values, desc): Fixed set of choices

  • type_array(items, desc): List of items

  • type_object(...): Nested object

Examples

if (FALSE) { # \dontrun{
# Simple tool
greet_tool <- claude_tool(
  fn = function(name) paste("Hello,", name),
  name = "greet",
  desc = "Greet a person by name",
  name = ellmer::type_string("Person's name")
)

# Tool with multiple parameters
search_tool <- claude_tool(
  fn = function(query, limit = 10) {
    paste("Found", limit, "results for:", query)
  },
  name = "search_database",
  desc = "Search the artwork database",
  query = ellmer::type_string("Search query"),
  limit = ellmer::type_integer("Max results (default 10)")
)

# Tool with enum parameter
format_tool <- claude_tool(
  fn = function(text, style) {
    switch(style,
      uppercase = toupper(text),
      lowercase = tolower(text),
      title = tools::toTitleCase(text)
    )
  },
  name = "format_text",
  desc = "Format text in different styles",
  text = ellmer::type_string("Text to format"),
  style = ellmer::type_enum(
    c("uppercase", "lowercase", "title"),
    "Formatting style"
  )
)

# Use tools with claude_new()
chat <- claude_new(tools = list(greet_tool, search_tool))
chat$chat("Greet Alice and search for impressionist paintings")
} # }