-
Notifications
You must be signed in to change notification settings - Fork 0
/
stream_reader.go
88 lines (72 loc) · 1.63 KB
/
stream_reader.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package openai
import (
"bufio"
"bytes"
"fmt"
"io"
"net/http"
utils "github.com/lysunagopher/go-openai/internal"
)
type streamable interface {
ChatCompletionStreamResponse | CompletionResponse
}
type streamReader[T streamable] struct {
emptyMessagesLimit uint
isFinished bool
reader *bufio.Reader
response *http.Response
errAccumulator utils.ErrorAccumulator
unmarshaler utils.Unmarshaler
}
func (stream *streamReader[T]) Recv() (response T, err error) {
if stream.isFinished {
err = io.EOF
return
}
var emptyMessagesCount uint
waitForData:
line, err := stream.reader.ReadBytes('\n')
if err != nil {
respErr := stream.unmarshalError()
if respErr != nil {
err = fmt.Errorf("error, %w", respErr.Error)
}
return
}
var headerData = []byte("data: ")
line = bytes.TrimSpace(line)
if !bytes.HasPrefix(line, headerData) {
if writeErr := stream.errAccumulator.Write(line); writeErr != nil {
err = writeErr
return
}
emptyMessagesCount++
if emptyMessagesCount > stream.emptyMessagesLimit {
err = ErrTooManyEmptyStreamMessages
return
}
goto waitForData
}
line = bytes.TrimPrefix(line, headerData)
if string(line) == "[DONE]" {
stream.isFinished = true
err = io.EOF
return
}
err = stream.unmarshaler.Unmarshal(line, &response)
return
}
func (stream *streamReader[T]) unmarshalError() (errResp *ErrorResponse) {
errBytes := stream.errAccumulator.Bytes()
if len(errBytes) == 0 {
return
}
err := stream.unmarshaler.Unmarshal(errBytes, &errResp)
if err != nil {
errResp = nil
}
return
}
func (stream *streamReader[T]) Close() {
stream.response.Body.Close()
}