-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathstream_reader.go
140 lines (112 loc) · 2.6 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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
package openai
import (
"bufio"
"bytes"
"fmt"
"io"
"net/http"
utils "github.com/sashabaranov/go-openai/internal"
)
var (
dataField = []byte("data")
errorPrefix = []byte(`{"error":`)
)
const (
splitParts = 2
)
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
httpHeader
}
func (stream *streamReader[T]) Recv() (response T, err error) {
rawLine, err := stream.RecvRaw()
if err != nil {
return
}
err = stream.unmarshaler.Unmarshal(rawLine, &response)
if err != nil {
return
}
return response, nil
}
func (stream *streamReader[T]) RecvRaw() ([]byte, error) {
if stream.isFinished {
return nil, io.EOF
}
return stream.processLines()
}
//nolint:gocognit
func (stream *streamReader[T]) processLines() ([]byte, error) {
var (
emptyMessagesCount uint
dataFieldNotFound bool
valueHasErrorPrefix bool
)
for {
rawLine, readErr := stream.reader.ReadBytes('\n')
if readErr != nil || valueHasErrorPrefix {
respErr := stream.unmarshalError()
if respErr != nil {
return nil, fmt.Errorf("error, %w", respErr.Error)
}
return nil, readErr
}
noSpaceLine := bytes.TrimSpace(rawLine)
var value []byte
split := bytes.SplitN(noSpaceLine, []byte(":"), splitParts)
if len(split) != splitParts || !bytes.Equal(split[0], dataField) {
dataFieldNotFound = true
} else {
value = split[1]
if bytes.HasPrefix(value, []byte(" ")) {
value = value[1:]
}
if bytes.HasPrefix(value, errorPrefix) {
valueHasErrorPrefix = true
}
}
if dataFieldNotFound || valueHasErrorPrefix {
if valueHasErrorPrefix {
noSpaceLine = value
}
writeErr := stream.errAccumulator.Write(noSpaceLine)
if writeErr != nil {
return nil, writeErr
}
emptyMessagesCount++
if emptyMessagesCount > stream.emptyMessagesLimit {
return nil, ErrTooManyEmptyStreamMessages
}
dataFieldNotFound = false
continue
}
noPrefixLine := value
if string(noPrefixLine) == "[DONE]" {
stream.isFinished = true
return nil, io.EOF
}
return noPrefixLine, nil
}
}
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() error {
return stream.response.Body.Close()
}