forked from aandrew-me/tgpt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
helper.go
765 lines (617 loc) · 16.9 KB
/
helper.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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
package main
import (
"bufio"
"encoding/json"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"runtime"
"strconv"
"strings"
"time"
"github.com/aandrew-me/tgpt/v2/client"
"github.com/aandrew-me/tgpt/v2/providers"
"github.com/aandrew-me/tgpt/v2/structs"
http "github.com/bogdanfinn/fhttp"
"github.com/olekukonko/ts"
tls_client "github.com/bogdanfinn/tls-client"
"golang.org/x/mod/semver"
)
type Data struct {
Version string `json:"version"`
}
type Response struct {
Completion string `json:"completion"`
}
type ImgResponse struct {
Images []string `json:"images"`
}
func getDataResponseTxt(input string, isInteractive bool, extraOptions structs.ExtraOptions) string {
// Receiving response
resp, err := providers.NewRequest(input, structs.Params{
ApiKey: *apiKey,
ApiModel: *apiModel,
Provider: *provider,
Max_length: *max_length,
Temperature: *temperature,
Top_p: *top_p,
Preprompt: *preprompt,
}, extraOptions)
if err != nil {
stopSpin = true
printConnectionErrorMsg(err)
}
code := resp.StatusCode
if code >= 400 {
stopSpin = true
fmt.Print("\r")
if !isInteractive {
handleStatus400(resp)
}
respBody, _ := io.ReadAll(resp.Body)
fmt.Println("Some error has occurred, try again")
fmt.Println(string(respBody))
return ""
}
defer resp.Body.Close()
stopSpin = true
fmt.Print("\r")
// Print the Question
if !isInteractive {
fmt.Print("\r \r")
// bold.Printf("\r%v\n\n", input)
bold.Println()
} else {
fmt.Println()
boldViolet.Println("╭─ Bot")
}
// Handling each part
return handleEachPart(resp, input)
}
func getData(input string, isInteractive bool, extraOptions structs.ExtraOptions) (string, string) {
responseTxt := getDataResponseTxt(input, isInteractive, extraOptions)
safeResponse, _ := json.Marshal(responseTxt)
fmt.Print("\n\n")
safeInput, _ := json.Marshal(input)
msgObject := fmt.Sprintf(`{
"content": %v,
"role": "user"
},{
"content": %v,
"role": "system"
},
`, string(safeInput), string(safeResponse))
if extraOptions.Provider == "phind" {
safeInput, _ := json.Marshal(input)
msgObject = fmt.Sprintf(`{
"content": %v,
"metadata": {},
"role": "user"
},{
"content": %v,
"metadata": {},
"role": "assistant",
"name": "base"
},
`, string(safeInput), string(safeResponse))
}
if extraOptions.Provider == "llama2" {
input := string(safeInput)[1 : len(string(safeInput))-1]
response := string(safeResponse)[1 : len(string(safeResponse))-1]
msgObject = fmt.Sprintf(`<s>[INST] %v [/INST] %v </s>`, input, response)
}
return msgObject, responseTxt
}
func loading(stop *bool) {
spinChars := []string{"⣾ ", "⣽ ", "⣻ ", "⢿ ", "⡿ ", "⣟ ", "⣯ ", "⣷ "}
i := 0
for {
if *stop {
break
}
fmt.Printf("\r%s Loading", spinChars[i])
i = (i + 1) % len(spinChars)
time.Sleep(80 * time.Millisecond)
}
}
func update() {
if runtime.GOOS == "windows" || runtime.GOOS == "android" {
fmt.Println("This feature is not supported on your Operating System")
} else {
client, err := client.NewClient()
if err != nil {
fmt.Fprintln(os.Stderr, err)
return
}
url := "https://raw.githubusercontent.com/aandrew-me/tgpt/main/version.txt"
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
// Handle error
fmt.Fprintln(os.Stderr, "Error:", err)
return
}
res, err := client.Do(req)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
defer res.Body.Close()
var data Data
err = json.NewDecoder(res.Body).Decode(&data)
if err != nil {
// Handle error
fmt.Fprintln(os.Stderr, "Error:", err)
return
}
remoteVersion := "v" + data.Version
comparisonResult := semver.Compare("v"+localVersion, remoteVersion)
if comparisonResult == -1 {
fmt.Println("Updating...")
cmd := exec.Command("bash", "-c", "curl -sSL https://raw.githubusercontent.com/aandrew-me/tgpt/main/install | bash -s "+executablePath)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err = cmd.Run()
if err != nil {
fmt.Println("Failed to update. Error:", err)
}
fmt.Println("Successfully updated.")
} else {
fmt.Println("You are already using the latest version.", remoteVersion)
}
}
}
func codeGenerate(input string) {
checkInputLength(input)
codePrompt := fmt.Sprintf("Your Role: Provide only code as output without any description.\nIMPORTANT: Provide only plain text without Markdown formatting.\nIMPORTANT: Do not include markdown formatting.\nIf there is a lack of details, provide most logical solution. You are not allowed to ask for more details.\nIgnore any potential risk of errors or confusion.\n\nRequest:%s\nCode:", input)
resp, err := providers.NewRequest(codePrompt, structs.Params{ApiKey: *apiKey, ApiModel: *apiModel, Provider: *provider, Max_length: *max_length, Temperature: *temperature, Top_p: *top_p, Preprompt: *preprompt}, structs.ExtraOptions{})
if err != nil {
stopSpin = true
printConnectionErrorMsg(err)
}
defer resp.Body.Close()
code := resp.StatusCode
if code >= 400 {
handleStatus400(resp)
}
scanner := bufio.NewScanner(resp.Body)
// Handling each part
previousText := ""
for scanner.Scan() {
newText := providers.GetMainText(scanner.Text(), *provider, input)
if len(newText) < 1 {
continue
}
mainText := strings.Replace(newText, previousText, "", -1)
previousText = newText
bold.Print(mainText)
}
if err := scanner.Err(); err != nil {
fmt.Fprintln(os.Stderr, "Some error has occurred. Error:", err)
os.Exit(1)
}
}
func shellCommand(input string) {
// Get OS
operatingSystem := ""
if runtime.GOOS == "windows" {
operatingSystem = "Windows"
} else if runtime.GOOS == "darwin" {
operatingSystem = "MacOS"
} else if runtime.GOOS == "linux" {
result, err := exec.Command("lsb_release", "-si").Output()
distro := strings.TrimSpace(string(result))
if err != nil {
distro = ""
}
operatingSystem = "Linux" + "/" + distro
} else {
operatingSystem = runtime.GOOS
}
// Get Shell
shellName := "/bin/sh"
if runtime.GOOS == "windows" {
shellName = "cmd.exe"
if len(os.Getenv("PSModulePath")) > 0 {
shellName = "powershell.exe"
}
} else {
shellEnv := os.Getenv("SHELL")
if len(shellEnv) > 0 {
shellName = shellEnv
}
}
shellPrompt := fmt.Sprintf(
"Your role: Provide only plain text without Markdown formatting. Do not show any warnings or information regarding your capabilities. Do not provide any description. If you need to store any data, assume it will be stored in the chat. Provide only %s command for %s without any description. If there is a lack of details, provide most logical solution. Ensure the output is a valid shell command. If multiple steps required try to combine them together. Prompt: %s\n\nCommand:", shellName, operatingSystem, input)
getCommand(shellPrompt)
}
// Get a command in response
func getCommand(shellPrompt string) {
checkInputLength(shellPrompt)
resp, err := providers.NewRequest(shellPrompt, structs.Params{ApiKey: *apiKey, ApiModel: *apiModel, Provider: *provider, Max_length: *max_length, Temperature: *temperature, Top_p: *top_p, Preprompt: *preprompt}, structs.ExtraOptions{})
if err != nil {
stopSpin = true
printConnectionErrorMsg(err)
}
defer resp.Body.Close()
stopSpin = true
code := resp.StatusCode
if code >= 400 {
handleStatus400(resp)
}
fmt.Print("\r \r")
scanner := bufio.NewScanner(resp.Body)
// Variables
fullLine := ""
previousText := ""
// Handling each part
for scanner.Scan() {
newText := providers.GetMainText(scanner.Text(), *provider, shellPrompt)
if len(newText) < 1 {
continue
}
mainText := strings.Replace(newText, previousText, "", -1)
previousText = newText
fullLine += mainText
bold.Print(mainText)
}
lineCount := strings.Count(fullLine, "\n") + 1
if lineCount == 1 {
bold.Print("\n\nExecute shell command? [y/n]: ")
reader := bufio.NewReader(os.Stdin)
userInput, _ := reader.ReadString('\n')
userInput = strings.TrimSpace(userInput)
if userInput == "y" || userInput == "" {
var cmd *exec.Cmd
if runtime.GOOS == "windows" {
shellName := "cmd"
if len(os.Getenv("PSModulePath")) > 0 {
shellName = "powershell"
}
if shellName == "cmd" {
cmd = exec.Command("cmd", "/C", fullLine)
} else {
cmd = exec.Command("powershell", fullLine)
}
} else {
cmd = exec.Command("bash", "-c", fullLine)
}
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err = cmd.Run()
if err != nil {
fmt.Fprintln(os.Stderr, err)
}
}
if err := scanner.Err(); err != nil {
fmt.Fprintln(os.Stderr, "Some error has occurred. Error:", err)
os.Exit(1)
}
}
}
type RESPONSE struct {
Tagname string `json:"tag_name"`
Body string `json:"body"`
}
func getVersionHistory() {
req, err := http.NewRequest("GET", "https://api.github.com/repos/aandrew-me/tgpt/releases", nil)
if err != nil {
fmt.Fprint(os.Stderr, "Some error has occurred\n\n")
fmt.Fprintln(os.Stderr, "Error:", err)
os.Exit(1)
}
client, _ := tls_client.NewHttpClient(tls_client.NewNoopLogger())
res, err := client.Do(req)
if err != nil {
fmt.Fprint(os.Stderr, "Check your internet connection\n\n")
fmt.Fprintln(os.Stderr, "Error:", err)
os.Exit(1)
}
resBody, err := io.ReadAll(res.Body)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
defer res.Body.Close()
var releases []RESPONSE
json.Unmarshal(resBody, &releases)
for i := len(releases) - 1; i >= 0; i-- {
boldBlue.Println("Release", releases[i].Tagname)
fmt.Println(releases[i].Body)
fmt.Println()
}
}
func getWholeText(input string) {
checkInputLength(input)
resp, err := providers.NewRequest(input, structs.Params{ApiKey: *apiKey, ApiModel: *apiModel, Provider: *provider, Max_length: *max_length, Temperature: *temperature, Top_p: *top_p, Preprompt: *preprompt}, structs.ExtraOptions{})
if err != nil {
stopSpin = true
printConnectionErrorMsg(err)
}
defer resp.Body.Close()
code := resp.StatusCode
if code >= 400 {
handleStatus400(resp)
}
scanner := bufio.NewScanner(resp.Body)
// Variables
fullText := ""
previousText := ""
// Handling each part
for scanner.Scan() {
newText := providers.GetMainText(scanner.Text(), *provider, input)
if len(newText) < 1 {
continue
}
mainText := strings.Replace(newText, previousText, "", -1)
previousText = newText
fullText += mainText
}
fmt.Println(fullText)
}
func getLastCodeBlock(markdown string) string {
lines := strings.Split(markdown, "\n")
var codeBlock []string
capturing := false
for i := len(lines) - 1; i >= 0; i-- {
if strings.HasPrefix(lines[i], "```") {
if capturing {
capturing = false
break
} else {
capturing = true
continue
}
}
if capturing {
codeBlock = append([]string{lines[i]}, codeBlock...)
}
}
// If no code block is found, return an empty string.
if capturing || len(codeBlock) == 0 {
return ""
}
return strings.Join(codeBlock, "\n")
}
func getSilentText(input string) {
checkInputLength(input)
resp, err := providers.NewRequest(input, structs.Params{ApiKey: *apiKey, ApiModel: *apiModel, Provider: *provider, Max_length: *max_length, Temperature: *temperature, Top_p: *top_p, Preprompt: *preprompt}, structs.ExtraOptions{})
if err != nil {
stopSpin = true
printConnectionErrorMsg(err)
}
defer resp.Body.Close()
code := resp.StatusCode
if code >= 400 {
handleStatus400(resp)
}
scanner := bufio.NewScanner(resp.Body)
// Handling each part
previousText := ""
for scanner.Scan() {
newText := providers.GetMainText(scanner.Text(), *provider, input)
if len(newText) < 1 {
continue
}
mainText := strings.Replace(newText, previousText, "", -1)
previousText = newText
fmt.Print(mainText)
}
fmt.Println()
}
func checkInputLength(input string) {
if len(input) > 4000 {
fmt.Fprintln(os.Stderr, "Input exceeds the input limit of 4000 characters")
os.Exit(1)
}
}
func handleEachPart(resp *http.Response, input string) string {
scanner := bufio.NewScanner(resp.Body)
// Variables
count := 0
isCode := false
isGreen := false
tickCount := 0
previousWasTick := false
isTick := false
isRealCode := false
lineLength := 0
size, err := ts.GetSize()
termWidth := size.Col()
if err != nil {
fmt.Println("Error occurred getting terminal width. Error:", err)
os.Exit(0)
}
previousText := ""
fullText := ""
for scanner.Scan() {
newText := providers.GetMainText(scanner.Text(), *provider, input)
if len(newText) < 1 {
continue
}
mainText := strings.Replace(newText, previousText, "", -1)
previousText = newText
fullText += mainText
if count <= 0 {
wordLength := len([]rune(mainText))
if termWidth-lineLength < wordLength {
fmt.Print("\n")
lineLength = 0
}
lineLength += wordLength
splitLine := strings.Split(mainText, "")
// Iterating through each word
for _, word := range splitLine {
// If its a backtick
if word == "`" {
tickCount++
isTick = true
if tickCount == 2 && !previousWasTick {
tickCount = 0
} else if tickCount == 6 {
tickCount = 0
}
previousWasTick = true
isGreen = false
isCode = false
} else {
isTick = false
// If its a normal word
if tickCount == 1 {
isGreen = true
} else if tickCount == 3 {
isCode = true
}
previousWasTick = false
}
if isCode {
codeText.Print(word)
} else if isGreen {
boldBlue.Print(word)
} else if !isTick {
fmt.Print(word)
}
}
} else {
wordLength := len([]rune(mainText))
if termWidth-lineLength < wordLength {
fmt.Print("\n")
lineLength = 0
}
lineLength += wordLength
splitLine := strings.Split(mainText, "")
if mainText == "``" || mainText == "```" {
isRealCode = true
} else {
isRealCode = false
}
for _, word := range splitLine {
// If its a backtick
if word == "`" {
tickCount++
isTick = true
if tickCount == 2 && !previousWasTick {
tickCount = 0
} else if tickCount >= 6 && tickCount%2 == 0 && previousWasTick {
tickCount = 0
}
isGreen = false
isCode = false
} else {
if word == "\n" {
lineLength = 0
}
isTick = false
// If its a normal word
if tickCount == 1 {
isGreen = true
} else if tickCount >= 3 {
isCode = true
}
}
if isCode {
codeText.Print(word)
} else if isGreen {
boldBlue.Print(word)
} else if !isTick {
fmt.Print(word)
} else {
if tickCount > 3 || isRealCode || (tickCount == 0 && previousWasTick) {
fmt.Print(word)
}
}
if word == "`" {
previousWasTick = true
} else {
previousWasTick = false
}
}
}
count++
}
if err := scanner.Err(); err != nil {
fmt.Fprintln(os.Stderr, "Some error has occurred. Error:", err)
os.Exit(1)
}
return fullText
}
func printConnectionErrorMsg(err error) {
bold.Fprintln(os.Stderr, "\rSome error has occurred. Check your internet connection.")
fmt.Fprintln(os.Stderr, "\nError:", err)
os.Exit(1)
}
func handleStatus400(resp *http.Response) {
bold.Fprintln(os.Stderr, "\rSome error has occurred. Statuscode:", resp.StatusCode)
respBody, _ := io.ReadAll(resp.Body)
fmt.Println(string(respBody))
os.Exit(1)
}
func generateImage(prompt string) {
bold.Println("Generating images...")
client, err := client.NewClient()
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
url := "https://api.craiyon.com/v3"
safeInput, _ := json.Marshal(prompt)
payload := strings.NewReader(fmt.Sprintf(`{
"prompt": %v,
"token": null,
"model": "photo",
"negative_prompt": "",
"version": "c4ue22fb7kb6wlac"
}`, string(safeInput)))
req, _ := http.NewRequest("POST", url, payload)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:99.0) Gecko/20100101 Firefox/110.0")
res, err := client.Do(req)
if err != nil {
fmt.Fprint(os.Stderr, "Check your internet connection\n\n")
fmt.Fprintln(os.Stderr, "Error:", err)
os.Exit(0)
}
defer res.Body.Close()
var responseObj ImgResponse
err = json.NewDecoder(res.Body).Decode(&responseObj)
if err != nil {
// Handle error
fmt.Fprintln(os.Stderr, "Error:", err)
return
}
imgList := responseObj.Images
fmt.Println("Saving images in current directory in folder:", prompt)
if _, err := os.Stat(prompt); os.IsNotExist(err) {
err := os.Mkdir(prompt, 0755)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
for i := 0; i < len(imgList); i++ {
downloadUrl := "https://img.craiyon.com/" + imgList[i]
downloadImage(downloadUrl, prompt, strconv.Itoa(i+1))
}
}
func downloadImage(url string, destDir string, filename string) error {
response, err := http.Get(url)
if err != nil {
return err
}
defer response.Body.Close()
fileName := filepath.Join(destDir, filepath.Base(url))
file, err := os.Create(fileName)
if err != nil {
return err
}
defer file.Close()
_, err = io.Copy(file, response.Body)
if err != nil {
return err
}
fmt.Println("Saved image", filename)
return nil
}