R/structured.R

Defines functions content_json_text check_output_type

# Helpers for structured output: `$invoke(prompt, type = ...)`.

# The prompt that turns an agent's text answer into structured data, used
# when the agent first answered with its tools.
structured_followup_prompt <- paste(
  "Now give the answer to my previous request as structured data,",
  "based on what you found."
)

# Checks the `type` argument of `$invoke()`.
check_output_type <- function(type, stream, on_event) {
  if (!inherits(type, "ellmer::Type")) {
    cli::cli_abort(c(
      "{.arg type} must be an ellmer type, such as {.code ellmer::type_object()}.",
      "x" = "You supplied {.obj_type_friendly {type}}."
    ), call = NULL)
  }
  if (isTRUE(stream) || !is.null(on_event)) {
    cli::cli_abort(c(
      "Structured output cannot be streamed.",
      "i" = "Call {.code $invoke()} with {.arg type} and without {.arg stream} or {.arg on_event}."
    ), call = NULL)
  }
  invisible(type)
}

# The text of an ellmer ContentJson: the JSON the model returned. ellmer
# wraps an answer that is not an object (eg. an array) in
# `{"wrapper": ...}`, since providers want an object; that wrapper is left out.
content_json_text <- function(ct) {
  data <- tryCatch(ct@data, error = function(e) NULL)
  if (is.list(data) && identical(names(data), "wrapper")) {
    return(as.character(jsonlite::toJSON(data$wrapper, auto_unbox = TRUE, null = "null")))
  }
  string <- tryCatch(ct@string, error = function(e) NULL)
  if (is.character(string) && length(string) == 1L && !is.na(string) && nzchar(string)) {
    return(string)
  }
  if (is.null(data)) data <- tryCatch(ct@parsed, error = function(e) NULL)
  as.character(jsonlite::toJSON(data, auto_unbox = TRUE, null = "null"))
}

Try the mini007 package in your browser

Any scripts or data that you put into this service are public.

mini007 documentation built on Dec. 3, 2026, 5:10 p.m.