# Generated by the protocol buffer compiler.  DO NOT EDIT!
# sources: google/ai/generativelanguage/v1beta/citation.proto, google/ai/generativelanguage/v1beta/content.proto, google/ai/generativelanguage/v1beta/generative_service.proto, google/ai/generativelanguage/v1beta/retriever.proto, google/ai/generativelanguage/v1beta/safety.proto
# plugin: python-betterproto
# This file has been @generated

from dataclasses import dataclass
from datetime import (
  datetime,
  timedelta,
)
from typing import (
  TYPE_CHECKING,
  AsyncIterable,
  AsyncIterator,
  Dict,
  Iterable,
  List,
  Optional,
  Union,
)

import betterproto
import betterproto.lib.google.protobuf as betterproto_lib_google_protobuf
import grpclib
from betterproto.grpc.grpclib_server import ServiceBase

from .... import type as ___type__

if TYPE_CHECKING:
  import grpclib.server
  from betterproto.grpc.grpclib_client import MetadataLike
  from grpclib.metadata import Deadline


class Type(betterproto.Enum):
  """
  Type contains the list of OpenAPI data types as defined by
   https://spec.openapis.org/oas/v3.0.3#data-types
  """

  UNSPECIFIED = 0
  """Not specified, should not be used."""

  STRING = 1
  """String type."""

  NUMBER = 2
  """Number type."""

  INTEGER = 3
  """Integer type."""

  BOOLEAN = 4
  """Boolean type."""

  ARRAY = 5
  """Array type."""

  OBJECT = 6
  """Object type."""

  NULL = 7
  """Null type."""


class Modality(betterproto.Enum):
  """Content Part modality"""

  UNSPECIFIED = 0
  """Unspecified modality."""

  TEXT = 1
  """Plain text."""

  IMAGE = 2
  """Image."""

  VIDEO = 3
  """Video."""

  AUDIO = 4
  """Audio."""

  DOCUMENT = 5
  """Document, e.g. PDF."""


class ExecutableCodeLanguage(betterproto.Enum):
  """Supported programming languages for the generated code."""

  LANGUAGE_UNSPECIFIED = 0
  """Unspecified language. This value should not be used."""

  PYTHON = 1
  """Python >= 3.10, with numpy and simpy available."""


class CodeExecutionResultOutcome(betterproto.Enum):
  """Enumeration of possible outcomes of the code execution."""

  OUTCOME_UNSPECIFIED = 0
  """Unspecified status. This value should not be used."""

  OUTCOME_OK = 1
  """Code execution completed successfully."""

  OUTCOME_FAILED = 2
  """
    Code execution finished but with a failure. `stderr` should contain the
     reason.
    """

  OUTCOME_DEADLINE_EXCEEDED = 3
  """
    Code execution ran for too long, and was cancelled. There may or may not
     be a partial output present.
    """


class ToolComputerUseEnvironment(betterproto.Enum):
  """Represents the environment being operated, such as a web browser."""

  ENVIRONMENT_UNSPECIFIED = 0
  """Defaults to browser."""

  ENVIRONMENT_BROWSER = 1
  """Operates in a web browser."""


class DynamicRetrievalConfigMode(betterproto.Enum):
  """The mode of the predictor to be used in dynamic retrieval."""

  MODE_UNSPECIFIED = 0
  """Always trigger retrieval."""

  MODE_DYNAMIC = 1
  """Run retrieval only when system decides it is necessary."""


class FunctionCallingConfigMode(betterproto.Enum):
  """
  Defines the execution behavior for function calling by defining the
   execution mode.
  """

  MODE_UNSPECIFIED = 0
  """Unspecified function calling mode. This value should not be used."""

  AUTO = 1
  """
    Default model behavior, model decides to predict either a function call
     or a natural language response.
    """

  ANY = 2
  """
    Model is constrained to always predicting a function call only.
     If "allowed_function_names" are set, the predicted function call will be
     limited to any one of "allowed_function_names", else the predicted
     function call will be any one of the provided "function_declarations".
    """

  NONE = 3
  """
    Model will not predict any function call. Model behavior is same as when
     not passing any function declarations.
    """

  VALIDATED = 4
  """
    Model decides to predict either a function call
     or a natural language response, but will validate function calls with
     constrained decoding.
     If "allowed_function_names" are set, the predicted function call will be
     limited to any one of "allowed_function_names", else the predicted
     function call will be any one of the provided "function_declarations".
    """


class FunctionDeclarationBehavior(betterproto.Enum):
  """Defines the function behavior. Defaults to `BLOCKING`."""

  UNSPECIFIED = 0
  """This value is unused."""

  BLOCKING = 1
  """
    If set, the system will wait to receive the function response before
     continuing the conversation.
    """

  NON_BLOCKING = 2
  """
    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.
    """


class FunctionResponseScheduling(betterproto.Enum):
  """Specifies how the response should be scheduled in the conversation."""

  SCHEDULING_UNSPECIFIED = 0
  """This value is unused."""

  SILENT = 1
  """
    Only add the result to the conversation context, do not interrupt or
     trigger generation.
    """

  WHEN_IDLE = 2
  """
    Add the result to the conversation context, and prompt to generate output
     without interrupting ongoing generation.
    """

  INTERRUPT = 3
  """
    Add the result to the conversation context, interrupt ongoing generation
     and prompt to generate output.
    """


class ConditionOperator(betterproto.Enum):
  """Defines the valid operators that can be applied to a key-value pair."""

  OPERATOR_UNSPECIFIED = 0
  """The default value. This value is unused."""

  LESS = 1
  """Supported by numeric."""

  LESS_EQUAL = 2
  """Supported by numeric."""

  EQUAL = 3
  """Supported by numeric & string."""

  GREATER_EQUAL = 4
  """Supported by numeric."""

  GREATER = 5
  """Supported by numeric."""

  NOT_EQUAL = 6
  """Supported by numeric & string."""

  INCLUDES = 7
  """
    Supported by string only when `CustomMetadata` value type for the given
     key has a `string_list_value`.
    """

  EXCLUDES = 8
  """
    Supported by string only when `CustomMetadata` value type for the given
     key has a `string_list_value`.
    """


class ChunkState(betterproto.Enum):
  """States for the lifecycle of a `Chunk`."""

  STATE_UNSPECIFIED = 0
  """The default value. This value is used if the state is omitted."""

  STATE_PENDING_PROCESSING = 1
  """`Chunk` is being processed (embedding and vector storage)."""

  STATE_ACTIVE = 2
  """`Chunk` is processed and available for querying."""

  STATE_FAILED = 10
  """`Chunk` failed processing."""


class HarmCategory(betterproto.Enum):
  """
  The category of a rating.

   These categories cover various kinds of harms that developers
   may wish to adjust.
  """

  UNSPECIFIED = 0
  """Category is unspecified."""

  DEROGATORY = 1
  """
    **PaLM** - Negative or harmful comments targeting identity and/or protected
     attribute.
    """

  TOXICITY = 2
  """**PaLM** - Content that is rude, disrespectful, or profane."""

  VIOLENCE = 3
  """
    **PaLM** - Describes scenarios depicting violence against an individual or
     group, or general descriptions of gore.
    """

  SEXUAL = 4
  """**PaLM** - Contains references to sexual acts or other lewd content."""

  MEDICAL = 5
  """**PaLM** - Promotes unchecked medical advice."""

  DANGEROUS = 6
  """
    **PaLM** - Dangerous content that promotes, facilitates, or encourages
     harmful acts.
    """

  HARASSMENT = 7
  """**Gemini** - Harassment content."""

  HATE_SPEECH = 8
  """**Gemini** - Hate speech and content."""

  SEXUALLY_EXPLICIT = 9
  """**Gemini** - Sexually explicit content."""

  DANGEROUS_CONTENT = 10
  """**Gemini** - Dangerous content."""

  CIVIC_INTEGRITY = 11
  """
    **Gemini** - Content that may be used to harm civic integrity.
     DEPRECATED: use enable_enhanced_civic_answers instead.
    """


class ContentFilterBlockedReason(betterproto.Enum):
  """A list of reasons why content may have been blocked."""

  BLOCKED_REASON_UNSPECIFIED = 0
  """A blocked reason was not specified."""

  SAFETY = 1
  """Content was blocked by safety settings."""

  OTHER = 2
  """Content was blocked, but the reason is uncategorized."""


class SafetyRatingHarmProbability(betterproto.Enum):
  """
  The probability that a piece of content is harmful.

   The classification system gives the probability of the content being
   unsafe. This does not indicate the severity of harm for a piece of content.
  """

  HARM_PROBABILITY_UNSPECIFIED = 0
  """Probability is unspecified."""

  NEGLIGIBLE = 1
  """Content has a negligible chance of being unsafe."""

  LOW = 2
  """Content has a low chance of being unsafe."""

  MEDIUM = 3
  """Content has a medium chance of being unsafe."""

  HIGH = 4
  """Content has a high chance of being unsafe."""


class SafetySettingHarmBlockThreshold(betterproto.Enum):
  """Block at and beyond a specified harm probability."""

  HARM_BLOCK_THRESHOLD_UNSPECIFIED = 0
  """Threshold is unspecified."""

  BLOCK_LOW_AND_ABOVE = 1
  """Content with NEGLIGIBLE will be allowed."""

  BLOCK_MEDIUM_AND_ABOVE = 2
  """Content with NEGLIGIBLE and LOW will be allowed."""

  BLOCK_ONLY_HIGH = 3
  """Content with NEGLIGIBLE, LOW, and MEDIUM will be allowed."""

  BLOCK_NONE = 4
  """All content will be allowed."""

  OFF = 5
  """Turn off the safety filter."""


class TaskType(betterproto.Enum):
  """Type of task for which the embedding will be used."""

  UNSPECIFIED = 0
  """Unset value, which will default to one of the other enum values."""

  RETRIEVAL_QUERY = 1
  """Specifies the given text is a query in a search/retrieval setting."""

  RETRIEVAL_DOCUMENT = 2
  """
    Specifies the given text is a document from the corpus being searched.
    """

  SEMANTIC_SIMILARITY = 3
  """Specifies the given text will be used for STS."""

  CLASSIFICATION = 4
  """Specifies that the given text will be classified."""

  CLUSTERING = 5
  """Specifies that the embeddings will be used for clustering."""

  QUESTION_ANSWERING = 6
  """Specifies that the given text will be used for question answering."""

  FACT_VERIFICATION = 7
  """Specifies that the given text will be used for fact verification."""

  CODE_RETRIEVAL_QUERY = 8
  """Specifies that the given text will be used for code retrieval."""


class GenerationConfigModality(betterproto.Enum):
  """Supported modalities of the response."""

  MODALITY_UNSPECIFIED = 0
  """Default value."""

  TEXT = 1
  """Indicates the model should return text."""

  IMAGE = 2
  """Indicates the model should return images."""

  AUDIO = 3
  """Indicates the model should return audio."""


class GenerationConfigMediaResolution(betterproto.Enum):
  """Media resolution for the input media."""

  MEDIA_RESOLUTION_UNSPECIFIED = 0
  """Media resolution has not been set."""

  MEDIA_RESOLUTION_LOW = 1
  """Media resolution set to low (64 tokens)."""

  MEDIA_RESOLUTION_MEDIUM = 2
  """Media resolution set to medium (256 tokens)."""

  MEDIA_RESOLUTION_HIGH = 3
  """Media resolution set to high (zoomed reframing with 256 tokens)."""


class GenerateContentResponsePromptFeedbackBlockReason(betterproto.Enum):
  """Specifies the reason why the prompt was blocked."""

  BLOCK_REASON_UNSPECIFIED = 0
  """Default value. This value is unused."""

  SAFETY = 1
  """
    Prompt was blocked due to safety reasons. Inspect `safety_ratings`
     to understand which safety category blocked it.
    """

  OTHER = 2
  """Prompt was blocked due to unknown reasons."""

  BLOCKLIST = 3
  """
    Prompt was blocked due to the terms which are included from the
     terminology blocklist.
    """

  PROHIBITED_CONTENT = 4
  """Prompt was blocked due to prohibited content."""

  IMAGE_SAFETY = 5
  """Candidates blocked due to unsafe image generation content."""


class CandidateFinishReason(betterproto.Enum):
  """Defines the reason why the model stopped generating tokens."""

  FINISH_REASON_UNSPECIFIED = 0
  """Default value. This value is unused."""

  STOP = 1
  """Natural stop point of the model or provided stop sequence."""

  MAX_TOKENS = 2
  """
    The maximum number of tokens as specified in the request was reached.
    """

  SAFETY = 3
  """The response candidate content was flagged for safety reasons."""

  RECITATION = 4
  """The response candidate content was flagged for recitation reasons."""

  LANGUAGE = 6
  """
    The response candidate content was flagged for using an unsupported
     language.
    """

  OTHER = 5
  """Unknown reason."""

  BLOCKLIST = 7
  """
    Token generation stopped because the content contains forbidden terms.
    """

  PROHIBITED_CONTENT = 8
  """
    Token generation stopped for potentially containing prohibited content.
    """

  SPII = 9
  """
    Token generation stopped because the content potentially contains
     Sensitive Personally Identifiable Information (SPII).
    """

  MALFORMED_FUNCTION_CALL = 10
  """The function call generated by the model is invalid."""

  IMAGE_SAFETY = 11
  """
    Token generation stopped because generated images contain safety
     violations.
    """

  IMAGE_PROHIBITED_CONTENT = 14
  """
    Image generation stopped because generated images has other prohibited
     content.
    """

  IMAGE_OTHER = 15
  """Image generation stopped because of other miscellaneous issue."""

  NO_IMAGE = 16
  """The model was expected to generate an image, but none was generated."""

  IMAGE_RECITATION = 17
  """Image generation stopped due to recitation."""

  UNEXPECTED_TOOL_CALL = 12
  """
    Model generated a tool call but no tools were enabled in the request.
    """

  TOO_MANY_TOOL_CALLS = 13
  """
    Model called too many tools consecutively, thus the system exited
     execution.
    """


