Skip to content

Commit

Permalink
Change default tool result serialization (#231)
Browse files Browse the repository at this point in the history
Instead of toString, use toJSON. But don't
over-encode strings or already-converted JSON.
  • Loading branch information
jcheng5 authored Dec 18, 2024
1 parent 3393463 commit 76185fb
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 1 deletion.
6 changes: 6 additions & 0 deletions R/chat.R
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,12 @@ Chat <- R6::R6Class("Chat",
#' @description Register a tool (an R function) that the chatbot can use.
#' If the chatbot decides to use the function, elmer will automatically
#' call it and submit the results back.
#'
#' The return value of the function. Generally, this should either be a
#' string, or a JSON-serializable value. If you must have more direct
#' control of the structure of the JSON that's returned, you can return a
#' JSON-serializable value wrapped in [base::I()], which elmer will leave
#' alone until the entire request is JSON-serialized.
#' @param tool_def Tool definition created by [tool()].
register_tool = function(tool_def) {
if (!S7_inherits(tool_def, ToolDef)) {
Expand Down
8 changes: 7 additions & 1 deletion R/content.R
Original file line number Diff line number Diff line change
Expand Up @@ -215,8 +215,14 @@ tool_errored <- function(x) !is.null(x@error)
tool_string <- function(x) {
if (tool_errored(x)) {
paste0("Tool calling failed with error ", x@error)
} else if (inherits(x@value, "AsIs")) {
x@value
} else if (inherits(x@value, "json")) {
x@value
} else if (is.character(x@value)) {
paste(x@value, collapse = "\n")
} else {
toString(x@value)
jsonlite::toJSON(x@value, auto_unbox = TRUE)
}
}

Expand Down

0 comments on commit 76185fb

Please sign in to comment.