Skip to content

fix: set max capacity for ssestream decoder bufio scanner #373

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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
12 changes: 11 additions & 1 deletion packages/ssestream/ssestream.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,11 @@ import (
"github.com/tidwall/gjson"
)

const (
// ScannerMaxCapacity is the maximum capacity of the scanner buffer used in the decoder.
DecoderScannerMaxCapacity = 512 * 1024 // 512 KiB
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure what the right value to set here is, hopefully someone from the OpenAI team can tell us what the max size needs to be, but I didn't notice any token too long errors after increasing the capacity to this.

)

type Decoder interface {
Event() Event
Next() bool
Expand All @@ -32,6 +37,11 @@ func NewDecoder(res *http.Response) Decoder {
decoder = t(res.Body)
} else {
scanner := bufio.NewScanner(res.Body)

// adjust the scanner max capacity
buf := make([]byte, DecoderScannerMaxCapacity)
scanner.Buffer(buf, DecoderScannerMaxCapacity)

decoder = &eventStreamDecoder{rc: res.Body, scn: scanner}
}
return decoder
Expand Down Expand Up @@ -161,7 +171,7 @@ func (s *Stream[T]) Next() bool {
s.done = true
continue
}

var nxt T
if s.decoder.Event().Type == "" || strings.HasPrefix(s.decoder.Event().Type, "response.") {
ep := gjson.GetBytes(s.decoder.Event().Data, "error")
Expand Down