class UrlMetadataUrlRetrievalStatus(betterproto.Enum):
  """Status of the url retrieval."""

  URL_RETRIEVAL_STATUS_UNSPECIFIED = 0
  """Default value. This value is unused."""

  URL_RETRIEVAL_STATUS_SUCCESS = 1
  """Url retrieval is successful."""

  URL_RETRIEVAL_STATUS_ERROR = 2
  """Url retrieval is failed due to error."""

  URL_RETRIEVAL_STATUS_PAYWALL = 3
  """Url retrieval is failed because the content is behind paywall."""

  URL_RETRIEVAL_STATUS_UNSAFE = 4
  """Url retrieval is failed because the content is unsafe."""


class GenerateAnswerRequestAnswerStyle(betterproto.Enum):
  """Style for grounded answers."""

  ANSWER_STYLE_UNSPECIFIED = 0
  """Unspecified answer style."""

  ABSTRACTIVE = 1
  """Succinct but abstract style."""

  EXTRACTIVE = 2
  """Very brief and extractive style."""

  VERBOSE = 3
  """
    Verbose style including extra details. The response may be formatted as a
     sentence, paragraph, multiple paragraphs, or bullet points, etc.
    """


class GenerateAnswerResponseInputFeedbackBlockReason(betterproto.Enum):
  """Specifies what was the reason why input was blocked."""

  BLOCK_REASON_UNSPECIFIED = 0
  """Default value. This value is unused."""

  SAFETY = 1
  """
    Input was blocked due to safety reasons. Inspect
     `safety_ratings` to understand which safety category blocked it.
    """

  OTHER = 2
  """Input was blocked due to other reasons."""


class RealtimeInputConfigActivityHandling(betterproto.Enum):
  """The different ways of handling user activity."""

  ACTIVITY_HANDLING_UNSPECIFIED = 0
  """
    If unspecified, the default behavior is `START_OF_ACTIVITY_INTERRUPTS`.
    """

  START_OF_ACTIVITY_INTERRUPTS = 1
  """
    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.
    """

  NO_INTERRUPTION = 2
  """The model's response will not be interrupted."""


class RealtimeInputConfigTurnCoverage(betterproto.Enum):
  """Options about which input is included in the user's turn."""

  TURN_COVERAGE_UNSPECIFIED = 0
  """
    If unspecified, the default behavior is `TURN_INCLUDES_ONLY_ACTIVITY`.
    """

  TURN_INCLUDES_ONLY_ACTIVITY = 1
  """
    The users turn only includes activity since the last turn, excluding
     inactivity (e.g. silence on the audio stream). This is the default
     behavior.
    """

  TURN_INCLUDES_ALL_INPUT = 2
  """
    The users turn includes all realtime input since the last turn, including
     inactivity (e.g. silence on the audio stream).
    """


class RealtimeInputConfigAutomaticActivityDetectionStartSensitivity(betterproto.Enum):
  """Determines how start of speech is detected."""

  START_SENSITIVITY_UNSPECIFIED = 0
  """The default is START_SENSITIVITY_HIGH."""

  START_SENSITIVITY_HIGH = 1
  """Automatic detection will detect the start of speech more often."""

  START_SENSITIVITY_LOW = 2
  """Automatic detection will detect the start of speech less often."""


class RealtimeInputConfigAutomaticActivityDetectionEndSensitivity(betterproto.Enum):
  """Determines how end of speech is detected."""

  END_SENSITIVITY_UNSPECIFIED = 0
  """The default is END_SENSITIVITY_HIGH."""

  END_SENSITIVITY_HIGH = 1
  """Automatic detection ends speech more often."""

  END_SENSITIVITY_LOW = 2
  """Automatic detection ends speech less often."""


@dataclass(eq=False, repr=False)
class CitationMetadata(betterproto.Message):
  """A collection of source attributions for a piece of content."""

  citation_sources: List["CitationSource"] = betterproto.message_field(1)
  """Citations to sources for a specific response."""


@dataclass(eq=False, repr=False)
class CitationSource(betterproto.Message):
  """A citation to a source for a portion of a specific response."""

  start_index: Optional[int] = betterproto.int32_field(1, optional=True)
  """
    Optional. Start of segment of the response that is attributed to this
     source.
    
     Index indicates the start of the segment, measured in bytes.
    """

  end_index: Optional[int] = betterproto.int32_field(2, optional=True)
  """Optional. End of the attributed segment, exclusive."""

  uri: Optional[str] = betterproto.string_field(3, optional=True)
  """
    Optional. URI that is attributed as a source for a portion of the text.
    """

  license: Optional[str] = betterproto.string_field(4, optional=True)
  """
    Optional. License for the GitHub project that is attributed as a source for
     segment.
    
     License info is required for code citations.
    """


@dataclass(eq=False, repr=False)
class Content(betterproto.Message):
  """
  The base structured datatype containing multi-part content of a message.

   A `Content` includes a `role` field designating the producer of the `Content`
   and a `parts` field containing multi-part data that contains the content of
   the message turn.
  """

  parts: List["Part"] = betterproto.message_field(1)
  """
    Ordered `Parts` that constitute a single message. Parts may have different
     MIME types.
    """

  role: str = betterproto.string_field(2)
  """
    Optional. The producer of the content. Must be either 'user' or 'model'.
    
     Useful to set for multi-turn conversations, otherwise can be left blank
     or unset.
    """


@dataclass(eq=False, repr=False)
class Part(betterproto.Message):
  """
  A datatype containing media that is part of a multi-part `Content` message.

   A `Part` consists of data which has an associated datatype. A `Part` can only
   contain one of the accepted types in `Part.data`.

   A `Part` 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.
  """

  text: str = betterproto.string_field(2, group="data")
  """Inline text."""

  inline_data: "Blob" = betterproto.message_field(3, group="data")
  """Inline media bytes."""

  function_call: "FunctionCall" = betterproto.message_field(4, group="data")
  """
    A predicted `FunctionCall` returned from the model that contains
     a string representing the `FunctionDeclaration.name` with the
     arguments and their values.
    """

  function_response: "FunctionResponse" = betterproto.message_field(5, group="data")
  """
    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 is used as context to
     the model.
    """

  file_data: "FileData" = betterproto.message_field(6, group="data")
  """URI based data."""

  executable_code: "ExecutableCode" = betterproto.message_field(9, group="data")
  """Code generated by the model that is meant to be executed."""

  code_execution_result: "CodeExecutionResult" = betterproto.message_field(
    10, group="data"
  )
  """Result of executing the `ExecutableCode`."""

  video_metadata: "VideoMetadata" = betterproto.message_field(14, group="metadata")
  """
    Optional. Video metadata. The metadata should only be specified while the
     video data is presented in inline_data or file_data.
    """

  thought: bool = betterproto.bool_field(11)
  """Optional. Indicates if the part is thought from the model."""

  thought_signature: bytes = betterproto.bytes_field(13)
  """
    Optional. An opaque signature for the thought so it can be reused in
     subsequent requests.
    """

  part_metadata: "betterproto_lib_google_protobuf.Struct" = betterproto.message_field(8)
  """
    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.
    """


@dataclass(eq=False, repr=False)
class FunctionResponsePart(betterproto.Message):
  """
  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.
  """

  inline_data: "FunctionResponseBlob" = betterproto.message_field(1, group="data")
  """Inline media bytes."""


@dataclass(eq=False, repr=False)
class Blob(betterproto.Message):
  """
  Raw media bytes.

   Text should not be sent as raw bytes, use the 'text' field.
  """

  mime_type: str = betterproto.string_field(1)
  """
    The IANA standard MIME type of the source data.
     Examples:
       - image/png
       - image/jpeg
     If an unsupported MIME type is provided, an error will be returned. For a
     complete list of supported types, see [Supported file
     formats](https://ai.google.dev/gemini-api/docs/prompting_with_media#supported_file_formats).
    """

  data: bytes = betterproto.bytes_field(2)
  """Raw bytes for media formats."""


@dataclass(eq=False, repr=False)
class FunctionResponseBlob(betterproto.Message):
  """
  Raw media bytes for function response.

   Text should not be sent as raw bytes, use the 'FunctionResponse.response'
   field.
  """

  mime_type: str = betterproto.string_field(1)
  """
    The IANA standard MIME type of the source data.
     Examples:
       - image/png
       - image/jpeg
     If an unsupported MIME type is provided, an error will be returned. For a
     complete list of supported types, see [Supported file
     formats](https://ai.google.dev/gemini-api/docs/prompting_with_media#supported_file_formats).
    """

  data: bytes = betterproto.bytes_field(2)
  """Raw bytes for media formats."""


@dataclass(eq=False, repr=False)
class FileData(betterproto.Message):
  """URI based data."""

  mime_type: str = betterproto.string_field(1)
  """Optional. The IANA standard MIME type of the source data."""

  file_uri: str = betterproto.string_field(2)
  """Required. URI."""


@dataclass(eq=False, repr=False)
class VideoMetadata(betterproto.Message):
  """Metadata describes the input video content."""

  start_offset: timedelta = betterproto.message_field(1)
  """Optional. The start offset of the video."""

  end_offset: timedelta = betterproto.message_field(2)
  """Optional. The end offset of the video."""

  fps: float = betterproto.double_field(3)
  """
    Optional. The frame rate of the video sent to the model. If not specified,
     the default value will be 1.0. The fps range is (0.0, 24.0].
    """


@dataclass(eq=False, repr=False)
class ExecutableCode(betterproto.Message):
  """
  Code generated by the model that is meant to be executed, and the result
   returned to the model.

   Only generated when using the `CodeExecution` tool, in which the code will
   be automatically executed, and a corresponding `CodeExecutionResult` will
   also be generated.
  """

  language: "ExecutableCodeLanguage" = betterproto.enum_field(1)
  """Required. Programming language of the `code`."""

  code: str = betterproto.string_field(2)
  """Required. The code to be executed."""


@dataclass(eq=False, repr=False)
class CodeExecutionResult(betterproto.Message):
  """
  Result of executing the `ExecutableCode`.

   Only generated when using the `CodeExecution`, and always follows a `part`
   containing the `ExecutableCode`.
  """

  outcome: "CodeExecutionResultOutcome" = betterproto.enum_field(1)
  """Required. Outcome of the code execution."""

  output: str = betterproto.string_field(2)
  """
    Optional. Contains stdout when code execution is successful, stderr or
     other description otherwise.
    """


@dataclass(eq=False, repr=False)
class Tool(betterproto.Message):
  """
  Tool details that the model may use to generate 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.

   Next ID: 12
  """

  function_declarations: List["FunctionDeclaration"] = betterproto.message_field(1)
  """
    Optional. A list of `FunctionDeclarations` available to the model that can
     be used for function calling.
    
     The model or system does not execute the function. Instead the defined
     function may be returned as a
     [FunctionCall][google.ai.generativelanguage.v1beta.Part.function_call] with
     arguments to the client side for execution. The model may decide to call a
     subset of these functions by populating
     [FunctionCall][google.ai.generativelanguage.v1beta.Part.function_call] in
     the response. The next conversation turn may contain a
     [FunctionResponse][google.ai.generativelanguage.v1beta.Part.function_response]
     with the [Content.role][google.ai.generativelanguage.v1beta.Content.role]
     "function" generation context for the next model turn.
    """

  google_search_retrieval: "GoogleSearchRetrieval" = betterproto.message_field(2)
  """Optional. Retrieval tool that is powered by Google search."""

  code_execution: "CodeExecution" = betterproto.message_field(3)
  """Optional. Enables the model to execute code as part of generation."""

  google_search: "ToolGoogleSearch" = betterproto.message_field(4)
  """
    Optional. GoogleSearch tool type.
     Tool to support Google Search in Model. Powered by Google.
    """

  computer_use: "ToolComputerUse" = betterproto.message_field(6)
  """
    Optional. Tool to support the model interacting directly with the computer.
     If enabled, it automatically populates computer-use specific Function
     Declarations.
    """

  url_context: "UrlContext" = betterproto.message_field(8)
  """Optional. Tool to support URL context retrieval."""

  file_search: "FileSearch" = betterproto.message_field(9)
  """
    Optional. FileSearch tool type.
     Tool to retrieve knowledge from Semantic Retrieval corpora.
    """

  google_maps: "GoogleMaps" = betterproto.message_field(11)
  """
    Optional. Tool that allows grounding the model's response with geospatial
     context related to the user's query.
    """


@dataclass(eq=False, repr=False)
class ToolGoogleSearch(betterproto.Message):
  """
  GoogleSearch tool type.
   Tool to support Google Search in Model. Powered by Google.
  """

  time_range_filter: "___type__.Interval" = betterproto.message_field(2)
  """
    Optional. Filter search results to a specific time range.
     If customers set a start time, they must set an end time (and vice
     versa).
    """


@dataclass(eq=False, repr=False)
class ToolComputerUse(betterproto.Message):
  """Computer Use tool type."""

  environment: "ToolComputerUseEnvironment" = betterproto.enum_field(3)
  """Required. The environment being operated."""

  excluded_predefined_functions: List[str] = betterproto.string_field(5)
  """
    Optional. By default, predefined functions 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.
    """


@dataclass(eq=False, repr=False)
class GoogleMaps(betterproto.Message):
  """
  The GoogleMaps Tool that provides geospatial context for the user's query.
  """

  enable_widget: bool = betterproto.bool_field(1)
  """
    Optional. Whether to return a widget context token in the GroundingMetadata
     of the response. Developers can use the widget context token to render a
     Google Maps widget with geospatial context related to the places that the
     model references in the response.
    """


@dataclass(eq=False, repr=False)
class UrlContext(betterproto.Message):
  """Tool to support URL context retrieval."""

  pass


@dataclass(eq=False, repr=False)
class FileSearch(betterproto.Message):
  """
  The FileSearch tool that retrieves knowledge from Semantic Retrieval corpora.
   Files are imported to Semantic Retrieval corpora using the ImportFile API.
  """

  retrieval_resources: List["FileSearchRetrievalResource"] = betterproto.message_field(
    1
  )
  """
    Required. Semantic retrieval resources to retrieve from.
     Currently only supports one corpus. In the future we may open up multiple
     corpora support.
    """

  retrieval_config: "FileSearchRetrievalConfig" = betterproto.message_field(2)
  """Optional. The configuration for the retrieval."""


