forked from changkun/chat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
89 lines (77 loc) · 1.73 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
// Copyright 2023 Changkun Ou. All rights reserved.
// Use of this source code is governed by a MIT
// license that can be found in the LICENSE file.
package main
import (
"bytes"
"context"
"fmt"
"io"
"os"
"changkun.de/x/chat/internal/openai"
"changkun.de/x/chat/internal/term"
)
func main() {
if os.Getenv("OPENAI_API_KEY") == "" {
fmt.Fprint(os.Stderr, "Please set OPENAI_API_KEY environment variable.\n")
return
}
stdin := os.Stdin
stdout := os.Stdout
fmt.Fprint(stdout, term.Orange("Hi, I'm a chatbot. How can I help you?\n"))
session := []openai.ChatMessage{
{
Role: "system",
Content: "You are a helpful assistant.",
},
}
for {
fmt.Fprint(stdout, term.Orange("User: "))
buf := bytes.NewBuffer(nil)
_, err := io.Copy(buf, stdin)
if err != nil {
fmt.Fprintf(stdout, "Error: %v", err)
return
}
userMsg := openai.ChatMessage{
Role: "user",
Content: buf.String(),
}
session = append(session, userMsg)
respCh, errCh := openai.Chat(context.Background(), &openai.ChatRequest{
Model: "gpt-4",
Stream: true,
Message: session,
})
response := openai.ChatMessage{
Role: "assistant",
Content: "",
}
fmt.Fprint(stdout, term.Orange("Assistant: "))
streamLoop:
for {
select {
case r, ok := <-respCh:
if !ok {
break streamLoop
}
if len(r.Choices) == 0 {
fmt.Fprint(stdout, "No response. End of the session.")
return
}
msg := r.Choices[0].Delta
fmt.Fprint(stdout, msg.Content)
response.Content += msg.Content
case err, ok := <-errCh:
if !ok {
if err != nil {
fmt.Fprintf(stdout, "Error: %v", err)
}
break streamLoop
}
}
}
session = append(session, response)
fmt.Fprintf(stdout, "\n")
}
}