-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
223 lines (178 loc) · 5.77 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
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
package main
import (
"bufio"
"context"
"flag"
"fmt"
"log"
"os"
"strings"
"time"
"cloud.google.com/go/vertexai/genai"
"github.com/michalswi/color"
openai "github.com/sashabaranov/go-openai"
"google.golang.org/api/option"
)
const (
appName = "chat-ai"
// https://pkg.go.dev/github.com/sashabaranov/go-openai#pkg-constants
openaiModel = openai.GPT4oMini20240718
// openaiModel = openai.GPT4oMini
// openaiModel = openai.GPT4o
// openaiModel = openai.O1Preview
geminiModel = "gemini-1.5-pro"
outputFile = "/tmp/chat-ai.log"
)
func main() {
var aiProvider string
flag.StringVar(&aiProvider, "p", "", "AI provider [chatgpt, gemini]")
flag.Parse()
reader := bufio.NewReader(os.Stdin)
apiKey := os.Getenv("API_KEY")
if apiKey == "" {
log.Fatal("Please set the API_KEY env variable")
}
file, err := os.OpenFile(outputFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
log.Fatalf("Error opening file: %v", err)
return
}
defer file.Close()
switch aiProvider {
case "chatgpt":
runChatGPT(apiKey, reader, aiProvider, file)
case "gemini":
runGemini(apiKey, reader, aiProvider)
default:
log.Fatalf("Invalid AI provider, select 'chatgpt' or 'gemini'.")
}
}
// runChatGPT handles the interaction loop with ChatGPT, processing user commands and displaying responses.
func runChatGPT(apiKey string, reader *bufio.Reader, aiProvider string, file *os.File) {
openaiClient := openai.NewClient(apiKey)
var conversation []openai.ChatCompletionMessage
for {
command, shouldContinue := prompt(reader, aiProvider)
if !shouldContinue {
break
}
if command == "h" && shouldContinue {
displayHelp()
continue
} else {
writeChatMessage(file, "> "+command+"\n")
}
// Add the user's message to the conversation history.
conversation = append(conversation, openai.ChatCompletionMessage{
Role: openai.ChatMessageRoleUser,
Content: command,
})
resp, err := chatGPTChat(openaiClient, conversation)
// resp, err := chatGPTChat(openaiClient, command)
if err != nil {
log.Fatalf("ChatGPT failed: %v", err)
}
fmt.Println(resp.Choices[0].Message.Content)
writeChatMessage(file, resp.Choices[0].Message.Content+"\n"+"\n")
conversation = append(conversation, openai.ChatCompletionMessage{
Role: openai.ChatMessageRoleAssistant,
Content: resp.Choices[0].Message.Content,
})
}
}
// chatGPTChat sends the user's command to the ChatGPT AI and returns the response.
func chatGPTChat(openaiClient *openai.Client, conversation []openai.ChatCompletionMessage) (resp openai.ChatCompletionResponse, err error) {
fmt.Println(color.Format(color.GREEN, "> Waiting for ChatGPT.."))
resp, err = openaiClient.CreateChatCompletion(
context.Background(),
openai.ChatCompletionRequest{
Model: openaiModel,
Messages: conversation,
},
)
if err != nil {
return
}
return resp, nil
}
// runGemini handles the interaction loop with Gemini, processing user commands and displaying responses.
func runGemini(apiKey string, reader *bufio.Reader, aiProvider string) {
ctx := context.Background()
projectID := os.Getenv("VAI_PROJECT_ID")
if projectID == "" {
log.Fatal("Please set the VAI_PROJECT_ID env variable")
}
region := os.Getenv("VAI_REGION")
if region == "" {
log.Fatal("Please set the VAI_REGION env variable")
}
client, err := genai.NewClient(ctx, projectID, region, option.WithCredentialsFile(apiKey))
if err != nil {
log.Fatalf("Gemini genai NewClient failed: %v", err)
}
for {
command, shouldContinue := prompt(reader, aiProvider)
if !shouldContinue {
break
}
if command == "h" && shouldContinue {
displayHelp()
continue
}
respGemini, err := geminiChat(ctx, client, command)
if err != nil {
log.Fatalf("Gemini failed: %v", err)
}
fmt.Println(respGemini.Candidates[0].Content.Parts[0])
}
}
// geminiChat sends the user's command to the Gemini AI and returns the response.
func geminiChat(ctx context.Context, client *genai.Client, command string) (resp *genai.GenerateContentResponse, err error) {
fmt.Println(color.Format(color.GREEN, "> Waiting for Gemini.."))
// https://pkg.go.dev/cloud.google.com/go/vertexai/genai#Client.GenerativeModel
model := client.GenerativeModel(geminiModel)
const ChatTemperature float32 = 0.1
temperature := ChatTemperature
model.Temperature = &temperature
chatSession := model.StartChat()
var builder strings.Builder
fmt.Fprintln(&builder, command)
introductionString := builder.String()
resp, err = chatSession.SendMessage(ctx, genai.Text(introductionString))
if err != nil {
return
}
return resp, nil
}
// prompt displays a prompt to the user, reads their input, and determines whether to continue the loop or handle special commands like "h" for help.
func prompt(reader *bufio.Reader, aiProvider string) (string, bool) {
prompt := fmt.Sprintf("%s [%s:%s]: ", time.Now().UTC().Format(time.RFC1123), appName, aiProvider)
fmt.Printf(color.Format(color.YELLOW, prompt))
command, err := reader.ReadString('\n')
if err != nil {
fmt.Println("Error reading command:", err)
return "", true
}
command = strings.TrimSpace(command)
switch command {
case "q":
fmt.Println(color.Format(color.GREEN, "Exiting chat. bye!"))
return "", false
case "h":
return "h", true
}
return command, true
}
// displayHelp prints out the available commands and their descriptions to the user.
func displayHelp() {
fmt.Println(color.Format(color.GREEN, "Commands:"))
fmt.Println(color.Format(color.GREEN, " q - quit: Exit the chat."))
fmt.Println(color.Format(color.GREEN, " h - help: Display this help message."))
}
// writeChatMessage writes ChatGPT answer message to a specified file, it's like keeping a history.
func writeChatMessage(file *os.File, message string) {
_, err := file.WriteString(message)
if err != nil {
fmt.Println("Error writing to file:", err)
}
}