@dataclass(eq=False, repr=False)
class FileSearchRetrievalResource(betterproto.Message):
  """The semantic retrieval resource to retrieve from."""

  rag_store_name: str = betterproto.string_field(1)
  """
    Required. The name of the semantic retrieval resource to retrieve from.
     Example: `ragStores/my-rag-store-123`
    """


@dataclass(eq=False, repr=False)
class FileSearchRetrievalConfig(betterproto.Message):
  """Semantic retrieval configuration."""

  top_k: Optional[int] = betterproto.int32_field(1, optional=True)
  """Optional. The number of semantic retrieval chunks to retrieve."""

  metadata_filter: str = betterproto.string_field(3)
  """
    Optional. Metadata filter to apply to the semantic retrieval documents
     and chunks.
    """


@dataclass(eq=False, repr=False)
class GoogleSearchRetrieval(betterproto.Message):
  """Tool to retrieve public web data for grounding, powered by Google."""

  dynamic_retrieval_config: "DynamicRetrievalConfig" = betterproto.message_field(1)
  """Specifies the dynamic retrieval configuration for the given source."""


@dataclass(eq=False, repr=False)
class DynamicRetrievalConfig(betterproto.Message):
  """Describes the options to customize dynamic retrieval."""

  mode: "DynamicRetrievalConfigMode" = betterproto.enum_field(1)
  """The mode of the predictor to be used in dynamic retrieval."""

  dynamic_threshold: Optional[float] = betterproto.float_field(2, optional=True)
  """
    The threshold to be used in dynamic retrieval.
     If not set, a system default value is used.
    """


@dataclass(eq=False, repr=False)
class CodeExecution(betterproto.Message):
  """
  Tool that executes code generated by the model, and automatically returns
   the result to the model.

   See also `ExecutableCode` and `CodeExecutionResult` which are only generated
   when using this tool.
  """

  pass


@dataclass(eq=False, repr=False)
class ToolConfig(betterproto.Message):
  """
  The Tool configuration containing parameters for specifying `Tool` use
   in the request.
  """

  function_calling_config: "FunctionCallingConfig" = betterproto.message_field(1)
  """Optional. Function calling config."""

  retrieval_config: "RetrievalConfig" = betterproto.message_field(2)
  """Optional. Retrieval config."""


@dataclass(eq=False, repr=False)
class RetrievalConfig(betterproto.Message):
  """Retrieval config."""

  lat_lng: "___type__.LatLng" = betterproto.message_field(1)
  """Optional. The location of the user."""

  language_code: str = betterproto.string_field(2)
  """
    Optional. The language code of the user.
     Language code for content. Use language tags defined by
     [BCP47](https://www.rfc-editor.org/rfc/bcp/bcp47.txt).
    """


@dataclass(eq=False, repr=False)
class FunctionCallingConfig(betterproto.Message):
  """Configuration for specifying function calling behavior."""

  mode: "FunctionCallingConfigMode" = betterproto.enum_field(1)
  """
    Optional. Specifies the mode in which function calling should execute. If
     unspecified, the default value will be set to AUTO.
    """

  allowed_function_names: List[str] = betterproto.string_field(2)
  """
    Optional. A set of function names that, when provided, limits the functions
     the model will call.
    
     This should only be set when the Mode is ANY or VALIDATED. Function names
     should match [FunctionDeclaration.name]. When set, model will
     predict a function call from only allowed function names.
    """


