Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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