-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathgemini.go
95 lines (83 loc) · 2.4 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
package main
import (
"context"
"fmt"
"log"
"github.com/google/generative-ai-go/genai"
"google.golang.org/api/option"
)
const ImageTemperture = 0.5
const ChatTemperture = 0.2
// Gemini Image: Input an image and get the response string.
func GeminiImage(imgData []byte) (string, error) {
ctx := context.Background()
client, err := genai.NewClient(ctx, option.WithAPIKey(geminiKey))
if err != nil {
log.Fatal(err)
}
defer client.Close()
model := client.GenerativeModel("gemini-1.5-flash-latest")
value := float32(ImageTemperture) // Set the temperature to 0.5
model.Temperature = &value
prompt := []genai.Part{
genai.ImageData("png", imgData),
genai.Text("Describe this image with scientific detail, reply in zh-TW:"),
}
log.Println("Begin processing image...")
resp, err := model.GenerateContent(ctx, prompt...)
log.Println("Finished processing image...", resp)
if err != nil {
log.Fatal(err)
return "", err
}
return printResponse(resp), nil
}
func GeminiChat(msg string) (*genai.GenerateContentResponse, error) {
ctx := context.Background()
// Access your API key as an environment variable (see "Set up your API key" above)
client, err := genai.NewClient(ctx, option.WithAPIKey(geminiKey))
if err != nil {
log.Fatal(err)
}
defer client.Close()
// For text-only input, use the gemini-pro model
model := client.GenerativeModel("gemini-1.5-flash-latest")
return model.GenerateContent(ctx, genai.Text(msg))
}
// startNewChatSession : Start a new chat session
func startNewChatSession() *genai.ChatSession {
ctx := context.Background()
client, err := genai.NewClient(ctx, option.WithAPIKey(geminiKey))
if err != nil {
log.Fatal(err)
}
model := client.GenerativeModel("gemini-1.5-flash-latest")
value := float32(ChatTemperture)
model.Temperature = &value
cs := model.StartChat()
return cs
}
// send: Send a message to the chat session
func send(cs *genai.ChatSession, msg string) *genai.GenerateContentResponse {
if cs == nil {
cs = startNewChatSession()
}
ctx := context.Background()
log.Printf("== Me: %s\n== Model:\n", msg)
res, err := cs.SendMessage(ctx, genai.Text(msg))
if err != nil {
log.Fatal(err)
}
return res
}
// Print response
func printResponse(resp *genai.GenerateContentResponse) string {
var ret string
for _, cand := range resp.Candidates {
for _, part := range cand.Content.Parts {
ret = ret + fmt.Sprintf("%v", part)
log.Println(part)
}
}
return ret
}