@dataclass(eq=False, repr=False)
class FunctionDeclaration(betterproto.Message):
  """
  Structured representation of a function declaration as defined by the
   [OpenAPI 3.03 specification](https://spec.openapis.org/oas/v3.0.3). Included
   in this declaration are the function name and parameters. 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.
  """

  name: str = betterproto.string_field(1)
  """
    Required. The name of the function.
     Must be a-z, A-Z, 0-9, or contain underscores, colons, dots, and dashes,
     with a maximum length of 64.
    """

  description: str = betterproto.string_field(2)
  """Required. A brief description of the function."""

  parameters: Optional["Schema"] = betterproto.message_field(3, optional=True)
  """
    Optional. Describes the parameters to this function. 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.
    """

  parameters_json_schema: Optional["betterproto_lib_google_protobuf.Value"] = (
    betterproto.message_field(6, optional=True)
  )
  """
    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`.
    """

  response: Optional["Schema"] = betterproto.message_field(4, optional=True)
  """
    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_json_schema: Optional["betterproto_lib_google_protobuf.Value"] = (
    betterproto.message_field(7, optional=True)
  )
  """
    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`.
    """

  behavior: "FunctionDeclarationBehavior" = betterproto.enum_field(5)
  """
    Optional. Specifies the function Behavior.
     Currently only supported by the BidiGenerateContent method.
    """


@dataclass(eq=False, repr=False)
class FunctionCall(betterproto.Message):
  """
  A predicted `FunctionCall` returned from the model that contains
   a string representing the `FunctionDeclaration.name` with the
   arguments and their values.
  """

  id: str = betterproto.string_field(3)
  """
    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`.
    """

  name: str = betterproto.string_field(1)
  """
    Required. The name of the function to call.
     Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum
     length of 64.
    """

  args: Optional["betterproto_lib_google_protobuf.Struct"] = betterproto.message_field(
    2, optional=True
  )
  """Optional. The function parameters and values in JSON object format."""


@dataclass(eq=False, repr=False)
class FunctionResponse(betterproto.Message):
  """
  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.
  """

  id: str = betterproto.string_field(3)
  """
    Optional. The id of the function call this response is for. Populated by
     the client to match the corresponding function call `id`.
    """

  name: str = betterproto.string_field(1)
  """
    Required. The name of the function to call.
     Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum
     length of 64.
    """

  response: "betterproto_lib_google_protobuf.Struct" = betterproto.message_field(2)
  """
    Required. The function response in JSON object format.
     Callers can use any keys of their choice that fit the function's syntax
     to return the function output, e.g. "output", "result", etc.
     In particular, if the function call failed to execute, the response can
     have an "error" key to return error details to the model.
    """

  parts: List["FunctionResponsePart"] = betterproto.message_field(8)
  """
    Optional. Ordered `Parts` that constitute a function response. Parts may
     have different IANA MIME types.
    """

  will_continue: bool = betterproto.bool_field(4)
  """
    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`.
    """

  scheduling: Optional["FunctionResponseScheduling"] = betterproto.enum_field(
    5, optional=True
  )
  """
    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.
    """


@dataclass(eq=False, repr=False)
class Schema(betterproto.Message):
  """
  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).
  """

  type: "Type" = betterproto.enum_field(1)
  """Required. Data type."""

  format: str = betterproto.string_field(2)
  """
    Optional. The format of the data. Any value is allowed, but most do not
     trigger any special functionality.
    """

  title: str = betterproto.string_field(24)
  """Optional. The title of the schema."""

  description: str = betterproto.string_field(3)
  """
    Optional. A brief description of the parameter. This could contain examples
     of use. Parameter description may be formatted as Markdown.
    """

  nullable: bool = betterproto.bool_field(4)
  """Optional. Indicates if the value may be null."""

  enum: List[str] = betterproto.string_field(5)
  """
    Optional. Possible values of the element of Type.STRING with enum format.
     For example we can define an Enum Direction as :
     {type:STRING, format:enum, enum:["EAST", NORTH", "SOUTH", "WEST"]}
    """

  items: Optional["Schema"] = betterproto.message_field(6, optional=True)
  """Optional. Schema of the elements of Type.ARRAY."""

  max_items: int = betterproto.int64_field(21)
  """Optional. Maximum number of the elements for Type.ARRAY."""

  min_items: int = betterproto.int64_field(22)
  """Optional. Minimum number of the elements for Type.ARRAY."""

  properties: Dict[str, "Schema"] = betterproto.map_field(
    7, betterproto.TYPE_STRING, betterproto.TYPE_MESSAGE
  )
  """Optional. Properties of Type.OBJECT."""

  required: List[str] = betterproto.string_field(8)
  """Optional. Required properties of Type.OBJECT."""

  min_properties: int = betterproto.int64_field(9)
  """Optional. Minimum number of the properties for Type.OBJECT."""

  max_properties: int = betterproto.int64_field(10)
  """Optional. Maximum number of the properties for Type.OBJECT."""

  minimum: Optional[float] = betterproto.double_field(11, optional=True)
  """
    Optional. SCHEMA FIELDS FOR TYPE INTEGER and NUMBER
     Minimum value of the Type.INTEGER and Type.NUMBER
    """

  maximum: Optional[float] = betterproto.double_field(12, optional=True)
  """Optional. Maximum value of the Type.INTEGER and Type.NUMBER"""

  min_length: int = betterproto.int64_field(13)
  """
    Optional. SCHEMA FIELDS FOR TYPE STRING
     Minimum length of the Type.STRING
    """

  max_length: int = betterproto.int64_field(14)
  """Optional. Maximum length of the Type.STRING"""

  pattern: str = betterproto.string_field(15)
  """
    Optional. Pattern of the Type.STRING to restrict a string to a regular
     expression.
    """

  example: "betterproto_lib_google_protobuf.Value" = betterproto.message_field(16)
  """
    Optional. Example of the object. Will only populated when the object is the
     root.
    """

  any_of: List["Schema"] = betterproto.message_field(18)
  """
    Optional. The value should be validated against any (one or more) of the
     subschemas in the list.
    """

  property_ordering: List[str] = betterproto.string_field(23)
  """
    Optional. The order of the properties.
     Not a standard field in open api spec. Used to determine the order of the
     properties in the response.
    """

  default: "betterproto_lib_google_protobuf.Value" = betterproto.message_field(25)
  """
    Optional. Default value of the field. Per JSON Schema, this field is
     intended for documentation generators and doesn't affect validation. Thus
     it's included here and ignored so that developers who send schemas with a
     `default` field don't get unknown-field errors.
    """


@dataclass(eq=False, repr=False)
class GroundingPassage(betterproto.Message):
  """Passage included inline with a grounding configuration."""

  id: str = betterproto.string_field(1)
  """
    Identifier for the passage for attributing this passage in grounded
     answers.
    """

  content: "Content" = betterproto.message_field(2)
  """Content of the passage."""


@dataclass(eq=False, repr=False)
class GroundingPassages(betterproto.Message):
  """A repeated list of passages."""

  passages: List["GroundingPassage"] = betterproto.message_field(1)
  """List of passages."""


@dataclass(eq=False, repr=False)
class ModalityTokenCount(betterproto.Message):
  """Represents token counting info for a single modality."""

  modality: "Modality" = betterproto.enum_field(1)
  """The modality associated with this token count."""

  token_count: int = betterproto.int32_field(2)
  """Number of tokens."""


@dataclass(eq=False, repr=False)
class Corpus(betterproto.Message):
  """
  A `Corpus` is a collection of `Document`s.
   A project can create up to 5 corpora.
  """

  name: str = betterproto.string_field(1)
  """
    Immutable. Identifier. The `Corpus` resource name. The ID (name excluding
     the "corpora/" 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: `corpora/my-awesome-corpora-123a456b789c`
    """

  display_name: str = betterproto.string_field(2)
  """
    Optional. The human-readable display name for the `Corpus`. The display
     name must be no more than 512 characters in length, including spaces.
     Example: "Docs on Semantic Retriever"
    """

  create_time: datetime = betterproto.message_field(3)
  """Output only. The Timestamp of when the `Corpus` was created."""

  update_time: datetime = betterproto.message_field(4)
  """Output only. The Timestamp of when the `Corpus` was last updated."""


@dataclass(eq=False, repr=False)
class Document(betterproto.Message):
  """
  A `Document` is a collection of `Chunk`s.
   A `Corpus` can have a maximum of 10,000 `Document`s.
  """

  name: str = betterproto.string_field(1)
  """
    Immutable. Identifier. The `Document` resource name. The ID (name excluding
     the "corpora/*/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: `corpora/{corpus_id}/documents/my-awesome-doc-123a456b789c`
    """

  display_name: str = betterproto.string_field(2)
  """
    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"
    """

  custom_metadata: List["CustomMetadata"] = betterproto.message_field(3)
  """
    Optional. User provided custom metadata stored as key-value pairs used for
     querying. A `Document` can have a maximum of 20 `CustomMetadata`.
    """

  update_time: datetime = betterproto.message_field(4)
  """Output only. The Timestamp of when the `Document` was last updated."""

  create_time: datetime = betterproto.message_field(5)
  """Output only. The Timestamp of when the `Document` was created."""


@dataclass(eq=False, repr=False)
class StringList(betterproto.Message):
  """User provided string values assigned to a single metadata key."""

  values: List[str] = betterproto.string_field(1)
  """The string values of the metadata to store."""


@dataclass(eq=False, repr=False)
class CustomMetadata(betterproto.Message):
  """User provided metadata stored as key-value pairs."""

  string_value: str = betterproto.string_field(2, group="value")
  """The string value of the metadata to store."""

  string_list_value: "StringList" = betterproto.message_field(6, group="value")
  """The StringList value of the metadata to store."""

  numeric_value: float = betterproto.float_field(7, group="value")
  """The numeric value of the metadata to store."""

  key: str = betterproto.string_field(1)
  """Required. The key of the metadata to store."""


@dataclass(eq=False, repr=False)
class MetadataFilter(betterproto.Message):
  """
  User provided filter to limit retrieval based on `Chunk` or `Document` level
   metadata values.
   Example (genre = drama OR genre = action):
     key = "document.custom_metadata.genre"
     conditions = [{string_value = "drama", operation = EQUAL},
                   {string_value = "action", operation = EQUAL}]
  """

  key: str = betterproto.string_field(1)
  """Required. The key of the metadata to filter on."""

  conditions: List["Condition"] = betterproto.message_field(2)
  """
    Required. The `Condition`s for the given key that will trigger this filter.
     Multiple `Condition`s are joined by logical ORs.
    """


@dataclass(eq=False, repr=False)
class Condition(betterproto.Message):
  """Filter condition applicable to a single key."""

  string_value: str = betterproto.string_field(1, group="value")
  """The string value to filter the metadata on."""

  numeric_value: float = betterproto.float_field(6, group="value")
  """The numeric value to filter the metadata on."""

  operation: "ConditionOperator" = betterproto.enum_field(5)
  """
    Required. Operator applied to the given key-value pair to trigger the
     condition.
    """


@dataclass(eq=False, repr=False)
class Chunk(betterproto.Message):
  """
  A `Chunk` is a subpart of a `Document` that is treated as an independent unit
   for the purposes of vector representation and storage.
   A `Corpus` can have a maximum of 1 million `Chunk`s.
  """

  name: str = betterproto.string_field(1)
  """
    Immutable. Identifier. The `Chunk` resource name. The ID (name excluding
     the "corpora/*/documents/*/chunks/" 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 random 12-character unique
     ID will be generated.
     Example: `corpora/{corpus_id}/documents/{document_id}/chunks/123a456b789c`
    """

  data: "ChunkData" = betterproto.message_field(2)
  """
    Required. The content for the `Chunk`, such as the text string.
     The maximum number of tokens per chunk is 2043.
    """

  custom_metadata: List["CustomMetadata"] = betterproto.message_field(3)
  """
    Optional. User provided custom metadata stored as key-value pairs.
     The maximum number of `CustomMetadata` per chunk is 20.
    """

  create_time: datetime = betterproto.message_field(4)
  """Output only. The Timestamp of when the `Chunk` was created."""

  update_time: datetime = betterproto.message_field(5)
  """Output only. The Timestamp of when the `Chunk` was last updated."""

  state: "ChunkState" = betterproto.enum_field(6)
  """Output only. Current state of the `Chunk`."""


@dataclass(eq=False, repr=False)
class ChunkData(betterproto.Message):
  """Extracted data that represents the `Chunk` content."""

  string_value: str = betterproto.string_field(1, group="data")
  """
    The `Chunk` content as a string.
     The maximum number of tokens per chunk is 2043.
    """


@dataclass(eq=False, repr=False)
class ContentFilter(betterproto.Message):
  """
  Content filtering metadata associated with processing a single request.

   ContentFilter contains a reason and an optional supporting string. The reason
   may be unspecified.
  """

  reason: "ContentFilterBlockedReason" = betterproto.enum_field(1)
  """The reason content was blocked during request processing."""

  message: Optional[str] = betterproto.string_field(2, optional=True)
  """A string that describes the filtering behavior in more detail."""


@dataclass(eq=False, repr=False)
class SafetyFeedback(betterproto.Message):
  """
  Safety feedback for an entire request.

   This field is populated if content in the input and/or response is blocked
   due to safety settings. SafetyFeedback may not exist for every HarmCategory.
   Each SafetyFeedback will return the safety settings used by the request as
   well as the lowest HarmProbability that should be allowed in order to return
   a result.
  """

  rating: "SafetyRating" = betterproto.message_field(1)
  """Safety rating evaluated from content."""

  setting: "SafetySetting" = betterproto.message_field(2)
  """Safety settings applied to the request."""


@dataclass(eq=False, repr=False)
class SafetyRating(betterproto.Message):
  """
  Safety rating for a piece of content.

   The safety rating contains the category of harm and the
   harm probability level in that category for a piece of content.
   Content is classified for safety across a number of
   harm categories and the probability of the harm classification is included
   here.
  """

  category: "HarmCategory" = betterproto.enum_field(3)
  """Required. The category for this rating."""

  probability: "SafetyRatingHarmProbability" = betterproto.enum_field(4)
  """Required. The probability of harm for this content."""

  blocked: bool = betterproto.bool_field(5)
  """Was this content blocked because of this rating?"""


@dataclass(eq=False, repr=False)
class SafetySetting(betterproto.Message):
  """
  Safety setting, affecting the safety-blocking behavior.

   Passing a safety setting for a category changes the allowed probability that
   content is blocked.
  """

  category: "HarmCategory" = betterproto.enum_field(3)
  """Required. The category for this setting."""

  threshold: "SafetySettingHarmBlockThreshold" = betterproto.enum_field(4)
  """
    Required. Controls the probability threshold at which harm is blocked.
    """


@dataclass(eq=False, repr=False)
class GenerateContentRequest(betterproto.Message):
  """Request to generate a completion from the model."""

  model: str = betterproto.string_field(1)
  """
    Required. The name of the `Model` to use for generating the completion.
    
     Format: `models/{model}`.
    """

  system_instruction: Optional["Content"] = betterproto.message_field(8, optional=True)
  """
    Optional. Developer set [system
     instruction(s)](https://ai.google.dev/gemini-api/docs/system-instructions).
     Currently, text only.
    """

  contents: List["Content"] = betterproto.message_field(2)
  """
    Required. The content of the current conversation with the model.
    
     For single-turn queries, this is a single instance. For multi-turn queries
     like [chat](https://ai.google.dev/gemini-api/docs/text-generation#chat),
     this is a repeated field that contains the conversation history and the
     latest request.
    """

  tools: List["Tool"] = betterproto.message_field(5)
  """
    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`. Supported `Tool`s are `Function` and
     `code_execution`. Refer to the [Function
     calling](https://ai.google.dev/gemini-api/docs/function-calling) and the
     [Code execution](https://ai.google.dev/gemini-api/docs/code-execution)
     guides to learn more.
    """

  tool_config: "ToolConfig" = betterproto.message_field(7)
  """
    Optional. Tool configuration for any `Tool` specified in the request. Refer
     to the [Function calling
     guide](https://ai.google.dev/gemini-api/docs/function-calling#function_calling_mode)
     for a usage example.
    """

  safety_settings: List["SafetySetting"] = betterproto.message_field(3)
  """
    Optional. A list of unique `SafetySetting` instances for blocking unsafe
     content.
    
     This will be enforced on the `GenerateContentRequest.contents` and
     `GenerateContentResponse.candidates`. There should not be more than one
     setting for each `SafetyCategory` type. The API will block any contents and
     responses that fail to meet the thresholds set by these settings. This list
     overrides the default settings for each `SafetyCategory` specified in the
     safety_settings. If there is no `SafetySetting` for a given
     `SafetyCategory` provided in the list, the API will use the default safety
     setting for that category. Harm categories HARM_CATEGORY_HATE_SPEECH,
     HARM_CATEGORY_SEXUALLY_EXPLICIT, HARM_CATEGORY_DANGEROUS_CONTENT,
     HARM_CATEGORY_HARASSMENT, HARM_CATEGORY_CIVIC_INTEGRITY are supported.
     Refer to the [guide](https://ai.google.dev/gemini-api/docs/safety-settings)
     for detailed information on available safety settings. Also refer to the
     [Safety guidance](https://ai.google.dev/gemini-api/docs/safety-guidance) to
     learn how to incorporate safety considerations in your AI applications.
    """

  generation_config: Optional["GenerationConfig"] = betterproto.message_field(
    4, optional=True
  )
  """Optional. Configuration options for model generation and outputs."""

  cached_content: Optional[str] = betterproto.string_field(9, optional=True)
  """
    Optional. The name of the content
     [cached](https://ai.google.dev/gemini-api/docs/caching) to use as context
     to serve the prediction. Format: `cachedContents/{cachedContent}`
    """


@dataclass(eq=False, repr=False)
class PrebuiltVoiceConfig(betterproto.Message):
  """The configuration for the prebuilt speaker to use."""

  voice_name: Optional[str] = betterproto.string_field(1, optional=True)
  """The name of the preset voice to use."""


@dataclass(eq=False, repr=False)
class VoiceConfig(betterproto.Message):
  """The configuration for the voice to use."""

  prebuilt_voice_config: "PrebuiltVoiceConfig" = betterproto.message_field(
    1, group="voice_config"
  )
  """The configuration for the prebuilt voice to use."""


@dataclass(eq=False, repr=False)
class SpeakerVoiceConfig(betterproto.Message):
  """The configuration for a single speaker in a multi speaker setup."""

  speaker: str = betterproto.string_field(1)
  """
    Required. The name of the speaker to use. Should be the same as in the
     prompt.
    """

  voice_config: "VoiceConfig" = betterproto.message_field(2)
  """Required. The configuration for the voice to use."""


@dataclass(eq=False, repr=False)
class MultiSpeakerVoiceConfig(betterproto.Message):
  """The configuration for the multi-speaker setup."""

  speaker_voice_configs: List["SpeakerVoiceConfig"] = betterproto.message_field(2)
  """Required. All the enabled speaker voices."""


@dataclass(eq=False, repr=False)
class SpeechConfig(betterproto.Message):
  """The speech generation config."""

  voice_config: "VoiceConfig" = betterproto.message_field(1)
  """The configuration in case of single-voice output."""

  multi_speaker_voice_config: "MultiSpeakerVoiceConfig" = betterproto.message_field(3)
  """
    Optional. The configuration for the multi-speaker setup.
     It is mutually exclusive with the voice_config field.
    """

  language_code: str = betterproto.string_field(2)
  """
    Optional. Language code (in BCP 47 format, e.g. "en-US") for speech
     synthesis.
    
     Valid values are: de-DE, en-AU, en-GB, en-IN, en-US, es-US, fr-FR, hi-IN,
     pt-BR, ar-XA, es-ES, fr-CA, id-ID, it-IT, ja-JP, tr-TR, vi-VN, bn-IN,
     gu-IN, kn-IN, ml-IN, mr-IN, ta-IN, te-IN, nl-NL, ko-KR, cmn-CN, pl-PL,
     ru-RU, and th-TH.
    """


@dataclass(eq=False, repr=False)
class ThinkingConfig(betterproto.Message):
  """Config for thinking features."""

  include_thoughts: Optional[bool] = betterproto.bool_field(1, optional=True)
  """
    Indicates whether to include thoughts in the response.
     If true, thoughts are returned only when available.
    """

  thinking_budget: Optional[int] = betterproto.int32_field(2, optional=True)
  """The number of thoughts tokens that the model should generate."""


@dataclass(eq=False, repr=False)
class ImageConfig(betterproto.Message):
  """Config for image generation features."""

  aspect_ratio: Optional[str] = betterproto.string_field(1, optional=True)
  """
    Optional. The aspect ratio of the image to generate. Supported aspect
     ratios: 1:1, 2:3, 3:2, 3:4, 4:3, 9:16, 16:9, 21:9.
    
     If not specified, the model will choose a default aspect ratio based on any
     reference images provided.
    """


@dataclass(eq=False, repr=False)
class GenerationConfig(betterproto.Message):
  """
  Configuration options for model generation and outputs. Not all parameters
   are configurable for every model.
  """

  candidate_count: Optional[int] = betterproto.int32_field(1, optional=True)
  """
    Optional. Number of generated responses to return. If unset, this will
     default to 1. Please note that this doesn't work for previous generation
     models (Gemini 1.0 family)
    """

  stop_sequences: List[str] = betterproto.string_field(2)
  """
    Optional. The set of character sequences (up to 5) that will stop output
     generation. If specified, the API will stop at the first appearance of a
     `stop_sequence`. The stop sequence will not be included as part of the
     response.
    """

  max_output_tokens: Optional[int] = betterproto.int32_field(4, optional=True)
  """
    Optional. The maximum number of tokens to include in a response candidate.
    
     Note: The default value varies by model, see the `Model.output_token_limit`
     attribute of the `Model` returned from the `getModel` function.
    """

  temperature: Optional[float] = betterproto.float_field(5, optional=True)
  """
    Optional. Controls the randomness of the output.
    
     Note: The default value varies by model, see the `Model.temperature`
     attribute of the `Model` returned from the `getModel` function.
    
     Values can range from [0.0, 2.0].
    """

  top_p: Optional[float] = betterproto.float_field(6, optional=True)
  """
    Optional. The maximum cumulative probability of tokens to consider when
     sampling.
    
     The model uses combined Top-k and Top-p (nucleus) sampling.
    
     Tokens are sorted based on their assigned probabilities so that only the
     most likely tokens are considered. Top-k sampling directly limits the
     maximum number of tokens to consider, while Nucleus sampling limits the
     number of tokens based on the cumulative probability.
    
     Note: The default value varies by `Model` and is specified by
     the`Model.top_p` attribute returned from the `getModel` function. An empty
     `top_k` attribute indicates that the model doesn't apply top-k sampling
     and doesn't allow setting `top_k` on requests.
    """

  top_k: Optional[int] = betterproto.int32_field(7, optional=True)
  """
    Optional. The maximum number of tokens to consider when sampling.
    
     Gemini models use Top-p (nucleus) sampling or a combination of Top-k and
     nucleus sampling. Top-k sampling considers the set of `top_k` most probable
     tokens. Models running with nucleus sampling don't allow top_k setting.
    
     Note: The default value varies by `Model` and is specified by
     the`Model.top_p` attribute returned from the `getModel` function. An empty
     `top_k` attribute indicates that the model doesn't apply top-k sampling
     and doesn't allow setting `top_k` on requests.
    """

  seed: Optional[int] = betterproto.int32_field(8, optional=True)
  """
    Optional. Seed used in decoding. If not set, the request uses a randomly
     generated seed.
    """

  response_mime_type: str = betterproto.string_field(13)
  """
    Optional. MIME type of the generated candidate text.
     Supported MIME types are:
     `text/plain`: (default) Text output.
     `application/json`: JSON response in the response candidates.
     `text/x.enum`: ENUM as a string response in the response candidates.
     Refer to the
     [docs](https://ai.google.dev/gemini-api/docs/prompting_with_media#plain_text_formats)
     for a list of all supported text MIME types.
    """

  response_schema: "Schema" = betterproto.message_field(14)
  """
    Optional. Output schema of the generated candidate text. Schemas must be a
     subset of the [OpenAPI schema](https://spec.openapis.org/oas/v3.0.3#schema)
     and can be objects, primitives or arrays.
    
     If set, a compatible `response_mime_type` must also be set.
     Compatible MIME types:
     `application/json`: Schema for JSON response.
     Refer to the [JSON text generation
     guide](https://ai.google.dev/gemini-api/docs/json-mode) for more details.
    """

  response_json_schema: "betterproto_lib_google_protobuf.Value" = (
    betterproto.message_field(24)
  )
  """
    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.
    """

  response_json_schema_ordered: "betterproto_lib_google_protobuf.Value" = (
    betterproto.message_field(28)
  )
  """
    Optional. An internal detail. Use `responseJsonSchema` rather than this
     field.
    """

  presence_penalty: Optional[float] = betterproto.float_field(15, optional=True)
  """
    Optional. Presence penalty applied to the next token's logprobs if the
     token has already been seen in the response.
    
     This penalty is binary on/off and not dependant on the number of times the
     token is used (after the first). Use
     [frequency_penalty][google.ai.generativelanguage.v1beta.GenerationConfig.frequency_penalty]
     for a penalty that increases with each use.
    
     A positive penalty will discourage the use of tokens that have already
     been used in the response, increasing the vocabulary.
    
     A negative penalty will encourage the use of tokens that have already been
     used in the response, decreasing the vocabulary.
    """

  frequency_penalty: Optional[float] = betterproto.float_field(16, optional=True)
  """
    Optional. Frequency penalty applied to the next token's logprobs,
     multiplied by the number of times each token has been seen in the respponse
     so far.
    
     A positive penalty will discourage the use of tokens that have already
     been used, proportional to the number of times the token has been used:
     The more a token is used, the more difficult it is for the model to use
     that token again increasing the vocabulary of responses.
    
     Caution: A _negative_ penalty will encourage the model to reuse tokens
     proportional to the number of times the token has been used. Small
     negative values will reduce the vocabulary of a response. Larger negative
     values will cause the model to start repeating a common token  until it
     hits the
     [max_output_tokens][google.ai.generativelanguage.v1beta.GenerationConfig.max_output_tokens]
     limit.
    """

  response_logprobs: Optional[bool] = betterproto.bool_field(17, optional=True)
  """Optional. If true, export the logprobs results in response."""

  logprobs: Optional[int] = betterproto.int32_field(18, optional=True)
  """
    Optional. Only valid if
     [response_logprobs=True][google.ai.generativelanguage.v1beta.GenerationConfig.response_logprobs].
     This sets the number of top logprobs to return at each decoding step in the
     [Candidate.logprobs_result][google.ai.generativelanguage.v1beta.Candidate.logprobs_result].
     The number must be in the range of [0, 20].
    """

  enable_enhanced_civic_answers: Optional[bool] = betterproto.bool_field(
    19, optional=True
  )
  """
    Optional. Enables enhanced civic answers. It may not be available for all
     models.
    """

  response_modalities: List["GenerationConfigModality"] = betterproto.enum_field(20)
  """
    Optional. The requested modalities of the response. Represents the set of
     modalities that the model can return, and should be expected in the
     response. This is an exact match to the modalities of the response.
    
     A model may have multiple combinations of supported modalities. If the
     requested modalities do not match any of the supported combinations, an
     error will be returned.
    
     An empty list is equivalent to requesting only text.
    """

  speech_config: Optional["SpeechConfig"] = betterproto.message_field(21, optional=True)
  """Optional. The speech generation config."""

  thinking_config: Optional["ThinkingConfig"] = betterproto.message_field(
    22, optional=True
  )
  """
    Optional. Config for thinking features.
     An error will be returned if this field is set for models that don't
     support thinking.
    """

  image_config: Optional["ImageConfig"] = betterproto.message_field(27, optional=True)
  """
    Optional. Config for image generation.
     An error will be returned if this field is set for models that don't
     support these config options.
    """

  media_resolution: Optional["GenerationConfigMediaResolution"] = (
    betterproto.enum_field(23, optional=True)
  )
  """Optional. If specified, the media resolution specified will be used."""


@dataclass(eq=False, repr=False)
class SemanticRetrieverConfig(betterproto.Message):
  """
  Configuration for retrieving grounding content from a `Corpus` or
   `Document` created using the Semantic Retriever API.
  """

  source: str = betterproto.string_field(1)
  """
    Required. Name of the resource for retrieval. Example: `corpora/123` or
     `corpora/123/documents/abc`.
    """

  query: "Content" = betterproto.message_field(2)
  """
    Required. Query to use for matching `Chunk`s in the given resource by
     similarity.
    """

  metadata_filters: List["MetadataFilter"] = betterproto.message_field(3)
  """
    Optional. Filters for selecting `Document`s and/or `Chunk`s from the
     resource.
    """

  max_chunks_count: Optional[int] = betterproto.int32_field(4, optional=True)
  """Optional. Maximum number of relevant `Chunk`s to retrieve."""

  minimum_relevance_score: Optional[float] = betterproto.float_field(5, optional=True)
  """Optional. Minimum relevance score for retrieved relevant `Chunk`s."""


@dataclass(eq=False, repr=False)
class GenerateContentResponse(betterproto.Message):
  """
  Response from the model supporting multiple candidate responses.

   Safety ratings and content filtering are reported for both
   prompt in `GenerateContentResponse.prompt_feedback` and for each candidate
   in `finish_reason` and in `safety_ratings`. The API:
    - Returns either all requested candidates or none of them
    - Returns no candidates at all only if there was something wrong with the
      prompt (check `prompt_feedback`)
    - Reports feedback on each candidate in `finish_reason` and
      `safety_ratings`.
  """

  candidates: List["Candidate"] = betterproto.message_field(1)
  """Candidate responses from the model."""

  prompt_feedback: "GenerateContentResponsePromptFeedback" = betterproto.message_field(
    2
  )
  """Returns the prompt's feedback related to the content filters."""

  usage_metadata: "GenerateContentResponseUsageMetadata" = betterproto.message_field(3)
  """Output only. Metadata on the generation requests' token usage."""

  model_version: str = betterproto.string_field(4)
  """Output only. The model version used to generate the response."""

  response_id: str = betterproto.string_field(5)
  """Output only. response_id is used to identify each response."""


@dataclass(eq=False, repr=False)
class GenerateContentResponsePromptFeedback(betterproto.Message):
  """
  A set of the feedback metadata the prompt specified in
   `GenerateContentRequest.content`.
  """

  block_reason: "GenerateContentResponsePromptFeedbackBlockReason" = (
    betterproto.enum_field(1)
  )
  """
    Optional. If set, the prompt was blocked and no candidates are returned.
     Rephrase the prompt.
    """

  safety_ratings: List["SafetyRating"] = betterproto.message_field(2)
  """
    Ratings for safety of the prompt.
     There is at most one rating per category.
    """


@dataclass(eq=False, repr=False)
class GenerateContentResponseUsageMetadata(betterproto.Message):
  """Metadata on the generation request's token usage."""

  prompt_token_count: int = betterproto.int32_field(1)
  """
    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.
    """

  cached_content_token_count: int = betterproto.int32_field(4)
  """
    Number of tokens in the cached part of the prompt (the cached content)
    """

  candidates_token_count: int = betterproto.int32_field(2)
  """Total number of tokens across all the generated response candidates."""

  tool_use_prompt_token_count: int = betterproto.int32_field(8)
  """Output only. Number of tokens present in tool-use prompt(s)."""

  thoughts_token_count: int = betterproto.int32_field(10)
  """Output only. Number of tokens of thoughts for thinking models."""

  total_token_count: int = betterproto.int32_field(3)
  """
    Total token count for the generation request (prompt + response
     candidates).
    """

  prompt_tokens_details: List["ModalityTokenCount"] = betterproto.message_field(5)
  """
    Output only. List of modalities that were processed in the request input.
    """

  cache_tokens_details: List["ModalityTokenCount"] = betterproto.message_field(6)
  """
    Output only. List of modalities of the cached content in the request
     input.
    """

  candidates_tokens_details: List["ModalityTokenCount"] = betterproto.message_field(7)
  """Output only. List of modalities that were returned in the response."""

  tool_use_prompt_tokens_details: List["ModalityTokenCount"] = (
    betterproto.message_field(9)
  )
  """
    Output only. List of modalities that were processed for tool-use request
     inputs.
    """


@dataclass(eq=False, repr=False)
class Candidate(betterproto.Message):
  """A response candidate generated from the model."""

  index: Optional[int] = betterproto.int32_field(3, optional=True)
  """
    Output only. Index of the candidate in the list of response candidates.
    """

  content: "Content" = betterproto.message_field(1)
  """Output only. Generated content returned from the model."""

  finish_reason: "CandidateFinishReason" = betterproto.enum_field(2)
  """
    Optional. Output only. The reason why the model stopped generating tokens.
    
     If empty, the model has not stopped generating tokens.
    """

  finish_message: Optional[str] = betterproto.string_field(4, optional=True)
  """
    Optional. Output only. Details the reason why the model stopped generating
     tokens. This is populated only when `finish_reason` is set.
    """

  safety_ratings: List["SafetyRating"] = betterproto.message_field(5)
  """
    List of ratings for the safety of a response candidate.
    
     There is at most one rating per category.
    """

  citation_metadata: "CitationMetadata" = betterproto.message_field(6)
  """
    Output only. Citation information for model-generated candidate.
    
     This field may be populated with recitation information for any text
     included in the `content`. These are passages that are "recited" from
     copyrighted material in the foundational LLM's training data.
    """

  token_count: int = betterproto.int32_field(7)
  """Output only. Token count for this candidate."""

  grounding_attributions: List["GroundingAttribution"] = betterproto.message_field(8)
  """
    Output only. Attribution information for sources that contributed to a
     grounded answer.
    
     This field is populated for `GenerateAnswer` calls.
    """

  grounding_metadata: "GroundingMetadata" = betterproto.message_field(9)
  """
    Output only. Grounding metadata for the candidate.
    
     This field is populated for `GenerateContent` calls.
    """

  avg_logprobs: float = betterproto.double_field(10)
  """Output only. Average log probability score of the candidate."""

  logprobs_result: "LogprobsResult" = betterproto.message_field(11)
  """
    Output only. Log-likelihood scores for the response tokens and top tokens
    """

  url_context_metadata: "UrlContextMetadata" = betterproto.message_field(13)
  """Output only. Metadata related to url context retrieval tool."""


@dataclass(eq=False, repr=False)
class UrlContextMetadata(betterproto.Message):
  """Metadata related to url context retrieval tool."""

  url_metadata: List["UrlMetadata"] = betterproto.message_field(1)
  """List of url context."""


@dataclass(eq=False, repr=False)
class UrlMetadata(betterproto.Message):
  """Context of the a single url retrieval."""

  retrieved_url: str = betterproto.string_field(1)
  """Retrieved url by the tool."""

  url_retrieval_status: "UrlMetadataUrlRetrievalStatus" = betterproto.enum_field(2)
  """Status of the url retrieval."""


@dataclass(eq=False, repr=False)
class LogprobsResult(betterproto.Message):
  """Logprobs Result"""

  log_probability_sum: Optional[float] = betterproto.float_field(3, optional=True)
  """Sum of log probabilities for all tokens."""

  top_candidates: List["LogprobsResultTopCandidates"] = betterproto.message_field(1)
  """Length = total number of decoding steps."""

  chosen_candidates: List["LogprobsResultCandidate"] = betterproto.message_field(2)
  """
    Length = total number of decoding steps.
     The chosen candidates may or may not be in top_candidates.
    """


@dataclass(eq=False, repr=False)
class LogprobsResultCandidate(betterproto.Message):
  """Candidate for the logprobs token and score."""

  token: Optional[str] = betterproto.string_field(1, optional=True)
  """The candidate’s token string value."""

  token_id: Optional[int] = betterproto.int32_field(3, optional=True)
  """The candidate’s token id value."""

  log_probability: Optional[float] = betterproto.float_field(2, optional=True)
  """The candidate's log probability."""


@dataclass(eq=False, repr=False)
class LogprobsResultTopCandidates(betterproto.Message):
  """Candidates with top log probabilities at each decoding step."""

  candidates: List["LogprobsResultCandidate"] = betterproto.message_field(1)
  """Sorted by log probability in descending order."""


@dataclass(eq=False, repr=False)
class AttributionSourceId(betterproto.Message):
  """Identifier for the source contributing to this attribution."""

  grounding_passage: "AttributionSourceIdGroundingPassageId" = (
    betterproto.message_field(1, group="source")
  )
  """Identifier for an inline passage."""

  semantic_retriever_chunk: "AttributionSourceIdSemanticRetrieverChunk" = (
    betterproto.message_field(2, group="source")
  )
  """Identifier for a `Chunk` fetched via Semantic Retriever."""


@dataclass(eq=False, repr=False)
class AttributionSourceIdGroundingPassageId(betterproto.Message):
  """Identifier for a part within a `GroundingPassage`."""

  passage_id: str = betterproto.string_field(1)
  """
    Output only. ID of the passage matching the `GenerateAnswerRequest`'s
     `GroundingPassage.id`.
    """

  part_index: int = betterproto.int32_field(2)
  """
    Output only. Index of the part within the `GenerateAnswerRequest`'s
     `GroundingPassage.content`.
    """


@dataclass(eq=False, repr=False)
class AttributionSourceIdSemanticRetrieverChunk(betterproto.Message):
  """
  Identifier for a `Chunk` retrieved via Semantic Retriever specified in the
   `GenerateAnswerRequest` using `SemanticRetrieverConfig`.
  """

  source: str = betterproto.string_field(1)
  """
    Output only. Name of the source matching the request's
     `SemanticRetrieverConfig.source`. Example: `corpora/123` or
     `corpora/123/documents/abc`
    """

  chunk: str = betterproto.string_field(2)
  """
    Output only. Name of the `Chunk` containing the attributed text.
     Example: `corpora/123/documents/abc/chunks/xyz`
    """


@dataclass(eq=False, repr=False)
class GroundingAttribution(betterproto.Message):
  """Attribution for a source that contributed to an answer."""

  source_id: "AttributionSourceId" = betterproto.message_field(3)
  """
    Output only. Identifier for the source contributing to this attribution.
    """

  content: "Content" = betterproto.message_field(2)
  """Grounding source content that makes up this attribution."""


@dataclass(eq=False, repr=False)
class RetrievalMetadata(betterproto.Message):
  """Metadata related to retrieval in the grounding flow."""

  google_search_dynamic_retrieval_score: float = betterproto.float_field(2)
  """
    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.
    """


@dataclass(eq=False, repr=False)
class GroundingMetadata(betterproto.Message):
  """Metadata returned to client when grounding is enabled."""

  search_entry_point: Optional["SearchEntryPoint"] = betterproto.message_field(
    1, optional=True
  )
  """Optional. Google search entry for the following-up web searches."""

  grounding_chunks: List["GroundingChunk"] = betterproto.message_field(2)
  """
    List of supporting references retrieved from specified grounding source.
    """

  grounding_supports: List["GroundingSupport"] = betterproto.message_field(3)
  """List of grounding support."""

  retrieval_metadata: Optional["RetrievalMetadata"] = betterproto.message_field(
    4, optional=True
  )
  """Metadata related to retrieval in the grounding flow."""

  web_search_queries: List[str] = betterproto.string_field(5)
  """Web search queries for the following-up web search."""

  google_maps_widget_context_token: Optional[str] = betterproto.string_field(
    7, optional=True
  )
  """
    Optional. Resource name of the Google Maps widget context token that can be
     used with the PlacesContextElement widget in order to render contextual
     data. Only populated in the case that grounding with Google Maps is
     enabled.
    """


@dataclass(eq=False, repr=False)
class SearchEntryPoint(betterproto.Message):
  """Google search entry point."""

  rendered_content: str = betterproto.string_field(1)
  """
    Optional. Web content snippet that can be embedded in a web page or an app
     webview.
    """

  sdk_blob: bytes = betterproto.bytes_field(2)
  """
    Optional. Base64 encoded JSON representing array of <search term, search
     url> tuple.
    """


@dataclass(eq=False, repr=False)
class GroundingChunk(betterproto.Message):
  """Grounding chunk."""

  web: "GroundingChunkWeb" = betterproto.message_field(1, group="chunk_type")
  """Grounding chunk from the web."""

  retrieved_context: "GroundingChunkRetrievedContext" = betterproto.message_field(
    2, group="chunk_type"
  )
  """
    Optional. Grounding chunk from context retrieved by the file search tool.
    """

  maps: "GroundingChunkMaps" = betterproto.message_field(3, group="chunk_type")
  """Optional. Grounding chunk from Google Maps."""


@dataclass(eq=False, repr=False)
class GroundingChunkWeb(betterproto.Message):
  """Chunk from the web."""

  uri: Optional[str] = betterproto.string_field(1, optional=True)
  """URI reference of the chunk."""

  title: Optional[str] = betterproto.string_field(2, optional=True)
  """Title of the chunk."""


@dataclass(eq=False, repr=False)
class GroundingChunkRetrievedContext(betterproto.Message):
  """Chunk from context retrieved by the file search tool."""

  uri: Optional[str] = betterproto.string_field(1, optional=True)
  """Optional. URI reference of the semantic retrieval document."""

  title: Optional[str] = betterproto.string_field(2, optional=True)
  """Optional. Title of the document."""

  text: Optional[str] = betterproto.string_field(3, optional=True)
  """Optional. Text of the chunk."""


@dataclass(eq=False, repr=False)
class GroundingChunkMaps(betterproto.Message):
  """
  A grounding chunk from Google Maps. A Maps chunk corresponds to a single
   place.
  """

  uri: Optional[str] = betterproto.string_field(1, optional=True)
  """URI reference of the place."""

  title: Optional[str] = betterproto.string_field(2, optional=True)
  """Title of the place."""

  text: Optional[str] = betterproto.string_field(3, optional=True)
  """Text description of the place answer."""

  place_id: Optional[str] = betterproto.string_field(4, optional=True)
  """
    This ID of the place, in `places/{place_id}` format. A user can use this
     ID to look up that place.
    """

  place_answer_sources: Optional["GroundingChunkMapsPlaceAnswerSources"] = (
    betterproto.message_field(5, optional=True)
  )
  """
    Sources that provide answers about the features of a given place in
     Google Maps.
    """


@dataclass(eq=False, repr=False)
class GroundingChunkMapsPlaceAnswerSources(betterproto.Message):
  """
  Collection of sources that provide answers about the features of a given
   place in Google Maps. Each PlaceAnswerSources message corresponds to a
   specific place in Google Maps. The Google Maps tool used these sources in
   order to answer questions about features of the place (e.g: "does Bar Foo
   have Wifi" or "is Foo Bar wheelchair accessible?"). Currently we only
   support review snippets as sources.
  """

  review_snippets: List["GroundingChunkMapsPlaceAnswerSourcesReviewSnippet"] = (
    betterproto.message_field(1)
  )
  """
    Snippets of reviews that are used to generate answers about the
     features of a given place in Google Maps.
    """


@dataclass(eq=False, repr=False)
class GroundingChunkMapsPlaceAnswerSourcesReviewSnippet(betterproto.Message):
  """
  Encapsulates a snippet of a user review that answers a question about
   the features of a specific place in Google Maps.
  """

  review_id: Optional[str] = betterproto.string_field(1, optional=True)
  """The ID of the review snippet."""

  google_maps_uri: Optional[str] = betterproto.string_field(2, optional=True)
  """A link that corresponds to the user review on Google Maps."""

  title: Optional[str] = betterproto.string_field(3, optional=True)
  """Title of the review."""


@dataclass(eq=False, repr=False)
class Segment(betterproto.Message):
  """Segment of the content."""

  part_index: int = betterproto.int32_field(1)
  """
    Output only. The index of a Part object within its parent Content object.
    """

  start_index: int = betterproto.int32_field(2)
  """
    Output only. Start index in the given Part, measured in bytes. Offset from
     the start of the Part, inclusive, starting at zero.
    """

  end_index: int = betterproto.int32_field(3)
  """
    Output only. End index in the given Part, measured in bytes. Offset from
     the start of the Part, exclusive, starting at zero.
    """

  text: str = betterproto.string_field(4)
  """
    Output only. The text corresponding to the segment from the response.
    """


@dataclass(eq=False, repr=False)
class GroundingSupport(betterproto.Message):
  """Grounding support."""

  segment: Optional["Segment"] = betterproto.message_field(1, optional=True)
  """Segment of the content this support belongs to."""

  grounding_chunk_indices: List[int] = betterproto.int32_field(2)
  """
    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.
    """

  confidence_scores: List[float] = betterproto.float_field(3)
  """
    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.
    """


@dataclass(eq=False, repr=False)
class GenerateAnswerRequest(betterproto.Message):
  """Request to generate a grounded answer from the `Model`."""

  inline_passages: "GroundingPassages" = betterproto.message_field(
    6, group="grounding_source"
  )
  """Passages provided inline with the request."""

  semantic_retriever: "SemanticRetrieverConfig" = betterproto.message_field(
    7, group="grounding_source"
  )
  """
    Content retrieved from resources created via the Semantic Retriever
     API.
    """

  model: str = betterproto.string_field(1)
  """
    Required. The name of the `Model` to use for generating the grounded
     response.
    
     Format: `model=models/{model}`.
    """

  contents: List["Content"] = betterproto.message_field(2)
  """
    Required. The content of the current conversation with the `Model`. For
     single-turn queries, this is a single question to answer. For multi-turn
     queries, this is a repeated field that contains conversation history and
     the last `Content` in the list containing the question.
    
     Note: `GenerateAnswer` only supports queries in English.
    """

  answer_style: "GenerateAnswerRequestAnswerStyle" = betterproto.enum_field(5)
  """Required. Style in which answers should be returned."""

  safety_settings: List["SafetySetting"] = betterproto.message_field(3)
  """
    Optional. A list of unique `SafetySetting` instances for blocking unsafe
     content.
    
     This will be enforced on the `GenerateAnswerRequest.contents` and
     `GenerateAnswerResponse.candidate`. There should not be more than one
     setting for each `SafetyCategory` type. The API will block any contents and
     responses that fail to meet the thresholds set by these settings. This list
     overrides the default settings for each `SafetyCategory` specified in the
     safety_settings. If there is no `SafetySetting` for a given
     `SafetyCategory` provided in the list, the API will use the default safety
     setting for that category. Harm categories HARM_CATEGORY_HATE_SPEECH,
     HARM_CATEGORY_SEXUALLY_EXPLICIT, HARM_CATEGORY_DANGEROUS_CONTENT,
     HARM_CATEGORY_HARASSMENT are supported.
     Refer to the
     [guide](https://ai.google.dev/gemini-api/docs/safety-settings)
     for detailed information on available safety settings. Also refer to the
     [Safety guidance](https://ai.google.dev/gemini-api/docs/safety-guidance) to
     learn how to incorporate safety considerations in your AI applications.
    """

  temperature: Optional[float] = betterproto.float_field(4, optional=True)
  """
    Optional. Controls the randomness of the output.
    
     Values can range from [0.0,1.0], inclusive. A value closer to 1.0 will
     produce responses that are more varied and creative, while a value closer
     to 0.0 will typically result in more straightforward responses from the
     model. A low temperature (~0.2) is usually recommended for
     Attributed-Question-Answering use cases.
    """


@dataclass(eq=False, repr=False)
class GenerateAnswerResponse(betterproto.Message):
  """Response from the model for a grounded answer."""

  answer: "Candidate" = betterproto.message_field(1)
  """
    Candidate answer from the model.
    
     Note: The model *always* attempts to provide a grounded answer, even when
     the answer is unlikely to be answerable from the given passages.
     In that case, a low-quality or ungrounded answer may be provided, along
     with a low `answerable_probability`.
    """

  answerable_probability: Optional[float] = betterproto.float_field(2, optional=True)
  """
    Output only. The model's estimate of the probability that its answer is
     correct and grounded in the input passages.
    
     A low `answerable_probability` indicates that the answer might not be
     grounded in the sources.
    
     When `answerable_probability` is low, you may want to:
    
     * Display a message to the effect of "We couldn’t answer that question" to
     the user.
     * Fall back to a general-purpose LLM that answers the question from world
     knowledge. The threshold and nature of such fallbacks will depend on
     individual use cases. `0.5` is a good starting threshold.
    """

  input_feedback: Optional["GenerateAnswerResponseInputFeedback"] = (
    betterproto.message_field(3, optional=True)
  )
  """
    Output only. Feedback related to the input data used to answer the
     question, as opposed to the model-generated response to the question.
    
     The input data can be one or more of the following:
    
     - Question specified by the last entry in `GenerateAnswerRequest.content`
     - Conversation history specified by the other entries in
     `GenerateAnswerRequest.content`
     - Grounding sources (`GenerateAnswerRequest.semantic_retriever` or
     `GenerateAnswerRequest.inline_passages`)
    """


@dataclass(eq=False, repr=False)
class GenerateAnswerResponseInputFeedback(betterproto.Message):
  """
  Feedback related to the input data used to answer the question, as opposed
   to the model-generated response to the question.
  """

  block_reason: Optional["GenerateAnswerResponseInputFeedbackBlockReason"] = (
    betterproto.enum_field(1, optional=True)
  )
  """
    Optional. If set, the input was blocked and no candidates are returned.
     Rephrase the input.
    """

  safety_ratings: List["SafetyRating"] = betterproto.message_field(2)
  """
    Ratings for safety of the input.
     There is at most one rating per category.
    """


@dataclass(eq=False, repr=False)
class EmbedContentRequest(betterproto.Message):
  """Request containing the `Content` for the model to embed."""

  model: str = betterproto.string_field(1)
  """
    Required. The model's resource name. This serves as an ID for the Model to
     use.
    
     This name should match a model name returned by the `ListModels` method.
    
     Format: `models/{model}`
    """

  content: "Content" = betterproto.message_field(2)
  """
    Required. The content to embed. Only the `parts.text` fields will be
     counted.
    """

  task_type: Optional["TaskType"] = betterproto.enum_field(3, optional=True)
  """
    Optional. Optional task type for which the embeddings will be used. Not
     supported on earlier models (`models/embedding-001`).
    """

  title: Optional[str] = betterproto.string_field(4, optional=True)
  """
    Optional. An optional title for the text. Only applicable when TaskType is
     `RETRIEVAL_DOCUMENT`.
    
     Note: Specifying a `title` for `RETRIEVAL_DOCUMENT` provides better quality
     embeddings for retrieval.
    """

  output_dimensionality: Optional[int] = betterproto.int32_field(5, optional=True)
  """
    Optional. Optional 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`).
    """


@dataclass(eq=False, repr=False)
class ContentEmbedding(betterproto.Message):
  """A list of floats representing an embedding."""

  values: List[float] = betterproto.float_field(1)
  """The embedding values."""


@dataclass(eq=False, repr=False)
class EmbedContentResponse(betterproto.Message):
  """The response to an `EmbedContentRequest`."""

  embedding: "ContentEmbedding" = betterproto.message_field(1)
  """Output only. The embedding generated from the input content."""


@dataclass(eq=False, repr=False)
class BatchEmbedContentsRequest(betterproto.Message):
  """
  Batch request to get embeddings from the model for a list of prompts.
  """

  model: str = betterproto.string_field(1)
  """
    Required. The model's resource name. This serves as an ID for the Model to
     use.
    
     This name should match a model name returned by the `ListModels` method.
    
     Format: `models/{model}`
    """

  requests: List["EmbedContentRequest"] = betterproto.message_field(2)
  """
    Required. Embed requests for the batch. The model in each of these requests
     must match the model specified `BatchEmbedContentsRequest.model`.
    """


@dataclass(eq=False, repr=False)
class BatchEmbedContentsResponse(betterproto.Message):
  """The response to a `BatchEmbedContentsRequest`."""

  embeddings: List["ContentEmbedding"] = betterproto.message_field(1)
  """
    Output only. The embeddings for each request, in the same order as provided
     in the batch request.
    """


@dataclass(eq=False, repr=False)
class CountTokensRequest(betterproto.Message):
  """
  Counts the number of tokens in the `prompt` sent to a model.

   Models may tokenize text differently, so each model may return a different
   `token_count`.
  """

  model: str = betterproto.string_field(1)
  """
    Required. The model's resource name. This serves as an ID for the Model to
     use.
    
     This name should match a model name returned by the `ListModels` method.
    
     Format: `models/{model}`
    """

  contents: List["Content"] = betterproto.message_field(2)
  """
    Optional. The input given to the model as a prompt. This field is ignored
     when `generate_content_request` is set.
    """

  generate_content_request: "GenerateContentRequest" = betterproto.message_field(3)
  """
    Optional. The overall input given to the `Model`. This includes the prompt
     as well as other model steering information like [system
     instructions](https://ai.google.dev/gemini-api/docs/system-instructions),
     and/or function declarations for [function
     calling](https://ai.google.dev/gemini-api/docs/function-calling).
     `Model`s/`Content`s and `generate_content_request`s are mutually
     exclusive. You can either send `Model` + `Content`s or a
     `generate_content_request`, but never both.
    """


@dataclass(eq=False, repr=False)
class CountTokensResponse(betterproto.Message):
  """
  A response from `CountTokens`.

   It returns the model's `token_count` for the `prompt`.
  """

  total_tokens: int = betterproto.int32_field(1)
  """
    The number of tokens that the `Model` tokenizes the `prompt` into. Always
     non-negative.
    """

  cached_content_token_count: int = betterproto.int32_field(5)
  """
    Number of tokens in the cached part of the prompt (the cached content).
    """

  prompt_tokens_details: List["ModalityTokenCount"] = betterproto.message_field(6)
  """
    Output only. List of modalities that were processed in the request input.
    """

  cache_tokens_details: List["ModalityTokenCount"] = betterproto.message_field(7)
  """
    Output only. List of modalities that were processed in the cached content.
    """


@dataclass(eq=False, repr=False)
class RealtimeInputConfig(betterproto.Message):
  """Configures the realtime input behavior in `BidiGenerateContent`."""

  automatic_activity_detection: "RealtimeInputConfigAutomaticActivityDetection" = (
    betterproto.message_field(1)
  )
  """
    Optional. If not set, automatic activity detection is enabled by default.
     If automatic voice detection is disabled, the client must send activity
     signals.
    """

  activity_handling: Optional["RealtimeInputConfigActivityHandling"] = (
    betterproto.enum_field(3, optional=True)
  )
  """Optional. Defines what effect activity has."""

  turn_coverage: Optional["RealtimeInputConfigTurnCoverage"] = betterproto.enum_field(
    4, optional=True
  )
  """Optional. Defines which input is included in the user's turn."""


@dataclass(eq=False, repr=False)
class RealtimeInputConfigAutomaticActivityDetection(betterproto.Message):
  """Configures automatic detection of activity."""

  disabled: Optional[bool] = betterproto.bool_field(2, optional=True)
  """
    Optional. If enabled (the default), detected voice and text input count
     as activity. If disabled, the client must send activity signals.
    """

  start_of_speech_sensitivity: Optional[
    "RealtimeInputConfigAutomaticActivityDetectionStartSensitivity"
  ] = betterproto.enum_field(3, optional=True)
  """Optional. Determines how likely speech is to be detected."""

  prefix_padding_ms: Optional[int] = betterproto.int32_field(4, optional=True)
  """
    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 shorter speech can be recognized.
     However, this also increases the probability of false positives.
    """

  end_of_speech_sensitivity: Optional[
    "RealtimeInputConfigAutomaticActivityDetectionEndSensitivity"
  ] = betterproto.enum_field(5, optional=True)
  """Optional. Determines how likely detected speech is ended."""

  silence_duration_ms: Optional[int] = betterproto.int32_field(6, optional=True)
  """
    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.
    """


@dataclass(eq=False, repr=False)
class SessionResumptionConfig(betterproto.Message):
  """
  Session resumption configuration.

   This message is included in the session configuration as
   `BidiGenerateContentSetup.session_resumption`. If configured, the server
   will send `SessionResumptionUpdate` messages.
  """

  handle: Optional[str] = betterproto.string_field(1, optional=True)
  """
    The handle of a previous session. If not present then a new session is
     created.
    
     Session handles come from `SessionResumptionUpdate.token` values in
     previous connections.
    """


@dataclass(eq=False, repr=False)
class ContextWindowCompressionConfig(betterproto.Message):
  """
  Enables context window compression — a mechanism for managing the model's
   context window so that it does not exceed a given length.
  """

  sliding_window: "ContextWindowCompressionConfigSlidingWindow" = (
    betterproto.message_field(2, group="compression_mechanism")
  )
  """A sliding-window mechanism."""

  trigger_tokens: Optional[int] = betterproto.int64_field(1, optional=True)
  """
    The number of tokens (before running a turn) required to trigger a context
     window compression.
    
     This can be used to balance quality against latency as shorter context
     windows may result in faster model responses. However, any compression
     operation will cause a temporary latency increase, so they should not be
     triggered frequently.
    
     If not set, the default is 80% of the model's context window limit. This
     leaves 20% for the next user request/model response.
    """


@dataclass(eq=False, repr=False)
class ContextWindowCompressionConfigSlidingWindow(betterproto.Message):
  """
  The SlidingWindow method operates by discarding content at the beginning of
   the context window. The resulting context will always begin at the start of
   a USER role turn. System instructions and any
   `BidiGenerateContentSetup.prefix_turns` will always remain at the beginning
   of the result.
  """

  target_tokens: Optional[int] = betterproto.int64_field(1, optional=True)
  """
    The target number of tokens to keep. The default value is
     trigger_tokens/2.
    
     Discarding parts of the context window causes a temporary latency
     increase so this value should be calibrated to avoid frequent compression
     operations.
    """


@dataclass(eq=False, repr=False)
class AudioTranscriptionConfig(betterproto.Message):
  """The audio transcription configuration."""

  pass


@dataclass(eq=False, repr=False)
class BidiGenerateContentSetup(betterproto.Message):
  """
  Message to be sent in the first (and only in the first)
   `BidiGenerateContentClientMessage`. Contains configuration that will apply
   for the duration of the streaming RPC.

   Clients should wait for a `BidiGenerateContentSetupComplete` message before
   sending any additional messages.
  """

  model: str = betterproto.string_field(1)
  """
    Required. The model's resource name. This serves as an ID for the Model to
     use.
    
     Format: `models/{model}`
    """

  generation_config: "GenerationConfig" = betterproto.message_field(2)
  """
    Optional. Generation config.
    
     The following fields are not supported:
    
      - `response_logprobs`
      - `response_mime_type`
      - `logprobs`
      - `response_schema`
      - `response_json_schema`
      - `stop_sequence`
      - `routing_config`
      - `audio_timestamp`
    """

  system_instruction: "Content" = betterproto.message_field(3)
  """
    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.
    """

  tools: List["Tool"] = betterproto.message_field(4)
  """
    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.
    """

  realtime_input_config: "RealtimeInputConfig" = betterproto.message_field(6)
  """Optional. Configures the handling of realtime input."""

  session_resumption: "SessionResumptionConfig" = betterproto.message_field(7)
  """
    Optional. Configures session resumption mechanism.
    
     If included, the server will send `SessionResumptionUpdate` messages.
    """

  context_window_compression: "ContextWindowCompressionConfig" = (
    betterproto.message_field(8)
  )
  """
    Optional. Configures a context window compression mechanism.
    
     If included, the server will automatically reduce the size of the context
     when it exceeds the configured length.
    """

  input_audio_transcription: "AudioTranscriptionConfig" = betterproto.message_field(10)
  """
    Optional. If set, enables transcription of voice input. The transcription
     aligns with the input audio language, if configured.
    """

  output_audio_transcription: "AudioTranscriptionConfig" = betterproto.message_field(11)
  """
    Optional. If set, enables transcription of the model's audio output. The
     transcription aligns with the language code specified for the output
     audio, if configured.
    """


@dataclass(eq=False, repr=False)
class BidiGenerateContentClientContent(betterproto.Message):
  """
  Incremental update of the current conversation delivered from the client.
   All of the content here is unconditionally 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.
  """

  turns: List["Content"] = betterproto.message_field(1)
  """
    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
     the latest request.
    """

  turn_complete: bool = betterproto.bool_field(2)
  """
    Optional. If true, indicates that the server content generation should
     start with the currently accumulated prompt. Otherwise, the server awaits
     additional messages before starting generation.
    """


@dataclass(eq=False, repr=False)
class BidiGenerateContentRealtimeInput(betterproto.Message):
  """
  User input that is sent in real time.

   The different modalities (audio, video and text) are handled as concurrent
   streams. The ordering across these streams is not guaranteed.

   This is different from
   [BidiGenerateContentClientContent][google.ai.generativelanguage.v1beta.BidiGenerateContentClientContent]
   in a few ways:

   * Can be sent continuously without interruption to model generation.
   * If there is a need to mix data interleaved across the
     [BidiGenerateContentClientContent][google.ai.generativelanguage.v1beta.BidiGenerateContentClientContent]
     and the
     [BidiGenerateContentRealtimeInput][google.ai.generativelanguage.v1beta.BidiGenerateContentRealtimeInput],
     the 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.
  """

  media_chunks: List["Blob"] = betterproto.message_field(1)
  """
    Optional. Inlined bytes data for media input. Multiple `media_chunks` are
     not supported, all but the first will be ignored.
    
     DEPRECATED: Use one of `audio`, `video`, or `text` instead.
    """

  audio: "Blob" = betterproto.message_field(2)
  """Optional. These form the realtime audio input stream."""

  audio_stream_end: Optional[bool] = betterproto.bool_field(3, optional=True)
  """
    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.
    """

  video: "Blob" = betterproto.message_field(4)
  """Optional. These form the realtime video input stream."""

  text: Optional[str] = betterproto.string_field(5, optional=True)
  """Optional. These form the realtime text input stream."""

  activity_start: "BidiGenerateContentRealtimeInputActivityStart" = (
    betterproto.message_field(6)
  )
  """
    Optional. Marks the start of user activity. This can only be sent if
     automatic (i.e. server-side) activity detection is disabled.
    """

  activity_end: "BidiGenerateContentRealtimeInputActivityEnd" = (
    betterproto.message_field(7)
  )
  """
    Optional. Marks the end of user activity. This can only be sent if
     automatic (i.e. server-side) activity detection is disabled.
    """


@dataclass(eq=False, repr=False)
class BidiGenerateContentRealtimeInputActivityStart(betterproto.Message):
  """Marks the start of user activity."""

  pass


@dataclass(eq=False, repr=False)
class BidiGenerateContentRealtimeInputActivityEnd(betterproto.Message):
  """Marks the end of user activity."""

  pass


@dataclass(eq=False, repr=False)
class BidiGenerateContentToolResponse(betterproto.Message):
  """
  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 these dedicated set of
   messages.
  """

  function_responses: List["FunctionResponse"] = betterproto.message_field(1)
  """Optional. The response to the function calls."""


@dataclass(eq=False, repr=False)
class BidiGenerateContentClientMessage(betterproto.Message):
  """Messages sent by the client in the BidiGenerateContent call."""

  setup: "BidiGenerateContentSetup" = betterproto.message_field(1, group="message_type")
  """
    Optional. Session configuration sent only in the first client message.
    """

  client_content: "BidiGenerateContentClientContent" = betterproto.message_field(
    2, group="message_type"
  )
  """
    Optional. Incremental update of the current conversation delivered from
     the client.
    """

  realtime_input: "BidiGenerateContentRealtimeInput" = betterproto.message_field(
    3, group="message_type"
  )
  """Optional. User input that is sent in real time."""

  tool_response: "BidiGenerateContentToolResponse" = betterproto.message_field(
    4, group="message_type"
  )
  """Optional. Response to a `ToolCallMessage` received from the server."""


@dataclass(eq=False, repr=False)
class BidiGenerateContentSetupComplete(betterproto.Message):
  """
  Sent in response to a `BidiGenerateContentSetup` message from the client.
  """

  pass


@dataclass(eq=False, repr=False)
class BidiGenerateContentServerContent(betterproto.Message):
  """
  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.
  """

  model_turn: Optional["Content"] = betterproto.message_field(1, optional=True)
  """
    Output only. The content that the model has generated as part of the
     current conversation with the user.
    """

  generation_complete: bool = betterproto.bool_field(5)
  """
    Output only. 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.
    """

  turn_complete: bool = betterproto.bool_field(2)
  """
    Output only. If true, indicates that the model has completed its turn.
     Generation will only start in response to additional client messages.
    """

  interrupted: bool = betterproto.bool_field(3)
  """
    Output only. If true, indicates that a client message has interrupted
     current model generation. If the client is playing out the content in real
     time, this is a good signal to stop and empty the current playback queue.
    """

  grounding_metadata: "GroundingMetadata" = betterproto.message_field(4)
  """Output only. Grounding metadata for the generated content."""

  input_transcription: "BidiGenerateContentTranscription" = betterproto.message_field(6)
  """
    Output only. Input audio transcription. The transcription is sent
     independently of the other server messages and there is no guaranteed
     ordering.
    """

  output_transcription: "BidiGenerateContentTranscription" = betterproto.message_field(
    7
  )
  """
    Output only. Output audio transcription. These transcriptions are part of
     the Generation output of the server. The last output transcription of this
     turn is sent before either `generation_complete` or `interrupted`, which in
     turn are followed by `turn_complete`. There is no guaranteed exact ordering
     between transcriptions and other `model_turn` output but the server tries
     to send the transcripts close to the corresponding audio output.
    """

  url_context_metadata: "UrlContextMetadata" = betterproto.message_field(9)
  waiting_for_input: bool = betterproto.bool_field(10)
  """
    Output only. 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.
    """


@dataclass(eq=False, repr=False)
class BidiGenerateContentToolCall(betterproto.Message):
  """
  Request for the client to execute the `function_calls` and return the
   responses with the matching `id`s.
  """

  function_calls: List["FunctionCall"] = betterproto.message_field(2)
  """Output only. The function call to be executed."""


@dataclass(eq=False, repr=False)
class BidiGenerateContentToolCallCancellation(betterproto.Message):
  """
  Notification for the client that a previously issued `ToolCallMessage`
   with the specified `id`s should not have been 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.
  """

  ids: List[str] = betterproto.string_field(1)
  """Output only. The ids of the tool calls to be cancelled."""


@dataclass(eq=False, repr=False)
class GoAway(betterproto.Message):
  """A notice that the server will soon disconnect."""

  time_left: timedelta = betterproto.message_field(1)
  """
    The remaining time before the connection will be terminated as ABORTED.
    
     This duration will never be less than a model-specific minimum, which will
     be specified together with the rate limits for the model.
    """


@dataclass(eq=False, repr=False)
class SessionResumptionUpdate(betterproto.Message):
  """
  Update of the session resumption state.

   Only sent if `BidiGenerateContentSetup.session_resumption` was set.
  """

  new_handle: str = betterproto.string_field(1)
  """
    New handle that represents a state that can be resumed. Empty if
     `resumable`=false.
    """

  resumable: bool = betterproto.bool_field(2)
  """
    True if the current session can be resumed at this point.
    
     Resumption is not possible at some points in the session. For example, when
     the model is executing function calls or generating. Resuming the session
     (using a previous session token) in such a state will result in some data
     loss. In these cases, `new_handle` will be empty and `resumable` will be
     false.
    """


@dataclass(eq=False, repr=False)
class BidiGenerateContentTranscription(betterproto.Message):
  """Transcription of audio (input or output)."""

  text: str = betterproto.string_field(1)
  """Transcription text."""


@dataclass(eq=False, repr=False)
class BidiGenerateContentServerMessage(betterproto.Message):
  """Response message for the BidiGenerateContent call."""

  setup_complete: "BidiGenerateContentSetupComplete" = betterproto.message_field(
    2, group="message_type"
  )
  """
    Output only. Sent in response to a `BidiGenerateContentSetup` message
     from the client when setup is complete.
    """

  server_content: "BidiGenerateContentServerContent" = betterproto.message_field(
    3, group="message_type"
  )
  """
    Output only. Content generated by the model in response to client
     messages.
    """

  tool_call: "BidiGenerateContentToolCall" = betterproto.message_field(
    4, group="message_type"
  )
  """
    Output only. Request for the client to execute the `function_calls` and
     return the responses with the matching `id`s.
    """

  tool_call_cancellation: "BidiGenerateContentToolCallCancellation" = (
    betterproto.message_field(5, group="message_type")
  )
  """
    Output only. Notification for the client that a previously issued
     `ToolCallMessage` with the specified `id`s should be cancelled.
    """

  go_away: "GoAway" = betterproto.message_field(6, group="message_type")
  """Output only. A notice that the server will soon disconnect."""

  session_resumption_update: "SessionResumptionUpdate" = betterproto.message_field(
    7, group="message_type"
  )
  """Output only. Update of the session resumption state."""

  usage_metadata: "UsageMetadata" = betterproto.message_field(10)
  """Output only. Usage metadata about the response(s)."""


@dataclass(eq=False, repr=False)
class UsageMetadata(betterproto.Message):
  """Usage metadata about response(s)."""

  prompt_token_count: int = betterproto.int32_field(1)
  """
    Output only. 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.
    """

  cached_content_token_count: int = betterproto.int32_field(4)
  """
    Number of tokens in the cached part of the prompt (the cached content)
    """

  response_token_count: int = betterproto.int32_field(2)
  """
    Output only. Total number of tokens across all the generated response
     candidates.
    """

  tool_use_prompt_token_count: int = betterproto.int32_field(8)
  """Output only. Number of tokens present in tool-use prompt(s)."""

  thoughts_token_count: int = betterproto.int32_field(10)
  """Output only. Number of tokens of thoughts for thinking models."""

  total_token_count: int = betterproto.int32_field(3)
  """
    Output only. Total token count for the generation request (prompt +
     response candidates).
    """

  prompt_tokens_details: List["ModalityTokenCount"] = betterproto.message_field(5)
  """
    Output only. List of modalities that were processed in the request input.
    """

  cache_tokens_details: List["ModalityTokenCount"] = betterproto.message_field(6)
  """
    Output only. List of modalities of the cached content in the request input.
    """

  response_tokens_details: List["ModalityTokenCount"] = betterproto.message_field(7)
  """Output only. List of modalities that were returned in the response."""

  tool_use_prompt_tokens_details: List["ModalityTokenCount"] = (
    betterproto.message_field(9)
  )
  """
    Output only. List of modalities that were processed for tool-use request
     inputs.
    """


class GenerativeServiceStub(betterproto.ServiceStub):
  async def generate_content(
    self,
    generate_content_request: "GenerateContentRequest",
    *,
    timeout: Optional[float] = None,
    deadline: Optional["Deadline"] = None,
    metadata: Optional["MetadataLike"] = None,
  ) -> "GenerateContentResponse":
    return await self._unary_unary(
      "/google.ai.generativelanguage.v1beta.GenerativeService/GenerateContent",
      generate_content_request,
      GenerateContentResponse,
      timeout=timeout,
      deadline=deadline,
      metadata=metadata,
    )

  async def generate_answer(
    self,
    generate_answer_request: "GenerateAnswerRequest",
    *,
    timeout: Optional[float] = None,
    deadline: Optional["Deadline"] = None,
    metadata: Optional["MetadataLike"] = None,
  ) -> "GenerateAnswerResponse":
    return await self._unary_unary(
      "/google.ai.generativelanguage.v1beta.GenerativeService/GenerateAnswer",
      generate_answer_request,
      GenerateAnswerResponse,
      timeout=timeout,
      deadline=deadline,
      metadata=metadata,
    )

  async def stream_generate_content(
    self,
    generate_content_request: "GenerateContentRequest",
    *,
    timeout: Optional[float] = None,
    deadline: Optional["Deadline"] = None,
    metadata: Optional["MetadataLike"] = None,
  ) -> AsyncIterator[GenerateContentResponse]:
    async for response in self._unary_stream(
      "/google.ai.generativelanguage.v1beta.GenerativeService/StreamGenerateContent",
      generate_content_request,
      GenerateContentResponse,
      timeout=timeout,
      deadline=deadline,
      metadata=metadata,
    ):
      yield response

  async def embed_content(
    self,
    embed_content_request: "EmbedContentRequest",
    *,
    timeout: Optional[float] = None,
    deadline: Optional["Deadline"] = None,
    metadata: Optional["MetadataLike"] = None,
  ) -> "EmbedContentResponse":
    return await self._unary_unary(
      "/google.ai.generativelanguage.v1beta.GenerativeService/EmbedContent",
      embed_content_request,
      EmbedContentResponse,
      timeout=timeout,
      deadline=deadline,
      metadata=metadata,
    )

  async def batch_embed_contents(
    self,
    batch_embed_contents_request: "BatchEmbedContentsRequest",
    *,
    timeout: Optional[float] = None,
    deadline: Optional["Deadline"] = None,
    metadata: Optional["MetadataLike"] = None,
  ) -> "BatchEmbedContentsResponse":
    return await self._unary_unary(
      "/google.ai.generativelanguage.v1beta.GenerativeService/BatchEmbedContents",
      batch_embed_contents_request,
      BatchEmbedContentsResponse,
      timeout=timeout,
      deadline=deadline,
      metadata=metadata,
    )

  async def count_tokens(
    self,
    count_tokens_request: "CountTokensRequest",
    *,
    timeout: Optional[float] = None,
    deadline: Optional["Deadline"] = None,
    metadata: Optional["MetadataLike"] = None,
  ) -> "CountTokensResponse":
    return await self._unary_unary(
      "/google.ai.generativelanguage.v1beta.GenerativeService/CountTokens",
      count_tokens_request,
      CountTokensResponse,
      timeout=timeout,
      deadline=deadline,
      metadata=metadata,
    )

  async def bidi_generate_content(
    self,
    bidi_generate_content_client_message_iterator: Union[
      AsyncIterable[BidiGenerateContentClientMessage],
      Iterable[BidiGenerateContentClientMessage],
    ],
    *,
    timeout: Optional[float] = None,
    deadline: Optional["Deadline"] = None,
    metadata: Optional["MetadataLike"] = None,
  ) -> AsyncIterator[BidiGenerateContentServerMessage]:
    async for response in self._stream_stream(
      "/google.ai.generativelanguage.v1beta.GenerativeService/BidiGenerateContent",
      bidi_generate_content_client_message_iterator,
      BidiGenerateContentClientMessage,
      BidiGenerateContentServerMessage,
      timeout=timeout,
      deadline=deadline,
      metadata=metadata,
    ):
      yield response


class GenerativeServiceBase(ServiceBase):
  async def generate_content(
    self, generate_content_request: "GenerateContentRequest"
  ) -> "GenerateContentResponse":
    raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED)

  async def generate_answer(
    self, generate_answer_request: "GenerateAnswerRequest"
  ) -> "GenerateAnswerResponse":
    raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED)

  async def stream_generate_content(
    self, generate_content_request: "GenerateContentRequest"
  ) -> AsyncIterator[GenerateContentResponse]:
    raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED)
    yield GenerateContentResponse()

  async def embed_content(
    self, embed_content_request: "EmbedContentRequest"
  ) -> "EmbedContentResponse":
    raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED)

  async def batch_embed_contents(
    self, batch_embed_contents_request: "BatchEmbedContentsRequest"
  ) -> "BatchEmbedContentsResponse":
    raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED)

  async def count_tokens(
    self, count_tokens_request: "CountTokensRequest"
  ) -> "CountTokensResponse":
    raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED)

  async def bidi_generate_content(
    self,
    bidi_generate_content_client_message_iterator: AsyncIterator[
      BidiGenerateContentClientMessage
    ],
  ) -> AsyncIterator[BidiGenerateContentServerMessage]:
    raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED)
    yield BidiGenerateContentServerMessage()

  async def __rpc_generate_content(
    self,
    stream: "grpclib.server.Stream[GenerateContentRequest, GenerateContentResponse]",
  ) -> None:
    request = await stream.recv_message()
    response = await self.generate_content(request)
    await stream.send_message(response)

  async def __rpc_generate_answer(
    self,
    stream: "grpclib.server.Stream[GenerateAnswerRequest, GenerateAnswerResponse]",
  ) -> None:
    request = await stream.recv_message()
    response = await self.generate_answer(request)
    await stream.send_message(response)

  async def __rpc_stream_generate_content(
    self,
    stream: "grpclib.server.Stream[GenerateContentRequest, GenerateContentResponse]",
  ) -> None:
    request = await stream.recv_message()
    await self._call_rpc_handler_server_stream(
      self.stream_generate_content,
      stream,
      request,
    )

  async def __rpc_embed_content(
    self, stream: "grpclib.server.Stream[EmbedContentRequest, EmbedContentResponse]"
  ) -> None:
    request = await stream.recv_message()
    response = await self.embed_content(request)
    await stream.send_message(response)

  async def __rpc_batch_embed_contents(
    self,
    stream: "grpclib.server.Stream[BatchEmbedContentsRequest, BatchEmbedContentsResponse]",
  ) -> None:
    request = await stream.recv_message()
    response = await self.batch_embed_contents(request)
    await stream.send_message(response)

  async def __rpc_count_tokens(
    self, stream: "grpclib.server.Stream[CountTokensRequest, CountTokensResponse]"
  ) -> None:
    request = await stream.recv_message()
    response = await self.count_tokens(request)
    await stream.send_message(response)

  async def __rpc_bidi_generate_content(
    self,
    stream: "grpclib.server.Stream[BidiGenerateContentClientMessage, BidiGenerateContentServerMessage]",
  ) -> None:
    request = stream.__aiter__()
    await self._call_rpc_handler_server_stream(
      self.bidi_generate_content,
      stream,
      request,
    )

  def __mapping__(self) -> Dict[str, grpclib.const.Handler]:
    return {
      "/google.ai.generativelanguage.v1beta.GenerativeService/GenerateContent": grpclib.const.Handler(
        self.__rpc_generate_content,
        grpclib.const.Cardinality.UNARY_UNARY,
        GenerateContentRequest,
        GenerateContentResponse,
      ),
      "/google.ai.generativelanguage.v1beta.GenerativeService/GenerateAnswer": grpclib.const.Handler(
        self.__rpc_generate_answer,
        grpclib.const.Cardinality.UNARY_UNARY,
        GenerateAnswerRequest,
        GenerateAnswerResponse,
      ),
      "/google.ai.generativelanguage.v1beta.GenerativeService/StreamGenerateContent": grpclib.const.Handler(
        self.__rpc_stream_generate_content,
        grpclib.const.Cardinality.UNARY_STREAM,
        GenerateContentRequest,
        GenerateContentResponse,
      ),
      "/google.ai.generativelanguage.v1beta.GenerativeService/EmbedContent": grpclib.const.Handler(
        self.__rpc_embed_content,
        grpclib.const.Cardinality.UNARY_UNARY,
        EmbedContentRequest,
        EmbedContentResponse,
      ),
      "/google.ai.generativelanguage.v1beta.GenerativeService/BatchEmbedContents": grpclib.const.Handler(
        self.__rpc_batch_embed_contents,
        grpclib.const.Cardinality.UNARY_UNARY,
        BatchEmbedContentsRequest,
        BatchEmbedContentsResponse,
      ),
      "/google.ai.generativelanguage.v1beta.GenerativeService/CountTokens": grpclib.const.Handler(
        self.__rpc_count_tokens,
        grpclib.const.Cardinality.UNARY_UNARY,
        CountTokensRequest,
        CountTokensResponse,
      ),
      "/google.ai.generativelanguage.v1beta.GenerativeService/BidiGenerateContent": grpclib.const.Handler(
        self.__rpc_bidi_generate_content,
        grpclib.const.Cardinality.STREAM_STREAM,
        BidiGenerateContentClientMessage,
        BidiGenerateContentServerMessage,
      ),
    }
