-
Notifications
You must be signed in to change notification settings - Fork 2
/
handler.go
256 lines (232 loc) · 6.9 KB
/
handler.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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
package chat
import (
"bufio"
"context"
"errors"
"fmt"
"os"
"os/user"
"path"
"slices"
"strconv"
"strings"
"time"
"github.com/baalimago/clai/internal/models"
"github.com/baalimago/clai/internal/utils"
"github.com/baalimago/go_away_boilerplate/pkg/ancli"
"github.com/baalimago/go_away_boilerplate/pkg/misc"
)
const chatUsage = `clai - (c)omand (l)ine (a)rtificial (i)intelligence
Usage: clai [flags] chat <subcommand> <prompt/chatID>
You may start a new chat using the prompt-modification flags which
are normally used in query mode.
Commands:
n|new <prompt> Create a new chat with the given prompt.
c|cotinue <chatID> <prompt> Continue an existing chat with the given chat ID. Prompt is optional
d|delete <chatID> Delete the chat with the given chat ID.
l|list List all existing chats.
The chatID is the 5 first words of the prompt joined by underscores. Easiest
way to get the chatID is to list all chats with 'clai chat list'. You may also select
a chat by its index in the list of chats.
The chats are found in %v/.clai/conversations, here they may be manually edited
as JSON files.
Examples:
- clai chat new "How's the weather?"
- clai chat list
- clai chat continue my_chat_id
- clai chat continue 3
- clai chat delete my_chat_id
`
type ChatHandler struct {
q models.ChatQuerier
debug bool
username string
subCmd string
chat models.Chat
prompt string
convDir string
}
func (q *ChatHandler) Query(ctx context.Context) error {
return q.actOnSubCmd(ctx)
}
func New(q models.ChatQuerier, confDir, args string) (*ChatHandler, error) {
username := "user"
debug := false
if misc.Truthy(os.Getenv("DEBUG")) {
debug = true
}
argsArr := strings.Split(args, " ")
subCmd := argsArr[0]
currentUser, err := user.Current()
if err == nil {
username = currentUser.Username
}
subPrompt := strings.Join(argsArr[1:], " ")
return &ChatHandler{
q: q,
username: username,
debug: debug,
subCmd: subCmd,
prompt: subPrompt,
convDir: path.Join(confDir, "/.clai/conversations/"),
}, nil
}
func (cq *ChatHandler) actOnSubCmd(ctx context.Context) error {
if cq.debug {
ancli.PrintOK(fmt.Sprintf("chat: %+v\n", cq))
}
switch cq.subCmd {
case "new", "n":
return cq.new(ctx)
case "continue", "c":
return cq.cont(ctx)
case "list", "l":
chats, err := cq.list()
if err == nil {
printChats(chats)
}
return err
case "delete", "d":
return cq.deleteFromPrompt()
case "query", "q":
// return cq.continueQueryAsChat(ctx, API_KEY, prompt)
return errors.New("not yet implemented")
case "help", "h":
cfgDir, _ := os.UserConfigDir()
fmt.Printf(chatUsage, cfgDir)
return nil
default:
return fmt.Errorf("unknown subcommand: '%s'\n%v", cq.subCmd, chatUsage)
}
}
func (cq *ChatHandler) new(ctx context.Context) error {
newChat := models.Chat{
Created: time.Now(),
ID: IdFromPrompt(cq.prompt),
Messages: []models.Message{
{Role: "user", Content: cq.prompt},
},
}
newChat, err := cq.q.TextQuery(ctx, newChat)
if err != nil {
return fmt.Errorf("failed to query chat model: %w", err)
}
cq.chat = newChat
return cq.loop(ctx)
}
func (cq *ChatHandler) findChatByID(potentialChatIdx string) (models.Chat, error) {
chats, err := cq.list()
if err != nil {
return models.Chat{}, fmt.Errorf("failed to list chats: %w", err)
}
split := strings.Split(potentialChatIdx, " ")
firstToken := split[0]
chatIdx, err := strconv.Atoi(firstToken)
if err == nil {
if chatIdx < 0 || chatIdx >= len(chats) {
return models.Chat{}, fmt.Errorf("chat index out of range")
}
// Reassemble the prompt from the split tokens, but without the index
// selecting the chat
cq.prompt = strings.Join(split[1:], " ")
return chats[chatIdx], nil
} else {
return cq.getByID(IdFromPrompt(potentialChatIdx))
}
}
func (cq *ChatHandler) cont(ctx context.Context) error {
if misc.Truthy(os.Getenv("DEBUG")) {
ancli.PrintOK(fmt.Sprintf("prompt: %v", cq.prompt))
}
chat, err := cq.findChatByID(cq.prompt)
if err != nil {
return fmt.Errorf("failed to get chat: %w", err)
}
for _, message := range chat.Messages {
err := utils.AttemptPrettyPrint(message, cq.username, false)
if err != nil {
return fmt.Errorf("failed to print chat message: %w", err)
}
}
if cq.prompt != "" {
chat.Messages = append(chat.Messages, models.Message{Role: "user", Content: cq.prompt})
}
cq.chat = chat
return cq.loop(ctx)
}
func (cq *ChatHandler) deleteFromPrompt() error {
c, err := cq.findChatByID(cq.prompt)
if err != nil {
return fmt.Errorf("failed to get chat to delete: %w", err)
}
err = os.Remove(path.Join(cq.convDir, fmt.Sprintf("%v.json", c.ID)))
if err != nil {
return fmt.Errorf("failed to delete chat: %w", err)
}
ancli.PrintOK(fmt.Sprintf("deleted chat '%v'\n", c.ID))
return nil
}
func (cq *ChatHandler) list() ([]models.Chat, error) {
files, err := os.ReadDir(cq.convDir)
if err != nil {
return nil, fmt.Errorf("failed to list conversations: %w", err)
}
var chats []models.Chat
if misc.Truthy(os.Getenv("DEBUG")) {
ancli.PrintOK(fmt.Sprintf("found '%v' conversations:\n", len(files)))
}
for _, file := range files {
chat, err := FromPath(path.Join(cq.convDir, file.Name()))
if err != nil {
return nil, fmt.Errorf("failed to get chat: %w", err)
}
chats = append(chats, chat)
}
slices.SortFunc(chats, func(a, b models.Chat) int {
return b.Created.Compare(a.Created)
})
return chats, err
}
func printChats(chats []models.Chat) {
ancli.PrintOK(fmt.Sprintf("found '%v' conversations:\n", len(chats)))
fmt.Printf("\t%-3s| %-20s| %v\n", "ID", "Created", "Filename + prompt")
line := strings.Repeat("-", 55)
fmt.Printf("\t%v\n", line)
for i, chat := range chats {
fmt.Printf("\t%-3s| %s | %v\n", fmt.Sprintf("%v", i), chat.Created.Format("2006-01-02 15:04:05"), chat.ID)
}
}
func (cq *ChatHandler) getByID(ID string) (models.Chat, error) {
return FromPath(path.Join(cq.convDir, fmt.Sprintf("%v.json", ID)))
}
func (cq *ChatHandler) loop(ctx context.Context) error {
defer func() {
err := Save(cq.convDir, cq.chat)
if err != nil {
panic(err)
}
}()
for {
lastMessage := cq.chat.Messages[len(cq.chat.Messages)-1]
if lastMessage.Role == "user" {
utils.AttemptPrettyPrint(lastMessage, cq.username, false)
} else {
fmt.Printf("%v(%v): ", ancli.ColoredMessage(ancli.CYAN, cq.username), "'exit/e/quit/q' to quit")
var userInput string
reader := bufio.NewReader(os.Stdin)
userInput, err := reader.ReadString('\n')
if err != nil {
return fmt.Errorf("failed to read user input: %w", err)
}
if userInput == "exit\n" || userInput == "quit\n" || userInput == "q\n" || userInput == "e\n" || ctx.Err() != nil {
return nil
}
cq.chat.Messages = append(cq.chat.Messages, models.Message{Role: "user", Content: userInput})
}
newChat, err := cq.q.TextQuery(ctx, cq.chat)
if err != nil {
return fmt.Errorf("failed to print chat completion: %w", err)
}
cq.chat = newChat
}
}