-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgoogle.go
97 lines (85 loc) · 1.9 KB
/
google.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
package summaraizer
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
)
// Google is a provider that uses Google as an AI provider.
type Google struct {
Model string // The Ai model to use.
Prompt string // The prompt to use for the AI model.
ApiToken string // The API Token for Google.
}
func (a *Google) Summarize(reader io.Reader) (string, error) {
return decodeAndSummarize(reader, func(comments Comments) (string, error) {
prompt, err := resolvePrompt(a.Prompt, comments)
if err != nil {
return "", err
}
request := googleRequest{
GoogleContentsRequest: []googleContentsRequest{
{
Parts: []googlePartsRequest{
{
Text: prompt,
},
},
},
},
}
reqBodyBytes, err := json.Marshal(request)
if err != nil {
return "", err
}
url := fmt.Sprintf(
"https://generativelanguage.googleapis.com/v1beta/models/%s:generateContent?key=%s",
a.Model,
a.ApiToken,
)
req, err := http.NewRequest(
"POST",
url,
bytes.NewBuffer(reqBodyBytes),
)
if err != nil {
return "", err
}
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return "", err
}
var response googleResponse
err = json.Unmarshal(respBody, &response)
if err != nil {
return "", err
}
return response.Candidates[0].Content.Parts[0].Text, nil
})
}
type googleRequest struct {
GoogleContentsRequest []googleContentsRequest `json:"contents"`
}
type googleContentsRequest struct {
Parts []googlePartsRequest `json:"parts"`
}
type googlePartsRequest struct {
Text string `json:"text"`
}
type googleResponse struct {
Candidates []struct {
Content struct {
Parts []struct {
Text string `json:"text"`
} `json:"parts"`
} `json:"content"`
} `json:"candidates"`
}