|
1 | | -#' Create a ggplot visualization tool |
| 1 | +run_ggplot_code <- function(code) { |
| 2 | + result <- tryCatch( |
| 3 | + run_r_code(code), |
| 4 | + error = function(e) { |
| 5 | + return(ellmer::ContentToolResult(error = conditionMessage(e))) |
| 6 | + } |
| 7 | + ) |
| 8 | + |
| 9 | + if (inherits(result, "ggplot")) { |
| 10 | + temp_file <- tempfile(fileext = ".png") |
| 11 | + ggplot2::ggsave(temp_file, plot = result, width = 7, height = 5, dpi = 150) |
| 12 | + return(ellmer::content_image_file(temp_file)) |
| 13 | + } |
| 14 | + |
| 15 | + ellmer::ContentToolResult(error = "Code did not return a ggplot object") |
| 16 | +} |
| 17 | + |
| 18 | +run_r_code <- function(code) { |
| 19 | + eval(parse(text = code), envir = .GlobalEnv) |
| 20 | +} |
| 21 | + |
| 22 | +#' ggplot visualization tool |
2 | 23 | #' |
3 | | -#' An ellmer tool that wraps `predictive:::run_r_code()` to allow models to |
4 | | -#' create ggplot visualizations. The tool is named "create_ggplot" and accepts |
5 | | -#' R code that returns a ggplot object. This intentionally presents a narrow |
6 | | -#' interface to discourage models from exploring data with arbitrary code. |
| 24 | +#' An ellmer tool that evaluates R code to create ggplot visualizations. |
| 25 | +#' The tool is named "create_ggplot" and accepts R code that returns a ggplot |
| 26 | +#' object. This intentionally presents a narrow interface to discourage models |
| 27 | +#' from exploring data with arbitrary code. |
7 | 28 | #' |
8 | 29 | #' @export |
9 | 30 | tool_create_ggplot <- ellmer::tool( |
10 | | - predictive:::run_r_code, |
| 31 | + run_ggplot_code, |
11 | 32 | name = "create_ggplot", |
12 | 33 | description = "Create a ggplot visualization from the provided R code.", |
13 | 34 | arguments = list( |
14 | 35 | code = ellmer::type_string( |
15 | | - "R code that begins with library(ggplot2) and then a call to the `ggplot()` function. Do _not_ run any code via this tool that could cause side effects in the global environment such as calling `data()` on an object." |
| 36 | + "R code that begins with library(ggplot2) and then a call to the `ggplot()` function. This code runs in the global environment--do _not_ run any code via this tool that could cause side effects in the global environment such as calling `data()` on an object." |
16 | 37 | ) |
17 | 38 | ) |
18 | 39 | ) |
0 commit comments