Skip to content

Commit

Permalink
some finer error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
romainfrancois committed Feb 9, 2025
1 parent 201a7dc commit 1af10c4
Show file tree
Hide file tree
Showing 4 changed files with 37 additions and 7 deletions.
4 changes: 3 additions & 1 deletion DESCRIPTION
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,7 @@ RoxygenNote: 7.3.2
URL: https://github.com/tadascience/valentine, https://valentine.tada.science/
BugReports: https://github.com/tadascience/valentine/issues
Imports:
cli,
ellmer,
glue
glue,
rlang
2 changes: 2 additions & 0 deletions NAMESPACE
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,7 @@

export(prompt)
export(roses)
importFrom(cli,cli_abort)
importFrom(ellmer,chat_openai)
importFrom(glue,glue)
importFrom(rlang,current_env)
28 changes: 24 additions & 4 deletions R/roses.R
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,12 @@
#' @param pkg A package
#' @param hint extra information to add to the prompt
#' @param emoji Should the poem include emojis ?
#' @param chat A Chat object, e.g. [ellmer::chat_openai()]. The default uses
#' @param chat A [ellmer::Chat] object, e.g. [ellmer::chat_openai()]. The default uses
#' the 'gpt-3.5-turbo' model from OpenAI.
#' @inheritParams rlang::args_error_context
#'
#' @return A lovely poem for your package crush
#'
#' @importFrom glue glue
#' @examples
#' prompt("dplyr")
#'
Expand All @@ -21,11 +21,31 @@
#' roses("dplyr")
#' }
#'
#' @importFrom glue glue
#' @importFrom ellmer chat_openai
#' @importFrom cli cli_abort
#' @importFrom rlang current_env
#' @export
roses <- function(pkg, hint = "", emoji = TRUE, chat = chat_openai(model = "gpt-3.5-turbo")) {
roses <- function(pkg, hint = "", emoji = TRUE, chat = chat_openai(model = "gpt-3.5-turbo"), error_call = current_env()) {
error_handler <- function(e) {
cli_abort(c(
"Problem creating or communicating with the LLM.",
i = "See {.fn ellmer::chat_openai} and friends for details on how to create a {.cls Chat} object.}"
), parent = e, call = error_call)
}

prompt <- prompt(pkg, hint = hint, emoji = emoji)
chat$chat(prompt, echo = "text")

chat <- withCallingHandlers(force(chat), error = error_handler)

if (!inherits(chat, "Chat")) {
cli_abort(
c("The {.arg chat} argument must be a {.cls Chat} object, not {.obj_type_friendly {chat}}."),
call = error_call
)
}

withCallingHandlers(chat$chat(prompt, echo = "text"), error = error_handler)
}

#' @rdname roses
Expand Down
10 changes: 8 additions & 2 deletions man/roses.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 1af10c4

Please sign in to comment.