Debian Codegraph @

vertexai/genai/aiplatformpb_veneer.gen.go

raw symbols SCIP
1 // Copyright 2025 Google LLC
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 // This file was generated by protoveneer. DO NOT EDIT.
16
17 package genai
18
19 import (
20 "fmt"
21 "time"
22
23 pb "cloud.google.com/go/aiplatform/apiv1beta1/aiplatformpb"
24 "cloud.google.com/go/civil"
25 "google.golang.org/genproto/googleapis/type/date"
26 "google.golang.org/protobuf/types/known/structpb"
27 "google.golang.org/protobuf/types/known/timestamppb"
28 )
29
30 // Blob contains binary data like images. Use [Text] for text.
31 type Blob struct {
32 // Required. The IANA standard MIME type of the source data.
33 MIMEType string
34 // Required. Raw bytes.
35 Data []byte
36 }
37
38 func (v *Blob) toProto() *pb.Blob {
39 if v == nil {
40 return nil
41 }
42 return &pb.Blob{
43 MimeType: v.MIMEType,
44 Data: v.Data,
45 }
46 }
47
48 func (Blob) fromProto(p *pb.Blob) *Blob {
49 if p == nil {
50 return nil
51 }
52 return &Blob{
53 MIMEType: p.MimeType,
54 Data: p.Data,
55 }
56 }
57
58 // BlockedReason is blocked reason enumeration.
59 type BlockedReason int32
60
61 const (
62 // BlockedReasonUnspecified means unspecified blocked reason.
63 BlockedReasonUnspecified BlockedReason = 0
64 // BlockedReasonSafety means candidates blocked due to safety.
65 BlockedReasonSafety BlockedReason = 1
66 // BlockedReasonOther means candidates blocked due to other reason.
67 BlockedReasonOther BlockedReason = 2
68 // BlockedReasonBlocklist means candidates blocked due to the terms which are included from the
69 // terminology blocklist.
70 BlockedReasonBlocklist BlockedReason = 3
71 // BlockedReasonProhibitedContent means candidates blocked due to prohibited content.
72 BlockedReasonProhibitedContent BlockedReason = 4
73 )
74
75 var namesForBlockedReason = map[BlockedReason]string{
76 BlockedReasonUnspecified: "BlockedReasonUnspecified",
77 BlockedReasonSafety: "BlockedReasonSafety",
78 BlockedReasonOther: "BlockedReasonOther",
79 BlockedReasonBlocklist: "BlockedReasonBlocklist",
80 BlockedReasonProhibitedContent: "BlockedReasonProhibitedContent",
81 }
82
83 func (v BlockedReason) String() string {
84 if n, ok := namesForBlockedReason[v]; ok {
85 return n
86 }
87 return fmt.Sprintf("BlockedReason(%d)", v)
88 }
89
90 // CachedContent is a resource used in LLM queries for users to explicitly specify what to cache
91 // and how to cache.
92 type CachedContent struct {
93 // Expiration time of the cached content.
94 //
95 // Types that are assignable to Expiration:
96 //
97 // *CachedContent_ExpireTime
98 // *CachedContent_Ttl
99 Expiration ExpireTimeOrTTL
100 // Immutable. Identifier. The server-generated resource name of the cached
101 // content Format:
102 // projects/{project}/locations/{location}/cachedContents/{cached_content}
103 Name string
104 // Immutable. The name of the `Model` to use for cached content. Currently,
105 // only the published Gemini base models are supported, in form of
106 // projects/{PROJECT}/locations/{LOCATION}/publishers/google/models/{MODEL}
107 Model string
108 // Optional. Input only. Immutable. Developer set system instruction.
109 // Currently, text only
110 SystemInstruction *Content
111 // Optional. Input only. Immutable. The content to cache
112 Contents []*Content
113 // Optional. Input only. Immutable. A list of `Tools` the model may use to
114 // generate the next response
115 Tools []*Tool
116 // Optional. Input only. Immutable. Tool config. This config is shared for all
117 // tools
118 ToolConfig *ToolConfig
119 // Output only. Creation time of the cache entry.
120 CreateTime time.Time
121 // Output only. When the cache entry was last updated in UTC time.
122 UpdateTime time.Time
123 }
124
125 func (v *CachedContent) toProto() *pb.CachedContent {
126 if v == nil {
127 return nil
128 }
129 p := &pb.CachedContent{
130 Name: v.Name,
131 Model: v.Model,
132 SystemInstruction: v.SystemInstruction.toProto(),
133 Contents: pvTransformSlice(v.Contents, (*Content).toProto),
134 Tools: pvTransformSlice(v.Tools, (*Tool).toProto),
135 ToolConfig: v.ToolConfig.toProto(),
136 CreateTime: pvTimeToProto(v.CreateTime),
137 UpdateTime: pvTimeToProto(v.UpdateTime),
138 }
139 populateCachedContentTo(p, v)
140 return p
141 }
142
143 func (CachedContent) fromProto(p *pb.CachedContent) *CachedContent {
144 if p == nil {
145 return nil
146 }
147 v := &CachedContent{
148 Name: p.Name,
149 Model: p.Model,
150 SystemInstruction: (Content{}).fromProto(p.SystemInstruction),
151 Contents: pvTransformSlice(p.Contents, (Content{}).fromProto),
152 Tools: pvTransformSlice(p.Tools, (Tool{}).fromProto),
153 ToolConfig: (ToolConfig{}).fromProto(p.ToolConfig),
154 CreateTime: pvTimeFromProto(p.CreateTime),
155 UpdateTime: pvTimeFromProto(p.UpdateTime),
156 }
157 populateCachedContentFrom(v, p)
158 return v
159 }
160
161 // Candidate is a response candidate generated from the model.
162 type Candidate struct {
163 // Output only. Index of the candidate.
164 Index int32
165 // Output only. Content parts of the candidate.
166 Content *Content
167 // Output only. The reason why the model stopped generating tokens.
168 // If empty, the model has not stopped generating the tokens.
169 FinishReason FinishReason
170 // Output only. List of ratings for the safety of a response candidate.
171 //
172 // There is at most one rating per category.
173 SafetyRatings []*SafetyRating
174 // Output only. Describes the reason the mode stopped generating tokens in
175 // more detail. This is only filled when `finish_reason` is set.
176 FinishMessage string
177 // Output only. Source attribution of the generated content.
178 CitationMetadata *CitationMetadata
179 }
180
181 func (v *Candidate) toProto() *pb.Candidate {
182 if v == nil {
183 return nil
184 }
185 return &pb.Candidate{
186 Index: v.Index,
187 Content: v.Content.toProto(),
188 FinishReason: pb.Candidate_FinishReason(v.FinishReason),
189 SafetyRatings: pvTransformSlice(v.SafetyRatings, (*SafetyRating).toProto),
190 FinishMessage: pvAddrOrNil(v.FinishMessage),
191 CitationMetadata: v.CitationMetadata.toProto(),
192 }
193 }
194
195 func (Candidate) fromProto(p *pb.Candidate) *Candidate {
196 if p == nil {
197 return nil
198 }
199 return &Candidate{
200 Index: p.Index,
201 Content: (Content{}).fromProto(p.Content),
202 FinishReason: FinishReason(p.FinishReason),
203 SafetyRatings: pvTransformSlice(p.SafetyRatings, (SafetyRating{}).fromProto),
204 FinishMessage: pvDerefOrZero(p.FinishMessage),
205 CitationMetadata: (CitationMetadata{}).fromProto(p.CitationMetadata),
206 }
207 }
208
209 // Citation contains source attributions for content.
210 type Citation struct {
211 // Output only. Start index into the content.
212 StartIndex int32
213 // Output only. End index into the content.
214 EndIndex int32
215 // Output only. Url reference of the attribution.
216 URI string
217 // Output only. Title of the attribution.
218 Title string
219 // Output only. License of the attribution.
220 License string
221 // Output only. Publication date of the attribution.
222 PublicationDate civil.Date
223 }
224
225 func (v *Citation) toProto() *pb.Citation {
226 if v == nil {
227 return nil
228 }
229 return &pb.Citation{
230 StartIndex: v.StartIndex,
231 EndIndex: v.EndIndex,
232 Uri: v.URI,
233 Title: v.Title,
234 License: v.License,
235 PublicationDate: pvCivilDateToProto(v.PublicationDate),
236 }
237 }
238
239 func (Citation) fromProto(p *pb.Citation) *Citation {
240 if p == nil {
241 return nil
242 }
243 return &Citation{
244 StartIndex: p.StartIndex,
245 EndIndex: p.EndIndex,
246 URI: p.Uri,
247 Title: p.Title,
248 License: p.License,
249 PublicationDate: pvCivilDateFromProto(p.PublicationDate),
250 }
251 }
252
253 // CitationMetadata is a collection of source attributions for a piece of content.
254 type CitationMetadata struct {
255 // Output only. List of citations.
256 Citations []*Citation
257 }
258
259 func (v *CitationMetadata) toProto() *pb.CitationMetadata {
260 if v == nil {
261 return nil
262 }
263 return &pb.CitationMetadata{
264 Citations: pvTransformSlice(v.Citations, (*Citation).toProto),
265 }
266 }
267
268 func (CitationMetadata) fromProto(p *pb.CitationMetadata) *CitationMetadata {
269 if p == nil {
270 return nil
271 }
272 return &CitationMetadata{
273 Citations: pvTransformSlice(p.Citations, (Citation{}).fromProto),
274 }
275 }
276
277 // Content is the base structured datatype containing multi-part content of a message.
278 //
279 // A `Content` includes a `role` field designating the producer of the `Content`
280 // and a `parts` field containing multi-part data that contains the content of
281 // the message turn.
282 type Content struct {
283 // Optional. The producer of the content. Must be either 'user' or 'model'.
284 //
285 // Useful to set for multi-turn conversations, otherwise can be left blank
286 // or unset.
287 Role string
288 // Required. Ordered `Parts` that constitute a single message. Parts may have
289 // different IANA MIME types.
290 Parts []Part
291 }
292
293 func (v *Content) toProto() *pb.Content {
294 if v == nil {
295 return nil
296 }
297 return &pb.Content{
298 Role: v.Role,
299 Parts: pvTransformSlice(v.Parts, partToProto),
300 }
301 }
302
303 func (Content) fromProto(p *pb.Content) *Content {
304 if p == nil {
305 return nil
306 }
307 return &Content{
308 Role: p.Role,
309 Parts: pvTransformSlice(p.Parts, partFromProto),
310 }
311 }
312
313 // CountTokensResponse is response message for
314 // [PredictionService.CountTokens][google.cloud.aiplatform.v1beta1.PredictionService.CountTokens].
315 type CountTokensResponse struct {
316 // The total number of tokens counted across all instances from the request.
317 TotalTokens int32
318 // The total number of billable characters counted across all instances from
319 // the request.
320 TotalBillableCharacters int32
321 }
322
323 func (v *CountTokensResponse) toProto() *pb.CountTokensResponse {
324 if v == nil {
325 return nil
326 }
327 return &pb.CountTokensResponse{
328 TotalTokens: v.TotalTokens,
329 TotalBillableCharacters: v.TotalBillableCharacters,
330 }
331 }
332
333 func (CountTokensResponse) fromProto(p *pb.CountTokensResponse) *CountTokensResponse {
334 if p == nil {
335 return nil
336 }
337 return &CountTokensResponse{
338 TotalTokens: p.TotalTokens,
339 TotalBillableCharacters: p.TotalBillableCharacters,
340 }
341 }
342
343 // FileData is URI based data.
344 type FileData struct {
345 // Required. The IANA standard MIME type of the source data.
346 MIMEType string
347 // Required. URI.
348 FileURI string
349 }
350
351 func (v *FileData) toProto() *pb.FileData {
352 if v == nil {
353 return nil
354 }
355 return &pb.FileData{
356 MimeType: v.MIMEType,
357 FileUri: v.FileURI,
358 }
359 }
360
361 func (FileData) fromProto(p *pb.FileData) *FileData {
362 if p == nil {
363 return nil
364 }
365 return &FileData{
366 MIMEType: p.MimeType,
367 FileURI: p.FileUri,
368 }
369 }
370
371 // FinishReason is the reason why the model stopped generating tokens.
372 // If empty, the model has not stopped generating the tokens.
373 type FinishReason int32
374
375 const (
376 // FinishReasonUnspecified means the finish reason is unspecified.
377 FinishReasonUnspecified FinishReason = 0
378 // FinishReasonStop means token generation reached a natural stopping point or a configured stop
379 // sequence.
380 FinishReasonStop FinishReason = 1
381 // FinishReasonMaxTokens means token generation reached the configured maximum output tokens.
382 FinishReasonMaxTokens FinishReason = 2
383 // FinishReasonSafety means token generation stopped because the content potentially contains safety
384 // violations. NOTE: When streaming,
385 // [content][google.cloud.aiplatform.v1beta1.Candidate.content] is empty if
386 // content filters blocks the output.
387 FinishReasonSafety FinishReason = 3
388 // FinishReasonRecitation means token generation stopped because the content potentially contains
389 // copyright violations.
390 FinishReasonRecitation FinishReason = 4
391 // FinishReasonOther means all other reasons that stopped the token generation.
392 FinishReasonOther FinishReason = 5
393 // FinishReasonBlocklist means token generation stopped because the content contains forbidden terms.
394 FinishReasonBlocklist FinishReason = 6
395 // FinishReasonProhibitedContent means token generation stopped for potentially containing prohibited content.
396 FinishReasonProhibitedContent FinishReason = 7
397 // FinishReasonSpii means token generation stopped because the content potentially contains
398 // Sensitive Personally Identifiable Information (SPII).
399 FinishReasonSpii FinishReason = 8
400 // FinishReasonMalformedFunctionCall means the function call generated by the model is invalid.
401 FinishReasonMalformedFunctionCall FinishReason = 9
402 )
403
404 var namesForFinishReason = map[FinishReason]string{
405 FinishReasonUnspecified: "FinishReasonUnspecified",
406 FinishReasonStop: "FinishReasonStop",
407 FinishReasonMaxTokens: "FinishReasonMaxTokens",
408 FinishReasonSafety: "FinishReasonSafety",
409 FinishReasonRecitation: "FinishReasonRecitation",
410 FinishReasonOther: "FinishReasonOther",
411 FinishReasonBlocklist: "FinishReasonBlocklist",
412 FinishReasonProhibitedContent: "FinishReasonProhibitedContent",
413 FinishReasonSpii: "FinishReasonSpii",
414 FinishReasonMalformedFunctionCall: "FinishReasonMalformedFunctionCall",
415 }
416
417 func (v FinishReason) String() string {
418 if n, ok := namesForFinishReason[v]; ok {
419 return n
420 }
421 return fmt.Sprintf("FinishReason(%d)", v)
422 }
423
424 // FunctionCall is a predicted [FunctionCall] returned from the model that contains a string
425 // representing the [FunctionDeclaration.name] and a structured JSON object
426 // containing the parameters and their values.
427 type FunctionCall struct {
428 // Required. The name of the function to call.
429 // Matches [FunctionDeclaration.name].
430 Name string
431 // Optional. Required. The function parameters and values in JSON object
432 // format. See [FunctionDeclaration.parameters] for parameter details.
433 Args map[string]any
434 }
435
436 func (v *FunctionCall) toProto() *pb.FunctionCall {
437 if v == nil {
438 return nil
439 }
440 return &pb.FunctionCall{
441 Name: v.Name,
442 Args: pvMapToStructPB(v.Args),
443 }
444 }
445
446 func (FunctionCall) fromProto(p *pb.FunctionCall) *FunctionCall {
447 if p == nil {
448 return nil
449 }
450 return &FunctionCall{
451 Name: p.Name,
452 Args: pvMapFromStructPB(p.Args),
453 }
454 }
455
456 // FunctionCallingConfig holds configuration for function calling.
457 type FunctionCallingConfig struct {
458 // Optional. Function calling mode.
459 Mode FunctionCallingMode
460 // Optional. Function names to call. Only set when the Mode is ANY. Function
461 // names should match [FunctionDeclaration.name]. With mode set to ANY, model
462 // will predict a function call from the set of function names provided.
463 AllowedFunctionNames []string
464 }
465
466 func (v *FunctionCallingConfig) toProto() *pb.FunctionCallingConfig {
467 if v == nil {
468 return nil
469 }
470 return &pb.FunctionCallingConfig{
471 Mode: pb.FunctionCallingConfig_Mode(v.Mode),
472 AllowedFunctionNames: v.AllowedFunctionNames,
473 }
474 }
475
476 func (FunctionCallingConfig) fromProto(p *pb.FunctionCallingConfig) *FunctionCallingConfig {
477 if p == nil {
478 return nil
479 }
480 return &FunctionCallingConfig{
481 Mode: FunctionCallingMode(p.Mode),
482 AllowedFunctionNames: p.AllowedFunctionNames,
483 }
484 }
485
486 // FunctionCallingMode is function calling mode.
487 type FunctionCallingMode int32
488
489 const (
490 // FunctionCallingUnspecified means unspecified function calling mode. This value should not be used.
491 FunctionCallingUnspecified FunctionCallingMode = 0
492 // FunctionCallingAuto means default model behavior, model decides to predict either function calls
493 // or natural language response.
494 FunctionCallingAuto FunctionCallingMode = 1
495 // FunctionCallingAny means model is constrained to always predicting function calls only.
496 // If "allowed_function_names" are set, the predicted function calls will be
497 // limited to any one of "allowed_function_names", else the predicted
498 // function calls will be any one of the provided "function_declarations".
499 FunctionCallingAny FunctionCallingMode = 2
500 // FunctionCallingNone means model will not predict any function calls. Model behavior is same as when
501 // not passing any function declarations.
502 FunctionCallingNone FunctionCallingMode = 3
503 )
504
505 var namesForFunctionCallingMode = map[FunctionCallingMode]string{
506 FunctionCallingUnspecified: "FunctionCallingUnspecified",
507 FunctionCallingAuto: "FunctionCallingAuto",
508 FunctionCallingAny: "FunctionCallingAny",
509 FunctionCallingNone: "FunctionCallingNone",
510 }
511
512 func (v FunctionCallingMode) String() string {
513 if n, ok := namesForFunctionCallingMode[v]; ok {
514 return n
515 }
516 return fmt.Sprintf("FunctionCallingMode(%d)", v)
517 }
518
519 // FunctionDeclaration is structured representation of a function declaration as defined by the
520 // [OpenAPI 3.0 specification](https://spec.openapis.org/oas/v3.0.3). Included
521 // in this declaration are the function name, description, parameters and
522 // response type. This FunctionDeclaration is a representation of a block of
523 // code that can be used as a `Tool` by the model and executed by the client.
524 type FunctionDeclaration struct {
525 // Required. The name of the function to call.
526 // Must start with a letter or an underscore.
527 // Must be a-z, A-Z, 0-9, or contain underscores, dots and dashes, with a
528 // maximum length of 64.
529 Name string
530 // Optional. Description and purpose of the function.
531 // Model uses it to decide how and whether to call the function.
532 Description string
533 // Optional. Describes the parameters to this function in JSON Schema Object
534 // format. Reflects the Open API 3.03 Parameter Object. string Key: the name
535 // of the parameter. Parameter names are case sensitive. Schema Value: the
536 // Schema defining the type used for the parameter. For function with no
537 // parameters, this can be left unset. Parameter names must start with a
538 // letter or an underscore and must only contain chars a-z, A-Z, 0-9, or
539 // underscores with a maximum length of 64. Example with 1 required and 1
540 // optional parameter: type: OBJECT properties:
541 //
542 // param1:
543 // type: STRING
544 // param2:
545 // type: INTEGER
546 //
547 // required:
548 // - param1
549 Parameters *Schema
550 // Optional. Describes the output from this function in JSON Schema format.
551 // Reflects the Open API 3.03 Response Object. The Schema defines the type
552 // used for the response value of the function.
553 Response *Schema
554 }
555
556 func (v *FunctionDeclaration) toProto() *pb.FunctionDeclaration {
557 if v == nil {
558 return nil
559 }
560 return &pb.FunctionDeclaration{
561 Name: v.Name,
562 Description: v.Description,
563 Parameters: v.Parameters.toProto(),
564 Response: v.Response.toProto(),
565 }
566 }
567
568 func (FunctionDeclaration) fromProto(p *pb.FunctionDeclaration) *FunctionDeclaration {
569 if p == nil {
570 return nil
571 }
572 return &FunctionDeclaration{
573 Name: p.Name,
574 Description: p.Description,
575 Parameters: (Schema{}).fromProto(p.Parameters),
576 Response: (Schema{}).fromProto(p.Response),
577 }
578 }
579
580 // FunctionResponse is the result output from a [FunctionCall] that contains a string representing
581 // the [FunctionDeclaration.name] and a structured JSON object containing any
582 // output from the function is used as context to the model. This should contain
583 // the result of a [FunctionCall] made based on model prediction.
584 type FunctionResponse struct {
585 // Required. The name of the function to call.
586 // Matches [FunctionDeclaration.name] and [FunctionCall.name].
587 Name string
588 // Required. The function response in JSON object format.
589 // Use "output" key to specify function output and "error" key to specify
590 // error details (if any). If "output" and "error" keys are not specified,
591 // then whole "response" is treated as function output.
592 Response map[string]any
593 }
594
595 func (v *FunctionResponse) toProto() *pb.FunctionResponse {
596 if v == nil {
597 return nil
598 }
599 return &pb.FunctionResponse{
600 Name: v.Name,
601 Response: pvMapToStructPB(v.Response),
602 }
603 }
604
605 func (FunctionResponse) fromProto(p *pb.FunctionResponse) *FunctionResponse {
606 if p == nil {
607 return nil
608 }
609 return &FunctionResponse{
610 Name: p.Name,
611 Response: pvMapFromStructPB(p.Response),
612 }
613 }
614
615 // GenerateContentResponse is the response from a GenerateContent or GenerateContentStream call.
616 type GenerateContentResponse struct {
617 // Output only. Generated candidates.
618 Candidates []*Candidate
619 // Output only. Content filter results for a prompt sent in the request.
620 // Note: Sent only in the first stream chunk.
621 // Only happens when no candidates were generated due to content violations.
622 PromptFeedback *PromptFeedback
623 // Usage metadata about the response(s).
624 UsageMetadata *UsageMetadata
625 }
626
627 func (v *GenerateContentResponse) toProto() *pb.GenerateContentResponse {
628 if v == nil {
629 return nil
630 }
631 return &pb.GenerateContentResponse{
632 Candidates: pvTransformSlice(v.Candidates, (*Candidate).toProto),
633 PromptFeedback: v.PromptFeedback.toProto(),
634 UsageMetadata: v.UsageMetadata.toProto(),
635 }
636 }
637
638 func (GenerateContentResponse) fromProto(p *pb.GenerateContentResponse) *GenerateContentResponse {
639 if p == nil {
640 return nil
641 }
642 return &GenerateContentResponse{
643 Candidates: pvTransformSlice(p.Candidates, (Candidate{}).fromProto),
644 PromptFeedback: (PromptFeedback{}).fromProto(p.PromptFeedback),
645 UsageMetadata: (UsageMetadata{}).fromProto(p.UsageMetadata),
646 }
647 }
648
649 // GenerationConfig is generation config.
650 type GenerationConfig struct {
651 // Optional. Controls the randomness of predictions.
652 Temperature *float32
653 // Optional. If specified, nucleus sampling will be used.
654 TopP *float32
655 // Optional. If specified, top-k sampling will be used.
656 TopK *int32
657 // Optional. Number of candidates to generate.
658 CandidateCount *int32
659 // Optional. The maximum number of output tokens to generate per message.
660 MaxOutputTokens *int32
661 // Optional. Stop sequences.
662 StopSequences []string
663 // Optional. Positive penalties.
664 PresencePenalty *float32
665 // Optional. Frequency penalties.
666 FrequencyPenalty *float32
667 // Optional. Output response mimetype of the generated candidate text.
668 // Supported mimetype:
669 // - `text/plain`: (default) Text output.
670 // - `application/json`: JSON response in the candidates.
671 // The model needs to be prompted to output the appropriate response type,
672 // otherwise the behavior is undefined.
673 // This is a preview feature.
674 ResponseMIMEType string
675 // Optional. The `Schema` object allows the definition of input and output
676 // data types. These types can be objects, but also primitives and arrays.
677 // Represents a select subset of an [OpenAPI 3.0 schema
678 // object](https://spec.openapis.org/oas/v3.0.3#schema).
679 // If set, a compatible response_mime_type must also be set.
680 // Compatible mimetypes:
681 // `application/json`: Schema for JSON response.
682 ResponseSchema *Schema
683 // Optional. Config for thinking features.
684 // An error will be returned if this field is set for models that don't
685 // support thinking.
686 ThinkingConfig *ThinkingConfig
687 }
688
689 func (v *GenerationConfig) toProto() *pb.GenerationConfig {
690 if v == nil {
691 return nil
692 }
693 return &pb.GenerationConfig{
694 Temperature: v.Temperature,
695 TopP: v.TopP,
696 TopK: int32pToFloat32p(v.TopK),
697 CandidateCount: v.CandidateCount,
698 MaxOutputTokens: v.MaxOutputTokens,
699 StopSequences: v.StopSequences,
700 PresencePenalty: v.PresencePenalty,
701 FrequencyPenalty: v.FrequencyPenalty,
702 ResponseMimeType: v.ResponseMIMEType,
703 ResponseSchema: v.ResponseSchema.toProto(),
704 ThinkingConfig: v.ThinkingConfig.toProto(),
705 }
706 }
707
708 func (GenerationConfig) fromProto(p *pb.GenerationConfig) *GenerationConfig {
709 if p == nil {
710 return nil
711 }
712 return &GenerationConfig{
713 Temperature: p.Temperature,
714 TopP: p.TopP,
715 TopK: float32pToInt32p(p.TopK),
716 CandidateCount: p.CandidateCount,
717 MaxOutputTokens: p.MaxOutputTokens,
718 StopSequences: p.StopSequences,
719 PresencePenalty: p.PresencePenalty,
720 FrequencyPenalty: p.FrequencyPenalty,
721 ResponseMIMEType: p.ResponseMimeType,
722 ResponseSchema: (Schema{}).fromProto(p.ResponseSchema),
723 ThinkingConfig: (ThinkingConfig{}).fromProto(p.ThinkingConfig),
724 }
725 }
726
727 // HarmBlockMethod determines how harm blocking is done.
728 type HarmBlockMethod int32
729
730 const (
731 // HarmBlockMethodUnspecified means the harm block method is unspecified.
732 HarmBlockMethodUnspecified HarmBlockMethod = 0
733 // HarmBlockMethodSeverity means the harm block method uses both probability and severity scores.
734 HarmBlockMethodSeverity HarmBlockMethod = 1
735 // HarmBlockMethodProbability means the harm block method uses the probability score.
736 HarmBlockMethodProbability HarmBlockMethod = 2
737 )
738
739 var namesForHarmBlockMethod = map[HarmBlockMethod]string{
740 HarmBlockMethodUnspecified: "HarmBlockMethodUnspecified",
741 HarmBlockMethodSeverity: "HarmBlockMethodSeverity",
742 HarmBlockMethodProbability: "HarmBlockMethodProbability",
743 }
744
745 func (v HarmBlockMethod) String() string {
746 if n, ok := namesForHarmBlockMethod[v]; ok {
747 return n
748 }
749 return fmt.Sprintf("HarmBlockMethod(%d)", v)
750 }
751
752 // HarmBlockThreshold specifies probability based thresholds levels for blocking.
753 type HarmBlockThreshold int32
754
755 const (
756 // HarmBlockUnspecified means unspecified harm block threshold.
757 HarmBlockUnspecified HarmBlockThreshold = 0
758 // HarmBlockLowAndAbove means block low threshold and above (i.e. block more).
759 HarmBlockLowAndAbove HarmBlockThreshold = 1
760 // HarmBlockMediumAndAbove means block medium threshold and above.
761 HarmBlockMediumAndAbove HarmBlockThreshold = 2
762 // HarmBlockOnlyHigh means block only high threshold (i.e. block less).
763 HarmBlockOnlyHigh HarmBlockThreshold = 3
764 // HarmBlockNone means block none.
765 HarmBlockNone HarmBlockThreshold = 4
766 // HarmBlockSafetysettingOff means turn off the safety filter.
767 HarmBlockSafetysettingOff HarmBlockThreshold = 5
768 )
769
770 var namesForHarmBlockThreshold = map[HarmBlockThreshold]string{
771 HarmBlockUnspecified: "HarmBlockUnspecified",
772 HarmBlockLowAndAbove: "HarmBlockLowAndAbove",
773 HarmBlockMediumAndAbove: "HarmBlockMediumAndAbove",
774 HarmBlockOnlyHigh: "HarmBlockOnlyHigh",
775 HarmBlockNone: "HarmBlockNone",
776 HarmBlockSafetysettingOff: "HarmBlockSafetysettingOff",
777 }
778
779 func (v HarmBlockThreshold) String() string {
780 if n, ok := namesForHarmBlockThreshold[v]; ok {
781 return n
782 }
783 return fmt.Sprintf("HarmBlockThreshold(%d)", v)
784 }
785
786 // HarmCategory specifies harm categories that will block the content.
787 type HarmCategory int32
788
789 const (
790 // HarmCategoryUnspecified means the harm category is unspecified.
791 HarmCategoryUnspecified HarmCategory = 0
792 // HarmCategoryHateSpeech means the harm category is hate speech.
793 HarmCategoryHateSpeech HarmCategory = 1
794 // HarmCategoryDangerousContent means the harm category is dangerous content.
795 HarmCategoryDangerousContent HarmCategory = 2
796 // HarmCategoryHarassment means the harm category is harassment.
797 HarmCategoryHarassment HarmCategory = 3
798 // HarmCategorySexuallyExplicit means the harm category is sexually explicit content.
799 HarmCategorySexuallyExplicit HarmCategory = 4
800 // HarmCategoryCivicIntegrity means deprecated: Election filter is not longer supported.
801 // The harm category is civic integrity.
802 //
803 // Deprecated: Marked as deprecated in google/cloud/aiplatform/v1beta1/content.proto.
804 HarmCategoryCivicIntegrity HarmCategory = 5
805 )
806
807 var namesForHarmCategory = map[HarmCategory]string{
808 HarmCategoryUnspecified: "HarmCategoryUnspecified",
809 HarmCategoryHateSpeech: "HarmCategoryHateSpeech",
810 HarmCategoryDangerousContent: "HarmCategoryDangerousContent",
811 HarmCategoryHarassment: "HarmCategoryHarassment",
812 HarmCategorySexuallyExplicit: "HarmCategorySexuallyExplicit",
813 HarmCategoryCivicIntegrity: "HarmCategoryCivicIntegrity",
814 }
815
816 func (v HarmCategory) String() string {
817 if n, ok := namesForHarmCategory[v]; ok {
818 return n
819 }
820 return fmt.Sprintf("HarmCategory(%d)", v)
821 }
822
823 // HarmProbability specifies harm probability levels in the content.
824 type HarmProbability int32
825
826 const (
827 // HarmProbabilityUnspecified means harm probability unspecified.
828 HarmProbabilityUnspecified HarmProbability = 0
829 // HarmProbabilityNegligible means negligible level of harm.
830 HarmProbabilityNegligible HarmProbability = 1
831 // HarmProbabilityLow means low level of harm.
832 HarmProbabilityLow HarmProbability = 2
833 // HarmProbabilityMedium means medium level of harm.
834 HarmProbabilityMedium HarmProbability = 3
835 // HarmProbabilityHigh means high level of harm.
836 HarmProbabilityHigh HarmProbability = 4
837 )
838
839 var namesForHarmProbability = map[HarmProbability]string{
840 HarmProbabilityUnspecified: "HarmProbabilityUnspecified",
841 HarmProbabilityNegligible: "HarmProbabilityNegligible",
842 HarmProbabilityLow: "HarmProbabilityLow",
843 HarmProbabilityMedium: "HarmProbabilityMedium",
844 HarmProbabilityHigh: "HarmProbabilityHigh",
845 }
846
847 func (v HarmProbability) String() string {
848 if n, ok := namesForHarmProbability[v]; ok {
849 return n
850 }
851 return fmt.Sprintf("HarmProbability(%d)", v)
852 }
853
854 // HarmSeverity specifies harm severity levels.
855 type HarmSeverity int32
856
857 const (
858 // HarmSeverityUnspecified means harm severity unspecified.
859 HarmSeverityUnspecified HarmSeverity = 0
860 // HarmSeverityNegligible means negligible level of harm severity.
861 HarmSeverityNegligible HarmSeverity = 1
862 // HarmSeverityLow means low level of harm severity.
863 HarmSeverityLow HarmSeverity = 2
864 // HarmSeverityMedium means medium level of harm severity.
865 HarmSeverityMedium HarmSeverity = 3
866 // HarmSeverityHigh means high level of harm severity.
867 HarmSeverityHigh HarmSeverity = 4
868 )
869
870 var namesForHarmSeverity = map[HarmSeverity]string{
871 HarmSeverityUnspecified: "HarmSeverityUnspecified",
872 HarmSeverityNegligible: "HarmSeverityNegligible",
873 HarmSeverityLow: "HarmSeverityLow",
874 HarmSeverityMedium: "HarmSeverityMedium",
875 HarmSeverityHigh: "HarmSeverityHigh",
876 }
877
878 func (v HarmSeverity) String() string {
879 if n, ok := namesForHarmSeverity[v]; ok {
880 return n
881 }
882 return fmt.Sprintf("HarmSeverity(%d)", v)
883 }
884
885 // PromptFeedback contains content filter results for a prompt sent in the request.
886 type PromptFeedback struct {
887 // Output only. Blocked reason.
888 BlockReason BlockedReason
889 // Output only. Safety ratings.
890 SafetyRatings []*SafetyRating
891 // Output only. A readable block reason message.
892 BlockReasonMessage string
893 }
894
895 func (v *PromptFeedback) toProto() *pb.GenerateContentResponse_PromptFeedback {
896 if v == nil {
897 return nil
898 }
899 return &pb.GenerateContentResponse_PromptFeedback{
900 BlockReason: pb.GenerateContentResponse_PromptFeedback_BlockedReason(v.BlockReason),
901 SafetyRatings: pvTransformSlice(v.SafetyRatings, (*SafetyRating).toProto),
902 BlockReasonMessage: v.BlockReasonMessage,
903 }
904 }
905
906 func (PromptFeedback) fromProto(p *pb.GenerateContentResponse_PromptFeedback) *PromptFeedback {
907 if p == nil {
908 return nil
909 }
910 return &PromptFeedback{
911 BlockReason: BlockedReason(p.BlockReason),
912 SafetyRatings: pvTransformSlice(p.SafetyRatings, (SafetyRating{}).fromProto),
913 BlockReasonMessage: p.BlockReasonMessage,
914 }
915 }
916
917 // SafetyRating is the safety rating corresponding to the generated content.
918 type SafetyRating struct {
919 // Output only. Harm category.
920 Category HarmCategory
921 // Output only. Harm probability levels in the content.
922 Probability HarmProbability
923 // Output only. Harm probability score.
924 ProbabilityScore float32
925 // Output only. Harm severity levels in the content.
926 Severity HarmSeverity
927 // Output only. Harm severity score.
928 SeverityScore float32
929 // Output only. Indicates whether the content was filtered out because of this
930 // rating.
931 Blocked bool
932 }
933
934 func (v *SafetyRating) toProto() *pb.SafetyRating {
935 if v == nil {
936 return nil
937 }
938 return &pb.SafetyRating{
939 Category: pb.HarmCategory(v.Category),
940 Probability: pb.SafetyRating_HarmProbability(v.Probability),
941 ProbabilityScore: v.ProbabilityScore,
942 Severity: pb.SafetyRating_HarmSeverity(v.Severity),
943 SeverityScore: v.SeverityScore,
944 Blocked: v.Blocked,
945 }
946 }
947
948 func (SafetyRating) fromProto(p *pb.SafetyRating) *SafetyRating {
949 if p == nil {
950 return nil
951 }
952 return &SafetyRating{
953 Category: HarmCategory(p.Category),
954 Probability: HarmProbability(p.Probability),
955 ProbabilityScore: p.ProbabilityScore,
956 Severity: HarmSeverity(p.Severity),
957 SeverityScore: p.SeverityScore,
958 Blocked: p.Blocked,
959 }
960 }
961
962 // SafetySetting is safety settings.
963 type SafetySetting struct {
964 // Required. Harm category.
965 Category HarmCategory
966 // Required. The harm block threshold.
967 Threshold HarmBlockThreshold
968 // Optional. Specify if the threshold is used for probability or severity
969 // score. If not specified, the threshold is used for probability score.
970 Method HarmBlockMethod
971 }
972
973 func (v *SafetySetting) toProto() *pb.SafetySetting {
974 if v == nil {
975 return nil
976 }
977 return &pb.SafetySetting{
978 Category: pb.HarmCategory(v.Category),
979 Threshold: pb.SafetySetting_HarmBlockThreshold(v.Threshold),
980 Method: pb.SafetySetting_HarmBlockMethod(v.Method),
981 }
982 }
983
984 func (SafetySetting) fromProto(p *pb.SafetySetting) *SafetySetting {
985 if p == nil {
986 return nil
987 }
988 return &SafetySetting{
989 Category: HarmCategory(p.Category),
990 Threshold: HarmBlockThreshold(p.Threshold),
991 Method: HarmBlockMethod(p.Method),
992 }
993 }
994
995 // Schema is used to define the format of input/output data. Represents a select
996 // subset of an [OpenAPI 3.0 schema
997 // object](https://spec.openapis.org/oas/v3.0.3#schema-object). More fields may
998 // be added in the future as needed.
999 type Schema struct {
1000 // Optional. The type of the data.
1001 Type Type
1002 // Optional. The format of the data.
1003 // Supported formats:
1004 //
1005 // for NUMBER type: "float", "double"
1006 // for INTEGER type: "int32", "int64"
1007 // for STRING type: "email", "byte", etc
1008 Format string
1009 // Optional. The title of the Schema.
1010 Title string
1011 // Optional. The description of the data.
1012 Description string
1013 // Optional. Indicates if the value may be null.
1014 Nullable bool
1015 // Optional. SCHEMA FIELDS FOR TYPE ARRAY
1016 // Schema of the elements of Type.ARRAY.
1017 Items *Schema
1018 // Optional. Minimum number of the elements for Type.ARRAY.
1019 MinItems int64
1020 // Optional. Maximum number of the elements for Type.ARRAY.
1021 MaxItems int64
1022 // Optional. Possible values of the element of Type.STRING with enum format.
1023 // For example we can define an Enum Direction as :
1024 // {type:STRING, format:enum, enum:["EAST", NORTH", "SOUTH", "WEST"]}
1025 Enum []string
1026 // Optional. SCHEMA FIELDS FOR TYPE OBJECT
1027 // Properties of Type.OBJECT.
1028 Properties map[string]*Schema
1029 // Optional. Required properties of Type.OBJECT.
1030 Required []string
1031 // Optional. Minimum number of the properties for Type.OBJECT.
1032 MinProperties int64
1033 // Optional. Maximum number of the properties for Type.OBJECT.
1034 MaxProperties int64
1035 // Optional. SCHEMA FIELDS FOR TYPE INTEGER and NUMBER
1036 // Minimum value of the Type.INTEGER and Type.NUMBER
1037 Minimum float64
1038 // Optional. Maximum value of the Type.INTEGER and Type.NUMBER
1039 Maximum float64
1040 // Optional. SCHEMA FIELDS FOR TYPE STRING
1041 // Minimum length of the Type.STRING
1042 MinLength int64
1043 // Optional. Maximum length of the Type.STRING
1044 MaxLength int64
1045 // Optional. Pattern of the Type.STRING to restrict a string to a regular
1046 // expression.
1047 Pattern string
1048 }
1049
1050 func (v *Schema) toProto() *pb.Schema {
1051 if v == nil {
1052 return nil
1053 }
1054 return &pb.Schema{
1055 Type: pb.Type(v.Type),
1056 Format: v.Format,
1057 Title: v.Title,
1058 Description: v.Description,
1059 Nullable: v.Nullable,
1060 Items: v.Items.toProto(),
1061 MinItems: v.MinItems,
1062 MaxItems: v.MaxItems,
1063 Enum: v.Enum,
1064 Properties: pvTransformMapValues(v.Properties, (*Schema).toProto),
1065 Required: v.Required,
1066 MinProperties: v.MinProperties,
1067 MaxProperties: v.MaxProperties,
1068 Minimum: v.Minimum,
1069 Maximum: v.Maximum,
1070 MinLength: v.MinLength,
1071 MaxLength: v.MaxLength,
1072 Pattern: v.Pattern,
1073 }
1074 }
1075
1076 func (Schema) fromProto(p *pb.Schema) *Schema {
1077 if p == nil {
1078 return nil
1079 }
1080 return &Schema{
1081 Type: Type(p.Type),
1082 Format: p.Format,
1083 Title: p.Title,
1084 Description: p.Description,
1085 Nullable: p.Nullable,
1086 Items: (Schema{}).fromProto(p.Items),
1087 MinItems: p.MinItems,
1088 MaxItems: p.MaxItems,
1089 Enum: p.Enum,
1090 Properties: pvTransformMapValues(p.Properties, (Schema{}).fromProto),
1091 Required: p.Required,
1092 MinProperties: p.MinProperties,
1093 MaxProperties: p.MaxProperties,
1094 Minimum: p.Minimum,
1095 Maximum: p.Maximum,
1096 MinLength: p.MinLength,
1097 MaxLength: p.MaxLength,
1098 Pattern: p.Pattern,
1099 }
1100 }
1101
1102 // ThinkingConfig is config for thinking features.
1103 type ThinkingConfig struct {
1104 // Indicates whether to include thoughts in the response.
1105 // If true, thoughts are returned only when available.
1106 IncludeThoughts *bool
1107 // Optional. Indicates the thinking budget in tokens.
1108 // This is only applied when enable_thinking is true.
1109 ThinkingBudget *int32
1110 }
1111
1112 func (v *ThinkingConfig) toProto() *pb.GenerationConfig_ThinkingConfig {
1113 if v == nil {
1114 return nil
1115 }
1116 return &pb.GenerationConfig_ThinkingConfig{
1117 IncludeThoughts: v.IncludeThoughts,
1118 ThinkingBudget: v.ThinkingBudget,
1119 }
1120 }
1121
1122 func (ThinkingConfig) fromProto(p *pb.GenerationConfig_ThinkingConfig) *ThinkingConfig {
1123 if p == nil {
1124 return nil
1125 }
1126 return &ThinkingConfig{
1127 IncludeThoughts: p.IncludeThoughts,
1128 ThinkingBudget: p.ThinkingBudget,
1129 }
1130 }
1131
1132 // Tool details that the model may use to generate response.
1133 //
1134 // A `Tool` is a piece of code that enables the system to interact with
1135 // external systems to perform an action, or set of actions, outside of
1136 // knowledge and scope of the model. A Tool object should contain exactly
1137 // one type of Tool (e.g FunctionDeclaration, Retrieval or
1138 // GoogleSearchRetrieval).
1139 type Tool struct {
1140 // Optional. Function tool type.
1141 // One or more function declarations to be passed to the model along with the
1142 // current user query. Model may decide to call a subset of these functions
1143 // by populating
1144 // [FunctionCall][google.cloud.aiplatform.v1beta1.Part.function_call] in the
1145 // response. User should provide a
1146 // [FunctionResponse][google.cloud.aiplatform.v1beta1.Part.function_response]
1147 // for each function call in the next turn. Based on the function responses,
1148 // Model will generate the final response back to the user.
1149 // Maximum 128 function declarations can be provided.
1150 FunctionDeclarations []*FunctionDeclaration
1151 }
1152
1153 func (v *Tool) toProto() *pb.Tool {
1154 if v == nil {
1155 return nil
1156 }
1157 return &pb.Tool{
1158 FunctionDeclarations: pvTransformSlice(v.FunctionDeclarations, (*FunctionDeclaration).toProto),
1159 }
1160 }
1161
1162 func (Tool) fromProto(p *pb.Tool) *Tool {
1163 if p == nil {
1164 return nil
1165 }
1166 return &Tool{
1167 FunctionDeclarations: pvTransformSlice(p.FunctionDeclarations, (FunctionDeclaration{}).fromProto),
1168 }
1169 }
1170
1171 // ToolConfig configures tools.
1172 type ToolConfig struct {
1173 // Optional. Function calling config.
1174 FunctionCallingConfig *FunctionCallingConfig
1175 }
1176
1177 func (v *ToolConfig) toProto() *pb.ToolConfig {
1178 if v == nil {
1179 return nil
1180 }
1181 return &pb.ToolConfig{
1182 FunctionCallingConfig: v.FunctionCallingConfig.toProto(),
1183 }
1184 }
1185
1186 func (ToolConfig) fromProto(p *pb.ToolConfig) *ToolConfig {
1187 if p == nil {
1188 return nil
1189 }
1190 return &ToolConfig{
1191 FunctionCallingConfig: (FunctionCallingConfig{}).fromProto(p.FunctionCallingConfig),
1192 }
1193 }
1194
1195 // Type contains the list of OpenAPI data types as defined by
1196 // https://swagger.io/docs/specification/data-models/data-types/
1197 type Type int32
1198
1199 const (
1200 // TypeUnspecified means not specified, should not be used.
1201 TypeUnspecified Type = 0
1202 // TypeString means openAPI string type
1203 TypeString Type = 1
1204 // TypeNumber means openAPI number type
1205 TypeNumber Type = 2
1206 // TypeInteger means openAPI integer type
1207 TypeInteger Type = 3
1208 // TypeBoolean means openAPI boolean type
1209 TypeBoolean Type = 4
1210 // TypeArray means openAPI array type
1211 TypeArray Type = 5
1212 // TypeObject means openAPI object type
1213 TypeObject Type = 6
1214 )
1215
1216 var namesForType = map[Type]string{
1217 TypeUnspecified: "TypeUnspecified",
1218 TypeString: "TypeString",
1219 TypeNumber: "TypeNumber",
1220 TypeInteger: "TypeInteger",
1221 TypeBoolean: "TypeBoolean",
1222 TypeArray: "TypeArray",
1223 TypeObject: "TypeObject",
1224 }
1225
1226 func (v Type) String() string {
1227 if n, ok := namesForType[v]; ok {
1228 return n
1229 }
1230 return fmt.Sprintf("Type(%d)", v)
1231 }
1232
1233 // UsageMetadata is usage metadata about response(s).
1234 type UsageMetadata struct {
1235 // Number of tokens in the request. When `cached_content` is set, this is
1236 // still the total effective prompt size meaning this includes the number of
1237 // tokens in the cached content.
1238 PromptTokenCount int32
1239 // Number of tokens in the response(s).
1240 CandidatesTokenCount int32
1241 // Output only. Number of tokens present in thoughts output.
1242 ThoughtsTokenCount int32
1243 // Total token count for prompt and response candidates.
1244 TotalTokenCount int32
1245 }
1246
1247 func (v *UsageMetadata) toProto() *pb.GenerateContentResponse_UsageMetadata {
1248 if v == nil {
1249 return nil
1250 }
1251 return &pb.GenerateContentResponse_UsageMetadata{
1252 PromptTokenCount: v.PromptTokenCount,
1253 CandidatesTokenCount: v.CandidatesTokenCount,
1254 ThoughtsTokenCount: v.ThoughtsTokenCount,
1255 TotalTokenCount: v.TotalTokenCount,
1256 }
1257 }
1258
1259 func (UsageMetadata) fromProto(p *pb.GenerateContentResponse_UsageMetadata) *UsageMetadata {
1260 if p == nil {
1261 return nil
1262 }
1263 return &UsageMetadata{
1264 PromptTokenCount: p.PromptTokenCount,
1265 CandidatesTokenCount: p.CandidatesTokenCount,
1266 ThoughtsTokenCount: p.ThoughtsTokenCount,
1267 TotalTokenCount: p.TotalTokenCount,
1268 }
1269 }
1270
1271 // pvTransformSlice applies f to each element of from and returns
1272 // a new slice with the results.
1273 func pvTransformSlice[From, To any](from []From, f func(From) To) []To {
1274 if from == nil {
1275 return nil
1276 }
1277 to := make([]To, len(from))
1278 for i, e := range from {
1279 to[i] = f(e)
1280 }
1281 return to
1282 }
1283
1284 // pvTransformMapValues applies f to each value of from, returning a new map.
1285 // It does not change the keys.
1286 func pvTransformMapValues[K comparable, VFrom, VTo any](from map[K]VFrom, f func(VFrom) VTo) map[K]VTo {
1287 if from == nil {
1288 return nil
1289 }
1290 to := map[K]VTo{}
1291 for k, v := range from {
1292 to[k] = f(v)
1293 }
1294 return to
1295 }
1296
1297 // pvAddrOrNil returns nil if x is the zero value for T,
1298 // or &x otherwise.
1299 func pvAddrOrNil[T comparable](x T) *T {
1300 var z T
1301 if x == z {
1302 return nil
1303 }
1304 return &x
1305 }
1306
1307 // pvDerefOrZero returns the zero value for T if x is nil,
1308 // or *x otherwise.
1309 func pvDerefOrZero[T any](x *T) T {
1310 if x == nil {
1311 var z T
1312 return z
1313 }
1314 return *x
1315 }
1316
1317 // pvCivilDateToProto converts a civil.Date to a date.Date.
1318 func pvCivilDateToProto(d civil.Date) *date.Date {
1319 return &date.Date{
1320 Year: int32(d.Year),
1321 Month: int32(d.Month),
1322 Day: int32(d.Day),
1323 }
1324 }
1325
1326 // pvCivilDateFromProto converts a date.Date to a civil.Date.
1327 func pvCivilDateFromProto(p *date.Date) civil.Date {
1328 if p == nil {
1329 return civil.Date{}
1330 }
1331 return civil.Date{
1332 Year: int(p.Year),
1333 Month: time.Month(p.Month),
1334 Day: int(p.Day),
1335 }
1336 }
1337
1338 // pvMapToStructPB converts a map into a structpb.Struct.
1339 func pvMapToStructPB(m map[string]any) *structpb.Struct {
1340 if m == nil {
1341 return nil
1342 }
1343 s, err := structpb.NewStruct(m)
1344 if err != nil {
1345 panic(pvPanic(fmt.Errorf("pvMapToStructPB: %w", err)))
1346 }
1347 return s
1348 }
1349
1350 // pvMapFromStructPB converts a structpb.Struct to a map.
1351 func pvMapFromStructPB(p *structpb.Struct) map[string]any {
1352 if p == nil {
1353 return nil
1354 }
1355 return p.AsMap()
1356 }
1357
1358 // pvTimeToProto converts a time.Time into a Timestamp.
1359 func pvTimeToProto(t time.Time) *timestamppb.Timestamp {
1360 if t.IsZero() {
1361 return nil
1362 }
1363 return timestamppb.New(t)
1364 }
1365
1366 // pvTimeFromProto converts a Timestamp into a time.Time.
1367 func pvTimeFromProto(ts *timestamppb.Timestamp) time.Time {
1368 if ts == nil {
1369 return time.Time{}
1370 }
1371 return ts.AsTime()
1372 }
1373
1374 // pvPanic wraps panics from support functions.
1375 // User-provided functions in the same package can also use it.
1376 // It allows callers to distinguish conversion function panics from other panics.
1377 type pvPanic error
1378
1379 // pvCatchPanic recovers from panics of type pvPanic and
1380 // returns an error instead.
1381 func pvCatchPanic[T any](f func() T) (_ T, err error) {
1382 defer func() {
1383 if r := recover(); r != nil {
1384 if _, ok := r.(pvPanic); ok {
1385 err = r.(error)
1386 } else {
1387 panic(r)
1388 }
1389 }
1390 }()
1391 return f(), nil
1392 }