tests/testthat/test-structured-output.R

library(testthat)
library(mini007)

# ── Helpers ───────────────────────────────────────────────────────────────────

setClass("Provider", slots = c(name = "character", model = "character"))

ContentJson <- getFromNamespace("ContentJson", "ellmer")

# A chat whose text replies cost 0.0015 (1000 input and 500 output tokens at
# US$1 per million) and whose structured replies return `self$data`.
StructuredChat <- R6::R6Class(
  "Chat",
  public = list(
    system_prompt = "",
    turns = list(),
    tools = list(),
    provider = NULL,
    data = NULL,
    fail = FALSE,
    structured_prompts = character(),
    tools_seen = NULL,
    initialize = function(data = list(city = "Oran")) {
      self$provider <- new("Provider", name = "tokenco", model = "token-model")
      self$data <- data
    },
    chat = function(prompt) {
      answer <- paste("Answer to:", prompt)
      self$turns <- c(self$turns, list(
        ellmer::Turn("user", list(ellmer::ContentText(prompt))),
        ellmer::Turn("assistant", list(ellmer::ContentText(answer)), tokens = c(1000, 500, 0))
      ))
      answer
    },
    chat_structured = function(prompt, type) {
      if (isTRUE(self$fail)) stop("the answer did not match the type")
      self$structured_prompts <- c(self$structured_prompts, prompt)
      self$tools_seen <- self$tools
      json <- as.character(jsonlite::toJSON(self$data, auto_unbox = TRUE))
      self$turns <- c(self$turns, list(
        ellmer::Turn("user", list(ellmer::ContentText(prompt))),
        ellmer::Turn("assistant", list(ContentJson(data = self$data, string = json)), tokens = c(1000, 500, 0))
      ))
      self$data
    },
    get_cost = function(include = "all") NA_real_,
    set_system_prompt = function(value) { self$system_prompt <- value },
    get_system_prompt = function() self$system_prompt,
    set_turns = function(turns) {
      self$turns <- Filter(function(turn) !identical(turn@role, "system"), turns)
    },
    get_turns = function(include_system_prompt = FALSE) {
      if (!include_system_prompt) return(self$turns)
      c(list(ellmer::Turn("system", list(ellmer::ContentText(self$system_prompt)))), self$turns)
    },
    register_tools = function(tools) {
      for (tool in tools) self$tools[[tool@name]] <- tool
    },
    get_tools = function() self$tools,
    # ReActAgent registers a step guard; this mock never calls tools.
    on_tool_request = function(callback) invisible(function() invisible()),
    set_tools = function(tools) { self$tools <- tools },
    get_provider = function() self$provider
  )
)

local_token_price <- function(env = parent.frame()) {
  clear_prices()
  set_prices("token-model", input = 1, output = 1, provider = "tokenco")
  do.call(on.exit, list(quote(mini007::clear_prices()), add = TRUE), envir = env)
}

city_type <- ellmer::type_object(city = ellmer::type_string())

wilaya_tool <- ellmer::tool(
  function(city) "31",
  name = "wilaya_code",
  description = "Wilaya code of an Algerian city.",
  arguments = list(city = ellmer::type_string("City name."))
)

# ── Agent ─────────────────────────────────────────────────────────────────────

test_that("invoke() with a type returns the structured data", {
  agent <- Agent$new("geo", "You know Algeria.", StructuredChat$new())
  out <- agent$invoke("Name a coastal city.", type = city_type)
  expect_equal(out, list(city = "Oran"))
  expect_equal(agent$llm_object$structured_prompts, "Name a coastal city.")
})

test_that("the structured answer is kept in the history as JSON", {
  agent <- Agent$new("geo", "You know Algeria.", StructuredChat$new())
  agent$invoke("Name a coastal city.", type = city_type)
  last <- agent$messages[[length(agent$messages)]]
  expect_equal(last$role, "assistant")
  expect_equal(last$content, "{\"city\":\"Oran\"}")

  # A text call afterwards works as usual.
  expect_equal(agent$invoke("Why?"), "Answer to: Why?")
  expect_length(agent$messages, 5)
})

test_that("ellmer's wrapper around an array is left out of the history", {
  wrapped <- list(wrapper = list(list(site = "Timgad"), list(site = "Tipasa")))
  agent <- Agent$new("geo", "You know Algeria.", StructuredChat$new(wrapped))
  agent$invoke("List two sites.", type = ellmer::type_array(city_type))
  last <- agent$messages[[length(agent$messages)]]
  expect_equal(last$content, "[{\"site\":\"Timgad\"},{\"site\":\"Tipasa\"}]")
})

test_that("structured calls count towards the cost and the budget", {
  local_token_price()
  agent <- Agent$new("geo", "You know Algeria.", StructuredChat$new(), budget = 0.002)
  agent$invoke("One.", type = city_type)
  expect_equal(agent$cost, 0.0015)
  agent$invoke("Two.", type = city_type)
  expect_equal(agent$cost, 0.003)
  expect_error(agent$invoke("Three.", type = city_type), "exceeded its budget")
})

test_that("an agent with tools answers with them first, then structures the answer", {
  agent <- Agent$new("geo", "You know Algeria.", StructuredChat$new())
  suppressMessages(agent$register_tools(list(wilaya_tool)))

  agent$invoke("Wilaya code of Oran?", type = city_type)

  chat <- agent$llm_object
  # First a text call with the prompt, then the structured call.
  expect_equal(chat$turns[[1]]@contents[[1]]@text, "Wilaya code of Oran?")
  expect_length(chat$structured_prompts, 1)
  expect_match(chat$structured_prompts, "structured data")
  # The structured call ran without tools, and the tools came back after.
  expect_length(chat$tools_seen, 0)
  expect_named(chat$get_tools(), "wilaya_code")
})

test_that("the tools come back even when the structured call fails", {
  agent <- Agent$new("geo", "You know Algeria.", StructuredChat$new())
  suppressMessages(agent$register_tools(list(wilaya_tool)))
  agent$llm_object$fail <- TRUE
  expect_error(
    agent$invoke("Wilaya code of Oran?", type = city_type),
    "could not get a structured response"
  )
  expect_named(agent$llm_object$get_tools(), "wilaya_code")
  # The text call that did run is in the history.
  expect_length(agent$messages, 3)
})

test_that("type must be an ellmer type and cannot be streamed", {
  agent <- Agent$new("geo", "You know Algeria.", StructuredChat$new())
  expect_error(agent$invoke("x", type = list(city = "string")), "must be an ellmer type")
  expect_error(agent$invoke("x", type = city_type, stream = TRUE), "cannot be streamed")
  expect_error(
    agent$invoke("x", type = city_type, on_event = function(e) NULL),
    "cannot be streamed"
  )
  expect_length(agent$llm_object$turns, 0)
})

# ── ReActAgent ────────────────────────────────────────────────────────────────

test_that("a ReActAgent returns structured data and records it in its trace", {
  agent <- ReActAgent$new(
    "coder", "You look up wilaya codes.", StructuredChat$new(list(city = "Oran", code = "31")),
    tools = list(wilaya_tool)
  )
  out <- suppressMessages(agent$invoke("Wilaya code of Oran?", type = city_type))
  expect_equal(out, list(city = "Oran", code = "31"))
  answers <- agent$trace$content[agent$trace$type == "answer"]
  expect_true("{\"city\":\"Oran\",\"code\":\"31\"}" %in% answers)
})

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.