forked from googleapis/go-genai
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtypes.go
2165 lines (1944 loc) · 87.4 KB
/
types.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
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2024 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Code generated by the Google Gen AI SDK generator DO NOT EDIT.
package genai
import (
"cloud.google.com/go/civil"
"encoding/json"
"errors"
"fmt"
"log"
"strconv"
"strings"
"time"
)
// Outcome of the code execution.
type Outcome string
const (
// Unspecified status. This value should not be used.
OutcomeUnspecified Outcome = "OUTCOME_UNSPECIFIED"
// Code execution completed successfully.
OutcomeOK Outcome = "OUTCOME_OK"
// Code execution finished but with a failure. `stderr` should contain the reason.
OutcomeFailed Outcome = "OUTCOME_FAILED"
// Code execution ran for too long, and was cancelled. There may or may not be a partial
// output present.
OutcomeDeadlineExceeded Outcome = "OUTCOME_DEADLINE_EXCEEDED"
)
// Programming language of the `code`.
type Language string
const (
// Unspecified language. This value should not be used.
LanguageUnspecified Language = "LANGUAGE_UNSPECIFIED"
// Python >= 3.10, with numpy and simpy available.
LanguagePython Language = "PYTHON"
)
// A basic data type.
type Type string
const (
TypeUnspecified Type = "TYPE_UNSPECIFIED"
TypeString Type = "STRING"
TypeNumber Type = "NUMBER"
TypeInteger Type = "INTEGER"
TypeBoolean Type = "BOOLEAN"
TypeArray Type = "ARRAY"
TypeObject Type = "OBJECT"
)
// Harm category.
type HarmCategory string
const (
// The harm category is unspecified.
HarmCategoryUnspecified HarmCategory = "HARM_CATEGORY_UNSPECIFIED"
// The harm category is hate speech.
HarmCategoryHateSpeech HarmCategory = "HARM_CATEGORY_HATE_SPEECH"
// The harm category is dangerous content.
HarmCategoryDangerousContent HarmCategory = "HARM_CATEGORY_DANGEROUS_CONTENT"
// The harm category is harassment.
HarmCategoryHarassment HarmCategory = "HARM_CATEGORY_HARASSMENT"
// The harm category is sexually explicit content.
HarmCategorySexuallyExplicit HarmCategory = "HARM_CATEGORY_SEXUALLY_EXPLICIT"
// The harm category is civic integrity.
HarmCategoryCivicIntegrity HarmCategory = "HARM_CATEGORY_CIVIC_INTEGRITY"
)
// Specify if the threshold is used for probability or severity score. If not specified,
// the threshold is used for probability score.
type HarmBlockMethod string
const (
// The harm block method is unspecified.
HarmBlockMethodUnspecified HarmBlockMethod = "HARM_BLOCK_METHOD_UNSPECIFIED"
// The harm block method uses both probability and severity scores.
HarmBlockMethodSeverity HarmBlockMethod = "SEVERITY"
// The harm block method uses the probability score.
HarmBlockMethodProbability HarmBlockMethod = "PROBABILITY"
)
// The harm block threshold.
type HarmBlockThreshold string
const (
// Unspecified harm block threshold.
HarmBlockThresholdUnspecified HarmBlockThreshold = "HARM_BLOCK_THRESHOLD_UNSPECIFIED"
// Block low threshold and above (i.e. block more).
HarmBlockThresholdBlockLowAndAbove HarmBlockThreshold = "BLOCK_LOW_AND_ABOVE"
// Block medium threshold and above.
HarmBlockThresholdBlockMediumAndAbove HarmBlockThreshold = "BLOCK_MEDIUM_AND_ABOVE"
// Block only high threshold (i.e. block less).
HarmBlockThresholdBlockOnlyHigh HarmBlockThreshold = "BLOCK_ONLY_HIGH"
// Block none.
HarmBlockThresholdBlockNone HarmBlockThreshold = "BLOCK_NONE"
// Turn off the safety filter.
HarmBlockThresholdOff HarmBlockThreshold = "OFF"
)
// The mode of the predictor to be used in dynamic retrieval.
type Mode string
const (
// Always trigger retrieval.
ModeUnspecified Mode = "MODE_UNSPECIFIED"
// Run retrieval only when system decides it is necessary.
ModeDynamic Mode = "MODE_DYNAMIC"
)
// The reason why the model stopped generating tokens. If empty, the model has not stopped
// generating the tokens.
type FinishReason string
const (
// The finish reason is unspecified.
FinishReasonUnspecified FinishReason = "FINISH_REASON_UNSPECIFIED"
// Token generation reached a natural stopping point or a configured stop sequence.
FinishReasonStop FinishReason = "STOP"
// Token generation reached the configured maximum output tokens.
FinishReasonMaxTokens FinishReason = "MAX_TOKENS"
// Token generation stopped because the content potentially contains safety violations.
// NOTE: When streaming, content is empty if content filters blocks the output.
FinishReasonSafety FinishReason = "SAFETY"
// The token generation stopped because of potential recitation.
FinishReasonRecitation FinishReason = "RECITATION"
// All other reasons that stopped the token generation.
FinishReasonOther FinishReason = "OTHER"
// Token generation stopped because the content contains forbidden terms.
FinishReasonBlocklist FinishReason = "BLOCKLIST"
// Token generation stopped for potentially containing prohibited content.
FinishReasonProhibitedContent FinishReason = "PROHIBITED_CONTENT"
// Token generation stopped because the content potentially contains Sensitive Personally
// Identifiable Information (SPII).
FinishReasonSPII FinishReason = "SPII"
// The function call generated by the model is invalid.
FinishReasonMalformedFunctionCall FinishReason = "MALFORMED_FUNCTION_CALL"
)
// Harm probability levels in the content.
type HarmProbability string
const (
// Harm probability unspecified.
HarmProbabilityUnspecified HarmProbability = "HARM_PROBABILITY_UNSPECIFIED"
// Negligible level of harm.
HarmProbabilityNegligible HarmProbability = "NEGLIGIBLE"
// Low level of harm.
HarmProbabilityLow HarmProbability = "LOW"
// Medium level of harm.
HarmProbabilityMedium HarmProbability = "MEDIUM"
// High level of harm.
HarmProbabilityHigh HarmProbability = "HIGH"
)
// Harm severity levels in the content.
type HarmSeverity string
const (
// Harm severity unspecified.
HarmSeverityUnspecified HarmSeverity = "HARM_SEVERITY_UNSPECIFIED"
// Negligible level of harm severity.
HarmSeverityNegligible HarmSeverity = "HARM_SEVERITY_NEGLIGIBLE"
// Low level of harm severity.
HarmSeverityLow HarmSeverity = "HARM_SEVERITY_LOW"
// Medium level of harm severity.
HarmSeverityMedium HarmSeverity = "HARM_SEVERITY_MEDIUM"
// High level of harm severity.
HarmSeverityHigh HarmSeverity = "HARM_SEVERITY_HIGH"
)
// Blocked reason.
type BlockedReason string
const (
// Unspecified blocked reason.
BlockedReasonUnspecified BlockedReason = "BLOCKED_REASON_UNSPECIFIED"
// Candidates blocked due to safety.
BlockedReasonSafety BlockedReason = "SAFETY"
// Candidates blocked due to other reason.
BlockedReasonOther BlockedReason = "OTHER"
// Candidates blocked due to the terms which are included from the terminology blocklist.
BlockedReasonBlocklist BlockedReason = "BLOCKLIST"
// Candidates blocked due to prohibited content.
BlockedReasonProhibitedContent BlockedReason = "PROHIBITED_CONTENT"
)
type DeploymentResourcesType string
const (
// Should not be used.
DeploymentResourcesTypeUnspecified DeploymentResourcesType = "DEPLOYMENT_RESOURCES_TYPE_UNSPECIFIED"
// Resources that are dedicated to the DeployedModel, and that need a higher degree
// of manual configuration.
DeploymentResourcesTypeDedicatedResources DeploymentResourcesType = "DEDICATED_RESOURCES"
// Resources that to large degree are decided by Vertex AI, and require only a modest
// additional configuration.
DeploymentResourcesTypeAutomaticResources DeploymentResourcesType = "AUTOMATIC_RESOURCES"
// Resources that can be shared by multiple DeployedModels. A pre-configured DeploymentResourcePool
// is required.
DeploymentResourcesTypeSharedResources DeploymentResourcesType = "SHARED_RESOURCES"
)
// Config for the dynamic retrieval config mode.
type DynamicRetrievalConfigMode string
const (
// Always trigger retrieval.
DynamicRetrievalConfigModeUnspecified DynamicRetrievalConfigMode = "MODE_UNSPECIFIED"
// Run retrieval only when system decides it is necessary.
DynamicRetrievalConfigModeDynamic DynamicRetrievalConfigMode = "MODE_DYNAMIC"
)
// Config for the function calling config mode.
type FunctionCallingConfigMode string
const (
// The function calling config mode is unspecified. Should not be used.
FunctionCallingConfigModeUnspecified FunctionCallingConfigMode = "MODE_UNSPECIFIED"
// Default model behavior, model decides to predict either function calls or natural
// language response.
FunctionCallingConfigModeAuto FunctionCallingConfigMode = "AUTO"
// Model is constrained to always predicting function calls only. If "allowed_function_names"
// are set, the predicted function calls will be limited to any one of "allowed_function_names",
// else the predicted function calls will be any one of the provided "function_declarations".
FunctionCallingConfigModeAny FunctionCallingConfigMode = "ANY"
// Model will not predict any function calls. Model behavior is same as when not passing
// any function declarations.
FunctionCallingConfigModeNone FunctionCallingConfigMode = "NONE"
)
// The media resolution to use.
type MediaResolution string
const (
// Media resolution has not been set
MediaResolutionUnspecified MediaResolution = "MEDIA_RESOLUTION_UNSPECIFIED"
// Media resolution set to low (64 tokens).
MediaResolutionLow MediaResolution = "MEDIA_RESOLUTION_LOW"
// Media resolution set to medium (256 tokens).
MediaResolutionMedium MediaResolution = "MEDIA_RESOLUTION_MEDIUM"
// Media resolution set to high (zoomed reframing with 256 tokens).
MediaResolutionHigh MediaResolution = "MEDIA_RESOLUTION_HIGH"
)
// Enum that controls the safety filter level for objectionable content.
type SafetyFilterLevel string
const (
SafetyFilterLevelBlockLowAndAbove SafetyFilterLevel = "BLOCK_LOW_AND_ABOVE"
SafetyFilterLevelBlockMediumAndAbove SafetyFilterLevel = "BLOCK_MEDIUM_AND_ABOVE"
SafetyFilterLevelBlockOnlyHigh SafetyFilterLevel = "BLOCK_ONLY_HIGH"
SafetyFilterLevelBlockNone SafetyFilterLevel = "BLOCK_NONE"
)
// Enum that controls the generation of people.
type PersonGeneration string
const (
PersonGenerationDontAllow PersonGeneration = "DONT_ALLOW"
PersonGenerationAllowAdult PersonGeneration = "ALLOW_ADULT"
PersonGenerationAllowAll PersonGeneration = "ALLOW_ALL"
)
// Enum that specifies the language of the text in the prompt.
type ImagePromptLanguage string
const (
ImagePromptLanguageAuto ImagePromptLanguage = "auto"
ImagePromptLanguageEn ImagePromptLanguage = "en"
ImagePromptLanguageJa ImagePromptLanguage = "ja"
ImagePromptLanguageKo ImagePromptLanguage = "ko"
ImagePromptLanguageHi ImagePromptLanguage = "hi"
)
// Enum representing the mask mode of a mask reference image.
type MaskReferenceMode string
const (
MaskReferenceModeMaskModeDefault MaskReferenceMode = "MASK_MODE_DEFAULT"
MaskReferenceModeMaskModeUserProvided MaskReferenceMode = "MASK_MODE_USER_PROVIDED"
MaskReferenceModeMaskModeBackground MaskReferenceMode = "MASK_MODE_BACKGROUND"
MaskReferenceModeMaskModeForeground MaskReferenceMode = "MASK_MODE_FOREGROUND"
MaskReferenceModeMaskModeSemantic MaskReferenceMode = "MASK_MODE_SEMANTIC"
)
// Enum representing the control type of a control reference image.
type ControlReferenceType string
const (
ControlReferenceTypeDefault ControlReferenceType = "CONTROL_TYPE_DEFAULT"
ControlReferenceTypeCanny ControlReferenceType = "CONTROL_TYPE_CANNY"
ControlReferenceTypeScribble ControlReferenceType = "CONTROL_TYPE_SCRIBBLE"
ControlReferenceTypeFaceMesh ControlReferenceType = "CONTROL_TYPE_FACE_MESH"
)
// Enum representing the subject type of a subject reference image.
type SubjectReferenceType string
const (
SubjectReferenceTypeSubjectTypeDefault SubjectReferenceType = "SUBJECT_TYPE_DEFAULT"
SubjectReferenceTypeSubjectTypePerson SubjectReferenceType = "SUBJECT_TYPE_PERSON"
SubjectReferenceTypeSubjectTypeAnimal SubjectReferenceType = "SUBJECT_TYPE_ANIMAL"
SubjectReferenceTypeSubjectTypeProduct SubjectReferenceType = "SUBJECT_TYPE_PRODUCT"
)
// Server content modalities.
type Modality string
const (
// The modality is unspecified.
ModalityUnspecified Modality = "MODALITY_UNSPECIFIED"
// Indicates the model should return text
ModalityText Modality = "TEXT"
// Indicates the model should return images.
ModalityImage Modality = "IMAGE"
// Indicates the model should return images.
ModalityAudio Modality = "AUDIO"
)
// Metadata describes the input video content.
type VideoMetadata struct {
// Optional. The end offset of the video.
EndOffset string `json:"endOffset,omitempty"`
// Optional. The start offset of the video.
StartOffset string `json:"startOffset,omitempty"`
}
// Result of executing the [ExecutableCode]. Always follows a `part` containing the
// [ExecutableCode].
type CodeExecutionResult struct {
// Required. Outcome of the code execution.
Outcome Outcome `json:"outcome,omitempty"`
// Optional. Contains stdout when code execution is successful, stderr or other description
// otherwise.
Output string `json:"output,omitempty"`
}
// Code generated by the model that is meant to be executed, and the result returned
// to the model. Generated when using the [FunctionDeclaration] tool and [FunctionCallingConfig]
// mode is set to [Mode.CODE].
type ExecutableCode struct {
// Required. The code to be executed.
Code string `json:"code,omitempty"`
// Required. Programming language of the `code`.
Language Language `json:"language,omitempty"`
}
// URI based data.
type FileData struct {
// Required. URI.
FileURI string `json:"fileUri,omitempty"`
// Required. The IANA standard MIME type of the source data.
MIMEType string `json:"mimeType,omitempty"`
}
// A function call.
type FunctionCall struct {
// The unique ID of the function call. If populated, the client to execute the
// `function_call` and return the response with the matching `id`.
ID string `json:"id,omitempty"`
// Optional. Required. The function parameters and values in JSON object format. See
// [FunctionDeclaration.parameters] for parameter details.
Args map[string]any `json:"args,omitempty"`
// Required. The name of the function to call. Matches [FunctionDeclaration.name].
Name string `json:"name,omitempty"`
}
// A function response.
type FunctionResponse struct {
// The ID of the function call this response is for. Populated by the client
// to match the corresponding function call `id`.
ID string `json:"id,omitempty"`
// Required. The name of the function to call. Matches [FunctionDeclaration.name] and
// [FunctionCall.name].
Name string `json:"name,omitempty"`
// Required. The function response in JSON object format. Use "output" key to specify
// function output and "error" key to specify error details (if any). If "output" and
// "error" keys are not specified, then whole "response" is treated as function output.
Response map[string]any `json:"response,omitempty"`
}
// Content blob.
type Blob struct {
// Required. Raw bytes.
Data []byte `json:"data,omitempty"`
// Required. The IANA standard MIME type of the source data.
MIMEType string `json:"mimeType,omitempty"`
}
// A datatype containing media content.
// Exactly one field within a Part should be set, representing the specific type
// of content being conveyed. Using multiple fields within the same `Part`
// instance is considered invalid.
type Part struct {
// Metadata for a given video.
VideoMetadata *VideoMetadata `json:"videoMetadata,omitempty"`
// Indicates if the part is thought from the model.
Thought bool `json:"thought,omitempty"`
// Optional. Result of executing the [ExecutableCode].
CodeExecutionResult *CodeExecutionResult `json:"codeExecutionResult,omitempty"`
// Optional. Code generated by the model that is meant to be executed.
ExecutableCode *ExecutableCode `json:"executableCode,omitempty"`
// Optional. URI based data.
FileData *FileData `json:"fileData,omitempty"`
// Optional. A predicted [FunctionCall] returned from the model that contains a string
// representing the [FunctionDeclaration.name] with the parameters and their values.
FunctionCall *FunctionCall `json:"functionCall,omitempty"`
// Optional. The result output of a [FunctionCall] that contains a string representing
// the [FunctionDeclaration.name] and a structured JSON object containing any output
// from the function call. It is used as context to the model.
FunctionResponse *FunctionResponse `json:"functionResponse,omitempty"`
// Optional. Inlined bytes data.
InlineData *Blob `json:"inlineData,omitempty"`
// Optional. Text part (can be code).
Text string `json:"text,omitempty"`
}
// NewPartFromURI builds a Part from a given file URI and mime type.
func NewPartFromURI(fileURI, mimeType string) *Part {
return &Part{
FileData: &FileData{
FileURI: fileURI,
MIMEType: mimeType,
},
}
}
// NewPartFromText builds a Part from a given text.
func NewPartFromText(text string) *Part {
return &Part{
Text: text,
}
}
// NewPartFromBytes builds a Part from a given byte array and mime type.
func NewPartFromBytes(data []byte, mimeType string) *Part {
return &Part{
InlineData: &Blob{
Data: data,
MIMEType: mimeType,
},
}
}
// NewPartFromFunctionCall builds a Part from a given function call.
func NewPartFromFunctionCall(name string, args map[string]any) *Part {
return &Part{
FunctionCall: &FunctionCall{
Name: name,
Args: args,
},
}
}
// NewPartFromFunctionResponse builds a Part from a given function response.
func NewPartFromFunctionResponse(name string, response map[string]any) *Part {
return &Part{
FunctionResponse: &FunctionResponse{
Name: name,
Response: response,
},
}
}
// NewPartFromVideoMetadata builds a Part from a given end offset and start offset.
func NewPartFromVideoMetadata(endOffset, startOffset string) *Part {
return &Part{
VideoMetadata: &VideoMetadata{
EndOffset: endOffset,
StartOffset: startOffset,
},
}
}
// NewPartFromExecutableCode builds a Part from a given executable code and language.
func NewPartFromExecutableCode(code string, language Language) *Part {
return &Part{
ExecutableCode: &ExecutableCode{
Code: code,
Language: language,
},
}
}
// NewPartFromCodeExecutionResult builds a Part from a given outcome and output.
func NewPartFromCodeExecutionResult(outcome Outcome, output string) *Part {
return &Part{
CodeExecutionResult: &CodeExecutionResult{
Outcome: outcome,
Output: output,
},
}
}
// Contains the multi-part content of a message.
type Content struct {
// List of parts that constitute a single message. Each part may have
// a different IANA MIME type.
Parts []*Part `json:"parts,omitempty"`
// Optional. The producer of the content. Must be either 'user' or
// 'model'. Useful to set for multi-turn conversations, otherwise can be
// left blank or unset. If role is not specified, SDK will determine the role.
Role string `json:"role,omitempty"`
}
// NewUserContent builds a Content with a "user" role from a list of parts.
func NewUserContentFromParts(parts []*Part) *Content {
return &Content{
Parts: parts,
Role: "user",
}
}
// NewUserContentFromText builds a Content with a "user" role from a single text string.
func NewUserContentFromText(text string) *Content {
return &Content{
Parts: []*Part{
NewPartFromText(text),
},
Role: "user",
}
}
// NewUserContentFromBytes builds a Content with a "user" role from a single byte array.
func NewUserContentFromBytes(data []byte, mimeType string) *Content {
return &Content{
Parts: []*Part{
NewPartFromBytes(data, mimeType),
},
Role: "user",
}
}
// NewUserContentFromURI builds a Content with a "user" role from a single file URI.
func NewUserContentFromURI(fileURI, mimeType string) *Content {
return &Content{
Parts: []*Part{
NewPartFromURI(fileURI, mimeType),
},
Role: "user",
}
}
// NewUserContentFromFunctionResponse builds a Content with a "user" role from a single function response.
func NewUserContentFromFunctionResponse(name string, response map[string]any) *Content {
return &Content{
Parts: []*Part{
NewPartFromFunctionResponse(name, response),
},
Role: "user",
}
}
// NewUserContentFromExecutableCode builds a Content with a "user" role from a single executable code.
func NewUserContentFromExecutableCode(code string, language Language) *Content {
return &Content{
Parts: []*Part{
NewPartFromExecutableCode(code, language),
},
Role: "user",
}
}
// NewUserContentFromCodeExecutionResult builds a Content with a "user" role from a single code execution result.
func NewUserContentFromCodeExecutionResult(outcome Outcome, output string) *Content {
return &Content{
Parts: []*Part{
NewPartFromCodeExecutionResult(outcome, output),
},
Role: "user",
}
}
// NewModelContent builds a Content with a "model" role from a list of parts.
func NewModelContentFromParts(parts []*Part) *Content {
return &Content{
Parts: parts,
Role: "model",
}
}
// NewModelContentFromText builds a Content with a "model" role from a single text string.
func NewModelContentFromText(text string) *Content {
return &Content{
Parts: []*Part{
NewPartFromText(text),
},
Role: "model",
}
}
// NewModelContentFromBytes builds a Content with a "model" role from a single byte array.
func NewModelContentFromBytes(data []byte, mimeType string) *Content {
return &Content{
Parts: []*Part{
NewPartFromBytes(data, mimeType),
},
Role: "model",
}
}
// NewModelContentFromURI builds a Content with a "model" role from a single file URI.
func NewModelContentFromURI(fileURI, mimeType string) *Content {
return &Content{
Parts: []*Part{
NewPartFromURI(fileURI, mimeType),
},
Role: "model",
}
}
// NewModelContentFromFunctionCall builds a Content with a "model" role from a single function call.
func NewModelContentFromFunctionCall(name string, args map[string]any) *Content {
return &Content{
Parts: []*Part{
NewPartFromFunctionCall(name, args),
},
Role: "model",
}
}
// NewModelContentFromExecutableCode builds a Content with a "model" role from a single executable code.
func NewModelContentFromExecutableCode(code string, language Language) *Content {
return &Content{
Parts: []*Part{
NewPartFromExecutableCode(code, language),
},
Role: "model",
}
}
// NewModelContentFromCodeExecutionResult builds a Content with a "model" role from a single code execution result.
func NewModelContentFromCodeExecutionResult(outcome Outcome, output string) *Content {
return &Content{
Parts: []*Part{
NewPartFromCodeExecutionResult(outcome, output),
},
Role: "model",
}
}
// HTTP options to be used in each of the requests.
type HTTPOptions struct {
// BaseURL specifies the base URL for the API endpoint. If unset, defaults to "https://generativelanguage.googleapis.com/"
// for the Gemini API backend, and location-specific Vertex AI endpoint (e.g., "https://us-central1-aiplatform.googleapis.com/
BaseURL string `json:"baseUrl,omitempty"`
// APIVersion specifies the version of the API to use.
APIVersion string `json:"apiVersion,omitempty"`
// Timeout sets the timeout for HTTP requests in milliseconds. If unset, defaults to
// "v1beta" for the Gemini API, and "v1beta1" for the Vertex AI.
Timeout int64 `json:"timeout,omitempty"`
}
// Schema that defines the format of input and output data. Represents a select subset
// of an OpenAPI 3.0 schema object. You can find more details and examples at https://spec.openapis.org/oas/v3.0.3.html#schema-object
type Schema struct {
// Optional. Minimum number of the elements for Type.ARRAY.
MinItems *int64 `json:"minItems,omitempty"`
// Optional. Example of the object. Will only populated when the object is the root.
Example any `json:"example,omitempty"`
// Optional. The order of the properties. Not a standard field in open API spec. Only
// used to support the order of the properties.
PropertyOrdering []string `json:"propertyOrdering,omitempty"`
// Optional. Pattern of the Type.STRING to restrict a string to a regular expression.
Pattern string `json:"pattern,omitempty"`
// Optional. SCHEMA FIELDS FOR TYPE INTEGER and NUMBER Minimum value of the Type.INTEGER
// and Type.NUMBER
Minimum *float64 `json:"minimum,omitempty"`
// Optional. Default value of the data.
Default any `json:"default,omitempty"`
// Optional. The value should be validated against any (one or more) of the subschemas
// in the list.
AnyOf []*Schema `json:"anyOf,omitempty"`
// Optional. Maximum length of the Type.STRING
MaxLength *int64 `json:"maxLength,omitempty"`
// Optional. The title of the Schema.
Title string `json:"title,omitempty"`
// Optional. SCHEMA FIELDS FOR TYPE STRING Minimum length of the Type.STRING
MinLength *int64 `json:"minLength,omitempty"`
// Optional. Minimum number of the properties for Type.OBJECT.
MinProperties *int64 `json:"minProperties,omitempty"`
// Optional. Maximum number of the elements for Type.ARRAY.
MaxItems *int64 `json:"maxItems,omitempty"`
// Optional. Maximum value of the Type.INTEGER and Type.NUMBER
Maximum *float64 `json:"maximum,omitempty"`
// Optional. Indicates if the value may be null.
Nullable bool `json:"nullable,omitempty"`
// Optional. Maximum number of the properties for Type.OBJECT.
MaxProperties *int64 `json:"maxProperties,omitempty"`
// Optional. The type of the data.
Type Type `json:"type,omitempty"`
// Optional. The description of the data.
Description string `json:"description,omitempty"`
// Optional. Possible values of the element of primitive type with enum format. Examples:
// 1. We can define direction as : {type:STRING, format:enum, enum:["EAST", NORTH",
// "SOUTH", "WEST"]} 2. We can define apartment number as : {type:INTEGER, format:enum,
// enum:["101", "201", "301"]}
Enum []string `json:"enum,omitempty"`
// Optional. The format of the data. Supported formats: for NUMBER type: "float", "double"
// for INTEGER type: "int32", "int64" for STRING type: "email", "byte", etc
Format string `json:"format,omitempty"`
// Optional. SCHEMA FIELDS FOR TYPE ARRAY Schema of the elements of Type.ARRAY.
Items *Schema `json:"items,omitempty"`
// Optional. SCHEMA FIELDS FOR TYPE OBJECT Properties of Type.OBJECT.
Properties map[string]*Schema `json:"properties,omitempty"`
// Optional. Required properties of Type.OBJECT.
Required []string `json:"required,omitempty"`
}
// Safety settings.
type SafetySetting struct {
// Determines if the harm block method uses probability or probability
// and severity scores.
Method HarmBlockMethod `json:"method,omitempty"`
// Required. Harm category.
Category HarmCategory `json:"category,omitempty"`
// Required. The harm block threshold.
Threshold HarmBlockThreshold `json:"threshold,omitempty"`
}
// Defines a function that the model can generate JSON inputs for.
// The inputs are based on `OpenAPI 3.0 specifications
// <https://spec.openapis.org/oas/v3.0.3>`_.
type FunctionDeclaration struct {
// Describes the output from the function in the OpenAPI JSON Schema
// Object format.
Response *Schema `json:"response,omitempty"`
// Optional. Description and purpose of the function. Model uses it to decide how and
// whether to call the function.
Description string `json:"description,omitempty"`
// Required. The name of the function to call. Must start with a letter or an underscore.
// Must be a-z, A-Z, 0-9, or contain underscores, dots and dashes, with a maximum length
// of 64.
Name string `json:"name,omitempty"`
// Optional. Describes the parameters to this function in JSON Schema Object format.
// Reflects the Open API 3.03 Parameter Object. string Key: the name of the parameter.
// Parameter names are case sensitive. Schema Value: the Schema defining the type used
// for the parameter. For function with no parameters, this can be left unset. Parameter
// names must start with a letter or an underscore and must only contain chars a-z,
// A-Z, 0-9, or underscores with a maximum length of 64. Example with 1 required and
// 1 optional parameter: type: OBJECT properties: param1: type: STRING param2: type:
// INTEGER required: - param1
Parameters *Schema `json:"parameters,omitempty"`
}
// Tool to support Google Search in Model. Powered by Google.
type GoogleSearch struct {
}
// Describes the options to customize dynamic retrieval.
type DynamicRetrievalConfig struct {
// The mode of the predictor to be used in dynamic retrieval.
Mode DynamicRetrievalConfigMode `json:"mode,omitempty"`
// Optional. The threshold to be used in dynamic retrieval. If not set, a system default
// value is used.
DynamicThreshold *float64 `json:"dynamicThreshold,omitempty"`
}
// Tool to retrieve public web data for grounding, powered by Google.
type GoogleSearchRetrieval struct {
// Specifies the dynamic retrieval configuration for the given source.
DynamicRetrievalConfig *DynamicRetrievalConfig `json:"dynamicRetrievalConfig,omitempty"`
}
// Retrieve from Vertex AI Search datastore for grounding. See https://cloud.google.com/products/agent-builder
type VertexAISearch struct {
// Required. Fully-qualified Vertex AI Search data store resource ID. Format: `projects/{project}/locations/{location}/collections/{collection}/dataStores/{dataStore}`
Datastore string `json:"datastore,omitempty"`
}
// The definition of the RAG resource.
type VertexRAGStoreRAGResource struct {
// Optional. RAGCorpora resource name. Format: `projects/{project}/locations/{location}/ragCorpora/{rag_corpus}`
RAGCorpus string `json:"ragCorpus,omitempty"`
// Optional. rag_file_id. The files should be in the same rag_corpus set in rag_corpus
// field.
RAGFileIDs []string `json:"ragFileIds,omitempty"`
}
// Retrieve from Vertex RAG Store for grounding. You can find API default values and
// more details at https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/rag-api-v1#parameters-list
type VertexRAGStore struct {
// Optional. Deprecated. Please use rag_resources instead.
RAGCorpora []string `json:"ragCorpora,omitempty"`
// Optional. The representation of the RAG source. It can be used to specify corpus
// only or ragfiles. Currently only support one corpus or multiple files from one corpus.
// In the future we may open up multiple corpora support.
RAGResources []*VertexRAGStoreRAGResource `json:"ragResources,omitempty"`
// Optional. Number of top k results to return from the selected corpora.
SimilarityTopK *int64 `json:"similarityTopK,omitempty"`
// Optional. Only return results with vector distance smaller than the threshold.
VectorDistanceThreshold *float64 `json:"vectorDistanceThreshold,omitempty"`
}
// Defines a retrieval tool that model can call to access external knowledge.
type Retrieval struct {
// Optional. Deprecated. This option is no longer supported.
DisableAttribution bool `json:"disableAttribution,omitempty"`
// Set to use data source powered by Vertex AI Search.
VertexAISearch *VertexAISearch `json:"vertexAiSearch,omitempty"`
// Set to use data source powered by Vertex RAG store. User data is uploaded via the
// VertexRAGDataService.
VertexRAGStore *VertexRAGStore `json:"vertexRagStore,omitempty"`
}
// Tool that executes code generated by the model, and automatically returns the result
// to the model. See also [ExecutableCode]and [CodeExecutionResult] which are input
// and output to this tool.
type ToolCodeExecution struct {
}
// Tool details of a tool that the model may use to generate a response.
type Tool struct {
// List of function declarations that the tool supports.
FunctionDeclarations []*FunctionDeclaration `json:"functionDeclarations,omitempty"`
// Optional. Retrieval tool type. System will always execute the provided retrieval
// tool(s) to get external knowledge to answer the prompt. Retrieval results are presented
// to the model for generation.
Retrieval *Retrieval `json:"retrieval,omitempty"`
// Optional. Google Search tool type. Specialized retrieval tool
// that is powered by Google Search.
GoogleSearch *GoogleSearch `json:"googleSearch,omitempty"`
// Optional. GoogleSearchRetrieval tool type. Specialized retrieval tool that is powered
// by Google search.
GoogleSearchRetrieval *GoogleSearchRetrieval `json:"googleSearchRetrieval,omitempty"`
// Optional. CodeExecution tool type. Enables the model to execute code as part of generation.
// This field is only used by the Gemini Developer API services.
CodeExecution *ToolCodeExecution `json:"codeExecution,omitempty"`
}
// Function calling config.
type FunctionCallingConfig struct {
// Optional. Function calling mode.
Mode FunctionCallingConfigMode `json:"mode,omitempty"`
// Optional. Function names to call. Only set when the Mode is ANY. Function names should
// match [FunctionDeclaration.name]. With mode set to ANY, model will predict a function
// call from the set of function names provided.
AllowedFunctionNames []string `json:"allowedFunctionNames,omitempty"`
}
// Tool config.
// This config is shared for all tools provided in the request.
type ToolConfig struct {
// Optional. Function calling config.
FunctionCallingConfig *FunctionCallingConfig `json:"functionCallingConfig,omitempty"`
}
// The configuration for the prebuilt speaker to use.
type PrebuiltVoiceConfig struct {
// The name of the prebuilt voice to use.
VoiceName string `json:"voiceName,omitempty"`
}
// The configuration for the voice to use.
type VoiceConfig struct {
// The configuration for the speaker to use.
PrebuiltVoiceConfig *PrebuiltVoiceConfig `json:"prebuiltVoiceConfig,omitempty"`
}
// The speech generation configuration.
type SpeechConfig struct {
// The configuration for the speaker to use.
VoiceConfig *VoiceConfig `json:"voiceConfig,omitempty"`
}
// The thinking features configuration.
type ThinkingConfig struct {
// Indicates whether to include thoughts in the response. If true, thoughts are returned
// only if the model supports thought and thoughts are available.
IncludeThoughts bool `json:"includeThoughts,omitempty"`
}
// When automated routing is specified, the routing will be determined by the pretrained
// routing model and customer provided model routing preference.
type GenerationConfigRoutingConfigAutoRoutingMode struct {
// The model routing preference.
ModelRoutingPreference string `json:"modelRoutingPreference,omitempty"`
}
// When manual routing is set, the specified model will be used directly.
type GenerationConfigRoutingConfigManualRoutingMode struct {
// The model name to use. Only the public LLM models are accepted. e.g. 'gemini-1.5-pro-001'.
ModelName string `json:"modelName,omitempty"`
}
// The configuration for routing the request to a specific model.
type GenerationConfigRoutingConfig struct {
// Automated routing.
AutoMode *GenerationConfigRoutingConfigAutoRoutingMode `json:"autoMode,omitempty"`
// Manual routing.
ManualMode *GenerationConfigRoutingConfigManualRoutingMode `json:"manualMode,omitempty"`
}
// Optional configuration for the GenerateContent. You can find API default values and
// more details at https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#generationconfig
// and https://cloud.google.com/vertex-ai/generative-ai/docs/multimodal/content-generation-parameters.
type GenerateContentConfig struct {
// Instructions for the model to steer it toward better performance.
// For example, "Answer as concisely as possible" or "Don't use technical
// terms in your response".
SystemInstruction *Content `json:"systemInstruction,omitempty"`
// Value that controls the degree of randomness in token selection.
// Lower temperatures are good for prompts that require a less open-ended or
// creative response, while higher temperatures can lead to more diverse or
// creative results.
Temperature *float64 `json:"temperature,omitempty"`
// Tokens are selected from the most to least probable until the sum
// of their probabilities equals this value. Use a lower value for less
// random responses and a higher value for more random responses.
TopP *float64 `json:"topP,omitempty"`
// For each token selection step, the ``top_k`` tokens with the
// highest probabilities are sampled. Then tokens are further filtered based
// on ``top_p`` with the final token selected using temperature sampling. Use
// a lower number for less random responses and a higher number for more
// random responses.
TopK *float64 `json:"topK,omitempty"`
// Number of response variations to return.
CandidateCount *int64 `json:"candidateCount,omitempty"`
// Maximum number of tokens that can be generated in the response.
MaxOutputTokens *int64 `json:"maxOutputTokens,omitempty"`
// List of strings that tells the model to stop generating text if one
// of the strings is encountered in the response.
StopSequences []string `json:"stopSequences,omitempty"`
// Whether to return the log probabilities of the tokens that were
// chosen by the model at each step.
ResponseLogprobs bool `json:"responseLogprobs,omitempty"`
// Number of top candidate tokens to return the log probabilities for
// at each generation step.
Logprobs *int64 `json:"logprobs,omitempty"`
// Positive values penalize tokens that already appear in the
// generated text, increasing the probability of generating more diverse
// content.
PresencePenalty *float64 `json:"presencePenalty,omitempty"`
// Positive values penalize tokens that repeatedly appear in the
// generated text, increasing the probability of generating more diverse
// content.
FrequencyPenalty *float64 `json:"frequencyPenalty,omitempty"`
// When ``seed`` is fixed to a specific number, the model makes a best
// effort to provide the same response for repeated requests. By default, a
// random number is used.
Seed *int64 `json:"seed,omitempty"`
// Output response media type of the generated candidate text.
ResponseMIMEType string `json:"responseMimeType,omitempty"`
// Schema that the generated candidate text must adhere to.
ResponseSchema *Schema `json:"responseSchema,omitempty"`
// Configuration for model router requests.
RoutingConfig *GenerationConfigRoutingConfig `json:"routingConfig,omitempty"`
// Safety settings in the request to block unsafe content in the
// response.
SafetySettings []*SafetySetting `json:"safetySettings,omitempty"`
// Code that enables the system to interact with external systems to
// perform an action outside of the knowledge and scope of the model.
Tools []*Tool `json:"tools,omitempty"`
// Associates model output to a specific function call.
ToolConfig *ToolConfig `json:"toolConfig,omitempty"`
// Labels with user-defined metadata to break down billed charges.
Labels map[string]string `json:"labels,omitempty"`
// Resource name of a context cache that can be used in subsequent
// requests.
CachedContent string `json:"cachedContent,omitempty"`
// The requested modalities of the response. Represents the set of
// modalities that the model can return.
ResponseModalities []string `json:"responseModalities,omitempty"`
// If specified, the media resolution specified will be used.
MediaResolution MediaResolution `json:"mediaResolution,omitempty"`
// The speech generation configuration.
SpeechConfig *SpeechConfig `json:"speechConfig,omitempty"`
// If enabled, audio timestamp will be included in the request to the
// model.
AudioTimestamp bool `json:"audioTimestamp,omitempty"`
// The thinking features configuration.
ThinkingConfig *ThinkingConfig `json:"thinkingConfig,omitempty"`
}
// Config for models.generate_content parameters.
type GenerateContentParameters struct {
// ID of the model to use. For a list of models, see `Google models
// <https://cloud.google.com/vertex-ai/generative-ai/docs/learn/models>`_.
Model string `json:"model,omitempty"`
// Content of the request.
Contents []*Content `json:"contents,omitempty"`
// Configuration that contains optional model parameters.
Config *GenerateContentConfig `json:"config,omitempty"`