forked from xusenlin/chatGPT
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
165 lines (141 loc) · 3.48 KB
/
main.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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
package main
import (
"context"
_ "embed"
"encoding/json"
"errors"
"fmt"
"github.com/google/uuid"
"github.com/sashabaranov/go-openai"
"io"
"io/ioutil"
"log"
"net/http"
)
var Ai = openai.NewClient("your token")
type EventStream struct {
Event string
Data string
}
type DialogMsg = map[string]chan EventStream
var ResponseEventStream = make(DialogMsg)
//go:embed index.html
var htmlTemplate string
//go:embed coffee.jpg
var imageBytes []byte
func main() {
http.HandleFunc("/", IndexHandler)
http.HandleFunc("/send", SendMsgHandler)
http.HandleFunc("/coffee", Coffee)
http.HandleFunc("/receive", ReceiveHandler)
fmt.Println("start chatGPT service on 8088")
log.Fatal(http.ListenAndServe(":8088", nil))
}
func SendMsgHandler(w http.ResponseWriter, r *http.Request) {
data, err := io.ReadAll(r.Body)
defer r.Body.Close()
if err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(err.Error()))
return
}
var msg struct {
Uuid string `json:"uuid"`
Chat []openai.ChatCompletionMessage `json:"chat"`
}
err = json.Unmarshal(data, &msg)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(err.Error()))
return
}
_, ok := ResponseEventStream[msg.Uuid]
if len(msg.Uuid) != 36 || !ok {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("err:uuid出错"))
return
}
if len(msg.Chat) == 0 {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("err:问题为空"))
return
}
ioutil.WriteFile(msg.Uuid+".json", data, 0666)
ctx := context.Background()
stream, err := Ai.CreateChatCompletionStream(ctx, openai.ChatCompletionRequest{
Model: openai.GPT3Dot5Turbo,
MaxTokens: 2000,
Stream: true,
Messages: msg.Chat,
})
if err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(err.Error()))
return
}
w.Write([]byte("ok"))
go func() {
defer stream.Close()
for {
response, err := stream.Recv()
if errors.Is(err, io.EOF) {
ResponseEventStream[msg.Uuid] <- EventStream{
Event: "eof",
Data: err.Error(),
}
return
}
if err != nil {
ResponseEventStream[msg.Uuid] <- EventStream{
Event: "error",
Data: err.Error(),
}
return
}
content := response.Choices[0].Delta.Content
m, _ := json.Marshal(struct {
Content string `json:"content"`
}{
Content: content,
})
ResponseEventStream[msg.Uuid] <- EventStream{
Event: "message",
Data: string(m),
}
}
}()
return
}
func ReceiveHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
u := uuid.New().String()
_, ok := ResponseEventStream[u]
if ok {
fmt.Fprintf(w, "event: %v\ndata: %v\n\n", "error", "The UUID already exists; please refresh the page and attempt again.")
w.(http.Flusher).Flush()
return
}
ResponseEventStream[u] = make(chan EventStream)
fmt.Fprintf(w, "event: %v\ndata: %v\n\n", "uuid", u)
w.(http.Flusher).Flush()
for {
select {
case msg := <-ResponseEventStream[u]:
fmt.Fprintf(w, "event: %v\ndata: %v\n\n", msg.Event, msg.Data)
w.(http.Flusher).Flush()
case _ = <-r.Context().Done():
delete(ResponseEventStream, u)
return
}
}
}
func IndexHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html")
w.Write([]byte(htmlTemplate))
}
func Coffee(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "image/jpeg")
w.Write(imageBytes)
}