// Copyright 2026 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"
	"fmt"
	"log"
	"net/http"
	"reflect"
	"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. `output` contains the stdout, if any.
	OutcomeOK Outcome = "OUTCOME_OK"
	// Code execution failed. `output` contains the stderr and stdout, if any.
	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"
)

// Specifies how the response should be scheduled in the conversation. Only applicable
// to NON_BLOCKING function calls, is ignored otherwise. Defaults to WHEN_IDLE.
type FunctionResponseScheduling string

const (
	// This value is unused.
	FunctionResponseSchedulingUnspecified FunctionResponseScheduling = "SCHEDULING_UNSPECIFIED"
	// Only add the result to the conversation context, do not interrupt or trigger generation.
	FunctionResponseSchedulingSilent FunctionResponseScheduling = "SILENT"
	// Add the result to the conversation context, and prompt to generate output without
	// interrupting ongoing generation.
	FunctionResponseSchedulingWhenIdle FunctionResponseScheduling = "WHEN_IDLE"
	// Add the result to the conversation context, interrupt ongoing generation and prompt
	// to generate output.
	FunctionResponseSchedulingInterrupt FunctionResponseScheduling = "INTERRUPT"
)

// Data type of the schema field.
type Type string

const (
	// Not specified, should not be used.
	TypeUnspecified Type = "TYPE_UNSPECIFIED"
	// OpenAPI string type
	TypeString Type = "STRING"
	// OpenAPI number type
	TypeNumber Type = "NUMBER"
	// OpenAPI integer type
	TypeInteger Type = "INTEGER"
	// OpenAPI boolean type
	TypeBoolean Type = "BOOLEAN"
	// OpenAPI array type
	TypeArray Type = "ARRAY"
	// OpenAPI object type
	TypeObject Type = "OBJECT"
	// NULL type
	TypeNULL Type = "NULL"
)

// Type of auth scheme. This enum is not supported in Gemini API.
type AuthType string

const (
	AuthTypeUnspecified AuthType = "AUTH_TYPE_UNSPECIFIED"
	// No Auth.
	AuthTypeNoAuth AuthType = "NO_AUTH"
	// API Key Auth.
	AuthTypeAPIKeyAuth AuthType = "API_KEY_AUTH"
	// HTTP Basic Auth.
	AuthTypeHTTPBasicAuth AuthType = "HTTP_BASIC_AUTH"
	// Google Service Account Auth.
	AuthTypeGoogleServiceAccountAuth AuthType = "GOOGLE_SERVICE_ACCOUNT_AUTH"
	// OAuth auth.
	AuthTypeOauth AuthType = "OAUTH"
	// OpenID Connect (OIDC) Auth.
	AuthTypeOidcAuth AuthType = "OIDC_AUTH"
)

// The location of the API key. This enum is not supported in Gemini API.
type HTTPElementLocation string

const (
	HTTPElementLocationHTTPInUnspecified HTTPElementLocation = "HTTP_IN_UNSPECIFIED"
	// Element is in the HTTP request query.
	HTTPElementLocationHTTPInQuery HTTPElementLocation = "HTTP_IN_QUERY"
	// Element is in the HTTP request header.
	HTTPElementLocationHTTPInHeader HTTPElementLocation = "HTTP_IN_HEADER"
	// Element is in the HTTP request path.
	HTTPElementLocationHTTPInPath HTTPElementLocation = "HTTP_IN_PATH"
	// Element is in the HTTP request body.
	HTTPElementLocationHTTPInBody HTTPElementLocation = "HTTP_IN_BODY"
	// Element is in the HTTP request cookie.
	HTTPElementLocationHTTPInCookie HTTPElementLocation = "HTTP_IN_COOKIE"
)

// The API spec that the external API implements. This enum is not supported in Gemini
// API.
type APISpec string

const (
	// Unspecified API spec. This value should not be used.
	APISpecUnspecified APISpec = "API_SPEC_UNSPECIFIED"
	// Simple search API spec.
	APISpecSimpleSearch APISpec = "SIMPLE_SEARCH"
	// Elastic search API spec.
	APISpecElasticSearch APISpec = "ELASTIC_SEARCH"
)

// The environment being operated.
type Environment string

const (
	// Defaults to browser.
	EnvironmentUnspecified Environment = "ENVIRONMENT_UNSPECIFIED"
	// Operates in a web browser.
	EnvironmentBrowser Environment = "ENVIRONMENT_BROWSER"
	// Operates in a mobile environment.
	EnvironmentMobile Environment = "ENVIRONMENT_MOBILE"
	// Operates in a desktop environment.
	EnvironmentDesktop Environment = "ENVIRONMENT_DESKTOP"
)

// SafetyPolicy
type SafetyPolicy string

const (
	// Unspecified safety policy.
	SafetyPolicyUnspecified SafetyPolicy = "SAFETY_POLICY_UNSPECIFIED"
	// Safety policy for financial transactions.
	SafetyPolicyFinancialTransactions SafetyPolicy = "FINANCIAL_TRANSACTIONS"
	// Safety policy for sensitive data modification.
	SafetyPolicySensitiveDataModification SafetyPolicy = "SENSITIVE_DATA_MODIFICATION"
	// Safety policy for communication tools (e.g. Gmail, Chat, Meet).
	SafetyPolicyCommunicationTool SafetyPolicy = "COMMUNICATION_TOOL"
	// Safety policy for account creation.
	SafetyPolicyAccountCreation SafetyPolicy = "ACCOUNT_CREATION"
	// Safety policy for data modification.
	SafetyPolicyDataModification SafetyPolicy = "DATA_MODIFICATION"
	// Safety policy for user consent management.
	SafetyPolicyUserConsentManagement SafetyPolicy = "USER_CONSENT_MANAGEMENT"
	// Safety policy for legal terms and agreements.
	SafetyPolicyLegalTermsAndAgreements SafetyPolicy = "LEGAL_TERMS_AND_AGREEMENTS"
)

// Sites with confidence level chosen & above this value will be blocked from the search
// results. This enum is not supported in Gemini API.
type PhishBlockThreshold string

const (
	// Defaults to unspecified.
	PhishBlockThresholdUnspecified PhishBlockThreshold = "PHISH_BLOCK_THRESHOLD_UNSPECIFIED"
	// Blocks Low and above confidence URL that is risky.
	PhishBlockThresholdBlockLowAndAbove PhishBlockThreshold = "BLOCK_LOW_AND_ABOVE"
	// Blocks Medium and above confidence URL that is risky.
	PhishBlockThresholdBlockMediumAndAbove PhishBlockThreshold = "BLOCK_MEDIUM_AND_ABOVE"
	// Blocks High and above confidence URL that is risky.
	PhishBlockThresholdBlockHighAndAbove PhishBlockThreshold = "BLOCK_HIGH_AND_ABOVE"
	// Blocks Higher and above confidence URL that is risky.
	PhishBlockThresholdBlockHigherAndAbove PhishBlockThreshold = "BLOCK_HIGHER_AND_ABOVE"
	// Blocks Very high and above confidence URL that is risky.
	PhishBlockThresholdBlockVeryHighAndAbove PhishBlockThreshold = "BLOCK_VERY_HIGH_AND_ABOVE"
	// Blocks Extremely high confidence URL that is risky.
	PhishBlockThresholdBlockOnlyExtremelyHigh PhishBlockThreshold = "BLOCK_ONLY_EXTREMELY_HIGH"
)

// Specifies the function Behavior. If not specified, the system keeps the current function
// call behavior. This field is currently only supported by the BidiGenerateContent
// method.
type Behavior string

const (
	// This value is unspecified.
	BehaviorUnspecified Behavior = "UNSPECIFIED"
	// If set, the system will wait to receive the function response before continuing the
	// conversation.
	BehaviorBlocking Behavior = "BLOCKING"
	// If set, the system will not wait to receive the function response. Instead, it will
	// attempt to handle function responses as they become available while maintaining the
	// conversation between the user and the model.
	BehaviorNonBlocking Behavior = "NON_BLOCKING"
)

// The mode of the predictor to be used in dynamic retrieval.
type DynamicRetrievalConfigMode string

const (
	// Always trigger retrieval.
	DynamicRetrievalConfigModeUnspecified DynamicRetrievalConfigMode = "MODE_UNSPECIFIED"
	// Run retrieval only when system decides it is necessary.
	DynamicRetrievalConfigModeDynamic DynamicRetrievalConfigMode = "MODE_DYNAMIC"
)

// The number of thoughts tokens that the model should generate.
type ThinkingLevel string

const (
	// Unspecified thinking level.
	ThinkingLevelUnspecified ThinkingLevel = "THINKING_LEVEL_UNSPECIFIED"
	// MINIMAL thinking level.
	ThinkingLevelMinimal ThinkingLevel = "MINIMAL"
	// Low thinking level.
	ThinkingLevelLow ThinkingLevel = "LOW"
	// Medium thinking level.
	ThinkingLevelMedium ThinkingLevel = "MEDIUM"
	// High thinking level.
	ThinkingLevelHigh ThinkingLevel = "HIGH"
)

// Enum that controls the generation of people.
type PersonGeneration string

const (
	// Block generation of images of people.
	PersonGenerationDontAllow PersonGeneration = "DONT_ALLOW"
	// Generate images of adults, but not children.
	PersonGenerationAllowAdult PersonGeneration = "ALLOW_ADULT"
	// Generate images that include adults and children.
	PersonGenerationAllowAll PersonGeneration = "ALLOW_ALL"
)

// Controls whether prominent people (celebrities) generation is allowed. If used with
// personGeneration, personGeneration enum would take precedence. For instance, if ALLOW_NONE
// is set, all person generation would be blocked. If this field is unspecified, the
// default behavior is to allow prominent people. This enum is not supported in Gemini
// API.
type ProminentPeople string

const (
	// Unspecified value. The model will proceed with the default behavior, which is to
	// allow generation of prominent people.
	ProminentPeopleUnspecified ProminentPeople = "PROMINENT_PEOPLE_UNSPECIFIED"
	// Allows the model to generate images of prominent people.
	ProminentPeopleAllowProminentPeople ProminentPeople = "ALLOW_PROMINENT_PEOPLE"
	// Prevents the model from generating images of prominent people.
	ProminentPeopleBlockProminentPeople ProminentPeople = "BLOCK_PROMINENT_PEOPLE"
)

// The harm category to be blocked.
type HarmCategory string

const (
	// Default value. This value is unused.
	HarmCategoryUnspecified HarmCategory = "HARM_CATEGORY_UNSPECIFIED"
	// Abusive, threatening, or content intended to bully, torment, or ridicule.
	HarmCategoryHarassment HarmCategory = "HARM_CATEGORY_HARASSMENT"
	// Content that promotes violence or incites hatred against individuals or groups based
	// on certain attributes.
	HarmCategoryHateSpeech HarmCategory = "HARM_CATEGORY_HATE_SPEECH"
	// Content that contains sexually explicit material.
	HarmCategorySexuallyExplicit HarmCategory = "HARM_CATEGORY_SEXUALLY_EXPLICIT"
	// Content that promotes, facilitates, or enables dangerous activities.
	HarmCategoryDangerousContent HarmCategory = "HARM_CATEGORY_DANGEROUS_CONTENT"
	// Deprecated: Election filter is not longer supported. The harm category is civic integrity.
	HarmCategoryCivicIntegrity HarmCategory = "HARM_CATEGORY_CIVIC_INTEGRITY"
	// Images that contain hate speech. This enum value is not supported in Gemini API.
	HarmCategoryImageHate HarmCategory = "HARM_CATEGORY_IMAGE_HATE"
	// Images that contain dangerous content. This enum value is not supported in Gemini
	// API.
	HarmCategoryImageDangerousContent HarmCategory = "HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT"
	// Images that contain harassment. This enum value is not supported in Gemini API.
	HarmCategoryImageHarassment HarmCategory = "HARM_CATEGORY_IMAGE_HARASSMENT"
	// Images that contain sexually explicit content. This enum value is not supported in
	// Gemini API.
	HarmCategoryImageSexuallyExplicit HarmCategory = "HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT"
	// Prompts designed to bypass safety filters. This enum value is not supported in Gemini
	// API.
	HarmCategoryJailbreak HarmCategory = "HARM_CATEGORY_JAILBREAK"
)

// The method for blocking content. If not specified, the default behavior is to use
// the probability score. This enum is not supported in Gemini API.
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 threshold for blocking content. If the harm probability exceeds this threshold,
// the content will be blocked.
type HarmBlockThreshold string

const (
	// The harm block threshold is unspecified.
	HarmBlockThresholdUnspecified HarmBlockThreshold = "HARM_BLOCK_THRESHOLD_UNSPECIFIED"
	// Block content with a low harm probability or higher.
	HarmBlockThresholdBlockLowAndAbove HarmBlockThreshold = "BLOCK_LOW_AND_ABOVE"
	// Block content with a medium harm probability or higher.
	HarmBlockThresholdBlockMediumAndAbove HarmBlockThreshold = "BLOCK_MEDIUM_AND_ABOVE"
	// Block content with a high harm probability.
	HarmBlockThresholdBlockOnlyHigh HarmBlockThreshold = "BLOCK_ONLY_HIGH"
	// Do not block any content, regardless of its harm probability.
	HarmBlockThresholdBlockNone HarmBlockThreshold = "BLOCK_NONE"
	// Turn off the safety filter entirely.
	HarmBlockThresholdOff HarmBlockThreshold = "OFF"
)

// Function calling mode.
type FunctionCallingConfigMode string

const (
	// Unspecified function calling mode. This value 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"
	// Model is constrained to predict either function calls or natural language response.
	// 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".
	FunctionCallingConfigModeValidated FunctionCallingConfigMode = "VALIDATED"
)

// 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"
	// The token generation stopped because of using an unsupported language.
	FinishReasonLanguage FinishReason = "LANGUAGE"
	// 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"
	// Token generation stopped because generated images have safety violations.
	FinishReasonImageSafety FinishReason = "IMAGE_SAFETY"
	// The tool call generated by the model is invalid.
	FinishReasonUnexpectedToolCall FinishReason = "UNEXPECTED_TOOL_CALL"
	// Image generation stopped because the generated images have prohibited content.
	FinishReasonImageProhibitedContent FinishReason = "IMAGE_PROHIBITED_CONTENT"
	// The model was expected to generate an image, but none was generated.
	FinishReasonNoImage FinishReason = "NO_IMAGE"
	// Image generation stopped because the generated image may be a recitation from a source.
	FinishReasonImageRecitation FinishReason = "IMAGE_RECITATION"
	// Image generation stopped for a reason not otherwise specified.
	FinishReasonImageOther FinishReason = "IMAGE_OTHER"
)

// The probability of harm for this category.
type HarmProbability string

const (
	// The harm probability is unspecified.
	HarmProbabilityUnspecified HarmProbability = "HARM_PROBABILITY_UNSPECIFIED"
	// The harm probability is negligible.
	HarmProbabilityNegligible HarmProbability = "NEGLIGIBLE"
	// The harm probability is low.
	HarmProbabilityLow HarmProbability = "LOW"
	// The harm probability is medium.
	HarmProbabilityMedium HarmProbability = "MEDIUM"
	// The harm probability is high.
	HarmProbabilityHigh HarmProbability = "HIGH"
)

// The severity of harm for this category. This enum is not supported in Gemini API.
type HarmSeverity string

const (
	// The harm severity is unspecified.
	HarmSeverityUnspecified HarmSeverity = "HARM_SEVERITY_UNSPECIFIED"
	// The harm severity is negligible.
	HarmSeverityNegligible HarmSeverity = "HARM_SEVERITY_NEGLIGIBLE"
	// The harm severity is low.
	HarmSeverityLow HarmSeverity = "HARM_SEVERITY_LOW"
	// The harm severity is medium.
	HarmSeverityMedium HarmSeverity = "HARM_SEVERITY_MEDIUM"
	// The harm severity is high.
	HarmSeverityHigh HarmSeverity = "HARM_SEVERITY_HIGH"
)

// The status of the URL retrieval.
type URLRetrievalStatus string

const (
	// Default value. This value is unused.
	URLRetrievalStatusUnspecified URLRetrievalStatus = "URL_RETRIEVAL_STATUS_UNSPECIFIED"
	// The URL was retrieved successfully.
	URLRetrievalStatusSuccess URLRetrievalStatus = "URL_RETRIEVAL_STATUS_SUCCESS"
	// The URL retrieval failed.
	URLRetrievalStatusError URLRetrievalStatus = "URL_RETRIEVAL_STATUS_ERROR"
	// URL retrieval is failed because the content is behind paywall. This enum value is
	// not supported in Vertex AI.
	URLRetrievalStatusPaywall URLRetrievalStatus = "URL_RETRIEVAL_STATUS_PAYWALL"
	// URL retrieval is failed because the content is unsafe. This enum value is not supported
	// in Vertex AI.
	URLRetrievalStatusUnsafe URLRetrievalStatus = "URL_RETRIEVAL_STATUS_UNSAFE"
)

// The reason why the prompt was blocked.
type BlockedReason string

const (
	// The blocked reason is unspecified.
	BlockedReasonUnspecified BlockedReason = "BLOCKED_REASON_UNSPECIFIED"
	// The prompt was blocked for safety reasons.
	BlockedReasonSafety BlockedReason = "SAFETY"
	// The prompt was blocked for other reasons. For example, it may be due to the prompt's
	// language, or because it contains other harmful content.
	BlockedReasonOther BlockedReason = "OTHER"
	// The prompt was blocked because it contains a term from the terminology blocklist.
	BlockedReasonBlocklist BlockedReason = "BLOCKLIST"
	// The prompt was blocked because it contains prohibited content.
	BlockedReasonProhibitedContent BlockedReason = "PROHIBITED_CONTENT"
	// The prompt was blocked because it contains content that is unsafe for image generation.
	BlockedReasonImageSafety BlockedReason = "IMAGE_SAFETY"
	// The prompt was blocked by Model Armor. This enum value is not supported in Gemini
	// API.
	BlockedReasonModelArmor BlockedReason = "MODEL_ARMOR"
	// The prompt was blocked as a jailbreak attempt. This enum value is not supported in
	// Gemini API.
	BlockedReasonJailbreak BlockedReason = "JAILBREAK"
)

// The traffic type for this request. This enum is not supported in Gemini API.
type TrafficType string

const (
	// Unspecified request traffic type.
	TrafficTypeUnspecified TrafficType = "TRAFFIC_TYPE_UNSPECIFIED"
	// The request was processed using Pay-As-You-Go quota.
	TrafficTypeOnDemand TrafficType = "ON_DEMAND"
	// Type for Priority Pay-As-You-Go traffic.
	TrafficTypeOnDemandPriority TrafficType = "ON_DEMAND_PRIORITY"
	// Type for Flex traffic.
	TrafficTypeOnDemandFlex TrafficType = "ON_DEMAND_FLEX"
	// Type for Provisioned Throughput traffic.
	TrafficTypeProvisionedThroughput TrafficType = "PROVISIONED_THROUGHPUT"
)

// The modality that this token count applies to.
type MediaModality string

const (
	// When a modality is not specified, it is treated as `TEXT`.
	MediaModalityUnspecified MediaModality = "MODALITY_UNSPECIFIED"
	// The `Part` contains plain text.
	MediaModalityText MediaModality = "TEXT"
	// The `Part` contains an image.
	MediaModalityImage MediaModality = "IMAGE"
	// The `Part` contains a video.
	MediaModalityVideo MediaModality = "VIDEO"
	// The `Part` contains audio.
	MediaModalityAudio MediaModality = "AUDIO"
	// The `Part` contains a document, such as a PDF.
	MediaModalityDocument MediaModality = "DOCUMENT"
)

// The stage of the underlying model. This enum is not supported in Vertex AI.
type ModelStage string

const (
	// Unspecified model stage.
	ModelStageUnspecified ModelStage = "MODEL_STAGE_UNSPECIFIED"
	// The underlying model is subject to lots of tunings.
	ModelStageUnstableExperimental ModelStage = "UNSTABLE_EXPERIMENTAL"
	// Models in this stage are for experimental purposes only.
	ModelStageExperimental ModelStage = "EXPERIMENTAL"
	// Models in this stage are more mature than experimental models.
	ModelStagePreview ModelStage = "PREVIEW"
	// Models in this stage are considered stable and ready for production use.
	ModelStageStable ModelStage = "STABLE"
	// If the model is on this stage, it means that this model is on the path to deprecation
	// in near future. Only existing customers can use this model.
	ModelStageLegacy ModelStage = "LEGACY"
	// Models in this stage are deprecated. These models cannot be used.
	ModelStageDeprecated ModelStage = "DEPRECATED"
	// Models in this stage are retired. These models cannot be used.
	ModelStageRetired ModelStage = "RETIRED"
)

// 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"
)

// 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 audio.
	ModalityAudio Modality = "AUDIO"
	// Indicates the model should return video.
	ModalityVideo Modality = "VIDEO"
)

// Delivery mode for the generated content.
type Delivery string

const (
	// Default value. This value is unused.
	DeliveryUnspecified Delivery = "DELIVERY_UNSPECIFIED"
	// Generated bytes are returned inline in the response.
	DeliveryInline Delivery = "INLINE"
	// Generated content is stored and a URI is returned.
	DeliveryURI Delivery = "URI"
)

// The aspect ratio for the image output.
type AspectRatio string

const (
	// Default value. This value is unused.
	AspectRatioUnspecified AspectRatio = "ASPECT_RATIO_UNSPECIFIED"
	// 1:1 aspect ratio.
	AspectRatioOneByOne AspectRatio = "ASPECT_RATIO_ONE_BY_ONE"
	// 2:3 aspect ratio.
	AspectRatioTwoByThree AspectRatio = "ASPECT_RATIO_TWO_BY_THREE"
	// 3:2 aspect ratio.
	AspectRatioThreeByTwo AspectRatio = "ASPECT_RATIO_THREE_BY_TWO"
	// 3:4 aspect ratio.
	AspectRatioThreeByFour AspectRatio = "ASPECT_RATIO_THREE_BY_FOUR"
	// 4:3 aspect ratio.
	AspectRatioFourByThree AspectRatio = "ASPECT_RATIO_FOUR_BY_THREE"
	// 4:5 aspect ratio.
	AspectRatioFourByFive AspectRatio = "ASPECT_RATIO_FOUR_BY_FIVE"
	// 5:4 aspect ratio.
	AspectRatioFiveByFour AspectRatio = "ASPECT_RATIO_FIVE_BY_FOUR"
	// 9:16 aspect ratio.
	AspectRatioNineBySixteen AspectRatio = "ASPECT_RATIO_NINE_BY_SIXTEEN"
	// 16:9 aspect ratio.
	AspectRatioSixteenByNine AspectRatio = "ASPECT_RATIO_SIXTEEN_BY_NINE"
	// 21:9 aspect ratio.
	AspectRatioTwentyOneByNine AspectRatio = "ASPECT_RATIO_TWENTY_ONE_BY_NINE"
	// 1:8 aspect ratio.
	AspectRatioOneByEight AspectRatio = "ASPECT_RATIO_ONE_BY_EIGHT"
	// 8:1 aspect ratio.
	AspectRatioEightByOne AspectRatio = "ASPECT_RATIO_EIGHT_BY_ONE"
	// 1:4 aspect ratio.
	AspectRatioOneByFour AspectRatio = "ASPECT_RATIO_ONE_BY_FOUR"
	// 4:1 aspect ratio.
	AspectRatioFourByOne AspectRatio = "ASPECT_RATIO_FOUR_BY_ONE"
)

// The size of the image output.
type ImageSize string

const (
	// Default value. This value is unused.
	ImageSizeUnspecified ImageSize = "IMAGE_SIZE_UNSPECIFIED"
	// 512px image size.
	ImageSizeFiveTwelve ImageSize = "IMAGE_SIZE_FIVE_TWELVE"
	// 1K image size.
	ImageSizeOneK ImageSize = "IMAGE_SIZE_ONE_K"
	// 2K image size.
	ImageSizeTwoK ImageSize = "IMAGE_SIZE_TWO_K"
	// 4K image size.
	ImageSizeFourK ImageSize = "IMAGE_SIZE_FOUR_K"
)

// Tuning mode. This enum is not supported in Gemini API.
type TuningMode string

const (
	// Tuning mode is unspecified.
	TuningModeUnspecified TuningMode = "TUNING_MODE_UNSPECIFIED"
	// Full fine-tuning mode.
	TuningModeFull TuningMode = "TUNING_MODE_FULL"
	// PEFT adapter tuning mode.
	TuningModePeftAdapter TuningMode = "TUNING_MODE_PEFT_ADAPTER"
)

// Adapter size for tuning. This enum is not supported in Gemini API.
type AdapterSize string

const (
	// Adapter size is unspecified.
	AdapterSizeUnspecified AdapterSize = "ADAPTER_SIZE_UNSPECIFIED"
	// Adapter size 1.
	AdapterSizeOne AdapterSize = "ADAPTER_SIZE_ONE"
	// Adapter size 2.
	AdapterSizeTwo AdapterSize = "ADAPTER_SIZE_TWO"
	// Adapter size 4.
	AdapterSizeFour AdapterSize = "ADAPTER_SIZE_FOUR"
	// Adapter size 8.
	AdapterSizeEight AdapterSize = "ADAPTER_SIZE_EIGHT"
	// Adapter size 16.
	AdapterSizeSixteen AdapterSize = "ADAPTER_SIZE_SIXTEEN"
	// Adapter size 32.
	AdapterSizeThirtyTwo AdapterSize = "ADAPTER_SIZE_THIRTY_TWO"
)

// Defines the type for parsing sample response. This enum is not supported in Gemini
// API.
type ResponseParseType string

const (
	// Default value. Fallback to IDENTITY
	ResponseParseTypeUnspecified ResponseParseType = "RESPONSE_PARSE_TYPE_UNSPECIFIED"
	// Returns the sample response as is.
	ResponseParseTypeIdentity ResponseParseType = "IDENTITY"
	// Uses regex to extract the important part of sample response. Similar to [GoogleSQL](https://cloud.google.com/bigquery/docs/reference/standard-sql/string_functions#regexp_extract)
	// `REGEX_EXTRACT(response, regex_extract_expression)`, but different in that if there
	// are multiple matches, the last match will be returned.
	ResponseParseTypeRegexExtract ResponseParseType = "REGEX_EXTRACT"
)

// Match operation to use for evaluating rewards. This enum is not supported in Gemini
// API.
type MatchOperation string

const (
	// Default value. A user error will be returned if not set.
	MatchOperationUnspecified MatchOperation = "MATCH_OPERATION_UNSPECIFIED"
	// Equivalent to [GoogleSQL](https://cloud.google.com/bigquery/docs/reference/standard-sql/string_functions#regexp_contains)
	// `REGEX_CONTAINS(target, expression)`.
	MatchOperationRegexContains MatchOperation = "REGEX_CONTAINS"
	// The match operation returns `true` if expression is a substring of the target.
	MatchOperationPartialMatch MatchOperation = "PARTIAL_MATCH"
	// The match operation returns `true` expression is an exact match of the target.
	MatchOperationExactMatch MatchOperation = "EXACT_MATCH"
)

// Represents how much to think for the tuning job.
type ReinforcementTuningThinkingLevel string

const (
	// Unspecified thinking level.
	ReinforcementTuningThinkingLevelUnspecified ReinforcementTuningThinkingLevel = "REINFORCEMENT_TUNING_THINKING_LEVEL_UNSPECIFIED"
	// Little to no thinking.
	ReinforcementTuningThinkingLevelMinimal ReinforcementTuningThinkingLevel = "MINIMAL"
	// High thinking level.
	ReinforcementTuningThinkingLevelHigh ReinforcementTuningThinkingLevel = "HIGH"
)

// Job state.
type JobState string

const (
	// The job state is unspecified.
	JobStateUnspecified JobState = "JOB_STATE_UNSPECIFIED"
	// The job has been just created or resumed and processing has not yet begun.
	JobStateQueued JobState = "JOB_STATE_QUEUED"
	// The service is preparing to run the job.
	JobStatePending JobState = "JOB_STATE_PENDING"
	// The job is in progress.
	JobStateRunning JobState = "JOB_STATE_RUNNING"
	// The job completed successfully.
	JobStateSucceeded JobState = "JOB_STATE_SUCCEEDED"
	// The job failed.
	JobStateFailed JobState = "JOB_STATE_FAILED"
	// The job is being cancelled. From this state the job may only go to either `JOB_STATE_SUCCEEDED`,
	// `JOB_STATE_FAILED` or `JOB_STATE_CANCELLED`.
	JobStateCancelling JobState = "JOB_STATE_CANCELLING"
	// The job has been cancelled.
	JobStateCancelled JobState = "JOB_STATE_CANCELLED"
	// The job has been stopped, and can be resumed.
	JobStatePaused JobState = "JOB_STATE_PAUSED"
	// The job has expired.
	JobStateExpired JobState = "JOB_STATE_EXPIRED"
	// The job is being updated. Only jobs in the `JOB_STATE_RUNNING` state can be updated.
	// After updating, the job goes back to the `JOB_STATE_RUNNING` state.
	JobStateUpdating JobState = "JOB_STATE_UPDATING"
	// The job is partially succeeded, some results may be missing due to errors.
	JobStatePartiallySucceeded JobState = "JOB_STATE_PARTIALLY_SUCCEEDED"
)

// The detail state of the tuning job (while the overall `JobState` is running). This
// enum is not supported in Gemini API.
type TuningJobState string

const (
	// Default tuning job state.
	TuningJobStateUnspecified TuningJobState = "TUNING_JOB_STATE_UNSPECIFIED"
	// Tuning job is waiting for job quota.
	TuningJobStateWaitingForQuota TuningJobState = "TUNING_JOB_STATE_WAITING_FOR_QUOTA"
	// Tuning job is validating the dataset.
	TuningJobStateProcessingDataset TuningJobState = "TUNING_JOB_STATE_PROCESSING_DATASET"
	// Tuning job is waiting for hardware capacity.
	TuningJobStateWaitingForCapacity TuningJobState = "TUNING_JOB_STATE_WAITING_FOR_CAPACITY"
	// Tuning job is running.
	TuningJobStateTuning TuningJobState = "TUNING_JOB_STATE_TUNING"
	// Tuning job is doing some post processing steps.
	TuningJobStatePostProcessing TuningJobState = "TUNING_JOB_STATE_POST_PROCESSING"
)

// Aggregation metric. This enum is not supported in Gemini API.
type AggregationMetric string

const (
	// Unspecified aggregation metric.
	AggregationMetricUnspecified AggregationMetric = "AGGREGATION_METRIC_UNSPECIFIED"
	// Average aggregation metric. Not supported for Pairwise metric.
	AggregationMetricAverage AggregationMetric = "AVERAGE"
	// Mode aggregation metric.
	AggregationMetricMode AggregationMetric = "MODE"
	// Standard deviation aggregation metric. Not supported for pairwise metric.
	AggregationMetricStandardDeviation AggregationMetric = "STANDARD_DEVIATION"
	// Variance aggregation metric. Not supported for pairwise metric.
	AggregationMetricVariance AggregationMetric = "VARIANCE"
	// Minimum aggregation metric. Not supported for pairwise metric.
	AggregationMetricMinimum AggregationMetric = "MINIMUM"
	// Maximum aggregation metric. Not supported for pairwise metric.
	AggregationMetricMaximum AggregationMetric = "MAXIMUM"
	// Median aggregation metric. Not supported for pairwise metric.
	AggregationMetricMedian AggregationMetric = "MEDIAN"
	// 90th percentile aggregation metric. Not supported for pairwise metric.
	AggregationMetricPercentileP90 AggregationMetric = "PERCENTILE_P90"
	// 95th percentile aggregation metric. Not supported for pairwise metric.
	AggregationMetricPercentileP95 AggregationMetric = "PERCENTILE_P95"
	// 99th percentile aggregation metric. Not supported for pairwise metric.
	AggregationMetricPercentileP99 AggregationMetric = "PERCENTILE_P99"
)

// Pairwise metric choice. This enum is not supported in Gemini API.
type PairwiseChoice string

const (
	// Unspecified prediction choice.
	PairwiseChoiceUnspecified PairwiseChoice = "PAIRWISE_CHOICE_UNSPECIFIED"
	// Baseline prediction wins
	PairwiseChoiceBaseline PairwiseChoice = "BASELINE"
	// Candidate prediction wins
	PairwiseChoiceCandidate PairwiseChoice = "CANDIDATE"
	// Winner cannot be determined
	PairwiseChoiceTie PairwiseChoice = "TIE"
)

// The speed of the tuning job. Only supported for Veo 3.0 models. This enum is not
// supported in Gemini API.
type TuningSpeed string

const (
	// The default / unset value. For Veo 3.0 models, this defaults to FAST.
	TuningSpeedUnspecified TuningSpeed = "TUNING_SPEED_UNSPECIFIED"
	// Regular tuning speed.
	TuningSpeedRegular TuningSpeed = "REGULAR"
	// Fast tuning speed.
	TuningSpeedFast TuningSpeed = "FAST"
)

// The tuning task for Veo. This enum is not supported in Gemini API.
type TuningTask string

const (
	// Default value. This value is unused.
	TuningTaskUnspecified TuningTask = "TUNING_TASK_UNSPECIFIED"
	// Tuning task for image to video.
	TuningTaskI2v TuningTask = "TUNING_TASK_I2V"
	// Tuning task for text to video.
	TuningTaskT2v TuningTask = "TUNING_TASK_T2V"
	// Tuning task for reference to video.
	TuningTaskR2v TuningTask = "TUNING_TASK_R2V"
)

// The orientation of the video. Defaults to LANDSCAPE. This enum is not supported in
// Gemini API.
type VideoOrientation string

const (
	// Unspecified video orientation. Defaults to landscape.
	VideoOrientationUnspecified VideoOrientation = "VIDEO_ORIENTATION_UNSPECIFIED"
	// Landscape orientation (e.g. 16:9, 1280x720).
	VideoOrientationLandscape VideoOrientation = "LANDSCAPE"
	// Portrait orientation (e.g. 9:16, 720x1280).
	VideoOrientationPortrait VideoOrientation = "PORTRAIT"
)

// Current state of the `Document`. This enum is not supported in Vertex AI.
type DocumentState string

const (
	// The default value. This value is used if the state is omitted.
	DocumentStateUnspecified DocumentState = "STATE_UNSPECIFIED"
	// Some `Chunks` of the `Document` are being processed (embedding and vector storage).
	DocumentStatePending DocumentState = "STATE_PENDING"
	// All `Chunks` of the `Document` is processed and available for querying.
	DocumentStateActive DocumentState = "STATE_ACTIVE"
	// Some `Chunks` of the `Document` failed processing.
	DocumentStateFailed DocumentState = "STATE_FAILED"
)

// Pricing and performance service tier.
type ServiceTier string

const (
	// Default service tier, which is standard.
	ServiceTierUnspecified ServiceTier = "unspecified"
	// Flex service tier.
	ServiceTierFlex ServiceTier = "flex"
	// Standard service tier.
	ServiceTierStandard ServiceTier = "standard"
	// Priority service tier.
	ServiceTierPriority ServiceTier = "priority"
)

// The tokenization quality used for given media.
type PartMediaResolutionLevel string

const (
	// Media resolution has not been set.
	PartMediaResolutionLevelMediaResolutionUnspecified PartMediaResolutionLevel = "MEDIA_RESOLUTION_UNSPECIFIED"
	// Media resolution set to low.
	PartMediaResolutionLevelMediaResolutionLow PartMediaResolutionLevel = "MEDIA_RESOLUTION_LOW"
	// Media resolution set to medium.
	PartMediaResolutionLevelMediaResolutionMedium PartMediaResolutionLevel = "MEDIA_RESOLUTION_MEDIUM"
	// Media resolution set to high.
	PartMediaResolutionLevelMediaResolutionHigh PartMediaResolutionLevel = "MEDIA_RESOLUTION_HIGH"
	// Media resolution set to ultra high.
	PartMediaResolutionLevelMediaResolutionUltraHigh PartMediaResolutionLevel = "MEDIA_RESOLUTION_ULTRA_HIGH"
)

// The type of tool in the function call.
type ToolType string

const (
	// Unspecified tool type.
	ToolTypeUnspecified ToolType = "TOOL_TYPE_UNSPECIFIED"
	// Google search tool, maps to Tool.google_search.search_types.web_search.
	ToolTypeGoogleSearchWeb ToolType = "GOOGLE_SEARCH_WEB"
	// Image search tool, maps to Tool.google_search.search_types.image_search.
	ToolTypeGoogleSearchImage ToolType = "GOOGLE_SEARCH_IMAGE"
	// URL context tool, maps to Tool.url_context.
	ToolTypeURLContext ToolType = "URL_CONTEXT"
	// Google maps tool, maps to Tool.google_maps.
	ToolTypeGoogleMaps ToolType = "GOOGLE_MAPS"
	// File search tool, maps to Tool.file_search.
	ToolTypeFileSearch ToolType = "FILE_SEARCH"
)

// Resource scope.
type ResourceScope string

const (
	// When setting base_url, this value configures resource scope to be the collection.
	// The resource name will not include API version, project, or location.
	// For example, if base_url is set to "https://aiplatform.googleapis.com",
	// then the resource name for a Model would be
	// "https://aiplatform.googleapis.com/publishers/google/models/gemini-3-pro-preview
	ResourceScopeCollection ResourceScope = "COLLECTION"
)

// Options for feature selection preference.
type FeatureSelectionPreference string

const (
	FeatureSelectionPreferenceUnspecified       FeatureSelectionPreference = "FEATURE_SELECTION_PREFERENCE_UNSPECIFIED"
	FeatureSelectionPreferencePrioritizeQuality FeatureSelectionPreference = "PRIORITIZE_QUALITY"
	FeatureSelectionPreferenceBalanced          FeatureSelectionPreference = "BALANCED"
	FeatureSelectionPreferencePrioritizeCost    FeatureSelectionPreference = "PRIORITIZE_COST"
)

// Enum representing the Gemini Enterprise Agent Platform embedding API to use.
type EmbeddingAPIType string

const (
	// predict API endpoint (default)
	EmbeddingAPITypePredict EmbeddingAPIType = "PREDICT"
	// embedContent API Endpoint
	EmbeddingAPITypeEmbedContent EmbeddingAPIType = "EMBED_CONTENT"
)

// 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 specifies the language of the text in the prompt.
type ImagePromptLanguage string

const (
	// Auto-detect the language.
	ImagePromptLanguageAuto ImagePromptLanguage = "auto"
	// English
	ImagePromptLanguageEn ImagePromptLanguage = "en"
	// Japanese
	ImagePromptLanguageJa ImagePromptLanguage = "ja"
	// Korean
	ImagePromptLanguageKo ImagePromptLanguage = "ko"
	// Hindi
	ImagePromptLanguageHi ImagePromptLanguage = "hi"
	// Chinese
	ImagePromptLanguageZh ImagePromptLanguage = "zh"
	// Portuguese
	ImagePromptLanguagePt ImagePromptLanguage = "pt"
	// Spanish
	ImagePromptLanguageEs ImagePromptLanguage = "es"
)

// 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"
)

// Enum representing the editing mode.
type EditMode string

const (
	EditModeDefault           EditMode = "EDIT_MODE_DEFAULT"
	EditModeInpaintRemoval    EditMode = "EDIT_MODE_INPAINT_REMOVAL"
	EditModeInpaintInsertion  EditMode = "EDIT_MODE_INPAINT_INSERTION"
	EditModeOutpaint          EditMode = "EDIT_MODE_OUTPAINT"
	EditModeControlledEditing EditMode = "EDIT_MODE_CONTROLLED_EDITING"
	EditModeStyle             EditMode = "EDIT_MODE_STYLE"
	EditModeBgswap            EditMode = "EDIT_MODE_BGSWAP"
	EditModeProductImage      EditMode = "EDIT_MODE_PRODUCT_IMAGE"
)

// Enum that represents the segmentation mode.
type SegmentMode string

const (
	SegmentModeForeground  SegmentMode = "FOREGROUND"
	SegmentModeBackground  SegmentMode = "BACKGROUND"
	SegmentModePrompt      SegmentMode = "PROMPT"
	SegmentModeSemantic    SegmentMode = "SEMANTIC"
	SegmentModeInteractive SegmentMode = "INTERACTIVE"
)

// Enum for the reference type of a video generation reference image.
type VideoGenerationReferenceType string

const (
	// A reference image that provides assets to the generated video,
	// such as the scene, an object, a character, etc.
	VideoGenerationReferenceTypeAsset VideoGenerationReferenceType = "ASSET"
	// A reference image that provides aesthetics including colors,
	// lighting, texture, etc., to be used as the style of the generated video,
	// such as 'anime', 'photography', 'origami', etc.
	VideoGenerationReferenceTypeStyle VideoGenerationReferenceType = "STYLE"
)

// Enum for the mask mode of a video generation mask.
type VideoGenerationMaskMode string

const (
	// The image mask contains a masked rectangular region which is
	// applied on the first frame of the input video. The object described in
	// the prompt is inserted into this region and will appear in subsequent
	// frames.
	VideoGenerationMaskModeInsert VideoGenerationMaskMode = "INSERT"
	// The image mask is used to determine an object in the
	// first video frame to track. This object is removed from the video.
	VideoGenerationMaskModeRemove VideoGenerationMaskMode = "REMOVE"
	// The image mask is used to determine a region in the
	// video. Objects in this region will be removed.
	VideoGenerationMaskModeRemoveStatic VideoGenerationMaskMode = "REMOVE_STATIC"
	// The image mask contains a masked rectangular region where
	// the input video will go. The remaining area will be generated. Video
	// masks are not supported.
	VideoGenerationMaskModeOutpaint VideoGenerationMaskMode = "OUTPAINT"
)

// Enum that controls the compression quality of the generated videos.
type VideoCompressionQuality string

const (
	// Optimized video compression quality. This will produce videos
	// with a compressed, smaller file size.
	VideoCompressionQualityOptimized VideoCompressionQuality = "OPTIMIZED"
	// Lossless video compression quality. This will produce videos
	// with a larger file size.
	VideoCompressionQualityLossless VideoCompressionQuality = "LOSSLESS"
)

// Resize mode for the image input for video generation.
type ImageResizeMode string

const (
	// Crop the image to fit the correct aspect ratio (so we lose parts
	// of the image in the process).
	ImageResizeModeCrop ImageResizeMode = "CROP"
	// Pad the image to fit the correct aspect ratio (so we don't lose
	// any parts of the image in the process).
	ImageResizeModePad ImageResizeMode = "PAD"
)

// Enum representing the tuning method.
type TuningMethod string

const (
	// Supervised fine tuning.
	TuningMethodSupervisedFineTuning TuningMethod = "SUPERVISED_FINE_TUNING"
	// Preference optimization tuning.
	TuningMethodPreferenceTuning TuningMethod = "PREFERENCE_TUNING"
	// Distillation tuning.
	TuningMethodDistillation TuningMethod = "DISTILLATION"
	// Reinforcement tuning.
	TuningMethodReinforcementTuning TuningMethod = "REINFORCEMENT_TUNING"
)

// State for the lifecycle of a File.
type FileState string

const (
	FileStateUnspecified FileState = "STATE_UNSPECIFIED"
	FileStateProcessing  FileState = "PROCESSING"
	FileStateActive      FileState = "ACTIVE"
	FileStateFailed      FileState = "FAILED"
)

// Source of the File.
type FileSource string

const (
	FileSourceUnspecified FileSource = "SOURCE_UNSPECIFIED"
	FileSourceUploaded    FileSource = "UPLOADED"
	FileSourceGenerated   FileSource = "GENERATED"
	FileSourceRegistered  FileSource = "REGISTERED"
)

// The reason why the turn is complete.
type TurnCompleteReason string

const (
	// Default value. Reason is unspecified.
	TurnCompleteReasonUnspecified TurnCompleteReason = "TURN_COMPLETE_REASON_UNSPECIFIED"
	// The function call generated by the model is invalid.
	TurnCompleteReasonMalformedFunctionCall TurnCompleteReason = "MALFORMED_FUNCTION_CALL"
	// The response is rejected by the model.
	TurnCompleteReasonResponseRejected TurnCompleteReason = "RESPONSE_REJECTED"
	// Needs more input from the user.
	TurnCompleteReasonNeedMoreInput TurnCompleteReason = "NEED_MORE_INPUT"
	// Input content is prohibited.
	TurnCompleteReasonProhibitedInputContent TurnCompleteReason = "PROHIBITED_INPUT_CONTENT"
	// Input image contains prohibited content.
	TurnCompleteReasonImageProhibitedInputContent TurnCompleteReason = "IMAGE_PROHIBITED_INPUT_CONTENT"
	// Input text contains prominent person reference.
	TurnCompleteReasonInputTextContainProminentPersonProhibited TurnCompleteReason = "INPUT_TEXT_CONTAIN_PROMINENT_PERSON_PROHIBITED"
	// Input image contains celebrity.
	TurnCompleteReasonInputImageCelebrity TurnCompleteReason = "INPUT_IMAGE_CELEBRITY"
	// Input image contains photo realistic child.
	TurnCompleteReasonInputImagePhotoRealisticChildProhibited TurnCompleteReason = "INPUT_IMAGE_PHOTO_REALISTIC_CHILD_PROHIBITED"
	// Input text contains NCII content.
	TurnCompleteReasonInputTextNciiProhibited TurnCompleteReason = "INPUT_TEXT_NCII_PROHIBITED"
	// Other input safety issue.
	TurnCompleteReasonInputOther TurnCompleteReason = "INPUT_OTHER"
	// Input contains IP violation.
	TurnCompleteReasonInputIpProhibited TurnCompleteReason = "INPUT_IP_PROHIBITED"
	// Input matched blocklist.
	TurnCompleteReasonBlocklist TurnCompleteReason = "BLOCKLIST"
	// Input is unsafe for image generation.
	TurnCompleteReasonUnsafePromptForImageGeneration TurnCompleteReason = "UNSAFE_PROMPT_FOR_IMAGE_GENERATION"
	// Generated image failed safety check.
	TurnCompleteReasonGeneratedImageSafety TurnCompleteReason = "GENERATED_IMAGE_SAFETY"
	// Generated content failed safety check.
	TurnCompleteReasonGeneratedContentSafety TurnCompleteReason = "GENERATED_CONTENT_SAFETY"
	// Generated audio failed safety check.
	TurnCompleteReasonGeneratedAudioSafety TurnCompleteReason = "GENERATED_AUDIO_SAFETY"
	// Generated video failed safety check.
	TurnCompleteReasonGeneratedVideoSafety TurnCompleteReason = "GENERATED_VIDEO_SAFETY"
	// Generated content is prohibited.
	TurnCompleteReasonGeneratedContentProhibited TurnCompleteReason = "GENERATED_CONTENT_PROHIBITED"
	// Generated content matched blocklist.
	TurnCompleteReasonGeneratedContentBlocklist TurnCompleteReason = "GENERATED_CONTENT_BLOCKLIST"
	// Generated image is prohibited.
	TurnCompleteReasonGeneratedImageProhibited TurnCompleteReason = "GENERATED_IMAGE_PROHIBITED"
	// Generated image contains celebrity.
	TurnCompleteReasonGeneratedImageCelebrity TurnCompleteReason = "GENERATED_IMAGE_CELEBRITY"
	// Generated image contains prominent people detected by rewriter.
	TurnCompleteReasonGeneratedImageProminentPeopleDetectedByRewriter TurnCompleteReason = "GENERATED_IMAGE_PROMINENT_PEOPLE_DETECTED_BY_REWRITER"
	// Generated image contains identifiable people.
	TurnCompleteReasonGeneratedImageIdentifiablePeople TurnCompleteReason = "GENERATED_IMAGE_IDENTIFIABLE_PEOPLE"
	// Generated image contains minors.
	TurnCompleteReasonGeneratedImageMinors TurnCompleteReason = "GENERATED_IMAGE_MINORS"
	// Generated image contains IP violation.
	TurnCompleteReasonOutputImageIpProhibited TurnCompleteReason = "OUTPUT_IMAGE_IP_PROHIBITED"
	// Other generated content issue.
	TurnCompleteReasonGeneratedOther TurnCompleteReason = "GENERATED_OTHER"
	// Max regeneration attempts reached.
	TurnCompleteReasonMaxRegenerationReached TurnCompleteReason = "MAX_REGENERATION_REACHED"
)

// The type of the VAD signal.
type VADSignalType string

const (
	// The default is VAD_SIGNAL_TYPE_UNSPECIFIED.
	VADSignalTypeUnspecified VADSignalType = "VAD_SIGNAL_TYPE_UNSPECIFIED"
	// Start of sentence signal.
	VADSignalTypeSos VADSignalType = "VAD_SIGNAL_TYPE_SOS"
	// End of sentence signal.
	VADSignalTypeEos VADSignalType = "VAD_SIGNAL_TYPE_EOS"
)

// The type of the voice activity signal.
type VoiceActivityType string

const (
	// The default is VOICE_ACTIVITY_TYPE_UNSPECIFIED.
	VoiceActivityTypeUnspecified VoiceActivityType = "TYPE_UNSPECIFIED"
	// Start of sentence signal.
	VoiceActivityTypeActivityStart VoiceActivityType = "ACTIVITY_START"
	// End of sentence signal.
	VoiceActivityTypeActivityEnd VoiceActivityType = "ACTIVITY_END"
)

// Start of speech sensitivity.
type StartSensitivity string

const (
	// The default is START_SENSITIVITY_LOW for Gemini Enterprise Agent Platform and START_SENSITIVITY_HIGH
	// for Gemini Live.
	StartSensitivityUnspecified StartSensitivity = "START_SENSITIVITY_UNSPECIFIED"
	// Automatic detection will detect the start of speech more often.
	StartSensitivityHigh StartSensitivity = "START_SENSITIVITY_HIGH"
	// Automatic detection will detect the start of speech less often.
	StartSensitivityLow StartSensitivity = "START_SENSITIVITY_LOW"
)

// End of speech sensitivity.
type EndSensitivity string

const (
	// The default is END_SENSITIVITY_LOW for Gemini Enterprise Agent Platform and END_SENSITIVITY_HIGH
	// for Gemini Live.
	EndSensitivityUnspecified EndSensitivity = "END_SENSITIVITY_UNSPECIFIED"
	// Automatic detection ends speech more often.
	EndSensitivityHigh EndSensitivity = "END_SENSITIVITY_HIGH"
	// Automatic detection ends speech less often.
	EndSensitivityLow EndSensitivity = "END_SENSITIVITY_LOW"
)

// The different ways of handling user activity.
type ActivityHandling string

const (
	// If unspecified, the default behavior is `START_OF_ACTIVITY_INTERRUPTS`.
	ActivityHandlingUnspecified ActivityHandling = "ACTIVITY_HANDLING_UNSPECIFIED"
	// If true, start of activity will interrupt the model's response (also called "barge
	// in"). The model's current response will be cut-off in the moment of the interruption.
	// This is the default behavior.
	ActivityHandlingStartOfActivityInterrupts ActivityHandling = "START_OF_ACTIVITY_INTERRUPTS"
	// The model's response will not be interrupted.
	ActivityHandlingNoInterruption ActivityHandling = "NO_INTERRUPTION"
)

// Options about which input is included in the user's turn.
type TurnCoverage string

const (
	// If unspecified, the default behavior is `TURN_INCLUDES_ONLY_ACTIVITY`.
	TurnCoverageUnspecified TurnCoverage = "TURN_COVERAGE_UNSPECIFIED"
	// The users turn only includes activity since the last turn, excluding inactivity (e.g.
	// silence on the audio stream). This is the default behavior.
	TurnCoverageTurnIncludesOnlyActivity TurnCoverage = "TURN_INCLUDES_ONLY_ACTIVITY"
	// The users turn includes all realtime input since the last turn, including inactivity
	// (e.g. silence on the audio stream).
	TurnCoverageTurnIncludesAllInput TurnCoverage = "TURN_INCLUDES_ALL_INPUT"
	// Includes audio activity and all video since the last turn. With automatic activity
	// detection, audio activity means speech and excludes silence.
	TurnCoverageTurnIncludesAudioActivityAndAllVideo TurnCoverage = "TURN_INCLUDES_AUDIO_ACTIVITY_AND_ALL_VIDEO"
)

// Media resolution for the input media.
type PartMediaResolution struct {
	// Optional. The tokenization quality used for given media.
	Level PartMediaResolutionLevel `json:"level,omitempty"`
	// Optional. Specifies the required sequence length for media tokenization.
	NumTokens *int32 `json:"numTokens,omitempty"`
}

// A predicted server-side `ToolCall` returned from the model.
// This message contains information about a tool that the model wants to invoke.
// The client is NOT expected to execute this `ToolCall`. Instead, the
// client should pass this `ToolCall` back to the API in a subsequent turn
// within a `Content` message, along with the corresponding `ToolResponse`.
type ToolCall struct {
	// Optional. Unique identifier of the tool call. The server returns the tool response
	// with the matching `id`.
	ID string `json:"id,omitempty"`
	// Optional. The type of tool that was called.
	ToolType ToolType `json:"toolType,omitempty"`
	// Optional. The tool call arguments. Example: {"arg1": "value1", "arg2": "value2"}.
	Args map[string]any `json:"args,omitempty"`
}

// The output from a server-side `ToolCall` execution.
// This message contains the results of a tool invocation that was initiated by a
// `ToolCall` from the model. The client should pass this `ToolResponse` back to
// the API in a subsequent turn within a `Content` message, along with the
// corresponding `ToolCall`.
type ToolResponse struct {
	// Optional. The identifier of the tool call this response is for.
	ID string `json:"id,omitempty"`
	// Optional. The type of tool that was called, matching the tool_type in the corresponding
	// ToolCall.
	ToolType ToolType `json:"toolType,omitempty"`
	// Optional. The tool response.
	Response map[string]any `json:"response,omitempty"`
}

// Result of executing the ExecutableCode. Generated only when the `CodeExecution` tool
// is used.
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"`
	// Optional. The identifier of the `ExecutableCode` part this result is for. Only populated
	// if the corresponding `ExecutableCode` has an id. This field is not supported in Vertex
	// AI.
	ID string `json:"id,omitempty"`
}

// Code generated by the model that is meant to be executed, and the result returned
// to the model. Generated when using the `CodeExecution` tool, in which the code will
// be automatically executed, and a corresponding CodeExecutionResult will also be generated.
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"`
	// Optional. Unique identifier of the `ExecutableCode` part. The server returns the
	// `CodeExecutionResult` with the matching `id`. This field is not supported in Vertex
	// AI.
	ID string `json:"id,omitempty"`
}

// URI-based data. A FileData message contains a URI pointing to data of a specific
// media type. It is used to represent images, audio, and video stored in Google Cloud
// Storage.
type FileData struct {
	// Optional. The display name of the file. Used to provide a label or filename to distinguish
	// files. This field is only returned in `PromptMessage` for prompt management. It is
	// used in the Gemini calls only when server side tools (`code_execution`, `google_search`,
	// and `url_context`) are enabled. This field is not supported in Gemini API.
	DisplayName string `json:"displayName,omitempty"`
	// Required. The URI of the file in Google Cloud Storage.
	FileURI string `json:"fileUri,omitempty"`
	// Required. The IANA standard MIME type of the source data.
	MIMEType string `json:"mimeType,omitempty"`
}

// Partial argument value of the function call. This data type is not supported in Gemini
// API.
type PartialArg struct {
	// Optional. Represents a boolean value.
	BoolValue *bool `json:"boolValue,omitempty"`
	// Required. A JSON Path (RFC 9535) to the argument being streamed. https://datatracker.ietf.org/doc/html/rfc9535.
	// e.g. "$.foo.bar[0].data".
	JsonPath string `json:"jsonPath,omitempty"`
	// Optional. Represents a NULL value.
	NULLValue string `json:"nullValue,omitempty"`
	// Optional. Represents a double value.
	NumberValue *float64 `json:"numberValue,omitempty"`
	// Optional. Represents a string value.
	StringValue string `json:"stringValue,omitempty"`
	// Optional. Whether this is not the last part of the same json_path. If true, another
	// PartialArg message for the current json_path is expected to follow.
	WillContinue *bool `json:"willContinue,omitempty"`
}

// A predicted FunctionCall returned from the model that contains a string representing
// the FunctionDeclaration.name and a structured JSON object containing the parameters
// and their values.
type FunctionCall struct {
	// Optional. 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. The function parameters and values in JSON object format. See FunctionDeclaration.parameters
	// for parameter details.
	Args map[string]any `json:"args,omitempty"`
	// Optional. Required. The name of the function to call. Matches [FunctionDeclaration.Name].
	Name string `json:"name,omitempty"`
	// Optional. The partial argument value of the function call. If provided, represents
	// the arguments/fields that are streamed incrementally. This field is not supported
	// in Gemini API.
	PartialArgs []*PartialArg `json:"partialArgs,omitempty"`
	// Optional. Whether this is the last part of the FunctionCall. If true, another partial
	// message for the current FunctionCall is expected to follow. This field is not supported
	// in Gemini API.
	WillContinue *bool `json:"willContinue,omitempty"`
}

// Raw media bytes for function response. Text should not be sent as raw bytes, use
// the 'text' field.
type FunctionResponseBlob struct {
	// Required. The IANA standard MIME type of the source data.
	MIMEType string `json:"mimeType,omitempty"`
	// Required. Raw bytes.
	Data []byte `json:"data,omitempty"`
	// Optional. Display name of the blob. Used to provide a label or filename to distinguish
	// blobs. This field is only returned in PromptMessage for prompt management. It is
	// currently used in the Gemini GenerateContent calls only when server side tools (code_execution,
	// google_search, and url_context) are enabled. This field is not supported in Gemini
	// API.
	DisplayName string `json:"displayName,omitempty"`
}

// URI based data for function response. This data type is not supported in Gemini API.
type FunctionResponseFileData struct {
	// Required. URI.
	FileURI string `json:"fileUri,omitempty"`
	// Required. The IANA standard MIME type of the source data.
	MIMEType string `json:"mimeType,omitempty"`
	// Optional. Display name of the file data. Used to provide a label or filename to distinguish
	// file datas. This field is only returned in PromptMessage for prompt management. It
	// is currently used in the Gemini GenerateContent calls only when server side tools
	// (code_execution, google_search, and url_context) are enabled.
	DisplayName string `json:"displayName,omitempty"`
}

// A datatype containing media that is part of a `FunctionResponse` message. A `FunctionResponsePart`
// consists of data which has an associated datatype. A `FunctionResponsePart` can only
// contain one of the accepted types in `FunctionResponsePart.data`. A `FunctionResponsePart`
// must have a fixed IANA MIME type identifying the type and subtype of the media if
// the `inline_data` field is filled with raw bytes.
type FunctionResponsePart struct {
	// Inline media bytes.
	InlineData *FunctionResponseBlob `json:"inlineData,omitempty"`
	// URI based data. This field is not supported in Gemini API.
	FileData *FunctionResponseFileData `json:"fileData,omitempty"`
}

// NewFunctionResponsePartFromURI builds a FunctionResponsePart from a given file URI and mime type.
func NewFunctionResponsePartFromURI(fileURI, mimeType string) *FunctionResponsePart {
	return &FunctionResponsePart{
		FileData: &FunctionResponseFileData{
			FileURI:  fileURI,
			MIMEType: mimeType,
		},
	}
}

// NewFunctionResponsePartFromBytes builds a FunctionResponsePart from a given byte array and mime type.
func NewFunctionResponsePartFromBytes(data []byte, mimeType string) *FunctionResponsePart {
	return &FunctionResponsePart{
		InlineData: &FunctionResponseBlob{
			Data:     data,
			MIMEType: mimeType,
		},
	}
}

// The result output from a FunctionCall that contains a string representing the FunctionDeclaration.name
// and a structured JSON object containing any output from the function is used as context
// to the model. This should contain the result of a `FunctionCall` made based on model
// prediction.
type FunctionResponse struct {
	// Optional. Signals that function call continues, and more responses will be returned,
	// turning the function call into a generator. Is only applicable to NON_BLOCKING function
	// calls, is ignored otherwise. If set to false, future responses will not be considered.
	// It is allowed to return empty `response` with `will_continue=False` to signal that
	// the function call is finished. This may still trigger the model generation. To avoid
	// triggering the generation and finish the function call, additionally set `scheduling`
	// to `SILENT`. This field is not supported in Vertex AI.
	WillContinue *bool `json:"willContinue,omitempty"`
	// Optional. Specifies how the response should be scheduled in the conversation. Only
	// applicable to NON_BLOCKING function calls, is ignored otherwise. Defaults to WHEN_IDLE.
	Scheduling FunctionResponseScheduling `json:"scheduling,omitempty"`
	// Optional. Ordered `Parts` that constitute a function response. Parts may have different
	// IANA MIME types.
	Parts []*FunctionResponsePart `json:"parts,omitempty"`
	// Optional. 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"`
}

// A content blob. A Blob contains data of a specific media type. It is used to represent
// images, audio, and video.
type Blob struct {
	// Required. The raw bytes of the data.
	Data []byte `json:"data,omitempty"`
	// Optional. The display name of the blob. Used to provide a label or filename to distinguish
	// blobs. This field is only returned in `PromptMessage` for prompt management. It is
	// used in the Gemini calls only when server-side tools (`code_execution`, `google_search`,
	// and `url_context`) are enabled. This field is not supported in Gemini API.
	DisplayName string `json:"displayName,omitempty"`
	// Required. The IANA standard MIME type of the source data.
	MIMEType string `json:"mimeType,omitempty"`
}

// Provides metadata for a video, including the start and end offsets for clipping and
// the frame rate.
type VideoMetadata struct {
	// Optional. The end offset of the video.
	EndOffset time.Duration `json:"endOffset,omitempty"`
	// Optional. The frame rate of the video sent to the model. If not specified, the default
	// value is 1.0. The valid range is (0.0, 24.0].
	FPS *float64 `json:"fps,omitempty"`
	// Optional. The start offset of the video.
	StartOffset time.Duration `json:"startOffset,omitempty"`
}

func (c *VideoMetadata) UnmarshalJSON(data []byte) error {
	type Alias VideoMetadata
	aux := &struct {
		EndOffset   string `json:"endOffset,omitempty"`
		StartOffset string `json:"startOffset,omitempty"`
		*Alias
	}{
		Alias: (*Alias)(c),
	}

	if err := json.Unmarshal(data, &aux); err != nil {
		return err
	}

	if aux.EndOffset != "" {
		d, err := time.ParseDuration(aux.EndOffset)
		if err != nil {
			return err
		}
		c.EndOffset = d
	}

	if aux.StartOffset != "" {
		d, err := time.ParseDuration(aux.StartOffset)
		if err != nil {
			return err
		}
		c.StartOffset = d
	}

	return nil
}

func (c *VideoMetadata) MarshalJSON() ([]byte, error) {
	type Alias VideoMetadata
	aux := &struct {
		EndOffset   string `json:"endOffset,omitempty"`
		StartOffset string `json:"startOffset,omitempty"`
		*Alias
	}{
		Alias: (*Alias)(c),
	}

	if c.StartOffset != 0 {
		aux.StartOffset = fmt.Sprintf("%.0fs", c.StartOffset.Seconds())
	}
	if c.EndOffset != 0 {
		aux.EndOffset = fmt.Sprintf("%.0fs", c.EndOffset.Seconds())
		if aux.StartOffset == "" {
			aux.StartOffset = "0s"
		}
	}

	return json.Marshal(aux)
}

// 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 {
	// Optional. Media resolution for the input media.
	MediaResolution *PartMediaResolution `json:"mediaResolution,omitempty"`
	// Optional. The result of executing the ExecutableCode.
	CodeExecutionResult *CodeExecutionResult `json:"codeExecutionResult,omitempty"`
	// Optional. Code generated by the model that is intended to be executed.
	ExecutableCode *ExecutableCode `json:"executableCode,omitempty"`
	// Optional. The URI-based data of the part. This can be used to include files from
	// Google Cloud Storage.
	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. The inline data content of the part. This can be used to include images,
	// audio, or video in a request.
	InlineData *Blob `json:"inlineData,omitempty"`
	// Optional. The text content of the part. When sent from the VSCode Gemini Code Assist
	// extension, references to @mentioned items will be converted to markdown boldface
	// text. For example `@my-repo` will be converted to and sent as `**my-repo**` by the
	// IDE agent.
	Text string `json:"text,omitempty"`
	// Optional. Indicates whether the `part` represents the model's thought process or
	// reasoning.
	Thought bool `json:"thought,omitempty"`
	// Optional. An opaque signature for the thought so it can be reused in subsequent requests.
	ThoughtSignature []byte `json:"thoughtSignature,omitempty"`
	// Optional. Video metadata. The metadata should only be specified while the video data
	// is presented in inline_data or file_data.
	VideoMetadata *VideoMetadata `json:"videoMetadata,omitempty"`
	// Optional. Server-side tool call. This field is populated when the model predicts
	// a tool invocation that should be executed on the server. The client is expected to
	// echo this message back to the API.
	ToolCall *ToolCall `json:"toolCall,omitempty"`
	// Optional. The output from a server-side ToolCall execution. This field is populated
	// by the client with the results of executing the corresponding ToolCall.
	ToolResponse *ToolResponse `json:"toolResponse,omitempty"`
	// Custom metadata associated with the Part. Agents using genai.Part as content representation
	// may need to keep track of the additional information. For example it can be name
	// of a file/source from which the Part originates or a way to multiplex multiple Part
	// streams. This field is not supported in Vertex AI.
	PartMetadata map[string]any `json:"partMetadata,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,
		},
	}
}

// NewPartFromFile builds a Part from a given [File].
func NewPartFromFile(file File) *Part {
	return &Part{
		FileData: &FileData{
			FileURI:  file.URI,
			MIMEType: file.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 [FunctionCall] Part from the given function name and args.
func NewPartFromFunctionCall(name string, args map[string]any) *Part {
	return &Part{
		FunctionCall: &FunctionCall{
			Name: name,
			Args: args,
		},
	}
}

// NewPartFromFunctionResponse builds a [FunctionResponse] Part from the given function name and response.
func NewPartFromFunctionResponse(name string, response map[string]any) *Part {
	return &Part{
		FunctionResponse: &FunctionResponse{
			Name:     name,
			Response: response,
		},
	}
}

// NewPartFromFunctionResponseWithParts builds a [FunctionResponse] Part from the given function name, response and function response parts.
func NewPartFromFunctionResponseWithParts(name string, response map[string]any, parts []*FunctionResponsePart) *Part {
	return &Part{
		FunctionResponse: &FunctionResponse{
			Name:     name,
			Response: response,
			Parts:    parts,
		},
	}
}

// NewPartFromExecutableCode builds a [ExecutableCode] Part from a single piece of source code in the given [Language].
func NewPartFromExecutableCode(code string, language Language) *Part {
	return &Part{
		ExecutableCode: &ExecutableCode{
			Code:     code,
			Language: language,
		},
	}
}

// NewPartFromCodeExecutionResult builds a [CodeExecutionResult] Part from the given [Outcome] and std 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 {
	// Optional. 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'. If not set,
	// the service will default to 'user'.
	Role string `json:"role,omitempty"`
}

type Role string

const (
	RoleUser  = "user"
	RoleModel = "model"
)

func roleString(role Role) string {
	if role == "" {
		return "user"
	}
	return string(role)
}

// NewContentFromParts builds a Content from a list of parts and a [Role].
// If role is the empty string, it defaults to [RoleUser].
func NewContentFromParts(parts []*Part, role Role) *Content {
	return &Content{
		Parts: parts,
		Role:  roleString(role),
	}
}

// NewContentFromText builds a Content from a text string.
// If role is the empty string, it defaults to [RoleUser].
func NewContentFromText(text string, role Role) *Content {
	return &Content{
		Parts: []*Part{
			NewPartFromText(text),
		},
		Role: roleString(role),
	}
}

// NewContentFromBytes builds a Content from a byte slice and mime type.
// If role is the empty string, it defaults to [RoleUser].
func NewContentFromBytes(data []byte, mimeType string, role Role) *Content {
	return &Content{
		Parts: []*Part{
			NewPartFromBytes(data, mimeType),
		},
		Role: roleString(role),
	}
}

// NewContentFromURI builds a Content from a file URI and mime type.
// If role is the empty string, it defaults to [RoleUser].
func NewContentFromURI(fileURI, mimeType string, role Role) *Content {
	return &Content{
		Parts: []*Part{
			NewPartFromURI(fileURI, mimeType),
		},
		Role: roleString(role),
	}
}

// NewContentFromFunctionCall builds a Content from a single [FunctionCall] given the function name and args.
// If role is the empty string, it defaults to [RoleUser].
func NewContentFromFunctionCall(name string, args map[string]any, role Role) *Content {
	return &Content{
		Parts: []*Part{
			NewPartFromFunctionCall(name, args),
		},
		Role: roleString(role),
	}
}

// NewContentFromFunctionResponse builds a Content from a single [FunctionResponse] given the function name and response.
// If role is the empty string, it defaults to [RoleUser].
func NewContentFromFunctionResponse(name string, response map[string]any, role Role) *Content {
	return &Content{
		Parts: []*Part{
			NewPartFromFunctionResponse(name, response),
		},
		Role: roleString(role),
	}
}

// NewContentFromExecutableCode builds a Content from a single piece of source code in the given [Language].
// If role is the empty string, it defaults to [RoleUser].
func NewContentFromExecutableCode(code string, language Language, role Role) *Content {
	return &Content{
		Parts: []*Part{
			NewPartFromExecutableCode(code, language),
		},
		Role: roleString(role),
	}
}

// NewContentFromCodeExecutionResult builds a Content from a given [Outcome] and std output of the code execution.
// If role is the empty string, it defaults to [RoleUser].
func NewContentFromCodeExecutionResult(outcome Outcome, output string, role Role) *Content {
	return &Content{
		Parts: []*Part{
			NewPartFromCodeExecutionResult(outcome, output),
		},
		Role: roleString(role),
	}
}

// HTTP options to be used in each of the requests.
type HTTPOptions struct {
	// Optional. BaseURL specifies the base URL for the API endpoint. If empty, defaults
	// to "https://generativelanguage.googleapis.com/" for the Gemini API backend, and location-specific
	// Gemini Enterprise Agent Platform endpoint (e.g., "https://us-central1-aiplatform.googleapis.com/
	BaseURL string `json:"baseUrl,omitempty"`
	// Optional. BaseURL specifies the base URL for the API endpoint. If empty, defaults
	// to "https://generativelanguage.googleapis.com/" for the Gemini API backend, and location-specific
	// Gemini Enterprise Agent Platform endpoint (e.g., "https://us-central1-aiplatform.googleapis.com/
	BaseURLResourceScope ResourceScope `json:"baseUrlResourceScope,omitempty"`
	// Optional. APIVersion specifies the version of the API to use. If empty, defaults
	// to "v1beta" for Gemini API and "v1beta1" for Gemini Enterprise Agent Platform.
	APIVersion string `json:"apiVersion,omitempty"`
	// Optional. Additional HTTP headers to be sent with the request.
	Headers http.Header `json:"headers,omitempty"`
	// Optional. Timeout for the request in milliseconds.
	Timeout *time.Duration `json:"timeout,omitempty"`
	// Optional. Extra parameters to add to the request body.
	// The structure must match the backend API's request structure.
	//   - Gemini Enterprise Agent Platform backend API docs: https://cloud.google.com/vertex-ai/docs/reference/rest
	//   - GeminiAPI backend API docs: https://ai.google.dev/api/rest
	ExtraBody map[string]any `json:"extraBody,omitempty"`
	// Optional. A function that allows for request body customization.
	// It is executed after ExtraBody has been merged, offering more advanced
	// control over the request body than the static ExtraBody.
	ExtrasRequestProvider ExtrasRequestProvider `json:"-"`
}

// ExtrasRequestProvider provides a way to dynamically modify the request body
// before it is sent. It is a function that takes the request body and returns
// the modified body. This is useful for advanced scenarios where request
// parameters need to be added based on logic that cannot
// be handled by a static map.
type ExtrasRequestProvider = func(body map[string]any) map[string]any

type UrlRetrievalStatus = URLRetrievalStatus

// Config for thinking feature.
//
// This struct will be deprecated. Please use ThinkingConfig instead.
type GenerationConfigThinkingConfig struct {
	ThinkingConfig
}

// Schema is used to define the format of input/output data.
// Represents a select subset of an [OpenAPI 3.0 schema
// object](https://spec.openapis.org/oas/v3.0.3#schema-object). More fields may
// be added in the future as needed.
// You can find more details and examples at https://spec.openapis.org/oas/v3.0.3.html#schema-object
type Schema struct {
	// Optional. The instance must be valid against any (one or more) of the subschemas
	// listed in `any_of`.
	AnyOf []*Schema `json:"anyOf,omitempty"`
	// Optional. Default value to use if the field is not specified.
	Default any `json:"default,omitempty"`
	// Optional. Describes the data. The model uses this field to understand the purpose
	// of the schema and how to use it. It is a best practice to provide a clear and descriptive
	// explanation for the schema and its properties here, rather than in the prompt.
	Description string `json:"description,omitempty"`
	// Optional. Possible values of the field. This field can be used to restrict a value
	// to a fixed set of values. To mark a field as an enum, set `format` to `enum` and
	// provide the list of possible values in `enum`. For example: 1. To define directions:
	// `{type:STRING, format:enum, enum:["EAST", "NORTH", "SOUTH", "WEST"]}` 2. To define
	// apartment numbers: `{type:INTEGER, format:enum, enum:["101", "201", "301"]}`
	Enum []string `json:"enum,omitempty"`
	// Optional. Example of an instance of this schema.
	Example any `json:"example,omitempty"`
	// Optional. The format of the data. For `NUMBER` type, format can be `float` or `double`.
	// For `INTEGER` type, format can be `int32` or `int64`. For `STRING` type, format can
	// be `email`, `byte`, `date`, `date-time`, `password`, and other formats to further
	// refine the data type.
	Format string `json:"format,omitempty"`
	// Optional. If type is `ARRAY`, `items` specifies the schema of elements in the array.
	Items *Schema `json:"items,omitempty"`
	// Optional. If type is `ARRAY`, `max_items` specifies the maximum number of items in
	// an array.
	MaxItems *int64 `json:"maxItems,omitempty"`
	// Optional. If type is `STRING`, `max_length` specifies the maximum length of the string.
	MaxLength *int64 `json:"maxLength,omitempty"`
	// Optional. If type is `OBJECT`, `max_properties` specifies the maximum number of properties
	// that can be provided.
	MaxProperties *int64 `json:"maxProperties,omitempty"`
	// Optional. If type is `INTEGER` or `NUMBER`, `maximum` specifies the maximum allowed
	// value.
	Maximum *float64 `json:"maximum,omitempty"`
	// Optional. If type is `ARRAY`, `min_items` specifies the minimum number of items in
	// an array.
	MinItems *int64 `json:"minItems,omitempty"`
	// Optional. If type is `STRING`, `min_length` specifies the minimum length of the string.
	MinLength *int64 `json:"minLength,omitempty"`
	// Optional. If type is `OBJECT`, `min_properties` specifies the minimum number of properties
	// that can be provided.
	MinProperties *int64 `json:"minProperties,omitempty"`
	// Optional. Minimum value of the Type.INTEGER and Type.NUMBER.
	Minimum *float64 `json:"minimum,omitempty"`
	// Optional. Indicates if the value of this field can be null.
	Nullable *bool `json:"nullable,omitempty"`
	// Optional. If type is `STRING`, `pattern` specifies a regular expression that the
	// string must match.
	Pattern string `json:"pattern,omitempty"`
	// Optional. If type is `OBJECT`, `properties` is a map of property names to schema
	// definitions for each property of the object.
	Properties map[string]*Schema `json:"properties,omitempty"`
	// Optional. Order of properties displayed or used where order matters. This is not
	// a standard field in OpenAPI specification, but can be used to control the order of
	// properties.
	PropertyOrdering []string `json:"propertyOrdering,omitempty"`
	// Optional. If type is `OBJECT`, `required` lists the names of properties that must
	// be present.
	Required []string `json:"required,omitempty"`
	// Optional. Title for the schema.
	Title string `json:"title,omitempty"`
	// Optional. Data type of the schema field.
	Type Type `json:"type,omitempty"`
}

// Config for model selection.
type ModelSelectionConfig struct {
	// Optional. Options for feature selection preference.
	FeatureSelectionPreference FeatureSelectionPreference `json:"featureSelectionPreference,omitempty"`
}

// Config for authentication with API key. This data type is not supported in Gemini
// API.
type APIKeyConfig struct {
	// Optional. The name of the SecretManager secret version resource storing the API key.
	// Format: `projects/{project}/secrets/{secrete}/versions/{version}` - If both `api_key_secret`
	// and `api_key_string` are specified, this field takes precedence over `api_key_string`.
	// - If specified, the `secretmanager.versions.access` permission should be granted
	// to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents)
	// on the specified resource.
	APIKeySecret string `json:"apiKeySecret,omitempty"`
	// Optional. The API key to be used in the request directly.
	APIKeyString string `json:"apiKeyString,omitempty"`
	// Optional. The location of the API key.
	HTTPElementLocation HTTPElementLocation `json:"httpElementLocation,omitempty"`
	// Optional. The parameter name of the API key. E.g. If the API request is "https://example.com/act?api_key=",
	// "api_key" would be the parameter name.
	Name string `json:"name,omitempty"`
}

// Config for Google Service Account Authentication. This data type is not supported
// in Gemini API.
type AuthConfigGoogleServiceAccountConfig struct {
	// Optional. The service account that the extension execution service runs as. - If
	// the service account is specified, the `iam.serviceAccounts.getAccessToken` permission
	// should be granted to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents)
	// on the specified service account. - If not specified, the Vertex AI Extension Service
	// Agent will be used to execute the Extension.
	ServiceAccount string `json:"serviceAccount,omitempty"`
}

// Config for HTTP Basic Authentication. This data type is not supported in Gemini API.
type AuthConfigHTTPBasicAuthConfig struct {
	// Required. The name of the SecretManager secret version resource storing the base64
	// encoded credentials. Format: `projects/{project}/secrets/{secrete}/versions/{version}`
	// - If specified, the `secretmanager.versions.access` permission should be granted
	// to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents)
	// on the specified resource.
	CredentialSecret string `json:"credentialSecret,omitempty"`
}

// Config for user oauth. This data type is not supported in Gemini API.
type AuthConfigOauthConfig struct {
	// Access token for extension endpoint. Only used to propagate token from [[ExecuteExtensionRequest.runtime_auth_config]]
	// at request time.
	AccessToken string `json:"accessToken,omitempty"`
	// The service account used to generate access tokens for executing the Extension. -
	// If the service account is specified, the `iam.serviceAccounts.getAccessToken` permission
	// should be granted to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents)
	// on the provided service account.
	ServiceAccount string `json:"serviceAccount,omitempty"`
}

// Config for user OIDC auth. This data type is not supported in Gemini API.
type AuthConfigOidcConfig struct {
	// OpenID Connect formatted ID token for extension endpoint. Only used to propagate
	// token from [[ExecuteExtensionRequest.runtime_auth_config]] at request time.
	IDToken string `json:"idToken,omitempty"`
	// The service account used to generate an OpenID Connect (OIDC)-compatible JWT token
	// signed by the Google OIDC Provider (accounts.google.com) for extension endpoint (https://cloud.google.com/iam/docs/create-short-lived-credentials-direct#sa-credentials-oidc).
	// - The audience for the token will be set to the URL in the server URL defined in
	// the OpenAPI spec. - If the service account is provided, the service account should
	// grant `iam.serviceAccounts.getOpenIDToken` permission to Vertex AI Extension Service
	// Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents).
	ServiceAccount string `json:"serviceAccount,omitempty"`
}

// The authentication config to access the API.
type AuthConfig struct {
	// Optional. The authentication config to access the API. Only API key is supported.
	// This field is not supported in Gemini API.
	APIKey string `json:"apiKey,omitempty"`
	// Config for API key auth.
	APIKeyConfig *APIKeyConfig `json:"apiKeyConfig,omitempty"`
	// Type of auth scheme.
	AuthType AuthType `json:"authType,omitempty"`
	// Config for Google Service Account auth.
	GoogleServiceAccountConfig *AuthConfigGoogleServiceAccountConfig `json:"googleServiceAccountConfig,omitempty"`
	// Config for HTTP Basic auth.
	HTTPBasicAuthConfig *AuthConfigHTTPBasicAuthConfig `json:"httpBasicAuthConfig,omitempty"`
	// Config for user oauth.
	OauthConfig *AuthConfigOauthConfig `json:"oauthConfig,omitempty"`
	// Config for user OIDC auth.
	OidcConfig *AuthConfigOidcConfig `json:"oidcConfig,omitempty"`
}

// Tool to retrieve knowledge from Google Maps.
type GoogleMaps struct {
	// Optional. The authentication config to access the API. Only API key is supported.
	// This field is not supported in Gemini API.
	AuthConfig *AuthConfig `json:"authConfig,omitempty"`
	// Optional. Deprecated. The Google Maps contextual widget behavior in Grounding with
	// Google Maps is being deprecated; this field is planned for removal and no longer
	// has any effect once removed. Optional. Whether to return a widget context token in
	// the GroundingMetadata of the response.
	EnableWidget *bool `json:"enableWidget,omitempty"`
}

// The API secret. This data type is not supported in Gemini API.
type APIAuthAPIKeyConfig struct {
	// Required. The SecretManager secret version resource name storing API key. e.g. projects/{project}/secrets/{secret}/versions/{version}
	APIKeySecretVersion string `json:"apiKeySecretVersion,omitempty"`
	// The API key string. Either this or `api_key_secret_version` must be set.
	APIKeyString string `json:"apiKeyString,omitempty"`
}

// The generic reusable API auth config. Deprecated. Please use AuthConfig (google/cloud/aiplatform/master/auth.proto)
// instead. This data type is not supported in Gemini API.
type APIAuth struct {
	// The API secret.
	APIKeyConfig *APIAuthAPIKeyConfig `json:"apiKeyConfig,omitempty"`
}

// The search parameters to use for the ELASTIC_SEARCH spec. This data type is not supported
// in Gemini API.
type ExternalAPIElasticSearchParams struct {
	// The ElasticSearch index to use.
	Index string `json:"index,omitempty"`
	// Optional. Number of hits (chunks) to request. When specified, it is passed to Elasticsearch
	// as the `num_hits` param.
	NumHits *int32 `json:"numHits,omitempty"`
	// The ElasticSearch search template to use.
	SearchTemplate string `json:"searchTemplate,omitempty"`
}

// The search parameters to use for SIMPLE_SEARCH spec. This data type is not supported
// in Gemini API.
type ExternalAPISimpleSearchParams struct {
}

// Retrieve from data source powered by external API for grounding. The external API
// is not owned by Google, but need to follow the pre-defined API spec. This data type
// is not supported in Gemini API.
type ExternalAPI struct {
	// The authentication config to access the API. Deprecated. Please use auth_config instead.
	APIAuth *APIAuth `json:"apiAuth,omitempty"`
	// The API spec that the external API implements.
	APISpec APISpec `json:"apiSpec,omitempty"`
	// The authentication config to access the API.
	AuthConfig *AuthConfig `json:"authConfig,omitempty"`
	// Parameters for the elastic search API.
	ElasticSearchParams *ExternalAPIElasticSearchParams `json:"elasticSearchParams,omitempty"`
	// The endpoint of the external API. The system will call the API at this endpoint to
	// retrieve the data for grounding. Example: https://acme.com:443/search
	Endpoint string `json:"endpoint,omitempty"`
	// Parameters for the simple search API.
	SimpleSearchParams *ExternalAPISimpleSearchParams `json:"simpleSearchParams,omitempty"`
}

// Define data stores within engine to filter on in a search call and configurations
// for those data stores. For more information, see https://cloud.google.com/generative-ai-app-builder/docs/reference/rpc/google.cloud.discoveryengine.v1#datastorespec.
// This data type is not supported in Gemini API.
type VertexAISearchDataStoreSpec struct {
	// Full resource name of DataStore, such as Format: `projects/{project}/locations/{location}/collections/{collection}/dataStores/{dataStore}`
	DataStore string `json:"dataStore,omitempty"`
	// Optional. Filter specification to filter documents in the data store specified by
	// data_store field. For more information on filtering, see [Filtering](https://cloud.google.com/generative-ai-app-builder/docs/filter-search-metadata)
	Filter string `json:"filter,omitempty"`
}

// Retrieve from Vertex AI Search datastore or engine for grounding. datastore and engine
// are mutually exclusive. See https://cloud.google.com/products/agent-builder. This
// data type is not supported in Gemini API.
type VertexAISearch struct {
	// Specifications that define the specific DataStores to be searched, along with configurations
	// for those data stores. This is only considered for Engines with multiple data stores.
	// It should only be set if engine is used.
	DataStoreSpecs []*VertexAISearchDataStoreSpec `json:"dataStoreSpecs,omitempty"`
	// Optional. Fully-qualified Vertex AI Search data store resource ID. Format: `projects/{project}/locations/{location}/collections/{collection}/dataStores/{dataStore}`
	Datastore string `json:"datastore,omitempty"`
	// Optional. Fully-qualified Vertex AI Search engine resource ID. Format: `projects/{project}/locations/{location}/collections/{collection}/engines/{engine}`
	Engine string `json:"engine,omitempty"`
	// Optional. Filter strings to be passed to the search API.
	Filter string `json:"filter,omitempty"`
	// Optional. Number of search results to return per query. The default value is 10.
	// The maximumm allowed value is 10.
	MaxResults *int32 `json:"maxResults,omitempty"`
}

// The definition of the RAG resource. This data type is not supported in Gemini API.
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"`
}

// Config for filters. This data type is not supported in Gemini API.
type RAGRetrievalConfigFilter struct {
	// Optional. String for metadata filtering.
	MetadataFilter string `json:"metadataFilter,omitempty"`
	// Optional. Only returns contexts with vector distance smaller than the threshold.
	VectorDistanceThreshold *float64 `json:"vectorDistanceThreshold,omitempty"`
	// Optional. Only returns contexts with vector similarity larger than the threshold.
	VectorSimilarityThreshold *float64 `json:"vectorSimilarityThreshold,omitempty"`
}

// Config for Hybrid Search. This data type is not supported in Gemini API.
type RAGRetrievalConfigHybridSearch struct {
	// Optional. Alpha value controls the weight between dense and sparse vector search
	// results. The range is [0, 1], while 0 means sparse vector search only and 1 means
	// dense vector search only. The default value is 0.5 which balances sparse and dense
	// vector search equally.
	Alpha *float32 `json:"alpha,omitempty"`
}

// Config for LlmRanker. This data type is not supported in Gemini API.
type RAGRetrievalConfigRankingLlmRanker struct {
	// Optional. The model name used for ranking. See [Supported models](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#supported-models).
	ModelName string `json:"modelName,omitempty"`
}

// Config for Rank Service. This data type is not supported in Gemini API.
type RAGRetrievalConfigRankingRankService struct {
	// Optional. The model name of the rank service. Format: `semantic-ranker-512@latest`
	ModelName string `json:"modelName,omitempty"`
}

// Config for ranking and reranking. This data type is not supported in Gemini API.
type RAGRetrievalConfigRanking struct {
	// Optional. Config for LlmRanker.
	LlmRanker *RAGRetrievalConfigRankingLlmRanker `json:"llmRanker,omitempty"`
	// Optional. Config for Rank Service.
	RankService *RAGRetrievalConfigRankingRankService `json:"rankService,omitempty"`
}

// Specifies the context retrieval config. This data type is not supported in Gemini
// API.
type RAGRetrievalConfig struct {
	// Optional. Config for filters.
	Filter *RAGRetrievalConfigFilter `json:"filter,omitempty"`
	// Optional. Config for Hybrid Search.
	HybridSearch *RAGRetrievalConfigHybridSearch `json:"hybridSearch,omitempty"`
	// Optional. Config for ranking and reranking.
	Ranking *RAGRetrievalConfigRanking `json:"ranking,omitempty"`
	// Optional. The number of contexts to retrieve.
	TopK *int32 `json:"topK,omitempty"`
}

// Retrieve from Vertex RAG Store for grounding. This data type is not supported in
// Gemini API. 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. The retrieval config for the RAG query.
	RAGRetrievalConfig *RAGRetrievalConfig `json:"ragRetrievalConfig,omitempty"`
	// Optional. Number of top k results to return from the selected corpora.
	SimilarityTopK *int32 `json:"similarityTopK,omitempty"`
	// Optional. Currently only supported for Gemini Multimodal Live API. In Gemini Multimodal
	// Live API, if `store_context` bool is specified, Gemini will leverage it to automatically
	// memorize the interactions between the client and Gemini, and retrieve context when
	// needed to augment the response generation for users' ongoing and future interactions.
	StoreContext *bool `json:"storeContext,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. This data
// type is not supported in Gemini API.
type Retrieval struct {
	// Optional. Deprecated. This option is no longer supported.
	DisableAttribution bool `json:"disableAttribution,omitempty"`
	// Use data source powered by external API for grounding.
	ExternalAPI *ExternalAPI `json:"externalApi,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 to support computer use.
type ComputerUse struct {
	// Required. The environment being operated.
	Environment Environment `json:"environment,omitempty"`
	// Optional. By default, [predefined functions](https://cloud.google.com/vertex-ai/generative-ai/docs/computer-use#supported-actions)
	// are included in the final model call. Some of them can be explicitly excluded from
	// being automatically included. This can serve two purposes: 1. Using a more restricted
	// / different action space. 2. Improving the definitions / instructions of predefined
	// functions.
	ExcludedPredefinedFunctions []string `json:"excludedPredefinedFunctions,omitempty"`
	// Optional. Enables the prompt injection detection check on computer-use request.
	EnablePromptInjectionDetection *bool `json:"enablePromptInjectionDetection,omitempty"`
	// Optional. Disabled safety policies for computer use. This field is not supported
	// in Vertex AI.
	DisabledSafetyPolicies []SafetyPolicy `json:"disabledSafetyPolicies,omitempty"`
}

// The FileSearch tool that retrieves knowledge from Semantic Retrieval corpora. Files
// are imported to Semantic Retrieval corpora using the ImportFile API. This data type
// is not supported in Vertex AI.
type FileSearch struct {
	// Required. The names of the file_search_stores to retrieve from. Example: `fileSearchStores/my-file-search-store-123`
	FileSearchStoreNames []string `json:"fileSearchStoreNames,omitempty"`
	// Optional. The number of semantic retrieval chunks to retrieve.
	TopK *int32 `json:"topK,omitempty"`
	// Optional. Metadata filter to apply to the semantic retrieval documents and chunks.
	MetadataFilter string `json:"metadataFilter,omitempty"`
}

// Standard web search for grounding and related configurations. Only text results are
// returned.
type WebSearch struct {
}

// Image search for grounding and related configurations.
type ImageSearch struct {
}

// Different types of search that can be enabled on the GoogleSearch tool.
type SearchTypes struct {
	// Optional. Setting this field enables web search. Only text results are returned.
	WebSearch *WebSearch `json:"webSearch,omitempty"`
	// Optional. Setting this field enables image search. Image bytes are returned.
	ImageSearch *ImageSearch `json:"imageSearch,omitempty"`
}

// Represents a time interval, encoded as a Timestamp start (inclusive) and a Timestamp
// end (exclusive). The start must be less than or equal to the end. When the start
// equals the end, the interval is empty (matches no time). When both start and end
// are unspecified, the interval matches any time.
type Interval struct {
	// Optional. Exclusive end of the interval. If specified, a Timestamp matching this
	// interval will have to be before the end.
	EndTime time.Time `json:"endTime,omitempty"`
	// Optional. Inclusive start of the interval. If specified, a Timestamp matching this
	// interval will have to be the same or after the start.
	StartTime time.Time `json:"startTime,omitempty"`
}

func (i *Interval) UnmarshalJSON(data []byte) error {
	type Alias Interval
	aux := &struct {
		EndTime   *time.Time `json:"endTime,omitempty"`
		StartTime *time.Time `json:"startTime,omitempty"`
		*Alias
	}{
		Alias: (*Alias)(i),
	}

	if err := json.Unmarshal(data, &aux); err != nil {
		return err
	}

	if !reflect.ValueOf(aux.EndTime).IsZero() {
		i.EndTime = time.Time(*aux.EndTime)
	}

	if !reflect.ValueOf(aux.StartTime).IsZero() {
		i.StartTime = time.Time(*aux.StartTime)
	}

	return nil
}

func (i *Interval) MarshalJSON() ([]byte, error) {
	type Alias Interval
	aux := &struct {
		EndTime   *time.Time `json:"endTime,omitempty"`
		StartTime *time.Time `json:"startTime,omitempty"`
		*Alias
	}{
		Alias: (*Alias)(i),
	}

	if !reflect.ValueOf(i.EndTime).IsZero() {
		aux.EndTime = (*time.Time)(&i.EndTime)
	}

	if !reflect.ValueOf(i.StartTime).IsZero() {
		aux.StartTime = (*time.Time)(&i.StartTime)
	}

	return json.Marshal(aux)
}

// GoogleSearch tool type. Tool to support Google Search in Model. Powered by Google.
type GoogleSearch struct {
	// Optional. The set of search types to enable. If not set, web search is enabled by
	// default.
	SearchTypes *SearchTypes `json:"searchTypes,omitempty"`
	// Optional. Sites with confidence level chosen & above this value will be blocked from
	// the search results. This field is not supported in Gemini API.
	BlockingConfidence PhishBlockThreshold `json:"blockingConfidence,omitempty"`
	// Optional. List of domains to be excluded from the search results. The default limit
	// is 2000 domains. Example: ["amazon.com", "facebook.com"]. This field is not supported
	// in Gemini API.
	ExcludeDomains []string `json:"excludeDomains,omitempty"`
	// Optional. Filter search results to a specific time range. If customers set a start
	// time, they must set an end time (and vice versa). This field is not supported in
	// Vertex AI.
	TimeRangeFilter *Interval `json:"timeRangeFilter,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. This data type is not supported in Gemini API.
type ToolCodeExecution struct {
}

// Tool to search public web data, powered by Vertex AI Search and Sec4 compliance.
// This data type is not supported in Gemini API.
type EnterpriseWebSearch struct {
	// Optional. Sites with confidence level chosen & above this value will be blocked from
	// the search results.
	BlockingConfidence PhishBlockThreshold `json:"blockingConfidence,omitempty"`
	// Optional. List of domains to be excluded from the search results. The default limit
	// is 2000 domains.
	ExcludeDomains []string `json:"excludeDomains,omitempty"`
}

// Structured representation of a function declaration as defined by the [OpenAPI 3.0
// specification](https://spec.openapis.org/oas/v3.0.3). Included in this declaration
// are the function name, description, parameters and response type. This FunctionDeclaration
// is a representation of a block of code that can be used as a `Tool` by the model
// and executed by the client.
type FunctionDeclaration struct {
	// 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, colons and dashes, with a maximum
	// length of 128.
	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"`
	// Optional. Describes the parameters to the function in JSON Schema format. The schema
	// must describe an object where the properties are the parameters to the function.
	// For example: ``` { "type": "object", "properties": { "name": { "type": "string" },
	// "age": { "type": "integer" } }, "additionalProperties": false, "required": ["name",
	// "age"], "propertyOrdering": ["name", "age"] } ``` This field is mutually exclusive
	// with `parameters`.
	ParametersJsonSchema any `json:"parametersJsonSchema,omitempty"`
	// Optional. Describes the output from this function in JSON Schema format. Reflects
	// the Open API 3.03 Response Object. The Schema defines the type used for the response
	// value of the function.
	Response *Schema `json:"response,omitempty"`
	// Optional. Describes the output from this function in JSON Schema format. The value
	// specified by the schema is the response value of the function. This field is mutually
	// exclusive with `response`.
	ResponseJsonSchema any `json:"responseJsonSchema,omitempty"`
	// Optional. Specifies the function Behavior. If not specified, the system keeps the
	// current function call behavior. This field is currently only supported by the BidiGenerateContent
	// method.
	Behavior Behavior `json:"behavior,omitempty"`
}

// Describes the options to customize dynamic retrieval.
type DynamicRetrievalConfig struct {
	// Optional. The threshold to be used in dynamic retrieval. If empty, a system default
	// value is used.
	DynamicThreshold *float32 `json:"dynamicThreshold,omitempty"`
	// The mode of the predictor to be used in dynamic retrieval.
	Mode DynamicRetrievalConfigMode `json:"mode,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"`
}

// ParallelAISearch tool type. A tool that uses the Parallel.ai search engine for grounding.
// This data type is not supported in Gemini API.
type ToolParallelAISearch struct {
	// Optional. The API key for ParallelAISearch. If an API key is not provided, the system
	// will attempt to verify access by checking for an active Parallel.ai subscription
	// through the Google Cloud Marketplace. See https://docs.parallel.ai/search/search-quickstart
	// for more details.
	APIKey string `json:"apiKey,omitempty"`
	// Optional. Custom configs for ParallelAISearch. This field can be used to pass any
	// parameter from the Parallel.ai Search API. See the Parallel.ai documentation for
	// the full list of available parameters and their usage: https://docs.parallel.ai/api-reference/search-beta/search
	// Currently only `source_policy`, `excerpts`, `max_results`, `mode`, `fetch_policy`
	// can be set via this field. For example: { "source_policy": { "include_domains": ["google.com",
	// "wikipedia.org"], "exclude_domains": ["example.com"] }, "fetch_policy": { "max_age_seconds":
	// 3600 } }
	CustomConfigs map[string]any `json:"customConfigs,omitempty"`
}

// Tool to support URL context.
type URLContext struct {
}

// A transport that can stream HTTP requests and responses. Next ID: 6. This data type
// is not supported in Vertex AI.
type StreamableHTTPTransport struct {
	// Optional. Optional: Fields for authentication headers, timeouts, etc., if needed.
	Headers map[string]string `json:"headers,omitempty"`
	// Timeout for SSE read operations.
	SseReadTimeout time.Duration `json:"sseReadTimeout,omitempty"`
	// Whether to close the client session when the transport closes.
	TerminateOnClose *bool `json:"terminateOnClose,omitempty"`
	// HTTP timeout for regular operations.
	Timeout time.Duration `json:"timeout,omitempty"`
	// The full URL for the MCPServer endpoint. Example: "https://api.example.com/mcp".
	URL string `json:"url,omitempty"`
}

func (s *StreamableHTTPTransport) UnmarshalJSON(data []byte) error {
	type Alias StreamableHTTPTransport
	aux := &struct {
		SseReadTimeout *InternalDurationJSON `json:"sseReadTimeout,omitempty"`
		Timeout        *InternalDurationJSON `json:"timeout,omitempty"`
		*Alias
	}{
		Alias: (*Alias)(s),
	}

	if err := json.Unmarshal(data, &aux); err != nil {
		return err
	}

	if !reflect.ValueOf(aux.SseReadTimeout).IsZero() {
		s.SseReadTimeout = time.Duration(*aux.SseReadTimeout)
	}

	if !reflect.ValueOf(aux.Timeout).IsZero() {
		s.Timeout = time.Duration(*aux.Timeout)
	}

	return nil
}

func (s *StreamableHTTPTransport) MarshalJSON() ([]byte, error) {
	type Alias StreamableHTTPTransport
	aux := &struct {
		SseReadTimeout *InternalDurationJSON `json:"sseReadTimeout,omitempty"`
		Timeout        *InternalDurationJSON `json:"timeout,omitempty"`
		*Alias
	}{
		Alias: (*Alias)(s),
	}

	if !reflect.ValueOf(s.SseReadTimeout).IsZero() {
		aux.SseReadTimeout = (*InternalDurationJSON)(&s.SseReadTimeout)
	}

	if !reflect.ValueOf(s.Timeout).IsZero() {
		aux.Timeout = (*InternalDurationJSON)(&s.Timeout)
	}

	return json.Marshal(aux)
}

// A MCPServer is a server that can be called by the model to perform actions. It is
// a server that implements the MCP protocol. Next ID: 6. This data type is not supported
// in Vertex AI.
type MCPServer struct {
	// The name of the MCPServer.
	Name string `json:"name,omitempty"`
	// A transport that can stream HTTP requests and responses.
	StreamableHTTPTransport *StreamableHTTPTransport `json:"streamableHttpTransport,omitempty"`
}

// ExaAISearch tool type. A tool that uses the Exa.ai search engine for grounding. This
// data type is not supported in Gemini API.
type ToolExaAISearch struct {
	// Required. The API key for ExaAISearch.
	APIKey string `json:"apiKey,omitempty"`
	// Optional. This field can be used to pass any parameter from the Exa.ai Search API.
	CustomConfigs map[string]any `json:"customConfigs,omitempty"`
}

// Tool details of a tool that the model may use to generate a response.
type Tool struct {
	// 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. This field is not supported in Gemini API.
	Retrieval *Retrieval `json:"retrieval,omitempty"`
	// Optional. Tool to support the model interacting directly with the computer. If enabled,
	// it automatically populates computer-use specific Function Declarations.
	ComputerUse *ComputerUse `json:"computerUse,omitempty"`
	// Optional. FileSearch tool type. Tool to retrieve knowledge from Semantic Retrieval
	// corpora. This field is not supported in Vertex AI.
	FileSearch *FileSearch `json:"fileSearch,omitempty"`
	// Optional. GoogleSearch tool type. Tool to support Google Search in Model. Powered
	// by Google.
	GoogleSearch *GoogleSearch `json:"googleSearch,omitempty"`
	// Optional. Tool that allows grounding the model's response with
	// geospatial context related to the user's query.
	GoogleMaps *GoogleMaps `json:"googleMaps,omitempty"`
	// Optional. CodeExecution tool type. Enables the model to execute code as part of generation.
	CodeExecution *ToolCodeExecution `json:"codeExecution,omitempty"`
	// Optional. Tool to support searching public web data, powered by Vertex AI Search
	// and Sec4 compliance. This field is not supported in Gemini API.
	EnterpriseWebSearch *EnterpriseWebSearch `json:"enterpriseWebSearch,omitempty"`
	// Optional. Function tool type. One or more function declarations to be passed to the
	// model along with the current user query. Model may decide to call a subset of these
	// functions by populating FunctionCall in the response. User should provide a FunctionResponse
	// for each function call in the next turn. Based on the function responses, Model will
	// generate the final response back to the user. Maximum 512 function declarations can
	// be provided.
	FunctionDeclarations []*FunctionDeclaration `json:"functionDeclarations,omitempty"`
	// Optional. Specialized retrieval tool that is powered by Google Search.
	GoogleSearchRetrieval *GoogleSearchRetrieval `json:"googleSearchRetrieval,omitempty"`
	// Optional. If specified, Vertex AI will use Parallel.ai to search for information
	// to answer user queries. The search results will be grounded on Parallel.ai and presented
	// to the model for response generation. This field is not supported in Gemini API.
	ParallelAISearch *ToolParallelAISearch `json:"parallelAiSearch,omitempty"`
	// Optional. Tool to support URL context retrieval.
	URLContext *URLContext `json:"urlContext,omitempty"`
	// Optional. MCP Servers to connect to. This field is not supported in Vertex AI.
	MCPServers []*MCPServer `json:"mcpServers,omitempty"`
	// Optional. Uses Exa.ai to search for information to answer user queries. The search
	// results will be grounded on Exa.ai and presented to the model for response generation.
	// This field is not supported in Gemini API.
	ExaAISearch *ToolExaAISearch `json:"exaAiSearch,omitempty"`
}

// The signature of the voice consent check.
type VoiceConsentSignature struct {
	// Optional. The signature string.
	Signature string `json:"signature,omitempty"`
}

// The configuration for the replicated voice to use.
type ReplicatedVoiceConfig struct {
	// Optional. The mimetype of the voice sample. The only currently supported
	// value is `audio/wav`. This represents 16-bit signed little-endian wav
	// data, with a 24kHz sampling rate.
	MIMEType string `json:"mimeType,omitempty"`
	// Optional. The sample of the custom voice.
	VoiceSampleAudio []byte `json:"voiceSampleAudio,omitempty"`
	// Optional. Recorded consent verifying ownership of the voice. This
	// represents 16-bit signed little-endian wav data, with a 24kHz sampling
	// rate.
	ConsentAudio []byte `json:"consentAudio,omitempty"`
	// Optional. Signature of a previously verified consent audio. This should be
	// populated with a signature generated by the server for a previous
	// request containing the consent_audio field. When provided, the
	// signature is verified instead of the consent_audio field to reduce
	// latency. Requests will fail if the signature is invalid or expired.
	VoiceConsentSignature *VoiceConsentSignature `json:"voiceConsentSignature,omitempty"`
}

// Configuration for a prebuilt voice.
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 {
	// Optional. The configuration for a replicated voice, which is a clone of a
	// user's voice that can be used for speech synthesis. If this is unset, a
	// default voice is used.
	ReplicatedVoiceConfig *ReplicatedVoiceConfig `json:"replicatedVoiceConfig,omitempty"`
	// The configuration for a prebuilt voice.
	PrebuiltVoiceConfig *PrebuiltVoiceConfig `json:"prebuiltVoiceConfig,omitempty"`
}

// Configuration for a single speaker in a multi-speaker setup.
type SpeakerVoiceConfig struct {
	// Required. The name of the speaker. This should be the same as the speaker name used
	// in the prompt.
	Speaker string `json:"speaker,omitempty"`
	// Required. The configuration for the voice of this speaker.
	VoiceConfig *VoiceConfig `json:"voiceConfig,omitempty"`
}

// Configuration for a multi-speaker text-to-speech request.
type MultiSpeakerVoiceConfig struct {
	// Required. A list of configurations for the voices of the speakers. Exactly two speaker
	// voice configurations must be provided.
	SpeakerVoiceConfigs []*SpeakerVoiceConfig `json:"speakerVoiceConfigs,omitempty"`
}

// Config for speech generation and transcription.
type SpeechConfig struct {
	// Optional. The configuration in case of single-voice output.
	VoiceConfig *VoiceConfig `json:"voiceConfig,omitempty"`
	// Optional. The language code (ISO 639-1) for the speech synthesis.
	LanguageCode string `json:"languageCode,omitempty"`
	// The configuration for a multi-speaker text-to-speech request. This field is mutually
	// exclusive with `voice_config`.
	MultiSpeakerVoiceConfig *MultiSpeakerVoiceConfig `json:"multiSpeakerVoiceConfig,omitempty"`
}

// The thinking features configuration.
type ThinkingConfig struct {
	// Optional. 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"`
	// Optional. Indicates the thinking budget in tokens.
	ThinkingBudget *int32 `json:"thinkingBudget,omitempty"`
	// Optional. The number of thoughts tokens that the model should generate.
	ThinkingLevel ThinkingLevel `json:"thinkingLevel,omitempty"`
}

// The image output format for generated images. This data type is not supported in
// Gemini API.
type ImageConfigImageOutputOptions struct {
	// Optional. The compression quality of the output image.
	CompressionQuality *int32 `json:"compressionQuality,omitempty"`
	// Optional. The image format that the output should be saved as.
	MIMEType string `json:"mimeType,omitempty"`
}

// The image generation configuration to be used in GenerateContentConfig.
type ImageConfig struct {
	// Optional. Aspect ratio of the generated images. Supported values are
	// "1:1", "2:3", "3:2", "3:4", "4:3", "9:16", "16:9", and "21:9".
	AspectRatio string `json:"aspectRatio,omitempty"`
	// Optional. Specifies the size of generated images. Supported
	// values are `1K`, `2K`, `4K`. If not specified, the model will use default
	// value `1K`.
	ImageSize string `json:"imageSize,omitempty"`
	// Optional. Controls the generation of people. Supported values are:
	// ALLOW_ALL, ALLOW_ADULT, ALLOW_NONE.
	PersonGeneration string `json:"personGeneration,omitempty"`
	// Optional. Controls whether prominent people (celebrities) generation is allowed.
	// If used with personGeneration, personGeneration enum would take precedence. For instance,
	// if ALLOW_NONE is set, all person generation would be blocked. If this field is unspecified,
	// the default behavior is to allow prominent people. This field is not supported in
	// Gemini API.
	ProminentPeople ProminentPeople `json:"prominentPeople,omitempty"`
	// Optional. MIME type of the generated image. This field is not
	// supported in Gemini API.
	OutputMIMEType string `json:"outputMimeType,omitempty"`
	// Optional. Compression quality of the generated image (for
	// ``image/jpeg`` only). This field is not supported in Gemini API.
	OutputCompressionQuality *int32 `json:"outputCompressionQuality,omitempty"`
	// Optional. The image output format for generated images. This field is not supported
	// in Gemini API.
	ImageOutputOptions *ImageConfigImageOutputOptions `json:"imageOutputOptions,omitempty"`
}

// The configuration for automated routing. When automated routing is specified, the
// routing will be determined by the pretrained routing model and customer provided
// model routing preference. This data type is not supported in Gemini API.
type GenerationConfigRoutingConfigAutoRoutingMode struct {
	// The model routing preference.
	ModelRoutingPreference string `json:"modelRoutingPreference,omitempty"`
}

// The configuration for manual routing. When manual routing is specified, the model
// will be selected based on the model name provided. This data type is not supported
// in Gemini API.
type GenerationConfigRoutingConfigManualRoutingMode struct {
	// The name of the model to use. Only public LLM models are accepted.
	ModelName string `json:"modelName,omitempty"`
}

// The configuration for routing the request to a specific model. This can be used to
// control which model is used for the generation, either automatically or by specifying
// a model name. This data type is not supported in Gemini API.
type GenerationConfigRoutingConfig struct {
	// In this mode, the model is selected automatically based on the content of the request.
	AutoMode *GenerationConfigRoutingConfigAutoRoutingMode `json:"autoMode,omitempty"`
	// In this mode, the model is specified manually.
	ManualMode *GenerationConfigRoutingConfigManualRoutingMode `json:"manualMode,omitempty"`
}

// A safety setting that affects the safety-blocking behavior. A SafetySetting consists
// of a harm category and a threshold for that category.
type SafetySetting struct {
	// Required. The harm category to be blocked.
	Category HarmCategory `json:"category,omitempty"`
	// Optional. The method for blocking content. If not specified, the default behavior
	// is to use the probability score. This field is not supported in Gemini API.
	Method HarmBlockMethod `json:"method,omitempty"`
	// Required. The threshold for blocking content. If the harm probability exceeds this
	// threshold, the content will be blocked.
	Threshold HarmBlockThreshold `json:"threshold,omitempty"`
}

// An object that represents a latitude/longitude pair. This is expressed as a pair
// of doubles to represent degrees latitude and degrees longitude. Unless specified
// otherwise, this object must conform to the WGS84 standard. Values must be within
// normalized ranges.
type LatLng struct {
	// The latitude in degrees. It must be in the range [-90.0, +90.0].
	Latitude *float64 `json:"latitude,omitempty"`
	// The longitude in degrees. It must be in the range [-180.0, +180.0].
	Longitude *float64 `json:"longitude,omitempty"`
}

// Retrieval config.
type RetrievalConfig struct {
	// The location of the user.
	LatLng *LatLng `json:"latLng,omitempty"`
	// The language code of the user.
	LanguageCode string `json:"languageCode,omitempty"`
}

// Function calling config.
type FunctionCallingConfig struct {
	// 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"`
	// Optional. Function calling mode.
	Mode FunctionCallingConfigMode `json:"mode,omitempty"`
	// Optional. When set to true, arguments of a single function call will be streamed
	// out in multiple parts/contents/responses. Partial parameter results will be returned
	// in the `FunctionCall.partial_args` field. This field is not supported in Gemini API.
	StreamFunctionCallArguments *bool `json:"streamFunctionCallArguments,omitempty"`
}

// Tool config. This config is shared for all tools provided in the request.
type ToolConfig struct {
	// Optional. Retrieval config.
	RetrievalConfig *RetrievalConfig `json:"retrievalConfig,omitempty"`
	// Optional. Function calling config.
	FunctionCallingConfig *FunctionCallingConfig `json:"functionCallingConfig,omitempty"`
	// Optional. If true, the API response will include the server-side tool calls and responses
	// within the `Content` message. This allows clients to observe the server's tool interactions.
	// This field is not supported in Vertex AI.
	IncludeServerSideToolInvocations *bool `json:"includeServerSideToolInvocations,omitempty"`
}

// Configuration for Model Armor. Model Armor is a Google Cloud service that provides
// safety and security filtering for prompts and responses. It helps protect your AI
// applications from risks such as harmful content, sensitive data leakage, and prompt
// injection attacks. This data type is not supported in Gemini API.
type ModelArmorConfig struct {
	// Optional. The resource name of the Model Armor template to use for prompt screening.
	// A Model Armor template is a set of customized filters and thresholds that define
	// how Model Armor screens content. If specified, Model Armor will use this template
	// to check the user's prompt for safety and security risks before it is sent to the
	// model. The name must be in the format `projects/{project}/locations/{location}/templates/{template}`.
	PromptTemplateName string `json:"promptTemplateName,omitempty"`
	// Optional. The resource name of the Model Armor template to use for response screening.
	// A Model Armor template is a set of customized filters and thresholds that define
	// how Model Armor screens content. If specified, Model Armor will use this template
	// to check the model's response for safety and security risks before it is returned
	// to the user. The name must be in the format `projects/{project}/locations/{location}/templates/{template}`.
	ResponseTemplateName string `json:"responseTemplateName,omitempty"`
}

// Optional model configuration parameters.
// For more information, see `Content generation parameters
// <https://cloud.google.com/vertex-ai/generative-ai/docs/multimodal/content-generation-parameters>`_.
type GenerateContentConfig struct {
	// Optional. Used to override HTTP request options.
	HTTPOptions *HTTPOptions `json:"httpOptions,omitempty"`
	// Optional. 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"`
	// Optional. 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 *float32 `json:"temperature,omitempty"`
	// Optional. 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 *float32 `json:"topP,omitempty"`
	// Optional. 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 *float32 `json:"topK,omitempty"`
	// Optional. Number of response variations to return.
	// If empty, the system will choose a default value (currently 1).
	CandidateCount int32 `json:"candidateCount,omitempty"`
	// Optional. Maximum number of tokens that can be generated in the response.
	// If empty, API will use a default value. The default value varies by model.
	MaxOutputTokens int32 `json:"maxOutputTokens,omitempty"`
	// Optional. 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"`
	// Optional. Whether to return the log probabilities of the tokens that were
	// chosen by the model at each step.
	ResponseLogprobs bool `json:"responseLogprobs,omitempty"`
	// Optional. Number of top candidate tokens to return the log probabilities for
	// at each generation step.
	Logprobs *int32 `json:"logprobs,omitempty"`
	// Optional. Positive values penalize tokens that already appear in the
	// generated text, increasing the probability of generating more diverse
	// content.
	PresencePenalty *float32 `json:"presencePenalty,omitempty"`
	// Optional. Positive values penalize tokens that repeatedly appear in the
	// generated text, increasing the probability of generating more diverse
	// content.
	FrequencyPenalty *float32 `json:"frequencyPenalty,omitempty"`
	// Optional. 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 *int32 `json:"seed,omitempty"`
	// Optional. Output response mimetype of the generated candidate text.
	// Supported mimetype:
	//   - `text/plain`: (default) Text output.
	//   - `application/json`: JSON response in the candidates.
	// The model needs to be prompted to output the appropriate response type,
	// otherwise the behavior is undefined.
	ResponseMIMEType string `json:"responseMimeType,omitempty"`
	// Optional. The `Schema` object allows the definition of input and output data types.
	// These types can be objects, but also primitives and arrays.
	// Represents a select subset of an [OpenAPI 3.0 schema
	// object](https://spec.openapis.org/oas/v3.0.3#schema).
	// If set, a compatible response_mime_type must also be set.
	// Compatible mimetypes: `application/json`: Schema for JSON response.
	// If `response_schema` doesn't process your schema correctly, try using
	// `response_json_schema` instead.
	ResponseSchema *Schema `json:"responseSchema,omitempty"`
	// Optional. Output schema of the generated response.
	// This is an alternative to `response_schema` that accepts [JSON
	// Schema](https://json-schema.org/). If set, `response_schema` must be
	// omitted, but `response_mime_type` is required. While the full JSON Schema
	// may be sent, not all features are supported. Specifically, only the
	// following properties are supported: - `$id` - `$defs` - `$ref` - `$anchor`
	//   - `type` - `format` - `title` - `description` - `enum` (for strings and
	// numbers) - `items` - `prefixItems` - `minItems` - `maxItems` - `minimum` -
	// `maximum` - `anyOf` - `oneOf` (interpreted the same as `anyOf`) -
	// `properties` - `additionalProperties` - `required` The non-standard
	// `propertyOrdering` property may also be set. Cyclic references are
	// unrolled to a limited degree and, as such, may only be used within
	// non-required properties. (Nullable properties are not sufficient.) If
	// `$ref` is set on a sub-schema, no other properties, except for than those
	// starting as a `$`, may be set.
	ResponseJsonSchema any `json:"responseJsonSchema,omitempty"`
	// Optional. Configuration for model router requests.
	RoutingConfig *GenerationConfigRoutingConfig `json:"routingConfig,omitempty"`
	// Optional. Configuration for model selection.
	ModelSelectionConfig *ModelSelectionConfig `json:"modelSelectionConfig,omitempty"`
	// Optional. Safety settings in the request to block unsafe content in the
	// response.
	SafetySettings []*SafetySetting `json:"safetySettings,omitempty"`
	// Optional. 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"`
	// Optional. Associates model output to a specific function call.
	ToolConfig *ToolConfig `json:"toolConfig,omitempty"`
	// Optional. Labels with user-defined metadata to break down billed charges.
	Labels map[string]string `json:"labels,omitempty"`
	// Optional. Resource name of a context cache that can be used in subsequent
	// requests.
	CachedContent string `json:"cachedContent,omitempty"`
	// Optional. The requested modalities of the response. Represents the set of
	// modalities that the model can return.
	ResponseModalities []string `json:"responseModalities,omitempty"`
	// Optional. If specified, the media resolution specified will be used.
	MediaResolution MediaResolution `json:"mediaResolution,omitempty"`
	// Optional. The speech generation configuration.
	SpeechConfig *SpeechConfig `json:"speechConfig,omitempty"`
	// Optional. If enabled, audio timestamp will be included in the request to the
	// model.
	AudioTimestamp bool `json:"audioTimestamp,omitempty"`
	// Optional. The thinking features configuration.
	ThinkingConfig *ThinkingConfig `json:"thinkingConfig,omitempty"`
	// Optional. The image generation configuration.
	ImageConfig *ImageConfig `json:"imageConfig,omitempty"`
	// Optional. Enables enhanced civic answers. It may not be available for all
	// models. This field is not supported in Gemini Enterprise Agent Platform.
	EnableEnhancedCivicAnswers *bool `json:"enableEnhancedCivicAnswers,omitempty"`
	// Optional. Settings for prompt and response sanitization using the Model Armor
	// service. If supplied, safety_settings must not be supplied.
	ModelArmorConfig *ModelArmorConfig `json:"modelArmorConfig,omitempty"`
	// Optional. The service tier to use for the request. For example, ServiceTier.FLEX.
	ServiceTier ServiceTier `json:"serviceTier,omitempty"`
}

func (c GenerateContentConfig) ToGenerationConfig(backend Backend) (*GenerationConfig, error) {
	ac := apiClient{
		clientConfig: &ClientConfig{
			Backend: backend,
		},
	}

	paramsMap := make(map[string]any)
	deepMarshal(c, &paramsMap)
	parentMap := make(map[string]any)
	var outputMap map[string]any
	var err error
	switch backend {
	case BackendGeminiAPI:
		outputMap, err = generateContentConfigToMldev(&ac, paramsMap, parentMap, paramsMap)
	case BackendVertexAI:
		outputMap, err = generateContentConfigToVertex(&ac, paramsMap, parentMap, paramsMap)
	default:
		return nil, fmt.Errorf("Unsupported backend: %v", backend)
	}

	if err != nil {
		return nil, err
	}

	if len(parentMap) > 0 {
		keys := make([]string, 0, len(parentMap))
		for k := range parentMap {
			keys = append(keys, k)
		}
		return nil, fmt.Errorf("Unsupported conversion for %v", keys)
	}

	output := new(GenerationConfig)
	if err := mapToStruct(outputMap, output); err != nil {
		return nil, err
	}

	return output, nil
}

// A wrapper class for the HTTP response.
type HTTPResponse struct {
	// Optional. Used to retain the processed HTTP headers in the response.
	Headers http.Header `json:"headers,omitempty"`
	// Optional. The raw HTTP response body, in JSON format.
	Body string `json:"body,omitempty"`
}

// A citation for a piece of generatedcontent. This data type is not supported in Gemini
// API.
type Citation struct {
	// Output only. The end index of the citation in the content.
	EndIndex int32 `json:"endIndex,omitempty"`
	// Output only. The license of the source of the citation.
	License string `json:"license,omitempty"`
	// Output only. The publication date of the source of the citation.
	PublicationDate civil.Date `json:"publicationDate,omitempty"`
	// Output only. The start index of the citation in the content.
	StartIndex int32 `json:"startIndex,omitempty"`
	// Output only. The title of the source of the citation.
	Title string `json:"title,omitempty"`
	// Output only. The URI of the source of the citation.
	URI string `json:"uri,omitempty"`
}

func (c *Citation) UnmarshalJSON(data []byte) error {
	type Alias Citation
	aux := &struct {
		PublicationDate *InternalDateJSON `json:"publicationDate,omitempty"`
		*Alias
	}{
		Alias: (*Alias)(c),
	}

	if err := json.Unmarshal(data, &aux); err != nil {
		return err
	}

	if !reflect.ValueOf(aux.PublicationDate).IsZero() {
		c.PublicationDate = civil.Date(*aux.PublicationDate)
	}

	return nil
}

func (c *Citation) MarshalJSON() ([]byte, error) {
	type Alias Citation
	aux := &struct {
		PublicationDate *InternalDateJSON `json:"publicationDate,omitempty"`
		*Alias
	}{
		Alias: (*Alias)(c),
	}

	if !reflect.ValueOf(c.PublicationDate).IsZero() {
		aux.PublicationDate = (*InternalDateJSON)(&c.PublicationDate)
	}

	return json.Marshal(aux)
}

// Citation information when the model quotes another source.
type CitationMetadata struct {
	// Optional. Contains citation information when the model directly quotes, at
	// length, from another source. Can include traditional websites and code
	// repositories.
	Citations []*Citation `json:"citations,omitempty"`
}

// Author attribution for a photo or review.
type GroundingChunkMapsPlaceAnswerSourcesAuthorAttribution struct {
	// Optional. Name of the author of the Photo or Review.
	DisplayName string `json:"displayName,omitempty"`
	// Optional. Profile photo URI of the author of the Photo or Review.
	PhotoURI string `json:"photoUri,omitempty"`
	// Optional. URI of the author of the Photo or Review.
	URI string `json:"uri,omitempty"`
}

// Encapsulates a review snippet.
type GroundingChunkMapsPlaceAnswerSourcesReviewSnippet struct {
	// Optional. This review's author.
	AuthorAttribution *GroundingChunkMapsPlaceAnswerSourcesAuthorAttribution `json:"authorAttribution,omitempty"`
	// Optional. A link where users can flag a problem with the review.
	FlagContentURI string `json:"flagContentUri,omitempty"`
	// Optional. A link to show the review on Google Maps.
	GoogleMapsURI string `json:"googleMapsUri,omitempty"`
	// Optional. A string of formatted recent time, expressing the review time relative
	// to the current time in a form appropriate for the language and country.
	RelativePublishTimeDescription string `json:"relativePublishTimeDescription,omitempty"`
	// Optional. A reference representing this place review which may be used to look up
	// this place review again.
	Review string `json:"review,omitempty"`
	// Optional. ID of the review referencing the place.
	ReviewID string `json:"reviewId,omitempty"`
	// Optional. Title of the review.
	Title string `json:"title,omitempty"`
}

// The sources that were used to generate the place answer.
// This includes review snippets and photos that were used to generate the
// answer, as well as URIs to flag content.
type GroundingChunkMapsPlaceAnswerSources struct {
	// Optional. Snippets of reviews that were used to generate the answer.
	ReviewSnippet []*GroundingChunkMapsPlaceAnswerSourcesReviewSnippet `json:"reviewSnippet,omitempty"`
	// Optional. A link where users can flag a problem with the generated answer.
	FlagContentURI string `json:"flagContentUri,omitempty"`
	// Snippets of reviews that were used to generate the answer.
	ReviewSnippets []*GroundingChunkMapsPlaceAnswerSourcesReviewSnippet `json:"reviewSnippets,omitempty"`
}

// Route information from Google Maps. This data type is not supported in Gemini API.
type GroundingChunkMapsRoute struct {
	// The total distance of the route, in meters.
	DistanceMeters *int32 `json:"distanceMeters,omitempty"`
	// The total duration of the route.
	Duration time.Duration `json:"duration,omitempty"`
	// An encoded polyline of the route. See https://developers.google.com/maps/documentation/utilities/polylinealgorithm
	EncodedPolyline string `json:"encodedPolyline,omitempty"`
}

func (g *GroundingChunkMapsRoute) UnmarshalJSON(data []byte) error {
	type Alias GroundingChunkMapsRoute
	aux := &struct {
		Duration *InternalDurationJSON `json:"duration,omitempty"`
		*Alias
	}{
		Alias: (*Alias)(g),
	}

	if err := json.Unmarshal(data, &aux); err != nil {
		return err
	}

	if !reflect.ValueOf(aux.Duration).IsZero() {
		g.Duration = time.Duration(*aux.Duration)
	}

	return nil
}

func (g *GroundingChunkMapsRoute) MarshalJSON() ([]byte, error) {
	type Alias GroundingChunkMapsRoute
	aux := &struct {
		Duration *InternalDurationJSON `json:"duration,omitempty"`
		*Alias
	}{
		Alias: (*Alias)(g),
	}

	if !reflect.ValueOf(g.Duration).IsZero() {
		aux.Duration = (*InternalDurationJSON)(&g.Duration)
	}

	return json.Marshal(aux)
}

// A `Maps` chunk is a piece of evidence that comes from Google Maps.
// It contains information about a place, such as its name, address, and reviews.
// This is used to provide the user with rich, location-based information.
type GroundingChunkMaps struct {
	// Optional. The sources that were used to generate the place answer.
	// This includes review snippets and photos that were used to generate the
	// answer, as well as URIs to flag content.
	PlaceAnswerSources *GroundingChunkMapsPlaceAnswerSources `json:"placeAnswerSources,omitempty"`
	// Optional. This Place's resource name, in `places/{place_id}` format.
	// This can be used to look up the place in the Google Maps API.
	PlaceID string `json:"placeId,omitempty"`
	// Optional. The text of the place answer.
	Text string `json:"text,omitempty"`
	// Optional. The title of the place.
	Title string `json:"title,omitempty"`
	// Optional. The URI of the place.
	URI string `json:"uri,omitempty"`
	// Output only. Route information.
	Route *GroundingChunkMapsRoute `json:"route,omitempty"`
}

// An `Image` chunk is a piece of evidence that comes from an image search result. It
// contains the URI of the image search result and the URI of the image. This is used
// to provide the user with a link to the source of the information.
type GroundingChunkImage struct {
	// The URI of the image search result page.
	SourceURI string `json:"sourceUri,omitempty"`
	// The URI of the image.
	ImageURI string `json:"imageUri,omitempty"`
	// The title of the image search result page.
	Title string `json:"title,omitempty"`
	// The domain of the image search result page.
	Domain string `json:"domain,omitempty"`
}

// Represents where the chunk starts and ends in the document. This data type is not
// supported in Gemini API.
type RAGChunkPageSpan struct {
	// Page where chunk starts in the document. Inclusive. 1-indexed.
	FirstPage int32 `json:"firstPage,omitempty"`
	// Page where chunk ends in the document. Inclusive. 1-indexed.
	LastPage int32 `json:"lastPage,omitempty"`
}

// A RAGChunk includes the content of a chunk of a RAGFile, and associated metadata.
// This data type is not supported in Gemini API.
type RAGChunk struct {
	// If populated, represents where the chunk starts and ends in the document.
	PageSpan *RAGChunkPageSpan `json:"pageSpan,omitempty"`
	// The content of the chunk.
	Text string `json:"text,omitempty"`
	// The ID of the chunk.
	ChunkID string `json:"chunkId,omitempty"`
	// The ID of the file that the chunk belongs to.
	FileID string `json:"fileId,omitempty"`
}

// A list of string values. This data type is not supported in Vertex AI.
type GroundingChunkStringList struct {
	// The string values of the list.
	Values []string `json:"values,omitempty"`
}

// User provided metadata about the GroundingFact. This data type is not supported in
// Vertex AI.
type GroundingChunkCustomMetadata struct {
	// The key of the metadata.
	Key string `json:"key,omitempty"`
	// Optional. The numeric value of the metadata. The expected range for this value depends
	// on the specific `key` used.
	NumericValue *float32 `json:"numericValue,omitempty"`
	// Optional. A list of string values for the metadata.
	StringListValue *GroundingChunkStringList `json:"stringListValue,omitempty"`
	// Optional. The string value of the metadata.
	StringValue string `json:"stringValue,omitempty"`
}

// Context retrieved from a data source to ground the model's response. This is used
// when a retrieval tool fetches information from a user-provided corpus or a public
// dataset.
type GroundingChunkRetrievedContext struct {
	// Output only. The full resource name of the referenced Vertex AI Search document.
	// This is used to identify the specific document that was retrieved. The format is
	// `projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}/documents/{document}`.
	// This field is not supported in Gemini API.
	DocumentName string `json:"documentName,omitempty"`
	// Additional context for a Retrieval-Augmented Generation (RAG) retrieval result. This
	// is populated only when the RAG retrieval tool is used. This field is not supported
	// in Gemini API.
	RAGChunk *RAGChunk `json:"ragChunk,omitempty"`
	// The content of the retrieved data source.
	Text string `json:"text,omitempty"`
	// The title of the retrieved data source.
	Title string `json:"title,omitempty"`
	// The URI of the retrieved data source.
	URI string `json:"uri,omitempty"`
	// Optional. User-provided metadata about the retrieved context. This field is not supported
	// in Vertex AI.
	CustomMetadata []*GroundingChunkCustomMetadata `json:"customMetadata,omitempty"`
	// Optional. Name of the `FileSearchStore` containing the document. Example: `fileSearchStores/123`.
	// This field is not supported in Vertex AI.
	FileSearchStore string `json:"fileSearchStore,omitempty"`
	// Optional. Page number of the retrieved context, if applicable. This field is not
	// supported in Vertex AI.
	PageNumber *int32 `json:"pageNumber,omitempty"`
	// Optional. The media blob resource name for multimodal file search results. Format:
	// fileSearchStores/{file_search_store_id}/media/{blob_id}. This field is not supported
	// in Vertex AI.
	MediaID string `json:"mediaId,omitempty"`
}

// A `Web` chunk is a piece of evidence that comes from a web page. It contains the
// URI of the web page, the title of the page, and the domain of the page. This is used
// to provide the user with a link to the source of the information.
type GroundingChunkWeb struct {
	// The domain of the web page that contains the evidence. This can be used to filter
	// out low-quality sources. This field is not supported in Gemini API.
	Domain string `json:"domain,omitempty"`
	// The title of the web page that contains the evidence.
	Title string `json:"title,omitempty"`
	// The URI of the web page that contains the evidence.
	URI string `json:"uri,omitempty"`
}

// A piece of evidence that supports a claim made by the model.
// This is used to show a citation for a claim made by the model. When grounding
// is enabled, the model returns a `GroundingChunk` that contains a reference to
// the source of the information.
type GroundingChunk struct {
	// A grounding chunk from an image search result. See the `Image` message for details.
	Image *GroundingChunkImage `json:"image,omitempty"`
	// Optional. A `Maps` chunk is a piece of evidence that comes from Google Maps.
	// It contains information about a place, such as its name, address, and
	// reviews. This is used to provide the user with rich, location-based
	// information.
	Maps *GroundingChunkMaps `json:"maps,omitempty"`
	// A grounding chunk from a data source retrieved by a retrieval tool, such as Vertex
	// AI Search. See the `RetrievedContext` message for details
	RetrievedContext *GroundingChunkRetrievedContext `json:"retrievedContext,omitempty"`
	// A grounding chunk from a web page, typically from Google Search. See the `Web` message
	// for details.
	Web *GroundingChunkWeb `json:"web,omitempty"`
}

// Segment of the content this support belongs to.
type Segment struct {
	// Optional. Output only. Start index in the given Part, measured in bytes.
	// Offset from the start of the Part, inclusive, starting at zero.
	StartIndex int32 `json:"startIndex,omitempty"`
	// Optional. Output only. End index in the given Part, measured in bytes.
	// Offset from the start of the Part, exclusive, starting at zero.
	EndIndex int32 `json:"endIndex,omitempty"`
	// Optional. Output only. The index of a Part object within its parent
	// Content object.
	PartIndex int32 `json:"partIndex,omitempty"`
	// Optional. Output only. The text corresponding to the segment from the
	// response.
	Text string `json:"text,omitempty"`
}

// Grounding support.
type GroundingSupport struct {
	// Optional. Confidence score of the support references.
	// Ranges from 0 to 1. 1 is the most confident. This list must have the
	// same size as the grounding_chunk_indices.
	ConfidenceScores []float32 `json:"confidenceScores,omitempty"`
	// Optional. A list of indices (into 'grounding_chunk') specifying the
	// citations associated with the claim. For instance [1,3,4] means that
	// grounding_chunk[1], grounding_chunk[3], grounding_chunk[4] are the
	// retrieved content attributed to the claim.
	GroundingChunkIndices []int32 `json:"groundingChunkIndices,omitempty"`
	// Optional. Segment of the content this support belongs to.
	Segment *Segment `json:"segment,omitempty"`
	// Indices into the `rendered_parts` field of the `GroundingMetadata` message. These
	// indices specify which rendered parts are associated with this support message.
	RenderedParts []int32 `json:"renderedParts,omitempty"`
}

// Metadata returned to client when grounding is enabled.
type RetrievalMetadata struct {
	// Optional. Score indicating how likely information from google
	// search could help answer the prompt. The score is in the range [0, 1],
	// where 0 is the least likely and 1 is the most likely. This score is only
	// populated when google search grounding and dynamic retrieval is enabled.
	// It will be compared to the threshold to determine whether to trigger
	// Google search.
	GoogleSearchDynamicRetrievalScore float32 `json:"googleSearchDynamicRetrievalScore,omitempty"`
}

// The entry point used to search for grounding sources.
type SearchEntryPoint struct {
	// Optional. Web content snippet that can be embedded in a web page
	// or an app webview.
	RenderedContent string `json:"renderedContent,omitempty"`
	// Optional. JSON representing array of tuples.
	SDKBlob []byte `json:"sdkBlob,omitempty"`
}

// A URI that can be used to flag a place or review for inappropriate content. This
// is populated only when the grounding source is Google Maps. This data type is not
// supported in Gemini API.
type GroundingMetadataSourceFlaggingURI struct {
	// The URI that can be used to flag the content.
	FlagContentURI string `json:"flagContentUri,omitempty"`
	// The ID of the place or review.
	SourceID string `json:"sourceId,omitempty"`
}

// Information for various kinds of grounding.
type GroundingMetadata struct {
	// Optional. The image search queries that were used to generate the content. This field
	// is populated only when the grounding source is Google Search with the Image Search
	// search_type enabled.
	ImageSearchQueries []string `json:"imageSearchQueries,omitempty"`
	// Optional. A list of supporting references retrieved from the grounding
	// source. This field is populated when the grounding source is Google
	// Search, Vertex AI Search, or Google Maps.
	GroundingChunks []*GroundingChunk `json:"groundingChunks,omitempty"`
	// Optional. List of grounding support.
	GroundingSupports []*GroundingSupport `json:"groundingSupports,omitempty"`
	// Optional. Metadata related to retrieval in the grounding flow.
	RetrievalMetadata *RetrievalMetadata `json:"retrievalMetadata,omitempty"`
	// Optional. Google search entry for the following-up web
	// searches.
	SearchEntryPoint *SearchEntryPoint `json:"searchEntryPoint,omitempty"`
	// Optional. Web search queries for the following-up web search.
	WebSearchQueries []string `json:"webSearchQueries,omitempty"`
	// Optional. Output only. Deprecated: The Google Maps contextual widget behavior in
	// Grounding with Google Maps is being deprecated; this field is planned for removal
	// and will no longer be populated once removed. A token that can be used to render
	// a Google Maps widget with the contextual data. This field is populated only when
	// the grounding source is Google Maps.
	GoogleMapsWidgetContextToken string `json:"googleMapsWidgetContextToken,omitempty"`
	// Optional. The queries that were executed by the retrieval tools. This field is populated
	// only when the grounding source is a retrieval tool, such as Vertex AI Search. This
	// field is not supported in Gemini API.
	RetrievalQueries []string `json:"retrievalQueries,omitempty"`
	// Optional. Output only. A list of URIs that can be used to flag a place or review
	// for inappropriate content. This field is populated only when the grounding source
	// is Google Maps. This field is not supported in Gemini API.
	SourceFlaggingUris []*GroundingMetadataSourceFlaggingURI `json:"sourceFlaggingUris,omitempty"`
}

// A single token and its associated log probability.
type LogprobsResultCandidate struct {
	// The log probability of this token. A higher value indicates that the model was more
	// confident in this token. The log probability can be used to assess the relative likelihood
	// of different tokens and to identify when the model is uncertain.
	LogProbability float32 `json:"logProbability,omitempty"`
	// The token's string representation.
	Token string `json:"token,omitempty"`
	// The token's numerical ID. While the `token` field provides the string representation
	// of the token, the `token_id` is the numerical representation that the model uses
	// internally. This can be useful for developers who want to build custom logic based
	// on the model's vocabulary.
	TokenID int32 `json:"tokenId,omitempty"`
}

// A list of the top candidate tokens and their log probabilities at each decoding step.
// This can be used to see what other tokens the model considered.
type LogprobsResultTopCandidates struct {
	// The list of candidate tokens, sorted by log probability in descending order.
	Candidates []*LogprobsResultCandidate `json:"candidates,omitempty"`
}

// The log probabilities of the tokens generated by the model. This is useful for understanding
// the model's confidence in its predictions and for debugging. For example, you can
// use log probabilities to identify when the model is making a less confident prediction
// or to explore alternative responses that the model considered. A low log probability
// can also indicate that the model is "hallucinating" or generating factually incorrect
// information.
type LogprobsResult struct {
	// A list of the chosen candidate tokens at each decoding step. The length of this list
	// is equal to the total number of decoding steps. Note that the chosen candidate might
	// not be in `top_candidates`.
	ChosenCandidates []*LogprobsResultCandidate `json:"chosenCandidates,omitempty"`
	// A list of the top candidate tokens at each decoding step. The length of this list
	// is equal to the total number of decoding steps.
	TopCandidates []*LogprobsResultTopCandidates `json:"topCandidates,omitempty"`
	// Sum of log probabilities for all tokens. This field is not supported in Vertex AI.
	LogProbabilitySum *float32 `json:"logProbabilitySum,omitempty"`
}

// A safety rating for a piece of content. The safety rating contains the harm category
// and the harm probability level.
type SafetyRating struct {
	// Output only. Indicates whether the content was blocked because of this rating.
	Blocked bool `json:"blocked,omitempty"`
	// Output only. The harm category of this rating.
	Category HarmCategory `json:"category,omitempty"`
	// Output only. The overwritten threshold for the safety category of Gemini 2.0 image
	// out. If minors are detected in the output image, the threshold of each safety category
	// will be overwritten if user sets a lower threshold. This field is not supported in
	// Gemini API.
	OverwrittenThreshold HarmBlockThreshold `json:"overwrittenThreshold,omitempty"`
	// Output only. The probability of harm for this category.
	Probability HarmProbability `json:"probability,omitempty"`
	// Output only. The probability score of harm for this category. This field is not supported
	// in Gemini API.
	ProbabilityScore float32 `json:"probabilityScore,omitempty"`
	// Output only. The severity of harm for this category. This field is not supported
	// in Gemini API.
	Severity HarmSeverity `json:"severity,omitempty"`
	// Output only. The severity score of harm for this category. This field is not supported
	// in Gemini API.
	SeverityScore float32 `json:"severityScore,omitempty"`
}

// The metadata for a single URL retrieval.
type URLMetadata struct {
	// The URL retrieved by the tool.
	RetrievedURL string `json:"retrievedUrl,omitempty"`
	// The status of the URL retrieval.
	URLRetrievalStatus URLRetrievalStatus `json:"urlRetrievalStatus,omitempty"`
}

// Metadata returned when the model uses the `url_context` tool to get information from
// a user-provided URL.
type URLContextMetadata struct {
	// Output only. A list of URL metadata, with one entry for each URL retrieved by the
	// tool.
	URLMetadata []*URLMetadata `json:"urlMetadata,omitempty"`
}

// A response candidate generated from the model.
type Candidate struct {
	// Optional. Contains the multi-part content of the response.
	Content *Content `json:"content,omitempty"`
	// Optional. Source attribution of the generated content.
	CitationMetadata *CitationMetadata `json:"citationMetadata,omitempty"`
	// Optional. Describes the reason the model stopped generating tokens.
	FinishMessage string `json:"finishMessage,omitempty"`
	// Optional. Number of tokens for this candidate.
	// This field is only available in the Gemini API.
	TokenCount int32 `json:"tokenCount,omitempty"`
	// Optional. The reason why the model stopped generating tokens.
	// If empty, the model has not stopped generating the tokens.
	FinishReason FinishReason `json:"finishReason,omitempty"`
	// Optional. Output only. Metadata returned when grounding is enabled. It
	// contains the sources used to ground the generated content.
	GroundingMetadata *GroundingMetadata `json:"groundingMetadata,omitempty"`
	// Output only. The average log probability of the tokens in this candidate. This is
	// a length-normalized score that can be used to compare the quality of candidates of
	// different lengths. A higher average log probability suggests a more confident and
	// coherent response.
	AvgLogprobs float64 `json:"avgLogprobs,omitempty"`
	// Output only. The 0-based index of this candidate in the list of generated responses.
	// This is useful for distinguishing between multiple candidates when `candidate_count`
	// > 1.
	Index int32 `json:"index,omitempty"`
	// Output only. The detailed log probability information for the tokens in this candidate.
	// This is useful for debugging, understanding model uncertainty, and identifying potential
	// "hallucinations".
	LogprobsResult *LogprobsResult `json:"logprobsResult,omitempty"`
	// Output only. A list of ratings for the safety of a response candidate. There is at
	// most one rating per category.
	SafetyRatings []*SafetyRating `json:"safetyRatings,omitempty"`
	// Output only. Metadata returned when the model uses the `url_context` tool to get
	// information from a user-provided URL.
	URLContextMetadata *URLContextMetadata `json:"urlContextMetadata,omitempty"`
}

// Content filter results for a prompt sent in the request. Note: This is sent only
// in the first stream chunk and only if no candidates were generated due to content
// violations.
type GenerateContentResponsePromptFeedback struct {
	// Output only. The reason why the prompt was blocked.
	BlockReason BlockedReason `json:"blockReason,omitempty"`
	// Output only. A readable message that explains the reason why the prompt was blocked.
	// This field is not supported in Gemini API.
	BlockReasonMessage string `json:"blockReasonMessage,omitempty"`
	// Output only. A list of safety ratings for the prompt. There is one rating per category.
	SafetyRatings []*SafetyRating `json:"safetyRatings,omitempty"`
}

// Represents a breakdown of token usage by modality. This message is used in CountTokensResponse
// and GenerateContentResponse.UsageMetadata to provide a detailed view of how many
// tokens are used by each modality (e.g., text, image, video) in a request. This is
// particularly useful for multimodal models, allowing you to track and manage token
// consumption for billing and quota purposes.
type ModalityTokenCount struct {
	// The modality that this token count applies to.
	Modality MediaModality `json:"modality,omitempty"`
	// The number of tokens counted for this modality.
	TokenCount int32 `json:"tokenCount,omitempty"`
}

// Usage metadata about the content generation request and response. This message provides
// a detailed breakdown of token usage and other relevant metrics. This data type is
// not supported in Gemini API.
type GenerateContentResponseUsageMetadata struct {
	// Output only. A detailed breakdown of the token count for each modality in the cached
	// content.
	CacheTokensDetails []*ModalityTokenCount `json:"cacheTokensDetails,omitempty"`
	// Output only. The number of tokens in the cached content that was used for this request.
	CachedContentTokenCount int32 `json:"cachedContentTokenCount,omitempty"`
	// The total number of tokens in the generated candidates. This includes all the generated
	// response candidates.
	CandidatesTokenCount int32 `json:"candidatesTokenCount,omitempty"`
	// Output only. A detailed breakdown of the token count for each modality in the generated
	// candidates.
	CandidatesTokensDetails []*ModalityTokenCount `json:"candidatesTokensDetails,omitempty"`
	// Number of tokens in the prompt. When cached_content is set, this is still the total
	// effective prompt size meaning this includes the number of tokens in the cached content.
	PromptTokenCount int32 `json:"promptTokenCount,omitempty"`
	// Output only. A detailed breakdown of the token count for each modality in the prompt.
	PromptTokensDetails []*ModalityTokenCount `json:"promptTokensDetails,omitempty"`
	// Output only. The number of tokens that were part of the model's generated "thoughts"
	// output, if applicable.
	ThoughtsTokenCount int32 `json:"thoughtsTokenCount,omitempty"`
	// Output only. The number of tokens in the results from tool executions, which are
	// provided back to the model as input, if applicable.
	ToolUsePromptTokenCount int32 `json:"toolUsePromptTokenCount,omitempty"`
	// Output only. A detailed breakdown by modality of the token counts from the results
	// of tool executions, which are provided back to the model as input.
	ToolUsePromptTokensDetails []*ModalityTokenCount `json:"toolUsePromptTokensDetails,omitempty"`
	// The total number of tokens for the entire request. This is the sum of `prompt_token_count`,
	// `candidates_token_count`, `tool_use_prompt_token_count`, and `thoughts_token_count`.
	TotalTokenCount int32 `json:"totalTokenCount,omitempty"`
	// Output only. The traffic type for this request.
	TrafficType TrafficType `json:"trafficType,omitempty"`
}

// The status of the underlying model. This is used to indicate the stage of the underlying
// model and the retirement time if applicable. This data type is not supported in Vertex
// AI.
type ModelStatus struct {
	// A message explaining the model status.
	Message string `json:"message,omitempty"`
	// The stage of the underlying model.
	ModelStage ModelStage `json:"modelStage,omitempty"`
	// The time at which the model will be retired.
	RetirementTime time.Time `json:"retirementTime,omitempty"`
}

func (m *ModelStatus) UnmarshalJSON(data []byte) error {
	type Alias ModelStatus
	aux := &struct {
		RetirementTime *time.Time `json:"retirementTime,omitempty"`
		*Alias
	}{
		Alias: (*Alias)(m),
	}

	if err := json.Unmarshal(data, &aux); err != nil {
		return err
	}

	if !reflect.ValueOf(aux.RetirementTime).IsZero() {
		m.RetirementTime = time.Time(*aux.RetirementTime)
	}

	return nil
}

func (m *ModelStatus) MarshalJSON() ([]byte, error) {
	type Alias ModelStatus
	aux := &struct {
		RetirementTime *time.Time `json:"retirementTime,omitempty"`
		*Alias
	}{
		Alias: (*Alias)(m),
	}

	if !reflect.ValueOf(m.RetirementTime).IsZero() {
		aux.RetirementTime = (*time.Time)(&m.RetirementTime)
	}

	return json.Marshal(aux)
}

// Response message for PredictionService.GenerateContent.
type GenerateContentResponse struct {
	// Optional. Used to retain the full HTTP response.
	SDKHTTPResponse *HTTPResponse `json:"sdkHttpResponse,omitempty"`
	// Response variations returned by the model.
	Candidates []*Candidate `json:"candidates,omitempty"`
	// Timestamp when the request is made to the server.
	CreateTime time.Time `json:"createTime,omitempty"`
	// Output only. The model version used to generate the response.
	ModelVersion string `json:"modelVersion,omitempty"`
	// Output only. Content filter results for a prompt sent in the request. Note: Sent
	// only in the first stream chunk. Only happens when no candidates were generated due
	// to content violations.
	PromptFeedback *GenerateContentResponsePromptFeedback `json:"promptFeedback,omitempty"`
	// Output only. response_id is used to identify each response. It is the encoding of
	// the event_id.
	ResponseID string `json:"responseId,omitempty"`
	// Usage metadata about the response(s).
	UsageMetadata *GenerateContentResponseUsageMetadata `json:"usageMetadata,omitempty"`
	// Output only. The current model status of this model. This field is not supported
	// in Vertex AI.
	ModelStatus *ModelStatus `json:"modelStatus,omitempty"`
}

func (g *GenerateContentResponse) UnmarshalJSON(data []byte) error {
	type Alias GenerateContentResponse
	aux := &struct {
		CreateTime *time.Time `json:"createTime,omitempty"`
		*Alias
	}{
		Alias: (*Alias)(g),
	}

	if err := json.Unmarshal(data, &aux); err != nil {
		return err
	}

	if !reflect.ValueOf(aux.CreateTime).IsZero() {
		g.CreateTime = time.Time(*aux.CreateTime)
	}

	return nil
}

func (g *GenerateContentResponse) MarshalJSON() ([]byte, error) {
	type Alias GenerateContentResponse
	aux := &struct {
		CreateTime *time.Time `json:"createTime,omitempty"`
		*Alias
	}{
		Alias: (*Alias)(g),
	}

	if !reflect.ValueOf(g.CreateTime).IsZero() {
		aux.CreateTime = (*time.Time)(&g.CreateTime)
	}

	return json.Marshal(aux)
}

// Text concatenates all the text parts in the GenerateContentResponse.
func (r *GenerateContentResponse) Text() string {
	if len(r.Candidates) == 0 || r.Candidates[0].Content == nil || len(r.Candidates[0].Content.Parts) == 0 {
		return ""
	}

	if len(r.Candidates) > 1 {
		log.Println("Warning: there are multiple candidates in the response, returning text from the first one.")
	}

	var texts []string
	var notTextParts []string
	for _, part := range r.Candidates[0].Content.Parts {
		if part.Text != "" {
			if part.Thought {
				continue
			}
			texts = append(texts, part.Text)
		} else {
			if part.InlineData != nil {
				notTextParts = append(notTextParts, "InlineData")
			}
			if part.CodeExecutionResult != nil {
				notTextParts = append(notTextParts, "CodeExecutionResult")
			}
			if part.ExecutableCode != nil {
				notTextParts = append(notTextParts, "ExecutableCode")
			}
			if part.FileData != nil {
				notTextParts = append(notTextParts, "FileData")
			}
			if part.FunctionCall != nil {
				notTextParts = append(notTextParts, "FunctionCall")
			}
			if part.FunctionResponse != nil {
				notTextParts = append(notTextParts, "FunctionResponse")
			}
		}
	}

	if len(notTextParts) > 0 {
		log.Printf("Warning: there are non-text parts %s in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.\n", strings.Join(notTextParts, ", "))
	}

	if len(texts) == 0 {
		return ""
	}

	return strings.Join(texts, "")
}

// FunctionCalls returns the list of function calls in the GenerateContentResponse.
func (r *GenerateContentResponse) FunctionCalls() []*FunctionCall {
	if len(r.Candidates) == 0 || r.Candidates[0].Content == nil || len(r.Candidates[0].Content.Parts) == 0 {
		return nil
	}

	if len(r.Candidates) > 1 {
		log.Println("Warning: there are multiple candidates in the response, returning function calls from the first one.")
	}

	var functionCalls []*FunctionCall
	for _, part := range r.Candidates[0].Content.Parts {
		if part.FunctionCall != nil {
			functionCalls = append(functionCalls, part.FunctionCall)
		}
	}

	if len(functionCalls) == 0 {
		return nil
	}

	return functionCalls
}

// ExecutableCode returns the executable code in the GenerateContentResponse.
func (r *GenerateContentResponse) ExecutableCode() string {
	if len(r.Candidates) == 0 || r.Candidates[0].Content == nil || len(r.Candidates[0].Content.Parts) == 0 {
		return ""
	}

	if len(r.Candidates) > 1 {
		log.Println("Warning: there are multiple candidates in the response, returning executable code from the first one.")
	}

	for _, part := range r.Candidates[0].Content.Parts {
		if part.ExecutableCode != nil {
			return part.ExecutableCode.Code
		}
	}

	return ""
}

// CodeExecutionResult returns the code execution result in the GenerateContentResponse.
func (r *GenerateContentResponse) CodeExecutionResult() string {
	if len(r.Candidates) == 0 || r.Candidates[0].Content == nil || len(r.Candidates[0].Content.Parts) == 0 {
		return ""
	}

	if len(r.Candidates) > 1 {
		log.Println("Warning: there are multiple candidates in the response, returning code execution result from the first one.")
	}

	for _, part := range r.Candidates[0].Content.Parts {
		if part.CodeExecutionResult != nil {
			return part.CodeExecutionResult.Output
		}
	}

	return ""
}

// Optional parameters for the EmbedContent method.
type EmbedContentConfig struct {
	// Type of task for which the embedding will be used.
	TaskType string `json:"taskType,omitempty"`
	// Title for the text. Only applicable when TaskType is
	// `RETRIEVAL_DOCUMENT`.
	Title string `json:"title,omitempty"`
	// Reduced dimension for the output embedding. If set,
	// excessive values in the output embedding are truncated from the end.
	// Supported by newer models since 2024 only. You cannot set this value if
	// using the earlier model (`models/embedding-001`).
	OutputDimensionality *int32 `json:"outputDimensionality,omitempty"`
	// Gemini Enterprise Agent Platform only. The MIME type of the input.
	MIMEType string `json:"mimeType,omitempty"`
	// Gemini Enterprise Agent Platform only. Whether to silently truncate inputs longer
	// than
	// the max sequence length. If this option is set to false, oversized inputs
	// will lead to an INVALID_ARGUMENT error, similar to other text APIs.
	AutoTruncate bool `json:"autoTruncate,omitempty"`
	// Gemini Enterprise Agent Platform only. Whether to enable OCR for document content.
	// Only applicable to Gemini Embedding 2 models.
	DocumentOcr *bool `json:"documentOcr,omitempty"`
	// Gemini Enterprise Agent Platform only. Whether to extract audio from video content.
	// Only applicable to Gemini Embedding 2 models.
	AudioTrackExtraction *bool `json:"audioTrackExtraction,omitempty"`
	// Optional. Used to override HTTP request options.
	HTTPOptions *HTTPOptions `json:"httpOptions,omitempty"`
}

// Statistics of the input text associated with the result of content embedding.
type ContentEmbeddingStatistics struct {
	// Gemini Enterprise Agent Platform only. If the input text was truncated due to having
	// a length longer than the allowed maximum input.
	Truncated bool `json:"truncated,omitempty"`
	// Gemini Enterprise Agent Platform only. Number of tokens of the input text.
	TokenCount float32 `json:"tokenCount,omitempty"`
}

// The embedding generated from an input content.
type ContentEmbedding struct {
	// A list of floats representing an embedding.
	Values []float32 `json:"values,omitempty"`
	// Gemini Enterprise Agent Platform only. Statistics of the input text associated with
	// this
	// embedding.
	Statistics *ContentEmbeddingStatistics `json:"statistics,omitempty"`
}

// Request-level metadata for the Gemini Enterprise Agent Platform Embed Content API.
type EmbedContentMetadata struct {
	// Gemini Enterprise Agent Platform only. The total number of billable characters included
	// in the request.
	BillableCharacterCount int32 `json:"billableCharacterCount,omitempty"`
}

// Response for the embed_content method.
type EmbedContentResponse struct {
	// Optional. Used to retain the full HTTP response.
	SDKHTTPResponse *HTTPResponse `json:"sdkHttpResponse,omitempty"`
	// The embeddings for each request, in the same order as provided in
	// the batch request.
	Embeddings []*ContentEmbedding `json:"embeddings,omitempty"`
	// Gemini Enterprise Agent Platform only. Metadata about the request.
	Metadata *EmbedContentMetadata `json:"metadata,omitempty"`
}

// The configuration for generating images. You can find API default values and more
// details at Gemini Enterprise Agent Platform: https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/imagen-api.
// GeminiAPI: https://ai.google.dev/gemini-api/docs/imagen#imagen-model
type GenerateImagesConfig struct {
	// Optional. Used to override HTTP request options.
	HTTPOptions *HTTPOptions `json:"httpOptions,omitempty"`
	// Optional. Cloud Storage URI used to store the generated images.
	OutputGCSURI string `json:"outputGcsUri,omitempty"`
	// Optional. Description of what to discourage in the generated images.
	NegativePrompt string `json:"negativePrompt,omitempty"`
	// Optional. Number of images to generate. If empty, the system will choose a default
	// value (currently 4).
	NumberOfImages int32 `json:"numberOfImages,omitempty"`
	// Optional. Aspect ratio of the generated images. Supported values are
	// "1:1", "3:4", "4:3", "9:16", and "16:9".
	AspectRatio string `json:"aspectRatio,omitempty"`
	// Optional. Controls how much the model adheres to the text prompt. Large
	// values increase output and prompt alignment, but may compromise image
	// quality.
	GuidanceScale *float32 `json:"guidanceScale,omitempty"`
	// Optional. Random seed for image generation. This is not available when
	// ``add_watermark`` is set to true.
	Seed *int32 `json:"seed,omitempty"`
	// Optional. Filter level for safety filtering.
	SafetyFilterLevel SafetyFilterLevel `json:"safetyFilterLevel,omitempty"`
	// Optional. Allows generation of people by the model.
	PersonGeneration PersonGeneration `json:"personGeneration,omitempty"`
	// Optional. Whether to report the safety scores of each generated image and
	// the positive prompt in the response.
	IncludeSafetyAttributes bool `json:"includeSafetyAttributes,omitempty"`
	// Optional. Whether to include the Responsible AI filter reason if the image
	// is filtered out of the response.
	IncludeRAIReason bool `json:"includeRaiReason,omitempty"`
	// Optional. Language of the text in the prompt.
	Language ImagePromptLanguage `json:"language,omitempty"`
	// Optional. MIME type of the generated image.
	OutputMIMEType string `json:"outputMimeType,omitempty"`
	// Optional. Compression quality of the generated image (for ``image/jpeg``
	// only).
	OutputCompressionQuality *int32 `json:"outputCompressionQuality,omitempty"`
	// Optional. Whether to add a watermark to the generated images.
	AddWatermark bool `json:"addWatermark,omitempty"`
	// Optional. User specified labels to track billing usage.
	Labels map[string]string `json:"labels,omitempty"`
	// Optional. The size of the largest dimension of the generated image.
	// Supported sizes are 1K and 2K (not supported for Imagen 3 models).
	ImageSize string `json:"imageSize,omitempty"`
	// Optional. Whether to use the prompt rewriting logic.
	EnhancePrompt bool `json:"enhancePrompt,omitempty"`
}

// An image.
type Image struct {
	// Optional. The Cloud Storage URI of the image. ``Image`` can contain a value
	// for this field or the ``image_bytes`` field but not both.
	GCSURI string `json:"gcsUri,omitempty"`
	// Optional. The image bytes data. ``Image`` can contain a value for this field
	// or the ``gcs_uri`` field but not both.
	ImageBytes []byte `json:"imageBytes,omitempty"`
	// Optional. The MIME type of the image.
	MIMEType string `json:"mimeType,omitempty"`
}

// Safety attributes of a GeneratedImage or the user-provided prompt.
type SafetyAttributes struct {
	// List of RAI categories.
	Categories []string `json:"categories,omitempty"`
	// List of scores of each categories.
	Scores []float32 `json:"scores,omitempty"`
	// Optional. Internal use only.
	ContentType string `json:"contentType,omitempty"`
}

// An output image.
type GeneratedImage struct {
	// The output image data.
	Image *Image `json:"image,omitempty"`
	// Optional. Responsible AI filter reason if the image is filtered out of the
	// response.
	RAIFilteredReason string `json:"raiFilteredReason,omitempty"`
	// Optional. Safety attributes of the image. Lists of RAI categories and their
	// scores of each content.
	SafetyAttributes *SafetyAttributes `json:"safetyAttributes,omitempty"`
	// Optional. The rewritten prompt used for the image generation if the prompt
	// enhancer is enabled.
	EnhancedPrompt string `json:"enhancedPrompt,omitempty"`
}

// The output images response.
type GenerateImagesResponse struct {
	// Optional. Used to retain the full HTTP response.
	SDKHTTPResponse *HTTPResponse `json:"sdkHttpResponse,omitempty"`
	// List of generated images.
	GeneratedImages []*GeneratedImage `json:"generatedImages,omitempty"`
	// Optional. Safety attributes of the positive prompt. Only populated if
	// ``include_safety_attributes`` is set to True.
	PositivePromptSafetyAttributes *SafetyAttributes `json:"positivePromptSafetyAttributes,omitempty"`
}

// Configuration for a Mask reference image.
type MaskReferenceConfig struct {
	// Optional. Prompts the model to generate a mask instead of you needing to
	// provide one (unless MASK_MODE_USER_PROVIDED is used).
	MaskMode MaskReferenceMode `json:"maskMode,omitempty"`
	// Optional. A list of up to 5 class IDs to use for semantic segmentation.
	// Automatically creates an image mask based on specific objects.
	SegmentationClasses []int32 `json:"segmentationClasses,omitempty"`
	// Optional. Dilation percentage of the mask provided.
	// Float between 0 and 1.
	MaskDilation *float32 `json:"maskDilation,omitempty"`
}

// Configuration for a Control reference image.
type ControlReferenceConfig struct {
	// Optional. The type of control reference image to use.
	ControlType ControlReferenceType `json:"controlType,omitempty"`
	// Optional. Defaults to False. When set to True, the control image will be
	// computed by the model based on the control type. When set to False,
	// the control image must be provided by the user.
	EnableControlImageComputation bool `json:"enableControlImageComputation,omitempty"`
}

// Configuration for a Style reference image.
type StyleReferenceConfig struct {
	// Optional. A text description of the style to use for the generated image.
	StyleDescription string `json:"styleDescription,omitempty"`
}

// Configuration for a Subject reference image.
type SubjectReferenceConfig struct {
	// Optional. The subject type of a subject reference image.
	SubjectType SubjectReferenceType `json:"subjectType,omitempty"`
	// Optional. Subject description for the image.
	SubjectDescription string `json:"subjectDescription,omitempty"`
}

// referenceImageAPI represents a Reference image that is sent to API.
type referenceImageAPI struct {
	// Optional. The reference image for the editing operation.
	ReferenceImage *Image `json:"referenceImage,omitempty"`
	// Optional. The ID of the reference image.
	ReferenceID int32 `json:"referenceId,omitempty"`
	// Optional. The type of the reference image. Only set by the SDK.
	ReferenceType string `json:"referenceType,omitempty"`
	// Optional. Configuration for the mask reference image.
	MaskImageConfig *MaskReferenceConfig `json:"maskImageConfig,omitempty"`
	// Optional. Configuration for the control reference image.
	ControlImageConfig *ControlReferenceConfig `json:"controlImageConfig,omitempty"`
	// Optional. Configuration for the style reference image.
	StyleImageConfig *StyleReferenceConfig `json:"styleImageConfig,omitempty"`
	// Optional. Configuration for the subject reference image.
	SubjectImageConfig *SubjectReferenceConfig `json:"subjectImageConfig,omitempty"`
}

func (r *referenceImageAPI) referenceImageAPI() *referenceImageAPI {
	return r
}

// ReferenceImage is an interface that represents a generic reference image.
//
// You can create instances that implement this interface using the following
// constructor functions:
//   - NewRawReferenceImage
//   - NewMaskReferenceImage
//   - NewControlReferenceImage
//   - NewStyleReferenceImage
//   - NewSubjectReferenceImage
//   - NewContentReferenceImage
//   - ...
type ReferenceImage interface {
	referenceImageAPI() *referenceImageAPI
}

// NewRawReferenceImage creates a new RawReferenceImage.
func NewRawReferenceImage(referenceImage *Image, referenceID int32) *RawReferenceImage {
	return &RawReferenceImage{
		ReferenceImage: referenceImage,
		ReferenceID:    referenceID,
		referenceType:  "REFERENCE_TYPE_RAW",
	}
}

// NewMaskReferenceImage creates a new MaskReferenceImage.
func NewMaskReferenceImage(referenceImage *Image, referenceID int32, config *MaskReferenceConfig) *MaskReferenceImage {
	return &MaskReferenceImage{
		ReferenceImage: referenceImage,
		ReferenceID:    referenceID,
		Config:         config,
		referenceType:  "REFERENCE_TYPE_MASK",
	}
}

// NewControlReferenceImage creates a new ControlReferenceImage.
func NewControlReferenceImage(referenceImage *Image, referenceID int32, config *ControlReferenceConfig) *ControlReferenceImage {
	return &ControlReferenceImage{
		ReferenceImage: referenceImage,
		ReferenceID:    referenceID,
		Config:         config,
		referenceType:  "REFERENCE_TYPE_CONTROL",
	}
}

// NewStyleReferenceImage creates a new ControlReferenceImage.
func NewStyleReferenceImage(referenceImage *Image, referenceID int32, config *StyleReferenceConfig) *StyleReferenceImage {
	return &StyleReferenceImage{
		ReferenceImage: referenceImage,
		ReferenceID:    referenceID,
		Config:         config,
		referenceType:  "REFERENCE_TYPE_STYLE",
	}
}

// NewSubjectReferenceImage creates a new SubjectReferenceImage.
func NewSubjectReferenceImage(referenceImage *Image, referenceID int32, config *SubjectReferenceConfig) *SubjectReferenceImage {
	return &SubjectReferenceImage{
		ReferenceImage: referenceImage,
		ReferenceID:    referenceID,
		Config:         config,
		referenceType:  "REFERENCE_TYPE_SUBJECT",
	}
}

// NewContentReferenceImage creates a new ContentReferenceImage.
func NewContentReferenceImage(referenceImage *Image, referenceID int32) *ContentReferenceImage {
	return &ContentReferenceImage{
		ReferenceImage: referenceImage,
		ReferenceID:    referenceID,
		referenceType:  "REFERENCE_TYPE_CONTENT",
	}
}

// Configuration for editing an image.
type EditImageConfig struct {
	// Optional. Used to override HTTP request options.
	HTTPOptions *HTTPOptions `json:"httpOptions,omitempty"`
	// Optional. Cloud Storage URI used to store the generated images.
	OutputGCSURI string `json:"outputGcsUri,omitempty"`
	// Optional. Description of what to discourage in the generated images.
	NegativePrompt string `json:"negativePrompt,omitempty"`
	// Optional. Number of images to generate. If empty, the system will choose a default
	// value (currently 4).
	NumberOfImages int32 `json:"numberOfImages,omitempty"`
	// Optional. Aspect ratio of the generated images. Supported values are
	// "1:1", "3:4", "4:3", "9:16", and "16:9".
	AspectRatio string `json:"aspectRatio,omitempty"`
	// Optional. Controls how much the model adheres to the text prompt. Large
	// values increase output and prompt alignment, but may compromise image
	// quality.
	GuidanceScale *float32 `json:"guidanceScale,omitempty"`
	// Optional. Random seed for image generation. This is not available when
	// ``add_watermark`` is set to true.
	Seed *int32 `json:"seed,omitempty"`
	// Optional. Filter level for safety filtering.
	SafetyFilterLevel SafetyFilterLevel `json:"safetyFilterLevel,omitempty"`
	// Optional. Allows generation of people by the model.
	PersonGeneration PersonGeneration `json:"personGeneration,omitempty"`
	// Optional. Whether to report the safety scores of each generated image and
	// the positive prompt in the response.
	IncludeSafetyAttributes bool `json:"includeSafetyAttributes,omitempty"`
	// Optional. Whether to include the Responsible AI filter reason if the image
	// is filtered out of the response.
	IncludeRAIReason bool `json:"includeRaiReason,omitempty"`
	// Optional. Language of the text in the prompt.
	Language ImagePromptLanguage `json:"language,omitempty"`
	// Optional. MIME type of the generated image.
	OutputMIMEType string `json:"outputMimeType,omitempty"`
	// Optional. Compression quality of the generated image (for ``image/jpeg``
	// only).
	OutputCompressionQuality *int32 `json:"outputCompressionQuality,omitempty"`
	// Optional. Whether to add a watermark to the generated images.
	AddWatermark *bool `json:"addWatermark,omitempty"`
	// Optional. User specified labels to track billing usage.
	Labels map[string]string `json:"labels,omitempty"`
	// Optional. Describes the editing mode for the request.
	EditMode EditMode `json:"editMode,omitempty"`
	// Optional. The number of sampling steps. A higher value has better image
	// quality, while a lower value has better latency.
	BaseSteps *int32 `json:"baseSteps,omitempty"`
}

// Response for the request to edit an image.
type EditImageResponse struct {
	// Optional. Used to retain the full HTTP response.
	SDKHTTPResponse *HTTPResponse `json:"sdkHttpResponse,omitempty"`
	// Generated images.
	GeneratedImages []*GeneratedImage `json:"generatedImages,omitempty"`
}

// Internal API config for UpscaleImage.
// These fields require default values sent to the API which are not intended
// to be modifiable or exposed to users in the SDK method.
type upscaleImageAPIConfig struct {
	// Optional. Used to override HTTP request options.
	HTTPOptions *HTTPOptions `json:"httpOptions,omitempty"`
	// Optional. Cloud Storage URI used to store the generated images.
	OutputGCSURI string `json:"outputGcsUri,omitempty"`
	// Optional. Filter level for safety filtering.
	SafetyFilterLevel SafetyFilterLevel `json:"safetyFilterLevel,omitempty"`
	// Optional. Allows generation of people by the model.
	PersonGeneration PersonGeneration `json:"personGeneration,omitempty"`
	// Optional. Whether to include a reason for filtered-out images in the
	// response.
	IncludeRAIReason bool `json:"includeRaiReason,omitempty"`
	// Optional. The image format that the output should be saved as.
	OutputMIMEType string `json:"outputMimeType,omitempty"`
	// Optional. The level of compression. Only applicable if the
	// ``output_mime_type`` is ``image/jpeg``.
	OutputCompressionQuality *int32 `json:"outputCompressionQuality,omitempty"`
	// Optional. Whether to add an image enhancing step before upscaling.
	// It is expected to suppress the noise and JPEG compression artifacts
	// from the input image.
	EnhanceInputImage bool `json:"enhanceInputImage,omitempty"`
	// Optional. With a higher image preservation factor, the original image
	// pixels are more respected. With a lower image preservation factor, the
	// output image will have be more different from the input image, but
	// with finer details and less noise.
	ImagePreservationFactor *float32 `json:"imagePreservationFactor,omitempty"`
	// Optional. User specified labels to track billing usage.
	Labels map[string]string `json:"labels,omitempty"`
	// Optional.
	NumberOfImages int32 `json:"numberOfImages,omitempty"`
	// Optional.
	Mode string `json:"mode,omitempty"`
}

type UpscaleImageResponse struct {
	// Optional. Used to retain the full HTTP response.
	SDKHTTPResponse *HTTPResponse `json:"sdkHttpResponse,omitempty"`
	// Generated images.
	GeneratedImages []*GeneratedImage `json:"generatedImages,omitempty"`
}

// An image of the product.
type ProductImage struct {
	// Optional. An image of the product to be recontextualized.
	ProductImage *Image `json:"productImage,omitempty"`
}

// A set of source input(s) for image recontextualization.
type RecontextImageSource struct {
	// Optional. A text prompt for guiding the model during image
	// recontextualization. Not supported for Virtual Try-On.
	Prompt string `json:"prompt,omitempty"`
	// Image of the person or subject who will be wearing the
	// product(s).
	PersonImage *Image `json:"personImage,omitempty"`
	// Optional. A list of product images.
	ProductImages []*ProductImage `json:"productImages,omitempty"`
}

// Configuration for recontextualizing an image.
type RecontextImageConfig struct {
	// Optional. Used to override HTTP request options.
	HTTPOptions *HTTPOptions `json:"httpOptions,omitempty"`
	// Optional. Number of images to generate.
	NumberOfImages *int32 `json:"numberOfImages,omitempty"`
	// Optional. The number of sampling steps. A higher value has better image
	// quality, while a lower value has better latency.
	BaseSteps *int32 `json:"baseSteps,omitempty"`
	// Optional. Cloud Storage URI used to store the generated images.
	OutputGCSURI string `json:"outputGcsUri,omitempty"`
	// Optional. Random seed for image generation.
	Seed *int32 `json:"seed,omitempty"`
	// Optional. Filter level for safety filtering.
	SafetyFilterLevel SafetyFilterLevel `json:"safetyFilterLevel,omitempty"`
	// Optional. Whether allow to generate person images, and restrict to specific
	// ages.
	PersonGeneration PersonGeneration `json:"personGeneration,omitempty"`
	// Optional. Whether to add a SynthID watermark to the generated images.
	AddWatermark *bool `json:"addWatermark,omitempty"`
	// Optional. MIME type of the generated image.
	OutputMIMEType string `json:"outputMimeType,omitempty"`
	// Optional. Compression quality of the generated image (for ``image/jpeg``
	// only).
	OutputCompressionQuality *int32 `json:"outputCompressionQuality,omitempty"`
	// Optional. Whether to use the prompt rewriting logic.
	EnhancePrompt *bool `json:"enhancePrompt,omitempty"`
	// Optional. User specified labels to track billing usage.
	Labels map[string]string `json:"labels,omitempty"`
}

// The output images response.
type RecontextImageResponse struct {
	// List of generated images.
	GeneratedImages []*GeneratedImage `json:"generatedImages,omitempty"`
}

// An image mask representing a brush scribble.
type ScribbleImage struct {
	// Optional. The brush scribble to guide segmentation. Valid for the interactive mode.
	Image *Image `json:"image,omitempty"`
}

// A set of source input(s) for image segmentation.
type SegmentImageSource struct {
	// Optional. A text prompt for guiding the model during image segmentation.
	// Required for prompt mode and semantic mode, disallowed for other modes.
	Prompt string `json:"prompt,omitempty"`
	// The image to be segmented.
	Image *Image `json:"image,omitempty"`
	// Optional. The brush scribble to guide segmentation.
	// Required for the interactive mode, disallowed for other modes.
	ScribbleImage *ScribbleImage `json:"scribbleImage,omitempty"`
}

// Configuration for segmenting an image.
type SegmentImageConfig struct {
	// Optional. Used to override HTTP request options.
	HTTPOptions *HTTPOptions `json:"httpOptions,omitempty"`
	// Optional. The segmentation mode to use.
	Mode SegmentMode `json:"mode,omitempty"`
	// Optional. The maximum number of predictions to return up to, by top
	// confidence score.
	MaxPredictions *int32 `json:"maxPredictions,omitempty"`
	// Optional. The confidence score threshold for the detections as a decimal
	// value. Only predictions with a confidence score higher than this
	// threshold will be returned.
	ConfidenceThreshold *float32 `json:"confidenceThreshold,omitempty"`
	// Optional. A decimal value representing how much dilation to apply to the
	// masks. 0 for no dilation. 1.0 means the masked area covers the whole
	// image.
	MaskDilation *float32 `json:"maskDilation,omitempty"`
	// Optional. The binary color threshold to apply to the masks. The threshold
	// can be set to a decimal value between 0 and 255 non-inclusive.
	// Set to -1 for no binary color thresholding.
	BinaryColorThreshold *float32 `json:"binaryColorThreshold,omitempty"`
	// Optional. User specified labels to track billing usage.
	Labels map[string]string `json:"labels,omitempty"`
}

// An entity representing the segmented area.
type EntityLabel struct {
	// Optional. The label of the segmented entity.
	Label string `json:"label,omitempty"`
	// Optional. The confidence score of the detected label.
	Score float32 `json:"score,omitempty,string"`
}

// A generated image mask.
type GeneratedImageMask struct {
	// Optional. The generated image mask.
	Mask *Image `json:"mask,omitempty"`
	// Optional. The detected entities on the segmented area.
	Labels []*EntityLabel `json:"labels,omitempty"`
}

// The output images response.
type SegmentImageResponse struct {
	// List of generated image masks.
	GeneratedMasks []*GeneratedImageMask `json:"generatedMasks,omitempty"`
}

// Optional parameters for models.get method.
type GetModelConfig struct {
	// Optional. Used to override HTTP request options.
	HTTPOptions *HTTPOptions `json:"httpOptions,omitempty"`
}

// An endpoint where models are deployed.
type Endpoint struct {
	// Optional. Resource name of the endpoint.
	Name string `json:"name,omitempty"`
	// Optional. ID of the model that's deployed to the endpoint.
	DeployedModelID string `json:"deployedModelId,omitempty"`
}

// A tuned machine learning model.
type TunedModelInfo struct {
	// Optional. ID of the base model that you want to tune.
	BaseModel string `json:"baseModel,omitempty"`
	// Optional. Date and time when the base model was created.
	CreateTime time.Time `json:"createTime,omitempty"`
	// Optional. Date and time when the base model was last updated.
	UpdateTime time.Time `json:"updateTime,omitempty"`
}

func (t *TunedModelInfo) UnmarshalJSON(data []byte) error {
	type Alias TunedModelInfo
	aux := &struct {
		CreateTime *time.Time `json:"createTime,omitempty"`
		UpdateTime *time.Time `json:"updateTime,omitempty"`
		*Alias
	}{
		Alias: (*Alias)(t),
	}

	if err := json.Unmarshal(data, &aux); err != nil {
		return err
	}

	if !reflect.ValueOf(aux.CreateTime).IsZero() {
		t.CreateTime = time.Time(*aux.CreateTime)
	}

	if !reflect.ValueOf(aux.UpdateTime).IsZero() {
		t.UpdateTime = time.Time(*aux.UpdateTime)
	}

	return nil
}

func (t *TunedModelInfo) MarshalJSON() ([]byte, error) {
	type Alias TunedModelInfo
	aux := &struct {
		CreateTime *time.Time `json:"createTime,omitempty"`
		UpdateTime *time.Time `json:"updateTime,omitempty"`
		*Alias
	}{
		Alias: (*Alias)(t),
	}

	if !reflect.ValueOf(t.CreateTime).IsZero() {
		aux.CreateTime = (*time.Time)(&t.CreateTime)
	}

	if !reflect.ValueOf(t.UpdateTime).IsZero() {
		aux.UpdateTime = (*time.Time)(&t.UpdateTime)
	}

	return json.Marshal(aux)
}

// Describes the machine learning model version checkpoint.
type Checkpoint struct {
	// Optional. The ID of the checkpoint.
	CheckpointID string `json:"checkpointId,omitempty"`
	// Optional. The epoch of the checkpoint.
	Epoch int64 `json:"epoch,omitempty,string"`
	// Optional. The step of the checkpoint.
	Step int64 `json:"step,omitempty,string"`
}

// A trained machine learning model.
type Model struct {
	// Optional. Resource name of the model.
	Name string `json:"name,omitempty"`
	// Optional. Display name of the model.
	DisplayName string `json:"displayName,omitempty"`
	// Optional. Description of the model.
	Description string `json:"description,omitempty"`
	// Optional. Version ID of the model. A new version is committed when a new
	// model version is uploaded or trained under an existing model ID. The
	// version ID is an auto-incrementing decimal number in string
	// representation.
	Version string `json:"version,omitempty"`
	// Optional. List of deployed models created from this base model. Note that a
	// model could have been deployed to endpoints in different locations.
	Endpoints []*Endpoint `json:"endpoints,omitempty"`
	// Optional. Labels with user-defined metadata to organize your models.
	Labels map[string]string `json:"labels,omitempty"`
	// Optional. Information about the tuned model from the base model.
	TunedModelInfo *TunedModelInfo `json:"tunedModelInfo,omitempty"`
	// Optional. The maximum number of input tokens that the model can handle.
	InputTokenLimit int32 `json:"inputTokenLimit,omitempty"`
	// Optional. The maximum number of output tokens that the model can generate.
	OutputTokenLimit int32 `json:"outputTokenLimit,omitempty"`
	// Optional. List of actions that are supported by the model.
	SupportedActions []string `json:"supportedActions,omitempty"`
	// Optional. The default checkpoint ID of a model version.
	DefaultCheckpointID string `json:"defaultCheckpointId,omitempty"`
	// Optional. The checkpoints of the model.
	Checkpoints []*Checkpoint `json:"checkpoints,omitempty"`
	// Optional. Temperature value used for sampling set when the dataset was saved.
	// This value is used to tune the degree of randomness.
	Temperature float32 `json:"temperature,omitempty"`
	// Optional. The maximum temperature value used for sampling set when the
	// dataset was saved. This value is used to tune the degree of randomness.
	MaxTemperature float32 `json:"maxTemperature,omitempty"`
	// Optional. Specifies the nucleus sampling threshold. The model
	// considers only the smallest set of tokens whose cumulative probability is
	// at least `top_p`. This helps generate more diverse and less repetitive
	// responses. For example, a `top_p` of 0.9 means the model considers tokens
	// until the cumulative probability of the tokens to select from reaches 0.9.
	// It's recommended to adjust either temperature or `top_p`, but not both.
	TopP float32 `json:"topP,omitempty"`
	// Optional. Specifies the top-k sampling threshold. The model
	// considers only the top k most probable tokens for the next token. This can
	// be useful for generating more coherent and less random text. For example,
	// a `top_k` of 40 means the model will choose the next word from the 40 most
	// likely words.
	TopK int32 `json:"topK,omitempty"`
	// Optional. Whether the model supports thinking features. If true, thoughts are
	// returned only if the model supports thought and thoughts are available.
	Thinking bool `json:"thinking,omitempty"`
}

type ListModelsConfig struct {
	// Optional. Used to override HTTP request options.
	HTTPOptions *HTTPOptions `json:"httpOptions,omitempty"`
	// Optional. PageSize specifies the maximum number of cached contents to return per
	// API call. If zero, the server will use a default value.
	PageSize int32 `json:"pageSize,omitempty"`
	// Optional. PageToken represents a token used for pagination in API responses. It's
	// an opaque string that should be passed to subsequent requests to retrieve the next
	// page of results. An empty PageToken typically indicates that there are no further
	// pages available.
	PageToken string `json:"pageToken,omitempty"`
	// Optional.
	Filter string `json:"filter,omitempty"`
	// Optional. QueryBase is a boolean flag to control whether to query base models or
	// tuned models. If nil, then SDK will use the default value Ptr(true).
	QueryBase *bool `json:"queryBase,omitempty"`
}

type ListModelsResponse struct {
	// Optional. Used to retain the full HTTP response.
	SDKHTTPResponse *HTTPResponse `json:"sdkHttpResponse,omitempty"`

	NextPageToken string `json:"nextPageToken,omitempty"`

	Models []*Model `json:"models,omitempty"`
}

// Configuration for updating a tuned model.
type UpdateModelConfig struct {
	// Optional. Used to override HTTP request options.
	HTTPOptions *HTTPOptions `json:"httpOptions,omitempty"`
	// Optional.
	DisplayName string `json:"displayName,omitempty"`
	// Optional.
	Description string `json:"description,omitempty"`
	// Optional.
	DefaultCheckpointID string `json:"defaultCheckpointId,omitempty"`
}

// Configuration for deleting a tuned model.
type DeleteModelConfig struct {
	// Optional. Used to override HTTP request options.
	HTTPOptions *HTTPOptions `json:"httpOptions,omitempty"`
}

type DeleteModelResponse struct {
	// Optional. Used to retain the full HTTP response.
	SDKHTTPResponse *HTTPResponse `json:"sdkHttpResponse,omitempty"`
}

// Configuration for audio-specific output formatting.
type AudioResponseFormat struct {
	// Optional. Bit rate in bits per second (bps). Only applicable for compressed formats
	// (MP3, Opus).
	BitRate *int32 `json:"bitRate,omitempty"`
	// Optional. Delivery mode for the generated content.
	Delivery Delivery `json:"delivery,omitempty"`
	// Optional. The MIME type of the audio output.
	MIMEType string `json:"mimeType,omitempty"`
	// Optional. Sample rate for the generated audio in Hertz.
	SampleRate *int32 `json:"sampleRate,omitempty"`
}

// Configuration for image-specific output formatting.
type ImageResponseFormat struct {
	// Optional. The aspect ratio for the image output.
	AspectRatio AspectRatio `json:"aspectRatio,omitempty"`
	// Optional. Delivery mode for the generated content.
	Delivery Delivery `json:"delivery,omitempty"`
	// Optional. The size of the image output.
	ImageSize ImageSize `json:"imageSize,omitempty"`
	// Optional. The MIME type of the image output.
	MIMEType string `json:"mimeType,omitempty"`
}

// Configuration for text-specific output formatting.
type TextResponseFormat struct {
	// Optional. The IANA standard MIME type of the response.
	MIMEType string `json:"mimeType,omitempty"`
	// Optional. The JSON schema that the output should conform to. Only applicable when
	// mime_type is APPLICATION_JSON.
	Schema any `json:"schema,omitempty"`
}

// Configuration for video-specific output formatting. This data type is not supported
// in Gemini API.
type VideoResponseFormat struct {
	// The aspect ratio for the video output.
	AspectRatio AspectRatio `json:"aspectRatio,omitempty"`
	// Optional. Delivery mode for the generated content.
	Delivery Delivery `json:"delivery,omitempty"`
	// Optional. The duration for the video output.
	Duration time.Duration `json:"duration,omitempty"`
	// Optional. The Google Cloud Storage URI to store the video output. Required for Vertex
	// if delivery is URI.
	GCSURI string `json:"gcsUri,omitempty"`
}

func (v *VideoResponseFormat) UnmarshalJSON(data []byte) error {
	type Alias VideoResponseFormat
	aux := &struct {
		Duration *InternalDurationJSON `json:"duration,omitempty"`
		*Alias
	}{
		Alias: (*Alias)(v),
	}

	if err := json.Unmarshal(data, &aux); err != nil {
		return err
	}

	if !reflect.ValueOf(aux.Duration).IsZero() {
		v.Duration = time.Duration(*aux.Duration)
	}

	return nil
}

func (v *VideoResponseFormat) MarshalJSON() ([]byte, error) {
	type Alias VideoResponseFormat
	aux := &struct {
		Duration *InternalDurationJSON `json:"duration,omitempty"`
		*Alias
	}{
		Alias: (*Alias)(v),
	}

	if !reflect.ValueOf(v.Duration).IsZero() {
		aux.Duration = (*InternalDurationJSON)(&v.Duration)
	}

	return json.Marshal(aux)
}

// Configuration for the model to configure output formatting and delivery. This data
// type is not supported in Gemini API.
type ResponseFormat struct {
	// Audio output format.
	Audio *AudioResponseFormat `json:"audio,omitempty"`
	// Image output format.
	Image *ImageResponseFormat `json:"image,omitempty"`
	// Text output format.
	Text *TextResponseFormat `json:"text,omitempty"`
	// Video output format.
	Video *VideoResponseFormat `json:"video,omitempty"`
}

// Config for stream translation.
type TranslationConfig struct {
	// Optional. If true, the model will generate audio when the target language is spoken,
	// essentially it will parrot the input. If false, we will not produce audio for the
	// target language.
	EchoTargetLanguage *bool `json:"echoTargetLanguage,omitempty"`
	// Required. The target language for translation. Supported values are BCP-47 language
	// codes (e.g. "en", "es", "fr").
	TargetLanguageCode string `json:"targetLanguageCode,omitempty"`
}

// Generation config. 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 GenerationConfig struct {
	// Optional. Config for model selection.
	ModelSelectionConfig *ModelSelectionConfig `json:"modelSelectionConfig,omitempty"`
	// Optional. Output schema of the generated response. This is an alternative to
	// `response_schema` that accepts [JSON Schema](https://json-schema.org/).
	ResponseJsonSchema any `json:"responseJsonSchema,omitempty"`
	// Optional. If enabled, audio timestamps will be included in the request to the model.
	// This can be useful for synchronizing audio with other modalities in the response.
	// This field is not supported in Gemini API.
	AudioTimestamp bool `json:"audioTimestamp,omitempty"`
	// Optional. The number of candidate responses to generate. A higher `candidate_count`
	// can provide more options to choose from, but it also consumes more resources. This
	// can be useful for generating a variety of responses and selecting the best one. If
	// empty, the system will choose a default value (currently 1).
	CandidateCount int32 `json:"candidateCount,omitempty"`
	// Optional. If enabled, the model will detect emotions and adapt its responses accordingly.
	// For example, if the model detects that the user is frustrated, it may provide a more
	// empathetic response. This field is not supported in Gemini API.
	EnableAffectiveDialog *bool `json:"enableAffectiveDialog,omitempty"`
	// Optional. Penalizes tokens based on their frequency in the generated text. A positive
	// value helps to reduce the repetition of words and phrases. Valid values can range
	// from [-2.0, 2.0].
	FrequencyPenalty *float32 `json:"frequencyPenalty,omitempty"`
	// Optional. The number of top log probabilities to return for each token. This can
	// be used to see which other tokens were considered likely candidates for a given position.
	// A higher value will return more options, but it will also increase the size of the
	// response.
	Logprobs *int32 `json:"logprobs,omitempty"`
	// Optional. The maximum number of tokens to generate in the response. A token is approximately
	// four characters. The default value varies by model. This parameter can be used to
	// control the length of the generated text and prevent overly long responses. If empty,
	// API will use a default value. The default value varies by model.
	MaxOutputTokens int32 `json:"maxOutputTokens,omitempty"`
	// Optional. The token resolution at which input media content is sampled. This is used
	// to control the trade-off between the quality of the response and the number of tokens
	// used to represent the media. A higher resolution allows the model to perceive more
	// detail, which can lead to a more nuanced response, but it will also use more tokens.
	// This does not affect the image dimensions sent to the model.
	MediaResolution MediaResolution `json:"mediaResolution,omitempty"`
	// Optional. Penalizes tokens that have already appeared in the generated text. A positive
	// value encourages the model to generate more diverse and less repetitive text. Valid
	// values can range from [-2.0, 2.0].
	PresencePenalty *float32 `json:"presencePenalty,omitempty"`
	// Optional. If set to true, the log probabilities of the output tokens are returned.
	// Log probabilities are the logarithm of the probability of a token appearing in the
	// output. A higher log probability means the token is more likely to be generated.
	// This can be useful for analyzing the model's confidence in its own output and for
	// debugging.
	ResponseLogprobs bool `json:"responseLogprobs,omitempty"`
	// Optional. The IANA standard MIME type of the response. The model will generate output
	// that conforms to this MIME type. Supported values include 'text/plain' (default)
	// and 'application/json'. The model needs to be prompted to output the appropriate
	// response type, otherwise the behavior is undefined. Deprecated: Use `response_format`
	// instead.
	ResponseMIMEType string `json:"responseMimeType,omitempty"`
	// Optional. The modalities of the response. The model will generate a response that
	// includes all the specified modalities. For example, if this is set to `[TEXT, IMAGE]`,
	// the response will include both text and an image.
	ResponseModalities []Modality `json:"responseModalities,omitempty"`
	// Optional. Lets you to specify a schema for the model's response, ensuring that the
	// output conforms to a particular structure. This is useful for generating structured
	// data such as JSON. The schema is a subset of the [OpenAPI 3.0 schema object](https://spec.openapis.org/oas/v3.0.3#schema)
	// object. When this field is set, you must also set the `response_mime_type` to `application/json`.
	// Deprecated: Use `response_format` instead.
	ResponseSchema *Schema `json:"responseSchema,omitempty"`
	// Optional. Routing configuration. This field is not supported in Gemini API.
	RoutingConfig *GenerationConfigRoutingConfig `json:"routingConfig,omitempty"`
	// Optional. A seed for the random number generator. By setting a seed, you can make
	// the model's output mostly deterministic. For a given prompt and parameters (like
	// temperature, top_p, etc.), the model will produce the same response every time. However,
	// it's not a guaranteed absolute deterministic behavior. This is different from parameters
	// like `temperature`, which control the *level* of randomness. `seed` ensures that
	// the "random" choices the model makes are the same on every run, making it essential
	// for testing and ensuring reproducible results.
	Seed *int32 `json:"seed,omitempty"`
	// Optional. The speech generation config.
	SpeechConfig *SpeechConfig `json:"speechConfig,omitempty"`
	// Optional. A list of character sequences that will stop the model from generating
	// further tokens. If a stop sequence is generated, the output will end at that point.
	// This is useful for controlling the length and structure of the output. For example,
	// you can use ["\n", "###"] to stop generation at a new line or a specific marker.
	StopSequences []string `json:"stopSequences,omitempty"`
	// Optional. Controls the randomness of the output. A higher temperature results in
	// more creative and diverse responses, while a lower temperature makes the output more
	// predictable and focused. The valid range is (0.0, 2.0].
	Temperature *float32 `json:"temperature,omitempty"`
	// Optional. Configuration for thinking features. An error will be returned if this
	// field is set for models that don't support thinking.
	ThinkingConfig *ThinkingConfig `json:"thinkingConfig,omitempty"`
	// Optional. Specifies the top-k sampling threshold. The model considers only the top
	// k most probable tokens for the next token. This can be useful for generating more
	// coherent and less random text. For example, a `top_k` of 40 means the model will
	// choose the next word from the 40 most likely words.
	TopK *float32 `json:"topK,omitempty"`
	// Optional. Specifies the nucleus sampling threshold. The model considers only the
	// smallest set of tokens whose cumulative probability is at least `top_p`. This helps
	// generate more diverse and less repetitive responses. For example, a `top_p` of 0.9
	// means the model considers tokens until the cumulative probability of the tokens to
	// select from reaches 0.9. It's recommended to adjust either temperature or `top_p`,
	// but not both.
	TopP *float32 `json:"topP,omitempty"`
	// Optional. Enables enhanced civic answers. It may not be available for all models.
	// This field is not supported in Vertex AI.
	EnableEnhancedCivicAnswers *bool `json:"enableEnhancedCivicAnswers,omitempty"`
	// Optional. New response format field for the model to configure output formatting
	// and delivery.
	ResponseFormat []*ResponseFormat `json:"responseFormat,omitempty"`
	// Optional. Config for translation. This field is not supported in Vertex AI.
	TranslationConfig *TranslationConfig `json:"translationConfig,omitempty"`
}

// Config for the count_tokens method.
type CountTokensConfig struct {
	// Optional. Used to override HTTP request options.
	HTTPOptions *HTTPOptions `json:"httpOptions,omitempty"`
	// Optional. Instructions for the model to steer it toward better performance.
	SystemInstruction *Content `json:"systemInstruction,omitempty"`
	// Optional. 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"`
	// Optional. Configuration that the model uses to generate the response. Not
	// supported by the Gemini Developer API.
	GenerationConfig *GenerationConfig `json:"generationConfig,omitempty"`
}

// Response for counting tokens.
type CountTokensResponse struct {
	// Optional. Used to retain the full HTTP response.
	SDKHTTPResponse *HTTPResponse `json:"sdkHttpResponse,omitempty"`
	// Total number of tokens.
	TotalTokens int32 `json:"totalTokens,omitempty"`
	// Number of tokens in the cached part of the prompt (the cached content). This field
	// is only available in the Gemini API.
	CachedContentTokenCount int32 `json:"cachedContentTokenCount,omitempty"`
}

// Optional parameters for computing tokens.
type ComputeTokensConfig struct {
	// Optional. Used to override HTTP request options.
	HTTPOptions *HTTPOptions `json:"httpOptions,omitempty"`
}

// Tokens info with a list of tokens and the corresponding list of token ids.
type TokensInfo struct {
	// Optional. Optional fields for the role from the corresponding Content.
	Role string `json:"role,omitempty"`
	// Optional. A list of token IDs from the input.
	TokenIDs []int64 `json:"tokenIds,omitempty"`
	// Optional. A list of tokens from the input.
	Tokens [][]byte `json:"tokens,omitempty"`
}

func (t *TokensInfo) UnmarshalJSON(data []byte) error {
	type Alias TokensInfo
	aux := &struct {
		TokenIDs InternalInt64SliceJSON `json:"tokenIds,omitempty"`
		*Alias
	}{
		Alias: (*Alias)(t),
	}

	if err := json.Unmarshal(data, &aux); err != nil {
		return err
	}

	if !reflect.ValueOf(aux.TokenIDs).IsZero() {
		t.TokenIDs = aux.TokenIDs
	}

	return nil
}

func (t *TokensInfo) MarshalJSON() ([]byte, error) {
	type Alias TokensInfo
	aux := &struct {
		TokenIDs InternalInt64SliceJSON `json:"tokenIds,omitempty"`
		*Alias
	}{
		Alias: (*Alias)(t),
	}

	if !reflect.ValueOf(t.TokenIDs).IsZero() {
		aux.TokenIDs = t.TokenIDs
	}

	return json.Marshal(aux)
}

// Response for computing tokens.
type ComputeTokensResponse struct {
	// Optional. Used to retain the full HTTP response.
	SDKHTTPResponse *HTTPResponse `json:"sdkHttpResponse,omitempty"`
	// Lists of tokens info from the input. A ComputeTokensRequest could have multiple instances
	// with a prompt in each instance. We also need to return lists of tokens info for the
	// request with multiple instances.
	TokensInfo []*TokensInfo `json:"tokensInfo,omitempty"`
}

// A generated video.
type Video struct {
	// Optional. Path to another storage.
	URI string `json:"uri,omitempty"`
	// Optional. Video bytes.
	VideoBytes []byte `json:"videoBytes,omitempty"`
	// Optional. Video encoding, for example ``video/mp4``.
	MIMEType string `json:"mimeType,omitempty"`
}

func (v *Video) uri() string {
	return v.URI
}

func (v *Video) setVideoBytes(b []byte) bool {
	v.VideoBytes = b
	return true
}

// A set of source input(s) for video generation.
type GenerateVideosSource struct {
	// Optional. The text prompt for generating the videos.
	// Optional if image or video is provided.
	Prompt string `json:"prompt,omitempty"`
	// Optional. The input image for generating the videos.
	// Optional if prompt is provided. Not allowed if video is provided.
	Image *Image `json:"image,omitempty"`
	// Optional. The input video for video extension use cases.
	// Optional if prompt is provided. Not allowed if image is provided.
	Video *Video `json:"video,omitempty"`
}

// A reference image for video generation.
type VideoGenerationReferenceImage struct {
	// The reference image.
	Image *Image `json:"image,omitempty"`
	// The type of the reference image, which defines how the reference
	// image will be used to generate the video.
	ReferenceType VideoGenerationReferenceType `json:"referenceType,omitempty"`
}

// A mask for video generation.
type VideoGenerationMask struct {
	// Optional. The image mask to use for generating videos.
	Image *Image `json:"image,omitempty"`
	// Describes how the mask will be used. Inpainting masks must
	// match the aspect ratio of the input video. Outpainting masks can be
	// either 9:16 or 16:9.
	MaskMode VideoGenerationMaskMode `json:"maskMode,omitempty"`
}

// Configuration for webhook notifications.
// Used to configure webhook endpoints that will receive notifications
// when long-running operations (e.g., batch jobs, video generation) complete.
type WebhookConfig struct {
	// Optional. The webhook URIs to receive notifications. If set, these
	// webhook URIs will be used instead of the registered webhooks.
	Uris []string `json:"uris,omitempty"`
	// Optional. User metadata that will be included in each webhook event
	// notification. Use this to attach custom key-value data to correlate
	// webhook events with your internal systems.
	UserMetadata map[string]any `json:"userMetadata,omitempty"`
}

// You can find API default values and more details at Gemini Enterprise Agent Platform:
// https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/veo-video-generation.
type GenerateVideosConfig struct {
	// Optional. Used to override HTTP request options.
	HTTPOptions *HTTPOptions `json:"httpOptions,omitempty"`
	// Optional. Number of output videos. If empty, the system will choose a default value.
	NumberOfVideos int32 `json:"numberOfVideos,omitempty"`
	// Optional. The GCS bucket where to save the generated videos.
	OutputGCSURI string `json:"outputGcsUri,omitempty"`
	// Optional. Frames per second for video generation.
	FPS *int32 `json:"fps,omitempty"`
	// Optional. Duration of the clip for video generation in seconds.
	DurationSeconds *int32 `json:"durationSeconds,omitempty"`
	// Optional. The RNG seed. If RNG seed is exactly same for each request with
	// unchanged inputs, the prediction results will be consistent. Otherwise,
	// a random RNG seed will be used each time to produce a different
	// result.
	Seed *int32 `json:"seed,omitempty"`
	// Optional. The aspect ratio for the generated video. 16:9 (landscape) and
	// 9:16 (portrait) are supported.
	AspectRatio string `json:"aspectRatio,omitempty"`
	// Optional. The resolution for the generated video. 720p and 1080p are
	// supported.
	Resolution string `json:"resolution,omitempty"`
	// Optional. Whether allow to generate person videos, and restrict to specific
	// ages. Supported values are: dont_allow, allow_adult.
	PersonGeneration string `json:"personGeneration,omitempty"`
	// Optional. The pubsub topic where to publish the video generation
	// progress.
	PubsubTopic string `json:"pubsubTopic,omitempty"`
	// Optional. Explicitly state what should not be included in the generated
	// videos.
	NegativePrompt string `json:"negativePrompt,omitempty"`
	// Optional. Whether to use the prompt rewriting logic.
	EnhancePrompt bool `json:"enhancePrompt,omitempty"`
	// Optional. Whether to generate audio along with the video.
	GenerateAudio *bool `json:"generateAudio,omitempty"`
	// Optional. Image to use as the last frame of generated videos.
	// Only supported for image to video use cases.
	LastFrame *Image `json:"lastFrame,omitempty"`
	// Optional. The images to use as the references to generate the videos.
	// If this field is provided, the text prompt field must also be provided.
	// The image, video, or last_frame field are not supported. Each image must
	// be associated with a type. Veo 2 supports up to 3 asset images *or* 1
	// style image.
	ReferenceImages []*VideoGenerationReferenceImage `json:"referenceImages,omitempty"`
	// Optional. The mask to use for generating videos.
	Mask *VideoGenerationMask `json:"mask,omitempty"`
	// Optional. Compression quality of the generated videos.
	CompressionQuality VideoCompressionQuality `json:"compressionQuality,omitempty"`
	// Optional. User specified labels to track billing usage.
	Labels map[string]string `json:"labels,omitempty"`
	// Optional. Webhook configuration for receiving notifications when the
	// video generation operation completes.
	WebhookConfig *WebhookConfig `json:"webhookConfig,omitempty"`
	// Optional. Resize mode of the image input for video generation.
	ResizeMode ImageResizeMode `json:"resizeMode,omitempty"`
}

// A generated video.
type GeneratedVideo struct {
	// Optional. The output video
	Video *Video `json:"video,omitempty"`
}

func (v *GeneratedVideo) uri() string {
	return v.Video.uri()
}

func (v *GeneratedVideo) setVideoBytes(b []byte) bool {
	v.Video.setVideoBytes(b)
	return true
}

// Response with generated videos.
type GenerateVideosResponse struct {
	// List of the generated videos
	GeneratedVideos []*GeneratedVideo `json:"generatedVideos,omitempty"`
	// Returns if any videos were filtered due to RAI policies.
	RAIMediaFilteredCount int32 `json:"raiMediaFilteredCount,omitempty"`
	// Returns RAI failure reasons if any.
	RAIMediaFilteredReasons []string `json:"raiMediaFilteredReasons,omitempty"`
}

// A video generation operation.
type GenerateVideosOperation struct {
	// The server-assigned name, which is only unique within the same service that originally
	// returns it. If you use the default HTTP mapping, the `name` should be a resource
	// name ending with `operations/{unique_id}`.
	Name string `json:"name,omitempty"`
	// Optional. Service-specific metadata associated with the operation. It typically contains
	// progress information and common metadata such as create time. Some services might
	// not provide such metadata. Any method that returns a long-running operation should
	// document the metadata type, if any.
	Metadata map[string]any `json:"metadata,omitempty"`
	// If the value is `false`, it means the operation is still in progress. If `true`,
	// the operation is completed, and either `error` or `response` is available.
	Done bool `json:"done,omitempty"`
	// Optional. The error result of the operation in case of failure or cancellation.
	Error map[string]any `json:"error,omitempty"`
	// Optional. The generated videos.
	Response *GenerateVideosResponse `json:"response,omitempty"`
}

// Optional parameters for tunings.get method.
type GetTuningJobConfig struct {
	// Optional. Used to override HTTP request options.
	HTTPOptions *HTTPOptions `json:"httpOptions,omitempty"`
}

// TunedModelCheckpoint for the Tuned Model of a Tuning Job.
type TunedModelCheckpoint struct {
	// Optional. The ID of the checkpoint.
	CheckpointID string `json:"checkpointId,omitempty"`
	// Optional. The epoch of the checkpoint.
	Epoch int64 `json:"epoch,omitempty,string"`
	// Optional. The step of the checkpoint.
	Step int64 `json:"step,omitempty,string"`
	// Optional. The Endpoint resource name that the checkpoint is deployed to.
	// Format: `projects/{project}/locations/{location}/endpoints/{endpoint}`.
	Endpoint string `json:"endpoint,omitempty"`
}

// TunedModel for the Tuned Model of a Tuning Job.
type TunedModel struct {
	// Output only. The resource name of the TunedModel.
	// Format: `projects/{project}/locations/{location}/models/{model}@{version_id}`
	// When tuning from a base model, the version_id will be 1.
	// For continuous tuning, the version ID will be incremented by 1 from the
	// last version ID in the parent model. E.g., `projects/{project}/locations/{location}/models/{model}@{last_version_id
	// + 1}`
	Model string `json:"model,omitempty"`
	// Output only. A resource name of an Endpoint.
	// Format: `projects/{project}/locations/{location}/endpoints/{endpoint}`.
	Endpoint string `json:"endpoint,omitempty"`
	// The checkpoints associated with this TunedModel.
	// This field is only populated for tuning jobs that enable intermediate
	// checkpoints.
	Checkpoints []*TunedModelCheckpoint `json:"checkpoints,omitempty"`
}

// Hyperparameters for SFT. This data type is not supported in Gemini API.
type SupervisedHyperParameters struct {
	// Optional. Adapter size for tuning.
	AdapterSize AdapterSize `json:"adapterSize,omitempty"`
	// Optional. Batch size for tuning. This feature is only available for open source models.
	BatchSize int64 `json:"batchSize,omitempty,string"`
	// Optional. Number of complete passes the model makes over the entire training dataset
	// during training.
	EpochCount int64 `json:"epochCount,omitempty,string"`
	// Optional. Learning rate for tuning. Mutually exclusive with `learning_rate_multiplier`.
	// This feature is only available for open source models.
	LearningRate float64 `json:"learningRate,omitempty"`
	// Optional. Multiplier for adjusting the default learning rate. Mutually exclusive
	// with `learning_rate`. This feature is only available for 1P models.
	LearningRateMultiplier float64 `json:"learningRateMultiplier,omitempty"`
}

// Supervised tuning spec for tuning.
type SupervisedTuningSpec struct {
	// Optional. If set to true, disable intermediate checkpoints for SFT and only the last
	// checkpoint will be exported. Otherwise, enable intermediate checkpoints for SFT.
	// Default is false.
	ExportLastCheckpointOnly bool `json:"exportLastCheckpointOnly,omitempty"`
	// Optional. Hyperparameters for SFT.
	HyperParameters *SupervisedHyperParameters `json:"hyperParameters,omitempty"`
	// Required. Training dataset used for tuning. The dataset can be specified as either
	// a Cloud Storage path to a JSONL file or as the resource name of a Vertex Multimodal
	// Dataset.
	TrainingDatasetURI string `json:"trainingDatasetUri,omitempty"`
	// Tuning mode.
	TuningMode TuningMode `json:"tuningMode,omitempty"`
	// Optional. Validation dataset used for tuning. The dataset can be specified as either
	// a Cloud Storage path to a JSONL file or as the resource name of a Vertex Multimodal
	// Dataset.
	ValidationDatasetURI string `json:"validationDatasetUri,omitempty"`
}

// Hyperparameters for Preference Optimization. This data type is not supported in Gemini
// API.
type PreferenceOptimizationHyperParameters struct {
	// Optional. Adapter size for preference optimization.
	AdapterSize AdapterSize `json:"adapterSize,omitempty"`
	// Optional. Weight for KL Divergence regularization.
	Beta float64 `json:"beta,omitempty"`
	// Optional. Number of complete passes the model makes over the entire training dataset
	// during training.
	EpochCount int64 `json:"epochCount,omitempty,string"`
	// Optional. Multiplier for adjusting the default learning rate.
	LearningRateMultiplier float64 `json:"learningRateMultiplier,omitempty"`
}

// Preference optimization tuning spec for tuning.
type PreferenceOptimizationSpec struct {
	// Optional. If set to true, disable intermediate checkpoints for Preference Optimization
	// and only the last checkpoint will be exported. Otherwise, enable intermediate checkpoints
	// for Preference Optimization. Default is false.
	ExportLastCheckpointOnly bool `json:"exportLastCheckpointOnly,omitempty"`
	// Optional. Hyperparameters for Preference Optimization.
	HyperParameters *PreferenceOptimizationHyperParameters `json:"hyperParameters,omitempty"`
	// Required. Cloud Storage path to file containing training dataset for preference optimization
	// tuning. The dataset must be formatted as a JSONL file.
	TrainingDatasetURI string `json:"trainingDatasetUri,omitempty"`
	// Optional. Cloud Storage path to file containing validation dataset for preference
	// optimization tuning. The dataset must be formatted as a JSONL file.
	ValidationDatasetURI string `json:"validationDatasetUri,omitempty"`
}

// Distillation hyperparameters for tuning.
type DistillationHyperParameters struct {
	// Optional. The size of the adapter. Can be 'small', 'medium', or 'large'.
	AdapterSize AdapterSize `json:"adapterSize,omitempty"`
	// Optional. Number of complete passes the model makes over the entire training dataset
	// during training.
	EpochCount int64 `json:"epochCount,omitempty,string"`
	// Optional. Multiplier for adjusting the default learning rate.
	LearningRateMultiplier float32 `json:"learningRateMultiplier,omitempty"`
	// Optional. Generation config for Distillation teacher model sampling. Only the
	// following fields are supported for distillation teacher samplings:
	//   - temperature
	//   - top_p
	//   - top_k
	//   - candidate_count
	//   - thinking_config
	GenerationConfig *GenerationConfig `json:"generationConfig,omitempty"`
	// Optional. The learning rate for distillation tuning.
	LearningRate float32 `json:"learningRate,omitempty"`
	// Optional. Batch size for tuning. This feature is only available for open
	// source models.
	BatchSize int32 `json:"batchSize,omitempty"`
}

// Distillation sampling spec for tuning.
type DistillationSamplingSpec struct {
	// Optional. The base teacher model that is being distilled. See [Supported
	// models](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/tuning#supported_models).
	BaseTeacherModel string `json:"baseTeacherModel,omitempty"`
	// Optional. The resource name of the Tuned teacher model. Format:
	// `projects/{project}/locations/{location}/models/{model}`.
	TunedTeacherModelSource string `json:"tunedTeacherModelSource,omitempty"`
	// Cloud Storage path to file containing validation dataset for distillation.
	// The dataset must be formatted as a JSONL file.
	ValidationDatasetURI string `json:"validationDatasetUri,omitempty"`
	// Cloud Storage path to file containing prompt dataset for distillation.
	// The dataset must be formatted as a JSONL file.
	PromptDatasetURI string `json:"promptDatasetUri,omitempty"`
	// Optional. Hyperparameters for distillation tuning.
	Hyperparameters *DistillationHyperParameters `json:"hyperparameters,omitempty"`
}

// Distillation tuning spec for tuning.
type DistillationSpec struct {
	// Optional. Cloud Storage path to file containing prompt dataset for distillation.
	// The dataset must be formatted as a JSONL file.
	PromptDatasetURI string `json:"promptDatasetUri,omitempty"`
	// The base teacher model that is being distilled. See [Supported models](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/tuning#supported_models).
	BaseTeacherModel string `json:"baseTeacherModel,omitempty"`
	// Optional. Hyperparameters for Distillation.
	HyperParameters *DistillationHyperParameters `json:"hyperParameters,omitempty"`
	// Deprecated. A path in a Cloud Storage bucket, which will be treated as the root output
	// directory of the distillation pipeline. It is used by the system to generate the
	// paths of output artifacts.
	PipelineRootDirectory string `json:"pipelineRootDirectory,omitempty"`
	// The student model that is being tuned, e.g., "google/gemma-2b-1.1-it". Deprecated.
	// Use base_model instead.
	StudentModel string `json:"studentModel,omitempty"`
	// Deprecated. Cloud Storage path to file containing training dataset for tuning. The
	// dataset must be formatted as a JSONL file.
	TrainingDatasetURI string `json:"trainingDatasetUri,omitempty"`
	// The resource name of the Tuned teacher model. Format: `projects/{project}/locations/{location}/models/{model}`.
	TunedTeacherModelSource string `json:"tunedTeacherModelSource,omitempty"`
	// Optional. Cloud Storage path to file containing validation dataset for tuning. The
	// dataset must be formatted as a JSONL file.
	ValidationDatasetURI string `json:"validationDatasetUri,omitempty"`
	// Optional. Specifies the tuning mode for distillation (sft part). This feature is
	// only available for open source models.
	TuningMode TuningMode `json:"tuningMode,omitempty"`
}

// Autorater config used for evaluation.
type AutoraterConfig struct {
	// Optional. Number of samples for each instance in the dataset.
	// If not specified, the default is 4. Minimum value is 1, maximum value
	// is 32.
	SamplingCount *int32 `json:"samplingCount,omitempty"`
	// Optional. Default is true. Whether to flip the candidate and baseline
	// responses. This is only applicable to the pairwise metric. If enabled, also
	// provide PairwiseMetricSpec.candidate_response_field_name and
	// PairwiseMetricSpec.baseline_response_field_name. When rendering
	// PairwiseMetricSpec.metric_prompt_template, the candidate and baseline
	// fields will be flipped for half of the samples to reduce bias.
	FlipEnabled *bool `json:"flipEnabled,omitempty"`
	// Optional. The fully qualified name of the publisher model or tuned autorater
	// endpoint to use.
	// Publisher model format:
	// `projects/{project}/locations/{location}/publishers/{publisher}/models/{model}`
	// Tuned model endpoint format:
	// `projects/{project}/locations/{location}/endpoints/{endpoint}`
	AutoraterModel string `json:"autoraterModel,omitempty"`
	// Optional. Configuration options for model generation and outputs.
	GenerationConfig *GenerationConfig `json:"generationConfig,omitempty"`
}

// Defines how to parse sample response config for reinforcement tuning. The parsed
// response (i.e., substring) will be passed to the reward functions. For example, the
// input prompt might be: > "Perform step-by-step thoughts first to problem A, finally
// output answer in the <ans> </ans> block." The sample response from the model under
// tuning might look like: > "<ans>Yes</ans>" Here, users can define the following parse
// config: ``` { "parseType": "REGEX_EXTRACT", "regexExtractExpression": ".*(.*?)" }
// ``` The resulting parsed response would be `"Yes"` and will be passed to the reward
// functions for evaluating rewards. This data type is not supported in Gemini API.
type ReinforcementTuningParseResponseConfig struct {
	// Defines the type for parsing sample response.
	ParseType ResponseParseType `json:"parseType,omitempty"`
	// Defines the regex for extracting the important part of sample response. This field
	// is only used when parse_type is ResponseParseType.REGEX_EXTRACT.
	RegexExtractExpression string `json:"regexExtractExpression,omitempty"`
}

// Scores responses by directly converting the parsed autorater response to a float
// reward. Note: Reward is clipped to be within `[-1, 1]`, i.e., `reward = max(min(reward,
// 1.0), -1.0)`. This data type is not supported in Gemini API.
type ReinforcementTuningAutoraterScorerParsedResponseConversionScorer struct {
}

// Scores autorater responses by using exact string match reward scorer. This data type
// is not supported in Gemini API.
type ReinforcementTuningAutoraterScorerExactMatchScorer struct {
	// Assigns this reward score if the parsed response string equals the expression.
	CorrectAnswerReward *float32 `json:"correctAnswerReward,omitempty"`
	// Assigns this reward score if the parsed reward value does not equal the expression.
	WrongAnswerReward *float32 `json:"wrongAnswerReward,omitempty"`
	// The string expression to match against for scoring. This field supports placeholders
	// in the format of {{references.key}} that will be replaced before matching. Regex
	// is not supported for this expression. For example, users can define an ExactMatchScorer
	// as follows: { "correctAnswerReward": 1.0, "wrongAnswerReward": -1.0, "expression":
	// "{{references.concise_answer}}" } When evaluating the reward for each parsed autorater
	// response, if the prompt references in the training/validation dataset has the following
	// fields: ``` { "example": ..., "references": { "concise_ansser": "Yes", "verbose_answer":
	// "The answer is Yes" } } ``` The above ExactMatchScorer will be replaced as follows
	// for scoring: ``` { "correctAnswerReward": 1.0, "wrongAnswerReward": -1.0, "expression":
	// "Yes" } ``` If the *parsed* autorater response is equal to the string `"Yes"`, then
	// the reward is `1.0`, otherwise the reward is `-1.0`.
	Expression string `json:"expression,omitempty"`
}

// Reinforcement tuning autorater scorer.
type ReinforcementTuningAutoraterScorer struct {
	// Optional. Autorater config for evaluation.
	AutoraterConfig *AutoraterConfig `json:"autoraterConfig,omitempty"`
	// The prompt for an autorater to scorer the parsed sample response. This field supports
	// the following placeholders that will be replaced before scoring: - {{prompt}} - {{response}}
	// - {{system_instruction}} - {{references.key}}
	AutoraterPrompt string `json:"autoraterPrompt,omitempty"`
	// Parses autorater returned response for scoring. For example, if the autorater response
	// has reward stored in the `2.0` block, defining a parsing response config using regex
	// `".*(.*?)"` will return a score `"2.0"`.
	AutoraterResponseParseConfig *ReinforcementTuningParseResponseConfig `json:"autoraterResponseParseConfig,omitempty"`
	// Scores autorater responses by directly converting parsed autorater response to a
	// float reward. Note: Reward is clipped to be within `[-1, 1]`, i.e., `reward = max(min(reward,
	// 1.0), -1.0)`.
	ParsedResponseConversionScorer *ReinforcementTuningAutoraterScorerParsedResponseConversionScorer `json:"parsedResponseConversionScorer,omitempty"`
	// Scores autorater responses by using string match reward scorer.
	ExactMatchScorer *ReinforcementTuningAutoraterScorerExactMatchScorer `json:"exactMatchScorer,omitempty"`
}

// ReinforcementTuningCodeExecutionRewardScorer allows users to implement a function
// to evaluate rewards for the sample response. The function signature is as follows:
// ``` def evaluate(example: dict[str, Any], response: dict[str, Any]) -> float: ...
// ``` `example` is a ReinforcementTuningExample in ProtoJSON format, (i.e., the format
// is the same as as one line in the training/validation dataset except that the keys
// must be in camel case). System instructions (i.e., `example.get("systemInstruction")`)
// and references (i.e., `example.get("references")`) are also included in the `example`
// provided that they are set in the training/validation dataset. `response` is a Content
// in ProtoJSON format (i.e., keys must be in camel case), which is the same as the
// Online Prediction response for Gemini models. Note: Reward output by the `evaluate`
// function is clipped to be within `[-1, 1]`, i.e., `reward = max(min(reward, 1.0),
// -1.0)`. This data type is not supported in Gemini API.
type ReinforcementTuningCodeExecutionRewardScorer struct {
	// The python code snippet as a string for evaluating rewards. The following is an example
	// python code snippet that returns a reward `1.0` for a parsed response matching the
	// user-provided reference answer in per prompt references map. ``` def evaluate(example,
	// response) -> float: response_str = response.get("parts", [])0 references = example.get("references",
	// {}) if response_str == references.get("concise_answer"): return 1.0 return -1.0 ```
	// Note: Reward output by the evaluate function is clipped to be within `[-1, 1]`, i.e.,
	// `reward = max(min(reward, 1.0), -1.0)`.
	PythonCodeSnippet string `json:"pythonCodeSnippet,omitempty"`
}

// Evaluates parsed response using match type against the expression. Returns `true`
// if `MatchOperation(target, expression)` evaluates to `true`, and `false` otherwise.
// This data type is not supported in Gemini API.
type ReinforcementTuningStringMatchRewardScorerStringMatchExpression struct {
	// Match operation to use for evaluating rewards.
	MatchOperation MatchOperation `json:"matchOperation,omitempty"`
	// A string or a regular expression to match against for evaluating rewards. Users can
	// also provide a references map of `{key: value}` whose `value` will be used to replace
	// the placeholder {{references.key}} in the expression. For example, if the following
	// `references` are defined in the training / validation dataset: ``` { "systemInstruction":
	// ..., "contents": ..., "references": { "concise_answer": "Yes", "verbose_answer":
	// "The answer is Yes" } } ``` and if users define the following StringMatchExpression:
	// { "matchOperation": "REGEX_CONTAINS", "expression": ".*{{references.concise_answer}}.*"
	// } On evaluating the reward for each sample response, this StringMatchExpression will
	// be substituted as: ``` { "matchOperation": "REGEX_CONTAINS", "expression": ".*Yes.*"
	// } ```
	Expression string `json:"expression,omitempty"`
}

// JsonMatchExpression supports converting the parsed responses to JSON format, finding
// the value in the JSON response that matches the key_name in the first level, and
// performing StringMatchExpression operation on the matched JSON value. This data type
// is not supported in Gemini API.
type ReinforcementTuningStringMatchRewardScorerJsonMatchExpression struct {
	// The key name to find the value in the parsed response that's in JSON format. Only
	// first-level key matching is supported.
	KeyName string `json:"keyName,omitempty"`
	// String match expression to match against the extracted value from the JSON representation
	// of the parsed response.
	ValueStringMatchExpression *ReinforcementTuningStringMatchRewardScorerStringMatchExpression `json:"valueStringMatchExpression,omitempty"`
}

// ReinforcementTuningStringMatchRewardScorer is used to score parsed responses for
// string matching use cases. For example, for math problems, users can use string match
// scorer to check if the correct exact answer is generated. Note: Reward returned by
// the string match reward function is clipped to be within `[-1, 1]` if wrongAnswerReward
// or correctAnswerReward are beyond the range, i.e., `reward = max(min(reward, 1.0),
// -1.0)`. This data type is not supported in Gemini API.
type ReinforcementTuningStringMatchRewardScorer struct {
	// Wrong answer reward is returned if the parsed response is evaluated as `false`. All
	// wrong answers get the same reward.
	WrongAnswerReward *float32 `json:"wrongAnswerReward,omitempty"`
	// Correct answer rewawrd is returned if the parsed response is evaluated as `true`.
	// All correct answers get the same reward.
	CorrectAnswerReward *float32 `json:"correctAnswerReward,omitempty"`
	// Uses string match expression to evaluate parsed response.
	StringMatchExpression *ReinforcementTuningStringMatchRewardScorerStringMatchExpression `json:"stringMatchExpression,omitempty"`
	// Uses json match expression to evaluate parsed response.
	JsonMatchExpression *ReinforcementTuningStringMatchRewardScorerJsonMatchExpression `json:"jsonMatchExpression,omitempty"`
}

// ReinforcementTuningCloudRunRewardScorer allows users to implement a reward function
// through GCP Cloud Run. Comparing with ReinforcementTuningCodeExecutionRewardScorer
// that runs in a Sandbox and has no internet access, Cloud Run reward scorer is fully
// controlled by users. The Cloud Run service should implement the following HTTP API:
// HTTP method: `POST` HTTP request body: ``` { "example": ReinforcementTuningExample,
// "response": Content, "metadata": { "step": int "tuning_job_id": int64 } } ``` * `example`
// is a ReinforcementTuningExample in ProtoJSON format, (i.e., the format is the same
// as as one line in the training/validation dataset except that the keys must be in
// camel case). System instructions (i.e., `example.get("systemInstruction")`) and references
// (i.e., `example.get("references")`) are also included in the `example` provided that
// they are set in the training/validation dataset. * `response` is a Content in ProtoJSON
// format (i.e., keys must be in camel case), which is the same as the Online Prediction
// response for Gemini models. HTTP response body: { "reward": float, "user_requested_aux_info":
// str // Optional } where the field "user_requested_aux_info" is any (optional) string
// provided by users for assisting debugging. It's in snake case. This field is mostly
// useful when calling the GenAITuningService.ValidateReinforcementTuningReward API,
// where the proto field (not Cloud Run HTTP response body) userRequestedAuxInfo will
// be populated if the Cloud Run reward function sets this field in the HTTP response.
// The following are examples for the HTTP request and response body. Example HTTP request
// body: ``` { "example": { "contents": [ { "role": "user", "parts": [ { "text": "What
// is the capital of France?" } ] } ], "references": { "answer": "Paris" } }, "response":
// { "parts": [ { "text": "London" } ] }, "metadata": { "step": 1, "tuning_job_id":
// 123456789 } } ``` Example HTTP response body: ``` { "reward": -1.0 } ``` Note: Reward
// output by Cloud Run reward function is clipped to be within `[-1, 1]`, i.e., `reward
// = max(min(reward, 1.0), -1.0)`. This data type is not supported in Gemini API.
type ReinforcementTuningCloudRunRewardScorer struct {
	// URI of the Cloud Run service that will be used to compute the reward. The [Vertex
	// AI Secure Fine Tuning Service Agent](https://docs.cloud.google.com/iam/docs/service-agents#vertex-ai-secure-fine-tuning-service-agent)
	// (`service-@gcp-sa-vertex-tune.iam.gserviceaccount.com`) must be granted the permission
	// (e.g. by granting `roles/run.invoker` in IAM) to invoke the Cloud Run service.
	CloudRunURI string `json:"cloudRunUri,omitempty"`
}

// Single reinforcement tuning reward config.
type SingleReinforcementTuningRewardConfig struct {
	// Scores parsed responses for autorater use cases by using a model to compute the reward.
	AutoraterScorer *ReinforcementTuningAutoraterScorer `json:"autoraterScorer,omitempty"`
	// A unique reward name for identifying each single reinforcement tuning reward.
	RewardName string `json:"rewardName,omitempty"`
	// Defines how to parse sample response. For example, given a sample response for evaluating
	// the reward, users might want to extract the text only between `` and `` in the sample
	// response, and keeps only the last one in case there are multiple such tags. To achieve
	// such a purpose, they can define a regex `".*(.*?)"` using the ReinforcementTuningParseResponseConfig.ResponseParseType.REGEX_EXTRACT
	// parse type.
	ParseResponseConfig *ReinforcementTuningParseResponseConfig `json:"parseResponseConfig,omitempty"`
	// ReinforcementTuningCodeExecutionRewardScorer is used to score parsed responses for
	// code execution use cases.
	CodeExecutionRewardScorer *ReinforcementTuningCodeExecutionRewardScorer `json:"codeExecutionRewardScorer,omitempty"`
	// ReinforcementTuningStringMatchRewardScorer is used to score parsed responses for
	// simple string matching use cases against reference answers.
	StringMatchRewardScorer *ReinforcementTuningStringMatchRewardScorer `json:"stringMatchRewardScorer,omitempty"`
	// ReinforcementTuningCloudRunRewardScorer is used to score parsed responses by calling
	// a Cloud Run service.
	CloudRunRewardScorer *ReinforcementTuningCloudRunRewardScorer `json:"cloudRunRewardScorer,omitempty"`
}

// Composite reinforcement tuning reward config weighted reward config.
type CompositeReinforcementTuningRewardConfigWeightedRewardConfig struct {
	// Single reward configuration.
	RewardConfig *SingleReinforcementTuningRewardConfig `json:"rewardConfig,omitempty"`
	// How much this single reward contributes to the total overall reward. Total reward
	// is a linear combination of single rewards with their corresponding weights, i.e.,
	// ``` total_reward = ( weight_a * reward_a + weight_b * reward_b + ... ) / (weight_a
	// + weight_b + ...) ```
	Weight *float32 `json:"weight,omitempty"`
}

// Composite reinforcement tuning reward config.
type CompositeReinforcementTuningRewardConfig struct {
	// List of reward function configurations with weights.
	WeightedRewardConfigs []*CompositeReinforcementTuningRewardConfigWeightedRewardConfig `json:"weightedRewardConfigs,omitempty"`
}

// Hyperparameters for Reinforcement Tuning.
type ReinforcementTuningHyperParameters struct {
	// Optional. Number of training epoches for the tuning job.
	EpochCount int64 `json:"epochCount,omitempty,string"`
	// Optional. Learning rate multiplier for Reinforcement Learning.
	LearningRateMultiplier float32 `json:"learningRateMultiplier,omitempty"`
	// Optional. Adapter size for Reinforcement Tuning.
	AdapterSize AdapterSize `json:"adapterSize,omitempty"`
	// Optional. Number of different responses to generate per prompt during tuning.
	SamplesPerPrompt int32 `json:"samplesPerPrompt,omitempty"`
	// Optional. Batch size for the tuning job. How many prompts to process at a train step.
	// If not set, the batch size will be determined automatically.
	BatchSize int32 `json:"batchSize,omitempty"`
	// Optional. How often at steps to evaluate the tuning job during training. If not set,
	// evel will be run per epoch. `total_steps = epoch_count * samples_per_prompt / total_prompts_in_dataset`
	EvaluateInterval int32 `json:"evaluateInterval,omitempty"`
	// Optional. How often at steps to save checkpoints during training. If not set, one
	// checkpoint per epoch will be set. ```total_steps = epoch_count * samples_per_prompt
	// / total_prompts_in_dataset```
	CheckpointInterval int32 `json:"checkpointInterval,omitempty"`
	// Optional. The maximum number of tokens to generate per prompt. Default to 32768.
	MaxOutputTokens int32 `json:"maxOutputTokens,omitempty"`
	// Indicates the maximum thinking depth during tuning. Starting from Gemini 3.5 models,
	// the old thinking_budget will no longer be supported and will result in a user error
	// if set. Instead, users should use the thinking_level parameter to control the maximum
	// thinking depth.
	ThinkingLevel ReinforcementTuningThinkingLevel `json:"thinkingLevel,omitempty"`
	// Optional. The thinking budget for the tuning job to optimize for (Gemini 2.5 only).
	// * -1 means dynamic thinking * 0 means no thinking * > 0 means thinking budget in
	// tokens If not set, default to -1 (dynamic thinking).
	ThinkingBudget int32 `json:"thinkingBudget,omitempty"`
}

// Reinforcement tuning spec for tuning.
type ReinforcementTuningSpec struct {
	// Composite reward function configuration for reinforcement tuning.
	CompositeRewardConfig *CompositeReinforcementTuningRewardConfig `json:"compositeRewardConfig,omitempty"`
	// Cloud Storage path to the file containing training dataset for tuning. The dataset
	// must be formatted as a JSONL file.
	TrainingDatasetURI string `json:"trainingDatasetUri,omitempty"`
	// Cloud Storage path to the file containing validation dataset for tuning. The dataset
	// must be formatted as a JSONL file.
	ValidationDatasetURI string `json:"validationDatasetUri,omitempty"`
	// Optional. Additional hyper-parameters to use during tuning.
	HyperParameters *ReinforcementTuningHyperParameters `json:"hyperParameters,omitempty"`
	// Optional. Single reward function configuration for reinforcement tuning.
	SingleRewardConfig *SingleReinforcementTuningRewardConfig `json:"singleRewardConfig,omitempty"`
}

// The `Status` type defines a logical error model that is suitable for different programming
// environments, including REST APIs and RPC APIs. It is used by [gRPC](https://github.com/grpc).
// Each `Status` message contains three pieces of data: error code, error message, and
// error details. You can find out more about this error model and how to work with
// it in the [API Design Guide](https://cloud.google.com/apis/design/errors). This data
// type is not supported in Gemini API.
type GoogleRpcStatus struct {
	// The status code, which should be an enum value of google.rpc.Code.
	Code int32 `json:"code,omitempty"`
	// A list of messages that carry the error details. There is a common set of message
	// types for APIs to use.
	Details []map[string]any `json:"details,omitempty"`
	// A developer-facing error message, which should be in English. Any user-facing error
	// message should be localized and sent in the google.rpc.Status.details field, or localized
	// by the client.
	Message string `json:"message,omitempty"`
}

// A pre-tuned model for continuous tuning. This data type is not supported in Gemini
// API.
type PreTunedModel struct {
	// Output only. The name of the base model this PreTunedModel was tuned from.
	BaseModel string `json:"baseModel,omitempty"`
	// Optional. The source checkpoint id. If not specified, the default checkpoint will
	// be used.
	CheckpointID string `json:"checkpointId,omitempty"`
	// The resource name of the Model. E.g., a model resource name with a specified version
	// ID or alias: `projects/{project}/locations/{location}/models/{model}@{version_id}`
	// `projects/{project}/locations/{location}/models/{model}@{alias}` Or, omit the version
	// ID to use the default version: `projects/{project}/locations/{location}/models/{model}`
	TunedModelName string `json:"tunedModelName,omitempty"`
}

// Dataset bucket used to create a histogram for the distribution given a population
// of values. This data type is not supported in Gemini API.
type DatasetDistributionDistributionBucket struct {
	// Output only. Number of values in the bucket.
	Count int64 `json:"count,omitempty,string"`
	// Output only. Left bound of the bucket.
	Left float64 `json:"left,omitempty"`
	// Output only. Right bound of the bucket.
	Right float64 `json:"right,omitempty"`
}

// Distribution computed over a tuning dataset. This data type is not supported in Gemini
// API.
type DatasetDistribution struct {
	// Output only. Defines the histogram bucket.
	Buckets []*DatasetDistributionDistributionBucket `json:"buckets,omitempty"`
	// Output only. The maximum of the population values.
	Max float64 `json:"max,omitempty"`
	// Output only. The arithmetic mean of the values in the population.
	Mean float64 `json:"mean,omitempty"`
	// Output only. The median of the values in the population.
	Median float64 `json:"median,omitempty"`
	// Output only. The minimum of the population values.
	Min float64 `json:"min,omitempty"`
	// Output only. The 5th percentile of the values in the population.
	P5 float64 `json:"p5,omitempty"`
	// Output only. The 95th percentile of the values in the population.
	P95 float64 `json:"p95,omitempty"`
	// Output only. Sum of a given population of values.
	Sum float64 `json:"sum,omitempty"`
}

// User-facing format for Gemini Reinforcement Tuning examples on Vertex.
type ReinforcementTuningExample struct {
	// Multi-turn contents that represents the Prompt.
	Contents []*Content `json:"contents,omitempty"`
	// Optional. References for the given prompt. The key is the name of the reference,
	// and the value is the reference itself.
	References map[string]string `json:"references,omitempty"`
	// Corresponds to system_instruction in user-facing GenerateContentRequest.
	SystemInstruction *Content `json:"systemInstruction,omitempty"`
}

// Sample reinforcement tuning user data in the training dataset. The contents are truncated
// for better UI showing. This data type is not supported in Gemini API.
type ReinforcementTuningUserDatasetExamples struct {
	// List of user datasset examples showing to user.
	UserDatasetExamples []*ReinforcementTuningExample `json:"userDatasetExamples,omitempty"`
}

// Statistics computed over a tuning dataset. This data type is not supported in Gemini
// API.
type DatasetStats struct {
	// Output only. A partial sample of the indices (starting from 1) of the dropped examples.
	DroppedExampleIndices []int64 `json:"droppedExampleIndices,omitempty"`
	// Output only. For each index in `dropped_example_indices`, the user-facing reason
	// why the example was dropped.
	DroppedExampleReasons []string `json:"droppedExampleReasons,omitempty"`
	// Output only. Number of billable characters in the tuning dataset.
	TotalBillableCharacterCount int64 `json:"totalBillableCharacterCount,omitempty,string"`
	// Output only. Number of tuning characters in the tuning dataset.
	TotalTuningCharacterCount int64 `json:"totalTuningCharacterCount,omitempty,string"`
	// Output only. Number of examples in the tuning dataset.
	TuningDatasetExampleCount int64 `json:"tuningDatasetExampleCount,omitempty,string"`
	// Output only. Number of tuning steps for this Tuning Job.
	TuningStepCount int64 `json:"tuningStepCount,omitempty,string"`
	// Output only. Sample user messages in the training dataset uri.
	UserDatasetExamples []*Content `json:"userDatasetExamples,omitempty"`
	// Output only. Dataset distributions for the user input tokens.
	UserInputTokenDistribution *DatasetDistribution `json:"userInputTokenDistribution,omitempty"`
	// Output only. Dataset distributions for the messages per example.
	UserMessagePerExampleDistribution *DatasetDistribution `json:"userMessagePerExampleDistribution,omitempty"`
	// Output only. Dataset distributions for the user output tokens.
	UserOutputTokenDistribution *DatasetDistribution `json:"userOutputTokenDistribution,omitempty"`
	// Output only. Dataset distributions for the number of contents per example.
	ContentsPerExampleDistribution *DatasetDistribution `json:"contentsPerExampleDistribution,omitempty"`
	// Output only. Sample user dataset examples in the training dataset URI for Reinforcement
	// Tuning.
	ReinforcementTuningUserDatasetExamples *ReinforcementTuningUserDatasetExamples `json:"reinforcementTuningUserDatasetExamples,omitempty"`
	// Output only. Number of billable tokens in the tuning dataset.
	TotalBillableTokenCount int64 `json:"totalBillableTokenCount,omitempty,string"`
}

func (d *DatasetStats) UnmarshalJSON(data []byte) error {
	type Alias DatasetStats
	aux := &struct {
		DroppedExampleIndices InternalInt64SliceJSON `json:"droppedExampleIndices,omitempty"`
		*Alias
	}{
		Alias: (*Alias)(d),
	}

	if err := json.Unmarshal(data, &aux); err != nil {
		return err
	}

	if !reflect.ValueOf(aux.DroppedExampleIndices).IsZero() {
		d.DroppedExampleIndices = aux.DroppedExampleIndices
	}

	return nil
}

func (d *DatasetStats) MarshalJSON() ([]byte, error) {
	type Alias DatasetStats
	aux := &struct {
		DroppedExampleIndices InternalInt64SliceJSON `json:"droppedExampleIndices,omitempty"`
		*Alias
	}{
		Alias: (*Alias)(d),
	}

	if !reflect.ValueOf(d.DroppedExampleIndices).IsZero() {
		aux.DroppedExampleIndices = d.DroppedExampleIndices
	}

	return json.Marshal(aux)
}

// Statistics for distillation prompt dataset. These statistics do not include the responses
// sampled from the teacher model. This data type is not supported in Gemini API.
type DistillationDataStats struct {
	// Output only. Statistics computed for the training dataset.
	TrainingDatasetStats *DatasetStats `json:"trainingDatasetStats,omitempty"`
}

// Completion and its preference score. This data type is not supported in Gemini API.
type GeminiPreferenceExampleCompletion struct {
	// Single turn completion for the given prompt.
	Completion *Content `json:"completion,omitempty"`
	// The score for the given completion.
	Score float32 `json:"score,omitempty"`
}

// Input example for preference optimization. This data type is not supported in Gemini
// API.
type GeminiPreferenceExample struct {
	// List of completions for a given prompt.
	Completions []*GeminiPreferenceExampleCompletion `json:"completions,omitempty"`
	// Multi-turn contents that represents the Prompt.
	Contents []*Content `json:"contents,omitempty"`
}

// Statistics computed for datasets used for preference optimization. This data type
// is not supported in Gemini API.
type PreferenceOptimizationDataStats struct {
	// Output only. A partial sample of the indices (starting from 1) of the dropped examples.
	DroppedExampleIndices []int64 `json:"droppedExampleIndices,omitempty"`
	// Output only. For each index in `dropped_example_indices`, the user-facing reason
	// why the example was dropped.
	DroppedExampleReasons []string `json:"droppedExampleReasons,omitempty"`
	// Output only. Dataset distributions for scores variance per example.
	ScoreVariancePerExampleDistribution *DatasetDistribution `json:"scoreVariancePerExampleDistribution,omitempty"`
	// Output only. Dataset distributions for scores.
	ScoresDistribution *DatasetDistribution `json:"scoresDistribution,omitempty"`
	// Output only. Number of billable tokens in the tuning dataset.
	TotalBillableTokenCount int64 `json:"totalBillableTokenCount,omitempty,string"`
	// Output only. Number of examples in the tuning dataset.
	TuningDatasetExampleCount int64 `json:"tuningDatasetExampleCount,omitempty,string"`
	// Output only. Number of tuning steps for this Tuning Job.
	TuningStepCount int64 `json:"tuningStepCount,omitempty,string"`
	// Output only. Sample user examples in the training dataset.
	UserDatasetExamples []*GeminiPreferenceExample `json:"userDatasetExamples,omitempty"`
	// Output only. Dataset distributions for the user input tokens.
	UserInputTokenDistribution *DatasetDistribution `json:"userInputTokenDistribution,omitempty"`
	// Output only. Dataset distributions for the user output tokens.
	UserOutputTokenDistribution *DatasetDistribution `json:"userOutputTokenDistribution,omitempty"`
}

func (p *PreferenceOptimizationDataStats) UnmarshalJSON(data []byte) error {
	type Alias PreferenceOptimizationDataStats
	aux := &struct {
		DroppedExampleIndices InternalInt64SliceJSON `json:"droppedExampleIndices,omitempty"`
		*Alias
	}{
		Alias: (*Alias)(p),
	}

	if err := json.Unmarshal(data, &aux); err != nil {
		return err
	}

	if !reflect.ValueOf(aux.DroppedExampleIndices).IsZero() {
		p.DroppedExampleIndices = aux.DroppedExampleIndices
	}

	return nil
}

func (p *PreferenceOptimizationDataStats) MarshalJSON() ([]byte, error) {
	type Alias PreferenceOptimizationDataStats
	aux := &struct {
		DroppedExampleIndices InternalInt64SliceJSON `json:"droppedExampleIndices,omitempty"`
		*Alias
	}{
		Alias: (*Alias)(p),
	}

	if !reflect.ValueOf(p.DroppedExampleIndices).IsZero() {
		aux.DroppedExampleIndices = p.DroppedExampleIndices
	}

	return json.Marshal(aux)
}

// Dataset bucket used to create a histogram for the distribution given a population
// of values. This data type is not supported in Gemini API.
type SupervisedTuningDatasetDistributionDatasetBucket struct {
	// Output only. Number of values in the bucket.
	Count float64 `json:"count,omitempty"`
	// Output only. Left bound of the bucket.
	Left float64 `json:"left,omitempty"`
	// Output only. Right bound of the bucket.
	Right float64 `json:"right,omitempty"`
}

// Dataset distribution for Supervised Tuning. This data type is not supported in Gemini
// API.
type SupervisedTuningDatasetDistribution struct {
	// Output only. Sum of a given population of values that are billable.
	BillableSum int64 `json:"billableSum,omitempty,string"`
	// Output only. Defines the histogram bucket.
	Buckets []*SupervisedTuningDatasetDistributionDatasetBucket `json:"buckets,omitempty"`
	// Output only. The maximum of the population values.
	Max float64 `json:"max,omitempty"`
	// Output only. The arithmetic mean of the values in the population.
	Mean float64 `json:"mean,omitempty"`
	// Output only. The median of the values in the population.
	Median float64 `json:"median,omitempty"`
	// Output only. The minimum of the population values.
	Min float64 `json:"min,omitempty"`
	// Output only. The 5th percentile of the values in the population.
	P5 float64 `json:"p5,omitempty"`
	// Output only. The 95th percentile of the values in the population.
	P95 float64 `json:"p95,omitempty"`
	// Output only. Sum of a given population of values.
	Sum int64 `json:"sum,omitempty,string"`
}

// Tuning data statistics for Supervised Tuning. This data type is not supported in
// Gemini API.
type SupervisedTuningDataStats struct {
	// Output only. For each index in `truncated_example_indices`, the user-facing reason
	// why the example was dropped.
	DroppedExampleReasons []string `json:"droppedExampleReasons,omitempty"`
	// Output only. Number of billable characters in the tuning dataset.
	TotalBillableCharacterCount int64 `json:"totalBillableCharacterCount,omitempty,string"`
	// Output only. Number of billable tokens in the tuning dataset.
	TotalBillableTokenCount int64 `json:"totalBillableTokenCount,omitempty,string"`
	// Output only. The number of examples in the dataset that have been dropped. An example
	// can be dropped for reasons including: too many tokens, contains an invalid image,
	// contains too many images, etc.
	TotalTruncatedExampleCount int64 `json:"totalTruncatedExampleCount,omitempty,string"`
	// Output only. Number of tuning characters in the tuning dataset.
	TotalTuningCharacterCount int64 `json:"totalTuningCharacterCount,omitempty,string"`
	// Output only. A partial sample of the indices (starting from 1) of the dropped examples.
	TruncatedExampleIndices []int64 `json:"truncatedExampleIndices,omitempty"`
	// Output only. Number of examples in the tuning dataset.
	TuningDatasetExampleCount int64 `json:"tuningDatasetExampleCount,omitempty,string"`
	// Output only. Number of tuning steps for this Tuning Job.
	TuningStepCount int64 `json:"tuningStepCount,omitempty,string"`
	// Output only. Sample user messages in the training dataset uri.
	UserDatasetExamples []*Content `json:"userDatasetExamples,omitempty"`
	// Output only. Dataset distributions for the user input tokens.
	UserInputTokenDistribution *SupervisedTuningDatasetDistribution `json:"userInputTokenDistribution,omitempty"`
	// Output only. Dataset distributions for the messages per example.
	UserMessagePerExampleDistribution *SupervisedTuningDatasetDistribution `json:"userMessagePerExampleDistribution,omitempty"`
	// Output only. Dataset distributions for the user output tokens.
	UserOutputTokenDistribution *SupervisedTuningDatasetDistribution `json:"userOutputTokenDistribution,omitempty"`
}

func (s *SupervisedTuningDataStats) UnmarshalJSON(data []byte) error {
	type Alias SupervisedTuningDataStats
	aux := &struct {
		TruncatedExampleIndices InternalInt64SliceJSON `json:"truncatedExampleIndices,omitempty"`
		*Alias
	}{
		Alias: (*Alias)(s),
	}

	if err := json.Unmarshal(data, &aux); err != nil {
		return err
	}

	if !reflect.ValueOf(aux.TruncatedExampleIndices).IsZero() {
		s.TruncatedExampleIndices = aux.TruncatedExampleIndices
	}

	return nil
}

func (s *SupervisedTuningDataStats) MarshalJSON() ([]byte, error) {
	type Alias SupervisedTuningDataStats
	aux := &struct {
		TruncatedExampleIndices InternalInt64SliceJSON `json:"truncatedExampleIndices,omitempty"`
		*Alias
	}{
		Alias: (*Alias)(s),
	}

	if !reflect.ValueOf(s.TruncatedExampleIndices).IsZero() {
		aux.TruncatedExampleIndices = s.TruncatedExampleIndices
	}

	return json.Marshal(aux)
}

// The tuning data statistic values for TuningJob. This data type is not supported in
// Gemini API.
type TuningDataStats struct {
	// Output only. Statistics for distillation prompt dataset. These statistics do not
	// include the responses sampled from the teacher model.
	DistillationDataStats *DistillationDataStats `json:"distillationDataStats,omitempty"`
	// Output only. Statistics for preference optimization.
	PreferenceOptimizationDataStats *PreferenceOptimizationDataStats `json:"preferenceOptimizationDataStats,omitempty"`
	// The SFT Tuning data stats.
	SupervisedTuningDataStats *SupervisedTuningDataStats `json:"supervisedTuningDataStats,omitempty"`
	// Output only. Statistics for reinforcement tuning.
	ReinforcementTuningDataStats *DatasetStats `json:"reinforcementTuningDataStats,omitempty"`
}

// Represents a customer-managed encryption key specification that can be applied to
// a Vertex AI resource. This data type is not supported in Gemini API.
type EncryptionSpec struct {
	// Required. Resource name of the Cloud KMS key used to protect the resource. The Cloud
	// KMS key must be in the same region as the resource. It must have the format `projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}`.
	KmsKeyName string `json:"kmsKeyName,omitempty"`
}

// Tuning spec for Partner models. This data type is not supported in Gemini API.
type PartnerModelTuningSpec struct {
	// Hyperparameters for tuning. The accepted hyper_parameters and their valid range of
	// values will differ depending on the base model.
	HyperParameters map[string]any `json:"hyperParameters,omitempty"`
	// Required. Cloud Storage path to file containing training dataset for tuning. The
	// dataset must be formatted as a JSONL file.
	TrainingDatasetURI string `json:"trainingDatasetUri,omitempty"`
	// Optional. Cloud Storage path to file containing validation dataset for tuning. The
	// dataset must be formatted as a JSONL file.
	ValidationDatasetURI string `json:"validationDatasetUri,omitempty"`
}

// Bleu metric value for an instance. This data type is not supported in Gemini API.
type BleuMetricValue struct {
	// Output only. Bleu score.
	Score float32 `json:"score,omitempty"`
}

// Result for custom code execution metric. This data type is not supported in Gemini
// API.
type CustomCodeExecutionResult struct {
	// Output only. Custom code execution score.
	Score float32 `json:"score,omitempty"`
}

// Exact match metric value for an instance. This data type is not supported in Gemini
// API.
type ExactMatchMetricValue struct {
	// Output only. Exact match score.
	Score float32 `json:"score,omitempty"`
}

// Raw output. This data type is not supported in Gemini API.
type RawOutput struct {
	// Output only. Raw output string.
	RawOutput []string `json:"rawOutput,omitempty"`
}

// Spec for custom output. This data type is not supported in Gemini API.
type CustomOutput struct {
	// Output only. List of raw output strings.
	RawOutputs *RawOutput `json:"rawOutputs,omitempty"`
}

// Spec for pairwise metric result. This data type is not supported in Gemini API.
type PairwiseMetricResult struct {
	// Output only. Spec for custom output.
	CustomOutput *CustomOutput `json:"customOutput,omitempty"`
	// Output only. Explanation for pairwise metric score.
	Explanation string `json:"explanation,omitempty"`
	// Output only. Pairwise metric choice.
	PairwiseChoice PairwiseChoice `json:"pairwiseChoice,omitempty"`
}

// Spec for pointwise metric result. This data type is not supported in Gemini API.
type PointwiseMetricResult struct {
	// Output only. Spec for custom output.
	CustomOutput *CustomOutput `json:"customOutput,omitempty"`
	// Output only. Explanation for pointwise metric score.
	Explanation string `json:"explanation,omitempty"`
	// Output only. Pointwise metric score.
	Score float32 `json:"score,omitempty"`
}

// Rouge metric value for an instance. This data type is not supported in Gemini API.
type RougeMetricValue struct {
	// Output only. Rouge score.
	Score float32 `json:"score,omitempty"`
}

// The aggregation result for a single metric. This data type is not supported in Gemini
// API.
type AggregationResult struct {
	// Aggregation metric.
	AggregationMetric AggregationMetric `json:"aggregationMetric,omitempty"`
	// Results for bleu metric.
	BleuMetricValue *BleuMetricValue `json:"bleuMetricValue,omitempty"`
	// Result for code execution metric.
	CustomCodeExecutionResult *CustomCodeExecutionResult `json:"customCodeExecutionResult,omitempty"`
	// Results for exact match metric.
	ExactMatchMetricValue *ExactMatchMetricValue `json:"exactMatchMetricValue,omitempty"`
	// Result for pairwise metric.
	PairwiseMetricResult *PairwiseMetricResult `json:"pairwiseMetricResult,omitempty"`
	// Result for pointwise metric.
	PointwiseMetricResult *PointwiseMetricResult `json:"pointwiseMetricResult,omitempty"`
	// Results for rouge metric.
	RougeMetricValue *RougeMetricValue `json:"rougeMetricValue,omitempty"`
}

// The BigQuery location for the input content. This data type is not supported in Gemini
// API.
type BigQuerySource struct {
	// Required. BigQuery URI to a table, up to 2000 characters long. Accepted forms: *
	// BigQuery path. For example: `bq://projectId.bqDatasetId.bqTableId`.
	InputURI string `json:"inputUri,omitempty"`
}

// The Google Cloud Storage location for the input content. This data type is not supported
// in Gemini API.
type GCSSource struct {
	// Required. Google Cloud Storage URI(-s) to the input file(s). May contain wildcards.
	// For more information on wildcards, see https://cloud.google.com/storage/docs/wildcards.
	Uris []string `json:"uris,omitempty"`
}

// The dataset used for evaluation. This data type is not supported in Gemini API.
type EvaluationDataset struct {
	// BigQuery source holds the dataset.
	BigquerySource *BigQuerySource `json:"bigquerySource,omitempty"`
	// Cloud storage source holds the dataset. Currently only one Cloud Storage file path
	// is supported.
	GCSSource *GCSSource `json:"gcsSource,omitempty"`
}

// The aggregation result for the entire dataset and all metrics. This data type is
// not supported in Gemini API.
type AggregationOutput struct {
	// One AggregationResult per metric.
	AggregationResults []*AggregationResult `json:"aggregationResults,omitempty"`
	// The dataset used for evaluation & aggregation.
	Dataset *EvaluationDataset `json:"dataset,omitempty"`
}

// Describes the info for output of EvaluationService. This data type is not supported
// in Gemini API.
type OutputInfo struct {
	// Output only. The full path of the Cloud Storage directory created, into which the
	// evaluation results and aggregation results are written.
	GCSOutputDirectory string `json:"gcsOutputDirectory,omitempty"`
}

// The results from an evaluation run performed by the EvaluationService. This data
// type is not supported in Gemini API.
type EvaluateDatasetResponse struct {
	// Output only. Aggregation statistics derived from results of EvaluationService.
	AggregationOutput *AggregationOutput `json:"aggregationOutput,omitempty"`
	// Output only. Output info for EvaluationService.
	OutputInfo *OutputInfo `json:"outputInfo,omitempty"`
}

// Evaluate Dataset Run Result for Tuning Job. This data type is not supported in Gemini
// API.
type EvaluateDatasetRun struct {
	// Output only. The checkpoint ID used in the evaluation run. Only populated when evaluating
	// checkpoints.
	CheckpointID string `json:"checkpointId,omitempty"`
	// Output only. The error of the evaluation run if any.
	Error *GoogleRpcStatus `json:"error,omitempty"`
	// Output only. Results for EvaluationService.
	EvaluateDatasetResponse *EvaluateDatasetResponse `json:"evaluateDatasetResponse,omitempty"`
	// Output only. The resource name of the evaluation run. Format: `projects/{project}/locations/{location}/evaluationRuns/{evaluation_run_id}`.
	EvaluationRun string `json:"evaluationRun,omitempty"`
	// Output only. Deprecated: The updated architecture uses evaluation_run instead.
	OperationName string `json:"operationName,omitempty"`
}

// Tuning Spec for Full Fine Tuning. This data type is not supported in Gemini API.
type FullFineTuningSpec struct {
	// Optional. Hyperparameters for Full Fine Tuning.
	HyperParameters *SupervisedHyperParameters `json:"hyperParameters,omitempty"`
	// Required. Training dataset used for tuning. The dataset can be specified as either
	// a Cloud Storage path to a JSONL file or as the resource name of a Vertex Multimodal
	// Dataset.
	TrainingDatasetURI string `json:"trainingDatasetUri,omitempty"`
	// Optional. Validation dataset used for tuning. The dataset can be specified as either
	// a Cloud Storage path to a JSONL file or as the resource name of a Vertex Multimodal
	// Dataset.
	ValidationDatasetURI string `json:"validationDatasetUri,omitempty"`
}

// Hyperparameters for Veo. This data type is not supported in Gemini API.
type VeoHyperParameters struct {
	// Optional. Number of complete passes the model makes over the entire training dataset
	// during training.
	EpochCount int64 `json:"epochCount,omitempty,string"`
	// Optional. Multiplier for adjusting the default learning rate.
	LearningRateMultiplier float64 `json:"learningRateMultiplier,omitempty"`
	// The tuning task for Veo.
	TuningTask TuningTask `json:"tuningTask,omitempty"`
	// Optional. The ratio of Google internal dataset to use in the training mixture, in
	// range of `[0, 1)`. If `0.2`, it means 20% of Google internal dataset and 80% of user
	// dataset will be used for training. If not set, the default value is 0.1.
	VeoDataMixtureRatio float64 `json:"veoDataMixtureRatio,omitempty"`
	// Optional. The adapter size for LoRA tuning.
	AdapterSize AdapterSize `json:"adapterSize,omitempty"`
	// The speed of the tuning job. Only supported for Veo 3.0 models.
	TuningSpeed TuningSpeed `json:"tuningSpeed,omitempty"`
}

// Tuning Spec for Veo Model Tuning. This data type is not supported in Gemini API.
type VeoTuningSpec struct {
	// Optional. Hyperparameters for Veo.
	HyperParameters *VeoHyperParameters `json:"hyperParameters,omitempty"`
	// Required. Training dataset used for tuning. The dataset can be specified as either
	// a Cloud Storage path to a JSONL file or as the resource name of a Vertex Multimodal
	// Dataset.
	TrainingDatasetURI string `json:"trainingDatasetUri,omitempty"`
	// Optional. Validation dataset used for tuning. The dataset can be specified as either
	// a Cloud Storage path to a JSONL file or as the resource name of a Vertex Multimodal
	// Dataset.
	ValidationDatasetURI string `json:"validationDatasetUri,omitempty"`
}

// Tuning job metadata. This data type is not supported in Gemini API.
type TuningJobMetadata struct {
	// Output only. The number of epochs that have been completed.
	CompletedEpochCount int64 `json:"completedEpochCount,omitempty,string"`
	// Output only. The number of steps that have been completed. Set for Multi-Step RL.
	CompletedStepCount int64 `json:"completedStepCount,omitempty,string"`
}

// Tuning Spec for Veo LoRA Model Tuning. This data type is not supported in Gemini
// API.
type VeoLoraTuningSpec struct {
	// Optional. Hyperparameters for Veo LoRA.
	HyperParameters *VeoHyperParameters `json:"hyperParameters,omitempty"`
	// Required. Training dataset used for tuning. The dataset can be specified as either
	// a Cloud Storage path to a JSONL file or as the resource name of a Vertex Multimodal
	// Dataset.
	TrainingDatasetURI string `json:"trainingDatasetUri,omitempty"`
	// Optional. Validation dataset used for tuning. The dataset can be specified as either
	// a Cloud Storage path to a JSONL file or as the resource name of a Vertex Multimodal
	// Dataset.
	ValidationDatasetURI string `json:"validationDatasetUri,omitempty"`
	// Optional. The orientation of the video. Defaults to LANDSCAPE.
	VideoOrientation VideoOrientation `json:"videoOrientation,omitempty"`
}

// A tuning job.
type TuningJob struct {
	// Optional. Used to retain the full HTTP response.
	SDKHTTPResponse *HTTPResponse `json:"sdkHttpResponse,omitempty"`
	// Output only. Identifier. Resource name of a TuningJob. Format: `projects/{project}/locations/{location}/tuningJobs/{tuning_job}`
	Name string `json:"name,omitempty"`
	// Output only. The detailed state of the job.
	State JobState `json:"state,omitempty"`
	// Output only. Time when the TuningJob was created.
	CreateTime time.Time `json:"createTime,omitempty"`
	// Output only. Time when the TuningJob for the first time entered the `JOB_STATE_RUNNING`
	// state.
	StartTime time.Time `json:"startTime,omitempty"`
	// Output only. Time when the TuningJob entered any of the following JobStates: `JOB_STATE_SUCCEEDED`,
	// `JOB_STATE_FAILED`, `JOB_STATE_CANCELLED`, `JOB_STATE_EXPIRED`.
	EndTime time.Time `json:"endTime,omitempty"`
	// Output only. Time when the TuningJob was most recently updated.
	UpdateTime time.Time `json:"updateTime,omitempty"`
	// Output only. Only populated when job's state is `JOB_STATE_FAILED` or `JOB_STATE_CANCELLED`.
	Error *GoogleRpcStatus `json:"error,omitempty"`
	// Optional. The description of the TuningJob.
	Description string `json:"description,omitempty"`
	// The base model that is being tuned. See [Supported models](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/tuning#supported_models).
	BaseModel string `json:"baseModel,omitempty"`
	// Output only. The tuned model resources associated with this TuningJob.
	TunedModel *TunedModel `json:"tunedModel,omitempty"`
	// The pre-tuned model for continuous tuning.
	PreTunedModel *PreTunedModel `json:"preTunedModel,omitempty"`
	// Tuning Spec for Supervised Fine Tuning.
	SupervisedTuningSpec *SupervisedTuningSpec `json:"supervisedTuningSpec,omitempty"`
	// Tuning Spec for Preference Optimization.
	PreferenceOptimizationSpec *PreferenceOptimizationSpec `json:"preferenceOptimizationSpec,omitempty"`
	// Tuning Spec for Distillation.
	DistillationSpec *DistillationSpec `json:"distillationSpec,omitempty"`
	// Tuning Spec for Reinforcement Tuning.
	ReinforcementTuningSpec *ReinforcementTuningSpec `json:"reinforcementTuningSpec,omitempty"`
	// Output only. The tuning data statistics associated with this TuningJob.
	TuningDataStats *TuningDataStats `json:"tuningDataStats,omitempty"`
	// Customer-managed encryption key options for a TuningJob. If this is set, then all
	// resources created by the TuningJob will be encrypted with the provided encryption
	// key.
	EncryptionSpec *EncryptionSpec `json:"encryptionSpec,omitempty"`
	// Tuning Spec for open sourced and third party Partner models.
	PartnerModelTuningSpec *PartnerModelTuningSpec `json:"partnerModelTuningSpec,omitempty"`
	// Optional. The user-provided path to custom model weights. Set this field to tune
	// a custom model. The path must be a Cloud Storage directory that contains the model
	// weights in .safetensors format along with associated model metadata files. If this
	// field is set, the base_model field must still be set to indicate which base model
	// the custom model is derived from. This feature is only available for open source
	// models.
	CustomBaseModel string `json:"customBaseModel,omitempty"`
	// Output only. Evaluation runs for the Tuning Job.
	EvaluateDatasetRuns []*EvaluateDatasetRun `json:"evaluateDatasetRuns,omitempty"`
	// Output only. The Experiment associated with this TuningJob.
	Experiment string `json:"experiment,omitempty"`
	// Tuning Spec for Full Fine Tuning.
	FullFineTuningSpec *FullFineTuningSpec `json:"fullFineTuningSpec,omitempty"`
	// Optional. The labels with user-defined metadata to organize TuningJob and generated
	// resources such as Model and Endpoint. Label keys and values can be no longer than
	// 64 characters (Unicode codepoints), can only contain lowercase letters, numeric characters,
	// underscores and dashes. International characters are allowed. See https://goo.gl/xmQnxf
	// for more information and examples of labels.
	Labels map[string]string `json:"labels,omitempty"`
	// Optional. Cloud Storage path to the directory where tuning job outputs are written
	// to. This field is only available and required for open source models.
	OutputURI string `json:"outputUri,omitempty"`
	// Output only. The resource name of the PipelineJob associated with the TuningJob.
	// Format: `projects/{project}/locations/{location}/pipelineJobs/{pipeline_job}`.
	PipelineJob string `json:"pipelineJob,omitempty"`
	// The service account that the tuningJob workload runs as. If not specified, the Vertex
	// AI Secure Fine-Tuned Service Agent in the project will be used. See https://cloud.google.com/iam/docs/service-agents#vertex-ai-secure-fine-tuning-service-agent
	// Users starting the pipeline must have the `iam.serviceAccounts.actAs` permission
	// on this service account.
	ServiceAccount string `json:"serviceAccount,omitempty"`
	// Optional. The display name of the TunedModel. The name can be up to 128 characters
	// long and can consist of any UTF-8 characters. For continuous tuning, tuned_model_display_name
	// will by default use the same display name as the pre-tuned model. If a new display
	// name is provided, the tuning job will create a new model instead of a new version.
	TunedModelDisplayName string `json:"tunedModelDisplayName,omitempty"`
	// Output only. The detail state of the tuning job (while the overall `JobState` is
	// running).
	TuningJobState TuningJobState `json:"tuningJobState,omitempty"`
	// Tuning Spec for Veo Tuning.
	VeoTuningSpec *VeoTuningSpec `json:"veoTuningSpec,omitempty"`
	// Output only. Tuning Job metadata.
	TuningJobMetadata *TuningJobMetadata `json:"tuningJobMetadata,omitempty"`
	// Tuning Spec for Veo LoRA Tuning.
	VeoLoraTuningSpec *VeoLoraTuningSpec `json:"veoLoraTuningSpec,omitempty"`

	DistillationSamplingSpec *DistillationSamplingSpec `json:"distillationSamplingSpec,omitempty"`
}

func (t *TuningJob) UnmarshalJSON(data []byte) error {
	type Alias TuningJob
	aux := &struct {
		CreateTime *time.Time `json:"createTime,omitempty"`
		StartTime  *time.Time `json:"startTime,omitempty"`
		EndTime    *time.Time `json:"endTime,omitempty"`
		UpdateTime *time.Time `json:"updateTime,omitempty"`
		*Alias
	}{
		Alias: (*Alias)(t),
	}

	if err := json.Unmarshal(data, &aux); err != nil {
		return err
	}

	if !reflect.ValueOf(aux.CreateTime).IsZero() {
		t.CreateTime = time.Time(*aux.CreateTime)
	}

	if !reflect.ValueOf(aux.StartTime).IsZero() {
		t.StartTime = time.Time(*aux.StartTime)
	}

	if !reflect.ValueOf(aux.EndTime).IsZero() {
		t.EndTime = time.Time(*aux.EndTime)
	}

	if !reflect.ValueOf(aux.UpdateTime).IsZero() {
		t.UpdateTime = time.Time(*aux.UpdateTime)
	}

	return nil
}

func (t *TuningJob) MarshalJSON() ([]byte, error) {
	type Alias TuningJob
	aux := &struct {
		CreateTime *time.Time `json:"createTime,omitempty"`
		StartTime  *time.Time `json:"startTime,omitempty"`
		EndTime    *time.Time `json:"endTime,omitempty"`
		UpdateTime *time.Time `json:"updateTime,omitempty"`
		*Alias
	}{
		Alias: (*Alias)(t),
	}

	if !reflect.ValueOf(t.CreateTime).IsZero() {
		aux.CreateTime = (*time.Time)(&t.CreateTime)
	}

	if !reflect.ValueOf(t.StartTime).IsZero() {
		aux.StartTime = (*time.Time)(&t.StartTime)
	}

	if !reflect.ValueOf(t.EndTime).IsZero() {
		aux.EndTime = (*time.Time)(&t.EndTime)
	}

	if !reflect.ValueOf(t.UpdateTime).IsZero() {
		aux.UpdateTime = (*time.Time)(&t.UpdateTime)
	}

	return json.Marshal(aux)
}

// Configuration for the list tuning jobs method.
type ListTuningJobsConfig struct {
	// Optional. Used to override HTTP request options.
	HTTPOptions *HTTPOptions `json:"httpOptions,omitempty"`
	// Optional. PageSize specifies the maximum number of cached contents to return per
	// API call. If zero, the server will use a default value.
	PageSize int32 `json:"pageSize,omitempty"`
	// Optional. PageToken represents a token used for pagination in API responses. It's
	// an opaque string that should be passed to subsequent requests to retrieve the next
	// page of results. An empty PageToken typically indicates that there are no further
	// pages available.
	PageToken string `json:"pageToken,omitempty"`
	// Optional.
	Filter string `json:"filter,omitempty"`
}

// Response for the list tuning jobs method.
type ListTuningJobsResponse struct {
	// Optional. Used to retain the full HTTP response.
	SDKHTTPResponse *HTTPResponse `json:"sdkHttpResponse,omitempty"`
	// A token to retrieve the next page of results. Pass this token in a subsequent [GenAITuningService.ListTuningJobs]
	// call to retrieve the next page of results.
	NextPageToken string `json:"nextPageToken,omitempty"`
	// The tuning jobs that match the request.
	TuningJobs []*TuningJob `json:"tuningJobs,omitempty"`
}

// Optional parameters for tunings.cancel method.
type CancelTuningJobConfig struct {
	// Optional. Used to override HTTP request options.
	HTTPOptions *HTTPOptions `json:"httpOptions,omitempty"`
}

// Empty response for tunings.cancel method.
type CancelTuningJobResponse struct {
	// Optional. Used to retain the full HTTP response.
	SDKHTTPResponse *HTTPResponse `json:"sdkHttpResponse,omitempty"`
}

// A single example for tuning. This data type is not supported in Vertex AI.
type TuningExample struct {
	// Required. The expected model output.
	Output string `json:"output,omitempty"`
	// Optional. Text model input.
	TextInput string `json:"textInput,omitempty"`
}

// Supervised fine-tuning training dataset.
type TuningDataset struct {
	// Optional. GCS URI of the file containing training dataset in JSONL format.
	GCSURI string `json:"gcsUri,omitempty"`
	// Optional. The resource name of the Gemini Enterprise Agent Platform (previously known
	// as Vertex AI) Multimodal Dataset that is used as training dataset. Example: 'projects/my-project-id-or-number/locations/my-location/datasets/my-dataset-id'.
	VertexDatasetResource string `json:"vertexDatasetResource,omitempty"`
	// Optional. Inline examples with simple input/output text.
	Examples []*TuningExample `json:"examples,omitempty"`
}

type TuningValidationDataset struct {
	// Optional. GCS URI of the file containing validation dataset in JSONL format.
	GCSURI string `json:"gcsUri,omitempty"`
	// Optional. The resource name of the Gemini Enterprise Agent Platform (previously known
	// as Vertex AI) Multimodal Dataset that is used as validation dataset. Example: 'projects/my-project-id-or-number/locations/my-location/datasets/my-dataset-id'.
	VertexDatasetResource string `json:"vertexDatasetResource,omitempty"`
}

// Fine-tuning job creation request - optional fields.
type CreateTuningJobConfig struct {
	// Optional. Used to override HTTP request options.
	HTTPOptions *HTTPOptions `json:"httpOptions,omitempty"`
	// The method to use for tuning (SUPERVISED_FINE_TUNING or PREFERENCE_TUNING or DISTILLATION
	// or REINFORCEMENT_TUNING). If not set, the default method (SFT) will be used.
	Method TuningMethod `json:"method,omitempty"`
	// Optional. Validation dataset for tuning. The dataset must be formatted as a JSONL
	// file.
	ValidationDataset *TuningValidationDataset `json:"validationDataset,omitempty"`
	// Optional. The display name of the tuned Model. The name can be up to 128 characters
	// long and can consist of any UTF-8 characters.
	TunedModelDisplayName string `json:"tunedModelDisplayName,omitempty"`
	// Optional. The description of the TuningJob
	Description string `json:"description,omitempty"`
	// Optional. Number of complete passes the model makes over the entire training dataset
	// during training.
	EpochCount *int32 `json:"epochCount,omitempty"`
	// Optional. Multiplier for adjusting the default learning rate. 1P models only. Mutually
	// exclusive with learning_rate.
	LearningRateMultiplier *float32 `json:"learningRateMultiplier,omitempty"`
	// Optional. If set to true, disable intermediate checkpoints and only the last checkpoint
	// will be exported. Otherwise, enable intermediate checkpoints.
	ExportLastCheckpointOnly *bool `json:"exportLastCheckpointOnly,omitempty"`
	// Optional. The optional checkpoint ID of the pre-tuned model to use for tuning, if
	// applicable.
	PreTunedModelCheckpointID string `json:"preTunedModelCheckpointId,omitempty"`
	// Optional. Adapter size for tuning.
	AdapterSize AdapterSize `json:"adapterSize,omitempty"`
	// Optional. Tuning mode for tuning.
	TuningMode TuningMode `json:"tuningMode,omitempty"`
	// Optional. Custom base model for tuning. This is only supported for OSS models in
	// Gemini Enterprise Agent Platform.
	CustomBaseModel string `json:"customBaseModel,omitempty"`
	// Optional. The batch size hyperparameter for tuning. This is only supported for OSS
	// models in Gemini Enterprise Agent Platform.
	BatchSize *int32 `json:"batchSize,omitempty"`
	// Optional. The learning rate for tuning. OSS models only. Mutually exclusive with
	// learning_rate_multiplier.
	LearningRate *float32 `json:"learningRate,omitempty"`
	// Optional. The labels with user-defined metadata to organize TuningJob and generated
	// resources such as Model and Endpoint. Label keys and values can be no longer than
	// 64 characters (Unicode codepoints), can only contain lowercase letters, numeric characters,
	// underscores and dashes. International characters are allowed. See https://goo.gl/xmQnxf
	// for more information and examples of labels.
	Labels map[string]string `json:"labels,omitempty"`
	// Optional. Weight for KL Divergence regularization, Preference Optimization tuning
	// only.
	Beta *float32 `json:"beta,omitempty"`
	// Optional. The base teacher model that is being distilled. Distillation only.
	BaseTeacherModel string `json:"baseTeacherModel,omitempty"`
	// Optional. The resource name of the Tuned teacher model. Distillation only.
	TunedTeacherModelSource string `json:"tunedTeacherModelSource,omitempty"`
	// Optional. Multiplier for adjusting the weight of the SFT loss. Distillation only.
	SftLossWeightMultiplier *float32 `json:"sftLossWeightMultiplier,omitempty"`
	// Optional. The Google Cloud Storage location where the tuning job outputs are written.
	OutputURI string `json:"outputUri,omitempty"`
	// Optional. The encryption spec of the tuning job. Customer-managed encryption key
	// options for a TuningJob. If this is set, then all resources created by the TuningJob
	// will be encrypted with provided encryption key.
	EncryptionSpec *EncryptionSpec `json:"encryptionSpec,omitempty"`
	// Optional. Reward function configuration for reinforcement tuning. Reinforcement tuning
	// only.
	RewardConfig *SingleReinforcementTuningRewardConfig `json:"rewardConfig,omitempty"`
	// Optional. Composite reward function configuration for reinforcement tuning. Reinforcement
	// tuning only.
	CompositeRewardConfig *CompositeReinforcementTuningRewardConfig `json:"compositeRewardConfig,omitempty"`
	// Optional. Number of different responses to generate per prompt during tuning. Reinforcement
	// tuning only.
	SamplesPerPrompt *int32 `json:"samplesPerPrompt,omitempty"`
	// Optional. How often at steps to evaluate the tuning job during training. Reinforcement
	// tuning only.
	EvaluateInterval *int32 `json:"evaluateInterval,omitempty"`
	// Optional. How often at steps to save checkpoints during training. Reinforcement tuning
	// only.
	CheckpointInterval *int32 `json:"checkpointInterval,omitempty"`
	// Optional. The maximum number of tokens to generate per prompt. Reinforcement tuning
	// only. If empty, API will use a default value. The default value varies by model.
	MaxOutputTokens int32 `json:"maxOutputTokens,omitempty"`
	// Optional. Indicates the maximum thinking depth. Use with earlier models shall result
	// in error. Reinforcement tuning only.
	ThinkingLevel ReinforcementTuningThinkingLevel `json:"thinkingLevel,omitempty"`
	// Optional. Cloud Storage path to file containing validation dataset for tuning. The
	// dataset must be formatted as a JSONL file. If no validation dataset is provided,
	// by default the API splits 25% of the training dataset or 50 examples, whichever is
	// larger, as the validation dataset. Reinforcement tuning only.
	ValidationDatasetURI string `json:"validationDatasetUri,omitempty"`
}

// A long-running operation.
type TuningOperation struct {
	// Optional. Used to retain the full HTTP response.
	SDKHTTPResponse *HTTPResponse `json:"sdkHttpResponse,omitempty"`
	// The server-assigned name, which is only unique within the same service that originally
	// returns it. If you use the default HTTP mapping, the `name` should be a resource
	// name ending with `operations/{unique_id}`.
	Name string `json:"name,omitempty"`
	// Optional. Service-specific metadata associated with the operation. It typically contains
	// progress information and common metadata such as create time. Some services might
	// not provide such metadata. Any method that returns a long-running operation should
	// document the metadata type, if any.
	Metadata map[string]any `json:"metadata,omitempty"`
	// If the value is `false`, it means the operation is still in progress. If `true`,
	// the operation is completed, and either `error` or `response` is available.
	Done bool `json:"done,omitempty"`
	// Optional. The error result of the operation in case of failure or cancellation.
	Error map[string]any `json:"error,omitempty"`
}

// Optional parameters for tunings.validate_reward.
type ValidateRewardConfig struct {
	// Optional. Used to override HTTP request options.
	HTTPOptions *HTTPOptions `json:"httpOptions,omitempty"`
}

// The reward info for a reward function.
type ReinforcementTuningRewardInfo struct {
	// Output only. The calculated reward for the reward function.
	Reward float32 `json:"reward,omitempty"`
	// Output only. The user-requested auxiliary info for the reward function. This field
	// is set only if the Cloud Run reward function configured by user returns a "user_requested_aux_info".
	// Refer to ReinforcementTuningCloudRunRewardScorer for more details.
	UserRequestedAuxInfo string `json:"userRequestedAuxInfo,omitempty"`
}

// Response for the validate_reward method.
// Contains the computed reward for a reinforcement tuning reward
// configuration.
type ValidateRewardResponse struct {
	// Optional. Used to retain the full HTTP response.
	SDKHTTPResponse *HTTPResponse `json:"sdkHttpResponse,omitempty"`
	// Optional. Output only. The overall weighted reward. For a `CompositeReinforcementTuningRewardConfig`,
	// this is the weighted average of all rewards. For a `SingleReinforcementTuningRewardConfig`,
	// this will be the value of the single reward.
	OverallReward float32 `json:"overallReward,omitempty"`
	// Optional. Output only. In case of an error, this field will be populated with a detailed
	// error message to help with debugging.
	Error string `json:"error,omitempty"`
	// Optional. A map from reward name to reward info.
	RewardInfoDetails map[string]*ReinforcementTuningRewardInfo `json:"rewardInfoDetails,omitempty"`
}

// Optional configuration for cached content creation.
type CreateCachedContentConfig struct {
	// Optional. Used to override HTTP request options.
	HTTPOptions *HTTPOptions `json:"httpOptions,omitempty"`
	// Optional. The TTL for this resource. The expiration time is computed: now + TTL.
	TTL time.Duration `json:"ttl,omitempty"`
	// Optional. Timestamp of when this resource is considered expired.
	ExpireTime time.Time `json:"expireTime,omitempty"`
	// Optional. The user-generated meaningful display name of the cached content.
	DisplayName string `json:"displayName,omitempty"`
	// Optional. The content to cache.
	Contents []*Content `json:"contents,omitempty"`
	// Optional. Developer set system instruction.
	SystemInstruction *Content `json:"systemInstruction,omitempty"`
	// Optional. A list of `Tools` the model may use to generate the next response.
	Tools []*Tool `json:"tools,omitempty"`
	// Optional. Configuration for the tools to use. This config is shared for all tools.
	ToolConfig *ToolConfig `json:"toolConfig,omitempty"`
	// Optional. The Cloud KMS resource identifier of the customer managed
	// encryption key used to protect a resource.
	// The key needs to be in the same region as where the compute resource is
	// created. See
	// https://cloud.google.com/vertex-ai/docs/general/cmek for more
	// details. If this is set, then all created CachedContent objects
	// will be encrypted with the provided encryption key.
	// Allowed formats: projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}
	KmsKeyName string `json:"kmsKeyName,omitempty"`
}

func (c *CreateCachedContentConfig) UnmarshalJSON(data []byte) error {
	type Alias CreateCachedContentConfig
	aux := &struct {
		TTL        *InternalDurationJSON `json:"ttl,omitempty"`
		ExpireTime *time.Time            `json:"expireTime,omitempty"`
		*Alias
	}{
		Alias: (*Alias)(c),
	}

	if err := json.Unmarshal(data, &aux); err != nil {
		return err
	}

	if !reflect.ValueOf(aux.TTL).IsZero() {
		c.TTL = time.Duration(*aux.TTL)
	}

	if !reflect.ValueOf(aux.ExpireTime).IsZero() {
		c.ExpireTime = time.Time(*aux.ExpireTime)
	}

	return nil
}

func (c *CreateCachedContentConfig) MarshalJSON() ([]byte, error) {
	type Alias CreateCachedContentConfig
	aux := &struct {
		TTL        *InternalDurationJSON `json:"ttl,omitempty"`
		ExpireTime *time.Time            `json:"expireTime,omitempty"`
		*Alias
	}{
		Alias: (*Alias)(c),
	}

	if !reflect.ValueOf(c.TTL).IsZero() {
		aux.TTL = (*InternalDurationJSON)(&c.TTL)
	}

	if !reflect.ValueOf(c.ExpireTime).IsZero() {
		aux.ExpireTime = (*time.Time)(&c.ExpireTime)
	}

	return json.Marshal(aux)
}

// Metadata on the usage of the cached content.
type CachedContentUsageMetadata struct {
	// Duration of audio in seconds. This field is not supported in Gemini API.
	AudioDurationSeconds int32 `json:"audioDurationSeconds,omitempty"`
	// Number of images. This field is not supported in Gemini API.
	ImageCount int32 `json:"imageCount,omitempty"`
	// Number of text characters. This field is not supported in Gemini API.
	TextCount int32 `json:"textCount,omitempty"`
	// Total number of tokens that the cached content consumes.
	TotalTokenCount int32 `json:"totalTokenCount,omitempty"`
	// Duration of video in seconds. This field is not supported in Gemini API.
	VideoDurationSeconds int32 `json:"videoDurationSeconds,omitempty"`
}

// A resource used in LLM queries for users to explicitly specify what to cache.
type CachedContent struct {
	// Optional. The server-generated resource name of the cached content.
	Name string `json:"name,omitempty"`
	// Optional. The user-generated meaningful display name of the cached content.
	DisplayName string `json:"displayName,omitempty"`
	// Optional. The name of the publisher model to use for cached content.
	Model string `json:"model,omitempty"`
	// Optional. Creation time of the cache entry.
	CreateTime time.Time `json:"createTime,omitempty"`
	// Optional. When the cache entry was last updated in UTC time.
	UpdateTime time.Time `json:"updateTime,omitempty"`
	// Optional. Expiration time of the cached content.
	ExpireTime time.Time `json:"expireTime,omitempty"`
	// Optional. Metadata on the usage of the cached content.
	UsageMetadata *CachedContentUsageMetadata `json:"usageMetadata,omitempty"`
}

func (c *CachedContent) UnmarshalJSON(data []byte) error {
	type Alias CachedContent
	aux := &struct {
		CreateTime *time.Time `json:"createTime,omitempty"`
		UpdateTime *time.Time `json:"updateTime,omitempty"`
		ExpireTime *time.Time `json:"expireTime,omitempty"`
		*Alias
	}{
		Alias: (*Alias)(c),
	}

	if err := json.Unmarshal(data, &aux); err != nil {
		return err
	}

	if !reflect.ValueOf(aux.CreateTime).IsZero() {
		c.CreateTime = time.Time(*aux.CreateTime)
	}

	if !reflect.ValueOf(aux.UpdateTime).IsZero() {
		c.UpdateTime = time.Time(*aux.UpdateTime)
	}

	if !reflect.ValueOf(aux.ExpireTime).IsZero() {
		c.ExpireTime = time.Time(*aux.ExpireTime)
	}

	return nil
}

func (c *CachedContent) MarshalJSON() ([]byte, error) {
	type Alias CachedContent
	aux := &struct {
		CreateTime *time.Time `json:"createTime,omitempty"`
		UpdateTime *time.Time `json:"updateTime,omitempty"`
		ExpireTime *time.Time `json:"expireTime,omitempty"`
		*Alias
	}{
		Alias: (*Alias)(c),
	}

	if !reflect.ValueOf(c.CreateTime).IsZero() {
		aux.CreateTime = (*time.Time)(&c.CreateTime)
	}

	if !reflect.ValueOf(c.UpdateTime).IsZero() {
		aux.UpdateTime = (*time.Time)(&c.UpdateTime)
	}

	if !reflect.ValueOf(c.ExpireTime).IsZero() {
		aux.ExpireTime = (*time.Time)(&c.ExpireTime)
	}

	return json.Marshal(aux)
}

// Optional parameters for caches.get method.
type GetCachedContentConfig struct {
	// Optional. Used to override HTTP request options.
	HTTPOptions *HTTPOptions `json:"httpOptions,omitempty"`
}

// Optional parameters for caches.delete method.
type DeleteCachedContentConfig struct {
	// Optional. Used to override HTTP request options.
	HTTPOptions *HTTPOptions `json:"httpOptions,omitempty"`
}

// Empty response for caches.delete method.
type DeleteCachedContentResponse struct {
	// Optional. Used to retain the full HTTP response.
	SDKHTTPResponse *HTTPResponse `json:"sdkHttpResponse,omitempty"`
}

// Optional parameters for caches.update method.
type UpdateCachedContentConfig struct {
	// Optional. Used to override HTTP request options.
	HTTPOptions *HTTPOptions `json:"httpOptions,omitempty"`
	// Optional. The TTL for this resource. The expiration time is computed: now + TTL.
	TTL time.Duration `json:"ttl,omitempty"`
	// Optional. Timestamp of when this resource is considered expired.
	ExpireTime time.Time `json:"expireTime,omitempty"`
}

func (u *UpdateCachedContentConfig) UnmarshalJSON(data []byte) error {
	type Alias UpdateCachedContentConfig
	aux := &struct {
		TTL        *InternalDurationJSON `json:"ttl,omitempty"`
		ExpireTime *time.Time            `json:"expireTime,omitempty"`
		*Alias
	}{
		Alias: (*Alias)(u),
	}

	if err := json.Unmarshal(data, &aux); err != nil {
		return err
	}

	if !reflect.ValueOf(aux.TTL).IsZero() {
		u.TTL = time.Duration(*aux.TTL)
	}

	if !reflect.ValueOf(aux.ExpireTime).IsZero() {
		u.ExpireTime = time.Time(*aux.ExpireTime)
	}

	return nil
}

func (u *UpdateCachedContentConfig) MarshalJSON() ([]byte, error) {
	type Alias UpdateCachedContentConfig
	aux := &struct {
		TTL        *InternalDurationJSON `json:"ttl,omitempty"`
		ExpireTime *time.Time            `json:"expireTime,omitempty"`
		*Alias
	}{
		Alias: (*Alias)(u),
	}

	if !reflect.ValueOf(u.TTL).IsZero() {
		aux.TTL = (*InternalDurationJSON)(&u.TTL)
	}

	if !reflect.ValueOf(u.ExpireTime).IsZero() {
		aux.ExpireTime = (*time.Time)(&u.ExpireTime)
	}

	return json.Marshal(aux)
}

// Config for caches.list method.
type ListCachedContentsConfig struct {
	// Optional. Used to override HTTP request options.
	HTTPOptions *HTTPOptions `json:"httpOptions,omitempty"`
	// Optional. PageSize specifies the maximum number of cached contents to return per
	// API call. If zero, the server will use a default value.
	PageSize int32 `json:"pageSize,omitempty"`
	// Optional. PageToken represents a token used for pagination in API responses. It's
	// an opaque string that should be passed to subsequent requests to retrieve the next
	// page of results. An empty PageToken typically indicates that there are no further
	// pages available.
	PageToken string `json:"pageToken,omitempty"`
}

type ListCachedContentsResponse struct {
	// Optional. Used to retain the full HTTP response.
	SDKHTTPResponse *HTTPResponse `json:"sdkHttpResponse,omitempty"`

	NextPageToken string `json:"nextPageToken,omitempty"`
	// List of cached contents.
	CachedContents []*CachedContent `json:"cachedContents,omitempty"`
}

// Optional Config.
type GetDocumentConfig struct {
	// Optional. Used to override HTTP request options.
	HTTPOptions *HTTPOptions `json:"httpOptions,omitempty"`
}

// User provided string values assigned to a single metadata key. This data type is
// not supported in Vertex AI.
type StringList struct {
	// The string values of the metadata to store.
	Values []string `json:"values,omitempty"`
}

// User provided metadata stored as key-value pairs. This data type is not supported
// in Vertex AI.
type CustomMetadata struct {
	// Required. The key of the metadata to store.
	Key string `json:"key,omitempty"`
	// The numeric value of the metadata to store.
	NumericValue *float32 `json:"numericValue,omitempty"`
	// The StringList value of the metadata to store.
	StringListValue *StringList `json:"stringListValue,omitempty"`
	// The string value of the metadata to store.
	StringValue string `json:"stringValue,omitempty"`
}

// A Document is a collection of Chunks.
type Document struct {
	// Immutable. Identifier. The `Document` resource name. The ID (name excluding the "fileSearchStores/&#42;/documents/"
	// prefix) can contain up to 40 characters that are lowercase alphanumeric or dashes
	// (-). The ID cannot start or end with a dash. If the name is empty on create, a unique
	// name will be derived from `display_name` along with a 12 character random suffix.
	// Example: `fileSearchStores/{file_search_store_id}/documents/my-awesome-doc-123a456b789c`
	Name string `json:"name,omitempty"`
	// Optional. The human-readable display name for the `Document`. The display name must
	// be no more than 512 characters in length, including spaces. Example: "Semantic Retriever
	// Documentation".
	DisplayName string `json:"displayName,omitempty"`
	// Output only. Current state of the `Document`.
	State DocumentState `json:"state,omitempty"`
	// Output only. The size of raw bytes ingested into the Document.
	SizeBytes int64 `json:"sizeBytes,omitempty,string"`
	// Output only. The MIME type of the Document.
	MIMEType string `json:"mimeType,omitempty"`
	// Output only. The Timestamp of when the `Document` was created.
	CreateTime time.Time `json:"createTime,omitempty"`
	// Optional. User provided custom metadata stored as key-value pairs used for querying.
	// A `Document` can have a maximum of 20 `CustomMetadata`.
	CustomMetadata []*CustomMetadata `json:"customMetadata,omitempty"`
	// Output only. The Timestamp of when the `Document` was last updated.
	UpdateTime time.Time `json:"updateTime,omitempty"`
}

func (d *Document) UnmarshalJSON(data []byte) error {
	type Alias Document
	aux := &struct {
		CreateTime *time.Time `json:"createTime,omitempty"`
		UpdateTime *time.Time `json:"updateTime,omitempty"`
		*Alias
	}{
		Alias: (*Alias)(d),
	}

	if err := json.Unmarshal(data, &aux); err != nil {
		return err
	}

	if !reflect.ValueOf(aux.CreateTime).IsZero() {
		d.CreateTime = time.Time(*aux.CreateTime)
	}

	if !reflect.ValueOf(aux.UpdateTime).IsZero() {
		d.UpdateTime = time.Time(*aux.UpdateTime)
	}

	return nil
}

func (d *Document) MarshalJSON() ([]byte, error) {
	type Alias Document
	aux := &struct {
		CreateTime *time.Time `json:"createTime,omitempty"`
		UpdateTime *time.Time `json:"updateTime,omitempty"`
		*Alias
	}{
		Alias: (*Alias)(d),
	}

	if !reflect.ValueOf(d.CreateTime).IsZero() {
		aux.CreateTime = (*time.Time)(&d.CreateTime)
	}

	if !reflect.ValueOf(d.UpdateTime).IsZero() {
		aux.UpdateTime = (*time.Time)(&d.UpdateTime)
	}

	return json.Marshal(aux)
}

// Config for optional parameters.
type DeleteDocumentConfig struct {
	// Optional. Used to override HTTP request options.
	HTTPOptions *HTTPOptions `json:"httpOptions,omitempty"`
	// Optional. If set to true, any `Chunk`s and objects related to this `Document` will
	// also be deleted.
	Force *bool `json:"force,omitempty"`
}

// Config for optional parameters.
type ListDocumentsConfig struct {
	// Optional. Used to override HTTP request options.
	HTTPOptions *HTTPOptions `json:"httpOptions,omitempty"`
	// Optional. PageSize specifies the maximum number of cached contents to return per
	// API call. If zero, the server will use a default value.
	PageSize int32 `json:"pageSize,omitempty"`
	// Optional. PageToken represents a token used for pagination in API responses. It's
	// an opaque string that should be passed to subsequent requests to retrieve the next
	// page of results. An empty PageToken typically indicates that there are no further
	// pages available.
	PageToken string `json:"pageToken,omitempty"`
}

// Config for documents.list return value.
type ListDocumentsResponse struct {
	// Optional. Used to retain the full HTTP response.
	SDKHTTPResponse *HTTPResponse `json:"sdkHttpResponse,omitempty"`
	// A token, which can be sent as `page_token` to retrieve the next page. If this field
	// is omitted, there are no more pages.
	NextPageToken string `json:"nextPageToken,omitempty"`
	// The returned `Document`s.
	Documents []*Document `json:"documents,omitempty"`
}

// Optional parameters for creating a file search store.
type CreateFileSearchStoreConfig struct {
	// Optional. Used to override HTTP request options.
	HTTPOptions *HTTPOptions `json:"httpOptions,omitempty"`
	// Optional. The human-readable display name for the file search store.
	DisplayName string `json:"displayName,omitempty"`
	// Optional. The embedding model to use for the FileSearchStore.
	// Format: `models/{model}`. If not specified, the default embedding model will be used.
	EmbeddingModel string `json:"embeddingModel,omitempty"`
}

// A collection of Documents.
type FileSearchStore struct {
	// Output only. Immutable. Identifier. The `FileSearchStore` resource name. It is an
	// ID (name excluding the "fileSearchStores/" prefix) that can contain up to 40 characters
	// that are lowercase alphanumeric or dashes (-). It is output only. The unique name
	// will be derived from `display_name` along with a 12 character random suffix. Example:
	// `fileSearchStores/my-awesome-file-search-store-123a456b789c` If `display_name` is
	// not provided, the name will be randomly generated.
	Name string `json:"name,omitempty"`
	// Optional. The human-readable display name for the `FileSearchStore`. The display
	// name must be no more than 512 characters in length, including spaces. Example: "Docs
	// on Semantic Retriever".
	DisplayName string `json:"displayName,omitempty"`
	// Output only. The Timestamp of when the `FileSearchStore` was created.
	CreateTime time.Time `json:"createTime,omitempty"`
	// Output only. The Timestamp of when the `FileSearchStore` was last updated.
	UpdateTime time.Time `json:"updateTime,omitempty"`
	// Output only. The number of documents in the `FileSearchStore` that are active and
	// ready for retrieval.
	ActiveDocumentsCount int64 `json:"activeDocumentsCount,omitempty,string"`
	// Output only. The number of documents in the `FileSearchStore` that are being processed.
	PendingDocumentsCount int64 `json:"pendingDocumentsCount,omitempty,string"`
	// Output only. The number of documents in the `FileSearchStore` that have failed processing.
	FailedDocumentsCount int64 `json:"failedDocumentsCount,omitempty,string"`
	// Output only. The size of raw bytes ingested into the `FileSearchStore`. This is the
	// total size of all the documents in the `FileSearchStore`.
	SizeBytes int64 `json:"sizeBytes,omitempty,string"`
	// Optional. The embedding model used by the FileSearchStore.
	EmbeddingModel string `json:"embeddingModel,omitempty"`
}

func (f *FileSearchStore) UnmarshalJSON(data []byte) error {
	type Alias FileSearchStore
	aux := &struct {
		CreateTime *time.Time `json:"createTime,omitempty"`
		UpdateTime *time.Time `json:"updateTime,omitempty"`
		*Alias
	}{
		Alias: (*Alias)(f),
	}

	if err := json.Unmarshal(data, &aux); err != nil {
		return err
	}

	if !reflect.ValueOf(aux.CreateTime).IsZero() {
		f.CreateTime = time.Time(*aux.CreateTime)
	}

	if !reflect.ValueOf(aux.UpdateTime).IsZero() {
		f.UpdateTime = time.Time(*aux.UpdateTime)
	}

	return nil
}

func (f *FileSearchStore) MarshalJSON() ([]byte, error) {
	type Alias FileSearchStore
	aux := &struct {
		CreateTime *time.Time `json:"createTime,omitempty"`
		UpdateTime *time.Time `json:"updateTime,omitempty"`
		*Alias
	}{
		Alias: (*Alias)(f),
	}

	if !reflect.ValueOf(f.CreateTime).IsZero() {
		aux.CreateTime = (*time.Time)(&f.CreateTime)
	}

	if !reflect.ValueOf(f.UpdateTime).IsZero() {
		aux.UpdateTime = (*time.Time)(&f.UpdateTime)
	}

	return json.Marshal(aux)
}

// Optional parameters for getting a FileSearchStore.
type GetFileSearchStoreConfig struct {
	// Optional. Used to override HTTP request options.
	HTTPOptions *HTTPOptions `json:"httpOptions,omitempty"`
}

// Optional parameters for deleting a FileSearchStore.
type DeleteFileSearchStoreConfig struct {
	// Optional. Used to override HTTP request options.
	HTTPOptions *HTTPOptions `json:"httpOptions,omitempty"`
	// Optional. If set to true, any Documents and objects related to this FileSearchStore
	// will also be deleted.
	// If false (the default), a FAILED_PRECONDITION error will be returned if
	// the FileSearchStore contains any Documents.
	Force *bool `json:"force,omitempty"`
}

// Optional parameters for listing FileSearchStore.
type ListFileSearchStoresConfig struct {
	// Optional. Used to override HTTP request options.
	HTTPOptions *HTTPOptions `json:"httpOptions,omitempty"`
	// Optional. PageSize specifies the maximum number of cached contents to return per
	// API call. If zero, the server will use a default value.
	PageSize int32 `json:"pageSize,omitempty"`
	// Optional. PageToken represents a token used for pagination in API responses. It's
	// an opaque string that should be passed to subsequent requests to retrieve the next
	// page of results. An empty PageToken typically indicates that there are no further
	// pages available.
	PageToken string `json:"pageToken,omitempty"`
}

// Config for file_search_stores.list return value.
type ListFileSearchStoresResponse struct {
	// Optional. Used to retain the full HTTP response.
	SDKHTTPResponse *HTTPResponse `json:"sdkHttpResponse,omitempty"`
	// A token, which can be sent as `page_token` to retrieve the next page. If this field
	// is omitted, there are no more pages.
	NextPageToken string `json:"nextPageToken,omitempty"`
	// The returned file search stores.
	FileSearchStores []*FileSearchStore `json:"fileSearchStores,omitempty"`
}

// Configuration for a white space chunking algorithm.
type WhiteSpaceConfig struct {
	// Optional. Maximum number of tokens per chunk.
	MaxTokensPerChunk *int32 `json:"maxTokensPerChunk,omitempty"`
	// Optional. Maximum number of overlapping tokens between two adjacent chunks.
	MaxOverlapTokens *int32 `json:"maxOverlapTokens,omitempty"`
}

// Config for telling the service how to chunk the file.
type ChunkingConfig struct {
	// Optional. White space chunking configuration.
	WhiteSpaceConfig *WhiteSpaceConfig `json:"whiteSpaceConfig,omitempty"`
}

// Optional parameters for uploading a file to a FileSearchStore.
type UploadToFileSearchStoreConfig struct {
	// Optional. Used to override HTTP request options.
	HTTPOptions *HTTPOptions `json:"httpOptions,omitempty"`
	// Optional. If true, the raw HTTP response will be returned in the 'sdk_http_response'
	// field.
	ShouldReturnHTTPResponse *bool `json:"shouldReturnHttpResponse,omitempty"`
	// Optional. MIME type of the file to be uploaded. If not provided, it will be inferred
	// from the file extension.
	MIMEType string `json:"mimeType,omitempty"`
	// Optional. Display name of the created document.
	DisplayName string `json:"displayName,omitempty"`
	// Optional. User provided custom metadata stored as key-value pairs used for querying.
	CustomMetadata []*CustomMetadata `json:"customMetadata,omitempty"`
	// Optional. Config for telling the service how to chunk the file.
	ChunkingConfig *ChunkingConfig `json:"chunkingConfig,omitempty"`
}

// Response for the resumable upload method.
type UploadToFileSearchStoreResumableResponse struct {
	// Optional. Used to retain the full HTTP response.
	SDKHTTPResponse *HTTPResponse `json:"sdkHttpResponse,omitempty"`
}

// Optional parameters for importing a file.
type ImportFileConfig struct {
	// Optional. Used to override HTTP request options.
	HTTPOptions *HTTPOptions `json:"httpOptions,omitempty"`
	// Optional. User provided custom metadata stored as key-value pairs used for querying.
	CustomMetadata []*CustomMetadata `json:"customMetadata,omitempty"`
	// Optional. Config for telling the service how to chunk the file.
	ChunkingConfig *ChunkingConfig `json:"chunkingConfig,omitempty"`
}

// Response for ImportFile to import a File API file with a file search store.
type ImportFileResponse struct {
	// Optional. Used to retain the full HTTP response.
	SDKHTTPResponse *HTTPResponse `json:"sdkHttpResponse,omitempty"`
	// The name of the FileSearchStore containing Documents.
	Parent string `json:"parent,omitempty"`
	// The identifier for the Document imported.
	DocumentName string `json:"documentName,omitempty"`
}

// Long-running operation for importing a file to a FileSearchStore.
type ImportFileOperation struct {
	// The server-assigned name, which is only unique within the same service that originally
	// returns it. If you use the default HTTP mapping, the `name` should be a resource
	// name ending with `operations/{unique_id}`.
	Name string `json:"name,omitempty"`
	// Optional. Service-specific metadata associated with the operation. It typically contains
	// progress information and common metadata such as create time. Some services might
	// not provide such metadata. Any method that returns a long-running operation should
	// document the metadata type, if any.
	Metadata map[string]any `json:"metadata,omitempty"`
	// If the value is `false`, it means the operation is still in progress. If `true`,
	// the operation is completed, and either `error` or `response` is available.
	Done bool `json:"done,omitempty"`
	// Optional. The error result of the operation in case of failure or cancellation.
	Error map[string]any `json:"error,omitempty"`
	// Optional. The result of the ImportFile operation, available when the operation is
	// done.
	Response *ImportFileResponse `json:"response,omitempty"`
}

// Used to override the default configuration.
type ListFilesConfig struct {
	// Optional. Used to override HTTP request options.
	HTTPOptions *HTTPOptions `json:"httpOptions,omitempty"`
	// Optional. PageSize specifies the maximum number of cached contents to return per
	// API call. If zero, the server will use a default value.
	PageSize int32 `json:"pageSize,omitempty"`
	// Optional. PageToken represents a token used for pagination in API responses. It's
	// an opaque string that should be passed to subsequent requests to retrieve the next
	// page of results. An empty PageToken typically indicates that there are no further
	// pages available.
	PageToken string `json:"pageToken,omitempty"`
}

// Status of a File that uses a common error model.
type FileStatus struct {
	// Optional. A list of messages that carry the error details. There is a common set
	// of message types for APIs to use.
	Details []map[string]any `json:"details,omitempty"`
	// Optional. A list of messages that carry the error details. There is a common set
	// of message types for APIs to use.
	Message string `json:"message,omitempty"`
	// Optional. The status code. 0 for OK, 1 for CANCELLED
	Code *int32 `json:"code,omitempty"`
}

// A file uploaded to the API.
type File struct {
	// Optional. The `File` resource name. The ID (name excluding the "files/" prefix) can
	// contain up to 40 characters that are lowercase alphanumeric or dashes (-). The ID
	// cannot start or end with a dash. If the name is empty on create, a unique name will
	// be generated. Example: `files/123-456`
	Name string `json:"name,omitempty"`
	// Optional. The human-readable display name for the `File`. The display name must be
	// no more than 512 characters in length, including spaces. Example: 'Welcome Image'
	DisplayName string `json:"displayName,omitempty"`
	// Optional. Output only. MIME type of the file.
	MIMEType string `json:"mimeType,omitempty"`
	// Optional. Output only. Size of the file in bytes.
	SizeBytes *int64 `json:"sizeBytes,omitempty,string"`
	// Optional. Output only. The timestamp of when the `File` was created.
	CreateTime time.Time `json:"createTime,omitempty"`
	// Optional. Output only. The timestamp of when the `File` will be deleted. Only set
	// if the `File` is scheduled to expire.
	ExpirationTime time.Time `json:"expirationTime,omitempty"`
	// Optional. Output only. The timestamp of when the `File` was last updated.
	UpdateTime time.Time `json:"updateTime,omitempty"`
	// Optional. Output only. SHA-256 hash of the uploaded bytes. The hash value is encoded
	// in base64 format.
	Sha256Hash string `json:"sha256Hash,omitempty"`
	// Optional. Output only. The URI of the `File`.
	URI string `json:"uri,omitempty"`
	// Optional. Output only. The URI of the `File`, only set for downloadable (generated)
	// files.
	DownloadURI string `json:"downloadUri,omitempty"`
	// Optional. Output only. Processing state of the File.
	State FileState `json:"state,omitempty"`
	// Optional. Output only. The source of the `File`.
	Source FileSource `json:"source,omitempty"`
	// Optional. Output only. Metadata for a video.
	VideoMetadata map[string]any `json:"videoMetadata,omitempty"`
	// Optional. Output only. Error status if File processing failed.
	Error *FileStatus `json:"error,omitempty"`
}

func (f *File) UnmarshalJSON(data []byte) error {
	type Alias File
	aux := &struct {
		CreateTime     *time.Time `json:"createTime,omitempty"`
		ExpirationTime *time.Time `json:"expirationTime,omitempty"`
		UpdateTime     *time.Time `json:"updateTime,omitempty"`
		*Alias
	}{
		Alias: (*Alias)(f),
	}

	if err := json.Unmarshal(data, &aux); err != nil {
		return err
	}

	if !reflect.ValueOf(aux.CreateTime).IsZero() {
		f.CreateTime = time.Time(*aux.CreateTime)
	}

	if !reflect.ValueOf(aux.ExpirationTime).IsZero() {
		f.ExpirationTime = time.Time(*aux.ExpirationTime)
	}

	if !reflect.ValueOf(aux.UpdateTime).IsZero() {
		f.UpdateTime = time.Time(*aux.UpdateTime)
	}

	return nil
}

func (f *File) MarshalJSON() ([]byte, error) {
	type Alias File
	aux := &struct {
		CreateTime     *time.Time `json:"createTime,omitempty"`
		ExpirationTime *time.Time `json:"expirationTime,omitempty"`
		UpdateTime     *time.Time `json:"updateTime,omitempty"`
		*Alias
	}{
		Alias: (*Alias)(f),
	}

	if !reflect.ValueOf(f.CreateTime).IsZero() {
		aux.CreateTime = (*time.Time)(&f.CreateTime)
	}

	if !reflect.ValueOf(f.ExpirationTime).IsZero() {
		aux.ExpirationTime = (*time.Time)(&f.ExpirationTime)
	}

	if !reflect.ValueOf(f.UpdateTime).IsZero() {
		aux.UpdateTime = (*time.Time)(&f.UpdateTime)
	}

	return json.Marshal(aux)
}

// DownloadURI represents a resource that can be downloaded.
//
// It is used to abstract the different types of resources that can be downloaded,
// such as files or videos
//
// You can create instances that implement this interface using the following
// constructor functions:
//   - NewDownloadURIFromFile
//   - NewDownloadURIFromVideo
//   - NewDownloadURIFromGeneratedVideo
//   - ...
type DownloadURI interface {
	uri() string
	setVideoBytes([]byte) bool
}

// NewDownloadURIFromFile creates a DownloadURI from a [File].
func NewDownloadURIFromFile(f *File) DownloadURI {
	return f
}

// NewDownloadURIFromVideo creates a DownloadURI from a [Video].
func NewDownloadURIFromVideo(v *Video) DownloadURI {
	return v
}

// NewDownloadURIFromVideo creates a DownloadURI from a [GeneratedVideo].
func NewDownloadURIFromGeneratedVideo(v *GeneratedVideo) DownloadURI {
	return v
}

func (f *File) uri() string {
	return f.DownloadURI
}

func (f *File) setVideoBytes(b []byte) bool {
	// File does not support setting video bytes.
	return false
}

// Response for the list files method.
type ListFilesResponse struct {
	// Optional. Used to retain the full HTTP response.
	SDKHTTPResponse *HTTPResponse `json:"sdkHttpResponse,omitempty"`
	// A token that can be sent as a `page_token` into a subsequent `ListFiles` call.
	NextPageToken string `json:"nextPageToken,omitempty"`
	// The list of `File`s.
	Files []*File `json:"files,omitempty"`
}

// Used to override the default configuration.
type CreateFileConfig struct {
	// Optional. Used to override HTTP request options.
	HTTPOptions *HTTPOptions `json:"httpOptions,omitempty"`
	// Optional. If true, the raw HTTP response will be returned in the 'sdk_http_response'
	// field.
	ShouldReturnHTTPResponse bool `json:"shouldReturnHttpResponse,omitempty"`
}

// Response for the create file method.
type CreateFileResponse struct {
	// Optional. Used to retain the full HTTP response.
	SDKHTTPResponse *HTTPResponse `json:"sdkHttpResponse,omitempty"`
}

// Used to override the default configuration.
type GetFileConfig struct {
	// Optional. Used to override HTTP request options.
	HTTPOptions *HTTPOptions `json:"httpOptions,omitempty"`
}

// Used to override the default configuration.
type DeleteFileConfig struct {
	// Optional. Used to override HTTP request options.
	HTTPOptions *HTTPOptions `json:"httpOptions,omitempty"`
}

// Response for the delete file method.
type DeleteFileResponse struct {
	// Optional. Used to retain the full HTTP response.
	SDKHTTPResponse *HTTPResponse `json:"sdkHttpResponse,omitempty"`
}

// Used to override the default configuration.
type RegisterFilesConfig struct {
	// Optional. Used to override HTTP request options.
	HTTPOptions *HTTPOptions `json:"httpOptions,omitempty"`
	// Optional. If true, the raw HTTP response will be returned in the 'sdk_http_response'
	// field.
	ShouldReturnHTTPResponse *bool `json:"shouldReturnHttpResponse,omitempty"`
}

// Response for the _register file method.
type RegisterFilesResponse struct {
	// Optional. Used to retain the full HTTP response.
	SDKHTTPResponse *HTTPResponse `json:"sdkHttpResponse,omitempty"`
	// The registered files.
	Files []*File `json:"files,omitempty"`
}

// Config for inlined request.
type InlinedRequest 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"`
	// Optional. The metadata to be associated with the request.
	Metadata map[string]string `json:"metadata,omitempty"`
	// Optional. Configuration that contains optional model parameters.
	Config *GenerateContentConfig `json:"config,omitempty"`
}

// Config for `src` parameter.
type BatchJobSource struct {
	// Storage format of the input files. Must be one of:
	// 'jsonl', 'bigquery', 'vertex-dataset'.
	Format string `json:"format,omitempty"`
	// Optional. The Google Cloud Storage URIs to input files.
	GCSURI []string `json:"gcsUri,omitempty"`
	// Optional. The BigQuery URI to input table.
	BigqueryURI string `json:"bigqueryUri,omitempty"`
	// Optional. The Gemini Developer API's file resource name of the input data
	// (e.g. "files/12345").
	FileName string `json:"fileName,omitempty"`
	// Optional. The Gemini Developer API's inlined input data to run batch job.
	InlinedRequests []*InlinedRequest `json:"inlinedRequests,omitempty"`
	// Optional. This field is experimental and may change in future versions. The Vertex
	// AI dataset resource name to use as input. Must be of type multimodal.
	VertexDatasetName string `json:"vertexDatasetName,omitempty"`
}

// This class is experimental and may change in future versions.
// The specification for an output Vertex AI multimodal dataset.
type VertexMultimodalDatasetDestination struct {
	// Optional. The BigQuery destination for the multimodal dataset.
	BigqueryDestination string `json:"bigqueryDestination,omitempty"`
	// Optional. The display name of the multimodal dataset.
	DisplayName string `json:"displayName,omitempty"`
}

// Job error.
type JobError struct {
	// A list of messages that carry the error details. There is a common set of message
	// types for APIs to use.
	Details []string `json:"details,omitempty"`
	// The status code.
	Code *int32 `json:"code,omitempty"`
	// A developer-facing error message, which should be in English. Any user-facing error
	// message should be localized and sent in the `details` field.
	Message string `json:"message,omitempty"`
}

// Config for `inlined_responses` parameter.
type InlinedResponse struct {
	// The response to the request.
	Response *GenerateContentResponse `json:"response,omitempty"`
	// Optional. The metadata to be associated with the request.
	Metadata map[string]string `json:"metadata,omitempty"`
	// Optional. The error encountered while processing the request.
	Error *JobError `json:"error,omitempty"`
}

// Config for `response` parameter.
type SingleEmbedContentResponse struct {
	// The response to the request.
	Embedding *ContentEmbedding `json:"embedding,omitempty"`
	// Optional. The error encountered while processing the request.
	TokenCount int64 `json:"tokenCount,omitempty,string"`
}

// Config for `inlined_embedding_responses` parameter.
type InlinedEmbedContentResponse struct {
	// Output only. The response to the request.
	Response *SingleEmbedContentResponse `json:"response,omitempty"`
	// Output only. The error encountered while processing the request.
	Error *JobError `json:"error,omitempty"`
	// Output only. The metadata associated with the request.
	Metadata map[string]any `json:"metadata,omitempty"`
}

// Config for `dest` parameter.
type BatchJobDestination struct {
	// Storage format of the output files. Must be one of:
	// 'jsonl', 'bigquery', 'vertex-dataset'.
	Format string `json:"format,omitempty"`
	// Optional. The Google Cloud Storage URI to the output file.
	GCSURI string `json:"gcsUri,omitempty"`
	// Optional. The BigQuery URI to the output table.
	BigqueryURI string `json:"bigqueryUri,omitempty"`
	// Optional. The Gemini Developer API's file resource name of the output data
	// (e.g. "files/12345"). The file will be a JSONL file with a single response
	// per line. The responses will be GenerateContentResponse messages formatted
	// as JSON. The responses will be written in the same order as the input
	// requests.
	FileName string `json:"fileName,omitempty"`
	// Optional. The responses to the requests in the batch. Returned when the batch was
	// built using inlined requests. The responses will be in the same order as
	// the input requests.
	InlinedResponses []*InlinedResponse `json:"inlinedResponses,omitempty"`
	// Optional. The responses to the requests in the batch. Returned when the batch was
	// built using inlined requests. The responses will be in the same order as
	// the input requests.
	InlinedEmbedContentResponses []*InlinedEmbedContentResponse `json:"inlinedEmbedContentResponses,omitempty"`
	// Optional. This field is experimental and may change in future versions. The Vertex
	// AI dataset destination.
	VertexDataset *VertexMultimodalDatasetDestination `json:"vertexDataset,omitempty"`
}

// Config for optional parameters.
type CreateBatchJobConfig struct {
	// Optional. Used to override HTTP request options.
	HTTPOptions *HTTPOptions `json:"httpOptions,omitempty"`
	// The user-defined name of this BatchJob.
	DisplayName string `json:"displayName,omitempty"`
	// GCS or BigQuery URI prefix for the output predictions. Example:
	// "gs://path/to/output/data" or "bq://projectId.bqDatasetId.bqTableId".
	Dest *BatchJobDestination `json:"dest,omitempty"`
	// Optional. Webhook configuration for receiving notifications when the batch
	// operation completes.
	WebhookConfig *WebhookConfig `json:"webhookConfig,omitempty"`
}

// Represents the `output_info` field in batch jobs.
type BatchJobOutputInfo struct {
	// This field is experimental and may change in future versions. The Vertex AI dataset
	// name containing the output data.
	VertexMultimodalDatasetName string `json:"vertexMultimodalDatasetName,omitempty"`
	// The full path of the Cloud Storage directory created, into which the prediction output
	// is written.
	GCSOutputDirectory string `json:"gcsOutputDirectory,omitempty"`
	// The name of the BigQuery table created, in `predictions_TIMESTAMP` format, into which
	// the prediction output is written.
	BigqueryOutputTable string `json:"bigqueryOutputTable,omitempty"`
}

// Success and error statistics of processing multiple entities (for example, DataItems
// or structured data rows) in batch. This data type is not supported in Gemini API.
type CompletionStats struct {
	// Output only. The number of entities for which any error was encountered.
	FailedCount int64 `json:"failedCount,omitempty,string"`
	// Output only. In cases when enough errors are encountered a job, pipeline, or operation
	// may be failed as a whole. Below is the number of entities for which the processing
	// had not been finished (either in successful or failed state). Set to -1 if the number
	// is unknown (for example, the operation failed before the total entity number could
	// be collected).
	IncompleteCount int64 `json:"incompleteCount,omitempty,string"`
	// Output only. The number of entities that had been processed successfully.
	SuccessfulCount int64 `json:"successfulCount,omitempty,string"`
	// Output only. The number of the successful forecast points that are generated by the
	// forecasting model. This is ONLY used by the forecasting batch prediction.
	SuccessfulForecastPointCount int64 `json:"successfulForecastPointCount,omitempty,string"`
}

// Config for batches.create return value.
type BatchJob struct {
	// The resource name of the BatchJob. Output only.".
	Name string `json:"name,omitempty"`
	// The display name of the BatchJob.
	DisplayName string `json:"displayName,omitempty"`
	// The state of the BatchJob.
	State JobState `json:"state,omitempty"`
	// Output only. Only populated when the job's state is JOB_STATE_FAILED or JOB_STATE_CANCELLED.
	Error *JobError `json:"error,omitempty"`
	// The time when the BatchJob was created.
	CreateTime time.Time `json:"createTime,omitempty"`
	// Output only. Time when the Job for the first time entered the `JOB_STATE_RUNNING`
	// state.
	StartTime time.Time `json:"startTime,omitempty"`
	// The time when the BatchJob was completed. This field is for Gemini Enterprise Agent
	// Platform only.
	EndTime time.Time `json:"endTime,omitempty"`
	// The time when the BatchJob was last updated.
	UpdateTime time.Time `json:"updateTime,omitempty"`
	// The name of the model that produces the predictions via the BatchJob.
	Model string `json:"model,omitempty"`
	// Configuration for the input data. This field is for Gemini Enterprise Agent Platform
	// only.
	Src *BatchJobSource `json:"src,omitempty"`
	// Configuration for the output data.
	Dest *BatchJobDestination `json:"dest,omitempty"`
	// Statistics on completed and failed prediction instances. This field is for Gemini
	// Enterprise Agent Platform only.
	CompletionStats *CompletionStats `json:"completionStats,omitempty"`
	// Information further describing the output of this job. Output only.
	OutputInfo *BatchJobOutputInfo `json:"outputInfo,omitempty"`
}

func (b *BatchJob) UnmarshalJSON(data []byte) error {
	type Alias BatchJob
	aux := &struct {
		CreateTime *time.Time `json:"createTime,omitempty"`
		StartTime  *time.Time `json:"startTime,omitempty"`
		EndTime    *time.Time `json:"endTime,omitempty"`
		UpdateTime *time.Time `json:"updateTime,omitempty"`
		*Alias
	}{
		Alias: (*Alias)(b),
	}

	if err := json.Unmarshal(data, &aux); err != nil {
		return err
	}

	if !reflect.ValueOf(aux.CreateTime).IsZero() {
		b.CreateTime = time.Time(*aux.CreateTime)
	}

	if !reflect.ValueOf(aux.StartTime).IsZero() {
		b.StartTime = time.Time(*aux.StartTime)
	}

	if !reflect.ValueOf(aux.EndTime).IsZero() {
		b.EndTime = time.Time(*aux.EndTime)
	}

	if !reflect.ValueOf(aux.UpdateTime).IsZero() {
		b.UpdateTime = time.Time(*aux.UpdateTime)
	}

	return nil
}

func (b *BatchJob) MarshalJSON() ([]byte, error) {
	type Alias BatchJob
	aux := &struct {
		CreateTime *time.Time `json:"createTime,omitempty"`
		StartTime  *time.Time `json:"startTime,omitempty"`
		EndTime    *time.Time `json:"endTime,omitempty"`
		UpdateTime *time.Time `json:"updateTime,omitempty"`
		*Alias
	}{
		Alias: (*Alias)(b),
	}

	if !reflect.ValueOf(b.CreateTime).IsZero() {
		aux.CreateTime = (*time.Time)(&b.CreateTime)
	}

	if !reflect.ValueOf(b.StartTime).IsZero() {
		aux.StartTime = (*time.Time)(&b.StartTime)
	}

	if !reflect.ValueOf(b.EndTime).IsZero() {
		aux.EndTime = (*time.Time)(&b.EndTime)
	}

	if !reflect.ValueOf(b.UpdateTime).IsZero() {
		aux.UpdateTime = (*time.Time)(&b.UpdateTime)
	}

	return json.Marshal(aux)
}

// Parameters for the embed_content method.
type EmbedContentBatch struct {
	// The content to embed. Only the `parts.text` fields will be counted.
	Contents []*Content `json:"contents,omitempty"`
	// Optional. Configuration that contains optional parameters.
	Config *EmbedContentConfig `json:"config,omitempty"`
}

type EmbeddingsBatchJobSource struct {
	// Optional. The Gemini Developer API's file resource name of the input data
	// (e.g. "files/12345").
	FileName string `json:"fileName,omitempty"`
	// Optional. The Gemini Developer API's inlined input data to run batch job.
	InlinedRequests *EmbedContentBatch `json:"inlinedRequests,omitempty"`
}

// Config for optional parameters.
type CreateEmbeddingsBatchJobConfig struct {
	// Optional. Used to override HTTP request options.
	HTTPOptions *HTTPOptions `json:"httpOptions,omitempty"`
	// Optional. The user-defined name of this BatchJob.
	DisplayName string `json:"displayName,omitempty"`
}

// Optional parameters.
type GetBatchJobConfig struct {
	// Optional. Used to override HTTP request options.
	HTTPOptions *HTTPOptions `json:"httpOptions,omitempty"`
}

// Optional parameters.
type CancelBatchJobConfig struct {
	// Optional. Used to override HTTP request options.
	HTTPOptions *HTTPOptions `json:"httpOptions,omitempty"`
}

// Config for optional parameters.
type ListBatchJobsConfig struct {
	// Optional. Used to override HTTP request options.
	HTTPOptions *HTTPOptions `json:"httpOptions,omitempty"`
	// Optional. PageSize specifies the maximum number of cached contents to return per
	// API call. If zero, the server will use a default value.
	PageSize int32 `json:"pageSize,omitempty"`
	// Optional. PageToken represents a token used for pagination in API responses. It's
	// an opaque string that should be passed to subsequent requests to retrieve the next
	// page of results. An empty PageToken typically indicates that there are no further
	// pages available.
	PageToken string `json:"pageToken,omitempty"`
	// Optional.
	Filter string `json:"filter,omitempty"`
}

// Config for batches.list return value.
type ListBatchJobsResponse struct {
	// Optional. Used to retain the full HTTP response.
	SDKHTTPResponse *HTTPResponse `json:"sdkHttpResponse,omitempty"`

	NextPageToken string `json:"nextPageToken,omitempty"`

	BatchJobs []*BatchJob `json:"batchJobs,omitempty"`
}

// Optional parameters for models.get method.
type DeleteBatchJobConfig struct {
	// Optional. Used to override HTTP request options.
	HTTPOptions *HTTPOptions `json:"httpOptions,omitempty"`
}

// The return value of delete operation.
type DeleteResourceJob struct {
	// Optional. Used to retain the full HTTP response.
	SDKHTTPResponse *HTTPResponse `json:"sdkHttpResponse,omitempty"`
	// Optional.
	Name string `json:"name,omitempty"`
	// Optional.
	Done bool `json:"done,omitempty"`
	// Optional.
	Error *JobError `json:"error,omitempty"`
}

type GetOperationConfig struct {
	// Optional. Used to override HTTP request options.
	HTTPOptions *HTTPOptions `json:"httpOptions,omitempty"`
}

type FetchPredictOperationConfig struct {
	// Optional. Used to override HTTP request options.
	HTTPOptions *HTTPOptions `json:"httpOptions,omitempty"`
}

// The response when long-running operation for uploading a file to a FileSearchStore
// complete.
type UploadToFileSearchStoreResponse struct {
	// Optional. Used to retain the full HTTP response.
	SDKHTTPResponse *HTTPResponse `json:"sdkHttpResponse,omitempty"`
	// The name of the FileSearchStore containing Documents.
	Parent string `json:"parent,omitempty"`
	// The identifier for the Document imported.
	DocumentName string `json:"documentName,omitempty"`
}

// Long-running operation for uploading a file to a FileSearchStore.
type UploadToFileSearchStoreOperation struct {
	// The server-assigned name, which is only unique within the same service that originally
	// returns it. If you use the default HTTP mapping, the `name` should be a resource
	// name ending with `operations/{unique_id}`.
	Name string `json:"name,omitempty"`
	// Optional. Service-specific metadata associated with the operation. It typically contains
	// progress information and common metadata such as create time. Some services might
	// not provide such metadata. Any method that returns a long-running operation should
	// document the metadata type, if any.
	Metadata map[string]any `json:"metadata,omitempty"`
	// If the value is `false`, it means the operation is still in progress. If `true`,
	// the operation is completed, and either `error` or `response` is available.
	Done bool `json:"done,omitempty"`
	// Optional. The error result of the operation in case of failure or cancellation.
	Error map[string]any `json:"error,omitempty"`
	// Optional. The result of the UploadToFileSearchStore operation, available when the
	// operation is done.
	Response *UploadToFileSearchStoreResponse `json:"response,omitempty"`
}

type testTableItem struct {
	// The name of the test. This is used to derive the replay id.
	Name string `json:"name,omitempty"`
	// The parameters to the test. Use pydantic models.
	Parameters map[string]any `json:"parameters,omitempty"`
	// Optional. Expects an exception for MLDev matching the string.
	ExceptionIfMLDev string `json:"exceptionIfMldev,omitempty"`
	// Optional. Expects an exception for Vertex matching the string.
	ExceptionIfVertex string `json:"exceptionIfVertex,omitempty"`
	// Optional. Use if you don't want to use the default replay ID which is derived from
	// the test name.
	OverrideReplayID string `json:"overrideReplayId,omitempty"`
	// Optional. True if the parameters contain an unsupported union type. This test will
	// be skipped for languages that do not support the union type.
	HasUnion bool `json:"hasUnion,omitempty"`
	// Optional. When set to a reason string, this test will be skipped in the API mode.
	// Use this flag for tests that can not be reproduced with the real API. E.g. a test
	// that deletes a resource.
	SkipInAPIMode string `json:"skipInApiMode,omitempty"`
	// Optional. Keys to ignore when comparing the request and response. This is useful
	// for tests that are not deterministic.
	IgnoreKeys []string `json:"ignoreKeys,omitempty"`
}

type testTableFile struct {
	Comment string `json:"comment,omitempty"`

	TestMethod string `json:"testMethod,omitempty"`

	ParameterNames []string `json:"parameterNames,omitempty"`

	TestTable []*testTableItem `json:"testTable,omitempty"`
}

// Represents a single request in a replay.
type replayRequest struct {
	Method string `json:"method,omitempty"`

	URL string `json:"url,omitempty"`

	Headers map[string]string `json:"headers,omitempty"`

	BodySegments []map[string]any `json:"bodySegments,omitempty"`
}

// Represents a single response in a replay.
type replayResponse struct {
	StatusCode int32 `json:"statusCode,omitempty"`

	Headers map[string]string `json:"headers,omitempty"`

	BodySegments []map[string]any `json:"bodySegments,omitempty"`

	SDKResponseSegments []map[string]any `json:"sdkResponseSegments,omitempty"`
}

// Represents a single interaction, request and response in a replay.
type replayInteraction struct {
	Request *replayRequest `json:"request,omitempty"`

	Response *replayResponse `json:"response,omitempty"`
}

// Represents a recorded session.
type replayFile struct {
	ReplayID string `json:"replayId,omitempty"`

	Interactions []*replayInteraction `json:"interactions,omitempty"`
}

// Used to override the default configuration.
type UploadFileConfig struct {
	// Optional. Used to override HTTP request options.
	HTTPOptions *HTTPOptions `json:"httpOptions,omitempty"`
	// Optional. The name of the file in the destination (e.g., 'files/sample-image'. If
	// not provided one will be generated.
	Name string `json:"name,omitempty"`
	// Optional. mime_type: The MIME type of the file. If not provided, it will be inferred
	// from the file extension.
	MIMEType string `json:"mimeType,omitempty"`
	// Optional. Optional display name of the file.
	DisplayName string `json:"displayName,omitempty"`
}

// Used to override the default configuration.
type DownloadFileConfig struct {
	// Optional. Used to override HTTP request options.
	HTTPOptions *HTTPOptions `json:"httpOptions,omitempty"`
}

// Configuration for upscaling an image.
// For more information on this configuration, refer to
// the `Imagen API reference documentation
// <https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/imagen-api>`_.
type UpscaleImageConfig struct {
	// Optional. Used to override HTTP request options.
	HTTPOptions *HTTPOptions `json:"httpOptions,omitempty"`
	// Optional. Cloud Storage URI used to store the generated images.
	OutputGCSURI string `json:"outputGcsUri,omitempty"`
	// Optional. Filter level for safety filtering.
	SafetyFilterLevel SafetyFilterLevel `json:"safetyFilterLevel,omitempty"`
	// Optional. Allows generation of people by the model.
	PersonGeneration PersonGeneration `json:"personGeneration,omitempty"`
	// Optional. Whether to include a reason for filtered-out images in the
	// response.
	IncludeRAIReason bool `json:"includeRaiReason,omitempty"`
	// Optional. The image format that the output should be saved as.
	OutputMIMEType string `json:"outputMimeType,omitempty"`
	// Optional. The level of compression if the OutputMIMEType is image/jpeg.
	OutputCompressionQuality *int32 `json:"outputCompressionQuality,omitempty"`
	// Optional. Whether to add an image enhancing step before upscaling.
	// It is expected to suppress the noise and JPEG compression artifacts
	// from the input image.
	EnhanceInputImage bool `json:"enhanceInputImage,omitempty"`
	// Optional. With a higher image preservation factor, the original image
	// pixels are more respected. With a lower image preservation factor, the
	// output image will have be more different from the input image, but
	// with finer details and less noise.
	ImagePreservationFactor *float32 `json:"imagePreservationFactor,omitempty"`
	// Optional. User specified labels to track billing usage.
	Labels map[string]string `json:"labels,omitempty"`
}

// A raw reference image.
// A raw reference image represents the base image to edit, provided by the user.
// It can optionally be provided in addition to a mask reference image or
// a style reference image.
type RawReferenceImage struct {
	// Optional. The reference image for the editing operation.
	ReferenceImage *Image `json:"referenceImage,omitempty"`
	// Optional. The ID of the reference image.
	ReferenceID int32 `json:"referenceId,omitempty"`
	// Optional. The type of the reference image. Only set by the SDK.
	referenceType string
}

func (r *RawReferenceImage) referenceImageAPI() *referenceImageAPI {
	return &referenceImageAPI{
		ReferenceImage: r.ReferenceImage,
		ReferenceID:    r.ReferenceID,
		ReferenceType:  "REFERENCE_TYPE_RAW",
	}
}

// A mask reference image. This encapsulates either a mask image provided by the user
// and configs for the user provided mask, or only config parameters for the model to
// generate a mask. A mask image is an image whose non-zero values indicate where to
// edit the base image. If the user provides a mask image, the mask must be in the same
// dimensions as the raw image.
type MaskReferenceImage struct {
	// Optional. The reference image for the editing operation.
	ReferenceImage *Image `json:"referenceImage,omitempty"`
	// Optional. The ID of the reference image.
	ReferenceID int32 `json:"referenceId,omitempty"`
	// Optional. The type of the reference image. Only set by the SDK.
	referenceType string
	// Optional. Configuration for the mask reference image.
	Config *MaskReferenceConfig `json:"config,omitempty"`
}

func (r *MaskReferenceImage) referenceImageAPI() *referenceImageAPI {
	return &referenceImageAPI{
		ReferenceImage:  r.ReferenceImage,
		ReferenceID:     r.ReferenceID,
		ReferenceType:   "REFERENCE_TYPE_MASK",
		MaskImageConfig: r.Config,
	}
}

// A control image is an image that represents a sketch image of areas for the model
// to fill in based on the prompt. Its image is either a control image provided by the
// user, or a regular image which the backend will use to generate a control image of.
// In the case of the latter, the EnableControlImageComputation field in the config
// should be set to true.
type ControlReferenceImage struct {
	// Optional. The reference image for the editing operation.
	ReferenceImage *Image `json:"referenceImage,omitempty"`
	// Optional. The ID of the reference image.
	ReferenceID int32 `json:"referenceId,omitempty"`
	// Optional. The type of the reference image. Only set by the SDK.
	referenceType string
	// Optional. Configuration for the control reference image.
	Config *ControlReferenceConfig `json:"config,omitempty"`
}

func (r *ControlReferenceImage) referenceImageAPI() *referenceImageAPI {
	return &referenceImageAPI{
		ReferenceImage:     r.ReferenceImage,
		ReferenceID:        r.ReferenceID,
		ReferenceType:      "REFERENCE_TYPE_CONTROL",
		ControlImageConfig: r.Config,
	}
}

// A style reference image.
// This encapsulates a style reference image provided by the user, and
// additionally optional config parameters for the style reference image.
// A raw reference image can also be provided as a destination for the style to
// be applied to.
type StyleReferenceImage struct {
	// Optional. The reference image for the editing operation.
	ReferenceImage *Image `json:"referenceImage,omitempty"`
	// Optional. The ID of the reference image.
	ReferenceID int32 `json:"referenceId,omitempty"`
	// Optional. The type of the reference image. Only set by the SDK.
	referenceType string
	// Optional. Configuration for the style reference image.
	Config *StyleReferenceConfig `json:"config,omitempty"`
}

func (r *StyleReferenceImage) referenceImageAPI() *referenceImageAPI {
	return &referenceImageAPI{
		ReferenceImage:   r.ReferenceImage,
		ReferenceID:      r.ReferenceID,
		ReferenceType:    "REFERENCE_TYPE_CONTROL",
		StyleImageConfig: r.Config,
	}
}

// A subject reference image.
// This encapsulates a subject reference image provided by the user, and
// additionally optional config parameters for the subject reference image.
// A raw reference image can also be provided as a destination for the subject to
// be applied to.
type SubjectReferenceImage struct {
	// Optional. The reference image for the editing operation.
	ReferenceImage *Image `json:"referenceImage,omitempty"`
	// Optional. The ID of the reference image.
	ReferenceID int32 `json:"referenceId,omitempty"`
	// Optional. The type of the reference image. Only set by the SDK.
	referenceType string
	// Optional. Configuration for the subject reference image.
	Config *SubjectReferenceConfig `json:"config,omitempty"`
}

func (r *SubjectReferenceImage) referenceImageAPI() *referenceImageAPI {
	return &referenceImageAPI{
		ReferenceImage:     r.ReferenceImage,
		ReferenceID:        r.ReferenceID,
		ReferenceType:      "REFERENCE_TYPE_CONTROL",
		SubjectImageConfig: r.Config,
	}
}

// A content reference image.
// A content reference image represents a subject to reference (ex. person,
// product, animal) provided by the user. It can optionally be provided in
// addition to a style reference image (ex. background, style reference).
type ContentReferenceImage struct {
	// Optional. The reference image for the editing operation.
	ReferenceImage *Image `json:"referenceImage,omitempty"`
	// Optional. The ID of the reference image.
	ReferenceID int32 `json:"referenceId,omitempty"`
	// Optional. The type of the reference image. Only set by the SDK.
	referenceType string
}

func (r *ContentReferenceImage) referenceImageAPI() *referenceImageAPI {
	return &referenceImageAPI{
		ReferenceImage: r.ReferenceImage,
		ReferenceID:    r.ReferenceID,
		ReferenceType:  "REFERENCE_TYPE_CONTENT",
	}
}

// Sent in response to a `LiveGenerateContentSetup` message from the client.
type LiveServerSetupComplete struct {
	// Optional. The session ID of the live session.
	SessionID string `json:"sessionId,omitempty"`
	// Optional. Signature of the verified consent audio. This is populated when the
	// request has a ReplicatedVoiceConfig with consent_audio set, if the consent
	// verification was successful. This may be used in a subsequent request
	// instead of the consent_audio to verify the same consent.
	VoiceConsentSignature *VoiceConsentSignature `json:"voiceConsentSignature,omitempty"`
}

// Audio transcription in Server Content.
type Transcription struct {
	// Optional. Transcription text.
	Text string `json:"text,omitempty"`
	// Optional. The bool indicates the end of the transcription.
	Finished bool `json:"finished,omitempty"`
	// The BCP-47 language code of the transcription.
	LanguageCode string `json:"languageCode,omitempty"`
}

// Incremental server update generated by the model in response to client messages.
// Content is generated as quickly as possible, and not in real time. Clients
// may choose to buffer and play it out in real time.
type LiveServerContent struct {
	// Optional. The content that the model has generated as part of the current conversation
	// with the user.
	ModelTurn *Content `json:"modelTurn,omitempty"`
	// Optional. If true, indicates that the model is done generating. Generation will only
	// start in response to additional client messages. Can be set alongside `content`,
	// indicating that the `content` is the last in the turn.
	TurnComplete bool `json:"turnComplete,omitempty"`
	// Optional. If true, indicates that a client message has interrupted current model
	// generation. If the client is playing out the content in realtime, this is a good
	// signal to stop and empty the current queue.
	Interrupted bool `json:"interrupted,omitempty"`
	// Optional. Metadata returned to client when grounding is enabled.
	GroundingMetadata *GroundingMetadata `json:"groundingMetadata,omitempty"`
	// Optional. If true, indicates that the model is done generating. When model is
	// interrupted while generating there will be no generation_complete message
	// in interrupted turn, it will go through interrupted > turn_complete.
	// When model assumes realtime playback there will be delay between
	// generation_complete and turn_complete that is caused by model
	// waiting for playback to finish. If true, indicates that the model
	// has finished generating all content. This is a signal to the client
	// that it can stop sending messages.
	GenerationComplete bool `json:"generationComplete,omitempty"`
	// Optional. Input transcription. The transcription is independent to the model
	// turn which means it doesn’t imply any ordering between transcription and
	// model turn.
	InputTranscription *Transcription `json:"inputTranscription,omitempty"`
	// Optional. Output transcription. The transcription is independent to the model
	// turn which means it doesn’t imply any ordering between transcription and
	// model turn.
	OutputTranscription *Transcription `json:"outputTranscription,omitempty"`
	// Optional. Metadata related to URL context retrieval tool.
	URLContextMetadata *URLContextMetadata `json:"urlContextMetadata,omitempty"`
	// Optional. Reason for the turn is complete.
	TurnCompleteReason TurnCompleteReason `json:"turnCompleteReason,omitempty"`
	// Optional. If true, indicates that the model is not generating content because
	// it is waiting for more input from the user, e.g. because it expects the
	// user to continue talking.
	WaitingForInput bool `json:"waitingForInput,omitempty"`
	// Optional. Low latency transcription updated while the user is speaking.
	InterimInputTranscription *Transcription `json:"interimInputTranscription,omitempty"`
}

// Request for the client to execute the `function_calls` and return the responses with
// the matching `id`s.
type LiveServerToolCall struct {
	// Optional. The function call to be executed.
	FunctionCalls []*FunctionCall `json:"functionCalls,omitempty"`
}

// Notification for the client that a previously issued `ToolCallMessage` with the specified
// `id`s should have been not executed and should be cancelled.
// If there were side-effects to those tool calls, clients may attempt to undo
// the tool calls. This message occurs only in cases where the clients interrupt
// server turns.
type LiveServerToolCallCancellation struct {
	// Optional. The IDs of the tool calls to be cancelled.
	IDs []string `json:"ids,omitempty"`
}

// Usage metadata about response(s).
type UsageMetadata struct {
	// The total number of tokens in the prompt. This includes any text, images, or other
	// media provided in the request. When `cached_content` is set, this also includes the
	// number of tokens in the cached content.
	PromptTokenCount int32 `json:"promptTokenCount,omitempty"`
	// Output only. The number of tokens in the cached content that was used for this request.
	CachedContentTokenCount int32 `json:"cachedContentTokenCount,omitempty"`
	// Optional. Total number of tokens across all the generated response candidates.
	ResponseTokenCount int32 `json:"responseTokenCount,omitempty"`
	// Output only. The number of tokens in the results from tool executions, which are
	// provided back to the model as input, if applicable.
	ToolUsePromptTokenCount int32 `json:"toolUsePromptTokenCount,omitempty"`
	// Output only. The number of tokens that were part of the model's generated "thoughts"
	// output, if applicable.
	ThoughtsTokenCount int32 `json:"thoughtsTokenCount,omitempty"`
	// The total number of tokens for the entire request. This is the sum of `prompt_token_count`,
	// `candidates_token_count`, `tool_use_prompt_token_count`, and `thoughts_token_count`.
	TotalTokenCount int32 `json:"totalTokenCount,omitempty"`
	// Output only. A detailed breakdown of the token count for each modality in the prompt.
	PromptTokensDetails []*ModalityTokenCount `json:"promptTokensDetails,omitempty"`
	// Output only. A detailed breakdown of the token count for each modality in the cached
	// content.
	CacheTokensDetails []*ModalityTokenCount `json:"cacheTokensDetails,omitempty"`
	// Optional. List of modalities that were returned in the response.
	ResponseTokensDetails []*ModalityTokenCount `json:"responseTokensDetails,omitempty"`
	// Output only. A detailed breakdown by modality of the token counts from the results
	// of tool executions, which are provided back to the model as input.
	ToolUsePromptTokensDetails []*ModalityTokenCount `json:"toolUsePromptTokensDetails,omitempty"`
	// Output only. The traffic type for this request. This field is not supported in Gemini
	// API.
	TrafficType TrafficType `json:"trafficType,omitempty"`
	// Output only. Service tier of the request. This field is not supported in Vertex AI.
	ServiceTier ServiceTier `json:"serviceTier,omitempty"`
}

// Server will not be able to service client soon.
type LiveServerGoAway struct {
	// Optional. The remaining time before the connection will be terminated as ABORTED.
	// The minimal time returned here is specified differently together with the rate limits
	// for a given model.
	TimeLeft time.Duration `json:"timeLeft,omitempty"`
}

func (l *LiveServerGoAway) UnmarshalJSON(data []byte) error {
	type Alias LiveServerGoAway
	aux := &struct {
		TimeLeft *InternalDurationJSON `json:"timeLeft,omitempty"`
		*Alias
	}{
		Alias: (*Alias)(l),
	}

	if err := json.Unmarshal(data, &aux); err != nil {
		return err
	}

	if !reflect.ValueOf(aux.TimeLeft).IsZero() {
		l.TimeLeft = time.Duration(*aux.TimeLeft)
	}

	return nil
}

func (l *LiveServerGoAway) MarshalJSON() ([]byte, error) {
	type Alias LiveServerGoAway
	aux := &struct {
		TimeLeft *InternalDurationJSON `json:"timeLeft,omitempty"`
		*Alias
	}{
		Alias: (*Alias)(l),
	}

	if !reflect.ValueOf(l.TimeLeft).IsZero() {
		aux.TimeLeft = (*InternalDurationJSON)(&l.TimeLeft)
	}

	return json.Marshal(aux)
}

// Update of the session resumption state.
// Only sent if `session_resumption` was set in the connection config.
type LiveServerSessionResumptionUpdate struct {
	// Optional. New handle that represents state that can be resumed. Empty if `resumable`=false.
	NewHandle string `json:"newHandle,omitempty"`
	// Optional. True if session can be resumed at this point. It might be not possible
	// to resume session at some points. In that case we send update empty new_handle and
	// resumable=false. Example of such case could be model executing function calls or
	// just generating. Resuming session (using previous session token) in such state will
	// result in some data loss.
	Resumable bool `json:"resumable,omitempty"`
	// Optional. Index of last message sent by client that is included in state represented
	// by this SessionResumptionToken. Only sent when `SessionResumptionConfig.transparent`
	// is set.
	// Presence of this index allows users to transparently reconnect and avoid issue of
	// losing some part of realtime audio input/video. If client wishes to temporarily disconnect
	// (for example as result of receiving GoAway) they can do it without losing state by
	// buffering messages sent since last `SessionResumptionTokenUpdate`. This field will
	// enable them to limit buffering (avoid keeping all requests in RAM).
	// Note: This should not be used for when resuming a session at some time later -- in
	// those cases partial audio and video frames are likely not needed.
	LastConsumedClientMessageIndex int64 `json:"lastConsumedClientMessageIndex,omitempty,string"`
}

type VoiceActivityDetectionSignal struct {
	// Optional. The type of the VAD signal.
	VADSignalType VADSignalType `json:"vadSignalType,omitempty"`
}

// Voice activity signal.
type VoiceActivity struct {
	// Optional. The type of the voice activity signal.
	VoiceActivityType VoiceActivityType `json:"voiceActivityType,omitempty"`
	// Optional. The time voice activity detected in audio time, relative to the start of
	// the audio stream.
	AudioOffset time.Duration `json:"audioOffset,omitempty"`
}

func (v *VoiceActivity) UnmarshalJSON(data []byte) error {
	type Alias VoiceActivity
	aux := &struct {
		AudioOffset *InternalDurationJSON `json:"audioOffset,omitempty"`
		*Alias
	}{
		Alias: (*Alias)(v),
	}

	if err := json.Unmarshal(data, &aux); err != nil {
		return err
	}

	if !reflect.ValueOf(aux.AudioOffset).IsZero() {
		v.AudioOffset = time.Duration(*aux.AudioOffset)
	}

	return nil
}

func (v *VoiceActivity) MarshalJSON() ([]byte, error) {
	type Alias VoiceActivity
	aux := &struct {
		AudioOffset *InternalDurationJSON `json:"audioOffset,omitempty"`
		*Alias
	}{
		Alias: (*Alias)(v),
	}

	if !reflect.ValueOf(v.AudioOffset).IsZero() {
		aux.AudioOffset = (*InternalDurationJSON)(&v.AudioOffset)
	}

	return json.Marshal(aux)
}

// Response message for API call.
type LiveServerMessage struct {
	// Optional. Sent in response to a `LiveClientSetup` message from the client.
	SetupComplete *LiveServerSetupComplete `json:"setupComplete,omitempty"`
	// Optional. Content generated by the model in response to client messages.
	ServerContent *LiveServerContent `json:"serverContent,omitempty"`
	// Optional. Request for the client to execute the `function_calls` and return the responses
	// with the matching `id`s.
	ToolCall *LiveServerToolCall `json:"toolCall,omitempty"`
	// Optional. Notification for the client that a previously issued `ToolCallMessage`
	// with the specified `id`s should have been not executed and should be cancelled.
	ToolCallCancellation *LiveServerToolCallCancellation `json:"toolCallCancellation,omitempty"`
	// Optional. Usage metadata about model response(s).
	UsageMetadata *UsageMetadata `json:"usageMetadata,omitempty"`
	// Optional. Server will disconnect soon.
	GoAway *LiveServerGoAway `json:"goAway,omitempty"`
	// Optional. Update of the session resumption state.
	SessionResumptionUpdate *LiveServerSessionResumptionUpdate `json:"sessionResumptionUpdate,omitempty"`
	// Optional. Voice activity detection signal. Allowlisted only.
	VoiceActivityDetectionSignal *VoiceActivityDetectionSignal `json:"voiceActivityDetectionSignal,omitempty"`
	// Optional. Voice activity signal.
	VoiceActivity *VoiceActivity `json:"voiceActivity,omitempty"`
}

// Configures automatic detection of activity.
type AutomaticActivityDetection struct {
	// Optional. If enabled, detected voice and text input count as activity. If disabled,
	// the client must send activity signals.
	Disabled bool `json:"disabled,omitempty"`
	// Optional. Determines how likely speech is to be detected.
	StartOfSpeechSensitivity StartSensitivity `json:"startOfSpeechSensitivity,omitempty"`
	// Optional. Determines how likely detected speech is ended.
	EndOfSpeechSensitivity EndSensitivity `json:"endOfSpeechSensitivity,omitempty"`
	// Optional. The required duration of detected speech before start-of-speech is committed.
	// The lower this value the more sensitive the start-of-speech detection is and the
	// shorter speech can be recognized. However, this also increases the probability of
	// false positives.
	PrefixPaddingMs *int32 `json:"prefixPaddingMs,omitempty"`
	// Optional. The required duration of detected non-speech (e.g. silence) before end-of-speech
	// is committed. The larger this value, the longer speech gaps can be without interrupting
	// the user's activity but this will increase the model's latency.
	SilenceDurationMs *int32 `json:"silenceDurationMs,omitempty"`
}

// Marks the end of user activity.
// This can only be sent if automatic (i.e. server-side) activity detection is
// disabled.
type RealtimeInputConfig struct {
	// Optional. If not set, automatic activity detection is enabled by default. If automatic
	// voice detection is disabled, the client must send activity signals.
	AutomaticActivityDetection *AutomaticActivityDetection `json:"automaticActivityDetection,omitempty"`
	// Optional. Defines what effect activity has.
	ActivityHandling ActivityHandling `json:"activityHandling,omitempty"`
	// Optional. Defines which input is included in the user's turn.
	TurnCoverage TurnCoverage `json:"turnCoverage,omitempty"`
}

// Configuration of session resumption mechanism.
// Included in `LiveConnectConfig.session_resumption`. If included server
// will send `LiveServerSessionResumptionUpdate` messages.
type SessionResumptionConfig struct {
	// Optional. Session resumption handle of previous session (session to restore).
	// If not present new session will be started.
	Handle string `json:"handle,omitempty"`
	// Optional. If set the server will send `last_consumed_client_message_index` in the
	// `session_resumption_update` messages to allow for transparent reconnections.
	Transparent bool `json:"transparent,omitempty"`
}

// Context window will be truncated by keeping only suffix of it.
// Context window will always be cut at start of USER role turn. System
// instructions and `BidiGenerateContentSetup.prefix_turns` will not be
// subject to the sliding window mechanism, they will always stay at the
// beginning of context window.
type SlidingWindow struct {
	// Optional. Session reduction target -- how many tokens we should keep. Window shortening
	// operation has some latency costs, so we should avoid running it on every turn. Should
	// be < trigger_tokens. If not set, trigger_tokens/2 is assumed.
	TargetTokens *int64 `json:"targetTokens,omitempty,string"`
}

// Enables context window compression -- mechanism managing model context window so
// it does not exceed given length.
type ContextWindowCompressionConfig struct {
	// Optional. Number of tokens (before running turn) that triggers context window compression
	// mechanism.
	TriggerTokens *int64 `json:"triggerTokens,omitempty,string"`
	// Optional. Sliding window compression mechanism.
	SlidingWindow *SlidingWindow `json:"slidingWindow,omitempty"`
}

// Indicates the language of the audio should be automatically detected.
type LanguageAuto struct {
}

// Provides hints to the model about possible languages present in the audio.
type LanguageHints struct {
	// Optional. BCP-47 language codes. At least one must be specified.
	LanguageCodes []string `json:"languageCodes,omitempty"`
}

// The audio transcription configuration in Setup.
type AudioTranscriptionConfig struct {
	// Optional. Deprecated: use LanguageAuto or LanguageHints instead.
	LanguageCodes []string `json:"languageCodes,omitempty"`
	// Optional. The model will detect the language automatically. Do not use together with
	// LanguageHints.
	LanguageAuto *LanguageAuto `json:"languageAuto,omitempty"`
	// Optional. Specifies one or more languages in the audio. Do not use together with
	// LanguageAuto.
	LanguageHints *LanguageHints `json:"languageHints,omitempty"`
	// Optional. A list of phrases used for speech adaptation, which biases the ASR model
	// to improve recognition of these specific terms.
	AdaptationPhrases []string `json:"adaptationPhrases,omitempty"`
}

// Config for proactivity features.
type ProactivityConfig struct {
	// Optional. If enabled, the model can reject responding to the last prompt. For
	// example, this allows the model to ignore out of context speech or to stay
	// silent if the user did not make a request, yet.
	ProactiveAudio *bool `json:"proactiveAudio,omitempty"`
}

// Configures the customized avatar to be used in the session.
type CustomizedAvatar struct {
	// Optional. The MIME type of the reference image, e.g., "image/jpeg".
	ImageMIMEType string `json:"imageMimeType,omitempty"`
	// Optional. The data of the reference image. The dimensions of the reference
	// image should be 9:16 (portrait) with a minimum resolution of 704x1280.
	ImageData []byte `json:"imageData,omitempty"`
}

// Configures the avatar to be used in the session.
type AvatarConfig struct {
	// Optional. Pre-built avatar id.
	AvatarName string `json:"avatarName,omitempty"`
	// Optional. Customized avatar appearance with a reference image.
	CustomizedAvatar *CustomizedAvatar `json:"customizedAvatar,omitempty"`
	// Optional. The bitrate of compressed audio.
	AudioBitrateBps *int32 `json:"audioBitrateBps,omitempty"`
	// Optional. The bitrate of compressed video output.
	VideoBitrateBps *int32 `json:"videoBitrateBps,omitempty"`
}

// Message contains configuration that will apply for the duration of the streaming
// session.
type LiveClientSetup struct {
	// The fully qualified name of the publisher model or tuned model endpoint to
	// use.
	Model string `json:"model,omitempty"`
	// Optional. The generation configuration for the session.
	// Note: only a subset of fields are supported.
	GenerationConfig *GenerationConfig `json:"generationConfig,omitempty"`
	// Optional. The user provided system instructions for the model.
	// Note: only text should be used in parts and content in each part will be
	// in a separate paragraph.
	SystemInstruction *Content `json:"systemInstruction,omitempty"`
	// Optional. A list of `Tools` the model may use to generate the next response.
	// A `Tool` is a piece of code that enables the system to interact with
	// external systems to perform an action, or set of actions, outside of
	// knowledge and scope of the model.
	Tools []*Tool `json:"tools,omitempty"`
	// Optional. Configures the realtime input behavior in BidiGenerateContent.
	RealtimeInputConfig *RealtimeInputConfig `json:"realtimeInputConfig,omitempty"`
	// Optional. Configures session resumption mechanism.
	// If included server will send SessionResumptionUpdate messages.
	SessionResumption *SessionResumptionConfig `json:"sessionResumption,omitempty"`
	// Optional. Configures context window compression mechanism.
	// If included, server will compress context window to fit into given length.
	ContextWindowCompression *ContextWindowCompressionConfig `json:"contextWindowCompression,omitempty"`
	// Optional. The transcription of the input aligns with the input audio language.
	InputAudioTranscription *AudioTranscriptionConfig `json:"inputAudioTranscription,omitempty"`
	// Optional. The transcription of the output aligns with the language code
	// specified for the output audio.
	OutputAudioTranscription *AudioTranscriptionConfig `json:"outputAudioTranscription,omitempty"`
	// Optional. Configures the proactivity of the model. This allows the model to respond
	// proactively to
	// the input and to ignore irrelevant input.
	Proactivity *ProactivityConfig `json:"proactivity,omitempty"`
	// Optional. Configures the explicit VAD signal. If enabled, the client will send
	// vad_signal to indicate the start and end of speech. This allows the server
	// to process the audio more efficiently.
	ExplicitVADSignal bool `json:"explicitVadSignal,omitempty"`
	// Optional. Configures the avatar model behavior.
	AvatarConfig *AvatarConfig `json:"avatarConfig,omitempty"`
	// Optional. Safety settings in the request to block unsafe content in the
	// response.
	SafetySettings []*SafetySetting `json:"safetySettings,omitempty"`
}

// Incremental update of the current conversation delivered from the client.
// All the content here will unconditionally be appended to the conversation
// history and used as part of the prompt to the model to generate content.
// A message here will interrupt any current model generation.
type LiveClientContent struct {
	// Optional. The content appended to the current conversation with the model.
	// For single-turn queries, this is a single instance. For multi-turn
	// queries, this is a repeated field that contains conversation history and
	// latest request.
	Turns []*Content `json:"turns,omitempty"`
	// Optional. If true, indicates that the server content generation should start with
	// the currently accumulated prompt. Otherwise, the server will await
	// additional messages before starting generation.
	TurnComplete bool `json:"turnComplete,omitempty"`
}

// Marks the start of user activity.
// This can only be sent if automatic (i.e. server-side) activity detection is
// disabled.
type ActivityStart struct {
}

// Marks the end of user activity.
// This can only be sent if automatic (i.e. server-side) activity detection is
// disabled.
type ActivityEnd struct {
}

// User input that is sent in real time.
// This is different from `LiveClientContent` in a few ways:
//   - Can be sent continuously without interruption to model generation.
//   - If there is a need to mix data interleaved across the
//     `LiveClientContent` and the `LiveClientRealtimeInput`, server attempts to
//     optimize for best response, but there are no guarantees.
//   - End of turn is not explicitly specified, but is rather derived from user
//     activity (for example, end of speech).
//   - Even before the end of turn, the data is processed incrementally
//     to optimize for a fast start of the response from the model.
//   - Is always assumed to be the user's input (cannot be used to populate
//     conversation history).
type LiveClientRealtimeInput struct {
	// Optional. Inlined bytes data for media input.
	MediaChunks []*Blob `json:"mediaChunks,omitempty"`
	// Optional. Marks the start of user activity.
	ActivityStart *ActivityStart `json:"activityStart,omitempty"`
	// Optional. Marks the end of user activity.
	ActivityEnd *ActivityEnd `json:"activityEnd,omitempty"`
}

// Client generated response to a `ToolCall` received from the server.
// Individual `FunctionResponse` objects are matched to the respective
// `FunctionCall` objects by the `id` field.
// Note that in the unary and server-streaming GenerateContent APIs function
// calling happens by exchanging the `Content` parts, while in the bidi
// GenerateContent APIs function calling happens over this dedicated set of
// messages.
type LiveClientToolResponse struct {
	// Optional. The response to the function calls.
	FunctionResponses []*FunctionResponse `json:"functionResponses,omitempty"`
}

// Messages sent by the client in the API call.
type LiveClientMessage struct {
	// Optional. Message to be sent by the system when connecting to the API. SDK users
	// should not send this message.
	Setup *LiveClientSetup `json:"setup,omitempty"`
	// Optional. Incremental update of the current conversation delivered from the client.
	ClientContent *LiveClientContent `json:"clientContent,omitempty"`
	// Optional. User input that is sent in real time.
	RealtimeInput *LiveClientRealtimeInput `json:"realtimeInput,omitempty"`
	// Optional. Response to a `ToolCallMessage` received from the server.
	ToolResponse *LiveClientToolResponse `json:"toolResponse,omitempty"`
}

// Session config for the API connection.
type LiveConnectConfig struct {
	// Optional. Used to override HTTP request options.
	HTTPOptions *HTTPOptions `json:"httpOptions,omitempty"`
	// Optional. The requested modalities of the response. Represents the set of
	// modalities that the model can return. Defaults to AUDIO if not specified.
	ResponseModalities []Modality `json:"responseModalities,omitempty"`
	// Optional. 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 *float32 `json:"temperature,omitempty"`
	// Optional. 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 *float32 `json:"topP,omitempty"`
	// Optional. 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 *float32 `json:"topK,omitempty"`
	// Optional. Maximum number of tokens that can be generated in the response.
	// If empty, API will use a default value. The default value varies by model.
	MaxOutputTokens int32 `json:"maxOutputTokens,omitempty"`
	// Optional. If specified, the media resolution specified will be used.
	MediaResolution MediaResolution `json:"mediaResolution,omitempty"`
	// Optional. 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 *int32 `json:"seed,omitempty"`
	// Optional. The speech generation configuration.
	SpeechConfig *SpeechConfig `json:"speechConfig,omitempty"`
	// Optional. Config for thinking features.
	// An error will be returned if this field is set for models that don't
	// support thinking.
	ThinkingConfig *ThinkingConfig `json:"thinkingConfig,omitempty"`
	// Optional. If enabled, the model will detect emotions and adapt its responses accordingly.
	EnableAffectiveDialog *bool `json:"enableAffectiveDialog,omitempty"`
	// Optional. The user provided system instructions for the model.
	// Note: only text should be used in parts and content in each part will be
	// in a separate paragraph.
	SystemInstruction *Content `json:"systemInstruction,omitempty"`
	// Optional. A list of `Tools` the model may use to generate the next response.
	// A `Tool` is a piece of code that enables the system to interact with
	// external systems to perform an action, or set of actions, outside of
	// knowledge and scope of the model.
	Tools []*Tool `json:"tools,omitempty"`
	// Optional. Configures session resumption mechanism.
	// If included the server will send SessionResumptionUpdate messages.
	SessionResumption *SessionResumptionConfig `json:"sessionResumption,omitempty"`
	// Optional. The transcription of the input aligns with the input audio language.
	InputAudioTranscription *AudioTranscriptionConfig `json:"inputAudioTranscription,omitempty"`
	// Optional. The transcription of the output aligns with the language code
	// specified for the output audio.
	OutputAudioTranscription *AudioTranscriptionConfig `json:"outputAudioTranscription,omitempty"`
	// Optional. Configures the realtime input behavior in BidiGenerateContent.
	RealtimeInputConfig *RealtimeInputConfig `json:"realtimeInputConfig,omitempty"`
	// Optional. Configures context window compression mechanism.
	// If included, server will compress context window to fit into given length.
	ContextWindowCompression *ContextWindowCompressionConfig `json:"contextWindowCompression,omitempty"`
	// Optional. Configures the proactivity of the model. This allows the model to respond
	// proactively to
	// the input and to ignore irrelevant input.
	Proactivity *ProactivityConfig `json:"proactivity,omitempty"`
	// Optional. Configures the explicit VAD signal. If enabled, the client will send
	// vad_signal to indicate the start and end of speech. This allows the server
	// to process the audio more efficiently.
	ExplicitVADSignal *bool `json:"explicitVadSignal,omitempty"`
	// Optional. Configures the avatar model behavior.
	AvatarConfig *AvatarConfig `json:"avatarConfig,omitempty"`
	// Optional. Safety settings in the request to block unsafe content in the
	// response.
	SafetySettings []*SafetySetting `json:"safetySettings,omitempty"`
	// Optional. Config for translation.
	TranslationConfig *TranslationConfig `json:"translationConfig,omitempty"`
}

// Parameters for sending client content to the live API.
type LiveSendClientContentParameters struct {
	// Optional. Client content to send to the session.
	Turns []*Content `json:"turns,omitempty"`
	// Optional. If true, indicates that the server content generation should start with
	// the currently accumulated prompt. Otherwise, the server will await
	// additional messages before starting generation. If nil, then SDK will use the default
	// value Ptr(true).
	TurnComplete *bool `json:"turnComplete,omitempty"`
}

func (p LiveSendClientContentParameters) toLiveClientMessage() *LiveClientMessage {
	if p.TurnComplete == nil {
		p.TurnComplete = Ptr(true)
	}
	return &LiveClientMessage{
		ClientContent: &LiveClientContent{Turns: p.Turns, TurnComplete: *p.TurnComplete},
	}
}

// Parameters for sending realtime input to the live API.
type LiveSendRealtimeInputParameters struct {
	// Optional. Realtime input to send to the session.
	Media *Blob `json:"media,omitempty"`
	// Optional. The realtime audio input stream.
	Audio *Blob `json:"audio,omitempty"`
	// Optional.
	// Indicates that the audio stream has ended, e.g. because the microphone was
	// turned off.
	// This should only be sent when automatic activity detection is enabled
	// (which is the default).
	// The client can reopen the stream by sending an audio message.
	AudioStreamEnd bool `json:"audioStreamEnd,omitempty"`
	// Optional. The realtime video input stream.
	Video *Blob `json:"video,omitempty"`
	// Optional. The realtime text input stream.
	Text string `json:"text,omitempty"`
	// Optional. Marks the start of user activity.
	ActivityStart *ActivityStart `json:"activityStart,omitempty"`
	// Optional. Marks the end of user activity.
	ActivityEnd *ActivityEnd `json:"activityEnd,omitempty"`
}

// Parameters for sending tool responses to the live API.
type LiveSendToolResponseParameters struct {
	// Tool responses to send to the session.
	FunctionResponses []*FunctionResponse `json:"functionResponses,omitempty"`
}

func (p LiveSendToolResponseParameters) toLiveClientMessage() *LiveClientMessage {
	return &LiveClientMessage{
		ToolResponse: &LiveClientToolResponse{FunctionResponses: p.FunctionResponses},
	}
}

// Config for auth_tokens.create parameters.
type AuthToken struct {
	// Optional. The name of the auth token.
	Name string `json:"name,omitempty"`
}

// Config for LiveConnectConstraints for Auth Token creation.
type LiveConnectConstraints struct {
	// Optional. ID of the model to configure in the ephemeral token for Live API.
	// For a list of models, see `Gemini models
	// <https://ai.google.dev/gemini-api/docs/models>`.
	Model string `json:"model,omitempty"`
	// Optional. Configuration specific to Live API connections created using this token.
	Config *LiveConnectConfig `json:"config,omitempty"`
}

// Optional parameters.
type CreateAuthTokenConfig struct {
	// Optional. Used to override HTTP request options.
	HTTPOptions *HTTPOptions `json:"httpOptions,omitempty"`
	// Optional. An optional time after which, when using the resulting token,
	// messages in Live API sessions will be rejected. (Gemini may
	// preemptively close the session after this time.)
	// If not set then this defaults to 30 minutes in the future. If set, this
	// value must be less than 20 hours in the future.
	ExpireTime time.Time `json:"expireTime,omitempty"`
	// Optional. The time after which new Live API sessions using the token
	// resulting from this request will be rejected.
	// If not set this defaults to 60 seconds in the future. If set, this value
	// must be less than 20 hours in the future.
	NewSessionExpireTime time.Time `json:"newSessionExpireTime,omitempty"`
	// Optional. The number of times the token can be used. If this value is zero
	// then no limit is applied. Default is 1. Resuming a Live API session does
	// not count as a use.
	Uses *int32 `json:"uses,omitempty"`
	// Optional. Configuration specific to Live API connections created using this token.
	LiveConnectConstraints *LiveConnectConstraints `json:"liveConnectConstraints,omitempty"`
	// Optional. Additional fields to lock in the effective LiveConnectParameters.
	LockAdditionalFields []string `json:"lockAdditionalFields,omitempty"`
}

func (c *CreateAuthTokenConfig) UnmarshalJSON(data []byte) error {
	type Alias CreateAuthTokenConfig
	aux := &struct {
		ExpireTime           *time.Time `json:"expireTime,omitempty"`
		NewSessionExpireTime *time.Time `json:"newSessionExpireTime,omitempty"`
		*Alias
	}{
		Alias: (*Alias)(c),
	}

	if err := json.Unmarshal(data, &aux); err != nil {
		return err
	}

	if !reflect.ValueOf(aux.ExpireTime).IsZero() {
		c.ExpireTime = time.Time(*aux.ExpireTime)
	}

	if !reflect.ValueOf(aux.NewSessionExpireTime).IsZero() {
		c.NewSessionExpireTime = time.Time(*aux.NewSessionExpireTime)
	}

	return nil
}

func (c *CreateAuthTokenConfig) MarshalJSON() ([]byte, error) {
	type Alias CreateAuthTokenConfig
	aux := &struct {
		ExpireTime           *time.Time `json:"expireTime,omitempty"`
		NewSessionExpireTime *time.Time `json:"newSessionExpireTime,omitempty"`
		*Alias
	}{
		Alias: (*Alias)(c),
	}

	if !reflect.ValueOf(c.ExpireTime).IsZero() {
		aux.ExpireTime = (*time.Time)(&c.ExpireTime)
	}

	if !reflect.ValueOf(c.NewSessionExpireTime).IsZero() {
		aux.NewSessionExpireTime = (*time.Time)(&c.NewSessionExpireTime)
	}

	return json.Marshal(aux)
}

// Local tokenizer count tokens result.
type CountTokensResult struct {
	// Optional. The total number of tokens.
	TotalTokens int32 `json:"totalTokens,omitempty"`
}

// Local tokenizer compute tokens result.
type ComputeTokensResult struct {
	// Optional. Lists of tokens info from the input.
	TokensInfo []*TokensInfo `json:"tokensInfo,omitempty"`
}

// Used to override the default configuration.
type DownloadMediaConfig struct {
	// Optional. Used to override HTTP request options.
	HTTPOptions *HTTPOptions `json:"httpOptions,omitempty"`
}
