-
Notifications
You must be signed in to change notification settings - Fork 13
/
complete_stream.go
125 lines (112 loc) · 2.66 KB
/
complete_stream.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
package anthropic
import (
"bufio"
"bytes"
"context"
"encoding/json"
"errors"
"io"
"net/http"
)
type CompleteEvent string
const (
CompleteEventError CompleteEvent = "error"
CompleteEventCompletion CompleteEvent = "completion"
CompleteEventPing CompleteEvent = "ping"
)
type CompleteStreamRequest struct {
CompleteRequest
OnCompletion func(CompleteResponse) `json:"-"`
OnPing func(CompleteStreamPingData) `json:"-"`
OnError func(ErrorResponse) `json:"-"`
}
type CompleteStreamPingData struct {
Type string `json:"type"`
}
func (c *Client) CreateCompleteStream(
ctx context.Context,
request CompleteStreamRequest,
) (response CompleteResponse, err error) {
request.Stream = true
urlSuffix := "/complete"
req, err := c.newStreamRequest(ctx, http.MethodPost, urlSuffix, request)
if err != nil {
return
}
resp, err := c.config.HTTPClient.Do(req)
if err != nil {
return
}
defer resp.Body.Close()
response.SetHeader(resp.Header)
if err := c.handlerRequestError(resp); err != nil {
return response, err
}
reader := bufio.NewReader(resp.Body)
var (
event []byte
emptyMessageCount uint
)
for {
rawLine, readErr := reader.ReadBytes('\n')
if readErr != nil {
if errors.Is(readErr, io.EOF) {
break
}
return response, readErr
}
noSpaceLine := bytes.TrimSpace(rawLine)
if len(noSpaceLine) == 0 {
continue
}
if bytes.HasPrefix(noSpaceLine, eventPrefix) {
event = bytes.TrimSpace(bytes.TrimPrefix(noSpaceLine, eventPrefix))
continue
}
if bytes.HasPrefix(noSpaceLine, dataPrefix) {
var (
data = bytes.TrimPrefix(noSpaceLine, dataPrefix)
eventType = CompleteEvent(event)
)
switch eventType {
case CompleteEventError:
var d ErrorResponse
if err := json.Unmarshal(data, &d); err != nil {
return response, err
}
if request.OnError != nil {
request.OnError(d)
}
return response, d.Error
case CompleteEventPing:
var d CompleteStreamPingData
if err := json.Unmarshal(data, &d); err != nil {
return response, err
}
if request.OnPing != nil {
request.OnPing(d)
}
continue
case CompleteEventCompletion:
var d CompleteResponse
if err := json.Unmarshal(data, &d); err != nil {
return response, err
}
if request.OnCompletion != nil {
request.OnCompletion(d)
}
response.Type = d.Type
response.ID = d.ID
response.StopReason = d.StopReason
response.Model = d.Model
response.Completion += d.Completion
continue
}
}
emptyMessageCount++
if emptyMessageCount > c.config.EmptyMessagesLimit {
return response, ErrTooManyEmptyStreamMessages
}
}
return
}