-
Notifications
You must be signed in to change notification settings - Fork 0
/
gemini.go
75 lines (58 loc) · 1.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
package chatter
import (
"context"
"errors"
"fmt"
"strings"
"github.com/google/generative-ai-go/genai"
"google.golang.org/api/iterator"
"google.golang.org/api/option"
)
type Gemini struct {
APIKey string
Model string
}
type GeminiChatter struct {
client *genai.Client
session *genai.ChatSession
model string
}
func NewGeminiChatter(ctx context.Context, gCfg Gemini) (*GeminiChatter, error) {
gClient, gcErr := genai.NewClient(ctx, option.WithAPIKey(gCfg.APIKey))
if gcErr != nil {
return nil, gcErr
}
session := gClient.GenerativeModel(gCfg.Model).StartChat()
return &GeminiChatter{
client: gClient,
session: session,
model: gCfg.Model,
}, nil
}
func (c *GeminiChatter) Model() string {
return c.model
}
func (c *GeminiChatter) Close() error {
return c.client.Close()
}
func (c *GeminiChatter) MakeSynchronousTextQuery(ctx context.Context, console Console, prompt string) (string, error) {
iter := c.session.SendMessageStream(ctx, genai.Text(prompt))
var responseBuilder strings.Builder
for {
resp, errNext := iter.Next()
if errors.Is(errNext, iterator.Done) {
break
}
if errNext != nil {
return "", errNext
}
for _, candidate := range resp.Candidates {
for _, part := range candidate.Content.Parts {
responseBuilder.WriteString(fmt.Sprintf("%s", part))
console.Printf("%s", part)
}
}
}
console.Println()
return responseBuilder.String(), nil
}