Skip to content

Commit

Permalink
fix wrong input for batch_* and add timeout to batch_list
Browse files Browse the repository at this point in the history
  • Loading branch information
CorradoLanera committed Jun 9, 2024
1 parent b47d481 commit 06a33c2
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 11 deletions.
25 changes: 14 additions & 11 deletions R/batch.R
Original file line number Diff line number Diff line change
Expand Up @@ -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()
)
}


Expand Down Expand Up @@ -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"]]
Expand All @@ -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()
Expand Down
21 changes: 21 additions & 0 deletions tests/testthat/test-batch.R
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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)
Expand Down Expand Up @@ -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")
})

0 comments on commit 06a33c2

Please sign in to comment.