-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsearchCmd.go
80 lines (63 loc) · 2.07 KB
/
searchCmd.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
package cmd
import (
"context"
"fmt"
"log"
"os"
"regexp"
"strconv"
"strings"
"github.com/google/generative-ai-go/genai"
"github.com/spf13/cobra"
"google.golang.org/api/option"
)
var numWords string = "150"
var searchCmd = &cobra.Command{
Use: "search [your question]",
Example: "gencli search 'What is new in Golang?'",
Short: "Ask a question and get a response (Please put your question in quotes)",
Long: "Ask a question and get a response in a specified number of words. The default number of words is 150. You can change the number of words by using the --words flag.",
Args: cobra.MinimumNArgs(1),
Run: func(cmd *cobra.Command, args []string) {
res := getApiResponse(args)
fmt.Println(res)
},
}
func getApiResponse(args []string) string {
userArgs := strings.Join(args[0:], " ")
ctx := context.Background()
client, err := genai.NewClient(ctx, option.WithAPIKey(os.Getenv("GEMINI_API_KEY")))
CheckNilError(err)
defer client.Close()
// Validate user input is a number
_, err = strconv.Atoi(numWords)
if err != nil {
log.Fatal("Invalid number of words")
}
model := client.GenerativeModel("gemini-1.5-flash")
resp, err := model.GenerateContent(ctx, genai.Text(userArgs+" in "+numWords+" words."))
CheckNilError(err)
finalResponse := resp.Candidates[0].Content.Parts[0]
return formatAsPlainText(fmt.Sprint(finalResponse))
}
func formatAsPlainText(input string) string {
// Remove Markdown headings
re := regexp.MustCompile(`^#{1,6}\s+(.*)`)
input = re.ReplaceAllString(input, "$1")
// Remove horizontal rules
re = regexp.MustCompile(`\n---\n`)
input = re.ReplaceAllString(input, "\n")
// Remove italic formatting
re = regexp.MustCompile(`_([^_]+)_`)
input = re.ReplaceAllString(input, "$1")
// Remove bold formatting
re = regexp.MustCompile(`\*\*([^*]+)\*\*`)
input = re.ReplaceAllString(input, "$1")
// Remove bullet points
re = regexp.MustCompile(`\n\* (.*)`)
input = re.ReplaceAllString(input, "\n- $1")
return input
}
func init() {
searchCmd.Flags().StringVarP(&numWords, "words", "w", "150", "Number of words in the response")
}