Skip to content
Open
Show file tree
Hide file tree
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
2 changes: 1 addition & 1 deletion stream_reader.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ func (stream *streamReader[T]) processLines() ([]byte, error) {
rawLine, readErr := stream.reader.ReadBytes('\n')
if readErr != nil || hasErrorPrefix {
respErr := stream.unmarshalError()
if respErr != nil {
if respErr != nil && respErr.Error != nil {
return nil, fmt.Errorf("error, %w", respErr.Error)
}
return nil, readErr
Expand Down
31 changes: 31 additions & 0 deletions stream_reader_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"bufio"
"bytes"
"errors"
"io"
"testing"

utils "github.com/sashabaranov/go-openai/internal"
Expand Down Expand Up @@ -76,3 +77,33 @@ func TestStreamReaderRecvRaw(t *testing.T) {
t.Fatalf("Did not return raw line: %v", string(rawLine))
}
}

// TestStreamReaderReturnsReadErrWhenErrorResponseHasNilError tests that when
// unmarshalError returns an ErrorResponse with a nil Error field (e.g., when
// unmarshaling an empty JSON object "{}"), the original read error is returned
// instead of "error, <nil>". This fixes issue #1060.
func TestStreamReaderReturnsReadErrWhenErrorResponseHasNilError(t *testing.T) {
// Create a stream that will return io.EOF on read (simulating context cancellation)
// with an error accumulator that contains an empty JSON object
stream := &streamReader[ChatCompletionStreamResponse]{
reader: bufio.NewReader(bytes.NewReader([]byte{})), // empty reader returns io.EOF
errAccumulator: utils.NewErrorAccumulator(),
unmarshaler: &utils.JSONUnmarshaler{},
}

// Write an empty JSON object to the error accumulator
// This will unmarshal to ErrorResponse{Error: nil}
err := stream.errAccumulator.Write([]byte("{}"))
if err != nil {
t.Fatalf("Failed to write to error accumulator: %v", err)
}

// Call processLines which should return io.EOF, not "error, <nil>"
_, err = stream.processLines()
if err == nil {
t.Fatal("Expected error but got nil")
}
if !errors.Is(err, io.EOF) {
t.Fatalf("Expected io.EOF but got: %v", err)
}
}
Loading