-
Notifications
You must be signed in to change notification settings - Fork 0
/
stream.go
125 lines (114 loc) · 2.54 KB
/
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 gogpt
import (
"bufio"
"bytes"
"io"
"log"
"strings"
"net/http"
"github.com/tidwall/gjson"
)
type StreamContext struct {
*Context
channel chan string
}
func NewStreamContext() *StreamContext {
return &StreamContext{
Context: &Context{
body: map[string]any{
"model": "gpt-3.5-turbo",
"messages": []map[string]string{},
"stream": true,
},
count: 0,
maxTurns: 1,
output: nil,
stream: true,
},
channel: nil,
}
}
func NewStreamContextWithWriter(writer io.Writer) *StreamContext {
return &StreamContext{
Context: &Context{
body: map[string]any{
"model": "gpt-3.5-turbo",
"messages": []map[string]string{},
"stream": true,
},
count: 0,
maxTurns: 1,
output: writer,
stream: true,
},
channel: nil,
}
}
func NewStreamContextWithChannel(ch chan string) *StreamContext {
return &StreamContext{
Context: &Context{
body: map[string]any{
"model": "gpt-3.5-turbo",
"messages": []map[string]string{},
"stream": true,
},
count: 0,
maxTurns: 1,
output: nil,
stream: true,
},
channel: ch,
}
}
func (c *StreamContext) post() {
res := c.query()
defer res.Body.Close()
if c.output == nil && c.channel != nil {
c.streamOutputWithChannel(res)
} else if c.output != nil && c.channel == nil {
c.streamOutputWithWriter(res)
} else {
log.Fatal("Please choose how to return!")
}
}
func (c *StreamContext) Continue(prompt string) *StreamContext {
c.checkAndReset()
c.appendMessage("user", prompt)
c.post()
return c
}
func (c *StreamContext) streamOutputWithWriter(res *http.Response) {
reader := bufio.NewReader(res.Body)
buf := bytes.NewBufferString("")
writer := io.MultiWriter(buf, c.output)
for {
line, err := reader.ReadBytes('\n')
if err != nil {
break
}
output := strings.TrimPrefix(string(line), "data: ")
content := gjson.Get(output, "choices.0.delta.content").String()
writer.Write([]byte(content))
}
writer.Write([]byte{'\n'})
c.appendMessage("assistant", buf.String())
c.content = buf.String()
}
func (c *StreamContext) streamOutputWithChannel(res *http.Response) {
reader := bufio.NewReader(res.Body)
buf := bytes.NewBufferString("")
for {
line, err := reader.ReadBytes('\n')
if err != nil {
break
}
output := strings.TrimPrefix(string(line), "data: ")
content := gjson.Get(output, "choices.0.delta.content").String()
buf.WriteString(content)
c.channel <- content
}
buf.WriteString("\n")
close(c.channel)
c.appendMessage("assistant", buf.String())
c.content = buf.String()
}