-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgemini.go
102 lines (90 loc) · 2.37 KB
/
gemini.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
package gemini
import (
"context"
"fmt"
"strings"
"github.com/fimreal/goutils/ezap"
"github.com/google/generative-ai-go/genai"
"google.golang.org/api/option"
)
type Session struct {
Name string
Token string
Endpoint string
Prompt genai.Part
SafetyMode bool // default is false
}
func NewSession(token string) *Session {
return &Session{
// https://cloud.google.com/vertex-ai/generative-ai/docs/learn/model-versioning?hl=zh-cn#stable-versions-available for more information
Name: "gemini-1.0-pro",
Token: token,
Endpoint: "generativelanguage.googleapis.com",
Prompt: nil,
}
}
func (s *Session) SetModelName(name string) {
s.Name = name
ezap.Info("Set Model Name: ", s.Name)
}
func (s *Session) SetModelEndpoint(endpoint string) {
s.Endpoint = endpoint
ezap.Info("Set Model Endpoint: ", s.Endpoint)
}
func (s *Session) SetModelPrompt(prompt string) {
s.Prompt = genai.Text(prompt)
ezap.Info("Set Model Prompt: ", s.Prompt)
}
func (s *Session) SetSafetyMode(enabled bool) {
s.SafetyMode = enabled
ezap.Info("Set Safety Mode: ", s.SafetyMode)
}
func (s *Session) Ask(question string) (answer string, err error) {
ctx := context.Background()
client, err := genai.NewClient(ctx, option.WithAPIKey(s.Token), option.WithEndpoint(s.Endpoint))
if err != nil {
return "", err
}
defer client.Close()
// Create a Generative Model
model := client.GenerativeModel(s.Name)
// model.SetTemperature(0.9)
// model.SetTopP(0.5)
// model.SetTopK(20)
// model.SetMaxOutputTokens(100)
model.SystemInstruction = &genai.Content{
Parts: []genai.Part{s.Prompt},
}
// satety mode
if s.SafetyMode {
model.SafetySettings = []*genai.SafetySetting{
{
Category: genai.HarmCategoryDangerousContent,
Threshold: genai.HarmBlockLowAndAbove,
},
{
Category: genai.HarmCategoryHarassment,
Threshold: genai.HarmBlockMediumAndAbove,
},
}
}
ezap.Info("Ask Gemini: ", question)
resp, err := model.GenerateContent(ctx, genai.Text(question))
if err != nil {
return "", err
}
ctx.Done()
return readAllFrom(resp), err
}
func readAllFrom(resp *genai.GenerateContentResponse) string {
var parts strings.Builder
for _, cand := range resp.Candidates {
if cand.Content != nil {
for _, part := range cand.Content.Parts {
ezap.Debug("Gemini Say: ", part)
parts.WriteString(fmt.Sprintf("%s", part))
}
}
}
return parts.String()
}