diff --git a/R/chat.R b/R/chat.R index a42d32a..2ae70d2 100644 --- a/R/chat.R +++ b/R/chat.R @@ -24,17 +24,6 @@ chat <- function(messages, model = "mistral-tiny", ..., error_call = current_env resp <- authenticate(req, error_call = error_call) |> req_mistral_perform(error_call = error_call) - - req_messages <- x$request$body$data$messages - df_req <- map_dfr(req_messages, as.data.frame) - - df_resp <- as.data.frame( - resp_body_json(x)$choices[[1]]$message[c("role", "content")] - ) - - rbind(df_req, df_resp) - - class(resp) <- c("chat", class(resp)) resp } diff --git a/R/httr2.R b/R/httr2.R index dd370ee..2ba7a36 100644 --- a/R/httr2.R +++ b/R/httr2.R @@ -1,54 +1,30 @@ req_mistral_perform <- function(req, error_call = caller_env()) { - withCallingHandlers( - req_perform(req), - error = function(err) { - resp <- err$resp - handler <- mistral_error_handler(err, resp, req) - handler(err, req, resp, error_call = error_call) - } - ) -} - -mistral_error_handler <- function(err, resp, req) { - status <- resp_status(resp) - - if (status == 401) { - handle_unauthorized - } else if (status == 400 && resp_body_json(resp)$type == "invalid_model") { - handle_invalid_model - } else { - handle_other - } -} + handle_mistral_error <- function(err) { + req <- err$req + resp <- err$resp + url <- req$url + status <- resp_status(resp) -handle_invalid_model <- function(err, req, resp, error_call = caller_env()) { - status <- resp_status(resp) - if (status == 400 && resp_body_json(resp)$type == "invalid_model") { - model <- req$body$data$model - cli_abort(c( - "Invalid mistrai.ai model {.emph {model}}.", - i = "Use one of {.or {models()}}." - ), call = error_call) - } -} - -handle_unauthorized <- function(err, req, resp, error_call = caller_env()) { - status <- resp_status(resp) - url <- req$url + bullets <- if (status == 401) { + c( + "Unauthorized {.url {url}}.", + i = "Make sure your api key is valid {.url https://console.mistral.ai/api-keys/}", + i = "And set the {.envvar MISTRAL_API_KEY} environment variable", + i = "Perhaps using {.fn usethis::edit_r_environ}" + ) + } else if (status == 400 && resp_body_json(resp)$type == "invalid_model") { + model <- req$body$data$model + c( + "Invalid mistrai.ai model {.val {model}}.", + i = "Available models: {.val {models()}}." + ) + } else { + "Error with {.url {url}}." + } - if (status == 401) { - bullets <- c( - "Unauthorized {.url {url}}.", - i = "Make sure your api key is valid {.url https://console.mistral.ai/api-keys/}", - i = "And set the {.envvar MISTRAL_API_KEY} environment variable", - i = "Perhaps using {.fn usethis::edit_r_environ}" - ) cli_abort(bullets, call = error_call) } -} -handle_other <- function(err, req, resp, error_call = caller_env()) { - url <- req$url - cli_abort("Error with {.url {url}}.", call = error_call, parent = err) + req_perform(req) %!% handle_mistral_error }