-
-
Notifications
You must be signed in to change notification settings - Fork 701
/
Copy pathgoogleai.go
492 lines (443 loc) · 13.6 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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
//nolint:all
package googleai
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"strings"
"github.com/google/generative-ai-go/genai"
"github.com/tmc/langchaingo/internal/util"
"github.com/tmc/langchaingo/llms"
"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")
)
const (
CITATIONS = "citations"
SAFETY = "safety"
RoleSystem = "system"
RoleModel = "model"
RoleUser = "user"
RoleTool = "tool"
)
// 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
model.SafetySettings = []*genai.SafetySetting{
{
Category: genai.HarmCategoryDangerousContent,
Threshold: genai.HarmBlockThreshold(g.opts.HarmThreshold),
},
{
Category: genai.HarmCategoryHarassment,
Threshold: genai.HarmBlockThreshold(g.opts.HarmThreshold),
},
{
Category: genai.HarmCategoryHateSpeech,
Threshold: genai.HarmBlockThreshold(g.opts.HarmThreshold),
},
{
Category: genai.HarmCategorySexuallyExplicit,
Threshold: genai.HarmBlockThreshold(g.opts.HarmThreshold),
},
}
var err error
if model.Tools, err = convertTools(opts.Tools); err != nil {
return nil, err
}
var response *llms.ContentResponse
if len(messages) == 1 {
theMessage := messages[0]
if theMessage.Role != llms.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, usage *genai.UsageMetadata) (*llms.ContentResponse, error) {
var contentResponse llms.ContentResponse
var toolCalls []llms.ToolCall
for _, candidate := range candidates {
buf := strings.Builder{}
if candidate.Content != nil {
for _, part := range candidate.Content.Parts {
switch v := part.(type) {
case genai.Text:
_, err := buf.WriteString(string(v))
if err != nil {
return nil, err
}
case genai.FunctionCall:
b, err := json.Marshal(v.Args)
if err != nil {
return nil, err
}
toolCall := llms.ToolCall{
FunctionCall: &llms.FunctionCall{
Name: v.Name,
Arguments: string(b),
},
}
toolCalls = append(toolCalls, toolCall)
default:
return nil, ErrUnknownPartInResponse
}
}
}
metadata := make(map[string]any)
metadata[CITATIONS] = candidate.CitationMetadata
metadata[SAFETY] = candidate.SafetyRatings
if usage != nil {
metadata["input_tokens"] = usage.PromptTokenCount
metadata["output_tokens"] = usage.CandidatesTokenCount
metadata["total_tokens"] = usage.TotalTokenCount
}
contentResponse.Choices = append(contentResponse.Choices,
&llms.ContentChoice{
Content: buf.String(),
StopReason: candidate.FinishReason.String(),
GenerationInfo: metadata,
ToolCalls: toolCalls,
})
}
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)
case llms.ToolCall:
fc := p.FunctionCall
var argsMap map[string]any
if err := json.Unmarshal([]byte(fc.Arguments), &argsMap); err != nil {
return convertedParts, err
}
out = genai.FunctionCall{
Name: fc.Name,
Args: argsMap,
}
case llms.ToolCallResponse:
out = genai.FunctionResponse{
Name: p.Name,
Response: map[string]any{
"response": p.Content,
},
}
}
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 llms.ChatMessageTypeSystem:
c.Role = RoleSystem
case llms.ChatMessageTypeAI:
c.Role = RoleModel
case llms.ChatMessageTypeHuman:
c.Role = RoleUser
case llms.ChatMessageTypeGeneric:
c.Role = RoleUser
case llms.ChatMessageTypeTool:
c.Role = RoleUser
case llms.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, resp.UsageMetadata)
}
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
}
if mc.Role == RoleSystem {
model.SystemInstruction = content
continue
}
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]
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, resp.UsageMetadata)
}
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 {
return nil, fmt.Errorf("error in stream mode: %w", 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
}
}
}
}
mresp := iter.MergedResponse()
return convertCandidates([]*genai.Candidate{candidate}, mresp.UsageMetadata)
}
// convertTools converts from a list of langchaingo tools to a list of genai
// tools.
func convertTools(tools []llms.Tool) ([]*genai.Tool, error) {
genaiTools := make([]*genai.Tool, 0, len(tools))
for i, tool := range tools {
if tool.Type != "function" {
return nil, fmt.Errorf("tool [%d]: unsupported type %q, want 'function'", i, tool.Type)
}
// We have a llms.FunctionDefinition in tool.Function, and we have to
// convert it to genai.FunctionDeclaration
genaiFuncDecl := &genai.FunctionDeclaration{
Name: tool.Function.Name,
Description: tool.Function.Description,
}
// Expect the Parameters field to be a map[string]any, from which we will
// extract properties to populate the schema.
params, ok := tool.Function.Parameters.(map[string]any)
if !ok {
return nil, fmt.Errorf("tool [%d]: unsupported type %T of Parameters", i, tool.Function.Parameters)
}
schema := &genai.Schema{}
if ty, ok := params["type"]; ok {
tyString, ok := ty.(string)
if !ok {
return nil, fmt.Errorf("tool [%d]: expected string for type", i)
}
schema.Type = convertToolSchemaType(tyString)
}
paramProperties, ok := params["properties"].(map[string]any)
if !ok {
return nil, fmt.Errorf("tool [%d]: expected to find a map of properties", i)
}
schema.Properties = make(map[string]*genai.Schema)
for propName, propValue := range paramProperties {
valueMap, ok := propValue.(map[string]any)
if !ok {
return nil, fmt.Errorf("tool [%d], property [%v]: expect to find a value map", i, propName)
}
schema.Properties[propName] = &genai.Schema{}
if ty, ok := valueMap["type"]; ok {
tyString, ok := ty.(string)
if !ok {
return nil, fmt.Errorf("tool [%d]: expected string for type", i)
}
schema.Properties[propName].Type = convertToolSchemaType(tyString)
}
if desc, ok := valueMap["description"]; ok {
descString, ok := desc.(string)
if !ok {
return nil, fmt.Errorf("tool [%d]: expected string for description", i)
}
schema.Properties[propName].Description = descString
}
}
if required, ok := params["required"]; ok {
if rs, ok := required.([]string); ok {
schema.Required = rs
} else if ri, ok := required.([]interface{}); ok {
rs := make([]string, 0, len(ri))
for _, r := range ri {
rString, ok := r.(string)
if !ok {
return nil, fmt.Errorf("tool [%d]: expected string for required", i)
}
rs = append(rs, rString)
}
schema.Required = rs
} else {
return nil, fmt.Errorf("tool [%d]: expected string for required", i)
}
}
genaiFuncDecl.Parameters = schema
genaiTools = append(genaiTools, &genai.Tool{
FunctionDeclarations: []*genai.FunctionDeclaration{genaiFuncDecl},
})
}
return genaiTools, nil
}
// convertToolSchemaType converts a tool's schema type from its langchaingo
// representation (string) to a genai enum.
func convertToolSchemaType(ty string) genai.Type {
switch ty {
case "object":
return genai.TypeObject
case "string":
return genai.TypeString
case "number":
return genai.TypeNumber
case "integer":
return genai.TypeInteger
case "boolean":
return genai.TypeBoolean
case "array":
return genai.TypeArray
default:
return genai.TypeUnspecified
}
}
// showContent is a debugging helper for genai.Content.
func showContent(w io.Writer, cs []*genai.Content) {
fmt.Fprintf(w, "Content (len=%v)\n", len(cs))
for i, c := range cs {
fmt.Fprintf(w, "[%d]: Role=%s\n", i, c.Role)
for j, p := range c.Parts {
fmt.Fprintf(w, " Parts[%v]: ", j)
switch pp := p.(type) {
case genai.Text:
fmt.Fprintf(w, "Text %q\n", pp)
case genai.Blob:
fmt.Fprintf(w, "Blob MIME=%q, size=%d\n", pp.MIMEType, len(pp.Data))
case genai.FunctionCall:
fmt.Fprintf(w, "FunctionCall Name=%v, Args=%v\n", pp.Name, pp.Args)
case genai.FunctionResponse:
fmt.Fprintf(w, "FunctionResponse Name=%v Response=%v\n", pp.Name, pp.Response)
default:
fmt.Fprintf(w, "unknown type %T\n", pp)
}
}
}
}