forked from tmc/langchaingo
/
googleai.go
280 lines (242 loc) · 8.05 KB
/
googleai.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
package googleai
import (
"context"
"errors"
"fmt"
"log"
"strings"
"github.com/google/generative-ai-go/genai"
"github.com/shawti/langchaingo/internal/util"
"github.com/shawti/langchaingo/llms"
"github.com/shawti/langchaingo/schema"
"google.golang.org/api/iterator"
)
var (
ErrNoContentInResponse = errors.New("no content in generation response")
ErrUnknownPartInResponse = errors.New("unknown part type in generation response")
ErrInvalidMimeType = errors.New("invalid mime type on content")
ErrSystemRoleNotSupported = errors.New("system role isn't supporeted yet")
)
const (
CITATIONS = "citations"
SAFETY = "safety"
RoleModel = "model"
RoleUser = "user"
)
// Call implements the [llms.Model] interface.
func (g *GoogleAI) Call(ctx context.Context, prompt string, options ...llms.CallOption) (string, error) {
return llms.GenerateFromSinglePrompt(ctx, g, prompt, options...)
}
// GenerateContent implements the [llms.Model] interface.
func (g *GoogleAI) GenerateContent(ctx context.Context, messages []llms.MessageContent, options ...llms.CallOption) (*llms.ContentResponse, error) {
if g.CallbacksHandler != nil {
g.CallbacksHandler.HandleLLMGenerateContentStart(ctx, messages)
}
opts := llms.CallOptions{
Model: g.opts.defaultModel,
CandidateCount: g.opts.defaultCandidateCount,
MaxTokens: g.opts.defaultMaxTokens,
Temperature: g.opts.defaultTemperature,
TopP: g.opts.defaultTopP,
TopK: g.opts.defaultTopK,
}
for _, opt := range options {
opt(&opts)
}
model := g.client.GenerativeModel(opts.Model)
model.SetCandidateCount(int32(opts.CandidateCount))
model.SetMaxOutputTokens(int32(opts.MaxTokens))
model.SetTemperature(float32(opts.Temperature))
model.SetTopP(float32(opts.TopP))
model.SetTopK(int32(opts.TopK))
model.StopSequences = opts.StopWords
var response *llms.ContentResponse
var err error
if len(messages) == 1 {
theMessage := messages[0]
if theMessage.Role != schema.ChatMessageTypeHuman {
return nil, fmt.Errorf("got %v message role, want human", theMessage.Role)
}
response, err = generateFromSingleMessage(ctx, model, theMessage.Parts, &opts)
} else {
response, err = generateFromMessages(ctx, model, messages, &opts)
}
if err != nil {
return nil, err
}
if g.CallbacksHandler != nil {
g.CallbacksHandler.HandleLLMGenerateContentEnd(ctx, response)
}
return response, nil
}
// convertCandidates converts a sequence of genai.Candidate to a response.
func convertCandidates(candidates []*genai.Candidate) (*llms.ContentResponse, error) {
var contentResponse llms.ContentResponse
for _, candidate := range candidates {
buf := strings.Builder{}
if candidate.Content != nil {
for _, part := range candidate.Content.Parts {
if v, ok := part.(genai.Text); ok {
_, err := buf.WriteString(string(v))
if err != nil {
return nil, err
}
} else {
return nil, ErrUnknownPartInResponse
}
}
}
metadata := make(map[string]any)
metadata[CITATIONS] = candidate.CitationMetadata
metadata[SAFETY] = candidate.SafetyRatings
contentResponse.Choices = append(contentResponse.Choices,
&llms.ContentChoice{
Content: buf.String(),
StopReason: candidate.FinishReason.String(),
GenerationInfo: metadata,
})
}
return &contentResponse, nil
}
// convertParts converts between a sequence of langchain parts and genai parts.
func convertParts(parts []llms.ContentPart) ([]genai.Part, error) {
convertedParts := make([]genai.Part, 0, len(parts))
for _, part := range parts {
var out genai.Part
switch p := part.(type) {
case llms.TextContent:
out = genai.Text(p.Text)
case llms.BinaryContent:
out = genai.Blob{MIMEType: p.MIMEType, Data: p.Data}
case llms.ImageURLContent:
typ, data, err := util.DownloadImageData(p.URL)
if err != nil {
return nil, err
}
out = genai.ImageData(typ, data)
}
convertedParts = append(convertedParts, out)
}
return convertedParts, nil
}
// convertContent converts between a langchain MessageContent and genai content.
func convertContent(content llms.MessageContent) (*genai.Content, error) {
parts, err := convertParts(content.Parts)
if err != nil {
return nil, err
}
c := &genai.Content{
Parts: parts,
}
switch content.Role {
case schema.ChatMessageTypeSystem:
return nil, ErrSystemRoleNotSupported
case schema.ChatMessageTypeAI:
c.Role = RoleModel
case schema.ChatMessageTypeHuman:
c.Role = RoleUser
case schema.ChatMessageTypeGeneric:
c.Role = RoleUser
case schema.ChatMessageTypeFunction:
fallthrough
default:
return nil, fmt.Errorf("role %v not supported", content.Role)
}
return c, nil
}
// generateFromSingleMessage generates content from the parts of a single
// message.
func generateFromSingleMessage(ctx context.Context, model *genai.GenerativeModel, parts []llms.ContentPart, opts *llms.CallOptions) (*llms.ContentResponse, error) {
convertedParts, err := convertParts(parts)
if err != nil {
return nil, err
}
if opts.StreamingFunc == nil {
// When no streaming is requested, just call GenerateContent and return
// the complete response with a list of candidates.
resp, err := model.GenerateContent(ctx, convertedParts...)
if err != nil {
return nil, err
}
if len(resp.Candidates) == 0 {
return nil, ErrNoContentInResponse
}
return convertCandidates(resp.Candidates)
}
iter := model.GenerateContentStream(ctx, convertedParts...)
return convertAndStreamFromIterator(ctx, iter, opts)
}
func generateFromMessages(ctx context.Context, model *genai.GenerativeModel, messages []llms.MessageContent, opts *llms.CallOptions) (*llms.ContentResponse, error) {
history := make([]*genai.Content, 0, len(messages))
for _, mc := range messages {
content, err := convertContent(mc)
if err != nil {
return nil, err
}
history = append(history, content)
}
// Given N total messages, genai's chat expects the first N-1 messages as
// history and the last message as the actual request.
n := len(history)
reqContent := history[n-1]
history = history[:n-1]
if reqContent.Role != RoleUser {
return nil, fmt.Errorf("got %v message role, want user/human", reqContent.Role)
}
session := model.StartChat()
session.History = history
if opts.StreamingFunc == nil {
resp, err := session.SendMessage(ctx, reqContent.Parts...)
if err != nil {
return nil, err
}
if len(resp.Candidates) == 0 {
return nil, ErrNoContentInResponse
}
return convertCandidates(resp.Candidates)
}
iter := session.SendMessageStream(ctx, reqContent.Parts...)
return convertAndStreamFromIterator(ctx, iter, opts)
}
// convertAndStreamFromIterator takes an iterator of GenerateContentResponse
// and produces a llms.ContentResponse reply from it, while streaming the
// resulting text into the opts-provided streaming function.
// Note that this is tricky in the face of multiple
// candidates, so this code assumes only a single candidate for now.
func convertAndStreamFromIterator(ctx context.Context, iter *genai.GenerateContentResponseIterator, opts *llms.CallOptions) (*llms.ContentResponse, error) {
candidate := &genai.Candidate{
Content: &genai.Content{},
}
DoStream:
for {
resp, err := iter.Next()
if errors.Is(err, iterator.Done) {
break DoStream
}
if err != nil {
log.Println(err)
return nil, err
}
if len(resp.Candidates) != 1 {
return nil, fmt.Errorf("expect single candidate in stream mode; got %v", len(resp.Candidates))
}
respCandidate := resp.Candidates[0]
if respCandidate.Content == nil {
break DoStream
}
candidate.Content.Parts = append(candidate.Content.Parts, respCandidate.Content.Parts...)
candidate.Content.Role = respCandidate.Content.Role
candidate.FinishReason = respCandidate.FinishReason
candidate.SafetyRatings = respCandidate.SafetyRatings
candidate.CitationMetadata = respCandidate.CitationMetadata
candidate.TokenCount += respCandidate.TokenCount
for _, part := range respCandidate.Content.Parts {
if text, ok := part.(genai.Text); ok {
if opts.StreamingFunc(ctx, []byte(text)) != nil {
break DoStream
}
}
}
}
return convertCandidates([]*genai.Candidate{candidate})
}