From 06a33c24c411df666e92589f447d44fb729c1fdb Mon Sep 17 00:00:00 2001 From: Corrado Lanera Date: Sun, 9 Jun 2024 22:46:40 +0200 Subject: [PATCH] fix wrong input for batch_* and add timeout to batch_list --- R/batch.R | 25 ++++++++++++++----------- tests/testthat/test-batch.R | 21 +++++++++++++++++++++ 2 files changed, 35 insertions(+), 11 deletions(-) diff --git a/R/batch.R b/R/batch.R index d2d21b3..fda287b 100644 --- a/R/batch.R +++ b/R/batch.R @@ -184,15 +184,18 @@ batch_cancel <- function(batch_id) { batch_list <- function(n = 10) { checkmate::qassert(n, "X1(0,]") - httr::GET( - stringr::str_glue("https://api.openai.com/v1/batches?limit={n}"), - httr::add_headers( - "Authorization" = paste("Bearer", Sys.getenv("OPENAI_API_KEY")) - ), - httr::content_type_json(), - encode = "json" - ) |> - parse_httr_response() + httr::with_config( + httr::timeout(600), + httr::GET( + stringr::str_glue("https://api.openai.com/v1/batches?limit={n}"), + httr::add_headers( + "Authorization" = paste("Bearer", Sys.getenv("OPENAI_API_KEY")) + ), + httr::content_type_json(), + encode = "json" + ) |> + parse_httr_response() + ) } @@ -269,7 +272,8 @@ split_results <- function(response, simplify = TRUE) { parse_httr_response <- function(response, convert_json = TRUE) { parsed <- response |> - httr::content(as = "text", encoding = "UTF-8") + httr::content(as = "text", encoding = "UTF-8") |> + jsonlite::fromJSON() if (httr::http_error(response)) { err <- parsed[["error"]] @@ -285,7 +289,6 @@ parse_httr_response <- function(response, convert_json = TRUE) { if (convert_json) { parsed |> - jsonlite::fromJSON() |> purrr::map(\(x) x %||% NA) |> purrr::list_flatten() |> tibble::as_tibble() diff --git a/tests/testthat/test-batch.R b/tests/testthat/test-batch.R index 49a423f..4794fbe 100644 --- a/tests/testthat/test-batch.R +++ b/tests/testthat/test-batch.R @@ -28,6 +28,7 @@ test_that("batch utils works", { # eval before_start_status <- batch_list() + Sys.sleep(1) n <- nrow(before_start_status) batch_file_info <- batch_upload_file(out_jsonl_path) @@ -36,10 +37,12 @@ test_that("batch utils works", { batch_status <- batch_job_info[["id"]] |> batch_status() after_start_status <- batch_list() + Sys.sleep(1) batch_cancelled <- batch_job_info[["id"]] |> batch_cancel() after_cancel_status <- batch_list() + Sys.sleep(1) # expectations expect_tibble(before_start_status) @@ -79,3 +82,21 @@ test_that("batch utils works", { ) }) + +test_that("batch_* works well on error input", { + # setup + wrong_input <- "foo" + + # eval + batch_create(wrong_input) |> + expect_error("API request failed") + + batch_status(wrong_input) |> + expect_error("API request failed") + + batch_result(wrong_input) |> + expect_error("API request failed") + + batch_cancel(wrong_input) |> + expect_error("API request failed") +})