/
root.go
224 lines (195 loc) · 6.23 KB
/
root.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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
/*
Copyright © 2023 Hyunseok Jeong nicewook@hotmail.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package cmd
import (
"errors"
"fmt"
"io"
"log"
"os"
"path/filepath"
"strings"
"time"
"github.com/briandowns/spinner"
"github.com/chzyer/readline"
"github.com/fatih/color"
"github.com/sashabaranov/go-openai"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
Use: "gopt",
Short: "gopt is OpenAI GPT powered chat completion CLI",
Long: `gopt is OpenAI GPT powered chat completion CLI.
You can ask questions to the GPT model and get answers.`,
// Uncomment the following line if your bare application
// has an action associated with it:
Run: func(cmd *cobra.Command, args []string) {
startChat()
},
}
// Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
err := rootCmd.Execute()
if err != nil {
os.Exit(1)
}
}
func startChat() {
// usage
// help, model, token and bill info
// only one line question - 마지막 글자가 Ctrl+D이면 끝내게 하기?
fmt.Println()
fmt.Println(helpMessage())
var totalPromptTokens, totalCompletionTokens int
homeDir, err := os.UserHomeDir()
if err != nil {
log.Fatal(err)
}
appConfigPath := filepath.Join(homeDir, ".gopt")
var completer = readline.NewPrefixCompleter(
readline.PcItem("help"),
readline.PcItem("config"),
readline.PcItem("context"),
readline.PcItem("reset"),
readline.PcItem("clear"),
readline.PcItem("exit"),
)
cyan := color.New(color.FgCyan).SprintFunc()
yellow := color.New(color.FgYellow).SprintFunc()
blue := color.New(color.FgBlue).SprintFunc()
readlineConfig := &readline.Config{
Prompt: cyan("gpt> "),
HistoryFile: filepath.Join(appConfigPath, "readline-history"),
AutoComplete: completer,
InterruptPrompt: "^C",
EOFPrompt: "exit",
}
rl, err := readline.NewEx(readlineConfig)
if err != nil {
log.Fatal(err)
}
defer rl.Close()
rl.CaptureExitSignal()
loading := spinner.New([]string{".", "..", "...", "....", "....."}, 150*time.Millisecond)
loading.Prefix = yellow("loading")
loading.Color("yellow")
// start loop
for {
// get user input
userInput, err := rl.Readline()
if err == readline.ErrInterrupt {
if len(userInput) == 0 {
break
} else {
continue
}
} else if err == io.EOF {
break
}
userInput = strings.TrimSpace(userInput)
// TODO: reserved command execution
// help, msg(show), clear, sysmsg(get, set), config
if commandExecute(rl.Terminal, userInput) {
continue
}
// make messages
messages = append(messages, openai.ChatCompletionMessage{
Role: openai.ChatMessageRoleUser,
Content: userInput,
})
// request completion
var (
resp openai.ChatCompletionResponse
isStreamMode bool = true
responseContent string
curUsage openai.Usage
promptTokenLen int
)
// length check and adjust. except the system message
sTime := time.Now()
messages, promptTokenLen = contexLengthAdjust(messages)
log.Println("stream mode:", isStreamMode)
fmt.Println()
if isStreamMode {
stream, err := chatCompleteStream(viper.GetString("model"), messages)
if err != nil {
color.Red("ChatCompletion error: %v", err)
fmt.Println()
continue
}
defer stream.Close()
color.Blue("Assistant: ")
for {
response, err := stream.Recv()
if errors.Is(err, io.EOF) {
fmt.Println()
log.Println("Stream finished")
break
}
if err != nil {
log.Printf("Stream error: %v\n", err)
break
}
responseContent += response.Choices[0].Delta.Content
fmt.Print(response.Choices[0].Delta.Content)
}
completionTokensLen := NumTokensFromText(responseContent, viper.GetString("model"))
curUsage = openai.Usage{
PromptTokens: promptTokenLen,
CompletionTokens: completionTokensLen,
TotalTokens: promptTokenLen + completionTokensLen,
}
} else {
loading.Start() // Start the spinner
resp, err = chatComplete(viper.GetString("model"), messages)
if err != nil {
color.Red("ChatCompletion error: %v", err)
fmt.Println()
continue
}
loading.Stop()
responseContent = resp.Choices[0].Message.Content
curUsage = resp.Usage
fmt.Println(blue("Assistant:"), responseContent)
}
eTime := time.Since(sTime)
respMessage := openai.ChatCompletionMessage{
Role: openai.ChatMessageRoleAssistant,
Content: responseContent,
}
messages = append(messages, respMessage)
// print elapsed time, tokenInfo
totalPromptTokens += curUsage.PromptTokens
totalCompletionTokens += curUsage.CompletionTokens
printMetaInfo(eTime, curUsage, totalPromptTokens, totalCompletionTokens)
}
}
func printMetaInfo(eTime time.Duration, curUsage openai.Usage, totalPromptTokens int, totalCompletionTokens int) {
elapsedTime := prepareElapsedTime(eTime)
fmt.Printf(rightAlignWithColorWords(1), elapsedTime)
if viper.GetBool("token") {
tokenInfo := prepareTokenInfo(curUsage)
cumulativeTokenInfo := prepareCumulativeTokenInfo(totalPromptTokens, totalCompletionTokens)
fmt.Printf(rightAlignWithColorWords(4), tokenInfo)
fmt.Printf(rightAlignWithColorWords(2), cumulativeTokenInfo)
}
}