-
Notifications
You must be signed in to change notification settings - Fork 59
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add support for server-sent events #481
Comments
Done in #521 |
Here is an alternative implementation that I was preparing to submit as a PR, but @jcheng5 beat me by a few weeks :) It follows the simple approach outlined by @hadley above and mimics the Javascript req_perform_sse <- function(req, onmessage_callback = NULL,
event_callbacks = list(),
timeout_sec = Inf, buffer_kb = 64)
{
callback <- function(bytes) {
text <- rawToChar(bytes)
msgs <- strsplit(text, "\n\n", fixed = TRUE)[[1L]]
m <- gregexec("(event|data|id|retry): ?(.*)", msgs, perl = TRUE)
for (mat in regmatches(msgs, m)) {
event <- split(mat[3L,], mat[2L,])
event$data <- paste(event$data, collapse = "\n")
if (is.null(event$event))
callback <- onmessage_callback
else callback <- event_callbacks[[event$event]]
if (!is.null(callback) && !isTRUE(callback(event)))
return(FALSE)
}
TRUE
}
round <- function(bytes) {
nl <- bytes == charToRaw("\n")
which(diff(nl) == 0L & nl[-1L])
}
httr2::req_perform_stream(req, callback, timeout_sec, buffer_kb, round)
} |
I looked a bit into satisfying the draft spec, but the retry logic is a bit complicated. For example, I think |
I looked at it and thought for retry, it made more sense to implement the EventSource object exactly as it is in JS: a separate abstraction that sits one level above requests. I didn’t do it due to time pressure but also I am slightly skeptical that there is much adoption of Last-Event-ID in real world services (would love to find out I’m wrong though). |
Yea, it's still an evolving spec, so it makes sense to hold off until there is a use case. |
Oh, I don’t think it’s evolving; the HTML whatwg spec is “living” so it’s never officially stable. The EventSource part of it is very old, there’s a w3c spec from back in the day. If you wanted to write a full EventSource client just for completeness I think that would make sense and also be pretty fun. But I think we already have everything we would need or want for the LLM API cases in particular, as surely none of them implement retry? |
https://developer.mozilla.org/en-US/docs/Web/API/Server-sent%5Fevents/Using%5Fserver-sent%5Fevents#event_stream_format
Maybe
req_perform_sse()
? And then have some way to register functions for each event?The text was updated successfully, but these errors were encountered: