Skip to content

Commit

Permalink
be careful about truncated multi byte strings
Browse files Browse the repository at this point in the history
  • Loading branch information
romainfrancois committed Feb 7, 2024
1 parent 057ef71 commit 8e8c075
Showing 1 changed file with 12 additions and 7 deletions.
19 changes: 12 additions & 7 deletions R/backend-openai-core.R
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ openai_perform <- function(defaults, req_body) {

openai_stream_ide <- function(defaults, req_body) {
ch_env$stream <- list()
ch_env$stream$bytes <- NULL
ch_env$stream$raw <- NULL
ch_env$stream$response <- NULL

Expand All @@ -62,11 +63,15 @@ openai_stream_ide <- function(defaults, req_body) {
}

openai_stream_ide_delta <- function(x, defaults, testing = FALSE) {
ch_env$stream$raw <- paste0(
ch_env$stream$raw,
rawToChar(x),
collapse = ""
)
bytes <- ch_env$stream$bytes <- c(ch_env$stream$bytes, x)

raw <- rawToChar(bytes)
while (class(try(nchar(raw), silent = TRUE)) == "try-error") {
bytes <- head(bytes, -1)
raw <- rawToChar(bytes)
}

ch_env$stream$raw <- raw
current <- openai_stream_parse(
x = ch_env$stream$raw,
defaults = defaults
Expand Down Expand Up @@ -156,9 +161,9 @@ openai_check_error <- function(x) {
openai_stream_parse <- function(x, defaults) {
res <- x %>%
paste0(collapse = "") %>%
strsplit("data: ") %>%
stringr::str_split("data: ") %>%
unlist() %>%
discard(~ .x == "") %>%
discard(~ identical(.x, "")) %>%
keep(~ substr(.x, (nchar(.x) - 2), nchar(.x)) == "}\n\n") %>%
map(jsonlite::fromJSON)

Expand Down

0 comments on commit 8e8c075

Please sign in to comment.