-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathai.go
83 lines (65 loc) · 1.49 KB
/
ai.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
package ai
import (
"context"
"errors"
"fmt"
"log"
"os"
"strings"
"sync"
"github.com/google/generative-ai-go/genai"
"google.golang.org/api/option"
)
var (
client *genai.Client // Pointer to hold the Gemini client instance
once sync.Once // Once object for ensuring single client creation
)
func NewClient() (*genai.Client, error) {
once.Do(func() {
ctx := context.Background()
apiKey := os.Getenv("GEMINI_API_KEY")
if apiKey == "" {
log.Fatal("GEMINI_API_KEY not set")
}
var err error
client, err = genai.NewClient(ctx, option.WithAPIKey(apiKey))
if err != nil {
log.Fatal(err)
}
})
return client, nil
}
func Generate(ctx context.Context, template string, prompt string) (string, error) {
client, err := NewClient()
if err != nil {
return "", err
}
model := client.GenerativeModel("gemini-pro")
userPrompt := fmt.Sprintf(template, prompt)
resp, err := model.GenerateContent(ctx, genai.Text(userPrompt))
if err != nil {
return "", err
}
part := getResponse(resp)
if part == nil {
return "", errors.New("please provide a valid prompt")
}
return fmt.Sprint(part), nil
}
func getResponse(resp *genai.GenerateContentResponse) genai.Part {
var foundPart genai.Part
for _, cand := range resp.Candidates {
if cand.Content != nil {
for _, part := range cand.Content.Parts {
if strings.Contains(fmt.Sprint(part), "NAVI_AI_ERROR") {
return nil
}
foundPart = part
}
}
}
if foundPart == nil {
return nil
}
return foundPart
}