-
Notifications
You must be signed in to change notification settings - Fork 1
/
chat.go
97 lines (82 loc) · 2.11 KB
/
chat.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
package bard
import (
"bufio"
"fmt"
"os"
"strings"
)
type ChatBard struct {
userPrompt string
bard *Bard
chatHistory []map[string]string
language string
timeout int
token string
}
func NewChatBard(token string, timeout int, language string) *ChatBard {
bard := NewBard(token, timeout, nil, nil, "", language, false, "")
return &ChatBard{
userPrompt: ">>> ",
bard: bard,
chatHistory: []map[string]string{},
language: language,
timeout: timeout,
token: token,
}
}
func (c *ChatBard) Start() {
fmt.Println("Welcome to Chatbot")
fmt.Println("If you enter quit, q, or stop, the chat will end.")
reader := bufio.NewReader(os.Stdin)
for {
fmt.Print(c.userPrompt)
userInput, _ := reader.ReadString('\n')
userInput = strings.TrimSpace(userInput)
userInput = strings.ToLower(userInput)
if userInput == "quit" || userInput == "q" || userInput == "stop" {
break
}
if !c.isValidInput(userInput) {
fmt.Println("Invalid input! Please try again.")
continue
}
response, err := c.bard.GetAnswer(userInput)
if err != nil {
fmt.Println("Error occurred:", err.Error())
} else {
c.displayResponse(response)
c.addToChatHistory(userInput, response["content"].(string))
}
}
fmt.Println("Chat Ended.")
}
func (c *ChatBard) isValidInput(userInput string) bool {
if userInput == "" {
return false
}
if len(userInput) > 1000 {
return false
}
return true
}
func (c *ChatBard) displayResponse(response map[string]interface{}) {
if len(response["images"].(map[string]interface{})) > 0 {
fmt.Printf("Chatbot: %s\n\nImage links: %v\n", response["content"], response["images"])
} else {
fmt.Println("Chatbot:", response["content"])
}
}
func (c *ChatBard) addToChatHistory(userInput string, chatbotResponse string) {
entry := map[string]string{
"User": userInput,
"Chatbot": chatbotResponse,
}
c.chatHistory = append(c.chatHistory, entry)
}
func (c *ChatBard) DisplayChatHistory() {
fmt.Println("Chat History")
for _, entry := range c.chatHistory {
fmt.Println("User:", entry["User"])
fmt.Println("Chatbot:", entry["Chatbot"])
}
}