# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

# Code generated by the Google Gen AI SDK generator DO NOT EDIT.

import datetime
import json
import logging
import os
import re
import typing
from typing import (
    Any,
    Callable,
    ClassVar,
    Dict,
    List,
    Literal,
    Optional,
    Tuple,
    TypeVar,
    Union,
)
from google.genai import _common
from google.genai import types as genai_types
from pydantic import (
    ConfigDict,
    Field,
    PrivateAttr,
    computed_field,
    field_validator,
    model_validator,
)
from typing_extensions import TypedDict
from . import evals as evals_types


def camel_to_snake(camel_case_string: str) -> str:
    snake_case_string = re.sub(r"(?<!^)([A-Z])", r"_\1", camel_case_string)
    return snake_case_string.lower()


def _camel_key_to_snake(message: Any):
    """Converts all camelCase keys to snake_case in a dict or list."""
    if isinstance(message, dict):
        return {
            camel_to_snake(key): _camel_key_to_snake(value)
            for key, value in message.items()
        }
    elif isinstance(message, list):
        return [_camel_key_to_snake(value) for value in message]
    else:
        return message


if typing.TYPE_CHECKING:
    import pandas as pd

    PandasDataFrame = pd.DataFrame
else:
    try:
        import pandas as pd

        PandasDataFrame = pd.DataFrame
    except ImportError:
        pd = None
        PandasDataFrame = Any
if typing.TYPE_CHECKING:
    import yaml
else:
    try:
        import yaml
    except ImportError:
        yaml = None

logger = logging.getLogger("vertexai_genai.types")

MetricSubclass = TypeVar("MetricSubclass", bound="Metric")


class PairwiseChoice(_common.CaseInSensitiveEnum):
    """Output only. Pairwise metric choice."""

    PAIRWISE_CHOICE_UNSPECIFIED = "PAIRWISE_CHOICE_UNSPECIFIED"
    """Unspecified prediction choice."""
    BASELINE = "BASELINE"
    """Baseline prediction wins"""
    CANDIDATE = "CANDIDATE"
    """Candidate prediction wins"""
    TIE = "TIE"
    """Winner cannot be determined"""


class Strategy(_common.CaseInSensitiveEnum):
    """This determines which type of scheduling strategy to use."""

    STRATEGY_UNSPECIFIED = "STRATEGY_UNSPECIFIED"
    """Strategy will default to STANDARD."""
    ON_DEMAND = "ON_DEMAND"
    """Deprecated. Regular on-demand provisioning strategy."""
    LOW_COST = "LOW_COST"
    """Deprecated. Low cost by making potential use of spot resources."""
    STANDARD = "STANDARD"
    """Standard provisioning strategy uses regular on-demand resources."""
    SPOT = "SPOT"
    """Spot provisioning strategy uses spot resources."""
    FLEX_START = "FLEX_START"
    """Flex Start strategy uses DWS to queue for resources."""


class AcceleratorType(_common.CaseInSensitiveEnum):
    """Immutable. The type of accelerator(s) that may be attached to the machine as per accelerator_count."""

    ACCELERATOR_TYPE_UNSPECIFIED = "ACCELERATOR_TYPE_UNSPECIFIED"
    """Unspecified accelerator type, which means no accelerator."""
    NVIDIA_TESLA_K80 = "NVIDIA_TESLA_K80"
    """Deprecated: Nvidia Tesla K80 GPU has reached end of support, see https://cloud.google.com/compute/docs/eol/k80-eol."""
    NVIDIA_TESLA_P100 = "NVIDIA_TESLA_P100"
    """Nvidia Tesla P100 GPU."""
    NVIDIA_TESLA_V100 = "NVIDIA_TESLA_V100"
    """Nvidia Tesla V100 GPU."""
    NVIDIA_TESLA_P4 = "NVIDIA_TESLA_P4"
    """Nvidia Tesla P4 GPU."""
    NVIDIA_TESLA_T4 = "NVIDIA_TESLA_T4"
    """Nvidia Tesla T4 GPU."""
    NVIDIA_TESLA_A100 = "NVIDIA_TESLA_A100"
    """Nvidia Tesla A100 GPU."""
    NVIDIA_A100_80GB = "NVIDIA_A100_80GB"
    """Nvidia A100 80GB GPU."""
    NVIDIA_L4 = "NVIDIA_L4"
    """Nvidia L4 GPU."""
    NVIDIA_H100_80GB = "NVIDIA_H100_80GB"
    """Nvidia H100 80Gb GPU."""
    NVIDIA_H100_MEGA_80GB = "NVIDIA_H100_MEGA_80GB"
    """Nvidia H100 Mega 80Gb GPU."""
    NVIDIA_H200_141GB = "NVIDIA_H200_141GB"
    """Nvidia H200 141Gb GPU."""
    NVIDIA_B200 = "NVIDIA_B200"
    """Nvidia B200 GPU."""
    NVIDIA_GB200 = "NVIDIA_GB200"
    """Nvidia GB200 GPU."""
    NVIDIA_RTX_PRO_6000 = "NVIDIA_RTX_PRO_6000"
    """Nvidia RTX Pro 6000 GPU."""
    TPU_V2 = "TPU_V2"
    """TPU v2."""
    TPU_V3 = "TPU_V3"
    """TPU v3."""
    TPU_V4_POD = "TPU_V4_POD"
    """TPU v4."""
    TPU_V5_LITEPOD = "TPU_V5_LITEPOD"
    """TPU v5."""


class Type(_common.CaseInSensitiveEnum):
    """Specifies the reservation affinity type."""

    TYPE_UNSPECIFIED = "TYPE_UNSPECIFIED"
    """Default value. This should not be used."""
    NO_RESERVATION = "NO_RESERVATION"
    """Do not consume from any reserved capacity, only use on-demand."""
    ANY_RESERVATION = "ANY_RESERVATION"
    """Consume any reservation available, falling back to on-demand."""
    SPECIFIC_RESERVATION = "SPECIFIC_RESERVATION"
    """Consume from a specific reservation. When chosen, the reservation must be identified via the `key` and `values` fields."""


class JobState(_common.CaseInSensitiveEnum):
    """Output only. The detailed state of the job."""

    JOB_STATE_UNSPECIFIED = "JOB_STATE_UNSPECIFIED"
    """The job state is unspecified."""
    JOB_STATE_QUEUED = "JOB_STATE_QUEUED"
    """The job has been just created or resumed and processing has not yet begun."""
    JOB_STATE_PENDING = "JOB_STATE_PENDING"
    """The service is preparing to run the job."""
    JOB_STATE_RUNNING = "JOB_STATE_RUNNING"
    """The job is in progress."""
    JOB_STATE_SUCCEEDED = "JOB_STATE_SUCCEEDED"
    """The job completed successfully."""
    JOB_STATE_FAILED = "JOB_STATE_FAILED"
    """The job failed."""
    JOB_STATE_CANCELLING = "JOB_STATE_CANCELLING"
    """The job is being cancelled. From this state the job may only go to either `JOB_STATE_SUCCEEDED`, `JOB_STATE_FAILED` or `JOB_STATE_CANCELLED`."""
    JOB_STATE_CANCELLED = "JOB_STATE_CANCELLED"
    """The job has been cancelled."""
    JOB_STATE_PAUSED = "JOB_STATE_PAUSED"
    """The job has been stopped, and can be resumed."""
    JOB_STATE_EXPIRED = "JOB_STATE_EXPIRED"
    """The job has expired."""
    JOB_STATE_UPDATING = "JOB_STATE_UPDATING"
    """The job is being updated. Only jobs in the `RUNNING` state can be updated. After updating, the job goes back to the `RUNNING` state."""
    JOB_STATE_PARTIALLY_SUCCEEDED = "JOB_STATE_PARTIALLY_SUCCEEDED"
    """The job is partially succeeded, some results may be missing due to errors."""


class IdentityType(_common.CaseInSensitiveEnum):
    """The identity type to use for the Reasoning Engine. If not specified, the `service_account` field will be used if set, otherwise the default Vertex AI Reasoning Engine Service Agent in the project will be used."""

    IDENTITY_TYPE_UNSPECIFIED = "IDENTITY_TYPE_UNSPECIFIED"
    """Default value. Use a custom service account if the `service_account` field is set, otherwise use the default Vertex AI Reasoning Engine Service Agent in the project. Same behavior as SERVICE_ACCOUNT."""
    SERVICE_ACCOUNT = "SERVICE_ACCOUNT"
    """Use a custom service account if the `service_account` field is set, otherwise use the default Vertex AI Reasoning Engine Service Agent in the project."""
    AGENT_IDENTITY = "AGENT_IDENTITY"
    """Use Agent Identity. The `service_account` field must not be set."""


class AgentServerMode(_common.CaseInSensitiveEnum):
    """The agent server mode."""

    AGENT_SERVER_MODE_UNSPECIFIED = "AGENT_SERVER_MODE_UNSPECIFIED"
    """Unspecified agent server mode. Do not use."""
    STABLE = "STABLE"
    """Stable agent server mode. This mode has everything stable and well-tested features agent engine offers."""
    EXPERIMENTAL = "EXPERIMENTAL"
    """Experimental agent server mode. This mode contains experimental features."""


class ManagedTopicEnum(_common.CaseInSensitiveEnum):
    """The managed topic."""

    MANAGED_TOPIC_ENUM_UNSPECIFIED = "MANAGED_TOPIC_ENUM_UNSPECIFIED"
    """Unspecified topic. This value should not be used."""
    USER_PERSONAL_INFO = "USER_PERSONAL_INFO"
    """Significant personal information about the User like first names, relationships, hobbies, important dates."""
    USER_PREFERENCES = "USER_PREFERENCES"
    """Stated or implied likes, dislikes, preferred styles, or patterns."""
    KEY_CONVERSATION_DETAILS = "KEY_CONVERSATION_DETAILS"
    """Important milestones or conclusions within the dialogue."""
    EXPLICIT_INSTRUCTIONS = "EXPLICIT_INSTRUCTIONS"
    """Information that the user explicitly requested to remember or forget."""


class Language(_common.CaseInSensitiveEnum):
    """The coding language supported in this environment."""

    LANGUAGE_UNSPECIFIED = "LANGUAGE_UNSPECIFIED"
    """The default value. This value is unused."""
    LANGUAGE_PYTHON = "LANGUAGE_PYTHON"
    """The coding language is Python."""
    LANGUAGE_JAVASCRIPT = "LANGUAGE_JAVASCRIPT"
    """The coding language is JavaScript."""


class MachineConfig(_common.CaseInSensitiveEnum):
    """The machine config of the code execution environment."""

    MACHINE_CONFIG_UNSPECIFIED = "MACHINE_CONFIG_UNSPECIFIED"
    """The default value: milligcu 2000, memory 1.5Gib"""
    MACHINE_CONFIG_VCPU4_RAM4GIB = "MACHINE_CONFIG_VCPU4_RAM4GIB"
    """The default value: milligcu 4000, memory 4 Gib"""


class State(_common.CaseInSensitiveEnum):
    """Output only. The runtime state of the SandboxEnvironment."""

    STATE_UNSPECIFIED = "STATE_UNSPECIFIED"
    """The default value. This value is unused."""
    STATE_PROVISIONING = "STATE_PROVISIONING"
    """Runtime resources are being allocated for the sandbox environment."""
    STATE_RUNNING = "STATE_RUNNING"
    """Sandbox runtime is ready for serving."""
    STATE_DEPROVISIONING = "STATE_DEPROVISIONING"
    """Sandbox runtime is halted, performing tear down tasks."""
    STATE_TERMINATED = "STATE_TERMINATED"
    """Sandbox has terminated with underlying runtime failure."""
    STATE_DELETED = "STATE_DELETED"
    """Sandbox runtime has been deleted."""


class EvaluationItemType(_common.CaseInSensitiveEnum):
    """The type of the EvaluationItem."""

    EVALUATION_ITEM_TYPE_UNSPECIFIED = "EVALUATION_ITEM_TYPE_UNSPECIFIED"
    """The default value. This value is unused."""
    REQUEST = "REQUEST"
    """The EvaluationItem is a request to evaluate."""
    RESULT = "RESULT"
    """The EvaluationItem is the result of evaluation."""


class SamplingMethod(_common.CaseInSensitiveEnum):
    """Represents the sampling method for a BigQuery request set."""

    UNSPECIFIED = "UNSPECIFIED"
    """Sampling method is unspecified."""
    RANDOM = "RANDOM"
    """Sampling method is random."""


class RubricContentType(_common.CaseInSensitiveEnum):
    """Specifies the type of rubric content to generate."""

    PROPERTY = "PROPERTY"
    """Generate rubrics based on properties."""
    NL_QUESTION_ANSWER = "NL_QUESTION_ANSWER"
    """Generate rubrics in an NL question answer format."""
    PYTHON_CODE_ASSERTION = "PYTHON_CODE_ASSERTION"
    """Generate rubrics in a unit test format."""


class EvaluationRunState(_common.CaseInSensitiveEnum):
    """Represents the state of an evaluation run."""

    UNSPECIFIED = "UNSPECIFIED"
    """Evaluation run state is unspecified."""
    PENDING = "PENDING"
    """Evaluation run is pending."""
    RUNNING = "RUNNING"
    """Evaluation run is in progress."""
    SUCCEEDED = "SUCCEEDED"
    """Evaluation run has succeeded."""
    FAILED = "FAILED"
    """Evaluation run failed."""
    CANCELLED = "CANCELLED"
    """Evaluation run was cancelled."""
    INFERENCE = "INFERENCE"
    """Evaluation run is performing inference."""
    GENERATING_RUBRICS = "GENERATING_RUBRICS"
    """Evaluation run is performing rubric generation."""


class OptimizeTarget(_common.CaseInSensitiveEnum):
    """None"""

    OPTIMIZATION_TARGET_GEMINI_NANO = "OPTIMIZATION_TARGET_GEMINI_NANO"
    """The data driven prompt optimizer designer for prompts from Android core API."""


class GenerateMemoriesResponseGeneratedMemoryAction(_common.CaseInSensitiveEnum):
    """The action to take."""

    ACTION_UNSPECIFIED = "ACTION_UNSPECIFIED"
    """The action is unspecified."""
    CREATED = "CREATED"
    """The memory was created."""
    UPDATED = "UPDATED"
    """The memory was updated.

      The `fact` field may not be updated if the existing fact is still accurate.
      """
    DELETED = "DELETED"
    """The memory was deleted."""


class PromptOptimizerMethod(_common.CaseInSensitiveEnum):
    """The method for data driven prompt optimization."""

    VAPO = "VAPO"
    """The default data driven Vertex AI Prompt Optimizer."""
    OPTIMIZATION_TARGET_GEMINI_NANO = "OPTIMIZATION_TARGET_GEMINI_NANO"
    """The data driven prompt optimizer designer for prompts from Android core API."""


class CreateEvaluationItemConfig(_common.BaseModel):
    """Config to create an evaluation item."""

    http_options: Optional[genai_types.HttpOptions] = Field(
        default=None, description="""Used to override HTTP request options."""
    )


class CreateEvaluationItemConfigDict(TypedDict, total=False):
    """Config to create an evaluation item."""

    http_options: Optional[genai_types.HttpOptionsDict]
    """Used to override HTTP request options."""


CreateEvaluationItemConfigOrDict = Union[
    CreateEvaluationItemConfig, CreateEvaluationItemConfigDict
]


class _CreateEvaluationItemParameters(_common.BaseModel):
    """Represents a job that creates an evaluation item."""

    evaluation_item_type: Optional[str] = Field(default=None, description="""""")
    gcs_uri: Optional[str] = Field(default=None, description="""""")
    display_name: Optional[str] = Field(default=None, description="""""")
    config: Optional[CreateEvaluationItemConfig] = Field(
        default=None, description=""""""
    )


class _CreateEvaluationItemParametersDict(TypedDict, total=False):
    """Represents a job that creates an evaluation item."""

    evaluation_item_type: Optional[str]
    """"""

    gcs_uri: Optional[str]
    """"""

    display_name: Optional[str]
    """"""

    config: Optional[CreateEvaluationItemConfigDict]
    """"""


_CreateEvaluationItemParametersOrDict = Union[
    _CreateEvaluationItemParameters, _CreateEvaluationItemParametersDict
]


class PromptTemplateData(_common.BaseModel):
    """Message to hold a prompt template and the values to populate the template."""

    values: Optional[dict[str, genai_types.Content]] = Field(
        default=None, description="""The values for fields in the prompt template."""
    )


class PromptTemplateDataDict(TypedDict, total=False):
    """Message to hold a prompt template and the values to populate the template."""

    values: Optional[dict[str, genai_types.ContentDict]]
    """The values for fields in the prompt template."""


PromptTemplateDataOrDict = Union[PromptTemplateData, PromptTemplateDataDict]


class EvaluationPrompt(_common.BaseModel):
    """Represents the prompt to be evaluated."""

    text: Optional[str] = Field(default=None, description="""Text prompt.""")
    value: Optional[dict[str, Any]] = Field(
        default=None,
        description="""Fields and values that can be used to populate the prompt template.""",
    )
    prompt_template_data: Optional[PromptTemplateData] = Field(
        default=None, description="""Prompt template data."""
    )


class EvaluationPromptDict(TypedDict, total=False):
    """Represents the prompt to be evaluated."""

    text: Optional[str]
    """Text prompt."""

    value: Optional[dict[str, Any]]
    """Fields and values that can be used to populate the prompt template."""

    prompt_template_data: Optional[PromptTemplateDataDict]
    """Prompt template data."""


EvaluationPromptOrDict = Union[EvaluationPrompt, EvaluationPromptDict]


class CandidateResponse(_common.BaseModel):
    """Responses from model or agent."""

    candidate: Optional[str] = Field(
        default=None,
        description="""The name of the candidate that produced the response.""",
    )
    text: Optional[str] = Field(default=None, description="""The text response.""")
    value: Optional[dict[str, Any]] = Field(
        default=None,
        description="""Fields and values that can be used to populate the response template.""",
    )
    events: Optional[list[genai_types.Content]] = Field(
        default=None,
        description="""Intermediate events (such as tool calls and responses) that led to the final response.""",
    )


class CandidateResponseDict(TypedDict, total=False):
    """Responses from model or agent."""

    candidate: Optional[str]
    """The name of the candidate that produced the response."""

    text: Optional[str]
    """The text response."""

    value: Optional[dict[str, Any]]
    """Fields and values that can be used to populate the response template."""

    events: Optional[list[genai_types.ContentDict]]
    """Intermediate events (such as tool calls and responses) that led to the final response."""


CandidateResponseOrDict = Union[CandidateResponse, CandidateResponseDict]


class EvaluationItemRequest(_common.BaseModel):
    """Single evaluation request."""

    prompt: Optional[EvaluationPrompt] = Field(
        default=None, description="""The request/prompt to evaluate."""
    )
    golden_response: Optional[CandidateResponse] = Field(
        default=None, description="""The ideal response or ground truth."""
    )
    rubrics: Optional[dict[str, "RubricGroup"]] = Field(
        default=None,
        description="""Named groups of rubrics associated with this prompt. The key is a user-defined name for the rubric group.""",
    )
    candidate_responses: Optional[list[CandidateResponse]] = Field(
        default=None,
        description="""Responses from model under test and other baseline models for comparison.""",
    )


class EvaluationItemRequestDict(TypedDict, total=False):
    """Single evaluation request."""

    prompt: Optional[EvaluationPromptDict]
    """The request/prompt to evaluate."""

    golden_response: Optional[CandidateResponseDict]
    """The ideal response or ground truth."""

    rubrics: Optional[dict[str, "RubricGroupDict"]]
    """Named groups of rubrics associated with this prompt. The key is a user-defined name for the rubric group."""

    candidate_responses: Optional[list[CandidateResponseDict]]
    """Responses from model under test and other baseline models for comparison."""


EvaluationItemRequestOrDict = Union[EvaluationItemRequest, EvaluationItemRequestDict]


class EvaluationItemResult(_common.BaseModel):
    """Represents the result of an evaluation item."""

    evaluation_request: Optional[str] = Field(
        default=None, description="""The request item that was evaluated."""
    )
    evaluation_run: Optional[str] = Field(
        default=None,
        description="""The evaluation run that was used to generate the result.""",
    )
    request: Optional[EvaluationItemRequest] = Field(
        default=None, description="""The request that was evaluated."""
    )
    metric: Optional[str] = Field(
        default=None, description="""The metric that was evaluated."""
    )
    candidate_results: Optional[list[evals_types.CandidateResult]] = Field(
        default=None, description="""TThe results for the metric."""
    )
    metadata: Optional[dict[str, Any]] = Field(
        default=None, description="""Metadata about the evaluation result."""
    )


class EvaluationItemResultDict(TypedDict, total=False):
    """Represents the result of an evaluation item."""

    evaluation_request: Optional[str]
    """The request item that was evaluated."""

    evaluation_run: Optional[str]
    """The evaluation run that was used to generate the result."""

    request: Optional[EvaluationItemRequestDict]
    """The request that was evaluated."""

    metric: Optional[str]
    """The metric that was evaluated."""

    candidate_results: Optional[list[evals_types.CandidateResult]]
    """TThe results for the metric."""

    metadata: Optional[dict[str, Any]]
    """Metadata about the evaluation result."""


EvaluationItemResultOrDict = Union[EvaluationItemResult, EvaluationItemResultDict]


class EvaluationItem(_common.BaseModel):
    """EvaluationItem is a single evaluation request or result.

    The content of an EvaluationItem is immutable - it cannot be updated once
    created. EvaluationItems can be deleted when no longer needed.
    """

    name: Optional[str] = Field(
        default=None, description="""The resource name of the EvaluationItem."""
    )
    display_name: Optional[str] = Field(
        default=None, description="""The display name of the EvaluationItem."""
    )
    metadata: Optional[dict[str, Any]] = Field(
        default=None, description="""Metadata for the EvaluationItem."""
    )
    labels: Optional[dict[str, str]] = Field(
        default=None, description="""Labels for the EvaluationItem."""
    )
    evaluation_item_type: Optional[EvaluationItemType] = Field(
        default=None, description="""The type of the EvaluationItem."""
    )
    evaluation_request: Optional[EvaluationItemRequest] = Field(
        default=None, description="""The request to evaluate."""
    )
    evaluation_response: Optional[EvaluationItemResult] = Field(
        default=None, description="""The response from evaluation."""
    )
    gcs_uri: Optional[str] = Field(
        default=None,
        description="""The Cloud Storage object where the request or response is stored.""",
    )
    create_time: Optional[datetime.datetime] = Field(
        default=None, description="""Timestamp when this item was created."""
    )
    error: Optional[genai_types.GoogleRpcStatus] = Field(
        default=None, description="""Error for the evaluation item."""
    )

    # TODO(b/448806531): Remove all the overridden _from_response methods once the
    # ticket is resolved and published.
    @classmethod
    def _from_response(
        cls: typing.Type["EvaluationItem"],
        *,
        response: dict[str, object],
        kwargs: dict[str, object],
    ) -> "EvaluationItem":
        """Converts a dictionary response into a EvaluationItem object."""

        response = _camel_key_to_snake(response)
        result = super()._from_response(response=response, kwargs=kwargs)
        return result


class EvaluationItemDict(TypedDict, total=False):
    """EvaluationItem is a single evaluation request or result.

    The content of an EvaluationItem is immutable - it cannot be updated once
    created. EvaluationItems can be deleted when no longer needed.
    """

    name: Optional[str]
    """The resource name of the EvaluationItem."""

    display_name: Optional[str]
    """The display name of the EvaluationItem."""

    metadata: Optional[dict[str, Any]]
    """Metadata for the EvaluationItem."""

    labels: Optional[dict[str, str]]
    """Labels for the EvaluationItem."""

    evaluation_item_type: Optional[EvaluationItemType]
    """The type of the EvaluationItem."""

    evaluation_request: Optional[EvaluationItemRequestDict]
    """The request to evaluate."""

    evaluation_response: Optional[EvaluationItemResultDict]
    """The response from evaluation."""

    gcs_uri: Optional[str]
    """The Cloud Storage object where the request or response is stored."""

    create_time: Optional[datetime.datetime]
    """Timestamp when this item was created."""

    error: Optional[genai_types.GoogleRpcStatusDict]
    """Error for the evaluation item."""


EvaluationItemOrDict = Union[EvaluationItem, EvaluationItemDict]


class SamplingConfig(_common.BaseModel):
    """Sampling config for a BigQuery request set."""

    sampling_count: Optional[int] = Field(default=None, description="""""")
    sampling_method: Optional[SamplingMethod] = Field(default=None, description="""""")
    sampling_duration: Optional[str] = Field(default=None, description="""""")


class SamplingConfigDict(TypedDict, total=False):
    """Sampling config for a BigQuery request set."""

    sampling_count: Optional[int]
    """"""

    sampling_method: Optional[SamplingMethod]
    """"""

    sampling_duration: Optional[str]
    """"""


SamplingConfigOrDict = Union[SamplingConfig, SamplingConfigDict]


class BigQueryRequestSet(_common.BaseModel):
    """Represents a BigQuery request set."""

    uri: Optional[str] = Field(default=None, description="""""")
    prompt_column: Optional[str] = Field(
        default=None,
        description="""The column name of the prompt in the BigQuery table. Used for EvaluationRun only.""",
    )
    rubrics_column: Optional[str] = Field(
        default=None,
        description="""The column name of the rubrics in the BigQuery table. Used for EvaluationRun only.""",
    )
    candidate_response_columns: Optional[dict[str, str]] = Field(
        default=None,
        description="""The column name of the response candidates in the BigQuery table. Used for EvaluationRun only.""",
    )
    sampling_config: Optional[SamplingConfig] = Field(
        default=None,
        description="""The sampling config for the BigQuery request set. Used for EvaluationRun only.""",
    )


class BigQueryRequestSetDict(TypedDict, total=False):
    """Represents a BigQuery request set."""

    uri: Optional[str]
    """"""

    prompt_column: Optional[str]
    """The column name of the prompt in the BigQuery table. Used for EvaluationRun only."""

    rubrics_column: Optional[str]
    """The column name of the rubrics in the BigQuery table. Used for EvaluationRun only."""

    candidate_response_columns: Optional[dict[str, str]]
    """The column name of the response candidates in the BigQuery table. Used for EvaluationRun only."""

    sampling_config: Optional[SamplingConfigDict]
    """The sampling config for the BigQuery request set. Used for EvaluationRun only."""


BigQueryRequestSetOrDict = Union[BigQueryRequestSet, BigQueryRequestSetDict]


class EvaluationRunDataSource(_common.BaseModel):
    """Represents an evaluation run data source."""

    evaluation_set: Optional[str] = Field(default=None, description="""""")
    bigquery_request_set: Optional[BigQueryRequestSet] = Field(
        default=None, description=""""""
    )


class EvaluationRunDataSourceDict(TypedDict, total=False):
    """Represents an evaluation run data source."""

    evaluation_set: Optional[str]
    """"""

    bigquery_request_set: Optional[BigQueryRequestSetDict]
    """"""


EvaluationRunDataSourceOrDict = Union[
    EvaluationRunDataSource, EvaluationRunDataSourceDict
]


class PredefinedMetricSpec(_common.BaseModel):
    """Spec for predefined metric."""

    metric_spec_name: Optional[str] = Field(
        default=None,
        description="""The name of a pre-defined metric, such as "instruction_following_v1" or
      "text_quality_v1".""",
    )
    metric_spec_parameters: Optional[dict] = Field(
        default=None,
        description="""The parameters needed to run the pre-defined metric.""",
    )


class PredefinedMetricSpecDict(TypedDict, total=False):
    """Spec for predefined metric."""

    metric_spec_name: Optional[str]
    """The name of a pre-defined metric, such as "instruction_following_v1" or
      "text_quality_v1"."""

    metric_spec_parameters: Optional[dict]
    """The parameters needed to run the pre-defined metric."""


PredefinedMetricSpecOrDict = Union[PredefinedMetricSpec, PredefinedMetricSpecDict]


class RubricGenerationSpec(_common.BaseModel):
    """Spec for generating rubrics."""

    prompt_template: Optional[str] = Field(
        default=None,
        description="""Template for the prompt used to generate rubrics.
      The details should be updated based on the most-recent recipe requirements.""",
    )
    generator_model_config: Optional[genai_types.AutoraterConfig] = Field(
        default=None,
        description="""Configuration for the model used in rubric generation.
      Configs including sampling count and base model can be specified here.
      Flipping is not supported for rubric generation.""",
    )
    rubric_content_type: Optional[RubricContentType] = Field(
        default=None, description="""The type of rubric content to be generated."""
    )
    rubric_type_ontology: Optional[list[str]] = Field(
        default=None,
        description="""An optional, pre-defined list of allowed types for generated rubrics.
      If this field is provided, it implies `include_rubric_type` should be true,
      and the generated rubric types should be chosen from this ontology.""",
    )


class RubricGenerationSpecDict(TypedDict, total=False):
    """Spec for generating rubrics."""

    prompt_template: Optional[str]
    """Template for the prompt used to generate rubrics.
      The details should be updated based on the most-recent recipe requirements."""

    generator_model_config: Optional[genai_types.AutoraterConfigDict]
    """Configuration for the model used in rubric generation.
      Configs including sampling count and base model can be specified here.
      Flipping is not supported for rubric generation."""

    rubric_content_type: Optional[RubricContentType]
    """The type of rubric content to be generated."""

    rubric_type_ontology: Optional[list[str]]
    """An optional, pre-defined list of allowed types for generated rubrics.
      If this field is provided, it implies `include_rubric_type` should be true,
      and the generated rubric types should be chosen from this ontology."""


RubricGenerationSpecOrDict = Union[RubricGenerationSpec, RubricGenerationSpecDict]


class LLMBasedMetricSpec(_common.BaseModel):
    """Specification for an LLM based metric."""

    metric_prompt_template: Optional[str] = Field(
        default=None, description="""Template for the prompt sent to the judge model."""
    )
    system_instruction: Optional[str] = Field(
        default=None, description="""System instruction for the judge model."""
    )
    judge_autorater_config: Optional[genai_types.AutoraterConfig] = Field(
        default=None,
        description="""Optional configuration for the judge LLM (Autorater).""",
    )
    rubric_group_key: Optional[str] = Field(
        default=None,
        description="""Use a pre-defined group of rubrics associated with the input.
      Refers to a key in the rubric_groups map of EvaluationInstance.""",
    )
    predefined_rubric_generation_spec: Optional[PredefinedMetricSpec] = Field(
        default=None,
        description="""Dynamically generate rubrics using a predefined spec.""",
    )
    rubric_generation_spec: Optional[RubricGenerationSpec] = Field(
        default=None,
        description="""Dynamically generate rubrics using this specification.""",
    )


class LLMBasedMetricSpecDict(TypedDict, total=False):
    """Specification for an LLM based metric."""

    metric_prompt_template: Optional[str]
    """Template for the prompt sent to the judge model."""

    system_instruction: Optional[str]
    """System instruction for the judge model."""

    judge_autorater_config: Optional[genai_types.AutoraterConfigDict]
    """Optional configuration for the judge LLM (Autorater)."""

    rubric_group_key: Optional[str]
    """Use a pre-defined group of rubrics associated with the input.
      Refers to a key in the rubric_groups map of EvaluationInstance."""

    predefined_rubric_generation_spec: Optional[PredefinedMetricSpecDict]
    """Dynamically generate rubrics using a predefined spec."""

    rubric_generation_spec: Optional[RubricGenerationSpecDict]
    """Dynamically generate rubrics using this specification."""


LLMBasedMetricSpecOrDict = Union[LLMBasedMetricSpec, LLMBasedMetricSpecDict]


class CustomCodeExecutionSpec(_common.BaseModel):
    """Specificies a metric that is computed by running user-defined Python functions remotely."""

    remote_custom_function: Optional[str] = Field(
        default=None,
        description="""A string representing a user-defined function for evaluation.
  Expected user to define the following function, e.g.:
    def evaluate(instance: dict[str, Any]) -> float:
  Please include this function signature in the code snippet.
  Instance is the evaluation instance, any fields populated in the instance
  are available to the function as instance[field_name].""",
    )


class CustomCodeExecutionSpecDict(TypedDict, total=False):
    """Specificies a metric that is computed by running user-defined Python functions remotely."""

    remote_custom_function: Optional[str]
    """A string representing a user-defined function for evaluation.
  Expected user to define the following function, e.g.:
    def evaluate(instance: dict[str, Any]) -> float:
  Please include this function signature in the code snippet.
  Instance is the evaluation instance, any fields populated in the instance
  are available to the function as instance[field_name]."""


CustomCodeExecutionSpecOrDict = Union[
    CustomCodeExecutionSpec, CustomCodeExecutionSpecDict
]


class UnifiedMetric(_common.BaseModel):
    """The unified metric used for evaluation."""

    bleu_spec: Optional[genai_types.BleuSpec] = Field(
        default=None, description="""The Bleu metric spec."""
    )
    rouge_spec: Optional[genai_types.RougeSpec] = Field(
        default=None, description="""The rouge metric spec."""
    )
    pointwise_metric_spec: Optional[genai_types.PointwiseMetricSpec] = Field(
        default=None, description="""The pointwise metric spec."""
    )
    llm_based_metric_spec: Optional[LLMBasedMetricSpec] = Field(
        default=None, description="""The spec for an LLM based metric."""
    )
    custom_code_execution_spec: Optional[CustomCodeExecutionSpec] = Field(
        default=None, description="""The spec for a custom code execution metric."""
    )
    predefined_metric_spec: Optional[PredefinedMetricSpec] = Field(
        default=None, description="""The spec for a pre-defined metric."""
    )


class UnifiedMetricDict(TypedDict, total=False):
    """The unified metric used for evaluation."""

    bleu_spec: Optional[genai_types.BleuSpecDict]
    """The Bleu metric spec."""

    rouge_spec: Optional[genai_types.RougeSpecDict]
    """The rouge metric spec."""

    pointwise_metric_spec: Optional[genai_types.PointwiseMetricSpecDict]
    """The pointwise metric spec."""

    llm_based_metric_spec: Optional[LLMBasedMetricSpecDict]
    """The spec for an LLM based metric."""

    custom_code_execution_spec: Optional[CustomCodeExecutionSpecDict]
    """The spec for a custom code execution metric."""

    predefined_metric_spec: Optional[PredefinedMetricSpecDict]
    """The spec for a pre-defined metric."""


UnifiedMetricOrDict = Union[UnifiedMetric, UnifiedMetricDict]


class EvaluationRunMetric(_common.BaseModel):
    """The metric used for evaluation run."""

    metric: Optional[str] = Field(
        default=None, description="""The name of the metric."""
    )
    metric_config: Optional[UnifiedMetric] = Field(
        default=None, description="""The unified metric used for evaluation run."""
    )


class EvaluationRunMetricDict(TypedDict, total=False):
    """The metric used for evaluation run."""

    metric: Optional[str]
    """The name of the metric."""

    metric_config: Optional[UnifiedMetricDict]
    """The unified metric used for evaluation run."""


EvaluationRunMetricOrDict = Union[EvaluationRunMetric, EvaluationRunMetricDict]


class EvaluationRunConfig(_common.BaseModel):
    """The evaluation configuration used for the evaluation run."""

    metrics: Optional[list[EvaluationRunMetric]] = Field(
        default=None,
        description="""The metrics to be calculated in the evaluation run.""",
    )
    output_config: Optional[genai_types.OutputConfig] = Field(
        default=None, description="""The output config for the evaluation run."""
    )
    autorater_config: Optional[genai_types.AutoraterConfig] = Field(
        default=None, description="""The autorater config for the evaluation run."""
    )


class EvaluationRunConfigDict(TypedDict, total=False):
    """The evaluation configuration used for the evaluation run."""

    metrics: Optional[list[EvaluationRunMetricDict]]
    """The metrics to be calculated in the evaluation run."""

    output_config: Optional[genai_types.OutputConfigDict]
    """The output config for the evaluation run."""

    autorater_config: Optional[genai_types.AutoraterConfigDict]
    """The autorater config for the evaluation run."""


EvaluationRunConfigOrDict = Union[EvaluationRunConfig, EvaluationRunConfigDict]


class CreateEvaluationRunConfig(_common.BaseModel):
    """Config to create an evaluation run."""

    http_options: Optional[genai_types.HttpOptions] = Field(
        default=None, description="""Used to override HTTP request options."""
    )


class CreateEvaluationRunConfigDict(TypedDict, total=False):
    """Config to create an evaluation run."""

    http_options: Optional[genai_types.HttpOptionsDict]
    """Used to override HTTP request options."""


CreateEvaluationRunConfigOrDict = Union[
    CreateEvaluationRunConfig, CreateEvaluationRunConfigDict
]


class _CreateEvaluationRunParameters(_common.BaseModel):
    """Represents a job that creates an evaluation run."""

    name: Optional[str] = Field(default=None, description="""""")
    display_name: Optional[str] = Field(default=None, description="""""")
    data_source: Optional[EvaluationRunDataSource] = Field(
        default=None, description=""""""
    )
    evaluation_config: Optional[EvaluationRunConfig] = Field(
        default=None, description=""""""
    )
    labels: Optional[dict[str, str]] = Field(default=None, description="""""")
    inference_configs: Optional[dict[str, "EvaluationRunInferenceConfig"]] = Field(
        default=None, description=""""""
    )
    config: Optional[CreateEvaluationRunConfig] = Field(
        default=None, description=""""""
    )


class _CreateEvaluationRunParametersDict(TypedDict, total=False):
    """Represents a job that creates an evaluation run."""

    name: Optional[str]
    """"""

    display_name: Optional[str]
    """"""

    data_source: Optional[EvaluationRunDataSourceDict]
    """"""

    evaluation_config: Optional[EvaluationRunConfigDict]
    """"""

    labels: Optional[dict[str, str]]
    """"""

    inference_configs: Optional[dict[str, "EvaluationRunInferenceConfigDict"]]
    """"""

    config: Optional[CreateEvaluationRunConfigDict]
    """"""


_CreateEvaluationRunParametersOrDict = Union[
    _CreateEvaluationRunParameters, _CreateEvaluationRunParametersDict
]


class SummaryMetric(_common.BaseModel):
    """Represents a summary metric for an evaluation run."""

    metrics: Optional[dict[str, Any]] = Field(
        default=None, description="""Map of metric name to metric value."""
    )
    total_items: Optional[int] = Field(
        default=None, description="""The total number of items that were evaluated."""
    )
    failed_items: Optional[int] = Field(
        default=None, description="""The number of items that failed to be evaluated."""
    )


class SummaryMetricDict(TypedDict, total=False):
    """Represents a summary metric for an evaluation run."""

    metrics: Optional[dict[str, Any]]
    """Map of metric name to metric value."""

    total_items: Optional[int]
    """The total number of items that were evaluated."""

    failed_items: Optional[int]
    """The number of items that failed to be evaluated."""


SummaryMetricOrDict = Union[SummaryMetric, SummaryMetricDict]


class EvaluationRunResults(_common.BaseModel):
    """Represents the results of an evaluation run."""

    evaluation_set: Optional[str] = Field(
        default=None,
        description="""The evaluation set where item level results are stored.""",
    )
    summary_metrics: Optional[SummaryMetric] = Field(
        default=None, description="""The summary metrics for the evaluation run."""
    )


class EvaluationRunResultsDict(TypedDict, total=False):
    """Represents the results of an evaluation run."""

    evaluation_set: Optional[str]
    """The evaluation set where item level results are stored."""

    summary_metrics: Optional[SummaryMetricDict]
    """The summary metrics for the evaluation run."""


EvaluationRunResultsOrDict = Union[EvaluationRunResults, EvaluationRunResultsDict]


class ResponseCandidateResult(_common.BaseModel):
    """Aggregated metric results for a single response candidate of an EvalCase."""

    response_index: Optional[int] = Field(
        default=None,
        description="""Index of the response candidate this result pertains to.""",
    )
    metric_results: Optional[dict[str, "EvalCaseMetricResult"]] = Field(
        default=None,
        description="""A dictionary of metric results for this response candidate, keyed by metric name.""",
    )


class ResponseCandidateResultDict(TypedDict, total=False):
    """Aggregated metric results for a single response candidate of an EvalCase."""

    response_index: Optional[int]
    """Index of the response candidate this result pertains to."""

    metric_results: Optional[dict[str, "EvalCaseMetricResultDict"]]
    """A dictionary of metric results for this response candidate, keyed by metric name."""


ResponseCandidateResultOrDict = Union[
    ResponseCandidateResult, ResponseCandidateResultDict
]


class EvalCaseResult(_common.BaseModel):
    """Eval result for a single evaluation case."""

    eval_case_index: Optional[int] = Field(
        default=None, description="""Index of the evaluation case."""
    )
    response_candidate_results: Optional[list[ResponseCandidateResult]] = Field(
        default=None,
        description="""A list of results, one for each response candidate of the EvalCase.""",
    )


class EvalCaseResultDict(TypedDict, total=False):
    """Eval result for a single evaluation case."""

    eval_case_index: Optional[int]
    """Index of the evaluation case."""

    response_candidate_results: Optional[list[ResponseCandidateResultDict]]
    """A list of results, one for each response candidate of the EvalCase."""


EvalCaseResultOrDict = Union[EvalCaseResult, EvalCaseResultDict]


class AggregatedMetricResult(_common.BaseModel):
    """Evaluation result for a single metric for an evaluation dataset."""

    metric_name: Optional[str] = Field(
        default=None, description="""Name of the metric."""
    )
    num_cases_total: Optional[int] = Field(
        default=None, description="""Total number of cases in the dataset."""
    )
    num_cases_valid: Optional[int] = Field(
        default=None, description="""Number of valid cases in the dataset."""
    )
    num_cases_error: Optional[int] = Field(
        default=None, description="""Number of cases with errors in the dataset."""
    )
    mean_score: Optional[float] = Field(
        default=None, description="""Mean score of the metric."""
    )
    stdev_score: Optional[float] = Field(
        default=None, description="""Standard deviation of the metric."""
    )
    pass_rate: Optional[float] = Field(
        default=None,
        description="""Pass rate of the adaptive rubric metric. Calculated as the number of cases where all criteria passed divided by the total number of valid cases. A case is passing if it has a score of 1.0.""",
    )

    # Allow extra fields to support custom aggregation stats.
    model_config = ConfigDict(extra="allow")


class AggregatedMetricResultDict(TypedDict, total=False):
    """Evaluation result for a single metric for an evaluation dataset."""

    metric_name: Optional[str]
    """Name of the metric."""

    num_cases_total: Optional[int]
    """Total number of cases in the dataset."""

    num_cases_valid: Optional[int]
    """Number of valid cases in the dataset."""

    num_cases_error: Optional[int]
    """Number of cases with errors in the dataset."""

    mean_score: Optional[float]
    """Mean score of the metric."""

    stdev_score: Optional[float]
    """Standard deviation of the metric."""

    pass_rate: Optional[float]
    """Pass rate of the adaptive rubric metric. Calculated as the number of cases where all criteria passed divided by the total number of valid cases. A case is passing if it has a score of 1.0."""


AggregatedMetricResultOrDict = Union[AggregatedMetricResult, AggregatedMetricResultDict]


class ResponseCandidate(_common.BaseModel):
    """A model-generated content to the prompt."""

    response: Optional[genai_types.Content] = Field(
        default=None,
        description="""The final model-generated response to the `prompt`.""",
    )


class ResponseCandidateDict(TypedDict, total=False):
    """A model-generated content to the prompt."""

    response: Optional[genai_types.ContentDict]
    """The final model-generated response to the `prompt`."""


ResponseCandidateOrDict = Union[ResponseCandidate, ResponseCandidateDict]


class EvalCase(_common.BaseModel):
    """A comprehensive representation of a GenAI interaction for evaluation."""

    prompt: Optional[genai_types.Content] = Field(
        default=None, description="""The most recent user message (current input)."""
    )
    responses: Optional[list[ResponseCandidate]] = Field(
        default=None,
        description="""Model-generated replies to the last user message in a conversation. Multiple responses are allowed to support use cases such as comparing different model outputs.""",
    )
    reference: Optional[ResponseCandidate] = Field(
        default=None,
        description="""User-provided, golden reference model reply to prompt in context of chat history; Reference for last response in a conversation.""",
    )
    system_instruction: Optional[genai_types.Content] = Field(
        default=None, description="""System instruction for the model."""
    )
    conversation_history: Optional[list[evals_types.Message]] = Field(
        default=None,
        description="""List of all prior messages in the conversation (chat history).""",
    )
    rubric_groups: Optional[dict[str, "RubricGroup"]] = Field(
        default=None,
        description="""Named groups of rubrics associated with this prompt. The key is a user-defined name for the rubric group.""",
    )
    eval_case_id: Optional[str] = Field(
        default=None, description="""Unique identifier for the evaluation case."""
    )
    intermediate_events: Optional[list[evals_types.Event]] = Field(
        default=None,
        description="""This field is experimental and may change in future versions. Intermediate events of a single turn in an agent run or intermediate events of the last turn for multi-turn an agent run.""",
    )
    agent_info: Optional[evals_types.AgentInfo] = Field(
        default=None,
        description="""This field is experimental and may change in future versions. The agent info of the agent under evaluation. This can be extended for multi-agent evaluation.""",
    )
    # Allow extra fields to support custom metric prompts and stay backward compatible.
    model_config = ConfigDict(frozen=True, extra="allow")


class EvalCaseDict(TypedDict, total=False):
    """A comprehensive representation of a GenAI interaction for evaluation."""

    prompt: Optional[genai_types.ContentDict]
    """The most recent user message (current input)."""

    responses: Optional[list[ResponseCandidateDict]]
    """Model-generated replies to the last user message in a conversation. Multiple responses are allowed to support use cases such as comparing different model outputs."""

    reference: Optional[ResponseCandidateDict]
    """User-provided, golden reference model reply to prompt in context of chat history; Reference for last response in a conversation."""

    system_instruction: Optional[genai_types.ContentDict]
    """System instruction for the model."""

    conversation_history: Optional[list[evals_types.Message]]
    """List of all prior messages in the conversation (chat history)."""

    rubric_groups: Optional[dict[str, "RubricGroupDict"]]
    """Named groups of rubrics associated with this prompt. The key is a user-defined name for the rubric group."""

    eval_case_id: Optional[str]
    """Unique identifier for the evaluation case."""

    intermediate_events: Optional[list[evals_types.Event]]
    """This field is experimental and may change in future versions. Intermediate events of a single turn in an agent run or intermediate events of the last turn for multi-turn an agent run."""

    agent_info: Optional[evals_types.AgentInfo]
    """This field is experimental and may change in future versions. The agent info of the agent under evaluation. This can be extended for multi-agent evaluation."""


EvalCaseOrDict = Union[EvalCase, EvalCaseDict]


class GcsSource(_common.BaseModel):
    """Cloud storage source holds the dataset.

    Currently only one Cloud Storage file path is supported.
    """

    uris: Optional[list[str]] = Field(
        default=None,
        description="""Required. Google Cloud Storage URI(-s) to the input file(s). May contain wildcards. For more information on wildcards, see https://cloud.google.com/storage/docs/wildcards.""",
    )


class GcsSourceDict(TypedDict, total=False):
    """Cloud storage source holds the dataset.

    Currently only one Cloud Storage file path is supported.
    """

    uris: Optional[list[str]]
    """Required. Google Cloud Storage URI(-s) to the input file(s). May contain wildcards. For more information on wildcards, see https://cloud.google.com/storage/docs/wildcards."""


GcsSourceOrDict = Union[GcsSource, GcsSourceDict]


class BigQuerySource(_common.BaseModel):
    """The BigQuery location for the input content."""

    input_uri: Optional[str] = Field(
        default=None,
        description="""Required. BigQuery URI to a table, up to 2000 characters long. Accepted forms: * BigQuery path. For example: `bq://projectId.bqDatasetId.bqTableId`.""",
    )


class BigQuerySourceDict(TypedDict, total=False):
    """The BigQuery location for the input content."""

    input_uri: Optional[str]
    """Required. BigQuery URI to a table, up to 2000 characters long. Accepted forms: * BigQuery path. For example: `bq://projectId.bqDatasetId.bqTableId`."""


BigQuerySourceOrDict = Union[BigQuerySource, BigQuerySourceDict]


class EvaluationDataset(_common.BaseModel):
    """The dataset used for evaluation."""

    eval_cases: Optional[list[EvalCase]] = Field(
        default=None, description="""The evaluation cases to be evaluated."""
    )
    eval_dataset_df: Optional[PandasDataFrame] = Field(
        default=None,
        description="""The evaluation dataset in the form of a Pandas DataFrame.""",
    )
    candidate_name: Optional[str] = Field(
        default=None,
        description="""The name of the candidate model or agent for this evaluation dataset.""",
    )
    gcs_source: Optional[GcsSource] = Field(
        default=None, description="""The GCS source for the evaluation dataset."""
    )
    bigquery_source: Optional[BigQuerySource] = Field(
        default=None, description="""The BigQuery source for the evaluation dataset."""
    )

    @model_validator(mode="before")
    @classmethod
    def _check_pandas_installed(cls, data: Any) -> Any:
        if isinstance(data, dict) and data.get("eval_dataset_df") is not None:
            if pd is None:
                logger.warning(
                    "Pandas is not installed, some evals features are not available."
                    " Please install it with `pip install"
                    " google-cloud-aiplatform[evaluation]`."
                )
        return data

    @classmethod
    def load_from_observability_eval_cases(
        cls, cases: list["ObservabilityEvalCase"]
    ) -> "EvaluationDataset":
        """Fetches GenAI Observability data from GCS and parses into a DataFrame."""
        try:
            import pandas as pd
            from .. import _gcs_utils

            formats = []
            requests = []
            responses = []
            system_instructions = []

            for case in cases:
                gcs_utils = _gcs_utils.GcsUtils(
                    case.api_client._api_client if case.api_client else None
                )

                # Associate "observability" data format for given sources
                formats.append("observability")

                # Input source
                request_data = gcs_utils.read_file_contents(case.input_src)
                requests.append(request_data)

                # Output source
                response_data = gcs_utils.read_file_contents(case.output_src)
                responses.append(response_data)

                # System instruction source
                system_instruction_data = ""
                if case.system_instruction_src is not None:
                    system_instruction_data = gcs_utils.read_file_contents(
                        case.system_instruction_src
                    )
                system_instructions.append(system_instruction_data)

            eval_dataset_df = pd.DataFrame(
                {
                    "format": formats,
                    "request": requests,
                    "response": responses,
                    "system_instruction": system_instructions,
                }
            )

        except ImportError as e:
            raise ImportError("Pandas DataFrame library is required.") from e

        return EvaluationDataset(eval_dataset_df=eval_dataset_df)

    def show(self) -> None:
        """Shows the evaluation dataset."""
        from .. import _evals_visualization

        _evals_visualization.display_evaluation_dataset(self)


class EvaluationDatasetDict(TypedDict, total=False):
    """The dataset used for evaluation."""

    eval_cases: Optional[list[EvalCaseDict]]
    """The evaluation cases to be evaluated."""

    eval_dataset_df: Optional[PandasDataFrame]
    """The evaluation dataset in the form of a Pandas DataFrame."""

    candidate_name: Optional[str]
    """The name of the candidate model or agent for this evaluation dataset."""

    gcs_source: Optional[GcsSourceDict]
    """The GCS source for the evaluation dataset."""

    bigquery_source: Optional[BigQuerySourceDict]
    """The BigQuery source for the evaluation dataset."""


EvaluationDatasetOrDict = Union[EvaluationDataset, EvaluationDatasetDict]


class EvaluationRunMetadata(_common.BaseModel):
    """Metadata for an evaluation run."""

    candidate_names: Optional[list[str]] = Field(
        default=None,
        description="""Name of the candidate(s) being evaluated in the evaluation run.""",
    )
    dataset_name: Optional[str] = Field(
        default=None,
        description="""Name of the evaluation dataset used for the evaluation run.""",
    )
    dataset_id: Optional[str] = Field(
        default=None,
        description="""Unique identifier for the evaluation dataset used for the evaluation run.""",
    )
    creation_timestamp: Optional[datetime.datetime] = Field(
        default=None, description="""Creation timestamp of the evaluation run."""
    )


class EvaluationRunMetadataDict(TypedDict, total=False):
    """Metadata for an evaluation run."""

    candidate_names: Optional[list[str]]
    """Name of the candidate(s) being evaluated in the evaluation run."""

    dataset_name: Optional[str]
    """Name of the evaluation dataset used for the evaluation run."""

    dataset_id: Optional[str]
    """Unique identifier for the evaluation dataset used for the evaluation run."""

    creation_timestamp: Optional[datetime.datetime]
    """Creation timestamp of the evaluation run."""


EvaluationRunMetadataOrDict = Union[EvaluationRunMetadata, EvaluationRunMetadataDict]


class EvaluationResult(_common.BaseModel):
    """Result of an evaluation run for an evaluation dataset."""

    eval_case_results: Optional[list[EvalCaseResult]] = Field(
        default=None,
        description="""A list of evaluation results for each evaluation case.""",
    )
    summary_metrics: Optional[list[AggregatedMetricResult]] = Field(
        default=None,
        description="""A list of summary-level evaluation results for each metric.""",
    )
    win_rates: Optional[dict[str, "WinRateStats"]] = Field(
        default=None,
        description="""A dictionary of win rates for each metric, only populated for multi-response evaluation runs.""",
    )
    evaluation_dataset: Optional[list[EvaluationDataset]] = Field(
        default=None,
        description="""The input evaluation dataset(s) for the evaluation run.""",
    )
    metadata: Optional[EvaluationRunMetadata] = Field(
        default=None, description="""Metadata for the evaluation run."""
    )
    agent_info: Optional[evals_types.AgentInfo] = Field(
        default=None,
        description="""This field is experimental and may change in future versions. The agent info of the agent under evaluation. This can be extended for multi-agent evaluation.""",
    )

    def show(self, candidate_names: Optional[List[str]] = None) -> None:
        """Shows the evaluation result.

        Args:
            candidate_names: list of names for the evaluated candidates, used in
            comparison reports.
        """
        from .. import _evals_visualization

        _evals_visualization.display_evaluation_result(self, candidate_names)


class EvaluationResultDict(TypedDict, total=False):
    """Result of an evaluation run for an evaluation dataset."""

    eval_case_results: Optional[list[EvalCaseResultDict]]
    """A list of evaluation results for each evaluation case."""

    summary_metrics: Optional[list[AggregatedMetricResultDict]]
    """A list of summary-level evaluation results for each metric."""

    win_rates: Optional[dict[str, "WinRateStatsDict"]]
    """A dictionary of win rates for each metric, only populated for multi-response evaluation runs."""

    evaluation_dataset: Optional[list[EvaluationDatasetDict]]
    """The input evaluation dataset(s) for the evaluation run."""

    metadata: Optional[EvaluationRunMetadataDict]
    """Metadata for the evaluation run."""

    agent_info: Optional[evals_types.AgentInfo]
    """This field is experimental and may change in future versions. The agent info of the agent under evaluation. This can be extended for multi-agent evaluation."""


EvaluationResultOrDict = Union[EvaluationResult, EvaluationResultDict]


class EvaluationRun(_common.BaseModel):
    """Represents an evaluation run."""

    name: Optional[str] = Field(default=None, description="""""")
    display_name: Optional[str] = Field(default=None, description="""""")
    metadata: Optional[dict[str, Any]] = Field(default=None, description="""""")
    create_time: Optional[datetime.datetime] = Field(default=None, description="""""")
    completion_time: Optional[datetime.datetime] = Field(
        default=None, description=""""""
    )
    state: Optional[EvaluationRunState] = Field(default=None, description="""""")
    evaluation_set_snapshot: Optional[str] = Field(default=None, description="""""")
    error: Optional[genai_types.GoogleRpcStatus] = Field(
        default=None, description=""""""
    )
    data_source: Optional[EvaluationRunDataSource] = Field(
        default=None, description=""""""
    )
    evaluation_run_results: Optional[EvaluationRunResults] = Field(
        default=None, description="""The evaluation run formatted results."""
    )
    evaluation_item_results: Optional[EvaluationResult] = Field(
        default=None,
        description="""The parsed EvaluationItem results for the evaluation run. This is only populated when include_evaluation_items is set to True.""",
    )
    evaluation_config: Optional[EvaluationRunConfig] = Field(
        default=None, description="""The evaluation config for the evaluation run."""
    )
    inference_configs: Optional[dict[str, "EvaluationRunInferenceConfig"]] = Field(
        default=None,
        description="""This field is experimental and may change in future versions. The inference configs for the evaluation run.""",
    )
    labels: Optional[dict[str, str]] = Field(default=None, description="""""")

    # TODO(b/448806531): Remove all the overridden _from_response methods once the
    # ticket is resolved and published.
    @classmethod
    def _from_response(
        cls: typing.Type["EvaluationRun"],
        *,
        response: dict[str, object],
        kwargs: dict[str, object],
    ) -> "EvaluationRun":
        """Converts a dictionary response into a EvaluationRun object."""

        snaked_response = _camel_key_to_snake(response)
        if (
            "evaluation_run_results" in response
            and "summaryMetrics" in response["evaluation_run_results"]
        ):
            snaked_response["evaluation_run_results"]["summary_metrics"] = response[
                "evaluation_run_results"
            ]["summaryMetrics"]
        result = super()._from_response(response=snaked_response, kwargs=kwargs)
        return result

    def show(self) -> None:
        """Shows the evaluation result."""
        from .. import _evals_visualization

        if self.state == "SUCCEEDED":
            if self.evaluation_item_results is not None:
                _evals_visualization.display_evaluation_result(
                    self.evaluation_item_results, None
                )
            else:
                logger.warning(
                    "Evaluation Run succeeded but no evaluation item results found. To display results, please set include_evaluation_items to True when calling get_evaluation_run()."
                )
        else:
            _evals_visualization.display_evaluation_run_status(self)


class EvaluationRunDict(TypedDict, total=False):
    """Represents an evaluation run."""

    name: Optional[str]
    """"""

    display_name: Optional[str]
    """"""

    metadata: Optional[dict[str, Any]]
    """"""

    create_time: Optional[datetime.datetime]
    """"""

    completion_time: Optional[datetime.datetime]
    """"""

    state: Optional[EvaluationRunState]
    """"""

    evaluation_set_snapshot: Optional[str]
    """"""

    error: Optional[genai_types.GoogleRpcStatusDict]
    """"""

    data_source: Optional[EvaluationRunDataSourceDict]
    """"""

    evaluation_run_results: Optional[EvaluationRunResultsDict]
    """The evaluation run formatted results."""

    evaluation_item_results: Optional[EvaluationResultDict]
    """The parsed EvaluationItem results for the evaluation run. This is only populated when include_evaluation_items is set to True."""

    evaluation_config: Optional[EvaluationRunConfigDict]
    """The evaluation config for the evaluation run."""

    inference_configs: Optional[dict[str, "EvaluationRunInferenceConfigDict"]]
    """This field is experimental and may change in future versions. The inference configs for the evaluation run."""

    labels: Optional[dict[str, str]]
    """"""


EvaluationRunOrDict = Union[EvaluationRun, EvaluationRunDict]


class CreateEvaluationSetConfig(_common.BaseModel):
    """Config to create an evaluation set."""

    http_options: Optional[genai_types.HttpOptions] = Field(
        default=None, description="""Used to override HTTP request options."""
    )


class CreateEvaluationSetConfigDict(TypedDict, total=False):
    """Config to create an evaluation set."""

    http_options: Optional[genai_types.HttpOptionsDict]
    """Used to override HTTP request options."""


CreateEvaluationSetConfigOrDict = Union[
    CreateEvaluationSetConfig, CreateEvaluationSetConfigDict
]


class _CreateEvaluationSetParameters(_common.BaseModel):
    """Represents a job that creates an evaluation set."""

    evaluation_items: Optional[list[str]] = Field(default=None, description="""""")
    display_name: Optional[str] = Field(default=None, description="""""")
    config: Optional[CreateEvaluationSetConfig] = Field(
        default=None, description=""""""
    )


class _CreateEvaluationSetParametersDict(TypedDict, total=False):
    """Represents a job that creates an evaluation set."""

    evaluation_items: Optional[list[str]]
    """"""

    display_name: Optional[str]
    """"""

    config: Optional[CreateEvaluationSetConfigDict]
    """"""


_CreateEvaluationSetParametersOrDict = Union[
    _CreateEvaluationSetParameters, _CreateEvaluationSetParametersDict
]


class EvaluationSet(_common.BaseModel):
    """Represents an evaluation set."""

    name: Optional[str] = Field(
        default=None, description="""The resource name of the evaluation set."""
    )
    display_name: Optional[str] = Field(
        default=None, description="""The display name of the evaluation set."""
    )
    evaluation_items: Optional[list[str]] = Field(
        default=None,
        description="""The EvaluationItems that are part of this dataset.""",
    )
    create_time: Optional[datetime.datetime] = Field(
        default=None, description="""The create time of the evaluation set."""
    )
    update_time: Optional[datetime.datetime] = Field(
        default=None, description="""The update time of the evaluation set."""
    )
    metadata: Optional[dict[str, Any]] = Field(
        default=None, description="""The metadata of the evaluation set."""
    )


class EvaluationSetDict(TypedDict, total=False):
    """Represents an evaluation set."""

    name: Optional[str]
    """The resource name of the evaluation set."""

    display_name: Optional[str]
    """The display name of the evaluation set."""

    evaluation_items: Optional[list[str]]
    """The EvaluationItems that are part of this dataset."""

    create_time: Optional[datetime.datetime]
    """The create time of the evaluation set."""

    update_time: Optional[datetime.datetime]
    """The update time of the evaluation set."""

    metadata: Optional[dict[str, Any]]
    """The metadata of the evaluation set."""


EvaluationSetOrDict = Union[EvaluationSet, EvaluationSetDict]


class BleuInstance(_common.BaseModel):
    """Bleu instance."""

    prediction: Optional[str] = Field(
        default=None, description="""Required. Output of the evaluated model."""
    )
    reference: Optional[str] = Field(
        default=None,
        description="""Required. Ground truth used to compare against the prediction.""",
    )


class BleuInstanceDict(TypedDict, total=False):
    """Bleu instance."""

    prediction: Optional[str]
    """Required. Output of the evaluated model."""

    reference: Optional[str]
    """Required. Ground truth used to compare against the prediction."""


BleuInstanceOrDict = Union[BleuInstance, BleuInstanceDict]


class BleuInput(_common.BaseModel):

    instances: Optional[list[BleuInstance]] = Field(
        default=None, description="""Required. Repeated bleu instances."""
    )
    metric_spec: Optional[genai_types.BleuSpec] = Field(
        default=None, description="""Required. Spec for bleu score metric."""
    )


class BleuInputDict(TypedDict, total=False):

    instances: Optional[list[BleuInstanceDict]]
    """Required. Repeated bleu instances."""

    metric_spec: Optional[genai_types.BleuSpecDict]
    """Required. Spec for bleu score metric."""


BleuInputOrDict = Union[BleuInput, BleuInputDict]


class ExactMatchInstance(_common.BaseModel):
    """Exact match instance."""

    prediction: Optional[str] = Field(
        default=None, description="""Required. Output of the evaluated model."""
    )
    reference: Optional[str] = Field(
        default=None,
        description="""Required. Ground truth used to compare against the prediction.""",
    )


class ExactMatchInstanceDict(TypedDict, total=False):
    """Exact match instance."""

    prediction: Optional[str]
    """Required. Output of the evaluated model."""

    reference: Optional[str]
    """Required. Ground truth used to compare against the prediction."""


ExactMatchInstanceOrDict = Union[ExactMatchInstance, ExactMatchInstanceDict]


class ExactMatchSpec(_common.BaseModel):
    """Spec for exact match metric."""

    pass


class ExactMatchSpecDict(TypedDict, total=False):
    """Spec for exact match metric."""

    pass


ExactMatchSpecOrDict = Union[ExactMatchSpec, ExactMatchSpecDict]


class ExactMatchInput(_common.BaseModel):

    instances: Optional[list[ExactMatchInstance]] = Field(
        default=None, description="""Required. Repeated exact match instances."""
    )
    metric_spec: Optional[ExactMatchSpec] = Field(
        default=None, description="""Required. Spec for exact match metric."""
    )


class ExactMatchInputDict(TypedDict, total=False):

    instances: Optional[list[ExactMatchInstanceDict]]
    """Required. Repeated exact match instances."""

    metric_spec: Optional[ExactMatchSpecDict]
    """Required. Spec for exact match metric."""


ExactMatchInputOrDict = Union[ExactMatchInput, ExactMatchInputDict]


class RougeInstance(_common.BaseModel):
    """Rouge instance."""

    prediction: Optional[str] = Field(
        default=None, description="""Required. Output of the evaluated model."""
    )
    reference: Optional[str] = Field(
        default=None,
        description="""Required. Ground truth used to compare against the prediction.""",
    )


class RougeInstanceDict(TypedDict, total=False):
    """Rouge instance."""

    prediction: Optional[str]
    """Required. Output of the evaluated model."""

    reference: Optional[str]
    """Required. Ground truth used to compare against the prediction."""


RougeInstanceOrDict = Union[RougeInstance, RougeInstanceDict]


class RougeInput(_common.BaseModel):
    """Rouge input."""

    instances: Optional[list[RougeInstance]] = Field(
        default=None, description="""Required. Repeated rouge instances."""
    )
    metric_spec: Optional[genai_types.RougeSpec] = Field(
        default=None, description="""Required. Spec for rouge score metric."""
    )


class RougeInputDict(TypedDict, total=False):
    """Rouge input."""

    instances: Optional[list[RougeInstanceDict]]
    """Required. Repeated rouge instances."""

    metric_spec: Optional[genai_types.RougeSpecDict]
    """Required. Spec for rouge score metric."""


RougeInputOrDict = Union[RougeInput, RougeInputDict]


class ContentMap(_common.BaseModel):
    """Map of placeholder in metric prompt template to contents of model input."""

    values: Optional[dict[str, "ContentMapContents"]] = Field(
        default=None, description="""Map of placeholder to contents."""
    )


class ContentMapDict(TypedDict, total=False):
    """Map of placeholder in metric prompt template to contents of model input."""

    values: Optional[dict[str, "ContentMapContents"]]
    """Map of placeholder to contents."""


ContentMapOrDict = Union[ContentMap, ContentMapDict]


class PointwiseMetricInstance(_common.BaseModel):
    """Pointwise metric instance."""

    json_instance: Optional[str] = Field(
        default=None,
        description="""Instance specified as a json string. String key-value pairs are expected in the json_instance to render PointwiseMetricSpec.instance_prompt_template.""",
    )
    content_map_instance: Optional[ContentMap] = Field(
        default=None,
        description="""Key-value contents for the mutlimodality input, including text, image, video, audio, and pdf, etc. The key is placeholder in metric prompt template, and the value is the multimodal content.""",
    )


class PointwiseMetricInstanceDict(TypedDict, total=False):
    """Pointwise metric instance."""

    json_instance: Optional[str]
    """Instance specified as a json string. String key-value pairs are expected in the json_instance to render PointwiseMetricSpec.instance_prompt_template."""

    content_map_instance: Optional[ContentMapDict]
    """Key-value contents for the mutlimodality input, including text, image, video, audio, and pdf, etc. The key is placeholder in metric prompt template, and the value is the multimodal content."""


PointwiseMetricInstanceOrDict = Union[
    PointwiseMetricInstance, PointwiseMetricInstanceDict
]


class PointwiseMetricInput(_common.BaseModel):
    """Pointwise metric input."""

    instance: Optional[PointwiseMetricInstance] = Field(
        default=None, description="""Required. Pointwise metric instance."""
    )
    metric_spec: Optional[genai_types.PointwiseMetricSpec] = Field(
        default=None, description="""Required. Spec for pointwise metric."""
    )


class PointwiseMetricInputDict(TypedDict, total=False):
    """Pointwise metric input."""

    instance: Optional[PointwiseMetricInstanceDict]
    """Required. Pointwise metric instance."""

    metric_spec: Optional[genai_types.PointwiseMetricSpecDict]
    """Required. Spec for pointwise metric."""


PointwiseMetricInputOrDict = Union[PointwiseMetricInput, PointwiseMetricInputDict]


class PairwiseMetricInstance(_common.BaseModel):
    """Pairwise metric instance."""

    json_instance: Optional[str] = Field(
        default=None,
        description="""Instance specified as a json string. String key-value pairs are expected in the json_instance to render PairwiseMetricSpec.instance_prompt_template.""",
    )


class PairwiseMetricInstanceDict(TypedDict, total=False):
    """Pairwise metric instance."""

    json_instance: Optional[str]
    """Instance specified as a json string. String key-value pairs are expected in the json_instance to render PairwiseMetricSpec.instance_prompt_template."""


PairwiseMetricInstanceOrDict = Union[PairwiseMetricInstance, PairwiseMetricInstanceDict]


class PairwiseMetricInput(_common.BaseModel):
    """Pairwise metric instance."""

    instance: Optional[PairwiseMetricInstance] = Field(
        default=None, description="""Required. Pairwise metric instance."""
    )
    metric_spec: Optional[genai_types.PairwiseMetricSpec] = Field(
        default=None, description="""Required. Spec for pairwise metric."""
    )


class PairwiseMetricInputDict(TypedDict, total=False):
    """Pairwise metric instance."""

    instance: Optional[PairwiseMetricInstanceDict]
    """Required. Pairwise metric instance."""

    metric_spec: Optional[genai_types.PairwiseMetricSpecDict]
    """Required. Spec for pairwise metric."""


PairwiseMetricInputOrDict = Union[PairwiseMetricInput, PairwiseMetricInputDict]


class ToolCallValidInstance(_common.BaseModel):
    """Tool call valid instance."""

    prediction: Optional[str] = Field(
        default=None, description="""Required. Output of the evaluated model."""
    )
    reference: Optional[str] = Field(
        default=None,
        description="""Required. Ground truth used to compare against the prediction.""",
    )


class ToolCallValidInstanceDict(TypedDict, total=False):
    """Tool call valid instance."""

    prediction: Optional[str]
    """Required. Output of the evaluated model."""

    reference: Optional[str]
    """Required. Ground truth used to compare against the prediction."""


ToolCallValidInstanceOrDict = Union[ToolCallValidInstance, ToolCallValidInstanceDict]


class ToolCallValidSpec(_common.BaseModel):
    """Spec for tool call valid metric."""

    pass


class ToolCallValidSpecDict(TypedDict, total=False):
    """Spec for tool call valid metric."""

    pass


ToolCallValidSpecOrDict = Union[ToolCallValidSpec, ToolCallValidSpecDict]


class ToolCallValidInput(_common.BaseModel):
    """Tool call valid input."""

    instances: Optional[list[ToolCallValidInstance]] = Field(
        default=None, description="""Required. Repeated tool call valid instances."""
    )
    metric_spec: Optional[ToolCallValidSpec] = Field(
        default=None, description="""Required. Spec for tool call valid metric."""
    )


class ToolCallValidInputDict(TypedDict, total=False):
    """Tool call valid input."""

    instances: Optional[list[ToolCallValidInstanceDict]]
    """Required. Repeated tool call valid instances."""

    metric_spec: Optional[ToolCallValidSpecDict]
    """Required. Spec for tool call valid metric."""


ToolCallValidInputOrDict = Union[ToolCallValidInput, ToolCallValidInputDict]


class ToolNameMatchInstance(_common.BaseModel):
    """Tool name match instance."""

    prediction: Optional[str] = Field(
        default=None, description="""Required. Output of the evaluated model."""
    )
    reference: Optional[str] = Field(
        default=None,
        description="""Required. Ground truth used to compare against the prediction.""",
    )


class ToolNameMatchInstanceDict(TypedDict, total=False):
    """Tool name match instance."""

    prediction: Optional[str]
    """Required. Output of the evaluated model."""

    reference: Optional[str]
    """Required. Ground truth used to compare against the prediction."""


ToolNameMatchInstanceOrDict = Union[ToolNameMatchInstance, ToolNameMatchInstanceDict]


class ToolNameMatchSpec(_common.BaseModel):
    """Spec for tool name match metric."""

    pass


class ToolNameMatchSpecDict(TypedDict, total=False):
    """Spec for tool name match metric."""

    pass


ToolNameMatchSpecOrDict = Union[ToolNameMatchSpec, ToolNameMatchSpecDict]


class ToolNameMatchInput(_common.BaseModel):
    """Tool name match input."""

    instances: Optional[list[ToolNameMatchInstance]] = Field(
        default=None, description="""Required. Repeated tool name match instances."""
    )
    metric_spec: Optional[ToolNameMatchSpec] = Field(
        default=None, description="""Required. Spec for tool name match metric."""
    )


class ToolNameMatchInputDict(TypedDict, total=False):
    """Tool name match input."""

    instances: Optional[list[ToolNameMatchInstanceDict]]
    """Required. Repeated tool name match instances."""

    metric_spec: Optional[ToolNameMatchSpecDict]
    """Required. Spec for tool name match metric."""


ToolNameMatchInputOrDict = Union[ToolNameMatchInput, ToolNameMatchInputDict]


class ToolParameterKeyMatchInstance(_common.BaseModel):
    """Tool parameter key match instance."""

    prediction: Optional[str] = Field(
        default=None, description="""Required. Output of the evaluated model."""
    )
    reference: Optional[str] = Field(
        default=None,
        description="""Required. Ground truth used to compare against the prediction.""",
    )


class ToolParameterKeyMatchInstanceDict(TypedDict, total=False):
    """Tool parameter key match instance."""

    prediction: Optional[str]
    """Required. Output of the evaluated model."""

    reference: Optional[str]
    """Required. Ground truth used to compare against the prediction."""


ToolParameterKeyMatchInstanceOrDict = Union[
    ToolParameterKeyMatchInstance, ToolParameterKeyMatchInstanceDict
]


class ToolParameterKeyMatchSpec(_common.BaseModel):
    """Spec for tool parameter key match metric."""

    pass


class ToolParameterKeyMatchSpecDict(TypedDict, total=False):
    """Spec for tool parameter key match metric."""

    pass


ToolParameterKeyMatchSpecOrDict = Union[
    ToolParameterKeyMatchSpec, ToolParameterKeyMatchSpecDict
]


class ToolParameterKeyMatchInput(_common.BaseModel):
    """Tool parameter key match input."""

    instances: Optional[list[ToolParameterKeyMatchInstance]] = Field(
        default=None,
        description="""Required. Repeated tool parameter key match instances.""",
    )
    metric_spec: Optional[ToolParameterKeyMatchSpec] = Field(
        default=None,
        description="""Required. Spec for tool parameter key match metric.""",
    )


class ToolParameterKeyMatchInputDict(TypedDict, total=False):
    """Tool parameter key match input."""

    instances: Optional[list[ToolParameterKeyMatchInstanceDict]]
    """Required. Repeated tool parameter key match instances."""

    metric_spec: Optional[ToolParameterKeyMatchSpecDict]
    """Required. Spec for tool parameter key match metric."""


ToolParameterKeyMatchInputOrDict = Union[
    ToolParameterKeyMatchInput, ToolParameterKeyMatchInputDict
]


class ToolParameterKVMatchInstance(_common.BaseModel):
    """Tool parameter kv match instance."""

    prediction: Optional[str] = Field(
        default=None, description="""Required. Output of the evaluated model."""
    )
    reference: Optional[str] = Field(
        default=None,
        description="""Required. Ground truth used to compare against the prediction.""",
    )


class ToolParameterKVMatchInstanceDict(TypedDict, total=False):
    """Tool parameter kv match instance."""

    prediction: Optional[str]
    """Required. Output of the evaluated model."""

    reference: Optional[str]
    """Required. Ground truth used to compare against the prediction."""


ToolParameterKVMatchInstanceOrDict = Union[
    ToolParameterKVMatchInstance, ToolParameterKVMatchInstanceDict
]


class ToolParameterKVMatchSpec(_common.BaseModel):
    """Spec for tool parameter kv match metric."""

    use_strict_string_match: Optional[bool] = Field(
        default=None,
        description="""Optional. Whether to use STRICT string match on parameter values.""",
    )


class ToolParameterKVMatchSpecDict(TypedDict, total=False):
    """Spec for tool parameter kv match metric."""

    use_strict_string_match: Optional[bool]
    """Optional. Whether to use STRICT string match on parameter values."""


ToolParameterKVMatchSpecOrDict = Union[
    ToolParameterKVMatchSpec, ToolParameterKVMatchSpecDict
]


class ToolParameterKVMatchInput(_common.BaseModel):
    """Tool parameter kv match input."""

    instances: Optional[list[ToolParameterKVMatchInstance]] = Field(
        default=None,
        description="""Required. Repeated tool parameter key value match instances.""",
    )
    metric_spec: Optional[ToolParameterKVMatchSpec] = Field(
        default=None,
        description="""Required. Spec for tool parameter key value match metric.""",
    )


class ToolParameterKVMatchInputDict(TypedDict, total=False):
    """Tool parameter kv match input."""

    instances: Optional[list[ToolParameterKVMatchInstanceDict]]
    """Required. Repeated tool parameter key value match instances."""

    metric_spec: Optional[ToolParameterKVMatchSpecDict]
    """Required. Spec for tool parameter key value match metric."""


ToolParameterKVMatchInputOrDict = Union[
    ToolParameterKVMatchInput, ToolParameterKVMatchInputDict
]


class MapInstance(_common.BaseModel):
    """Instance data specified as a map."""

    map_instance: Optional[dict[str, evals_types.InstanceData]] = Field(
        default=None, description="""Map of instance data."""
    )


class MapInstanceDict(TypedDict, total=False):
    """Instance data specified as a map."""

    map_instance: Optional[dict[str, evals_types.InstanceData]]
    """Map of instance data."""


MapInstanceOrDict = Union[MapInstance, MapInstanceDict]


class EvaluationInstance(_common.BaseModel):
    """A single instance to be evaluated."""

    prompt: Optional[evals_types.InstanceData] = Field(
        default=None,
        description="""Data used to populate placeholder `prompt` in a metric prompt template.""",
    )
    response: Optional[evals_types.InstanceData] = Field(
        default=None,
        description="""Data used to populate placeholder `response` in a metric prompt template.""",
    )
    reference: Optional[evals_types.InstanceData] = Field(
        default=None,
        description="""Data used to populate placeholder `reference` in a metric prompt template.""",
    )
    other_data: Optional[MapInstance] = Field(
        default=None,
        description="""Other data used to populate placeholders based on their key.""",
    )
    agent_data: Optional[evals_types.AgentData] = Field(
        default=None, description="""Data used for agent evaluation."""
    )
    rubric_groups: Optional[dict[str, "RubricGroup"]] = Field(
        default=None,
        description="""Named groups of rubrics associated with this prompt. The key is a user-defined name for the rubric group.""",
    )


class EvaluationInstanceDict(TypedDict, total=False):
    """A single instance to be evaluated."""

    prompt: Optional[evals_types.InstanceData]
    """Data used to populate placeholder `prompt` in a metric prompt template."""

    response: Optional[evals_types.InstanceData]
    """Data used to populate placeholder `response` in a metric prompt template."""

    reference: Optional[evals_types.InstanceData]
    """Data used to populate placeholder `reference` in a metric prompt template."""

    other_data: Optional[MapInstanceDict]
    """Other data used to populate placeholders based on their key."""

    agent_data: Optional[evals_types.AgentData]
    """Data used for agent evaluation."""

    rubric_groups: Optional[dict[str, "RubricGroupDict"]]
    """Named groups of rubrics associated with this prompt. The key is a user-defined name for the rubric group."""


EvaluationInstanceOrDict = Union[EvaluationInstance, EvaluationInstanceDict]


class EvaluateInstancesConfig(_common.BaseModel):
    """Config for evaluate instances."""

    http_options: Optional[genai_types.HttpOptions] = Field(
        default=None, description="""Used to override HTTP request options."""
    )


class EvaluateInstancesConfigDict(TypedDict, total=False):
    """Config for evaluate instances."""

    http_options: Optional[genai_types.HttpOptionsDict]
    """Used to override HTTP request options."""


EvaluateInstancesConfigOrDict = Union[
    EvaluateInstancesConfig, EvaluateInstancesConfigDict
]


class RubricBasedMetricSpec(_common.BaseModel):
    """Specification for a metric that is based on rubrics."""

    metric_prompt_template: Optional[str] = Field(
        default=None,
        description="""Template for the prompt used by the judge model to evaluate against
      rubrics.""",
    )
    judge_autorater_config: Optional[genai_types.AutoraterConfig] = Field(
        default=None,
        description="""Optional configuration for the judge LLM (Autorater).""",
    )
    inline_rubrics: Optional[list[evals_types.Rubric]] = Field(
        default=None, description="""Use rubrics provided directly in the spec."""
    )
    rubric_group_key: Optional[str] = Field(
        default=None,
        description="""Use a pre-defined group of rubrics associated with the input content.
      This refers to a key in the `rubric_groups` map of
      `RubricEnhancedContents`.""",
    )
    rubric_generation_spec: Optional[RubricGenerationSpec] = Field(
        default=None,
        description="""Dynamically generate rubrics for evaluation using this specification.""",
    )


class RubricBasedMetricSpecDict(TypedDict, total=False):
    """Specification for a metric that is based on rubrics."""

    metric_prompt_template: Optional[str]
    """Template for the prompt used by the judge model to evaluate against
      rubrics."""

    judge_autorater_config: Optional[genai_types.AutoraterConfigDict]
    """Optional configuration for the judge LLM (Autorater)."""

    inline_rubrics: Optional[list[evals_types.Rubric]]
    """Use rubrics provided directly in the spec."""

    rubric_group_key: Optional[str]
    """Use a pre-defined group of rubrics associated with the input content.
      This refers to a key in the `rubric_groups` map of
      `RubricEnhancedContents`."""

    rubric_generation_spec: Optional[RubricGenerationSpecDict]
    """Dynamically generate rubrics for evaluation using this specification."""


RubricBasedMetricSpecOrDict = Union[RubricBasedMetricSpec, RubricBasedMetricSpecDict]


class RubricEnhancedContents(_common.BaseModel):
    """Rubric-enhanced contents for evaluation."""

    prompt: Optional[list[genai_types.Content]] = Field(
        default=None,
        description="""User prompt, using the standard Content type from the Gen AI SDK.""",
    )
    rubric_groups: Optional[dict[str, "RubricGroup"]] = Field(
        default=None,
        description="""Named groups of rubrics associated with this prompt.
      The key is a user-defined name for the rubric group.""",
    )
    response: Optional[list[genai_types.Content]] = Field(
        default=None,
        description="""Response, using the standard Content type from the Gen AI SDK.""",
    )
    other_content: Optional[ContentMap] = Field(
        default=None,
        description="""Other contents needed for the metric.
      For example, if `reference` is needed for the metric, it can be provided
      here.""",
    )


class RubricEnhancedContentsDict(TypedDict, total=False):
    """Rubric-enhanced contents for evaluation."""

    prompt: Optional[list[genai_types.ContentDict]]
    """User prompt, using the standard Content type from the Gen AI SDK."""

    rubric_groups: Optional[dict[str, "RubricGroup"]]
    """Named groups of rubrics associated with this prompt.
      The key is a user-defined name for the rubric group."""

    response: Optional[list[genai_types.ContentDict]]
    """Response, using the standard Content type from the Gen AI SDK."""

    other_content: Optional[ContentMapDict]
    """Other contents needed for the metric.
      For example, if `reference` is needed for the metric, it can be provided
      here."""


RubricEnhancedContentsOrDict = Union[RubricEnhancedContents, RubricEnhancedContentsDict]


class RubricBasedMetricInstance(_common.BaseModel):
    """Defines an instance for Rubric-based metrics, allowing various input formats."""

    json_instance: Optional[str] = Field(
        default=None,
        description="""Specify evaluation fields and their string values in JSON format.""",
    )
    content_map_instance: Optional[ContentMap] = Field(
        default=None,
        description="""Specify evaluation fields and their content values using a ContentMap.""",
    )
    rubric_enhanced_contents: Optional[RubricEnhancedContents] = Field(
        default=None,
        description="""Provide input as Gemini Content along with one or more
      associated rubric groups.""",
    )


class RubricBasedMetricInstanceDict(TypedDict, total=False):
    """Defines an instance for Rubric-based metrics, allowing various input formats."""

    json_instance: Optional[str]
    """Specify evaluation fields and their string values in JSON format."""

    content_map_instance: Optional[ContentMapDict]
    """Specify evaluation fields and their content values using a ContentMap."""

    rubric_enhanced_contents: Optional[RubricEnhancedContentsDict]
    """Provide input as Gemini Content along with one or more
      associated rubric groups."""


RubricBasedMetricInstanceOrDict = Union[
    RubricBasedMetricInstance, RubricBasedMetricInstanceDict
]


class RubricBasedMetricInput(_common.BaseModel):
    """Input for a rubric-based metrics."""

    metric_spec: Optional[RubricBasedMetricSpec] = Field(
        default=None, description="""Specification for the rubric-based metric."""
    )
    instance: Optional[RubricBasedMetricInstance] = Field(
        default=None, description="""The instance to be evaluated."""
    )


class RubricBasedMetricInputDict(TypedDict, total=False):
    """Input for a rubric-based metrics."""

    metric_spec: Optional[RubricBasedMetricSpecDict]
    """Specification for the rubric-based metric."""

    instance: Optional[RubricBasedMetricInstanceDict]
    """The instance to be evaluated."""


RubricBasedMetricInputOrDict = Union[RubricBasedMetricInput, RubricBasedMetricInputDict]


class Metric(_common.BaseModel):
    """The metric used for evaluation."""

    name: Optional[str] = Field(default=None, description="""The name of the metric.""")
    custom_function: Optional[Callable[..., Any]] = Field(
        default=None,
        description="""The custom function that defines the end-to-end logic for metric computation.""",
    )
    remote_custom_function: Optional[str] = Field(
        default=None,
        description="""The evaluation function for the custom code execution metric. This custom code is run remotely in the evaluation service.""",
    )
    prompt_template: Optional[str] = Field(
        default=None, description="""The prompt template for the metric."""
    )
    judge_model: Optional[str] = Field(
        default=None, description="""The judge model for the metric."""
    )
    judge_model_generation_config: Optional[genai_types.GenerationConfig] = Field(
        default=None,
        description="""The generation config for the judge LLM (temperature, top_k, top_p, etc).""",
    )
    judge_model_sampling_count: Optional[int] = Field(
        default=None, description="""The sampling count for the judge model."""
    )
    judge_model_system_instruction: Optional[str] = Field(
        default=None, description="""The system instruction for the judge model."""
    )
    return_raw_output: Optional[bool] = Field(
        default=None,
        description="""Whether to return the raw output from the judge model.""",
    )
    parse_and_reduce_fn: Optional[Callable[..., Any]] = Field(
        default=None,
        description="""The parse and reduce function for the judge model.""",
    )
    aggregate_summary_fn: Optional[Callable[..., Any]] = Field(
        default=None,
        description="""The aggregate summary function for the judge model.""",
    )
    rubric_group_name: Optional[str] = Field(
        default=None,
        description="""The rubric group name for the rubric-based metric.""",
    )
    metric_spec_parameters: Optional[dict[str, Any]] = Field(
        default=None,
        description="""Optional steering instruction parameters for the automated predefined metric.""",
    )

    # Allow extra fields to support metric-specific config fields.
    model_config = ConfigDict(extra="allow")

    _is_predefined: bool = PrivateAttr(default=False)
    """A boolean indicating whether the metric is predefined."""

    _config_source: Optional[str] = PrivateAttr(default=None)
    """An optional string indicating the source of the metric configuration."""

    _version: Optional[str] = PrivateAttr(default=None)
    """An optional string indicating the version of the metric."""

    @model_validator(mode="after")
    @classmethod
    def validate_name(cls, model: "Metric") -> "Metric":
        if not model.name:
            raise ValueError("Metric name cannot be empty.")
        model.name = model.name.lower()
        return model

    def to_yaml_file(self, file_path: str, version: Optional[str] = None) -> None:
        """Dumps the metric object to a YAML file.

        Args:
            file_path: The path to the YAML file.
            version: Optional version string to include in the YAML output.

        Raises:
            ImportError: If the pyyaml library is not installed.
        """
        if yaml is None:
            raise ImportError(
                "YAML serialization requires the pyyaml library. Please install"
                " it using 'pip install google-cloud-aiplatform[evaluation]'."
            )

        fields_to_exclude = {
            field_name
            for field_name, field_info in self.model_fields.items()
            if self.__getattribute__(field_name) is not None
            and isinstance(self.__getattribute__(field_name), Callable)
        }

        data_to_dump = self.model_dump(
            exclude_unset=True,
            exclude_none=True,
            mode="json",
            exclude=fields_to_exclude if fields_to_exclude else None,
        )

        if version:
            data_to_dump["version"] = version

        with open(file_path, "w", encoding="utf-8") as f:
            yaml.dump(data_to_dump, f, sort_keys=False, allow_unicode=True)


class LLMMetric(Metric):
    """A metric that uses LLM-as-a-judge for evaluation."""

    rubric_group_name: Optional[str] = Field(
        default=None,
        description="""Optional. The name of the column in the EvaluationDataset containing the list of rubrics to use for this metric.""",
    )

    @field_validator("prompt_template", mode="before")
    @classmethod
    def validate_prompt_template(cls, value: Union[str, "MetricPromptBuilder"]) -> str:
        """Validates prompt template to be a non-empty string."""
        if value is None:
            raise ValueError("Prompt template cannot be empty.")
        if isinstance(value, MetricPromptBuilder):
            value = str(value)
        if not value.strip():
            raise ValueError("Prompt template cannot be an empty string.")
        return value

    @field_validator("judge_model_sampling_count")
    @classmethod
    def validate_judge_model_sampling_count(cls, value: Optional[int]) -> Optional[int]:
        """Validates judge_model_sampling_count to be between 1 and 32."""
        if value is not None and (value < 1 or value > 32):
            raise ValueError("judge_model_sampling_count must be between 1 and 32.")
        return value

    @classmethod
    def load(cls, config_path: str, client: Optional[Any] = None) -> "LLMMetric":
        """Loads a metric configuration from a YAML or JSON file.

        This method allows for the creation of an LLMMetric instance from a
        local file path or a Google Cloud Storage (GCS) URI. It will automatically
        detect the file type (.yaml, .yml, or .json) and parse it accordingly.

        Args:
            config_path: The local path or GCS URI (e.g., 'gs://bucket/metric.yaml')
                to the metric configuration file.
            client: Optional. The Vertex AI client instance to use for authentication.
                If not provided, Application Default Credentials (ADC) will be used.

        Returns:
            An instance of LLMMetric configured with the loaded data.

        Raises:
            ValueError: If the file path is invalid or the file content cannot be parsed.
            ImportError: If a required library like 'PyYAML' or 'google-cloud-storage' is not installed.
            IOError: If the file cannot be read from the specified path.
        """
        file_extension = os.path.splitext(config_path)[1].lower()
        if file_extension not in [".yaml", ".yml", ".json"]:
            raise ValueError(
                "Unsupported file extension for metric config. Must be .yaml, .yml, or .json"
            )

        content_str: str
        if config_path.startswith("gs://"):
            try:
                from google.cloud import storage

                storage_client = storage.Client(
                    credentials=client._api_client._credentials if client else None
                )
                path_without_prefix = config_path[len("gs://") :]
                bucket_name, blob_path = path_without_prefix.split("/", 1)

                bucket = storage_client.bucket(bucket_name)
                blob = bucket.blob(blob_path)
                content_str = blob.download_as_bytes().decode("utf-8")
            except ImportError as e:
                raise ImportError(
                    "Reading from GCS requires the 'google-cloud-storage' library. Please install it with 'pip install google-cloud-aiplatform[evaluation]'."
                ) from e
            except Exception as e:
                raise IOError(f"Failed to read from GCS path {config_path}: {e}") from e
        else:
            try:
                with open(config_path, "r", encoding="utf-8") as f:
                    content_str = f.read()
            except FileNotFoundError:
                raise FileNotFoundError(
                    f"Local configuration file not found at: {config_path}"
                )
            except Exception as e:
                raise IOError(f"Failed to read local file {config_path}: {e}") from e

        data: Dict[str, Any]

        if file_extension in [".yaml", ".yml"]:
            if yaml is None:
                raise ImportError(
                    "YAML parsing requires the pyyaml library. Please install it with 'pip install google-cloud-aiplatform[evaluation]'."
                )
            data = yaml.safe_load(content_str)
        elif file_extension == ".json":
            data = json.loads(content_str)

        if not isinstance(data, dict):
            raise ValueError("Metric config content did not parse into a dictionary.")

        return cls.model_validate(data)


class MetricDict(TypedDict, total=False):
    """The metric used for evaluation."""

    name: Optional[str]
    """The name of the metric."""

    custom_function: Optional[Callable[..., Any]]
    """The custom function that defines the end-to-end logic for metric computation."""

    remote_custom_function: Optional[str]
    """The evaluation function for the custom code execution metric. This custom code is run remotely in the evaluation service."""

    prompt_template: Optional[str]
    """The prompt template for the metric."""

    judge_model: Optional[str]
    """The judge model for the metric."""

    judge_model_generation_config: Optional[genai_types.GenerationConfigDict]
    """The generation config for the judge LLM (temperature, top_k, top_p, etc)."""

    judge_model_sampling_count: Optional[int]
    """The sampling count for the judge model."""

    judge_model_system_instruction: Optional[str]
    """The system instruction for the judge model."""

    return_raw_output: Optional[bool]
    """Whether to return the raw output from the judge model."""

    parse_and_reduce_fn: Optional[Callable[..., Any]]
    """The parse and reduce function for the judge model."""

    aggregate_summary_fn: Optional[Callable[..., Any]]
    """The aggregate summary function for the judge model."""

    rubric_group_name: Optional[str]
    """The rubric group name for the rubric-based metric."""

    metric_spec_parameters: Optional[dict[str, Any]]
    """Optional steering instruction parameters for the automated predefined metric."""


MetricOrDict = Union[Metric, MetricDict]


class _EvaluateInstancesRequestParameters(_common.BaseModel):
    """Parameters for evaluating instances."""

    bleu_input: Optional[BleuInput] = Field(default=None, description="""""")
    exact_match_input: Optional[ExactMatchInput] = Field(
        default=None, description=""""""
    )
    rouge_input: Optional[RougeInput] = Field(default=None, description="""""")
    pointwise_metric_input: Optional[PointwiseMetricInput] = Field(
        default=None, description=""""""
    )
    pairwise_metric_input: Optional[PairwiseMetricInput] = Field(
        default=None, description=""""""
    )
    tool_call_valid_input: Optional[ToolCallValidInput] = Field(
        default=None, description=""""""
    )
    tool_name_match_input: Optional[ToolNameMatchInput] = Field(
        default=None, description=""""""
    )
    tool_parameter_key_match_input: Optional[ToolParameterKeyMatchInput] = Field(
        default=None, description=""""""
    )
    tool_parameter_kv_match_input: Optional[ToolParameterKVMatchInput] = Field(
        default=None, description=""""""
    )
    rubric_based_metric_input: Optional[RubricBasedMetricInput] = Field(
        default=None, description=""""""
    )
    autorater_config: Optional[genai_types.AutoraterConfig] = Field(
        default=None, description=""""""
    )
    metrics: Optional[list[Metric]] = Field(
        default=None,
        description="""The metrics used for evaluation.
  Currently, we only support evaluating a single metric. If multiple metrics
  are provided, only the first one will be evaluated.""",
    )
    instance: Optional[EvaluationInstance] = Field(
        default=None, description="""The instance to be evaluated."""
    )
    config: Optional[EvaluateInstancesConfig] = Field(default=None, description="""""")


class _EvaluateInstancesRequestParametersDict(TypedDict, total=False):
    """Parameters for evaluating instances."""

    bleu_input: Optional[BleuInputDict]
    """"""

    exact_match_input: Optional[ExactMatchInputDict]
    """"""

    rouge_input: Optional[RougeInputDict]
    """"""

    pointwise_metric_input: Optional[PointwiseMetricInputDict]
    """"""

    pairwise_metric_input: Optional[PairwiseMetricInputDict]
    """"""

    tool_call_valid_input: Optional[ToolCallValidInputDict]
    """"""

    tool_name_match_input: Optional[ToolNameMatchInputDict]
    """"""

    tool_parameter_key_match_input: Optional[ToolParameterKeyMatchInputDict]
    """"""

    tool_parameter_kv_match_input: Optional[ToolParameterKVMatchInputDict]
    """"""

    rubric_based_metric_input: Optional[RubricBasedMetricInputDict]
    """"""

    autorater_config: Optional[genai_types.AutoraterConfigDict]
    """"""

    metrics: Optional[list[MetricDict]]
    """The metrics used for evaluation.
  Currently, we only support evaluating a single metric. If multiple metrics
  are provided, only the first one will be evaluated."""

    instance: Optional[EvaluationInstanceDict]
    """The instance to be evaluated."""

    config: Optional[EvaluateInstancesConfigDict]
    """"""


_EvaluateInstancesRequestParametersOrDict = Union[
    _EvaluateInstancesRequestParameters, _EvaluateInstancesRequestParametersDict
]


class MetricResult(_common.BaseModel):
    """Result for a single metric on a single instance."""

    score: Optional[float] = Field(
        default=None,
        description="""The score for the metric. Please refer to each metric's documentation for the meaning of the score.""",
    )
    rubric_verdicts: Optional[list[evals_types.RubricVerdict]] = Field(
        default=None,
        description="""For rubric-based metrics, the verdicts for each rubric.""",
    )
    explanation: Optional[str] = Field(
        default=None, description="""The explanation for the metric result."""
    )
    error: Optional[genai_types.GoogleRpcStatus] = Field(
        default=None, description="""The error status for the metric result."""
    )


class MetricResultDict(TypedDict, total=False):
    """Result for a single metric on a single instance."""

    score: Optional[float]
    """The score for the metric. Please refer to each metric's documentation for the meaning of the score."""

    rubric_verdicts: Optional[list[evals_types.RubricVerdict]]
    """For rubric-based metrics, the verdicts for each rubric."""

    explanation: Optional[str]
    """The explanation for the metric result."""

    error: Optional[genai_types.GoogleRpcStatusDict]
    """The error status for the metric result."""


MetricResultOrDict = Union[MetricResult, MetricResultDict]


class RubricBasedMetricResult(_common.BaseModel):
    """Result for a rubric-based metric."""

    score: Optional[float] = Field(
        default=None, description="""Passing rate of all the rubrics."""
    )
    rubric_verdicts: Optional[list[evals_types.RubricVerdict]] = Field(
        default=None,
        description="""The details of all the rubrics and their verdicts.""",
    )


class RubricBasedMetricResultDict(TypedDict, total=False):
    """Result for a rubric-based metric."""

    score: Optional[float]
    """Passing rate of all the rubrics."""

    rubric_verdicts: Optional[list[evals_types.RubricVerdict]]
    """The details of all the rubrics and their verdicts."""


RubricBasedMetricResultOrDict = Union[
    RubricBasedMetricResult, RubricBasedMetricResultDict
]


class BleuMetricValue(_common.BaseModel):
    """Bleu metric value for an instance."""

    score: Optional[float] = Field(
        default=None, description="""Output only. Bleu score."""
    )


class BleuMetricValueDict(TypedDict, total=False):
    """Bleu metric value for an instance."""

    score: Optional[float]
    """Output only. Bleu score."""


BleuMetricValueOrDict = Union[BleuMetricValue, BleuMetricValueDict]


class BleuResults(_common.BaseModel):
    """Results for bleu metric."""

    bleu_metric_values: Optional[list[BleuMetricValue]] = Field(
        default=None, description="""Output only. Bleu metric values."""
    )


class BleuResultsDict(TypedDict, total=False):
    """Results for bleu metric."""

    bleu_metric_values: Optional[list[BleuMetricValueDict]]
    """Output only. Bleu metric values."""


BleuResultsOrDict = Union[BleuResults, BleuResultsDict]


class CometResult(_common.BaseModel):
    """Spec for Comet result - calculates the comet score for the given instance using the version specified in the spec."""

    score: Optional[float] = Field(
        default=None,
        description="""Output only. Comet score. Range depends on version.""",
    )


class CometResultDict(TypedDict, total=False):
    """Spec for Comet result - calculates the comet score for the given instance using the version specified in the spec."""

    score: Optional[float]
    """Output only. Comet score. Range depends on version."""


CometResultOrDict = Union[CometResult, CometResultDict]


class ExactMatchMetricValue(_common.BaseModel):
    """Exact match metric value for an instance."""

    score: Optional[float] = Field(
        default=None, description="""Output only. Exact match score."""
    )


class ExactMatchMetricValueDict(TypedDict, total=False):
    """Exact match metric value for an instance."""

    score: Optional[float]
    """Output only. Exact match score."""


ExactMatchMetricValueOrDict = Union[ExactMatchMetricValue, ExactMatchMetricValueDict]


class ExactMatchResults(_common.BaseModel):
    """Results for exact match metric."""

    exact_match_metric_values: Optional[list[ExactMatchMetricValue]] = Field(
        default=None, description="""Output only. Exact match metric values."""
    )


class ExactMatchResultsDict(TypedDict, total=False):
    """Results for exact match metric."""

    exact_match_metric_values: Optional[list[ExactMatchMetricValueDict]]
    """Output only. Exact match metric values."""


ExactMatchResultsOrDict = Union[ExactMatchResults, ExactMatchResultsDict]


class MetricxResult(_common.BaseModel):
    """Spec for MetricX result - calculates the MetricX score for the given instance using the version specified in the spec."""

    score: Optional[float] = Field(
        default=None,
        description="""Output only. MetricX score. Range depends on version.""",
    )


class MetricxResultDict(TypedDict, total=False):
    """Spec for MetricX result - calculates the MetricX score for the given instance using the version specified in the spec."""

    score: Optional[float]
    """Output only. MetricX score. Range depends on version."""


MetricxResultOrDict = Union[MetricxResult, MetricxResultDict]


class RawOutput(_common.BaseModel):
    """Raw output."""

    raw_output: Optional[list[str]] = Field(
        default=None, description="""Output only. Raw output string."""
    )


class RawOutputDict(TypedDict, total=False):
    """Raw output."""

    raw_output: Optional[list[str]]
    """Output only. Raw output string."""


RawOutputOrDict = Union[RawOutput, RawOutputDict]


class CustomOutput(_common.BaseModel):
    """Spec for custom output."""

    raw_outputs: Optional[RawOutput] = Field(
        default=None, description="""Output only. List of raw output strings."""
    )


class CustomOutputDict(TypedDict, total=False):
    """Spec for custom output."""

    raw_outputs: Optional[RawOutputDict]
    """Output only. List of raw output strings."""


CustomOutputOrDict = Union[CustomOutput, CustomOutputDict]


class PairwiseMetricResult(_common.BaseModel):
    """Spec for pairwise metric result."""

    custom_output: Optional[CustomOutput] = Field(
        default=None, description="""Output only. Spec for custom output."""
    )
    explanation: Optional[str] = Field(
        default=None,
        description="""Output only. Explanation for pairwise metric score.""",
    )
    pairwise_choice: Optional[PairwiseChoice] = Field(
        default=None, description="""Output only. Pairwise metric choice."""
    )


class PairwiseMetricResultDict(TypedDict, total=False):
    """Spec for pairwise metric result."""

    custom_output: Optional[CustomOutputDict]
    """Output only. Spec for custom output."""

    explanation: Optional[str]
    """Output only. Explanation for pairwise metric score."""

    pairwise_choice: Optional[PairwiseChoice]
    """Output only. Pairwise metric choice."""


PairwiseMetricResultOrDict = Union[PairwiseMetricResult, PairwiseMetricResultDict]


class PointwiseMetricResult(_common.BaseModel):
    """Spec for pointwise metric result."""

    custom_output: Optional[CustomOutput] = Field(
        default=None, description="""Output only. Spec for custom output."""
    )
    explanation: Optional[str] = Field(
        default=None,
        description="""Output only. Explanation for pointwise metric score.""",
    )
    score: Optional[float] = Field(
        default=None, description="""Output only. Pointwise metric score."""
    )


class PointwiseMetricResultDict(TypedDict, total=False):
    """Spec for pointwise metric result."""

    custom_output: Optional[CustomOutputDict]
    """Output only. Spec for custom output."""

    explanation: Optional[str]
    """Output only. Explanation for pointwise metric score."""

    score: Optional[float]
    """Output only. Pointwise metric score."""


PointwiseMetricResultOrDict = Union[PointwiseMetricResult, PointwiseMetricResultDict]


class RougeMetricValue(_common.BaseModel):
    """Rouge metric value for an instance."""

    score: Optional[float] = Field(
        default=None, description="""Output only. Rouge score."""
    )


class RougeMetricValueDict(TypedDict, total=False):
    """Rouge metric value for an instance."""

    score: Optional[float]
    """Output only. Rouge score."""


RougeMetricValueOrDict = Union[RougeMetricValue, RougeMetricValueDict]


class RougeResults(_common.BaseModel):
    """Results for rouge metric."""

    rouge_metric_values: Optional[list[RougeMetricValue]] = Field(
        default=None, description="""Output only. Rouge metric values."""
    )


class RougeResultsDict(TypedDict, total=False):
    """Results for rouge metric."""

    rouge_metric_values: Optional[list[RougeMetricValueDict]]
    """Output only. Rouge metric values."""


RougeResultsOrDict = Union[RougeResults, RougeResultsDict]


class ToolCallValidMetricValue(_common.BaseModel):
    """Tool call valid metric value for an instance."""

    score: Optional[float] = Field(
        default=None, description="""Output only. Tool call valid score."""
    )


class ToolCallValidMetricValueDict(TypedDict, total=False):
    """Tool call valid metric value for an instance."""

    score: Optional[float]
    """Output only. Tool call valid score."""


ToolCallValidMetricValueOrDict = Union[
    ToolCallValidMetricValue, ToolCallValidMetricValueDict
]


class ToolCallValidResults(_common.BaseModel):
    """Results for tool call valid metric."""

    tool_call_valid_metric_values: Optional[list[ToolCallValidMetricValue]] = Field(
        default=None, description="""Output only. Tool call valid metric values."""
    )


class ToolCallValidResultsDict(TypedDict, total=False):
    """Results for tool call valid metric."""

    tool_call_valid_metric_values: Optional[list[ToolCallValidMetricValueDict]]
    """Output only. Tool call valid metric values."""


ToolCallValidResultsOrDict = Union[ToolCallValidResults, ToolCallValidResultsDict]


class ToolNameMatchMetricValue(_common.BaseModel):
    """Tool name match metric value for an instance."""

    score: Optional[float] = Field(
        default=None, description="""Output only. Tool name match score."""
    )


class ToolNameMatchMetricValueDict(TypedDict, total=False):
    """Tool name match metric value for an instance."""

    score: Optional[float]
    """Output only. Tool name match score."""


ToolNameMatchMetricValueOrDict = Union[
    ToolNameMatchMetricValue, ToolNameMatchMetricValueDict
]


class ToolNameMatchResults(_common.BaseModel):
    """Results for tool name match metric."""

    tool_name_match_metric_values: Optional[list[ToolNameMatchMetricValue]] = Field(
        default=None, description="""Output only. Tool name match metric values."""
    )


class ToolNameMatchResultsDict(TypedDict, total=False):
    """Results for tool name match metric."""

    tool_name_match_metric_values: Optional[list[ToolNameMatchMetricValueDict]]
    """Output only. Tool name match metric values."""


ToolNameMatchResultsOrDict = Union[ToolNameMatchResults, ToolNameMatchResultsDict]


class ToolParameterKeyMatchMetricValue(_common.BaseModel):
    """Tool parameter key match metric value for an instance."""

    score: Optional[float] = Field(
        default=None, description="""Output only. Tool parameter key match score."""
    )


class ToolParameterKeyMatchMetricValueDict(TypedDict, total=False):
    """Tool parameter key match metric value for an instance."""

    score: Optional[float]
    """Output only. Tool parameter key match score."""


ToolParameterKeyMatchMetricValueOrDict = Union[
    ToolParameterKeyMatchMetricValue, ToolParameterKeyMatchMetricValueDict
]


class ToolParameterKeyMatchResults(_common.BaseModel):
    """Results for tool parameter key match metric."""

    tool_parameter_key_match_metric_values: Optional[
        list[ToolParameterKeyMatchMetricValue]
    ] = Field(
        default=None,
        description="""Output only. Tool parameter key match metric values.""",
    )


class ToolParameterKeyMatchResultsDict(TypedDict, total=False):
    """Results for tool parameter key match metric."""

    tool_parameter_key_match_metric_values: Optional[
        list[ToolParameterKeyMatchMetricValueDict]
    ]
    """Output only. Tool parameter key match metric values."""


ToolParameterKeyMatchResultsOrDict = Union[
    ToolParameterKeyMatchResults, ToolParameterKeyMatchResultsDict
]


class ToolParameterKVMatchMetricValue(_common.BaseModel):
    """Tool parameter key value match metric value for an instance."""

    score: Optional[float] = Field(
        default=None,
        description="""Output only. Tool parameter key value match score.""",
    )


class ToolParameterKVMatchMetricValueDict(TypedDict, total=False):
    """Tool parameter key value match metric value for an instance."""

    score: Optional[float]
    """Output only. Tool parameter key value match score."""


ToolParameterKVMatchMetricValueOrDict = Union[
    ToolParameterKVMatchMetricValue, ToolParameterKVMatchMetricValueDict
]


class ToolParameterKVMatchResults(_common.BaseModel):
    """Results for tool parameter key value match metric."""

    tool_parameter_kv_match_metric_values: Optional[
        list[ToolParameterKVMatchMetricValue]
    ] = Field(
        default=None,
        description="""Output only. Tool parameter key value match metric values.""",
    )


class ToolParameterKVMatchResultsDict(TypedDict, total=False):
    """Results for tool parameter key value match metric."""

    tool_parameter_kv_match_metric_values: Optional[
        list[ToolParameterKVMatchMetricValueDict]
    ]
    """Output only. Tool parameter key value match metric values."""


ToolParameterKVMatchResultsOrDict = Union[
    ToolParameterKVMatchResults, ToolParameterKVMatchResultsDict
]


class EvaluateInstancesResponse(_common.BaseModel):
    """Result of evaluating an LLM metric."""

    rubric_based_metric_result: Optional[RubricBasedMetricResult] = Field(
        default=None, description="""Result for rubric based metric."""
    )
    metric_results: Optional[list[MetricResult]] = Field(
        default=None,
        description="""A list of metric results for each evaluation case. The order of the metric results is guaranteed to be the same as the order of the instances in the request.""",
    )
    bleu_results: Optional[BleuResults] = Field(
        default=None, description="""Results for bleu metric."""
    )
    comet_result: Optional[CometResult] = Field(
        default=None, description="""Translation metrics. Result for Comet metric."""
    )
    exact_match_results: Optional[ExactMatchResults] = Field(
        default=None,
        description="""Auto metric evaluation results. Results for exact match metric.""",
    )
    metricx_result: Optional[MetricxResult] = Field(
        default=None, description="""Result for Metricx metric."""
    )
    pairwise_metric_result: Optional[PairwiseMetricResult] = Field(
        default=None, description="""Result for pairwise metric."""
    )
    pointwise_metric_result: Optional[PointwiseMetricResult] = Field(
        default=None, description="""Generic metrics. Result for pointwise metric."""
    )
    rouge_results: Optional[RougeResults] = Field(
        default=None, description="""Results for rouge metric."""
    )
    tool_call_valid_results: Optional[ToolCallValidResults] = Field(
        default=None,
        description="""Tool call metrics. Results for tool call valid metric.""",
    )
    tool_name_match_results: Optional[ToolNameMatchResults] = Field(
        default=None, description="""Results for tool name match metric."""
    )
    tool_parameter_key_match_results: Optional[ToolParameterKeyMatchResults] = Field(
        default=None, description="""Results for tool parameter key match metric."""
    )
    tool_parameter_kv_match_results: Optional[ToolParameterKVMatchResults] = Field(
        default=None,
        description="""Results for tool parameter key value match metric.""",
    )


class EvaluateInstancesResponseDict(TypedDict, total=False):
    """Result of evaluating an LLM metric."""

    rubric_based_metric_result: Optional[RubricBasedMetricResultDict]
    """Result for rubric based metric."""

    metric_results: Optional[list[MetricResultDict]]
    """A list of metric results for each evaluation case. The order of the metric results is guaranteed to be the same as the order of the instances in the request."""

    bleu_results: Optional[BleuResultsDict]
    """Results for bleu metric."""

    comet_result: Optional[CometResultDict]
    """Translation metrics. Result for Comet metric."""

    exact_match_results: Optional[ExactMatchResultsDict]
    """Auto metric evaluation results. Results for exact match metric."""

    metricx_result: Optional[MetricxResultDict]
    """Result for Metricx metric."""

    pairwise_metric_result: Optional[PairwiseMetricResultDict]
    """Result for pairwise metric."""

    pointwise_metric_result: Optional[PointwiseMetricResultDict]
    """Generic metrics. Result for pointwise metric."""

    rouge_results: Optional[RougeResultsDict]
    """Results for rouge metric."""

    tool_call_valid_results: Optional[ToolCallValidResultsDict]
    """Tool call metrics. Results for tool call valid metric."""

    tool_name_match_results: Optional[ToolNameMatchResultsDict]
    """Results for tool name match metric."""

    tool_parameter_key_match_results: Optional[ToolParameterKeyMatchResultsDict]
    """Results for tool parameter key match metric."""

    tool_parameter_kv_match_results: Optional[ToolParameterKVMatchResultsDict]
    """Results for tool parameter key value match metric."""


EvaluateInstancesResponseOrDict = Union[
    EvaluateInstancesResponse, EvaluateInstancesResponseDict
]


class RubricGenerationConfig(_common.BaseModel):
    """Config for generating rubrics."""

    http_options: Optional[genai_types.HttpOptions] = Field(
        default=None, description="""Used to override HTTP request options."""
    )


class RubricGenerationConfigDict(TypedDict, total=False):
    """Config for generating rubrics."""

    http_options: Optional[genai_types.HttpOptionsDict]
    """Used to override HTTP request options."""


RubricGenerationConfigOrDict = Union[RubricGenerationConfig, RubricGenerationConfigDict]


class _GenerateInstanceRubricsRequest(_common.BaseModel):
    """Parameters for generating rubrics."""

    contents: Optional[list[genai_types.Content]] = Field(
        default=None,
        description="""The prompt to generate rubrics from. For single-turn queries, this is a single instance. For multi-turn queries, this is a repeated field that contains conversation history + latest request.""",
    )
    predefined_rubric_generation_spec: Optional[PredefinedMetricSpec] = Field(
        default=None,
        description="""Specification for using the rubric generation configs of a pre-defined
          metric, e.g. "generic_quality_v1" and "instruction_following_v1".
          Some of the configs may be only used in rubric generation and not
          supporting evaluation, e.g. "fully_customized_generic_quality_v1".
          If this field is set, the `rubric_generation_spec` field will be ignored.
          """,
    )
    rubric_generation_spec: Optional[RubricGenerationSpec] = Field(
        default=None,
        description="""Specification for how the rubrics should be generated.""",
    )
    config: Optional[RubricGenerationConfig] = Field(default=None, description="""""")


class _GenerateInstanceRubricsRequestDict(TypedDict, total=False):
    """Parameters for generating rubrics."""

    contents: Optional[list[genai_types.ContentDict]]
    """The prompt to generate rubrics from. For single-turn queries, this is a single instance. For multi-turn queries, this is a repeated field that contains conversation history + latest request."""

    predefined_rubric_generation_spec: Optional[PredefinedMetricSpecDict]
    """Specification for using the rubric generation configs of a pre-defined
          metric, e.g. "generic_quality_v1" and "instruction_following_v1".
          Some of the configs may be only used in rubric generation and not
          supporting evaluation, e.g. "fully_customized_generic_quality_v1".
          If this field is set, the `rubric_generation_spec` field will be ignored.
          """

    rubric_generation_spec: Optional[RubricGenerationSpecDict]
    """Specification for how the rubrics should be generated."""

    config: Optional[RubricGenerationConfigDict]
    """"""


_GenerateInstanceRubricsRequestOrDict = Union[
    _GenerateInstanceRubricsRequest, _GenerateInstanceRubricsRequestDict
]


class GenerateInstanceRubricsResponse(_common.BaseModel):
    """Response for generating rubrics."""

    generated_rubrics: Optional[list[evals_types.Rubric]] = Field(
        default=None, description="""A list of generated rubrics."""
    )


class GenerateInstanceRubricsResponseDict(TypedDict, total=False):
    """Response for generating rubrics."""

    generated_rubrics: Optional[list[evals_types.Rubric]]
    """A list of generated rubrics."""


GenerateInstanceRubricsResponseOrDict = Union[
    GenerateInstanceRubricsResponse, GenerateInstanceRubricsResponseDict
]


class GetEvaluationRunConfig(_common.BaseModel):
    """Config for get evaluation run."""

    http_options: Optional[genai_types.HttpOptions] = Field(
        default=None, description="""Used to override HTTP request options."""
    )


class GetEvaluationRunConfigDict(TypedDict, total=False):
    """Config for get evaluation run."""

    http_options: Optional[genai_types.HttpOptionsDict]
    """Used to override HTTP request options."""


GetEvaluationRunConfigOrDict = Union[GetEvaluationRunConfig, GetEvaluationRunConfigDict]


class _GetEvaluationRunParameters(_common.BaseModel):
    """Represents a job that runs evaluation."""

    name: Optional[str] = Field(default=None, description="""""")
    config: Optional[GetEvaluationRunConfig] = Field(default=None, description="""""")


class _GetEvaluationRunParametersDict(TypedDict, total=False):
    """Represents a job that runs evaluation."""

    name: Optional[str]
    """"""

    config: Optional[GetEvaluationRunConfigDict]
    """"""


_GetEvaluationRunParametersOrDict = Union[
    _GetEvaluationRunParameters, _GetEvaluationRunParametersDict
]


class GetEvaluationSetConfig(_common.BaseModel):
    """Config for get evaluation set."""

    http_options: Optional[genai_types.HttpOptions] = Field(
        default=None, description="""Used to override HTTP request options."""
    )


class GetEvaluationSetConfigDict(TypedDict, total=False):
    """Config for get evaluation set."""

    http_options: Optional[genai_types.HttpOptionsDict]
    """Used to override HTTP request options."""


GetEvaluationSetConfigOrDict = Union[GetEvaluationSetConfig, GetEvaluationSetConfigDict]


class _GetEvaluationSetParameters(_common.BaseModel):
    """Represents a job that gets an evaluation set."""

    name: Optional[str] = Field(default=None, description="""""")
    config: Optional[GetEvaluationSetConfig] = Field(default=None, description="""""")


class _GetEvaluationSetParametersDict(TypedDict, total=False):
    """Represents a job that gets an evaluation set."""

    name: Optional[str]
    """"""

    config: Optional[GetEvaluationSetConfigDict]
    """"""


_GetEvaluationSetParametersOrDict = Union[
    _GetEvaluationSetParameters, _GetEvaluationSetParametersDict
]


class GetEvaluationItemConfig(_common.BaseModel):
    """Config for get evaluation item."""

    http_options: Optional[genai_types.HttpOptions] = Field(
        default=None, description="""Used to override HTTP request options."""
    )


class GetEvaluationItemConfigDict(TypedDict, total=False):
    """Config for get evaluation item."""

    http_options: Optional[genai_types.HttpOptionsDict]
    """Used to override HTTP request options."""


GetEvaluationItemConfigOrDict = Union[
    GetEvaluationItemConfig, GetEvaluationItemConfigDict
]


class _GetEvaluationItemParameters(_common.BaseModel):
    """Represents a job that gets an evaluation item."""

    name: Optional[str] = Field(default=None, description="""""")
    config: Optional[GetEvaluationItemConfig] = Field(default=None, description="""""")


class _GetEvaluationItemParametersDict(TypedDict, total=False):
    """Represents a job that gets an evaluation item."""

    name: Optional[str]
    """"""

    config: Optional[GetEvaluationItemConfigDict]
    """"""


_GetEvaluationItemParametersOrDict = Union[
    _GetEvaluationItemParameters, _GetEvaluationItemParametersDict
]


class OptimizeConfig(_common.BaseModel):
    """Config for Prompt Optimizer."""

    http_options: Optional[genai_types.HttpOptions] = Field(
        default=None, description="""Used to override HTTP request options."""
    )
    optimization_target: Optional[OptimizeTarget] = Field(
        default=None, description=""""""
    )


class OptimizeConfigDict(TypedDict, total=False):
    """Config for Prompt Optimizer."""

    http_options: Optional[genai_types.HttpOptionsDict]
    """Used to override HTTP request options."""

    optimization_target: Optional[OptimizeTarget]
    """"""


OptimizeConfigOrDict = Union[OptimizeConfig, OptimizeConfigDict]


class _OptimizeRequestParameters(_common.BaseModel):
    """Request for the optimize_prompt method."""

    content: Optional[genai_types.Content] = Field(default=None, description="""""")
    config: Optional[OptimizeConfig] = Field(default=None, description="""""")


class _OptimizeRequestParametersDict(TypedDict, total=False):
    """Request for the optimize_prompt method."""

    content: Optional[genai_types.ContentDict]
    """"""

    config: Optional[OptimizeConfigDict]
    """"""


_OptimizeRequestParametersOrDict = Union[
    _OptimizeRequestParameters, _OptimizeRequestParametersDict
]


class OptimizeResponseEndpoint(_common.BaseModel):
    """Response for the optimize_prompt method."""

    content: Optional[genai_types.Content] = Field(default=None, description="""""")


class OptimizeResponseEndpointDict(TypedDict, total=False):
    """Response for the optimize_prompt method."""

    content: Optional[genai_types.ContentDict]
    """"""


OptimizeResponseEndpointOrDict = Union[
    OptimizeResponseEndpoint, OptimizeResponseEndpointDict
]


class DnsPeeringConfig(_common.BaseModel):
    """DNS peering configuration. These configurations are used to create DNS peering zones in the Vertex tenant project VPC, enabling resolution of records within the specified domain hosted in the target network's Cloud DNS."""

    domain: Optional[str] = Field(
        default=None,
        description="""Required. The DNS name suffix of the zone being peered to, e.g., "my-internal-domain.corp.". Must end with a dot.""",
    )
    target_network: Optional[str] = Field(
        default=None,
        description="""Required. The VPC network name in the target_project where the DNS zone specified by 'domain' is visible.""",
    )
    target_project: Optional[str] = Field(
        default=None,
        description="""Required. The project ID hosting the Cloud DNS managed zone that contains the 'domain'. The Vertex AI Service Agent requires the dns.peer role on this project.""",
    )


class DnsPeeringConfigDict(TypedDict, total=False):
    """DNS peering configuration. These configurations are used to create DNS peering zones in the Vertex tenant project VPC, enabling resolution of records within the specified domain hosted in the target network's Cloud DNS."""

    domain: Optional[str]
    """Required. The DNS name suffix of the zone being peered to, e.g., "my-internal-domain.corp.". Must end with a dot."""

    target_network: Optional[str]
    """Required. The VPC network name in the target_project where the DNS zone specified by 'domain' is visible."""

    target_project: Optional[str]
    """Required. The project ID hosting the Cloud DNS managed zone that contains the 'domain'. The Vertex AI Service Agent requires the dns.peer role on this project."""


DnsPeeringConfigOrDict = Union[DnsPeeringConfig, DnsPeeringConfigDict]


class PscInterfaceConfig(_common.BaseModel):
    """The PSC interface config."""

    dns_peering_configs: Optional[list[DnsPeeringConfig]] = Field(
        default=None,
        description="""Optional. DNS peering configurations. When specified, Vertex AI will attempt to configure DNS peering zones in the tenant project VPC to resolve the specified domains using the target network's Cloud DNS. The user must grant the dns.peer role to the Vertex AI Service Agent on the target project.""",
    )
    network_attachment: Optional[str] = Field(
        default=None,
        description="""Optional. The name of the Compute Engine [network attachment](https://cloud.google.com/vpc/docs/about-network-attachments) to attach to the resource within the region and user project. To specify this field, you must have already [created a network attachment] (https://cloud.google.com/vpc/docs/create-manage-network-attachments#create-network-attachments). This field is only used for resources using PSC-I.""",
    )


class PscInterfaceConfigDict(TypedDict, total=False):
    """The PSC interface config."""

    dns_peering_configs: Optional[list[DnsPeeringConfigDict]]
    """Optional. DNS peering configurations. When specified, Vertex AI will attempt to configure DNS peering zones in the tenant project VPC to resolve the specified domains using the target network's Cloud DNS. The user must grant the dns.peer role to the Vertex AI Service Agent on the target project."""

    network_attachment: Optional[str]
    """Optional. The name of the Compute Engine [network attachment](https://cloud.google.com/vpc/docs/about-network-attachments) to attach to the resource within the region and user project. To specify this field, you must have already [created a network attachment] (https://cloud.google.com/vpc/docs/create-manage-network-attachments#create-network-attachments). This field is only used for resources using PSC-I."""


PscInterfaceConfigOrDict = Union[PscInterfaceConfig, PscInterfaceConfigDict]


class Scheduling(_common.BaseModel):
    """All parameters related to queuing and scheduling of custom jobs."""

    disable_retries: Optional[bool] = Field(
        default=None,
        description="""Optional. Indicates if the job should retry for internal errors after the job starts running. If true, overrides `Scheduling.restart_job_on_worker_restart` to false.""",
    )
    max_wait_duration: Optional[str] = Field(
        default=None,
        description="""Optional. This is the maximum duration that a job will wait for the requested resources to be provisioned if the scheduling strategy is set to [Strategy.DWS_FLEX_START]. If set to 0, the job will wait indefinitely. The default is 24 hours.""",
    )
    restart_job_on_worker_restart: Optional[bool] = Field(
        default=None,
        description="""Optional. Restarts the entire CustomJob if a worker gets restarted. This feature can be used by distributed training jobs that are not resilient to workers leaving and joining a job.""",
    )
    strategy: Optional[Strategy] = Field(
        default=None,
        description="""Optional. This determines which type of scheduling strategy to use.""",
    )
    timeout: Optional[str] = Field(
        default=None,
        description="""Optional. The maximum job running time. The default is 7 days.""",
    )


class SchedulingDict(TypedDict, total=False):
    """All parameters related to queuing and scheduling of custom jobs."""

    disable_retries: Optional[bool]
    """Optional. Indicates if the job should retry for internal errors after the job starts running. If true, overrides `Scheduling.restart_job_on_worker_restart` to false."""

    max_wait_duration: Optional[str]
    """Optional. This is the maximum duration that a job will wait for the requested resources to be provisioned if the scheduling strategy is set to [Strategy.DWS_FLEX_START]. If set to 0, the job will wait indefinitely. The default is 24 hours."""

    restart_job_on_worker_restart: Optional[bool]
    """Optional. Restarts the entire CustomJob if a worker gets restarted. This feature can be used by distributed training jobs that are not resilient to workers leaving and joining a job."""

    strategy: Optional[Strategy]
    """Optional. This determines which type of scheduling strategy to use."""

    timeout: Optional[str]
    """Optional. The maximum job running time. The default is 7 days."""


SchedulingOrDict = Union[Scheduling, SchedulingDict]


class EnvVar(_common.BaseModel):
    """Represents an environment variable present in a Container or Python Module."""

    name: Optional[str] = Field(
        default=None,
        description="""Required. Name of the environment variable. Must be a valid C identifier.""",
    )
    value: Optional[str] = Field(
        default=None,
        description="""Required. Variables that reference a $(VAR_NAME) are expanded using the previous defined environment variables in the container and any service environment variables. If a variable cannot be resolved, the reference in the input string will be unchanged. The $(VAR_NAME) syntax can be escaped with a double $$, ie: $$(VAR_NAME). Escaped references will never be expanded, regardless of whether the variable exists or not.""",
    )


class EnvVarDict(TypedDict, total=False):
    """Represents an environment variable present in a Container or Python Module."""

    name: Optional[str]
    """Required. Name of the environment variable. Must be a valid C identifier."""

    value: Optional[str]
    """Required. Variables that reference a $(VAR_NAME) are expanded using the previous defined environment variables in the container and any service environment variables. If a variable cannot be resolved, the reference in the input string will be unchanged. The $(VAR_NAME) syntax can be escaped with a double $$, ie: $$(VAR_NAME). Escaped references will never be expanded, regardless of whether the variable exists or not."""


EnvVarOrDict = Union[EnvVar, EnvVarDict]


class ContainerSpec(_common.BaseModel):
    """The spec of a Container."""

    args: Optional[list[str]] = Field(
        default=None,
        description="""The arguments to be passed when starting the container.""",
    )
    command: Optional[list[str]] = Field(
        default=None,
        description="""The command to be invoked when the container is started. It overrides the entrypoint instruction in Dockerfile when provided.""",
    )
    env: Optional[list[EnvVar]] = Field(
        default=None,
        description="""Environment variables to be passed to the container. Maximum limit is 100.""",
    )
    image_uri: Optional[str] = Field(
        default=None,
        description="""Required. The URI of a container image in the Container Registry that is to be run on each worker replica.""",
    )


class ContainerSpecDict(TypedDict, total=False):
    """The spec of a Container."""

    args: Optional[list[str]]
    """The arguments to be passed when starting the container."""

    command: Optional[list[str]]
    """The command to be invoked when the container is started. It overrides the entrypoint instruction in Dockerfile when provided."""

    env: Optional[list[EnvVarDict]]
    """Environment variables to be passed to the container. Maximum limit is 100."""

    image_uri: Optional[str]
    """Required. The URI of a container image in the Container Registry that is to be run on each worker replica."""


ContainerSpecOrDict = Union[ContainerSpec, ContainerSpecDict]


class DiskSpec(_common.BaseModel):
    """Represents the spec of disk options."""

    boot_disk_size_gb: Optional[int] = Field(
        default=None, description="""Size in GB of the boot disk (default is 100GB)."""
    )
    boot_disk_type: Optional[str] = Field(
        default=None,
        description="""Type of the boot disk. For non-A3U machines, the default value is "pd-ssd", for A3U machines, the default value is "hyperdisk-balanced". Valid values: "pd-ssd" (Persistent Disk Solid State Drive), "pd-standard" (Persistent Disk Hard Disk Drive) or "hyperdisk-balanced".""",
    )


class DiskSpecDict(TypedDict, total=False):
    """Represents the spec of disk options."""

    boot_disk_size_gb: Optional[int]
    """Size in GB of the boot disk (default is 100GB)."""

    boot_disk_type: Optional[str]
    """Type of the boot disk. For non-A3U machines, the default value is "pd-ssd", for A3U machines, the default value is "hyperdisk-balanced". Valid values: "pd-ssd" (Persistent Disk Solid State Drive), "pd-standard" (Persistent Disk Hard Disk Drive) or "hyperdisk-balanced"."""


DiskSpecOrDict = Union[DiskSpec, DiskSpecDict]


class LustreMount(_common.BaseModel):
    """Represents a mount configuration for Lustre file system."""

    filesystem: Optional[str] = Field(
        default=None, description="""Required. The name of the Lustre filesystem."""
    )
    instance_ip: Optional[str] = Field(
        default=None, description="""Required. IP address of the Lustre instance."""
    )
    mount_point: Optional[str] = Field(
        default=None,
        description="""Required. Destination mount path. The Lustre file system will be mounted for the user under /mnt/lustre/""",
    )
    volume_handle: Optional[str] = Field(
        default=None,
        description="""Required. The unique identifier of the Lustre volume.""",
    )


class LustreMountDict(TypedDict, total=False):
    """Represents a mount configuration for Lustre file system."""

    filesystem: Optional[str]
    """Required. The name of the Lustre filesystem."""

    instance_ip: Optional[str]
    """Required. IP address of the Lustre instance."""

    mount_point: Optional[str]
    """Required. Destination mount path. The Lustre file system will be mounted for the user under /mnt/lustre/"""

    volume_handle: Optional[str]
    """Required. The unique identifier of the Lustre volume."""


LustreMountOrDict = Union[LustreMount, LustreMountDict]


class ReservationAffinity(_common.BaseModel):
    """A ReservationAffinity can be used to configure a Vertex AI resource (e.g., a DeployedModel) to draw its Compute Engine resources from a Shared Reservation, or exclusively from on-demand capacity."""

    key: Optional[str] = Field(
        default=None,
        description="""Optional. Corresponds to the label key of a reservation resource. To target a SPECIFIC_RESERVATION by name, use `compute.googleapis.com/reservation-name` as the key and specify the name of your reservation as its value.""",
    )
    reservation_affinity_type: Optional[Type] = Field(
        default=None,
        description="""Required. Specifies the reservation affinity type.""",
    )
    values: Optional[list[str]] = Field(
        default=None,
        description="""Optional. Corresponds to the label values of a reservation resource. This must be the full resource name of the reservation or reservation block.""",
    )


class ReservationAffinityDict(TypedDict, total=False):
    """A ReservationAffinity can be used to configure a Vertex AI resource (e.g., a DeployedModel) to draw its Compute Engine resources from a Shared Reservation, or exclusively from on-demand capacity."""

    key: Optional[str]
    """Optional. Corresponds to the label key of a reservation resource. To target a SPECIFIC_RESERVATION by name, use `compute.googleapis.com/reservation-name` as the key and specify the name of your reservation as its value."""

    reservation_affinity_type: Optional[Type]
    """Required. Specifies the reservation affinity type."""

    values: Optional[list[str]]
    """Optional. Corresponds to the label values of a reservation resource. This must be the full resource name of the reservation or reservation block."""


ReservationAffinityOrDict = Union[ReservationAffinity, ReservationAffinityDict]


class MachineSpec(_common.BaseModel):
    """Specification of a single machine."""

    accelerator_count: Optional[int] = Field(
        default=None,
        description="""The number of accelerators to attach to the machine.""",
    )
    accelerator_type: Optional[AcceleratorType] = Field(
        default=None,
        description="""Immutable. The type of accelerator(s) that may be attached to the machine as per accelerator_count.""",
    )
    gpu_partition_size: Optional[str] = Field(
        default=None,
        description="""Optional. Immutable. The Nvidia GPU partition size. When specified, the requested accelerators will be partitioned into smaller GPU partitions. For example, if the request is for 8 units of NVIDIA A100 GPUs, and gpu_partition_size="1g.10gb", the service will create 8 * 7 = 56 partitioned MIG instances. The partition size must be a value supported by the requested accelerator. Refer to [Nvidia GPU Partitioning](https://cloud.google.com/kubernetes-engine/docs/how-to/gpus-multi#multi-instance_gpu_partitions) for the available partition sizes. If set, the accelerator_count should be set to 1.""",
    )
    machine_type: Optional[str] = Field(
        default=None,
        description="""Immutable. The type of the machine. See the [list of machine types supported for prediction](https://cloud.google.com/vertex-ai/docs/predictions/configure-compute#machine-types) See the [list of machine types supported for custom training](https://cloud.google.com/vertex-ai/docs/training/configure-compute#machine-types). For DeployedModel this field is optional, and the default value is `n1-standard-2`. For BatchPredictionJob or as part of WorkerPoolSpec this field is required.""",
    )
    multihost_gpu_node_count: Optional[int] = Field(
        default=None,
        description="""Optional. Immutable. The number of nodes per replica for multihost GPU deployments.""",
    )
    reservation_affinity: Optional[ReservationAffinity] = Field(
        default=None,
        description="""Optional. Immutable. Configuration controlling how this resource pool consumes reservation.""",
    )
    tpu_topology: Optional[str] = Field(
        default=None,
        description="""Immutable. The topology of the TPUs. Corresponds to the TPU topologies available from GKE. (Example: tpu_topology: "2x2x1").""",
    )


class MachineSpecDict(TypedDict, total=False):
    """Specification of a single machine."""

    accelerator_count: Optional[int]
    """The number of accelerators to attach to the machine."""

    accelerator_type: Optional[AcceleratorType]
    """Immutable. The type of accelerator(s) that may be attached to the machine as per accelerator_count."""

    gpu_partition_size: Optional[str]
    """Optional. Immutable. The Nvidia GPU partition size. When specified, the requested accelerators will be partitioned into smaller GPU partitions. For example, if the request is for 8 units of NVIDIA A100 GPUs, and gpu_partition_size="1g.10gb", the service will create 8 * 7 = 56 partitioned MIG instances. The partition size must be a value supported by the requested accelerator. Refer to [Nvidia GPU Partitioning](https://cloud.google.com/kubernetes-engine/docs/how-to/gpus-multi#multi-instance_gpu_partitions) for the available partition sizes. If set, the accelerator_count should be set to 1."""

    machine_type: Optional[str]
    """Immutable. The type of the machine. See the [list of machine types supported for prediction](https://cloud.google.com/vertex-ai/docs/predictions/configure-compute#machine-types) See the [list of machine types supported for custom training](https://cloud.google.com/vertex-ai/docs/training/configure-compute#machine-types). For DeployedModel this field is optional, and the default value is `n1-standard-2`. For BatchPredictionJob or as part of WorkerPoolSpec this field is required."""

    multihost_gpu_node_count: Optional[int]
    """Optional. Immutable. The number of nodes per replica for multihost GPU deployments."""

    reservation_affinity: Optional[ReservationAffinityDict]
    """Optional. Immutable. Configuration controlling how this resource pool consumes reservation."""

    tpu_topology: Optional[str]
    """Immutable. The topology of the TPUs. Corresponds to the TPU topologies available from GKE. (Example: tpu_topology: "2x2x1")."""


MachineSpecOrDict = Union[MachineSpec, MachineSpecDict]


class NfsMount(_common.BaseModel):
    """Represents a mount configuration for Network File System (NFS) to mount."""

    mount_point: Optional[str] = Field(
        default=None,
        description="""Required. Destination mount path. The NFS will be mounted for the user under /mnt/nfs/""",
    )
    path: Optional[str] = Field(
        default=None,
        description="""Required. Source path exported from NFS server. Has to start with '/', and combined with the ip address, it indicates the source mount path in the form of `server:path`""",
    )
    server: Optional[str] = Field(
        default=None, description="""Required. IP address of the NFS server."""
    )


class NfsMountDict(TypedDict, total=False):
    """Represents a mount configuration for Network File System (NFS) to mount."""

    mount_point: Optional[str]
    """Required. Destination mount path. The NFS will be mounted for the user under /mnt/nfs/"""

    path: Optional[str]
    """Required. Source path exported from NFS server. Has to start with '/', and combined with the ip address, it indicates the source mount path in the form of `server:path`"""

    server: Optional[str]
    """Required. IP address of the NFS server."""


NfsMountOrDict = Union[NfsMount, NfsMountDict]


class PythonPackageSpec(_common.BaseModel):
    """The spec of a Python packaged code."""

    args: Optional[list[str]] = Field(
        default=None,
        description="""Command line arguments to be passed to the Python task.""",
    )
    env: Optional[list[EnvVar]] = Field(
        default=None,
        description="""Environment variables to be passed to the python module. Maximum limit is 100.""",
    )
    executor_image_uri: Optional[str] = Field(
        default=None,
        description="""Required. The URI of a container image in Artifact Registry that will run the provided Python package. Vertex AI provides a wide range of executor images with pre-installed packages to meet users' various use cases. See the list of [pre-built containers for training](https://cloud.google.com/vertex-ai/docs/training/pre-built-containers). You must use an image from this list.""",
    )
    package_uris: Optional[list[str]] = Field(
        default=None,
        description="""Required. The Google Cloud Storage location of the Python package files which are the training program and its dependent packages. The maximum number of package URIs is 100.""",
    )
    python_module: Optional[str] = Field(
        default=None,
        description="""Required. The Python module name to run after installing the packages.""",
    )


class PythonPackageSpecDict(TypedDict, total=False):
    """The spec of a Python packaged code."""

    args: Optional[list[str]]
    """Command line arguments to be passed to the Python task."""

    env: Optional[list[EnvVarDict]]
    """Environment variables to be passed to the python module. Maximum limit is 100."""

    executor_image_uri: Optional[str]
    """Required. The URI of a container image in Artifact Registry that will run the provided Python package. Vertex AI provides a wide range of executor images with pre-installed packages to meet users' various use cases. See the list of [pre-built containers for training](https://cloud.google.com/vertex-ai/docs/training/pre-built-containers). You must use an image from this list."""

    package_uris: Optional[list[str]]
    """Required. The Google Cloud Storage location of the Python package files which are the training program and its dependent packages. The maximum number of package URIs is 100."""

    python_module: Optional[str]
    """Required. The Python module name to run after installing the packages."""


PythonPackageSpecOrDict = Union[PythonPackageSpec, PythonPackageSpecDict]


class WorkerPoolSpec(_common.BaseModel):
    """Represents the spec of a worker pool in a job."""

    container_spec: Optional[ContainerSpec] = Field(
        default=None, description="""The custom container task."""
    )
    disk_spec: Optional[DiskSpec] = Field(default=None, description="""Disk spec.""")
    lustre_mounts: Optional[list[LustreMount]] = Field(
        default=None, description="""Optional. List of Lustre mounts."""
    )
    machine_spec: Optional[MachineSpec] = Field(
        default=None,
        description="""Optional. Immutable. The specification of a single machine.""",
    )
    nfs_mounts: Optional[list[NfsMount]] = Field(
        default=None, description="""Optional. List of NFS mount spec."""
    )
    python_package_spec: Optional[PythonPackageSpec] = Field(
        default=None, description="""The Python packaged task."""
    )
    replica_count: Optional[int] = Field(
        default=None,
        description="""Optional. The number of worker replicas to use for this worker pool.""",
    )


class WorkerPoolSpecDict(TypedDict, total=False):
    """Represents the spec of a worker pool in a job."""

    container_spec: Optional[ContainerSpecDict]
    """The custom container task."""

    disk_spec: Optional[DiskSpecDict]
    """Disk spec."""

    lustre_mounts: Optional[list[LustreMountDict]]
    """Optional. List of Lustre mounts."""

    machine_spec: Optional[MachineSpecDict]
    """Optional. Immutable. The specification of a single machine."""

    nfs_mounts: Optional[list[NfsMountDict]]
    """Optional. List of NFS mount spec."""

    python_package_spec: Optional[PythonPackageSpecDict]
    """The Python packaged task."""

    replica_count: Optional[int]
    """Optional. The number of worker replicas to use for this worker pool."""


WorkerPoolSpecOrDict = Union[WorkerPoolSpec, WorkerPoolSpecDict]


class CustomJobSpec(_common.BaseModel):
    """Represents a job that runs custom workloads such as a Docker container or a Python package."""

    base_output_directory: Optional[genai_types.GcsDestination] = Field(
        default=None,
        description="""The Cloud Storage location to store the output of this CustomJob or HyperparameterTuningJob. For HyperparameterTuningJob, the baseOutputDirectory of each child CustomJob backing a Trial is set to a subdirectory of name id under its parent HyperparameterTuningJob's baseOutputDirectory. The following Vertex AI environment variables will be passed to containers or python modules when this field is set: For CustomJob: * AIP_MODEL_DIR = `/model/` * AIP_CHECKPOINT_DIR = `/checkpoints/` * AIP_TENSORBOARD_LOG_DIR = `/logs/` For CustomJob backing a Trial of HyperparameterTuningJob: * AIP_MODEL_DIR = `//model/` * AIP_CHECKPOINT_DIR = `//checkpoints/` * AIP_TENSORBOARD_LOG_DIR = `//logs/`""",
    )
    enable_dashboard_access: Optional[bool] = Field(
        default=None,
        description="""Optional. Whether you want Vertex AI to enable access to the customized dashboard in training chief container. If set to `true`, you can access the dashboard at the URIs given by CustomJob.web_access_uris or Trial.web_access_uris (within HyperparameterTuningJob.trials).""",
    )
    enable_web_access: Optional[bool] = Field(
        default=None,
        description="""Optional. Whether you want Vertex AI to enable [interactive shell access](https://cloud.google.com/vertex-ai/docs/training/monitor-debug-interactive-shell) to training containers. If set to `true`, you can access interactive shells at the URIs given by CustomJob.web_access_uris or Trial.web_access_uris (within HyperparameterTuningJob.trials).""",
    )
    experiment: Optional[str] = Field(
        default=None,
        description="""Optional. The Experiment associated with this job. Format: `projects/{project}/locations/{location}/metadataStores/{metadataStores}/contexts/{experiment-name}`""",
    )
    experiment_run: Optional[str] = Field(
        default=None,
        description="""Optional. The Experiment Run associated with this job. Format: `projects/{project}/locations/{location}/metadataStores/{metadataStores}/contexts/{experiment-name}-{experiment-run-name}`""",
    )
    models: Optional[list[str]] = Field(
        default=None,
        description="""Optional. The name of the Model resources for which to generate a mapping to artifact URIs. Applicable only to some of the Google-provided custom jobs. Format: `projects/{project}/locations/{location}/models/{model}` In order to retrieve a specific version of the model, also provide the version ID or version alias. Example: `projects/{project}/locations/{location}/models/{model}@2` or `projects/{project}/locations/{location}/models/{model}@golden` If no version ID or alias is specified, the "default" version will be returned. The "default" version alias is created for the first version of the model, and can be moved to other versions later on. There will be exactly one default version.""",
    )
    network: Optional[str] = Field(
        default=None,
        description="""Optional. The full name of the Compute Engine [network](/compute/docs/networks-and-firewalls#networks) to which the Job should be peered. For example, `projects/12345/global/networks/myVPC`. [Format](/compute/docs/reference/rest/v1/networks/insert) is of the form `projects/{project}/global/networks/{network}`. Where {project} is a project number, as in `12345`, and {network} is a network name. To specify this field, you must have already [configured VPC Network Peering for Vertex AI](https://cloud.google.com/vertex-ai/docs/general/vpc-peering). If this field is left unspecified, the job is not peered with any network.""",
    )
    persistent_resource_id: Optional[str] = Field(
        default=None,
        description="""Optional. The ID of the PersistentResource in the same Project and Location which to run If this is specified, the job will be run on existing machines held by the PersistentResource instead of on-demand short-live machines. The network and CMEK configs on the job should be consistent with those on the PersistentResource, otherwise, the job will be rejected.""",
    )
    protected_artifact_location_id: Optional[str] = Field(
        default=None,
        description="""The ID of the location to store protected artifacts. e.g. us-central1. Populate only when the location is different than CustomJob location. List of supported locations: https://cloud.google.com/vertex-ai/docs/general/locations""",
    )
    psc_interface_config: Optional[PscInterfaceConfig] = Field(
        default=None, description="""Optional. Configuration for PSC-I for CustomJob."""
    )
    reserved_ip_ranges: Optional[list[str]] = Field(
        default=None,
        description="""Optional. A list of names for the reserved ip ranges under the VPC network that can be used for this job. If set, we will deploy the job within the provided ip ranges. Otherwise, the job will be deployed to any ip ranges under the provided VPC network. Example: ['vertex-ai-ip-range'].""",
    )
    scheduling: Optional[Scheduling] = Field(
        default=None, description="""Scheduling options for a CustomJob."""
    )
    service_account: Optional[str] = Field(
        default=None,
        description="""Specifies the service account for workload run-as account. Users submitting jobs must have act-as permission on this run-as account. If unspecified, the [Vertex AI Custom Code Service Agent](https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents) for the CustomJob's project is used.""",
    )
    tensorboard: Optional[str] = Field(
        default=None,
        description="""Optional. The name of a Vertex AI Tensorboard resource to which this CustomJob will upload Tensorboard logs. Format: `projects/{project}/locations/{location}/tensorboards/{tensorboard}`""",
    )
    worker_pool_specs: Optional[list[WorkerPoolSpec]] = Field(
        default=None,
        description="""Required. The spec of the worker pools including machine type and Docker image. All worker pools except the first one are optional and can be skipped by providing an empty value.""",
    )


class CustomJobSpecDict(TypedDict, total=False):
    """Represents a job that runs custom workloads such as a Docker container or a Python package."""

    base_output_directory: Optional[genai_types.GcsDestinationDict]
    """The Cloud Storage location to store the output of this CustomJob or HyperparameterTuningJob. For HyperparameterTuningJob, the baseOutputDirectory of each child CustomJob backing a Trial is set to a subdirectory of name id under its parent HyperparameterTuningJob's baseOutputDirectory. The following Vertex AI environment variables will be passed to containers or python modules when this field is set: For CustomJob: * AIP_MODEL_DIR = `/model/` * AIP_CHECKPOINT_DIR = `/checkpoints/` * AIP_TENSORBOARD_LOG_DIR = `/logs/` For CustomJob backing a Trial of HyperparameterTuningJob: * AIP_MODEL_DIR = `//model/` * AIP_CHECKPOINT_DIR = `//checkpoints/` * AIP_TENSORBOARD_LOG_DIR = `//logs/`"""

    enable_dashboard_access: Optional[bool]
    """Optional. Whether you want Vertex AI to enable access to the customized dashboard in training chief container. If set to `true`, you can access the dashboard at the URIs given by CustomJob.web_access_uris or Trial.web_access_uris (within HyperparameterTuningJob.trials)."""

    enable_web_access: Optional[bool]
    """Optional. Whether you want Vertex AI to enable [interactive shell access](https://cloud.google.com/vertex-ai/docs/training/monitor-debug-interactive-shell) to training containers. If set to `true`, you can access interactive shells at the URIs given by CustomJob.web_access_uris or Trial.web_access_uris (within HyperparameterTuningJob.trials)."""

    experiment: Optional[str]
    """Optional. The Experiment associated with this job. Format: `projects/{project}/locations/{location}/metadataStores/{metadataStores}/contexts/{experiment-name}`"""

    experiment_run: Optional[str]
    """Optional. The Experiment Run associated with this job. Format: `projects/{project}/locations/{location}/metadataStores/{metadataStores}/contexts/{experiment-name}-{experiment-run-name}`"""

    models: Optional[list[str]]
    """Optional. The name of the Model resources for which to generate a mapping to artifact URIs. Applicable only to some of the Google-provided custom jobs. Format: `projects/{project}/locations/{location}/models/{model}` In order to retrieve a specific version of the model, also provide the version ID or version alias. Example: `projects/{project}/locations/{location}/models/{model}@2` or `projects/{project}/locations/{location}/models/{model}@golden` If no version ID or alias is specified, the "default" version will be returned. The "default" version alias is created for the first version of the model, and can be moved to other versions later on. There will be exactly one default version."""

    network: Optional[str]
    """Optional. The full name of the Compute Engine [network](/compute/docs/networks-and-firewalls#networks) to which the Job should be peered. For example, `projects/12345/global/networks/myVPC`. [Format](/compute/docs/reference/rest/v1/networks/insert) is of the form `projects/{project}/global/networks/{network}`. Where {project} is a project number, as in `12345`, and {network} is a network name. To specify this field, you must have already [configured VPC Network Peering for Vertex AI](https://cloud.google.com/vertex-ai/docs/general/vpc-peering). If this field is left unspecified, the job is not peered with any network."""

    persistent_resource_id: Optional[str]
    """Optional. The ID of the PersistentResource in the same Project and Location which to run If this is specified, the job will be run on existing machines held by the PersistentResource instead of on-demand short-live machines. The network and CMEK configs on the job should be consistent with those on the PersistentResource, otherwise, the job will be rejected."""

    protected_artifact_location_id: Optional[str]
    """The ID of the location to store protected artifacts. e.g. us-central1. Populate only when the location is different than CustomJob location. List of supported locations: https://cloud.google.com/vertex-ai/docs/general/locations"""

    psc_interface_config: Optional[PscInterfaceConfigDict]
    """Optional. Configuration for PSC-I for CustomJob."""

    reserved_ip_ranges: Optional[list[str]]
    """Optional. A list of names for the reserved ip ranges under the VPC network that can be used for this job. If set, we will deploy the job within the provided ip ranges. Otherwise, the job will be deployed to any ip ranges under the provided VPC network. Example: ['vertex-ai-ip-range']."""

    scheduling: Optional[SchedulingDict]
    """Scheduling options for a CustomJob."""

    service_account: Optional[str]
    """Specifies the service account for workload run-as account. Users submitting jobs must have act-as permission on this run-as account. If unspecified, the [Vertex AI Custom Code Service Agent](https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents) for the CustomJob's project is used."""

    tensorboard: Optional[str]
    """Optional. The name of a Vertex AI Tensorboard resource to which this CustomJob will upload Tensorboard logs. Format: `projects/{project}/locations/{location}/tensorboards/{tensorboard}`"""

    worker_pool_specs: Optional[list[WorkerPoolSpecDict]]
    """Required. The spec of the worker pools including machine type and Docker image. All worker pools except the first one are optional and can be skipped by providing an empty value."""


CustomJobSpecOrDict = Union[CustomJobSpec, CustomJobSpecDict]


class CustomJob(_common.BaseModel):
    """Represents a job that runs custom workloads such as a Docker container or a Python package."""

    display_name: Optional[str] = Field(
        default=None,
        description="""Required. The display name of the CustomJob. The name can be up to 128 characters long and can consist of any UTF-8 characters.""",
    )
    job_spec: Optional[CustomJobSpec] = Field(
        default=None, description="""Required. Job spec."""
    )
    encryption_spec: Optional[genai_types.EncryptionSpec] = Field(
        default=None,
        description="""Customer-managed encryption key options for a CustomJob. If this is set, then all resources created by the CustomJob will be encrypted with the provided encryption key.""",
    )
    state: Optional[genai_types.JobState] = Field(
        default=None, description="""Output only. The detailed state of the job."""
    )
    error: Optional[genai_types.GoogleRpcStatus] = Field(
        default=None,
        description="""Output only. Only populated when job's state is `JOB_STATE_FAILED` or `JOB_STATE_CANCELLED`.""",
    )
    create_time: Optional[datetime.datetime] = Field(
        default=None,
        description="""Output only. Time when the CustomJob was created.""",
    )
    end_time: Optional[datetime.datetime] = Field(
        default=None,
        description="""Output only. Time when the CustomJob entered any of the following states: `JOB_STATE_SUCCEEDED`, `JOB_STATE_FAILED`, `JOB_STATE_CANCELLED`.""",
    )
    labels: Optional[dict[str, str]] = Field(
        default=None,
        description="""The labels with user-defined metadata to organize CustomJobs. Label keys and values can be no longer than 64 characters (Unicode codepoints), can only contain lowercase letters, numeric characters, underscores and dashes. International characters are allowed. See https://goo.gl/xmQnxf for more information and examples of labels.""",
    )
    name: Optional[str] = Field(
        default=None, description="""Output only. Resource name of a CustomJob."""
    )
    satisfies_pzi: Optional[bool] = Field(
        default=None, description="""Output only. Reserved for future use."""
    )
    satisfies_pzs: Optional[bool] = Field(
        default=None, description="""Output only. Reserved for future use."""
    )
    start_time: Optional[datetime.datetime] = Field(
        default=None,
        description="""Output only. Time when the CustomJob for the first time entered the `JOB_STATE_RUNNING` state.""",
    )
    update_time: Optional[datetime.datetime] = Field(
        default=None,
        description="""Output only. Time when the CustomJob was most recently updated.""",
    )
    web_access_uris: Optional[dict[str, str]] = Field(
        default=None,
        description="""Output only. URIs for accessing [interactive shells](https://cloud.google.com/vertex-ai/docs/training/monitor-debug-interactive-shell) (one URI for each training node). Only available if job_spec.enable_web_access is `true`. The keys are names of each node in the training job; for example, `workerpool0-0` for the primary node, `workerpool1-0` for the first node in the second worker pool, and `workerpool1-1` for the second node in the second worker pool. The values are the URIs for each node's interactive shell.""",
    )


class CustomJobDict(TypedDict, total=False):
    """Represents a job that runs custom workloads such as a Docker container or a Python package."""

    display_name: Optional[str]
    """Required. The display name of the CustomJob. The name can be up to 128 characters long and can consist of any UTF-8 characters."""

    job_spec: Optional[CustomJobSpecDict]
    """Required. Job spec."""

    encryption_spec: Optional[genai_types.EncryptionSpecDict]
    """Customer-managed encryption key options for a CustomJob. If this is set, then all resources created by the CustomJob will be encrypted with the provided encryption key."""

    state: Optional[genai_types.JobState]
    """Output only. The detailed state of the job."""

    error: Optional[genai_types.GoogleRpcStatusDict]
    """Output only. Only populated when job's state is `JOB_STATE_FAILED` or `JOB_STATE_CANCELLED`."""

    create_time: Optional[datetime.datetime]
    """Output only. Time when the CustomJob was created."""

    end_time: Optional[datetime.datetime]
    """Output only. Time when the CustomJob entered any of the following states: `JOB_STATE_SUCCEEDED`, `JOB_STATE_FAILED`, `JOB_STATE_CANCELLED`."""

    labels: Optional[dict[str, str]]
    """The labels with user-defined metadata to organize CustomJobs. Label keys and values can be no longer than 64 characters (Unicode codepoints), can only contain lowercase letters, numeric characters, underscores and dashes. International characters are allowed. See https://goo.gl/xmQnxf for more information and examples of labels."""

    name: Optional[str]
    """Output only. Resource name of a CustomJob."""

    satisfies_pzi: Optional[bool]
    """Output only. Reserved for future use."""

    satisfies_pzs: Optional[bool]
    """Output only. Reserved for future use."""

    start_time: Optional[datetime.datetime]
    """Output only. Time when the CustomJob for the first time entered the `JOB_STATE_RUNNING` state."""

    update_time: Optional[datetime.datetime]
    """Output only. Time when the CustomJob was most recently updated."""

    web_access_uris: Optional[dict[str, str]]
    """Output only. URIs for accessing [interactive shells](https://cloud.google.com/vertex-ai/docs/training/monitor-debug-interactive-shell) (one URI for each training node). Only available if job_spec.enable_web_access is `true`. The keys are names of each node in the training job; for example, `workerpool0-0` for the primary node, `workerpool1-0` for the first node in the second worker pool, and `workerpool1-1` for the second node in the second worker pool. The values are the URIs for each node's interactive shell."""


CustomJobOrDict = Union[CustomJob, CustomJobDict]


class VertexBaseConfig(_common.BaseModel):
    """Base config for Vertex AI."""

    http_options: Optional[genai_types.HttpOptions] = Field(
        default=None, description="""Used to override HTTP request options."""
    )


class VertexBaseConfigDict(TypedDict, total=False):
    """Base config for Vertex AI."""

    http_options: Optional[genai_types.HttpOptionsDict]
    """Used to override HTTP request options."""


VertexBaseConfigOrDict = Union[VertexBaseConfig, VertexBaseConfigDict]


class _CustomJobParameters(_common.BaseModel):
    """Represents a job that runs custom workloads such as a Docker container or a Python package."""

    custom_job: Optional[CustomJob] = Field(default=None, description="""""")
    config: Optional[VertexBaseConfig] = Field(default=None, description="""""")


class _CustomJobParametersDict(TypedDict, total=False):
    """Represents a job that runs custom workloads such as a Docker container or a Python package."""

    custom_job: Optional[CustomJobDict]
    """"""

    config: Optional[VertexBaseConfigDict]
    """"""


_CustomJobParametersOrDict = Union[_CustomJobParameters, _CustomJobParametersDict]


class _GetCustomJobParameters(_common.BaseModel):
    """Represents a job that runs custom workloads such as a Docker container or a Python package."""

    name: Optional[str] = Field(default=None, description="""""")
    config: Optional[VertexBaseConfig] = Field(default=None, description="""""")


class _GetCustomJobParametersDict(TypedDict, total=False):
    """Represents a job that runs custom workloads such as a Docker container or a Python package."""

    name: Optional[str]
    """"""

    config: Optional[VertexBaseConfigDict]
    """"""


_GetCustomJobParametersOrDict = Union[
    _GetCustomJobParameters, _GetCustomJobParametersDict
]


class SecretRef(_common.BaseModel):
    """Reference to a secret stored in the Cloud Secret Manager that will provide the value for this environment variable."""

    secret: Optional[str] = Field(
        default=None,
        description="""Required. The name of the secret in Cloud Secret Manager. Format: {secret_name}.""",
    )
    version: Optional[str] = Field(
        default=None,
        description="""The Cloud Secret Manager secret version. Can be 'latest' for the latest version, an integer for a specific version, or a version alias.""",
    )


class SecretRefDict(TypedDict, total=False):
    """Reference to a secret stored in the Cloud Secret Manager that will provide the value for this environment variable."""

    secret: Optional[str]
    """Required. The name of the secret in Cloud Secret Manager. Format: {secret_name}."""

    version: Optional[str]
    """The Cloud Secret Manager secret version. Can be 'latest' for the latest version, an integer for a specific version, or a version alias."""


SecretRefOrDict = Union[SecretRef, SecretRefDict]


class SecretEnvVar(_common.BaseModel):
    """Represents an environment variable where the value is a secret in Cloud Secret Manager."""

    name: Optional[str] = Field(
        default=None,
        description="""Required. Name of the secret environment variable.""",
    )
    secret_ref: Optional[SecretRef] = Field(
        default=None,
        description="""Required. Reference to a secret stored in the Cloud Secret Manager that will provide the value for this environment variable.""",
    )


class SecretEnvVarDict(TypedDict, total=False):
    """Represents an environment variable where the value is a secret in Cloud Secret Manager."""

    name: Optional[str]
    """Required. Name of the secret environment variable."""

    secret_ref: Optional[SecretRefDict]
    """Required. Reference to a secret stored in the Cloud Secret Manager that will provide the value for this environment variable."""


SecretEnvVarOrDict = Union[SecretEnvVar, SecretEnvVarDict]


class ReasoningEngineSpecDeploymentSpec(_common.BaseModel):
    """The specification of a Reasoning Engine deployment."""

    agent_server_mode: Optional[AgentServerMode] = Field(
        default=None, description="""The agent server mode."""
    )
    container_concurrency: Optional[int] = Field(
        default=None,
        description="""Optional. The maximum number of concurrent requests that can be handled by the application. Defaults to 8.""",
    )
    env: Optional[list[EnvVar]] = Field(
        default=None,
        description="""Optional. Environment variables to be set with the Reasoning Engine deployment. The environment variables can be updated through the UpdateReasoningEngine API.""",
    )
    max_instances: Optional[int] = Field(
        default=None,
        description="""Optional. The maximum number of application instances that can be launched to handle increased traffic. Defaults to 100. Range: [1, 1000]. If VPC-SC or PSC-I is enabled, the acceptable range is [1, 100].""",
    )
    min_instances: Optional[int] = Field(
        default=None,
        description="""Optional. The minimum number of application instances that will be kept running at all times. Defaults to 1.""",
    )
    psc_interface_config: Optional[PscInterfaceConfig] = Field(
        default=None, description="""Optional. Configuration for PSC-I."""
    )
    resource_limits: Optional[dict[str, str]] = Field(
        default=None,
        description="""Optional. Resource limits for each container. Only 'cpu' and 'memory' keys are supported. Defaults to {"cpu": "4", "memory": "4Gi"}. * The only supported values for CPU are '1', '2', '4', and '8'. For more information, go to https://cloud.google.com/run/docs/configuring/cpu. * For supported 'memory' values and syntax, go to https://cloud.google.com/run/docs/configuring/memory-limits""",
    )
    secret_env: Optional[list[SecretEnvVar]] = Field(
        default=None,
        description="""Optional. Environment variables where the value is a secret in Cloud Secret Manager. To use this feature, add 'Secret Manager Secret Accessor' role (roles/secretmanager.secretAccessor) to AI Platform Reasoning Engine Service Agent.""",
    )


class ReasoningEngineSpecDeploymentSpecDict(TypedDict, total=False):
    """The specification of a Reasoning Engine deployment."""

    agent_server_mode: Optional[AgentServerMode]
    """The agent server mode."""

    container_concurrency: Optional[int]
    """Optional. The maximum number of concurrent requests that can be handled by the application. Defaults to 8."""

    env: Optional[list[EnvVarDict]]
    """Optional. Environment variables to be set with the Reasoning Engine deployment. The environment variables can be updated through the UpdateReasoningEngine API."""

    max_instances: Optional[int]
    """Optional. The maximum number of application instances that can be launched to handle increased traffic. Defaults to 100. Range: [1, 1000]. If VPC-SC or PSC-I is enabled, the acceptable range is [1, 100]."""

    min_instances: Optional[int]
    """Optional. The minimum number of application instances that will be kept running at all times. Defaults to 1."""

    psc_interface_config: Optional[PscInterfaceConfigDict]
    """Optional. Configuration for PSC-I."""

    resource_limits: Optional[dict[str, str]]
    """Optional. Resource limits for each container. Only 'cpu' and 'memory' keys are supported. Defaults to {"cpu": "4", "memory": "4Gi"}. * The only supported values for CPU are '1', '2', '4', and '8'. For more information, go to https://cloud.google.com/run/docs/configuring/cpu. * For supported 'memory' values and syntax, go to https://cloud.google.com/run/docs/configuring/memory-limits"""

    secret_env: Optional[list[SecretEnvVarDict]]
    """Optional. Environment variables where the value is a secret in Cloud Secret Manager. To use this feature, add 'Secret Manager Secret Accessor' role (roles/secretmanager.secretAccessor) to AI Platform Reasoning Engine Service Agent."""


ReasoningEngineSpecDeploymentSpecOrDict = Union[
    ReasoningEngineSpecDeploymentSpec, ReasoningEngineSpecDeploymentSpecDict
]


class ReasoningEngineSpecPackageSpec(_common.BaseModel):
    """User-provided package specification, containing pickled object and package requirements."""

    dependency_files_gcs_uri: Optional[str] = Field(
        default=None,
        description="""Optional. The Cloud Storage URI of the dependency files in tar.gz format.""",
    )
    pickle_object_gcs_uri: Optional[str] = Field(
        default=None,
        description="""Optional. The Cloud Storage URI of the pickled python object.""",
    )
    python_version: Optional[str] = Field(
        default=None,
        description="""Optional. The Python version. Currently support 3.8, 3.9, 3.10, 3.11. If not specified, default value is 3.10.""",
    )
    requirements_gcs_uri: Optional[str] = Field(
        default=None,
        description="""Optional. The Cloud Storage URI of the `requirements.txt` file""",
    )


class ReasoningEngineSpecPackageSpecDict(TypedDict, total=False):
    """User-provided package specification, containing pickled object and package requirements."""

    dependency_files_gcs_uri: Optional[str]
    """Optional. The Cloud Storage URI of the dependency files in tar.gz format."""

    pickle_object_gcs_uri: Optional[str]
    """Optional. The Cloud Storage URI of the pickled python object."""

    python_version: Optional[str]
    """Optional. The Python version. Currently support 3.8, 3.9, 3.10, 3.11. If not specified, default value is 3.10."""

    requirements_gcs_uri: Optional[str]
    """Optional. The Cloud Storage URI of the `requirements.txt` file"""


ReasoningEngineSpecPackageSpecOrDict = Union[
    ReasoningEngineSpecPackageSpec, ReasoningEngineSpecPackageSpecDict
]


class ReasoningEngineSpecSourceCodeSpecInlineSource(_common.BaseModel):
    """Specifies source code provided as a byte stream."""

    source_archive: Optional[bytes] = Field(
        default=None,
        description="""Required. Input only. The application source code archive, provided as a compressed tarball (.tar.gz) file.""",
    )


class ReasoningEngineSpecSourceCodeSpecInlineSourceDict(TypedDict, total=False):
    """Specifies source code provided as a byte stream."""

    source_archive: Optional[bytes]
    """Required. Input only. The application source code archive, provided as a compressed tarball (.tar.gz) file."""


ReasoningEngineSpecSourceCodeSpecInlineSourceOrDict = Union[
    ReasoningEngineSpecSourceCodeSpecInlineSource,
    ReasoningEngineSpecSourceCodeSpecInlineSourceDict,
]


class ReasoningEngineSpecSourceCodeSpecPythonSpec(_common.BaseModel):
    """Specification for running a Python application from source."""

    entrypoint_module: Optional[str] = Field(
        default=None,
        description="""Optional. The Python module to load as the entrypoint, specified as a fully qualified module name. For example: path.to.agent. If not specified, defaults to "agent". The project root will be added to Python sys.path, allowing imports to be specified relative to the root.""",
    )
    entrypoint_object: Optional[str] = Field(
        default=None,
        description="""Optional. The name of the callable object within the `entrypoint_module` to use as the application If not specified, defaults to "root_agent".""",
    )
    requirements_file: Optional[str] = Field(
        default=None,
        description="""Optional. The path to the requirements file, relative to the source root. If not specified, defaults to "requirements.txt".""",
    )
    version: Optional[str] = Field(
        default=None,
        description="""Optional. The version of Python to use. Support version includes 3.9, 3.10, 3.11, 3.12, 3.13. If not specified, default value is 3.10.""",
    )


class ReasoningEngineSpecSourceCodeSpecPythonSpecDict(TypedDict, total=False):
    """Specification for running a Python application from source."""

    entrypoint_module: Optional[str]
    """Optional. The Python module to load as the entrypoint, specified as a fully qualified module name. For example: path.to.agent. If not specified, defaults to "agent". The project root will be added to Python sys.path, allowing imports to be specified relative to the root."""

    entrypoint_object: Optional[str]
    """Optional. The name of the callable object within the `entrypoint_module` to use as the application If not specified, defaults to "root_agent"."""

    requirements_file: Optional[str]
    """Optional. The path to the requirements file, relative to the source root. If not specified, defaults to "requirements.txt"."""

    version: Optional[str]
    """Optional. The version of Python to use. Support version includes 3.9, 3.10, 3.11, 3.12, 3.13. If not specified, default value is 3.10."""


ReasoningEngineSpecSourceCodeSpecPythonSpecOrDict = Union[
    ReasoningEngineSpecSourceCodeSpecPythonSpec,
    ReasoningEngineSpecSourceCodeSpecPythonSpecDict,
]


class ReasoningEngineSpecSourceCodeSpec(_common.BaseModel):
    """Specification for deploying from source code."""

    inline_source: Optional[ReasoningEngineSpecSourceCodeSpecInlineSource] = Field(
        default=None, description="""Source code is provided directly in the request."""
    )
    python_spec: Optional[ReasoningEngineSpecSourceCodeSpecPythonSpec] = Field(
        default=None, description="""Configuration for a Python application."""
    )


class ReasoningEngineSpecSourceCodeSpecDict(TypedDict, total=False):
    """Specification for deploying from source code."""

    inline_source: Optional[ReasoningEngineSpecSourceCodeSpecInlineSourceDict]
    """Source code is provided directly in the request."""

    python_spec: Optional[ReasoningEngineSpecSourceCodeSpecPythonSpecDict]
    """Configuration for a Python application."""


ReasoningEngineSpecSourceCodeSpecOrDict = Union[
    ReasoningEngineSpecSourceCodeSpec, ReasoningEngineSpecSourceCodeSpecDict
]


class ReasoningEngineSpec(_common.BaseModel):
    """The specification of an agent engine."""

    agent_framework: Optional[str] = Field(
        default=None,
        description="""Optional. The OSS agent framework used to develop the agent. Currently supported values: "google-adk", "langchain", "langgraph", "ag2", "llama-index", "custom".""",
    )
    class_methods: Optional[list[dict[str, Any]]] = Field(
        default=None,
        description="""Optional. Declarations for object class methods in OpenAPI specification format.""",
    )
    deployment_spec: Optional[ReasoningEngineSpecDeploymentSpec] = Field(
        default=None,
        description="""Optional. The specification of a Reasoning Engine deployment.""",
    )
    effective_identity: Optional[str] = Field(
        default=None,
        description="""Output only. The identity to use for the Reasoning Engine. It can contain one of the following values: * service-{project}@gcp-sa-aiplatform-re.googleapis.com (for SERVICE_AGENT identity type) * {name}@{project}.gserviceaccount.com (for SERVICE_ACCOUNT identity type) * agents.global.{org}.system.id.goog/resources/aiplatform/projects/{project}/locations/{location}/reasoningEngines/{reasoning_engine} (for AGENT_IDENTITY identity type)""",
    )
    identity_type: Optional[IdentityType] = Field(
        default=None,
        description="""Optional. The identity type to use for the Reasoning Engine. If not specified, the `service_account` field will be used if set, otherwise the default Vertex AI Reasoning Engine Service Agent in the project will be used.""",
    )
    package_spec: Optional[ReasoningEngineSpecPackageSpec] = Field(
        default=None,
        description="""Optional. User provided package spec of the ReasoningEngine. Ignored when users directly specify a deployment image through `deployment_spec.first_party_image_override`, but keeping the field_behavior to avoid introducing breaking changes. The `deployment_source` field should not be set if `package_spec` is specified.""",
    )
    service_account: Optional[str] = Field(
        default=None,
        description="""Optional. The service account that the Reasoning Engine artifact runs as. It should have "roles/storage.objectViewer" for reading the user project's Cloud Storage and "roles/aiplatform.user" for using Vertex extensions. If not specified, the Vertex AI Reasoning Engine Service Agent in the project will be used.""",
    )
    source_code_spec: Optional[ReasoningEngineSpecSourceCodeSpec] = Field(
        default=None,
        description="""Deploy from source code files with a defined entrypoint.""",
    )


class ReasoningEngineSpecDict(TypedDict, total=False):
    """The specification of an agent engine."""

    agent_framework: Optional[str]
    """Optional. The OSS agent framework used to develop the agent. Currently supported values: "google-adk", "langchain", "langgraph", "ag2", "llama-index", "custom"."""

    class_methods: Optional[list[dict[str, Any]]]
    """Optional. Declarations for object class methods in OpenAPI specification format."""

    deployment_spec: Optional[ReasoningEngineSpecDeploymentSpecDict]
    """Optional. The specification of a Reasoning Engine deployment."""

    effective_identity: Optional[str]
    """Output only. The identity to use for the Reasoning Engine. It can contain one of the following values: * service-{project}@gcp-sa-aiplatform-re.googleapis.com (for SERVICE_AGENT identity type) * {name}@{project}.gserviceaccount.com (for SERVICE_ACCOUNT identity type) * agents.global.{org}.system.id.goog/resources/aiplatform/projects/{project}/locations/{location}/reasoningEngines/{reasoning_engine} (for AGENT_IDENTITY identity type)"""

    identity_type: Optional[IdentityType]
    """Optional. The identity type to use for the Reasoning Engine. If not specified, the `service_account` field will be used if set, otherwise the default Vertex AI Reasoning Engine Service Agent in the project will be used."""

    package_spec: Optional[ReasoningEngineSpecPackageSpecDict]
    """Optional. User provided package spec of the ReasoningEngine. Ignored when users directly specify a deployment image through `deployment_spec.first_party_image_override`, but keeping the field_behavior to avoid introducing breaking changes. The `deployment_source` field should not be set if `package_spec` is specified."""

    service_account: Optional[str]
    """Optional. The service account that the Reasoning Engine artifact runs as. It should have "roles/storage.objectViewer" for reading the user project's Cloud Storage and "roles/aiplatform.user" for using Vertex extensions. If not specified, the Vertex AI Reasoning Engine Service Agent in the project will be used."""

    source_code_spec: Optional[ReasoningEngineSpecSourceCodeSpecDict]
    """Deploy from source code files with a defined entrypoint."""


ReasoningEngineSpecOrDict = Union[ReasoningEngineSpec, ReasoningEngineSpecDict]


class MemoryBankCustomizationConfigMemoryTopicCustomMemoryTopic(_common.BaseModel):
    """A custom memory topic defined by the developer."""

    label: Optional[str] = Field(
        default=None, description="""Required. The label of the topic."""
    )
    description: Optional[str] = Field(
        default=None,
        description="""Required. Description of the memory topic. This should explain what information should be extracted for this topic.""",
    )


class MemoryBankCustomizationConfigMemoryTopicCustomMemoryTopicDict(
    TypedDict, total=False
):
    """A custom memory topic defined by the developer."""

    label: Optional[str]
    """Required. The label of the topic."""

    description: Optional[str]
    """Required. Description of the memory topic. This should explain what information should be extracted for this topic."""


MemoryBankCustomizationConfigMemoryTopicCustomMemoryTopicOrDict = Union[
    MemoryBankCustomizationConfigMemoryTopicCustomMemoryTopic,
    MemoryBankCustomizationConfigMemoryTopicCustomMemoryTopicDict,
]


class MemoryBankCustomizationConfigMemoryTopicManagedMemoryTopic(_common.BaseModel):
    """A managed memory topic defined by the system."""

    managed_topic_enum: Optional[ManagedTopicEnum] = Field(
        default=None, description="""Required. The managed topic."""
    )


class MemoryBankCustomizationConfigMemoryTopicManagedMemoryTopicDict(
    TypedDict, total=False
):
    """A managed memory topic defined by the system."""

    managed_topic_enum: Optional[ManagedTopicEnum]
    """Required. The managed topic."""


MemoryBankCustomizationConfigMemoryTopicManagedMemoryTopicOrDict = Union[
    MemoryBankCustomizationConfigMemoryTopicManagedMemoryTopic,
    MemoryBankCustomizationConfigMemoryTopicManagedMemoryTopicDict,
]


class MemoryBankCustomizationConfigMemoryTopic(_common.BaseModel):
    """A topic of information that should be extracted from conversations and stored as memories."""

    custom_memory_topic: Optional[
        MemoryBankCustomizationConfigMemoryTopicCustomMemoryTopic
    ] = Field(
        default=None, description="""A custom memory topic defined by the developer."""
    )
    managed_memory_topic: Optional[
        MemoryBankCustomizationConfigMemoryTopicManagedMemoryTopic
    ] = Field(
        default=None, description="""A managed memory topic defined by Memory Bank."""
    )


class MemoryBankCustomizationConfigMemoryTopicDict(TypedDict, total=False):
    """A topic of information that should be extracted from conversations and stored as memories."""

    custom_memory_topic: Optional[
        MemoryBankCustomizationConfigMemoryTopicCustomMemoryTopicDict
    ]
    """A custom memory topic defined by the developer."""

    managed_memory_topic: Optional[
        MemoryBankCustomizationConfigMemoryTopicManagedMemoryTopicDict
    ]
    """A managed memory topic defined by Memory Bank."""


MemoryBankCustomizationConfigMemoryTopicOrDict = Union[
    MemoryBankCustomizationConfigMemoryTopic,
    MemoryBankCustomizationConfigMemoryTopicDict,
]


class MemoryBankCustomizationConfigGenerateMemoriesExampleConversationSourceEvent(
    _common.BaseModel
):
    """The conversation source event for generating memories."""

    content: Optional[genai_types.Content] = Field(
        default=None, description="""Required. The content of the event."""
    )


class MemoryBankCustomizationConfigGenerateMemoriesExampleConversationSourceEventDict(
    TypedDict, total=False
):
    """The conversation source event for generating memories."""

    content: Optional[genai_types.ContentDict]
    """Required. The content of the event."""


MemoryBankCustomizationConfigGenerateMemoriesExampleConversationSourceEventOrDict = (
    Union[
        MemoryBankCustomizationConfigGenerateMemoriesExampleConversationSourceEvent,
        MemoryBankCustomizationConfigGenerateMemoriesExampleConversationSourceEventDict,
    ]
)


class MemoryBankCustomizationConfigGenerateMemoriesExampleConversationSource(
    _common.BaseModel
):
    """A conversation source for the example. This is similar to `DirectContentsSource`."""

    events: Optional[
        list[
            MemoryBankCustomizationConfigGenerateMemoriesExampleConversationSourceEvent
        ]
    ] = Field(
        default=None,
        description="""Optional. The input conversation events for the example.""",
    )


class MemoryBankCustomizationConfigGenerateMemoriesExampleConversationSourceDict(
    TypedDict, total=False
):
    """A conversation source for the example. This is similar to `DirectContentsSource`."""

    events: Optional[
        list[
            MemoryBankCustomizationConfigGenerateMemoriesExampleConversationSourceEventDict
        ]
    ]
    """Optional. The input conversation events for the example."""


MemoryBankCustomizationConfigGenerateMemoriesExampleConversationSourceOrDict = Union[
    MemoryBankCustomizationConfigGenerateMemoriesExampleConversationSource,
    MemoryBankCustomizationConfigGenerateMemoriesExampleConversationSourceDict,
]


class MemoryTopicId(_common.BaseModel):
    """The topic ID for a memory."""

    custom_memory_topic_label: Optional[str] = Field(
        default=None, description="""Optional. The custom memory topic label."""
    )
    managed_memory_topic: Optional[ManagedTopicEnum] = Field(
        default=None, description="""Optional. The managed memory topic."""
    )


class MemoryTopicIdDict(TypedDict, total=False):
    """The topic ID for a memory."""

    custom_memory_topic_label: Optional[str]
    """Optional. The custom memory topic label."""

    managed_memory_topic: Optional[ManagedTopicEnum]
    """Optional. The managed memory topic."""


MemoryTopicIdOrDict = Union[MemoryTopicId, MemoryTopicIdDict]


class MemoryBankCustomizationConfigGenerateMemoriesExampleGeneratedMemory(
    _common.BaseModel
):
    """A memory generated by the operation."""

    fact: Optional[str] = Field(
        default=None, description="""Required. The fact to generate a memory from."""
    )
    topics: Optional[list[MemoryTopicId]] = Field(
        default=None,
        description="""Optional. The list of topics that the memory should be associated with. For example, use `custom_memory_topic_label = "jargon"` if the extracted memory is an example of memory extraction for the custom topic `jargon`.""",
    )


class MemoryBankCustomizationConfigGenerateMemoriesExampleGeneratedMemoryDict(
    TypedDict, total=False
):
    """A memory generated by the operation."""

    fact: Optional[str]
    """Required. The fact to generate a memory from."""

    topics: Optional[list[MemoryTopicIdDict]]
    """Optional. The list of topics that the memory should be associated with. For example, use `custom_memory_topic_label = "jargon"` if the extracted memory is an example of memory extraction for the custom topic `jargon`."""


MemoryBankCustomizationConfigGenerateMemoriesExampleGeneratedMemoryOrDict = Union[
    MemoryBankCustomizationConfigGenerateMemoriesExampleGeneratedMemory,
    MemoryBankCustomizationConfigGenerateMemoriesExampleGeneratedMemoryDict,
]


class MemoryBankCustomizationConfigGenerateMemoriesExample(_common.BaseModel):
    """An example of how to generate memories for a particular scope."""

    conversation_source: Optional[
        MemoryBankCustomizationConfigGenerateMemoriesExampleConversationSource
    ] = Field(default=None, description="""A conversation source for the example.""")
    generated_memories: Optional[
        list[MemoryBankCustomizationConfigGenerateMemoriesExampleGeneratedMemory]
    ] = Field(
        default=None,
        description="""Optional. The memories that are expected to be generated from the input conversation. An empty list indicates that no memories are expected to be generated for the input conversation.""",
    )


class MemoryBankCustomizationConfigGenerateMemoriesExampleDict(TypedDict, total=False):
    """An example of how to generate memories for a particular scope."""

    conversation_source: Optional[
        MemoryBankCustomizationConfigGenerateMemoriesExampleConversationSourceDict
    ]
    """A conversation source for the example."""

    generated_memories: Optional[
        list[MemoryBankCustomizationConfigGenerateMemoriesExampleGeneratedMemoryDict]
    ]
    """Optional. The memories that are expected to be generated from the input conversation. An empty list indicates that no memories are expected to be generated for the input conversation."""


MemoryBankCustomizationConfigGenerateMemoriesExampleOrDict = Union[
    MemoryBankCustomizationConfigGenerateMemoriesExample,
    MemoryBankCustomizationConfigGenerateMemoriesExampleDict,
]


class MemoryBankCustomizationConfig(_common.BaseModel):
    """Configuration for organizing memories for a particular scope."""

    scope_keys: Optional[list[str]] = Field(
        default=None,
        description="""Optional. The scope keys (i.e. 'user_id') for which to use this config. A request's scope must include all of the provided keys for the config to be used (order does not matter). If empty, then the config will be used for all requests that do not have a more specific config. Only one default config is allowed per Memory Bank.""",
    )
    memory_topics: Optional[list[MemoryBankCustomizationConfigMemoryTopic]] = Field(
        default=None,
        description="""Optional. Topics of information that should be extracted from conversations and stored as memories. If not set, then Memory Bank's default topics will be used.""",
    )
    generate_memories_examples: Optional[
        list[MemoryBankCustomizationConfigGenerateMemoriesExample]
    ] = Field(
        default=None,
        description="""Optional. Examples of how to generate memories for a particular scope.""",
    )


class MemoryBankCustomizationConfigDict(TypedDict, total=False):
    """Configuration for organizing memories for a particular scope."""

    scope_keys: Optional[list[str]]
    """Optional. The scope keys (i.e. 'user_id') for which to use this config. A request's scope must include all of the provided keys for the config to be used (order does not matter). If empty, then the config will be used for all requests that do not have a more specific config. Only one default config is allowed per Memory Bank."""

    memory_topics: Optional[list[MemoryBankCustomizationConfigMemoryTopicDict]]
    """Optional. Topics of information that should be extracted from conversations and stored as memories. If not set, then Memory Bank's default topics will be used."""

    generate_memories_examples: Optional[
        list[MemoryBankCustomizationConfigGenerateMemoriesExampleDict]
    ]
    """Optional. Examples of how to generate memories for a particular scope."""


MemoryBankCustomizationConfigOrDict = Union[
    MemoryBankCustomizationConfig, MemoryBankCustomizationConfigDict
]


class ReasoningEngineContextSpecMemoryBankConfigGenerationConfig(_common.BaseModel):
    """Configuration for how to generate memories."""

    model: Optional[str] = Field(
        default=None,
        description="""Required. The model used to generate memories. Format: `projects/{project}/locations/{location}/publishers/google/models/{model}`.""",
    )


class ReasoningEngineContextSpecMemoryBankConfigGenerationConfigDict(
    TypedDict, total=False
):
    """Configuration for how to generate memories."""

    model: Optional[str]
    """Required. The model used to generate memories. Format: `projects/{project}/locations/{location}/publishers/google/models/{model}`."""


ReasoningEngineContextSpecMemoryBankConfigGenerationConfigOrDict = Union[
    ReasoningEngineContextSpecMemoryBankConfigGenerationConfig,
    ReasoningEngineContextSpecMemoryBankConfigGenerationConfigDict,
]


class ReasoningEngineContextSpecMemoryBankConfigSimilaritySearchConfig(
    _common.BaseModel
):
    """Configuration for how to perform similarity search on memories."""

    embedding_model: Optional[str] = Field(
        default=None,
        description="""Required. The model used to generate embeddings to lookup similar memories. Format: `projects/{project}/locations/{location}/publishers/google/models/{model}`.""",
    )


class ReasoningEngineContextSpecMemoryBankConfigSimilaritySearchConfigDict(
    TypedDict, total=False
):
    """Configuration for how to perform similarity search on memories."""

    embedding_model: Optional[str]
    """Required. The model used to generate embeddings to lookup similar memories. Format: `projects/{project}/locations/{location}/publishers/google/models/{model}`."""


ReasoningEngineContextSpecMemoryBankConfigSimilaritySearchConfigOrDict = Union[
    ReasoningEngineContextSpecMemoryBankConfigSimilaritySearchConfig,
    ReasoningEngineContextSpecMemoryBankConfigSimilaritySearchConfigDict,
]


class ReasoningEngineContextSpecMemoryBankConfigTtlConfigGranularTtlConfig(
    _common.BaseModel
):
    """Configuration for TTL of the memories in the Memory Bank based on the action that created or updated the memory."""

    create_ttl: Optional[str] = Field(
        default=None,
        description="""Optional. The TTL duration for memories uploaded via CreateMemory.""",
    )
    generate_created_ttl: Optional[str] = Field(
        default=None,
        description="""Optional. The TTL duration for memories newly generated via GenerateMemories (GenerateMemoriesResponse.GeneratedMemory.Action.CREATED).""",
    )
    generate_updated_ttl: Optional[str] = Field(
        default=None,
        description="""Optional. The TTL duration for memories updated via GenerateMemories (GenerateMemoriesResponse.GeneratedMemory.Action.UPDATED). In the case of an UPDATE action, the `expire_time` of the existing memory will be updated to the new value (now + TTL).""",
    )


class ReasoningEngineContextSpecMemoryBankConfigTtlConfigGranularTtlConfigDict(
    TypedDict, total=False
):
    """Configuration for TTL of the memories in the Memory Bank based on the action that created or updated the memory."""

    create_ttl: Optional[str]
    """Optional. The TTL duration for memories uploaded via CreateMemory."""

    generate_created_ttl: Optional[str]
    """Optional. The TTL duration for memories newly generated via GenerateMemories (GenerateMemoriesResponse.GeneratedMemory.Action.CREATED)."""

    generate_updated_ttl: Optional[str]
    """Optional. The TTL duration for memories updated via GenerateMemories (GenerateMemoriesResponse.GeneratedMemory.Action.UPDATED). In the case of an UPDATE action, the `expire_time` of the existing memory will be updated to the new value (now + TTL)."""


ReasoningEngineContextSpecMemoryBankConfigTtlConfigGranularTtlConfigOrDict = Union[
    ReasoningEngineContextSpecMemoryBankConfigTtlConfigGranularTtlConfig,
    ReasoningEngineContextSpecMemoryBankConfigTtlConfigGranularTtlConfigDict,
]


class ReasoningEngineContextSpecMemoryBankConfigTtlConfig(_common.BaseModel):
    """Configuration for automatically setting the TTL ("time-to-live") of the memories in the Memory Bank."""

    default_ttl: Optional[str] = Field(
        default=None,
        description="""Optional. The default TTL duration of the memories in the Memory Bank. This applies to all operations that create or update a memory.""",
    )
    granular_ttl_config: Optional[
        ReasoningEngineContextSpecMemoryBankConfigTtlConfigGranularTtlConfig
    ] = Field(
        default=None,
        description="""Optional. The granular TTL configuration of the memories in the Memory Bank.""",
    )
    memory_revision_default_ttl: Optional[str] = Field(
        default=None,
        description="""Optional. The default TTL duration of the memory revisions in the Memory Bank. This applies to all operations that create a memory revision. If not set, a default TTL of 365 days will be used.""",
    )


class ReasoningEngineContextSpecMemoryBankConfigTtlConfigDict(TypedDict, total=False):
    """Configuration for automatically setting the TTL ("time-to-live") of the memories in the Memory Bank."""

    default_ttl: Optional[str]
    """Optional. The default TTL duration of the memories in the Memory Bank. This applies to all operations that create or update a memory."""

    granular_ttl_config: Optional[
        ReasoningEngineContextSpecMemoryBankConfigTtlConfigGranularTtlConfigDict
    ]
    """Optional. The granular TTL configuration of the memories in the Memory Bank."""

    memory_revision_default_ttl: Optional[str]
    """Optional. The default TTL duration of the memory revisions in the Memory Bank. This applies to all operations that create a memory revision. If not set, a default TTL of 365 days will be used."""


ReasoningEngineContextSpecMemoryBankConfigTtlConfigOrDict = Union[
    ReasoningEngineContextSpecMemoryBankConfigTtlConfig,
    ReasoningEngineContextSpecMemoryBankConfigTtlConfigDict,
]


class ReasoningEngineContextSpecMemoryBankConfig(_common.BaseModel):
    """Specification for a Memory Bank."""

    customization_configs: Optional[list[MemoryBankCustomizationConfig]] = Field(
        default=None,
        description="""Optional. Configuration for how to customize Memory Bank behavior for a particular scope.""",
    )
    generation_config: Optional[
        ReasoningEngineContextSpecMemoryBankConfigGenerationConfig
    ] = Field(
        default=None,
        description="""Optional. Configuration for how to generate memories for the Memory Bank.""",
    )
    similarity_search_config: Optional[
        ReasoningEngineContextSpecMemoryBankConfigSimilaritySearchConfig
    ] = Field(
        default=None,
        description="""Optional. Configuration for how to perform similarity search on memories. If not set, the Memory Bank will use the default embedding model `text-embedding-005`.""",
    )
    ttl_config: Optional[ReasoningEngineContextSpecMemoryBankConfigTtlConfig] = Field(
        default=None,
        description="""Optional. Configuration for automatic TTL ("time-to-live") of the memories in the Memory Bank. If not set, TTL will not be applied automatically. The TTL can be explicitly set by modifying the `expire_time` of each Memory resource.""",
    )
    disable_memory_revisions: Optional[bool] = Field(
        default=None,
        description="""If true, no memory revisions will be created for any requests to the Memory Bank.""",
    )


class ReasoningEngineContextSpecMemoryBankConfigDict(TypedDict, total=False):
    """Specification for a Memory Bank."""

    customization_configs: Optional[list[MemoryBankCustomizationConfigDict]]
    """Optional. Configuration for how to customize Memory Bank behavior for a particular scope."""

    generation_config: Optional[
        ReasoningEngineContextSpecMemoryBankConfigGenerationConfigDict
    ]
    """Optional. Configuration for how to generate memories for the Memory Bank."""

    similarity_search_config: Optional[
        ReasoningEngineContextSpecMemoryBankConfigSimilaritySearchConfigDict
    ]
    """Optional. Configuration for how to perform similarity search on memories. If not set, the Memory Bank will use the default embedding model `text-embedding-005`."""

    ttl_config: Optional[ReasoningEngineContextSpecMemoryBankConfigTtlConfigDict]
    """Optional. Configuration for automatic TTL ("time-to-live") of the memories in the Memory Bank. If not set, TTL will not be applied automatically. The TTL can be explicitly set by modifying the `expire_time` of each Memory resource."""

    disable_memory_revisions: Optional[bool]
    """If true, no memory revisions will be created for any requests to the Memory Bank."""


ReasoningEngineContextSpecMemoryBankConfigOrDict = Union[
    ReasoningEngineContextSpecMemoryBankConfig,
    ReasoningEngineContextSpecMemoryBankConfigDict,
]


class ReasoningEngineContextSpec(_common.BaseModel):
    """The configuration for agent engine sub-resources to manage context."""

    memory_bank_config: Optional[ReasoningEngineContextSpecMemoryBankConfig] = Field(
        default=None,
        description="""Optional. Specification for a Memory Bank, which manages memories for the Agent Engine.""",
    )


class ReasoningEngineContextSpecDict(TypedDict, total=False):
    """The configuration for agent engine sub-resources to manage context."""

    memory_bank_config: Optional[ReasoningEngineContextSpecMemoryBankConfigDict]
    """Optional. Specification for a Memory Bank, which manages memories for the Agent Engine."""


ReasoningEngineContextSpecOrDict = Union[
    ReasoningEngineContextSpec, ReasoningEngineContextSpecDict
]


class CreateAgentEngineConfig(_common.BaseModel):
    """Config for create agent engine."""

    http_options: Optional[genai_types.HttpOptions] = Field(
        default=None, description="""Used to override HTTP request options."""
    )
    display_name: Optional[str] = Field(
        default=None,
        description="""The user-defined name of the Agent Engine.

      The display name can be up to 128 characters long and can comprise any
      UTF-8 characters.
      """,
    )
    description: Optional[str] = Field(
        default=None, description="""The description of the Agent Engine."""
    )
    spec: Optional[ReasoningEngineSpec] = Field(
        default=None, description="""Optional. Configurations of the Agent Engine."""
    )
    context_spec: Optional[ReasoningEngineContextSpec] = Field(
        default=None,
        description="""Optional. The context spec to be used for the Agent Engine.""",
    )
    psc_interface_config: Optional[PscInterfaceConfig] = Field(
        default=None,
        description="""Optional. The PSC interface config for PSC-I to be used for the
      Agent Engine.""",
    )
    min_instances: Optional[int] = Field(
        default=None,
        description="""The minimum number of instances to run for the Agent Engine.
      Defaults to 1. Range: [0, 10].
      """,
    )
    max_instances: Optional[int] = Field(
        default=None,
        description="""The maximum number of instances to run for the Agent Engine.
      Defaults to 100. Range: [1, 1000].
      If VPC-SC or PSC-I is enabled, the acceptable range is [1, 100].
      """,
    )
    resource_limits: Optional[dict[str, str]] = Field(
        default=None,
        description="""The resource limits to be applied to the Agent Engine.
      Required keys: 'cpu' and 'memory'.
      Supported values for 'cpu': '1', '2', '4', '6', '8'.
      Supported values for 'memory': '1Gi', '2Gi', ..., '32Gi'.
      """,
    )
    container_concurrency: Optional[int] = Field(
        default=None,
        description="""The container concurrency to be used for the Agent Engine.
      Recommended value: 2 * cpu + 1. Defaults to 9.
      """,
    )
    encryption_spec: Optional[genai_types.EncryptionSpec] = Field(
        default=None,
        description="""The encryption spec to be used for the Agent Engine.""",
    )
    labels: Optional[dict[str, str]] = Field(
        default=None, description="""The labels to be used for the Agent Engine."""
    )
    class_methods: Optional[list[dict[str, Any]]] = Field(
        default=None,
        description="""The class methods to be used for the Agent Engine.
      If specified, they'll override the class methods that are autogenerated by
      default. By default, methods are generated by inspecting the agent object
      and generating a corresponding method for each method defined on the
      agent class.
      """,
    )
    source_packages: Optional[list[str]] = Field(
        default=None,
        description="""The user-provided paths to the source packages (if any).
      If specified, the files in the source packages will be packed into a
      a tarball file, uploaded to Agent Engine's API, and deployed to the
      Agent Engine.
      The following fields will be ignored:
        - agent
        - extra_packages
        - staging_bucket
        - requirements
      The following fields will be used to install and use the agent from the
      source packages:
        - entrypoint_module (required)
        - entrypoint_object (required)
        - requirements_file (optional)
        - class_methods     (required)
      """,
    )
    entrypoint_module: Optional[str] = Field(
        default=None,
        description="""The entrypoint module to be used for the Agent Engine
      This field only used when source_packages is specified.""",
    )
    entrypoint_object: Optional[str] = Field(
        default=None,
        description="""The entrypoint object to be used for the Agent Engine.
      This field only used when source_packages is specified.""",
    )
    requirements_file: Optional[str] = Field(
        default=None,
        description="""The user-provided path to the requirements file (if any).
      This field is only used when source_packages is specified.
      If not specified, agent engine will find and use the `requirements.txt` in
      the source package.
      """,
    )
    agent_framework: Optional[
        Literal["google-adk", "langchain", "langgraph", "ag2", "llama-index", "custom"]
    ] = Field(
        default=None,
        description="""The agent framework to be used for the Agent Engine.
      The OSS agent framework used to develop the agent.
      Currently supported values: "google-adk", "langchain", "langgraph",
      "ag2", "llama-index", "custom".
      If not specified:
      - If `agent` is specified, the agent framework will be auto-detected.
      - If `source_packages` is specified, the agent framework will
        default to "custom".""",
    )
    python_version: Optional[Literal["3.9", "3.10", "3.11", "3.12", "3.13"]] = Field(
        default=None,
        description="""The Python version to be used for the Agent Engine.
      If not specified, it will use the current Python version of the environment.
      Supported versions: "3.9", "3.10", "3.11", "3.12", "3.13".
      """,
    )
    build_options: Optional[dict[str, list[str]]] = Field(
        default=None,
        description="""The build options for the Agent Engine.
      The following keys are supported:
      - installation_scripts:
          Optional. The paths to the installation scripts to be
          executed in the Docker image.
          The scripts must be located in the `installation_scripts`
          subdirectory and the path must be added to `extra_packages`.
      """,
    )


class CreateAgentEngineConfigDict(TypedDict, total=False):
    """Config for create agent engine."""

    http_options: Optional[genai_types.HttpOptionsDict]
    """Used to override HTTP request options."""

    display_name: Optional[str]
    """The user-defined name of the Agent Engine.

      The display name can be up to 128 characters long and can comprise any
      UTF-8 characters.
      """

    description: Optional[str]
    """The description of the Agent Engine."""

    spec: Optional[ReasoningEngineSpecDict]
    """Optional. Configurations of the Agent Engine."""

    context_spec: Optional[ReasoningEngineContextSpecDict]
    """Optional. The context spec to be used for the Agent Engine."""

    psc_interface_config: Optional[PscInterfaceConfigDict]
    """Optional. The PSC interface config for PSC-I to be used for the
      Agent Engine."""

    min_instances: Optional[int]
    """The minimum number of instances to run for the Agent Engine.
      Defaults to 1. Range: [0, 10].
      """

    max_instances: Optional[int]
    """The maximum number of instances to run for the Agent Engine.
      Defaults to 100. Range: [1, 1000].
      If VPC-SC or PSC-I is enabled, the acceptable range is [1, 100].
      """

    resource_limits: Optional[dict[str, str]]
    """The resource limits to be applied to the Agent Engine.
      Required keys: 'cpu' and 'memory'.
      Supported values for 'cpu': '1', '2', '4', '6', '8'.
      Supported values for 'memory': '1Gi', '2Gi', ..., '32Gi'.
      """

    container_concurrency: Optional[int]
    """The container concurrency to be used for the Agent Engine.
      Recommended value: 2 * cpu + 1. Defaults to 9.
      """

    encryption_spec: Optional[genai_types.EncryptionSpecDict]
    """The encryption spec to be used for the Agent Engine."""

    labels: Optional[dict[str, str]]
    """The labels to be used for the Agent Engine."""

    class_methods: Optional[list[dict[str, Any]]]
    """The class methods to be used for the Agent Engine.
      If specified, they'll override the class methods that are autogenerated by
      default. By default, methods are generated by inspecting the agent object
      and generating a corresponding method for each method defined on the
      agent class.
      """

    source_packages: Optional[list[str]]
    """The user-provided paths to the source packages (if any).
      If specified, the files in the source packages will be packed into a
      a tarball file, uploaded to Agent Engine's API, and deployed to the
      Agent Engine.
      The following fields will be ignored:
        - agent
        - extra_packages
        - staging_bucket
        - requirements
      The following fields will be used to install and use the agent from the
      source packages:
        - entrypoint_module (required)
        - entrypoint_object (required)
        - requirements_file (optional)
        - class_methods     (required)
      """

    entrypoint_module: Optional[str]
    """The entrypoint module to be used for the Agent Engine
      This field only used when source_packages is specified."""

    entrypoint_object: Optional[str]
    """The entrypoint object to be used for the Agent Engine.
      This field only used when source_packages is specified."""

    requirements_file: Optional[str]
    """The user-provided path to the requirements file (if any).
      This field is only used when source_packages is specified.
      If not specified, agent engine will find and use the `requirements.txt` in
      the source package.
      """

    agent_framework: Optional[
        Literal["google-adk", "langchain", "langgraph", "ag2", "llama-index", "custom"]
    ]
    """The agent framework to be used for the Agent Engine.
      The OSS agent framework used to develop the agent.
      Currently supported values: "google-adk", "langchain", "langgraph",
      "ag2", "llama-index", "custom".
      If not specified:
      - If `agent` is specified, the agent framework will be auto-detected.
      - If `source_packages` is specified, the agent framework will
        default to "custom"."""

    python_version: Optional[Literal["3.9", "3.10", "3.11", "3.12", "3.13"]]
    """The Python version to be used for the Agent Engine.
      If not specified, it will use the current Python version of the environment.
      Supported versions: "3.9", "3.10", "3.11", "3.12", "3.13".
      """

    build_options: Optional[dict[str, list[str]]]
    """The build options for the Agent Engine.
      The following keys are supported:
      - installation_scripts:
          Optional. The paths to the installation scripts to be
          executed in the Docker image.
          The scripts must be located in the `installation_scripts`
          subdirectory and the path must be added to `extra_packages`.
      """


CreateAgentEngineConfigOrDict = Union[
    CreateAgentEngineConfig, CreateAgentEngineConfigDict
]


class _CreateAgentEngineRequestParameters(_common.BaseModel):
    """Parameters for creating agent engines."""

    config: Optional[CreateAgentEngineConfig] = Field(default=None, description="""""")


class _CreateAgentEngineRequestParametersDict(TypedDict, total=False):
    """Parameters for creating agent engines."""

    config: Optional[CreateAgentEngineConfigDict]
    """"""


_CreateAgentEngineRequestParametersOrDict = Union[
    _CreateAgentEngineRequestParameters, _CreateAgentEngineRequestParametersDict
]


class ReasoningEngine(_common.BaseModel):
    """An agent engine."""

    encryption_spec: Optional[genai_types.EncryptionSpec] = Field(
        default=None,
        description="""Customer-managed encryption key spec for a ReasoningEngine. If set, this ReasoningEngine and all sub-resources of this ReasoningEngine will be secured by this key.""",
    )
    context_spec: Optional[ReasoningEngineContextSpec] = Field(
        default=None,
        description="""Optional. Configuration for how Agent Engine sub-resources should manage context.""",
    )
    create_time: Optional[datetime.datetime] = Field(
        default=None,
        description="""Output only. Timestamp when this ReasoningEngine was created.""",
    )
    description: Optional[str] = Field(
        default=None,
        description="""Optional. The description of the ReasoningEngine.""",
    )
    display_name: Optional[str] = Field(
        default=None,
        description="""Required. The display name of the ReasoningEngine.""",
    )
    etag: Optional[str] = Field(
        default=None,
        description="""Optional. Used to perform consistent read-modify-write updates. If not set, a blind "overwrite" update happens.""",
    )
    labels: Optional[dict[str, str]] = Field(
        default=None, description="""Labels for the ReasoningEngine."""
    )
    name: Optional[str] = Field(
        default=None,
        description="""Identifier. The resource name of the ReasoningEngine. Format: `projects/{project}/locations/{location}/reasoningEngines/{reasoning_engine}`""",
    )
    spec: Optional[ReasoningEngineSpec] = Field(
        default=None, description="""Optional. Configurations of the ReasoningEngine"""
    )
    update_time: Optional[datetime.datetime] = Field(
        default=None,
        description="""Output only. Timestamp when this ReasoningEngine was most recently updated.""",
    )


class ReasoningEngineDict(TypedDict, total=False):
    """An agent engine."""

    encryption_spec: Optional[genai_types.EncryptionSpecDict]
    """Customer-managed encryption key spec for a ReasoningEngine. If set, this ReasoningEngine and all sub-resources of this ReasoningEngine will be secured by this key."""

    context_spec: Optional[ReasoningEngineContextSpecDict]
    """Optional. Configuration for how Agent Engine sub-resources should manage context."""

    create_time: Optional[datetime.datetime]
    """Output only. Timestamp when this ReasoningEngine was created."""

    description: Optional[str]
    """Optional. The description of the ReasoningEngine."""

    display_name: Optional[str]
    """Required. The display name of the ReasoningEngine."""

    etag: Optional[str]
    """Optional. Used to perform consistent read-modify-write updates. If not set, a blind "overwrite" update happens."""

    labels: Optional[dict[str, str]]
    """Labels for the ReasoningEngine."""

    name: Optional[str]
    """Identifier. The resource name of the ReasoningEngine. Format: `projects/{project}/locations/{location}/reasoningEngines/{reasoning_engine}`"""

    spec: Optional[ReasoningEngineSpecDict]
    """Optional. Configurations of the ReasoningEngine"""

    update_time: Optional[datetime.datetime]
    """Output only. Timestamp when this ReasoningEngine was most recently updated."""


ReasoningEngineOrDict = Union[ReasoningEngine, ReasoningEngineDict]


class AgentEngineOperation(_common.BaseModel):
    """Operation that has an agent engine as a response."""

    name: Optional[str] = Field(
        default=None,
        description="""The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`.""",
    )
    metadata: Optional[dict[str, Any]] = Field(
        default=None,
        description="""Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata.  Any method that returns a long-running operation should document the metadata type, if any.""",
    )
    done: Optional[bool] = Field(
        default=None,
        description="""If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available.""",
    )
    error: Optional[dict[str, Any]] = Field(
        default=None,
        description="""The error result of the operation in case of failure or cancellation.""",
    )
    response: Optional[ReasoningEngine] = Field(
        default=None, description="""The created Agent Engine."""
    )


class AgentEngineOperationDict(TypedDict, total=False):
    """Operation that has an agent engine as a response."""

    name: Optional[str]
    """The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`."""

    metadata: Optional[dict[str, Any]]
    """Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata.  Any method that returns a long-running operation should document the metadata type, if any."""

    done: Optional[bool]
    """If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available."""

    error: Optional[dict[str, Any]]
    """The error result of the operation in case of failure or cancellation."""

    response: Optional[ReasoningEngineDict]
    """The created Agent Engine."""


AgentEngineOperationOrDict = Union[AgentEngineOperation, AgentEngineOperationDict]


class DeleteAgentEngineConfig(_common.BaseModel):
    """Config for deleting agent engine."""

    http_options: Optional[genai_types.HttpOptions] = Field(
        default=None, description="""Used to override HTTP request options."""
    )


class DeleteAgentEngineConfigDict(TypedDict, total=False):
    """Config for deleting agent engine."""

    http_options: Optional[genai_types.HttpOptionsDict]
    """Used to override HTTP request options."""


DeleteAgentEngineConfigOrDict = Union[
    DeleteAgentEngineConfig, DeleteAgentEngineConfigDict
]


class _DeleteAgentEngineRequestParameters(_common.BaseModel):
    """Parameters for deleting agent engines."""

    name: Optional[str] = Field(
        default=None, description="""Name of the agent engine."""
    )
    force: Optional[bool] = Field(
        default=False,
        description="""If set to true, any child resources will also be deleted.""",
    )
    config: Optional[DeleteAgentEngineConfig] = Field(default=None, description="""""")


class _DeleteAgentEngineRequestParametersDict(TypedDict, total=False):
    """Parameters for deleting agent engines."""

    name: Optional[str]
    """Name of the agent engine."""

    force: Optional[bool]
    """If set to true, any child resources will also be deleted."""

    config: Optional[DeleteAgentEngineConfigDict]
    """"""


_DeleteAgentEngineRequestParametersOrDict = Union[
    _DeleteAgentEngineRequestParameters, _DeleteAgentEngineRequestParametersDict
]


class DeleteAgentEngineOperation(_common.BaseModel):
    """Operation for deleting agent engines."""

    name: Optional[str] = Field(
        default=None,
        description="""The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`.""",
    )
    metadata: Optional[dict[str, Any]] = Field(
        default=None,
        description="""Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata.  Any method that returns a long-running operation should document the metadata type, if any.""",
    )
    done: Optional[bool] = Field(
        default=None,
        description="""If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available.""",
    )
    error: Optional[dict[str, Any]] = Field(
        default=None,
        description="""The error result of the operation in case of failure or cancellation.""",
    )


class DeleteAgentEngineOperationDict(TypedDict, total=False):
    """Operation for deleting agent engines."""

    name: Optional[str]
    """The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`."""

    metadata: Optional[dict[str, Any]]
    """Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata.  Any method that returns a long-running operation should document the metadata type, if any."""

    done: Optional[bool]
    """If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available."""

    error: Optional[dict[str, Any]]
    """The error result of the operation in case of failure or cancellation."""


DeleteAgentEngineOperationOrDict = Union[
    DeleteAgentEngineOperation, DeleteAgentEngineOperationDict
]


class GetAgentEngineConfig(_common.BaseModel):
    """Config for create agent engine."""

    http_options: Optional[genai_types.HttpOptions] = Field(
        default=None, description="""Used to override HTTP request options."""
    )


class GetAgentEngineConfigDict(TypedDict, total=False):
    """Config for create agent engine."""

    http_options: Optional[genai_types.HttpOptionsDict]
    """Used to override HTTP request options."""


GetAgentEngineConfigOrDict = Union[GetAgentEngineConfig, GetAgentEngineConfigDict]


class _GetAgentEngineRequestParameters(_common.BaseModel):
    """Parameters for getting agent engines."""

    name: Optional[str] = Field(
        default=None, description="""Name of the agent engine."""
    )
    config: Optional[GetAgentEngineConfig] = Field(default=None, description="""""")


class _GetAgentEngineRequestParametersDict(TypedDict, total=False):
    """Parameters for getting agent engines."""

    name: Optional[str]
    """Name of the agent engine."""

    config: Optional[GetAgentEngineConfigDict]
    """"""


_GetAgentEngineRequestParametersOrDict = Union[
    _GetAgentEngineRequestParameters, _GetAgentEngineRequestParametersDict
]


class ListAgentEngineConfig(_common.BaseModel):
    """Config for listing agent engines."""

    http_options: Optional[genai_types.HttpOptions] = Field(
        default=None, description="""Used to override HTTP request options."""
    )
    page_size: Optional[int] = Field(default=None, description="""""")
    page_token: Optional[str] = Field(default=None, description="""""")
    filter: Optional[str] = Field(
        default=None,
        description="""An expression for filtering the results of the request.
      For field names both snake_case and camelCase are supported.""",
    )


class ListAgentEngineConfigDict(TypedDict, total=False):
    """Config for listing agent engines."""

    http_options: Optional[genai_types.HttpOptionsDict]
    """Used to override HTTP request options."""

    page_size: Optional[int]
    """"""

    page_token: Optional[str]
    """"""

    filter: Optional[str]
    """An expression for filtering the results of the request.
      For field names both snake_case and camelCase are supported."""


ListAgentEngineConfigOrDict = Union[ListAgentEngineConfig, ListAgentEngineConfigDict]


class _ListAgentEngineRequestParameters(_common.BaseModel):
    """Parameters for listing agent engines."""

    config: Optional[ListAgentEngineConfig] = Field(default=None, description="""""")


class _ListAgentEngineRequestParametersDict(TypedDict, total=False):
    """Parameters for listing agent engines."""

    config: Optional[ListAgentEngineConfigDict]
    """"""


_ListAgentEngineRequestParametersOrDict = Union[
    _ListAgentEngineRequestParameters, _ListAgentEngineRequestParametersDict
]


class ListReasoningEnginesResponse(_common.BaseModel):
    """Response for listing agent engines."""

    sdk_http_response: Optional[genai_types.HttpResponse] = Field(
        default=None, description="""Used to retain the full HTTP response."""
    )
    next_page_token: Optional[str] = Field(default=None, description="""""")
    reasoning_engines: Optional[list[ReasoningEngine]] = Field(
        default=None,
        description="""List of agent engines.
      """,
    )


class ListReasoningEnginesResponseDict(TypedDict, total=False):
    """Response for listing agent engines."""

    sdk_http_response: Optional[genai_types.HttpResponseDict]
    """Used to retain the full HTTP response."""

    next_page_token: Optional[str]
    """"""

    reasoning_engines: Optional[list[ReasoningEngineDict]]
    """List of agent engines.
      """


ListReasoningEnginesResponseOrDict = Union[
    ListReasoningEnginesResponse, ListReasoningEnginesResponseDict
]


class GetAgentEngineOperationConfig(_common.BaseModel):

    http_options: Optional[genai_types.HttpOptions] = Field(
        default=None, description="""Used to override HTTP request options."""
    )


class GetAgentEngineOperationConfigDict(TypedDict, total=False):

    http_options: Optional[genai_types.HttpOptionsDict]
    """Used to override HTTP request options."""


GetAgentEngineOperationConfigOrDict = Union[
    GetAgentEngineOperationConfig, GetAgentEngineOperationConfigDict
]


class _GetAgentEngineOperationParameters(_common.BaseModel):
    """Parameters for getting an operation with an agent engine as a response."""

    operation_name: Optional[str] = Field(
        default=None, description="""The server-assigned name for the operation."""
    )
    config: Optional[GetAgentEngineOperationConfig] = Field(
        default=None, description="""Used to override the default configuration."""
    )


class _GetAgentEngineOperationParametersDict(TypedDict, total=False):
    """Parameters for getting an operation with an agent engine as a response."""

    operation_name: Optional[str]
    """The server-assigned name for the operation."""

    config: Optional[GetAgentEngineOperationConfigDict]
    """Used to override the default configuration."""


_GetAgentEngineOperationParametersOrDict = Union[
    _GetAgentEngineOperationParameters, _GetAgentEngineOperationParametersDict
]


class QueryAgentEngineConfig(_common.BaseModel):
    """Config for querying agent engines."""

    http_options: Optional[genai_types.HttpOptions] = Field(
        default=None, description="""Used to override HTTP request options."""
    )
    class_method: Optional[str] = Field(
        default=None, description="""The class method to call."""
    )
    input: Optional[dict[str, Any]] = Field(
        default=None, description="""The input to the class method."""
    )
    include_all_fields: Optional[bool] = Field(default=False, description="""""")


class QueryAgentEngineConfigDict(TypedDict, total=False):
    """Config for querying agent engines."""

    http_options: Optional[genai_types.HttpOptionsDict]
    """Used to override HTTP request options."""

    class_method: Optional[str]
    """The class method to call."""

    input: Optional[dict[str, Any]]
    """The input to the class method."""

    include_all_fields: Optional[bool]
    """"""


QueryAgentEngineConfigOrDict = Union[QueryAgentEngineConfig, QueryAgentEngineConfigDict]


class _QueryAgentEngineRequestParameters(_common.BaseModel):
    """Parameters for querying agent engines."""

    name: Optional[str] = Field(
        default=None, description="""Name of the agent engine."""
    )
    config: Optional[QueryAgentEngineConfig] = Field(default=None, description="""""")


class _QueryAgentEngineRequestParametersDict(TypedDict, total=False):
    """Parameters for querying agent engines."""

    name: Optional[str]
    """Name of the agent engine."""

    config: Optional[QueryAgentEngineConfigDict]
    """"""


_QueryAgentEngineRequestParametersOrDict = Union[
    _QueryAgentEngineRequestParameters, _QueryAgentEngineRequestParametersDict
]


class QueryReasoningEngineResponse(_common.BaseModel):
    """The response for querying an agent engine."""

    output: Optional[Any] = Field(
        default=None,
        description="""Response provided by users in JSON object format.""",
    )


class QueryReasoningEngineResponseDict(TypedDict, total=False):
    """The response for querying an agent engine."""

    output: Optional[Any]
    """Response provided by users in JSON object format."""


QueryReasoningEngineResponseOrDict = Union[
    QueryReasoningEngineResponse, QueryReasoningEngineResponseDict
]


class UpdateAgentEngineConfig(_common.BaseModel):
    """Config for updating agent engine."""

    http_options: Optional[genai_types.HttpOptions] = Field(
        default=None, description="""Used to override HTTP request options."""
    )
    display_name: Optional[str] = Field(
        default=None,
        description="""The user-defined name of the Agent Engine.

      The display name can be up to 128 characters long and can comprise any
      UTF-8 characters.
      """,
    )
    description: Optional[str] = Field(
        default=None, description="""The description of the Agent Engine."""
    )
    spec: Optional[ReasoningEngineSpec] = Field(
        default=None, description="""Optional. Configurations of the Agent Engine."""
    )
    context_spec: Optional[ReasoningEngineContextSpec] = Field(
        default=None,
        description="""Optional. The context spec to be used for the Agent Engine.""",
    )
    psc_interface_config: Optional[PscInterfaceConfig] = Field(
        default=None,
        description="""Optional. The PSC interface config for PSC-I to be used for the
      Agent Engine.""",
    )
    min_instances: Optional[int] = Field(
        default=None,
        description="""The minimum number of instances to run for the Agent Engine.
      Defaults to 1. Range: [0, 10].
      """,
    )
    max_instances: Optional[int] = Field(
        default=None,
        description="""The maximum number of instances to run for the Agent Engine.
      Defaults to 100. Range: [1, 1000].
      If VPC-SC or PSC-I is enabled, the acceptable range is [1, 100].
      """,
    )
    resource_limits: Optional[dict[str, str]] = Field(
        default=None,
        description="""The resource limits to be applied to the Agent Engine.
      Required keys: 'cpu' and 'memory'.
      Supported values for 'cpu': '1', '2', '4', '6', '8'.
      Supported values for 'memory': '1Gi', '2Gi', ..., '32Gi'.
      """,
    )
    container_concurrency: Optional[int] = Field(
        default=None,
        description="""The container concurrency to be used for the Agent Engine.
      Recommended value: 2 * cpu + 1. Defaults to 9.
      """,
    )
    encryption_spec: Optional[genai_types.EncryptionSpec] = Field(
        default=None,
        description="""The encryption spec to be used for the Agent Engine.""",
    )
    labels: Optional[dict[str, str]] = Field(
        default=None, description="""The labels to be used for the Agent Engine."""
    )
    class_methods: Optional[list[dict[str, Any]]] = Field(
        default=None,
        description="""The class methods to be used for the Agent Engine.
      If specified, they'll override the class methods that are autogenerated by
      default. By default, methods are generated by inspecting the agent object
      and generating a corresponding method for each method defined on the
      agent class.
      """,
    )
    source_packages: Optional[list[str]] = Field(
        default=None,
        description="""The user-provided paths to the source packages (if any).
      If specified, the files in the source packages will be packed into a
      a tarball file, uploaded to Agent Engine's API, and deployed to the
      Agent Engine.
      The following fields will be ignored:
        - agent
        - extra_packages
        - staging_bucket
        - requirements
      The following fields will be used to install and use the agent from the
      source packages:
        - entrypoint_module (required)
        - entrypoint_object (required)
        - requirements_file (optional)
        - class_methods     (required)
      """,
    )
    entrypoint_module: Optional[str] = Field(
        default=None,
        description="""The entrypoint module to be used for the Agent Engine
      This field only used when source_packages is specified.""",
    )
    entrypoint_object: Optional[str] = Field(
        default=None,
        description="""The entrypoint object to be used for the Agent Engine.
      This field only used when source_packages is specified.""",
    )
    requirements_file: Optional[str] = Field(
        default=None,
        description="""The user-provided path to the requirements file (if any).
      This field is only used when source_packages is specified.
      If not specified, agent engine will find and use the `requirements.txt` in
      the source package.
      """,
    )
    agent_framework: Optional[
        Literal["google-adk", "langchain", "langgraph", "ag2", "llama-index", "custom"]
    ] = Field(
        default=None,
        description="""The agent framework to be used for the Agent Engine.
      The OSS agent framework used to develop the agent.
      Currently supported values: "google-adk", "langchain", "langgraph",
      "ag2", "llama-index", "custom".
      If not specified:
      - If `agent` is specified, the agent framework will be auto-detected.
      - If `source_packages` is specified, the agent framework will
        default to "custom".""",
    )
    python_version: Optional[Literal["3.9", "3.10", "3.11", "3.12", "3.13"]] = Field(
        default=None,
        description="""The Python version to be used for the Agent Engine.
      If not specified, it will use the current Python version of the environment.
      Supported versions: "3.9", "3.10", "3.11", "3.12", "3.13".
      """,
    )
    build_options: Optional[dict[str, list[str]]] = Field(
        default=None,
        description="""The build options for the Agent Engine.
      The following keys are supported:
      - installation_scripts:
          Optional. The paths to the installation scripts to be
          executed in the Docker image.
          The scripts must be located in the `installation_scripts`
          subdirectory and the path must be added to `extra_packages`.
      """,
    )
    update_mask: Optional[str] = Field(
        default=None,
        description="""The update mask to apply. For the `FieldMask` definition, see
      https://protobuf.dev/reference/protobuf/google.protobuf/#field-mask.""",
    )


class UpdateAgentEngineConfigDict(TypedDict, total=False):
    """Config for updating agent engine."""

    http_options: Optional[genai_types.HttpOptionsDict]
    """Used to override HTTP request options."""

    display_name: Optional[str]
    """The user-defined name of the Agent Engine.

      The display name can be up to 128 characters long and can comprise any
      UTF-8 characters.
      """

    description: Optional[str]
    """The description of the Agent Engine."""

    spec: Optional[ReasoningEngineSpecDict]
    """Optional. Configurations of the Agent Engine."""

    context_spec: Optional[ReasoningEngineContextSpecDict]
    """Optional. The context spec to be used for the Agent Engine."""

    psc_interface_config: Optional[PscInterfaceConfigDict]
    """Optional. The PSC interface config for PSC-I to be used for the
      Agent Engine."""

    min_instances: Optional[int]
    """The minimum number of instances to run for the Agent Engine.
      Defaults to 1. Range: [0, 10].
      """

    max_instances: Optional[int]
    """The maximum number of instances to run for the Agent Engine.
      Defaults to 100. Range: [1, 1000].
      If VPC-SC or PSC-I is enabled, the acceptable range is [1, 100].
      """

    resource_limits: Optional[dict[str, str]]
    """The resource limits to be applied to the Agent Engine.
      Required keys: 'cpu' and 'memory'.
      Supported values for 'cpu': '1', '2', '4', '6', '8'.
      Supported values for 'memory': '1Gi', '2Gi', ..., '32Gi'.
      """

    container_concurrency: Optional[int]
    """The container concurrency to be used for the Agent Engine.
      Recommended value: 2 * cpu + 1. Defaults to 9.
      """

    encryption_spec: Optional[genai_types.EncryptionSpecDict]
    """The encryption spec to be used for the Agent Engine."""

    labels: Optional[dict[str, str]]
    """The labels to be used for the Agent Engine."""

    class_methods: Optional[list[dict[str, Any]]]
    """The class methods to be used for the Agent Engine.
      If specified, they'll override the class methods that are autogenerated by
      default. By default, methods are generated by inspecting the agent object
      and generating a corresponding method for each method defined on the
      agent class.
      """

    source_packages: Optional[list[str]]
    """The user-provided paths to the source packages (if any).
      If specified, the files in the source packages will be packed into a
      a tarball file, uploaded to Agent Engine's API, and deployed to the
      Agent Engine.
      The following fields will be ignored:
        - agent
        - extra_packages
        - staging_bucket
        - requirements
      The following fields will be used to install and use the agent from the
      source packages:
        - entrypoint_module (required)
        - entrypoint_object (required)
        - requirements_file (optional)
        - class_methods     (required)
      """

    entrypoint_module: Optional[str]
    """The entrypoint module to be used for the Agent Engine
      This field only used when source_packages is specified."""

    entrypoint_object: Optional[str]
    """The entrypoint object to be used for the Agent Engine.
      This field only used when source_packages is specified."""

    requirements_file: Optional[str]
    """The user-provided path to the requirements file (if any).
      This field is only used when source_packages is specified.
      If not specified, agent engine will find and use the `requirements.txt` in
      the source package.
      """

    agent_framework: Optional[
        Literal["google-adk", "langchain", "langgraph", "ag2", "llama-index", "custom"]
    ]
    """The agent framework to be used for the Agent Engine.
      The OSS agent framework used to develop the agent.
      Currently supported values: "google-adk", "langchain", "langgraph",
      "ag2", "llama-index", "custom".
      If not specified:
      - If `agent` is specified, the agent framework will be auto-detected.
      - If `source_packages` is specified, the agent framework will
        default to "custom"."""

    python_version: Optional[Literal["3.9", "3.10", "3.11", "3.12", "3.13"]]
    """The Python version to be used for the Agent Engine.
      If not specified, it will use the current Python version of the environment.
      Supported versions: "3.9", "3.10", "3.11", "3.12", "3.13".
      """

    build_options: Optional[dict[str, list[str]]]
    """The build options for the Agent Engine.
      The following keys are supported:
      - installation_scripts:
          Optional. The paths to the installation scripts to be
          executed in the Docker image.
          The scripts must be located in the `installation_scripts`
          subdirectory and the path must be added to `extra_packages`.
      """

    update_mask: Optional[str]
    """The update mask to apply. For the `FieldMask` definition, see
      https://protobuf.dev/reference/protobuf/google.protobuf/#field-mask."""


UpdateAgentEngineConfigOrDict = Union[
    UpdateAgentEngineConfig, UpdateAgentEngineConfigDict
]


class _UpdateAgentEngineRequestParameters(_common.BaseModel):
    """Parameters for updating agent engines."""

    name: Optional[str] = Field(
        default=None, description="""Name of the agent engine."""
    )
    config: Optional[UpdateAgentEngineConfig] = Field(default=None, description="""""")


class _UpdateAgentEngineRequestParametersDict(TypedDict, total=False):
    """Parameters for updating agent engines."""

    name: Optional[str]
    """Name of the agent engine."""

    config: Optional[UpdateAgentEngineConfigDict]
    """"""


_UpdateAgentEngineRequestParametersOrDict = Union[
    _UpdateAgentEngineRequestParameters, _UpdateAgentEngineRequestParametersDict
]


class AgentEngineMemoryConfig(_common.BaseModel):
    """Config for creating a Memory."""

    http_options: Optional[genai_types.HttpOptions] = Field(
        default=None, description="""Used to override HTTP request options."""
    )
    display_name: Optional[str] = Field(
        default=None, description="""The display name of the memory."""
    )
    description: Optional[str] = Field(
        default=None, description="""The description of the memory."""
    )
    wait_for_completion: Optional[bool] = Field(
        default=True,
        description="""Waits for the operation to complete before returning.""",
    )
    ttl: Optional[str] = Field(
        default=None,
        description="""Optional. Input only. The TTL for this resource.

      The expiration time is computed: now + TTL.""",
    )
    expire_time: Optional[datetime.datetime] = Field(
        default=None,
        description="""Optional. Timestamp of when this resource is considered expired. This is *always* provided on output, regardless of what `expiration` was sent on input.""",
    )
    revision_expire_time: Optional[datetime.datetime] = Field(
        default=None,
        description="""Optional. Input only. Timestamp of when the revision is considered expired. If not set, the memory revision will be kept until manually deleted.""",
    )
    revision_ttl: Optional[str] = Field(
        default=None,
        description="""Optional. Input only. The TTL for the revision. The expiration time is computed: now + TTL.""",
    )
    disable_memory_revisions: Optional[bool] = Field(
        default=None,
        description="""Optional. Input only. If true, no revision will be created for this request.""",
    )
    topics: Optional[list[MemoryTopicId]] = Field(
        default=None, description="""Optional. The topics of the memory."""
    )


class AgentEngineMemoryConfigDict(TypedDict, total=False):
    """Config for creating a Memory."""

    http_options: Optional[genai_types.HttpOptionsDict]
    """Used to override HTTP request options."""

    display_name: Optional[str]
    """The display name of the memory."""

    description: Optional[str]
    """The description of the memory."""

    wait_for_completion: Optional[bool]
    """Waits for the operation to complete before returning."""

    ttl: Optional[str]
    """Optional. Input only. The TTL for this resource.

      The expiration time is computed: now + TTL."""

    expire_time: Optional[datetime.datetime]
    """Optional. Timestamp of when this resource is considered expired. This is *always* provided on output, regardless of what `expiration` was sent on input."""

    revision_expire_time: Optional[datetime.datetime]
    """Optional. Input only. Timestamp of when the revision is considered expired. If not set, the memory revision will be kept until manually deleted."""

    revision_ttl: Optional[str]
    """Optional. Input only. The TTL for the revision. The expiration time is computed: now + TTL."""

    disable_memory_revisions: Optional[bool]
    """Optional. Input only. If true, no revision will be created for this request."""

    topics: Optional[list[MemoryTopicIdDict]]
    """Optional. The topics of the memory."""


AgentEngineMemoryConfigOrDict = Union[
    AgentEngineMemoryConfig, AgentEngineMemoryConfigDict
]


class _CreateAgentEngineMemoryRequestParameters(_common.BaseModel):
    """Parameters for creating Agent Engine Memories."""

    name: Optional[str] = Field(
        default=None,
        description="""Name of the agent engine to create the memory under.""",
    )
    fact: Optional[str] = Field(
        default=None,
        description="""The fact of the memory.

      This is the semantic knowledge extracted from the source content).""",
    )
    scope: Optional[dict[str, str]] = Field(
        default=None,
        description="""The scope of the memory.

      Memories are isolated within their scope. The scope is defined when
      creating or generating memories. Up to 5 key-value pairs are accepted,
      andscope values cannot contain the wildcard character '*'.""",
    )
    config: Optional[AgentEngineMemoryConfig] = Field(default=None, description="""""")


class _CreateAgentEngineMemoryRequestParametersDict(TypedDict, total=False):
    """Parameters for creating Agent Engine Memories."""

    name: Optional[str]
    """Name of the agent engine to create the memory under."""

    fact: Optional[str]
    """The fact of the memory.

      This is the semantic knowledge extracted from the source content)."""

    scope: Optional[dict[str, str]]
    """The scope of the memory.

      Memories are isolated within their scope. The scope is defined when
      creating or generating memories. Up to 5 key-value pairs are accepted,
      andscope values cannot contain the wildcard character '*'."""

    config: Optional[AgentEngineMemoryConfigDict]
    """"""


_CreateAgentEngineMemoryRequestParametersOrDict = Union[
    _CreateAgentEngineMemoryRequestParameters,
    _CreateAgentEngineMemoryRequestParametersDict,
]


class Memory(_common.BaseModel):
    """A memory."""

    expire_time: Optional[datetime.datetime] = Field(
        default=None,
        description="""Optional. Timestamp of when this resource is considered expired. This is *always* provided on output when `expiration` is set on input, regardless of whether `expire_time` or `ttl` was provided.""",
    )
    ttl: Optional[str] = Field(
        default=None,
        description="""Optional. Input only. The TTL for this resource. The expiration time is computed: now + TTL.""",
    )
    revision_expire_time: Optional[datetime.datetime] = Field(
        default=None,
        description="""Optional. Input only. Timestamp of when the revision is considered expired. If not set, the memory revision will be kept until manually deleted.""",
    )
    revision_ttl: Optional[str] = Field(
        default=None,
        description="""Optional. Input only. The TTL for the revision. The expiration time is computed: now + TTL.""",
    )
    disable_memory_revisions: Optional[bool] = Field(
        default=None,
        description="""Optional. Input only. If true, no revision will be created for this request.""",
    )
    create_time: Optional[datetime.datetime] = Field(
        default=None,
        description="""Output only. Timestamp when this Memory was created.""",
    )
    description: Optional[str] = Field(
        default=None, description="""Optional. Description of the Memory."""
    )
    display_name: Optional[str] = Field(
        default=None, description="""Optional. Display name of the Memory."""
    )
    fact: Optional[str] = Field(
        default=None,
        description="""Required. Semantic knowledge extracted from the source content.""",
    )
    name: Optional[str] = Field(
        default=None,
        description="""Identifier. The resource name of the Memory. Format: `projects/{project}/locations/{location}/reasoningEngines/{reasoning_engine}/memories/{memory}`""",
    )
    scope: Optional[dict[str, str]] = Field(
        default=None,
        description="""Required. Immutable. The scope of the Memory. Memories are isolated within their scope. The scope is defined when creating or generating memories. Scope values cannot contain the wildcard character '*'.""",
    )
    update_time: Optional[datetime.datetime] = Field(
        default=None,
        description="""Output only. Timestamp when this Memory was most recently updated.""",
    )
    topics: Optional[list[MemoryTopicId]] = Field(
        default=None, description="""Optional. The Topics of the Memory."""
    )


class MemoryDict(TypedDict, total=False):
    """A memory."""

    expire_time: Optional[datetime.datetime]
    """Optional. Timestamp of when this resource is considered expired. This is *always* provided on output when `expiration` is set on input, regardless of whether `expire_time` or `ttl` was provided."""

    ttl: Optional[str]
    """Optional. Input only. The TTL for this resource. The expiration time is computed: now + TTL."""

    revision_expire_time: Optional[datetime.datetime]
    """Optional. Input only. Timestamp of when the revision is considered expired. If not set, the memory revision will be kept until manually deleted."""

    revision_ttl: Optional[str]
    """Optional. Input only. The TTL for the revision. The expiration time is computed: now + TTL."""

    disable_memory_revisions: Optional[bool]
    """Optional. Input only. If true, no revision will be created for this request."""

    create_time: Optional[datetime.datetime]
    """Output only. Timestamp when this Memory was created."""

    description: Optional[str]
    """Optional. Description of the Memory."""

    display_name: Optional[str]
    """Optional. Display name of the Memory."""

    fact: Optional[str]
    """Required. Semantic knowledge extracted from the source content."""

    name: Optional[str]
    """Identifier. The resource name of the Memory. Format: `projects/{project}/locations/{location}/reasoningEngines/{reasoning_engine}/memories/{memory}`"""

    scope: Optional[dict[str, str]]
    """Required. Immutable. The scope of the Memory. Memories are isolated within their scope. The scope is defined when creating or generating memories. Scope values cannot contain the wildcard character '*'."""

    update_time: Optional[datetime.datetime]
    """Output only. Timestamp when this Memory was most recently updated."""

    topics: Optional[list[MemoryTopicIdDict]]
    """Optional. The Topics of the Memory."""


MemoryOrDict = Union[Memory, MemoryDict]


class AgentEngineMemoryOperation(_common.BaseModel):
    """Operation that has an agent engine memory as a response."""

    name: Optional[str] = Field(
        default=None,
        description="""The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`.""",
    )
    metadata: Optional[dict[str, Any]] = Field(
        default=None,
        description="""Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata.  Any method that returns a long-running operation should document the metadata type, if any.""",
    )
    done: Optional[bool] = Field(
        default=None,
        description="""If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available.""",
    )
    error: Optional[dict[str, Any]] = Field(
        default=None,
        description="""The error result of the operation in case of failure or cancellation.""",
    )
    response: Optional[Memory] = Field(
        default=None, description="""The Agent Engine Memory."""
    )


class AgentEngineMemoryOperationDict(TypedDict, total=False):
    """Operation that has an agent engine memory as a response."""

    name: Optional[str]
    """The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`."""

    metadata: Optional[dict[str, Any]]
    """Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata.  Any method that returns a long-running operation should document the metadata type, if any."""

    done: Optional[bool]
    """If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available."""

    error: Optional[dict[str, Any]]
    """The error result of the operation in case of failure or cancellation."""

    response: Optional[MemoryDict]
    """The Agent Engine Memory."""


AgentEngineMemoryOperationOrDict = Union[
    AgentEngineMemoryOperation, AgentEngineMemoryOperationDict
]


class DeleteAgentEngineMemoryConfig(_common.BaseModel):
    """Config for deleting an Agent Engine Memory."""

    http_options: Optional[genai_types.HttpOptions] = Field(
        default=None, description="""Used to override HTTP request options."""
    )


class DeleteAgentEngineMemoryConfigDict(TypedDict, total=False):
    """Config for deleting an Agent Engine Memory."""

    http_options: Optional[genai_types.HttpOptionsDict]
    """Used to override HTTP request options."""


DeleteAgentEngineMemoryConfigOrDict = Union[
    DeleteAgentEngineMemoryConfig, DeleteAgentEngineMemoryConfigDict
]


class _DeleteAgentEngineMemoryRequestParameters(_common.BaseModel):
    """Parameters for deleting agent engines."""

    name: Optional[str] = Field(
        default=None, description="""Name of the agent engine memory to delete."""
    )
    config: Optional[DeleteAgentEngineMemoryConfig] = Field(
        default=None, description=""""""
    )


class _DeleteAgentEngineMemoryRequestParametersDict(TypedDict, total=False):
    """Parameters for deleting agent engines."""

    name: Optional[str]
    """Name of the agent engine memory to delete."""

    config: Optional[DeleteAgentEngineMemoryConfigDict]
    """"""


_DeleteAgentEngineMemoryRequestParametersOrDict = Union[
    _DeleteAgentEngineMemoryRequestParameters,
    _DeleteAgentEngineMemoryRequestParametersDict,
]


class DeleteAgentEngineMemoryOperation(_common.BaseModel):
    """Operation for deleting agent engines."""

    name: Optional[str] = Field(
        default=None,
        description="""The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`.""",
    )
    metadata: Optional[dict[str, Any]] = Field(
        default=None,
        description="""Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata.  Any method that returns a long-running operation should document the metadata type, if any.""",
    )
    done: Optional[bool] = Field(
        default=None,
        description="""If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available.""",
    )
    error: Optional[dict[str, Any]] = Field(
        default=None,
        description="""The error result of the operation in case of failure or cancellation.""",
    )


class DeleteAgentEngineMemoryOperationDict(TypedDict, total=False):
    """Operation for deleting agent engines."""

    name: Optional[str]
    """The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`."""

    metadata: Optional[dict[str, Any]]
    """Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata.  Any method that returns a long-running operation should document the metadata type, if any."""

    done: Optional[bool]
    """If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available."""

    error: Optional[dict[str, Any]]
    """The error result of the operation in case of failure or cancellation."""


DeleteAgentEngineMemoryOperationOrDict = Union[
    DeleteAgentEngineMemoryOperation, DeleteAgentEngineMemoryOperationDict
]


class GenerateMemoriesRequestVertexSessionSource(_common.BaseModel):
    """The vertex session source for generating memories."""

    end_time: Optional[datetime.datetime] = Field(
        default=None,
        description="""Optional. End time (exclusive) of the time range. If not set, the end time is unbounded.""",
    )
    session: Optional[str] = Field(
        default=None,
        description="""Required. The resource name of the Session to generate memories for. Format: `projects/{project}/locations/{location}/reasoningEngines/{reasoning_engine}/sessions/{session}`""",
    )
    start_time: Optional[datetime.datetime] = Field(
        default=None,
        description="""Optional. Time range to define which session events should be used to generate memories. Start time (inclusive) of the time range. If not set, the start time is unbounded.""",
    )


class GenerateMemoriesRequestVertexSessionSourceDict(TypedDict, total=False):
    """The vertex session source for generating memories."""

    end_time: Optional[datetime.datetime]
    """Optional. End time (exclusive) of the time range. If not set, the end time is unbounded."""

    session: Optional[str]
    """Required. The resource name of the Session to generate memories for. Format: `projects/{project}/locations/{location}/reasoningEngines/{reasoning_engine}/sessions/{session}`"""

    start_time: Optional[datetime.datetime]
    """Optional. Time range to define which session events should be used to generate memories. Start time (inclusive) of the time range. If not set, the start time is unbounded."""


GenerateMemoriesRequestVertexSessionSourceOrDict = Union[
    GenerateMemoriesRequestVertexSessionSource,
    GenerateMemoriesRequestVertexSessionSourceDict,
]


class GenerateMemoriesRequestDirectContentsSourceEvent(_common.BaseModel):

    content: Optional[genai_types.Content] = Field(
        default=None,
        description="""Required. A single piece of content from which to generate memories.""",
    )


class GenerateMemoriesRequestDirectContentsSourceEventDict(TypedDict, total=False):

    content: Optional[genai_types.ContentDict]
    """Required. A single piece of content from which to generate memories."""


GenerateMemoriesRequestDirectContentsSourceEventOrDict = Union[
    GenerateMemoriesRequestDirectContentsSourceEvent,
    GenerateMemoriesRequestDirectContentsSourceEventDict,
]


class GenerateMemoriesRequestDirectContentsSource(_common.BaseModel):
    """The direct contents source for generating memories."""

    events: Optional[list[GenerateMemoriesRequestDirectContentsSourceEvent]] = Field(
        default=None,
        description="""Required. The source content (i.e. chat history) to generate memories from.""",
    )


class GenerateMemoriesRequestDirectContentsSourceDict(TypedDict, total=False):
    """The direct contents source for generating memories."""

    events: Optional[list[GenerateMemoriesRequestDirectContentsSourceEventDict]]
    """Required. The source content (i.e. chat history) to generate memories from."""


GenerateMemoriesRequestDirectContentsSourceOrDict = Union[
    GenerateMemoriesRequestDirectContentsSource,
    GenerateMemoriesRequestDirectContentsSourceDict,
]


class GenerateMemoriesRequestDirectMemoriesSourceDirectMemory(_common.BaseModel):
    """A direct memory to upload to Memory Bank."""

    fact: Optional[str] = Field(
        default=None,
        description="""Required. The fact to consolidate with existing memories.""",
    )
    topics: Optional[list[MemoryTopicId]] = Field(
        default=None,
        description="""Optional. The topics that the consolidated memories should be associated with.""",
    )


class GenerateMemoriesRequestDirectMemoriesSourceDirectMemoryDict(
    TypedDict, total=False
):
    """A direct memory to upload to Memory Bank."""

    fact: Optional[str]
    """Required. The fact to consolidate with existing memories."""

    topics: Optional[list[MemoryTopicIdDict]]
    """Optional. The topics that the consolidated memories should be associated with."""


GenerateMemoriesRequestDirectMemoriesSourceDirectMemoryOrDict = Union[
    GenerateMemoriesRequestDirectMemoriesSourceDirectMemory,
    GenerateMemoriesRequestDirectMemoriesSourceDirectMemoryDict,
]


class GenerateMemoriesRequestDirectMemoriesSource(_common.BaseModel):
    """The direct memories source for generating memories."""

    direct_memories: Optional[
        list[GenerateMemoriesRequestDirectMemoriesSourceDirectMemory]
    ] = Field(
        default=None,
        description="""Required. The direct memories to upload to Memory Bank. At most 5 direct memories are allowed per request.""",
    )


class GenerateMemoriesRequestDirectMemoriesSourceDict(TypedDict, total=False):
    """The direct memories source for generating memories."""

    direct_memories: Optional[
        list[GenerateMemoriesRequestDirectMemoriesSourceDirectMemoryDict]
    ]
    """Required. The direct memories to upload to Memory Bank. At most 5 direct memories are allowed per request."""


GenerateMemoriesRequestDirectMemoriesSourceOrDict = Union[
    GenerateMemoriesRequestDirectMemoriesSource,
    GenerateMemoriesRequestDirectMemoriesSourceDict,
]


class GenerateAgentEngineMemoriesConfig(_common.BaseModel):
    """Config for generating memories."""

    http_options: Optional[genai_types.HttpOptions] = Field(
        default=None, description="""Used to override HTTP request options."""
    )
    disable_consolidation: Optional[bool] = Field(
        default=None,
        description="""Whether to disable consolidation of memories.

      If true, generated memories will not be consolidated with existing
      memories; all generated memories will be added as new memories regardless
      of whether they are duplicates of or contradictory to existing memories.
      By default, memory consolidation is enabled.""",
    )
    wait_for_completion: Optional[bool] = Field(
        default=True,
        description="""Waits for the operation to complete before returning.""",
    )
    revision_labels: Optional[dict[str, str]] = Field(
        default=None,
        description="""Labels to apply to the memory revision. For example, you can use this to label a revision with its data source.""",
    )
    revision_expire_time: Optional[datetime.datetime] = Field(
        default=None,
        description="""Optional. Input only. Timestamp of when the revision is considered expired. If not set, the memory revision will be kept until manually deleted.""",
    )
    revision_ttl: Optional[str] = Field(
        default=None,
        description="""Optional. Input only. The TTL for the revision. The expiration time is computed: now + TTL.""",
    )
    disable_memory_revisions: Optional[bool] = Field(
        default=None,
        description="""Optional. Input only. If true, no revisions will be created for this request.""",
    )


class GenerateAgentEngineMemoriesConfigDict(TypedDict, total=False):
    """Config for generating memories."""

    http_options: Optional[genai_types.HttpOptionsDict]
    """Used to override HTTP request options."""

    disable_consolidation: Optional[bool]
    """Whether to disable consolidation of memories.

      If true, generated memories will not be consolidated with existing
      memories; all generated memories will be added as new memories regardless
      of whether they are duplicates of or contradictory to existing memories.
      By default, memory consolidation is enabled."""

    wait_for_completion: Optional[bool]
    """Waits for the operation to complete before returning."""

    revision_labels: Optional[dict[str, str]]
    """Labels to apply to the memory revision. For example, you can use this to label a revision with its data source."""

    revision_expire_time: Optional[datetime.datetime]
    """Optional. Input only. Timestamp of when the revision is considered expired. If not set, the memory revision will be kept until manually deleted."""

    revision_ttl: Optional[str]
    """Optional. Input only. The TTL for the revision. The expiration time is computed: now + TTL."""

    disable_memory_revisions: Optional[bool]
    """Optional. Input only. If true, no revisions will be created for this request."""


GenerateAgentEngineMemoriesConfigOrDict = Union[
    GenerateAgentEngineMemoriesConfig, GenerateAgentEngineMemoriesConfigDict
]


class _GenerateAgentEngineMemoriesRequestParameters(_common.BaseModel):
    """Parameters for generating agent engine memories."""

    name: Optional[str] = Field(
        default=None,
        description="""Name of the agent engine to generate memories for.""",
    )
    vertex_session_source: Optional[GenerateMemoriesRequestVertexSessionSource] = Field(
        default=None,
        description="""The vertex session source of the memories that should be generated.""",
    )
    direct_contents_source: Optional[GenerateMemoriesRequestDirectContentsSource] = (
        Field(
            default=None,
            description="""The direct contents source of the memories that should be generated.""",
        )
    )
    direct_memories_source: Optional[GenerateMemoriesRequestDirectMemoriesSource] = (
        Field(
            default=None,
            description="""The direct memories source of the memories that should be generated.""",
        )
    )
    scope: Optional[dict[str, str]] = Field(
        default=None,
        description="""The scope of the memories that should be generated.

      Memories will be consolidated across memories with the same scope. Must be
      provided unless the scope is defined in the source content. If `scope` is
      provided, it will override the scope defined in the source content. Scope
      values cannot contain the wildcard character '*'.""",
    )
    config: Optional[GenerateAgentEngineMemoriesConfig] = Field(
        default=None, description=""""""
    )


class _GenerateAgentEngineMemoriesRequestParametersDict(TypedDict, total=False):
    """Parameters for generating agent engine memories."""

    name: Optional[str]
    """Name of the agent engine to generate memories for."""

    vertex_session_source: Optional[GenerateMemoriesRequestVertexSessionSourceDict]
    """The vertex session source of the memories that should be generated."""

    direct_contents_source: Optional[GenerateMemoriesRequestDirectContentsSourceDict]
    """The direct contents source of the memories that should be generated."""

    direct_memories_source: Optional[GenerateMemoriesRequestDirectMemoriesSourceDict]
    """The direct memories source of the memories that should be generated."""

    scope: Optional[dict[str, str]]
    """The scope of the memories that should be generated.

      Memories will be consolidated across memories with the same scope. Must be
      provided unless the scope is defined in the source content. If `scope` is
      provided, it will override the scope defined in the source content. Scope
      values cannot contain the wildcard character '*'."""

    config: Optional[GenerateAgentEngineMemoriesConfigDict]
    """"""


_GenerateAgentEngineMemoriesRequestParametersOrDict = Union[
    _GenerateAgentEngineMemoriesRequestParameters,
    _GenerateAgentEngineMemoriesRequestParametersDict,
]


class GenerateMemoriesResponseGeneratedMemory(_common.BaseModel):
    """A memory that was generated."""

    memory: Optional[Memory] = Field(
        default=None, description="""The generated memory."""
    )
    action: Optional[GenerateMemoriesResponseGeneratedMemoryAction] = Field(
        default=None, description="""The action to take."""
    )
    previous_revision: Optional[str] = Field(
        default=None,
        description="""The previous revision of the Memory before the action was performed. This
      field is only set if the action is `UPDATED` or `DELETED`. You can use
      this to rollback the Memory to the previous revision, undoing the action.
      Format:
      `projects/{project}/locations/{location}/reasoningEngines/{reasoning_engine}/memories/{memory}/revisions/{revision}`""",
    )


class GenerateMemoriesResponseGeneratedMemoryDict(TypedDict, total=False):
    """A memory that was generated."""

    memory: Optional[MemoryDict]
    """The generated memory."""

    action: Optional[GenerateMemoriesResponseGeneratedMemoryAction]
    """The action to take."""

    previous_revision: Optional[str]
    """The previous revision of the Memory before the action was performed. This
      field is only set if the action is `UPDATED` or `DELETED`. You can use
      this to rollback the Memory to the previous revision, undoing the action.
      Format:
      `projects/{project}/locations/{location}/reasoningEngines/{reasoning_engine}/memories/{memory}/revisions/{revision}`"""


GenerateMemoriesResponseGeneratedMemoryOrDict = Union[
    GenerateMemoriesResponseGeneratedMemory, GenerateMemoriesResponseGeneratedMemoryDict
]


class GenerateMemoriesResponse(_common.BaseModel):
    """The response for generating memories."""

    generated_memories: Optional[list[GenerateMemoriesResponseGeneratedMemory]] = Field(
        default=None, description="""The generated memories."""
    )


class GenerateMemoriesResponseDict(TypedDict, total=False):
    """The response for generating memories."""

    generated_memories: Optional[list[GenerateMemoriesResponseGeneratedMemoryDict]]
    """The generated memories."""


GenerateMemoriesResponseOrDict = Union[
    GenerateMemoriesResponse, GenerateMemoriesResponseDict
]


class AgentEngineGenerateMemoriesOperation(_common.BaseModel):
    """Operation that generates memories for an agent engine."""

    name: Optional[str] = Field(
        default=None,
        description="""The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`.""",
    )
    metadata: Optional[dict[str, Any]] = Field(
        default=None,
        description="""Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata.  Any method that returns a long-running operation should document the metadata type, if any.""",
    )
    done: Optional[bool] = Field(
        default=None,
        description="""If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available.""",
    )
    error: Optional[dict[str, Any]] = Field(
        default=None,
        description="""The error result of the operation in case of failure or cancellation.""",
    )
    response: Optional[GenerateMemoriesResponse] = Field(
        default=None, description="""The response for generating memories."""
    )


class AgentEngineGenerateMemoriesOperationDict(TypedDict, total=False):
    """Operation that generates memories for an agent engine."""

    name: Optional[str]
    """The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`."""

    metadata: Optional[dict[str, Any]]
    """Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata.  Any method that returns a long-running operation should document the metadata type, if any."""

    done: Optional[bool]
    """If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available."""

    error: Optional[dict[str, Any]]
    """The error result of the operation in case of failure or cancellation."""

    response: Optional[GenerateMemoriesResponseDict]
    """The response for generating memories."""


AgentEngineGenerateMemoriesOperationOrDict = Union[
    AgentEngineGenerateMemoriesOperation, AgentEngineGenerateMemoriesOperationDict
]


class GetAgentEngineMemoryConfig(_common.BaseModel):
    """Config for getting an Agent Engine Memory."""

    http_options: Optional[genai_types.HttpOptions] = Field(
        default=None, description="""Used to override HTTP request options."""
    )


class GetAgentEngineMemoryConfigDict(TypedDict, total=False):
    """Config for getting an Agent Engine Memory."""

    http_options: Optional[genai_types.HttpOptionsDict]
    """Used to override HTTP request options."""


GetAgentEngineMemoryConfigOrDict = Union[
    GetAgentEngineMemoryConfig, GetAgentEngineMemoryConfigDict
]


class _GetAgentEngineMemoryRequestParameters(_common.BaseModel):
    """Parameters for getting an agent engine."""

    name: Optional[str] = Field(
        default=None, description="""Name of the agent engine."""
    )
    config: Optional[GetAgentEngineMemoryConfig] = Field(
        default=None, description=""""""
    )


class _GetAgentEngineMemoryRequestParametersDict(TypedDict, total=False):
    """Parameters for getting an agent engine."""

    name: Optional[str]
    """Name of the agent engine."""

    config: Optional[GetAgentEngineMemoryConfigDict]
    """"""


_GetAgentEngineMemoryRequestParametersOrDict = Union[
    _GetAgentEngineMemoryRequestParameters, _GetAgentEngineMemoryRequestParametersDict
]


class ListAgentEngineMemoryConfig(_common.BaseModel):
    """Config for listing agent engine memories."""

    http_options: Optional[genai_types.HttpOptions] = Field(
        default=None, description="""Used to override HTTP request options."""
    )
    page_size: Optional[int] = Field(default=None, description="""""")
    page_token: Optional[str] = Field(default=None, description="""""")
    filter: Optional[str] = Field(
        default=None,
        description="""An expression for filtering the results of the request.
      For field names both snake_case and camelCase are supported.""",
    )
    order_by: Optional[str] = Field(
        default=None,
        description="""The standard list order by string. If not specified, the default
      order is `create_time desc`. If specified, the default sorting order of
      provided fields is ascending. More detail in
      [AIP-132](https://google.aip.dev/132).

      Supported fields:
      * `create_time`
      * `update_time`""",
    )


class ListAgentEngineMemoryConfigDict(TypedDict, total=False):
    """Config for listing agent engine memories."""

    http_options: Optional[genai_types.HttpOptionsDict]
    """Used to override HTTP request options."""

    page_size: Optional[int]
    """"""

    page_token: Optional[str]
    """"""

    filter: Optional[str]
    """An expression for filtering the results of the request.
      For field names both snake_case and camelCase are supported."""

    order_by: Optional[str]
    """The standard list order by string. If not specified, the default
      order is `create_time desc`. If specified, the default sorting order of
      provided fields is ascending. More detail in
      [AIP-132](https://google.aip.dev/132).

      Supported fields:
      * `create_time`
      * `update_time`"""


ListAgentEngineMemoryConfigOrDict = Union[
    ListAgentEngineMemoryConfig, ListAgentEngineMemoryConfigDict
]


class _ListAgentEngineMemoryRequestParameters(_common.BaseModel):
    """Parameters for listing agent engines."""

    name: Optional[str] = Field(
        default=None, description="""Name of the agent engine."""
    )
    config: Optional[ListAgentEngineMemoryConfig] = Field(
        default=None, description=""""""
    )


class _ListAgentEngineMemoryRequestParametersDict(TypedDict, total=False):
    """Parameters for listing agent engines."""

    name: Optional[str]
    """Name of the agent engine."""

    config: Optional[ListAgentEngineMemoryConfigDict]
    """"""


_ListAgentEngineMemoryRequestParametersOrDict = Union[
    _ListAgentEngineMemoryRequestParameters, _ListAgentEngineMemoryRequestParametersDict
]


class ListReasoningEnginesMemoriesResponse(_common.BaseModel):
    """Response for listing agent engine memories."""

    sdk_http_response: Optional[genai_types.HttpResponse] = Field(
        default=None, description="""Used to retain the full HTTP response."""
    )
    next_page_token: Optional[str] = Field(default=None, description="""""")
    memories: Optional[list[Memory]] = Field(
        default=None, description="""List of agent engine memories."""
    )


class ListReasoningEnginesMemoriesResponseDict(TypedDict, total=False):
    """Response for listing agent engine memories."""

    sdk_http_response: Optional[genai_types.HttpResponseDict]
    """Used to retain the full HTTP response."""

    next_page_token: Optional[str]
    """"""

    memories: Optional[list[MemoryDict]]
    """List of agent engine memories."""


ListReasoningEnginesMemoriesResponseOrDict = Union[
    ListReasoningEnginesMemoriesResponse, ListReasoningEnginesMemoriesResponseDict
]


class _GetAgentEngineMemoryOperationParameters(_common.BaseModel):
    """Parameters for getting an operation with a memory as a response."""

    operation_name: Optional[str] = Field(
        default=None, description="""The server-assigned name for the operation."""
    )
    config: Optional[GetAgentEngineOperationConfig] = Field(
        default=None, description="""Used to override the default configuration."""
    )


class _GetAgentEngineMemoryOperationParametersDict(TypedDict, total=False):
    """Parameters for getting an operation with a memory as a response."""

    operation_name: Optional[str]
    """The server-assigned name for the operation."""

    config: Optional[GetAgentEngineOperationConfigDict]
    """Used to override the default configuration."""


_GetAgentEngineMemoryOperationParametersOrDict = Union[
    _GetAgentEngineMemoryOperationParameters,
    _GetAgentEngineMemoryOperationParametersDict,
]


class _GetAgentEngineGenerateMemoriesOperationParameters(_common.BaseModel):
    """Parameters for getting an operation with generated memories as a response."""

    operation_name: Optional[str] = Field(
        default=None, description="""The server-assigned name for the operation."""
    )
    config: Optional[GetAgentEngineOperationConfig] = Field(
        default=None, description="""Used to override the default configuration."""
    )


class _GetAgentEngineGenerateMemoriesOperationParametersDict(TypedDict, total=False):
    """Parameters for getting an operation with generated memories as a response."""

    operation_name: Optional[str]
    """The server-assigned name for the operation."""

    config: Optional[GetAgentEngineOperationConfigDict]
    """Used to override the default configuration."""


_GetAgentEngineGenerateMemoriesOperationParametersOrDict = Union[
    _GetAgentEngineGenerateMemoriesOperationParameters,
    _GetAgentEngineGenerateMemoriesOperationParametersDict,
]


class RetrieveMemoriesRequestSimilaritySearchParams(_common.BaseModel):
    """The parameters for semantic similarity search based retrieval."""

    search_query: Optional[str] = Field(
        default=None,
        description="""Required. Query to use for similarity search retrieval. If provided, then the parent ReasoningEngine must have ReasoningEngineContextSpec.MemoryBankConfig.SimilaritySearchConfig set.""",
    )
    top_k: Optional[int] = Field(
        default=None,
        description="""Optional. The maximum number of memories to return. The service may return fewer than this value. If unspecified, at most 3 memories will be returned. The maximum value is 100; values above 100 will be coerced to 100.""",
    )


class RetrieveMemoriesRequestSimilaritySearchParamsDict(TypedDict, total=False):
    """The parameters for semantic similarity search based retrieval."""

    search_query: Optional[str]
    """Required. Query to use for similarity search retrieval. If provided, then the parent ReasoningEngine must have ReasoningEngineContextSpec.MemoryBankConfig.SimilaritySearchConfig set."""

    top_k: Optional[int]
    """Optional. The maximum number of memories to return. The service may return fewer than this value. If unspecified, at most 3 memories will be returned. The maximum value is 100; values above 100 will be coerced to 100."""


RetrieveMemoriesRequestSimilaritySearchParamsOrDict = Union[
    RetrieveMemoriesRequestSimilaritySearchParams,
    RetrieveMemoriesRequestSimilaritySearchParamsDict,
]


class RetrieveMemoriesRequestSimpleRetrievalParams(_common.BaseModel):
    """The parameters for simple (non-similarity search) retrieval."""

    page_size: Optional[int] = Field(
        default=None,
        description="""Optional. The maximum number of memories to return. The service may return fewer than this value. If unspecified, at most 3 memories will be returned. The maximum value is 100; values above 100 will be coerced to 100.""",
    )
    page_token: Optional[str] = Field(
        default=None,
        description="""Optional. A page token, received from a previous `RetrieveMemories` call. Provide this to retrieve the subsequent page.""",
    )


class RetrieveMemoriesRequestSimpleRetrievalParamsDict(TypedDict, total=False):
    """The parameters for simple (non-similarity search) retrieval."""

    page_size: Optional[int]
    """Optional. The maximum number of memories to return. The service may return fewer than this value. If unspecified, at most 3 memories will be returned. The maximum value is 100; values above 100 will be coerced to 100."""

    page_token: Optional[str]
    """Optional. A page token, received from a previous `RetrieveMemories` call. Provide this to retrieve the subsequent page."""


RetrieveMemoriesRequestSimpleRetrievalParamsOrDict = Union[
    RetrieveMemoriesRequestSimpleRetrievalParams,
    RetrieveMemoriesRequestSimpleRetrievalParamsDict,
]


class RetrieveAgentEngineMemoriesConfig(_common.BaseModel):
    """Config for retrieving memories."""

    http_options: Optional[genai_types.HttpOptions] = Field(
        default=None, description="""Used to override HTTP request options."""
    )
    filter: Optional[str] = Field(
        default=None,
        description="""The standard list filter that will be applied to the retrieved
      memories. More detail in [AIP-160](https://google.aip.dev/160).

      Supported fields:
       * `fact`
       * `create_time`
       * `update_time`
      """,
    )


class RetrieveAgentEngineMemoriesConfigDict(TypedDict, total=False):
    """Config for retrieving memories."""

    http_options: Optional[genai_types.HttpOptionsDict]
    """Used to override HTTP request options."""

    filter: Optional[str]
    """The standard list filter that will be applied to the retrieved
      memories. More detail in [AIP-160](https://google.aip.dev/160).

      Supported fields:
       * `fact`
       * `create_time`
       * `update_time`
      """


RetrieveAgentEngineMemoriesConfigOrDict = Union[
    RetrieveAgentEngineMemoriesConfig, RetrieveAgentEngineMemoriesConfigDict
]


class _RetrieveAgentEngineMemoriesRequestParameters(_common.BaseModel):
    """Parameters for retrieving agent engine memories."""

    name: Optional[str] = Field(
        default=None,
        description="""Name of the agent engine to retrieve memories from.""",
    )
    scope: Optional[dict[str, str]] = Field(
        default=None,
        description="""The scope of the memories to retrieve.

      A memory must have exactly the same scope as the scope provided here to be
      retrieved (i.e. same keys and values). Order does not matter, but it is
      case-sensitive.""",
    )
    similarity_search_params: Optional[
        RetrieveMemoriesRequestSimilaritySearchParams
    ] = Field(
        default=None,
        description="""Parameters for semantic similarity search based retrieval.""",
    )
    simple_retrieval_params: Optional[RetrieveMemoriesRequestSimpleRetrievalParams] = (
        Field(
            default=None,
            description="""Parameters for simple (non-similarity search) retrieval.""",
        )
    )
    config: Optional[RetrieveAgentEngineMemoriesConfig] = Field(
        default=None, description=""""""
    )


class _RetrieveAgentEngineMemoriesRequestParametersDict(TypedDict, total=False):
    """Parameters for retrieving agent engine memories."""

    name: Optional[str]
    """Name of the agent engine to retrieve memories from."""

    scope: Optional[dict[str, str]]
    """The scope of the memories to retrieve.

      A memory must have exactly the same scope as the scope provided here to be
      retrieved (i.e. same keys and values). Order does not matter, but it is
      case-sensitive."""

    similarity_search_params: Optional[
        RetrieveMemoriesRequestSimilaritySearchParamsDict
    ]
    """Parameters for semantic similarity search based retrieval."""

    simple_retrieval_params: Optional[RetrieveMemoriesRequestSimpleRetrievalParamsDict]
    """Parameters for simple (non-similarity search) retrieval."""

    config: Optional[RetrieveAgentEngineMemoriesConfigDict]
    """"""


_RetrieveAgentEngineMemoriesRequestParametersOrDict = Union[
    _RetrieveAgentEngineMemoriesRequestParameters,
    _RetrieveAgentEngineMemoriesRequestParametersDict,
]


class RetrieveMemoriesResponseRetrievedMemory(_common.BaseModel):
    """A retrieved memory."""

    distance: Optional[float] = Field(
        default=None,
        description="""The distance between the query and the retrieved Memory. Smaller values indicate more similar memories. This is only set if similarity search was used for retrieval.""",
    )
    memory: Optional[Memory] = Field(
        default=None, description="""The retrieved Memory."""
    )


class RetrieveMemoriesResponseRetrievedMemoryDict(TypedDict, total=False):
    """A retrieved memory."""

    distance: Optional[float]
    """The distance between the query and the retrieved Memory. Smaller values indicate more similar memories. This is only set if similarity search was used for retrieval."""

    memory: Optional[MemoryDict]
    """The retrieved Memory."""


RetrieveMemoriesResponseRetrievedMemoryOrDict = Union[
    RetrieveMemoriesResponseRetrievedMemory, RetrieveMemoriesResponseRetrievedMemoryDict
]


class RetrieveMemoriesResponse(_common.BaseModel):
    """The response for retrieving memories."""

    next_page_token: Optional[str] = Field(
        default=None,
        description="""A token that can be sent as `page_token` to retrieve the next page. If this field is omitted, there are no subsequent pages. This token is not set if similarity search was used for retrieval.""",
    )
    retrieved_memories: Optional[list[RetrieveMemoriesResponseRetrievedMemory]] = Field(
        default=None, description="""The retrieved memories."""
    )


class RetrieveMemoriesResponseDict(TypedDict, total=False):
    """The response for retrieving memories."""

    next_page_token: Optional[str]
    """A token that can be sent as `page_token` to retrieve the next page. If this field is omitted, there are no subsequent pages. This token is not set if similarity search was used for retrieval."""

    retrieved_memories: Optional[list[RetrieveMemoriesResponseRetrievedMemoryDict]]
    """The retrieved memories."""


RetrieveMemoriesResponseOrDict = Union[
    RetrieveMemoriesResponse, RetrieveMemoriesResponseDict
]


class RollbackAgentEngineMemoryConfig(_common.BaseModel):
    """Config for rolling back a memory."""

    http_options: Optional[genai_types.HttpOptions] = Field(
        default=None, description="""Used to override HTTP request options."""
    )
    wait_for_completion: Optional[bool] = Field(
        default=True,
        description="""Waits for the operation to complete before returning.""",
    )


class RollbackAgentEngineMemoryConfigDict(TypedDict, total=False):
    """Config for rolling back a memory."""

    http_options: Optional[genai_types.HttpOptionsDict]
    """Used to override HTTP request options."""

    wait_for_completion: Optional[bool]
    """Waits for the operation to complete before returning."""


RollbackAgentEngineMemoryConfigOrDict = Union[
    RollbackAgentEngineMemoryConfig, RollbackAgentEngineMemoryConfigDict
]


class _RollbackAgentEngineMemoryRequestParameters(_common.BaseModel):
    """Parameters for generating agent engine memories."""

    name: Optional[str] = Field(
        default=None, description="""Name of the agent engine memory to rollback."""
    )
    target_revision_id: Optional[str] = Field(
        default=None, description="""The ID of the revision to rollback to."""
    )
    config: Optional[RollbackAgentEngineMemoryConfig] = Field(
        default=None, description=""""""
    )


class _RollbackAgentEngineMemoryRequestParametersDict(TypedDict, total=False):
    """Parameters for generating agent engine memories."""

    name: Optional[str]
    """Name of the agent engine memory to rollback."""

    target_revision_id: Optional[str]
    """The ID of the revision to rollback to."""

    config: Optional[RollbackAgentEngineMemoryConfigDict]
    """"""


_RollbackAgentEngineMemoryRequestParametersOrDict = Union[
    _RollbackAgentEngineMemoryRequestParameters,
    _RollbackAgentEngineMemoryRequestParametersDict,
]


class AgentEngineRollbackMemoryOperation(_common.BaseModel):
    """Operation that rolls back a memory."""

    name: Optional[str] = Field(
        default=None,
        description="""The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`.""",
    )
    metadata: Optional[dict[str, Any]] = Field(
        default=None,
        description="""Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata.  Any method that returns a long-running operation should document the metadata type, if any.""",
    )
    done: Optional[bool] = Field(
        default=None,
        description="""If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available.""",
    )
    error: Optional[dict[str, Any]] = Field(
        default=None,
        description="""The error result of the operation in case of failure or cancellation.""",
    )


class AgentEngineRollbackMemoryOperationDict(TypedDict, total=False):
    """Operation that rolls back a memory."""

    name: Optional[str]
    """The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`."""

    metadata: Optional[dict[str, Any]]
    """Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata.  Any method that returns a long-running operation should document the metadata type, if any."""

    done: Optional[bool]
    """If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available."""

    error: Optional[dict[str, Any]]
    """The error result of the operation in case of failure or cancellation."""


AgentEngineRollbackMemoryOperationOrDict = Union[
    AgentEngineRollbackMemoryOperation, AgentEngineRollbackMemoryOperationDict
]


class UpdateAgentEngineMemoryConfig(_common.BaseModel):
    """Config for updating agent engine memory."""

    http_options: Optional[genai_types.HttpOptions] = Field(
        default=None, description="""Used to override HTTP request options."""
    )
    display_name: Optional[str] = Field(
        default=None, description="""The display name of the memory."""
    )
    description: Optional[str] = Field(
        default=None, description="""The description of the memory."""
    )
    wait_for_completion: Optional[bool] = Field(
        default=True,
        description="""Waits for the operation to complete before returning.""",
    )
    ttl: Optional[str] = Field(
        default=None,
        description="""Optional. Input only. The TTL for this resource.

      The expiration time is computed: now + TTL.""",
    )
    expire_time: Optional[datetime.datetime] = Field(
        default=None,
        description="""Optional. Timestamp of when this resource is considered expired. This is *always* provided on output, regardless of what `expiration` was sent on input.""",
    )
    revision_expire_time: Optional[datetime.datetime] = Field(
        default=None,
        description="""Optional. Input only. Timestamp of when the revision is considered expired. If not set, the memory revision will be kept until manually deleted.""",
    )
    revision_ttl: Optional[str] = Field(
        default=None,
        description="""Optional. Input only. The TTL for the revision. The expiration time is computed: now + TTL.""",
    )
    disable_memory_revisions: Optional[bool] = Field(
        default=None,
        description="""Optional. Input only. If true, no revision will be created for this request.""",
    )
    topics: Optional[list[MemoryTopicId]] = Field(
        default=None, description="""Optional. The topics of the memory."""
    )
    update_mask: Optional[str] = Field(
        default=None,
        description="""The update mask to apply. For the `FieldMask` definition, see
      https://protobuf.dev/reference/protobuf/google.protobuf/#field-mask.""",
    )


class UpdateAgentEngineMemoryConfigDict(TypedDict, total=False):
    """Config for updating agent engine memory."""

    http_options: Optional[genai_types.HttpOptionsDict]
    """Used to override HTTP request options."""

    display_name: Optional[str]
    """The display name of the memory."""

    description: Optional[str]
    """The description of the memory."""

    wait_for_completion: Optional[bool]
    """Waits for the operation to complete before returning."""

    ttl: Optional[str]
    """Optional. Input only. The TTL for this resource.

      The expiration time is computed: now + TTL."""

    expire_time: Optional[datetime.datetime]
    """Optional. Timestamp of when this resource is considered expired. This is *always* provided on output, regardless of what `expiration` was sent on input."""

    revision_expire_time: Optional[datetime.datetime]
    """Optional. Input only. Timestamp of when the revision is considered expired. If not set, the memory revision will be kept until manually deleted."""

    revision_ttl: Optional[str]
    """Optional. Input only. The TTL for the revision. The expiration time is computed: now + TTL."""

    disable_memory_revisions: Optional[bool]
    """Optional. Input only. If true, no revision will be created for this request."""

    topics: Optional[list[MemoryTopicIdDict]]
    """Optional. The topics of the memory."""

    update_mask: Optional[str]
    """The update mask to apply. For the `FieldMask` definition, see
      https://protobuf.dev/reference/protobuf/google.protobuf/#field-mask."""


UpdateAgentEngineMemoryConfigOrDict = Union[
    UpdateAgentEngineMemoryConfig, UpdateAgentEngineMemoryConfigDict
]


class _UpdateAgentEngineMemoryRequestParameters(_common.BaseModel):
    """Parameters for updating agent engine memories."""

    name: Optional[str] = Field(
        default=None, description="""Name of the agent engine memory to update."""
    )
    fact: Optional[str] = Field(
        default=None,
        description="""The updated fact of the memory.

      This is the semantic knowledge extracted from the source content.""",
    )
    scope: Optional[dict[str, str]] = Field(
        default=None,
        description="""The updated scope of the memory.

      Memories are isolated within their scope. The scope is defined when
      creating or generating memories. Up to 5 key-value pairs are accepted,
      and scope values cannot contain the wildcard character '*'.""",
    )
    config: Optional[UpdateAgentEngineMemoryConfig] = Field(
        default=None, description=""""""
    )


class _UpdateAgentEngineMemoryRequestParametersDict(TypedDict, total=False):
    """Parameters for updating agent engine memories."""

    name: Optional[str]
    """Name of the agent engine memory to update."""

    fact: Optional[str]
    """The updated fact of the memory.

      This is the semantic knowledge extracted from the source content."""

    scope: Optional[dict[str, str]]
    """The updated scope of the memory.

      Memories are isolated within their scope. The scope is defined when
      creating or generating memories. Up to 5 key-value pairs are accepted,
      and scope values cannot contain the wildcard character '*'."""

    config: Optional[UpdateAgentEngineMemoryConfigDict]
    """"""


_UpdateAgentEngineMemoryRequestParametersOrDict = Union[
    _UpdateAgentEngineMemoryRequestParameters,
    _UpdateAgentEngineMemoryRequestParametersDict,
]


class PurgeAgentEngineMemoriesConfig(_common.BaseModel):
    """Config for purging memories."""

    http_options: Optional[genai_types.HttpOptions] = Field(
        default=None, description="""Used to override HTTP request options."""
    )
    wait_for_completion: Optional[bool] = Field(
        default=True,
        description="""Waits for the operation to complete before returning.""",
    )


class PurgeAgentEngineMemoriesConfigDict(TypedDict, total=False):
    """Config for purging memories."""

    http_options: Optional[genai_types.HttpOptionsDict]
    """Used to override HTTP request options."""

    wait_for_completion: Optional[bool]
    """Waits for the operation to complete before returning."""


PurgeAgentEngineMemoriesConfigOrDict = Union[
    PurgeAgentEngineMemoriesConfig, PurgeAgentEngineMemoriesConfigDict
]


class _PurgeAgentEngineMemoriesRequestParameters(_common.BaseModel):
    """Parameters for purging agent engine memories."""

    name: Optional[str] = Field(
        default=None, description="""Name of the Agent Engine to purge memories from."""
    )
    filter: Optional[str] = Field(
        default=None,
        description="""The standard list filter to determine which memories to purge.
      More detail in [AIP-160](https://google.aip.dev/160).""",
    )
    force: Optional[bool] = Field(
        default=None,
        description="""If true, the memories will actually be purged. If false, the purge request will be validated but not executed.""",
    )
    config: Optional[PurgeAgentEngineMemoriesConfig] = Field(
        default=None, description=""""""
    )


class _PurgeAgentEngineMemoriesRequestParametersDict(TypedDict, total=False):
    """Parameters for purging agent engine memories."""

    name: Optional[str]
    """Name of the Agent Engine to purge memories from."""

    filter: Optional[str]
    """The standard list filter to determine which memories to purge.
      More detail in [AIP-160](https://google.aip.dev/160)."""

    force: Optional[bool]
    """If true, the memories will actually be purged. If false, the purge request will be validated but not executed."""

    config: Optional[PurgeAgentEngineMemoriesConfigDict]
    """"""


_PurgeAgentEngineMemoriesRequestParametersOrDict = Union[
    _PurgeAgentEngineMemoriesRequestParameters,
    _PurgeAgentEngineMemoriesRequestParametersDict,
]


class PurgeMemoriesResponse(_common.BaseModel):
    """The response for purging memories."""

    purge_count: Optional[int] = Field(
        default=None, description="""The number of memories that were purged."""
    )


class PurgeMemoriesResponseDict(TypedDict, total=False):
    """The response for purging memories."""

    purge_count: Optional[int]
    """The number of memories that were purged."""


PurgeMemoriesResponseOrDict = Union[PurgeMemoriesResponse, PurgeMemoriesResponseDict]


class AgentEnginePurgeMemoriesOperation(_common.BaseModel):
    """Operation that purges memories from an agent engine."""

    name: Optional[str] = Field(
        default=None,
        description="""The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`.""",
    )
    metadata: Optional[dict[str, Any]] = Field(
        default=None,
        description="""Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata.  Any method that returns a long-running operation should document the metadata type, if any.""",
    )
    done: Optional[bool] = Field(
        default=None,
        description="""If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available.""",
    )
    error: Optional[dict[str, Any]] = Field(
        default=None,
        description="""The error result of the operation in case of failure or cancellation.""",
    )
    response: Optional[PurgeMemoriesResponse] = Field(
        default=None, description="""The response for purging memories."""
    )


class AgentEnginePurgeMemoriesOperationDict(TypedDict, total=False):
    """Operation that purges memories from an agent engine."""

    name: Optional[str]
    """The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`."""

    metadata: Optional[dict[str, Any]]
    """Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata.  Any method that returns a long-running operation should document the metadata type, if any."""

    done: Optional[bool]
    """If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available."""

    error: Optional[dict[str, Any]]
    """The error result of the operation in case of failure or cancellation."""

    response: Optional[PurgeMemoriesResponseDict]
    """The response for purging memories."""


AgentEnginePurgeMemoriesOperationOrDict = Union[
    AgentEnginePurgeMemoriesOperation, AgentEnginePurgeMemoriesOperationDict
]


class GetAgentEngineMemoryRevisionConfig(_common.BaseModel):
    """Config for getting an Agent Engine Memory Revision."""

    http_options: Optional[genai_types.HttpOptions] = Field(
        default=None, description="""Used to override HTTP request options."""
    )


class GetAgentEngineMemoryRevisionConfigDict(TypedDict, total=False):
    """Config for getting an Agent Engine Memory Revision."""

    http_options: Optional[genai_types.HttpOptionsDict]
    """Used to override HTTP request options."""


GetAgentEngineMemoryRevisionConfigOrDict = Union[
    GetAgentEngineMemoryRevisionConfig, GetAgentEngineMemoryRevisionConfigDict
]


class _GetAgentEngineMemoryRevisionRequestParameters(_common.BaseModel):
    """Parameters for getting an Agent Engine memory revision."""

    name: Optional[str] = Field(
        default=None, description="""Name of the agent engine."""
    )
    config: Optional[GetAgentEngineMemoryRevisionConfig] = Field(
        default=None, description=""""""
    )


class _GetAgentEngineMemoryRevisionRequestParametersDict(TypedDict, total=False):
    """Parameters for getting an Agent Engine memory revision."""

    name: Optional[str]
    """Name of the agent engine."""

    config: Optional[GetAgentEngineMemoryRevisionConfigDict]
    """"""


_GetAgentEngineMemoryRevisionRequestParametersOrDict = Union[
    _GetAgentEngineMemoryRevisionRequestParameters,
    _GetAgentEngineMemoryRevisionRequestParametersDict,
]


class IntermediateExtractedMemory(_common.BaseModel):
    """An extracted memory that is the intermediate result before consolidation."""

    fact: Optional[str] = Field(
        default=None, description="""Output only. The fact of the extracted memory."""
    )


class IntermediateExtractedMemoryDict(TypedDict, total=False):
    """An extracted memory that is the intermediate result before consolidation."""

    fact: Optional[str]
    """Output only. The fact of the extracted memory."""


IntermediateExtractedMemoryOrDict = Union[
    IntermediateExtractedMemory, IntermediateExtractedMemoryDict
]


class MemoryRevision(_common.BaseModel):
    """A memory revision."""

    name: Optional[str] = Field(
        default=None,
        description="""Identifier. The resource name of the Memory Revision. Format: `projects/{project}/locations/{location}/reasoningEngines/{reasoning_engine}/memories/{memory}/revisions/{memory_revision}`""",
    )
    create_time: Optional[datetime.datetime] = Field(
        default=None,
        description="""Output only. Timestamp when this Memory Revision was created.""",
    )
    expire_time: Optional[datetime.datetime] = Field(
        default=None,
        description="""Output only. Timestamp of when this resource is considered expired.""",
    )
    fact: Optional[str] = Field(
        default=None,
        description="""Output only. The fact of the Memory Revision. This corresponds to the `fact` field of the parent Memory at the time of revision creation.""",
    )
    labels: Optional[dict[str, str]] = Field(
        default=None,
        description="""Output only. The labels of the Memory Revision. These labels are applied to the MemoryRevision when it is created based on `GenerateMemoriesRequest.revision_labels`.""",
    )
    extracted_memories: Optional[list[IntermediateExtractedMemory]] = Field(
        default=None,
        description="""Output only. The extracted memories from the source content before consolidation when the memory was updated via GenerateMemories. This information was used to modify an existing Memory via Consolidation.""",
    )


class MemoryRevisionDict(TypedDict, total=False):
    """A memory revision."""

    name: Optional[str]
    """Identifier. The resource name of the Memory Revision. Format: `projects/{project}/locations/{location}/reasoningEngines/{reasoning_engine}/memories/{memory}/revisions/{memory_revision}`"""

    create_time: Optional[datetime.datetime]
    """Output only. Timestamp when this Memory Revision was created."""

    expire_time: Optional[datetime.datetime]
    """Output only. Timestamp of when this resource is considered expired."""

    fact: Optional[str]
    """Output only. The fact of the Memory Revision. This corresponds to the `fact` field of the parent Memory at the time of revision creation."""

    labels: Optional[dict[str, str]]
    """Output only. The labels of the Memory Revision. These labels are applied to the MemoryRevision when it is created based on `GenerateMemoriesRequest.revision_labels`."""

    extracted_memories: Optional[list[IntermediateExtractedMemoryDict]]
    """Output only. The extracted memories from the source content before consolidation when the memory was updated via GenerateMemories. This information was used to modify an existing Memory via Consolidation."""


MemoryRevisionOrDict = Union[MemoryRevision, MemoryRevisionDict]


class ListAgentEngineMemoryRevisionsConfig(_common.BaseModel):
    """Config for listing Agent Engine memory revisions."""

    http_options: Optional[genai_types.HttpOptions] = Field(
        default=None, description="""Used to override HTTP request options."""
    )
    page_size: Optional[int] = Field(default=None, description="""""")
    page_token: Optional[str] = Field(default=None, description="""""")
    filter: Optional[str] = Field(
        default=None,
        description="""An expression for filtering the results of the request.
      For field names both snake_case and camelCase are supported.""",
    )


class ListAgentEngineMemoryRevisionsConfigDict(TypedDict, total=False):
    """Config for listing Agent Engine memory revisions."""

    http_options: Optional[genai_types.HttpOptionsDict]
    """Used to override HTTP request options."""

    page_size: Optional[int]
    """"""

    page_token: Optional[str]
    """"""

    filter: Optional[str]
    """An expression for filtering the results of the request.
      For field names both snake_case and camelCase are supported."""


ListAgentEngineMemoryRevisionsConfigOrDict = Union[
    ListAgentEngineMemoryRevisionsConfig, ListAgentEngineMemoryRevisionsConfigDict
]


class _ListAgentEngineMemoryRevisionsRequestParameters(_common.BaseModel):
    """Parameters for listing Agent Engine memory revisions."""

    name: Optional[str] = Field(
        default=None, description="""Name of the Agent Engine memory"""
    )
    config: Optional[ListAgentEngineMemoryRevisionsConfig] = Field(
        default=None, description=""""""
    )


class _ListAgentEngineMemoryRevisionsRequestParametersDict(TypedDict, total=False):
    """Parameters for listing Agent Engine memory revisions."""

    name: Optional[str]
    """Name of the Agent Engine memory"""

    config: Optional[ListAgentEngineMemoryRevisionsConfigDict]
    """"""


_ListAgentEngineMemoryRevisionsRequestParametersOrDict = Union[
    _ListAgentEngineMemoryRevisionsRequestParameters,
    _ListAgentEngineMemoryRevisionsRequestParametersDict,
]


class ListAgentEngineMemoryRevisionsResponse(_common.BaseModel):
    """Response for listing agent engine memory revisions."""

    sdk_http_response: Optional[genai_types.HttpResponse] = Field(
        default=None, description="""Used to retain the full HTTP response."""
    )
    next_page_token: Optional[str] = Field(default=None, description="""""")
    memory_revisions: Optional[list[MemoryRevision]] = Field(
        default=None, description="""List of memory revisions."""
    )


class ListAgentEngineMemoryRevisionsResponseDict(TypedDict, total=False):
    """Response for listing agent engine memory revisions."""

    sdk_http_response: Optional[genai_types.HttpResponseDict]
    """Used to retain the full HTTP response."""

    next_page_token: Optional[str]
    """"""

    memory_revisions: Optional[list[MemoryRevisionDict]]
    """List of memory revisions."""


ListAgentEngineMemoryRevisionsResponseOrDict = Union[
    ListAgentEngineMemoryRevisionsResponse, ListAgentEngineMemoryRevisionsResponseDict
]


class SandboxEnvironmentSpecCodeExecutionEnvironment(_common.BaseModel):
    """The code execution environment with customized settings."""

    code_language: Optional[Language] = Field(
        default=None,
        description="""The coding language supported in this environment.""",
    )
    machine_config: Optional[MachineConfig] = Field(
        default=None,
        description="""The machine config of the code execution environment.""",
    )


class SandboxEnvironmentSpecCodeExecutionEnvironmentDict(TypedDict, total=False):
    """The code execution environment with customized settings."""

    code_language: Optional[Language]
    """The coding language supported in this environment."""

    machine_config: Optional[MachineConfig]
    """The machine config of the code execution environment."""


SandboxEnvironmentSpecCodeExecutionEnvironmentOrDict = Union[
    SandboxEnvironmentSpecCodeExecutionEnvironment,
    SandboxEnvironmentSpecCodeExecutionEnvironmentDict,
]


class SandboxEnvironmentSpecComputerUseEnvironment(_common.BaseModel):
    """The computer use environment with customized settings."""

    pass


class SandboxEnvironmentSpecComputerUseEnvironmentDict(TypedDict, total=False):
    """The computer use environment with customized settings."""

    pass


SandboxEnvironmentSpecComputerUseEnvironmentOrDict = Union[
    SandboxEnvironmentSpecComputerUseEnvironment,
    SandboxEnvironmentSpecComputerUseEnvironmentDict,
]


class SandboxEnvironmentSpec(_common.BaseModel):
    """The specification of a sandbox environment."""

    code_execution_environment: Optional[
        SandboxEnvironmentSpecCodeExecutionEnvironment
    ] = Field(default=None, description="""Optional. The code execution environment.""")
    computer_use_environment: Optional[SandboxEnvironmentSpecComputerUseEnvironment] = (
        Field(default=None, description="""Optional. The computer use environment.""")
    )


class SandboxEnvironmentSpecDict(TypedDict, total=False):
    """The specification of a sandbox environment."""

    code_execution_environment: Optional[
        SandboxEnvironmentSpecCodeExecutionEnvironmentDict
    ]
    """Optional. The code execution environment."""

    computer_use_environment: Optional[SandboxEnvironmentSpecComputerUseEnvironmentDict]
    """Optional. The computer use environment."""


SandboxEnvironmentSpecOrDict = Union[SandboxEnvironmentSpec, SandboxEnvironmentSpecDict]


class CreateAgentEngineSandboxConfig(_common.BaseModel):
    """Config for creating a Sandbox."""

    http_options: Optional[genai_types.HttpOptions] = Field(
        default=None, description="""Used to override HTTP request options."""
    )
    display_name: Optional[str] = Field(
        default=None, description="""The display name of the sandbox."""
    )
    description: Optional[str] = Field(
        default=None, description="""The description of the sandbox."""
    )
    wait_for_completion: Optional[bool] = Field(
        default=True,
        description="""Waits for the operation to complete before returning.""",
    )
    ttl: Optional[str] = Field(
        default=None,
        description="""The TTL for this resource. The expiration time is computed: now + TTL.""",
    )


class CreateAgentEngineSandboxConfigDict(TypedDict, total=False):
    """Config for creating a Sandbox."""

    http_options: Optional[genai_types.HttpOptionsDict]
    """Used to override HTTP request options."""

    display_name: Optional[str]
    """The display name of the sandbox."""

    description: Optional[str]
    """The description of the sandbox."""

    wait_for_completion: Optional[bool]
    """Waits for the operation to complete before returning."""

    ttl: Optional[str]
    """The TTL for this resource. The expiration time is computed: now + TTL."""


CreateAgentEngineSandboxConfigOrDict = Union[
    CreateAgentEngineSandboxConfig, CreateAgentEngineSandboxConfigDict
]


class _CreateAgentEngineSandboxRequestParameters(_common.BaseModel):
    """Parameters for creating Agent Engine Sandboxes."""

    name: Optional[str] = Field(
        default=None,
        description="""Name of the agent engine to create the sandbox under.""",
    )
    spec: Optional[SandboxEnvironmentSpec] = Field(
        default=None, description="""The specification of the sandbox."""
    )
    config: Optional[CreateAgentEngineSandboxConfig] = Field(
        default=None, description=""""""
    )


class _CreateAgentEngineSandboxRequestParametersDict(TypedDict, total=False):
    """Parameters for creating Agent Engine Sandboxes."""

    name: Optional[str]
    """Name of the agent engine to create the sandbox under."""

    spec: Optional[SandboxEnvironmentSpecDict]
    """The specification of the sandbox."""

    config: Optional[CreateAgentEngineSandboxConfigDict]
    """"""


_CreateAgentEngineSandboxRequestParametersOrDict = Union[
    _CreateAgentEngineSandboxRequestParameters,
    _CreateAgentEngineSandboxRequestParametersDict,
]


class SandboxEnvironmentConnectionInfo(_common.BaseModel):
    """The connection information of the SandboxEnvironment."""

    load_balancer_hostname: Optional[str] = Field(
        default=None, description="""Output only. The hostname of the load balancer."""
    )
    load_balancer_ip: Optional[str] = Field(
        default=None,
        description="""Output only. The IP address of the load balancer.""",
    )
    sandbox_internal_ip: Optional[str] = Field(
        default=None,
        description="""Output only. The internal IP address of the SandboxEnvironment.""",
    )


class SandboxEnvironmentConnectionInfoDict(TypedDict, total=False):
    """The connection information of the SandboxEnvironment."""

    load_balancer_hostname: Optional[str]
    """Output only. The hostname of the load balancer."""

    load_balancer_ip: Optional[str]
    """Output only. The IP address of the load balancer."""

    sandbox_internal_ip: Optional[str]
    """Output only. The internal IP address of the SandboxEnvironment."""


SandboxEnvironmentConnectionInfoOrDict = Union[
    SandboxEnvironmentConnectionInfo, SandboxEnvironmentConnectionInfoDict
]


class SandboxEnvironment(_common.BaseModel):
    """A sandbox environment."""

    expire_time: Optional[datetime.datetime] = Field(
        default=None,
        description="""Expiration time of the sandbox environment.
      """,
    )
    connection_info: Optional[SandboxEnvironmentConnectionInfo] = Field(
        default=None,
        description="""Output only. The connection information of the SandboxEnvironment.""",
    )
    create_time: Optional[datetime.datetime] = Field(
        default=None,
        description="""Output only. The timestamp when this SandboxEnvironment was created.""",
    )
    display_name: Optional[str] = Field(
        default=None,
        description="""Required. The display name of the SandboxEnvironment.""",
    )
    name: Optional[str] = Field(
        default=None, description="""Identifier. The name of the SandboxEnvironment."""
    )
    spec: Optional[SandboxEnvironmentSpec] = Field(
        default=None,
        description="""Optional. The configuration of the SandboxEnvironment.""",
    )
    state: Optional[State] = Field(
        default=None,
        description="""Output only. The runtime state of the SandboxEnvironment.""",
    )
    ttl: Optional[str] = Field(
        default=None,
        description="""Optional. Input only. The TTL for the sandbox environment. The expiration time is computed: now + TTL.""",
    )
    update_time: Optional[datetime.datetime] = Field(
        default=None,
        description="""Output only. The timestamp when this SandboxEnvironment was most recently updated.""",
    )


class SandboxEnvironmentDict(TypedDict, total=False):
    """A sandbox environment."""

    expire_time: Optional[datetime.datetime]
    """Expiration time of the sandbox environment.
      """

    connection_info: Optional[SandboxEnvironmentConnectionInfoDict]
    """Output only. The connection information of the SandboxEnvironment."""

    create_time: Optional[datetime.datetime]
    """Output only. The timestamp when this SandboxEnvironment was created."""

    display_name: Optional[str]
    """Required. The display name of the SandboxEnvironment."""

    name: Optional[str]
    """Identifier. The name of the SandboxEnvironment."""

    spec: Optional[SandboxEnvironmentSpecDict]
    """Optional. The configuration of the SandboxEnvironment."""

    state: Optional[State]
    """Output only. The runtime state of the SandboxEnvironment."""

    ttl: Optional[str]
    """Optional. Input only. The TTL for the sandbox environment. The expiration time is computed: now + TTL."""

    update_time: Optional[datetime.datetime]
    """Output only. The timestamp when this SandboxEnvironment was most recently updated."""


SandboxEnvironmentOrDict = Union[SandboxEnvironment, SandboxEnvironmentDict]


class AgentEngineSandboxOperation(_common.BaseModel):
    """Operation that has an agent engine sandbox as a response."""

    name: Optional[str] = Field(
        default=None,
        description="""The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`.""",
    )
    metadata: Optional[dict[str, Any]] = Field(
        default=None,
        description="""Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata.  Any method that returns a long-running operation should document the metadata type, if any.""",
    )
    done: Optional[bool] = Field(
        default=None,
        description="""If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available.""",
    )
    error: Optional[dict[str, Any]] = Field(
        default=None,
        description="""The error result of the operation in case of failure or cancellation.""",
    )
    response: Optional[SandboxEnvironment] = Field(
        default=None, description="""The Agent Engine Sandbox."""
    )


class AgentEngineSandboxOperationDict(TypedDict, total=False):
    """Operation that has an agent engine sandbox as a response."""

    name: Optional[str]
    """The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`."""

    metadata: Optional[dict[str, Any]]
    """Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata.  Any method that returns a long-running operation should document the metadata type, if any."""

    done: Optional[bool]
    """If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available."""

    error: Optional[dict[str, Any]]
    """The error result of the operation in case of failure or cancellation."""

    response: Optional[SandboxEnvironmentDict]
    """The Agent Engine Sandbox."""


AgentEngineSandboxOperationOrDict = Union[
    AgentEngineSandboxOperation, AgentEngineSandboxOperationDict
]


class DeleteAgentEngineSandboxConfig(_common.BaseModel):
    """Config for deleting an Agent Engine Sandbox."""

    http_options: Optional[genai_types.HttpOptions] = Field(
        default=None, description="""Used to override HTTP request options."""
    )


class DeleteAgentEngineSandboxConfigDict(TypedDict, total=False):
    """Config for deleting an Agent Engine Sandbox."""

    http_options: Optional[genai_types.HttpOptionsDict]
    """Used to override HTTP request options."""


DeleteAgentEngineSandboxConfigOrDict = Union[
    DeleteAgentEngineSandboxConfig, DeleteAgentEngineSandboxConfigDict
]


class _DeleteAgentEngineSandboxRequestParameters(_common.BaseModel):
    """Parameters for deleting agent engines."""

    name: Optional[str] = Field(
        default=None, description="""Name of the agent engine sandbox to delete."""
    )
    config: Optional[DeleteAgentEngineSandboxConfig] = Field(
        default=None, description=""""""
    )


class _DeleteAgentEngineSandboxRequestParametersDict(TypedDict, total=False):
    """Parameters for deleting agent engines."""

    name: Optional[str]
    """Name of the agent engine sandbox to delete."""

    config: Optional[DeleteAgentEngineSandboxConfigDict]
    """"""


_DeleteAgentEngineSandboxRequestParametersOrDict = Union[
    _DeleteAgentEngineSandboxRequestParameters,
    _DeleteAgentEngineSandboxRequestParametersDict,
]


class DeleteAgentEngineSandboxOperation(_common.BaseModel):
    """Operation for deleting agent engines."""

    name: Optional[str] = Field(
        default=None,
        description="""The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`.""",
    )
    metadata: Optional[dict[str, Any]] = Field(
        default=None,
        description="""Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata.  Any method that returns a long-running operation should document the metadata type, if any.""",
    )
    done: Optional[bool] = Field(
        default=None,
        description="""If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available.""",
    )
    error: Optional[dict[str, Any]] = Field(
        default=None,
        description="""The error result of the operation in case of failure or cancellation.""",
    )


class DeleteAgentEngineSandboxOperationDict(TypedDict, total=False):
    """Operation for deleting agent engines."""

    name: Optional[str]
    """The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`."""

    metadata: Optional[dict[str, Any]]
    """Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata.  Any method that returns a long-running operation should document the metadata type, if any."""

    done: Optional[bool]
    """If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available."""

    error: Optional[dict[str, Any]]
    """The error result of the operation in case of failure or cancellation."""


DeleteAgentEngineSandboxOperationOrDict = Union[
    DeleteAgentEngineSandboxOperation, DeleteAgentEngineSandboxOperationDict
]


class Metadata(_common.BaseModel):
    """Metadata for a chunk."""

    attributes: Optional[dict[str, bytes]] = Field(
        default=None,
        description="""Optional. Attributes attached to the data. The keys have semantic conventions and the consumers of the attributes should know how to deserialize the value bytes based on the keys.""",
    )


class MetadataDict(TypedDict, total=False):
    """Metadata for a chunk."""

    attributes: Optional[dict[str, bytes]]
    """Optional. Attributes attached to the data. The keys have semantic conventions and the consumers of the attributes should know how to deserialize the value bytes based on the keys."""


MetadataOrDict = Union[Metadata, MetadataDict]


class Chunk(_common.BaseModel):
    """A chunk of data."""

    data: Optional[bytes] = Field(
        default=None, description="""Required. The data in the chunk."""
    )
    metadata: Optional[Metadata] = Field(
        default=None,
        description="""Optional. Metadata that is associated with the data in the payload.""",
    )
    mime_type: Optional[str] = Field(
        default=None,
        description="""Required. Mime type of the chunk data. See https://www.iana.org/assignments/media-types/media-types.xhtml for the full list.""",
    )


class ChunkDict(TypedDict, total=False):
    """A chunk of data."""

    data: Optional[bytes]
    """Required. The data in the chunk."""

    metadata: Optional[MetadataDict]
    """Optional. Metadata that is associated with the data in the payload."""

    mime_type: Optional[str]
    """Required. Mime type of the chunk data. See https://www.iana.org/assignments/media-types/media-types.xhtml for the full list."""


ChunkOrDict = Union[Chunk, ChunkDict]


class ExecuteCodeAgentEngineSandboxConfig(_common.BaseModel):
    """Config for executing code in an Agent Engine sandbox."""

    http_options: Optional[genai_types.HttpOptions] = Field(
        default=None, description="""Used to override HTTP request options."""
    )


class ExecuteCodeAgentEngineSandboxConfigDict(TypedDict, total=False):
    """Config for executing code in an Agent Engine sandbox."""

    http_options: Optional[genai_types.HttpOptionsDict]
    """Used to override HTTP request options."""


ExecuteCodeAgentEngineSandboxConfigOrDict = Union[
    ExecuteCodeAgentEngineSandboxConfig, ExecuteCodeAgentEngineSandboxConfigDict
]


class _ExecuteCodeAgentEngineSandboxRequestParameters(_common.BaseModel):
    """Parameters for executing code in an agent engine sandbox."""

    name: Optional[str] = Field(
        default=None,
        description="""Name of the agent engine sandbox to execute code in.""",
    )
    inputs: Optional[list[Chunk]] = Field(
        default=None, description="""Inputs to the code execution."""
    )
    config: Optional[ExecuteCodeAgentEngineSandboxConfig] = Field(
        default=None, description=""""""
    )


class _ExecuteCodeAgentEngineSandboxRequestParametersDict(TypedDict, total=False):
    """Parameters for executing code in an agent engine sandbox."""

    name: Optional[str]
    """Name of the agent engine sandbox to execute code in."""

    inputs: Optional[list[ChunkDict]]
    """Inputs to the code execution."""

    config: Optional[ExecuteCodeAgentEngineSandboxConfigDict]
    """"""


_ExecuteCodeAgentEngineSandboxRequestParametersOrDict = Union[
    _ExecuteCodeAgentEngineSandboxRequestParameters,
    _ExecuteCodeAgentEngineSandboxRequestParametersDict,
]


class ExecuteSandboxEnvironmentResponse(_common.BaseModel):
    """The response for executing a sandbox environment."""

    outputs: Optional[list[Chunk]] = Field(
        default=None, description="""The outputs from the sandbox environment."""
    )


class ExecuteSandboxEnvironmentResponseDict(TypedDict, total=False):
    """The response for executing a sandbox environment."""

    outputs: Optional[list[ChunkDict]]
    """The outputs from the sandbox environment."""


ExecuteSandboxEnvironmentResponseOrDict = Union[
    ExecuteSandboxEnvironmentResponse, ExecuteSandboxEnvironmentResponseDict
]


class GetAgentEngineSandboxConfig(_common.BaseModel):
    """Config for getting an Agent Engine Memory."""

    http_options: Optional[genai_types.HttpOptions] = Field(
        default=None, description="""Used to override HTTP request options."""
    )


class GetAgentEngineSandboxConfigDict(TypedDict, total=False):
    """Config for getting an Agent Engine Memory."""

    http_options: Optional[genai_types.HttpOptionsDict]
    """Used to override HTTP request options."""


GetAgentEngineSandboxConfigOrDict = Union[
    GetAgentEngineSandboxConfig, GetAgentEngineSandboxConfigDict
]


class _GetAgentEngineSandboxRequestParameters(_common.BaseModel):
    """Parameters for getting an agent engine sandbox."""

    name: Optional[str] = Field(
        default=None, description="""Name of the agent engine sandbox."""
    )
    config: Optional[GetAgentEngineSandboxConfig] = Field(
        default=None, description=""""""
    )


class _GetAgentEngineSandboxRequestParametersDict(TypedDict, total=False):
    """Parameters for getting an agent engine sandbox."""

    name: Optional[str]
    """Name of the agent engine sandbox."""

    config: Optional[GetAgentEngineSandboxConfigDict]
    """"""


_GetAgentEngineSandboxRequestParametersOrDict = Union[
    _GetAgentEngineSandboxRequestParameters, _GetAgentEngineSandboxRequestParametersDict
]


class ListAgentEngineSandboxesConfig(_common.BaseModel):
    """Config for listing agent engine sandboxes."""

    http_options: Optional[genai_types.HttpOptions] = Field(
        default=None, description="""Used to override HTTP request options."""
    )
    page_size: Optional[int] = Field(default=None, description="""""")
    page_token: Optional[str] = Field(default=None, description="""""")
    filter: Optional[str] = Field(
        default=None,
        description="""An expression for filtering the results of the request.
      For field names both snake_case and camelCase are supported.""",
    )


class ListAgentEngineSandboxesConfigDict(TypedDict, total=False):
    """Config for listing agent engine sandboxes."""

    http_options: Optional[genai_types.HttpOptionsDict]
    """Used to override HTTP request options."""

    page_size: Optional[int]
    """"""

    page_token: Optional[str]
    """"""

    filter: Optional[str]
    """An expression for filtering the results of the request.
      For field names both snake_case and camelCase are supported."""


ListAgentEngineSandboxesConfigOrDict = Union[
    ListAgentEngineSandboxesConfig, ListAgentEngineSandboxesConfigDict
]


class _ListAgentEngineSandboxesRequestParameters(_common.BaseModel):
    """Parameters for listing agent engine sandboxes."""

    name: Optional[str] = Field(
        default=None, description="""Name of the agent engine."""
    )
    config: Optional[ListAgentEngineSandboxesConfig] = Field(
        default=None, description=""""""
    )


class _ListAgentEngineSandboxesRequestParametersDict(TypedDict, total=False):
    """Parameters for listing agent engine sandboxes."""

    name: Optional[str]
    """Name of the agent engine."""

    config: Optional[ListAgentEngineSandboxesConfigDict]
    """"""


_ListAgentEngineSandboxesRequestParametersOrDict = Union[
    _ListAgentEngineSandboxesRequestParameters,
    _ListAgentEngineSandboxesRequestParametersDict,
]


class ListAgentEngineSandboxesResponse(_common.BaseModel):
    """Response for listing agent engine sandboxes."""

    sdk_http_response: Optional[genai_types.HttpResponse] = Field(
        default=None, description="""Used to retain the full HTTP response."""
    )
    next_page_token: Optional[str] = Field(default=None, description="""""")
    sandbox_environments: Optional[list[SandboxEnvironment]] = Field(
        default=None, description="""List of agent engine sandboxes."""
    )


class ListAgentEngineSandboxesResponseDict(TypedDict, total=False):
    """Response for listing agent engine sandboxes."""

    sdk_http_response: Optional[genai_types.HttpResponseDict]
    """Used to retain the full HTTP response."""

    next_page_token: Optional[str]
    """"""

    sandbox_environments: Optional[list[SandboxEnvironmentDict]]
    """List of agent engine sandboxes."""


ListAgentEngineSandboxesResponseOrDict = Union[
    ListAgentEngineSandboxesResponse, ListAgentEngineSandboxesResponseDict
]


class _GetAgentEngineSandboxOperationParameters(_common.BaseModel):
    """Parameters for getting an operation with a sandbox as a response."""

    operation_name: Optional[str] = Field(
        default=None, description="""The server-assigned name for the operation."""
    )
    config: Optional[GetAgentEngineOperationConfig] = Field(
        default=None, description="""Used to override the default configuration."""
    )


class _GetAgentEngineSandboxOperationParametersDict(TypedDict, total=False):
    """Parameters for getting an operation with a sandbox as a response."""

    operation_name: Optional[str]
    """The server-assigned name for the operation."""

    config: Optional[GetAgentEngineOperationConfigDict]
    """Used to override the default configuration."""


_GetAgentEngineSandboxOperationParametersOrDict = Union[
    _GetAgentEngineSandboxOperationParameters,
    _GetAgentEngineSandboxOperationParametersDict,
]


class CreateAgentEngineSessionConfig(_common.BaseModel):
    """Config for creating a Session."""

    http_options: Optional[genai_types.HttpOptions] = Field(
        default=None, description="""Used to override HTTP request options."""
    )
    display_name: Optional[str] = Field(
        default=None, description="""The display name of the session."""
    )
    session_state: Optional[dict[str, Any]] = Field(
        default=None,
        description="""Session state which stores key conversation points.""",
    )
    wait_for_completion: Optional[bool] = Field(
        default=True,
        description="""Waits for the operation to complete before returning.""",
    )
    ttl: Optional[str] = Field(
        default=None,
        description="""Optional. Input only. The TTL for this resource.

      The expiration time is computed: now + TTL.""",
    )
    expire_time: Optional[datetime.datetime] = Field(
        default=None,
        description="""Optional. Timestamp of when this resource is considered expired. This is *always* provided on output, regardless of what `expiration` was sent on input.""",
    )
    labels: Optional[dict[str, str]] = Field(
        default=None,
        description="""Optional. The labels with user-defined metadata to organize your Sessions. Label keys and values can be no longer than 64 characters (Unicode codepoints), can only contain lowercase letters, numeric characters, underscores and dashes. International characters are allowed. See https://goo.gl/xmQnxf for more information and examples of labels.""",
    )


class CreateAgentEngineSessionConfigDict(TypedDict, total=False):
    """Config for creating a Session."""

    http_options: Optional[genai_types.HttpOptionsDict]
    """Used to override HTTP request options."""

    display_name: Optional[str]
    """The display name of the session."""

    session_state: Optional[dict[str, Any]]
    """Session state which stores key conversation points."""

    wait_for_completion: Optional[bool]
    """Waits for the operation to complete before returning."""

    ttl: Optional[str]
    """Optional. Input only. The TTL for this resource.

      The expiration time is computed: now + TTL."""

    expire_time: Optional[datetime.datetime]
    """Optional. Timestamp of when this resource is considered expired. This is *always* provided on output, regardless of what `expiration` was sent on input."""

    labels: Optional[dict[str, str]]
    """Optional. The labels with user-defined metadata to organize your Sessions. Label keys and values can be no longer than 64 characters (Unicode codepoints), can only contain lowercase letters, numeric characters, underscores and dashes. International characters are allowed. See https://goo.gl/xmQnxf for more information and examples of labels."""


CreateAgentEngineSessionConfigOrDict = Union[
    CreateAgentEngineSessionConfig, CreateAgentEngineSessionConfigDict
]


class _CreateAgentEngineSessionRequestParameters(_common.BaseModel):
    """Parameters for creating Agent Engine Sessions."""

    name: Optional[str] = Field(
        default=None,
        description="""Name of the agent engine to create the session under.""",
    )
    user_id: Optional[str] = Field(
        default=None, description="""The user ID of the session."""
    )
    config: Optional[CreateAgentEngineSessionConfig] = Field(
        default=None, description=""""""
    )


class _CreateAgentEngineSessionRequestParametersDict(TypedDict, total=False):
    """Parameters for creating Agent Engine Sessions."""

    name: Optional[str]
    """Name of the agent engine to create the session under."""

    user_id: Optional[str]
    """The user ID of the session."""

    config: Optional[CreateAgentEngineSessionConfigDict]
    """"""


_CreateAgentEngineSessionRequestParametersOrDict = Union[
    _CreateAgentEngineSessionRequestParameters,
    _CreateAgentEngineSessionRequestParametersDict,
]


class Session(_common.BaseModel):
    """A session."""

    expire_time: Optional[datetime.datetime] = Field(
        default=None,
        description="""Optional. Timestamp of when this session is considered expired. This is *always* provided on output, regardless of what was sent on input.""",
    )
    ttl: Optional[str] = Field(
        default=None, description="""Optional. Input only. The TTL for this session."""
    )
    name: Optional[str] = Field(
        default=None,
        description="""Identifier. The resource name of the session. Format: 'projects/{project}/locations/{location}/reasoningEngines/{reasoning_engine}/sessions/{session}'.""",
    )
    create_time: Optional[datetime.datetime] = Field(
        default=None,
        description="""Output only. Timestamp when the session was created.""",
    )
    update_time: Optional[datetime.datetime] = Field(
        default=None,
        description="""Output only. Timestamp when the session was updated.""",
    )
    display_name: Optional[str] = Field(
        default=None, description="""Optional. The display name of the session."""
    )
    labels: Optional[dict[str, str]] = Field(
        default=None,
        description="""The labels with user-defined metadata to organize your Sessions. Label keys and values can be no longer than 64 characters (Unicode codepoints), can only contain lowercase letters, numeric characters, underscores and dashes. International characters are allowed. See https://goo.gl/xmQnxf for more information and examples of labels.""",
    )
    session_state: Optional[dict[str, Any]] = Field(
        default=None,
        description="""Optional. Session specific memory which stores key conversation points.""",
    )
    user_id: Optional[str] = Field(
        default=None,
        description="""Required. Immutable. String id provided by the user""",
    )


class SessionDict(TypedDict, total=False):
    """A session."""

    expire_time: Optional[datetime.datetime]
    """Optional. Timestamp of when this session is considered expired. This is *always* provided on output, regardless of what was sent on input."""

    ttl: Optional[str]
    """Optional. Input only. The TTL for this session."""

    name: Optional[str]
    """Identifier. The resource name of the session. Format: 'projects/{project}/locations/{location}/reasoningEngines/{reasoning_engine}/sessions/{session}'."""

    create_time: Optional[datetime.datetime]
    """Output only. Timestamp when the session was created."""

    update_time: Optional[datetime.datetime]
    """Output only. Timestamp when the session was updated."""

    display_name: Optional[str]
    """Optional. The display name of the session."""

    labels: Optional[dict[str, str]]
    """The labels with user-defined metadata to organize your Sessions. Label keys and values can be no longer than 64 characters (Unicode codepoints), can only contain lowercase letters, numeric characters, underscores and dashes. International characters are allowed. See https://goo.gl/xmQnxf for more information and examples of labels."""

    session_state: Optional[dict[str, Any]]
    """Optional. Session specific memory which stores key conversation points."""

    user_id: Optional[str]
    """Required. Immutable. String id provided by the user"""


SessionOrDict = Union[Session, SessionDict]


class AgentEngineSessionOperation(_common.BaseModel):
    """Operation that has an agent engine session as a response."""

    name: Optional[str] = Field(
        default=None,
        description="""The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`.""",
    )
    metadata: Optional[dict[str, Any]] = Field(
        default=None,
        description="""Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata.  Any method that returns a long-running operation should document the metadata type, if any.""",
    )
    done: Optional[bool] = Field(
        default=None,
        description="""If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available.""",
    )
    error: Optional[dict[str, Any]] = Field(
        default=None,
        description="""The error result of the operation in case of failure or cancellation.""",
    )
    response: Optional[Session] = Field(
        default=None, description="""The Agent Engine Session."""
    )


class AgentEngineSessionOperationDict(TypedDict, total=False):
    """Operation that has an agent engine session as a response."""

    name: Optional[str]
    """The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`."""

    metadata: Optional[dict[str, Any]]
    """Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata.  Any method that returns a long-running operation should document the metadata type, if any."""

    done: Optional[bool]
    """If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available."""

    error: Optional[dict[str, Any]]
    """The error result of the operation in case of failure or cancellation."""

    response: Optional[SessionDict]
    """The Agent Engine Session."""


AgentEngineSessionOperationOrDict = Union[
    AgentEngineSessionOperation, AgentEngineSessionOperationDict
]


class DeleteAgentEngineSessionConfig(_common.BaseModel):
    """Config for deleting an Agent Engine Session."""

    http_options: Optional[genai_types.HttpOptions] = Field(
        default=None, description="""Used to override HTTP request options."""
    )


class DeleteAgentEngineSessionConfigDict(TypedDict, total=False):
    """Config for deleting an Agent Engine Session."""

    http_options: Optional[genai_types.HttpOptionsDict]
    """Used to override HTTP request options."""


DeleteAgentEngineSessionConfigOrDict = Union[
    DeleteAgentEngineSessionConfig, DeleteAgentEngineSessionConfigDict
]


class _DeleteAgentEngineSessionRequestParameters(_common.BaseModel):
    """Parameters for deleting agent engine sessions."""

    name: Optional[str] = Field(
        default=None, description="""Name of the agent engine session to delete."""
    )
    config: Optional[DeleteAgentEngineSessionConfig] = Field(
        default=None, description=""""""
    )


class _DeleteAgentEngineSessionRequestParametersDict(TypedDict, total=False):
    """Parameters for deleting agent engine sessions."""

    name: Optional[str]
    """Name of the agent engine session to delete."""

    config: Optional[DeleteAgentEngineSessionConfigDict]
    """"""


_DeleteAgentEngineSessionRequestParametersOrDict = Union[
    _DeleteAgentEngineSessionRequestParameters,
    _DeleteAgentEngineSessionRequestParametersDict,
]


class DeleteAgentEngineSessionOperation(_common.BaseModel):
    """Operation for deleting agent engine sessions."""

    name: Optional[str] = Field(
        default=None,
        description="""The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`.""",
    )
    metadata: Optional[dict[str, Any]] = Field(
        default=None,
        description="""Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata.  Any method that returns a long-running operation should document the metadata type, if any.""",
    )
    done: Optional[bool] = Field(
        default=None,
        description="""If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available.""",
    )
    error: Optional[dict[str, Any]] = Field(
        default=None,
        description="""The error result of the operation in case of failure or cancellation.""",
    )


class DeleteAgentEngineSessionOperationDict(TypedDict, total=False):
    """Operation for deleting agent engine sessions."""

    name: Optional[str]
    """The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`."""

    metadata: Optional[dict[str, Any]]
    """Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata.  Any method that returns a long-running operation should document the metadata type, if any."""

    done: Optional[bool]
    """If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available."""

    error: Optional[dict[str, Any]]
    """The error result of the operation in case of failure or cancellation."""


DeleteAgentEngineSessionOperationOrDict = Union[
    DeleteAgentEngineSessionOperation, DeleteAgentEngineSessionOperationDict
]


class GetAgentEngineSessionConfig(_common.BaseModel):
    """Config for getting an Agent Engine Session."""

    http_options: Optional[genai_types.HttpOptions] = Field(
        default=None, description="""Used to override HTTP request options."""
    )


class GetAgentEngineSessionConfigDict(TypedDict, total=False):
    """Config for getting an Agent Engine Session."""

    http_options: Optional[genai_types.HttpOptionsDict]
    """Used to override HTTP request options."""


GetAgentEngineSessionConfigOrDict = Union[
    GetAgentEngineSessionConfig, GetAgentEngineSessionConfigDict
]


class _GetAgentEngineSessionRequestParameters(_common.BaseModel):
    """Parameters for getting an agent engine session."""

    name: Optional[str] = Field(
        default=None, description="""Name of the agent engine session."""
    )
    config: Optional[GetAgentEngineSessionConfig] = Field(
        default=None, description=""""""
    )


class _GetAgentEngineSessionRequestParametersDict(TypedDict, total=False):
    """Parameters for getting an agent engine session."""

    name: Optional[str]
    """Name of the agent engine session."""

    config: Optional[GetAgentEngineSessionConfigDict]
    """"""


_GetAgentEngineSessionRequestParametersOrDict = Union[
    _GetAgentEngineSessionRequestParameters, _GetAgentEngineSessionRequestParametersDict
]


class ListAgentEngineSessionsConfig(_common.BaseModel):
    """Config for listing agent engine sessions."""

    http_options: Optional[genai_types.HttpOptions] = Field(
        default=None, description="""Used to override HTTP request options."""
    )
    page_size: Optional[int] = Field(default=None, description="""""")
    page_token: Optional[str] = Field(default=None, description="""""")
    filter: Optional[str] = Field(
        default=None,
        description="""An expression for filtering the results of the request.
      For field names both snake_case and camelCase are supported.""",
    )


class ListAgentEngineSessionsConfigDict(TypedDict, total=False):
    """Config for listing agent engine sessions."""

    http_options: Optional[genai_types.HttpOptionsDict]
    """Used to override HTTP request options."""

    page_size: Optional[int]
    """"""

    page_token: Optional[str]
    """"""

    filter: Optional[str]
    """An expression for filtering the results of the request.
      For field names both snake_case and camelCase are supported."""


ListAgentEngineSessionsConfigOrDict = Union[
    ListAgentEngineSessionsConfig, ListAgentEngineSessionsConfigDict
]


class _ListAgentEngineSessionsRequestParameters(_common.BaseModel):
    """Parameters for listing agent engines."""

    name: Optional[str] = Field(
        default=None, description="""Name of the agent engine."""
    )
    config: Optional[ListAgentEngineSessionsConfig] = Field(
        default=None, description=""""""
    )


class _ListAgentEngineSessionsRequestParametersDict(TypedDict, total=False):
    """Parameters for listing agent engines."""

    name: Optional[str]
    """Name of the agent engine."""

    config: Optional[ListAgentEngineSessionsConfigDict]
    """"""


_ListAgentEngineSessionsRequestParametersOrDict = Union[
    _ListAgentEngineSessionsRequestParameters,
    _ListAgentEngineSessionsRequestParametersDict,
]


class ListReasoningEnginesSessionsResponse(_common.BaseModel):
    """Response for listing agent engine sessions."""

    sdk_http_response: Optional[genai_types.HttpResponse] = Field(
        default=None, description="""Used to retain the full HTTP response."""
    )
    next_page_token: Optional[str] = Field(default=None, description="""""")
    sessions: Optional[list[Session]] = Field(
        default=None, description="""List of agent engine sessions."""
    )


class ListReasoningEnginesSessionsResponseDict(TypedDict, total=False):
    """Response for listing agent engine sessions."""

    sdk_http_response: Optional[genai_types.HttpResponseDict]
    """Used to retain the full HTTP response."""

    next_page_token: Optional[str]
    """"""

    sessions: Optional[list[SessionDict]]
    """List of agent engine sessions."""


ListReasoningEnginesSessionsResponseOrDict = Union[
    ListReasoningEnginesSessionsResponse, ListReasoningEnginesSessionsResponseDict
]


class _GetAgentEngineSessionOperationParameters(_common.BaseModel):
    """Parameters for getting an operation with a session as a response."""

    operation_name: Optional[str] = Field(
        default=None, description="""The server-assigned name for the operation."""
    )
    config: Optional[GetAgentEngineOperationConfig] = Field(
        default=None, description="""Used to override the default configuration."""
    )


class _GetAgentEngineSessionOperationParametersDict(TypedDict, total=False):
    """Parameters for getting an operation with a session as a response."""

    operation_name: Optional[str]
    """The server-assigned name for the operation."""

    config: Optional[GetAgentEngineOperationConfigDict]
    """Used to override the default configuration."""


_GetAgentEngineSessionOperationParametersOrDict = Union[
    _GetAgentEngineSessionOperationParameters,
    _GetAgentEngineSessionOperationParametersDict,
]


class UpdateAgentEngineSessionConfig(_common.BaseModel):
    """Config for updating agent engine session."""

    http_options: Optional[genai_types.HttpOptions] = Field(
        default=None, description="""Used to override HTTP request options."""
    )
    display_name: Optional[str] = Field(
        default=None, description="""The display name of the session."""
    )
    session_state: Optional[dict[str, Any]] = Field(
        default=None,
        description="""Session state which stores key conversation points.""",
    )
    wait_for_completion: Optional[bool] = Field(
        default=True,
        description="""Waits for the operation to complete before returning.""",
    )
    ttl: Optional[str] = Field(
        default=None,
        description="""Optional. Input only. The TTL for this resource.

      The expiration time is computed: now + TTL.""",
    )
    expire_time: Optional[datetime.datetime] = Field(
        default=None,
        description="""Optional. Timestamp of when this resource is considered expired. This is *always* provided on output, regardless of what `expiration` was sent on input.""",
    )
    labels: Optional[dict[str, str]] = Field(
        default=None,
        description="""Optional. The labels with user-defined metadata to organize your Sessions. Label keys and values can be no longer than 64 characters (Unicode codepoints), can only contain lowercase letters, numeric characters, underscores and dashes. International characters are allowed. See https://goo.gl/xmQnxf for more information and examples of labels.""",
    )
    update_mask: Optional[str] = Field(
        default=None,
        description="""The update mask to apply. For the `FieldMask` definition, see
      https://protobuf.dev/reference/protobuf/google.protobuf/#field-mask.""",
    )
    user_id: Optional[str] = Field(
        default=None, description="""User ID of the agent engine session to update."""
    )


class UpdateAgentEngineSessionConfigDict(TypedDict, total=False):
    """Config for updating agent engine session."""

    http_options: Optional[genai_types.HttpOptionsDict]
    """Used to override HTTP request options."""

    display_name: Optional[str]
    """The display name of the session."""

    session_state: Optional[dict[str, Any]]
    """Session state which stores key conversation points."""

    wait_for_completion: Optional[bool]
    """Waits for the operation to complete before returning."""

    ttl: Optional[str]
    """Optional. Input only. The TTL for this resource.

      The expiration time is computed: now + TTL."""

    expire_time: Optional[datetime.datetime]
    """Optional. Timestamp of when this resource is considered expired. This is *always* provided on output, regardless of what `expiration` was sent on input."""

    labels: Optional[dict[str, str]]
    """Optional. The labels with user-defined metadata to organize your Sessions. Label keys and values can be no longer than 64 characters (Unicode codepoints), can only contain lowercase letters, numeric characters, underscores and dashes. International characters are allowed. See https://goo.gl/xmQnxf for more information and examples of labels."""

    update_mask: Optional[str]
    """The update mask to apply. For the `FieldMask` definition, see
      https://protobuf.dev/reference/protobuf/google.protobuf/#field-mask."""

    user_id: Optional[str]
    """User ID of the agent engine session to update."""


UpdateAgentEngineSessionConfigOrDict = Union[
    UpdateAgentEngineSessionConfig, UpdateAgentEngineSessionConfigDict
]


class _UpdateAgentEngineSessionRequestParameters(_common.BaseModel):
    """Parameters for updating agent engine sessions."""

    name: Optional[str] = Field(
        default=None, description="""Name of the agent engine session to update."""
    )
    config: Optional[UpdateAgentEngineSessionConfig] = Field(
        default=None, description=""""""
    )


class _UpdateAgentEngineSessionRequestParametersDict(TypedDict, total=False):
    """Parameters for updating agent engine sessions."""

    name: Optional[str]
    """Name of the agent engine session to update."""

    config: Optional[UpdateAgentEngineSessionConfigDict]
    """"""


_UpdateAgentEngineSessionRequestParametersOrDict = Union[
    _UpdateAgentEngineSessionRequestParameters,
    _UpdateAgentEngineSessionRequestParametersDict,
]


class EventActions(_common.BaseModel):
    """Actions are parts of events that are executed by the agent."""

    artifact_delta: Optional[dict[str, int]] = Field(
        default=None,
        description="""Optional. Indicates that the event is updating an artifact. key is the filename, value is the version.""",
    )
    escalate: Optional[bool] = Field(
        default=None,
        description="""Optional. The agent is escalating to a higher level agent.""",
    )
    requested_auth_configs: Optional[dict[str, Any]] = Field(
        default=None,
        description="""Optional. Will only be set by a tool response indicating tool request euc. Struct key is the function call id since one function call response (from model) could correspond to multiple function calls. Struct value is the required auth config, which can be another struct.""",
    )
    skip_summarization: Optional[bool] = Field(
        default=None,
        description="""Optional. If true, it won't call model to summarize function response. Only used for function_response event.""",
    )
    state_delta: Optional[dict[str, Any]] = Field(
        default=None,
        description="""Optional. Indicates that the event is updating the state with the given delta.""",
    )
    transfer_agent: Optional[str] = Field(
        default=None,
        description="""Optional. If set, the event transfers to the specified agent.""",
    )


class EventActionsDict(TypedDict, total=False):
    """Actions are parts of events that are executed by the agent."""

    artifact_delta: Optional[dict[str, int]]
    """Optional. Indicates that the event is updating an artifact. key is the filename, value is the version."""

    escalate: Optional[bool]
    """Optional. The agent is escalating to a higher level agent."""

    requested_auth_configs: Optional[dict[str, Any]]
    """Optional. Will only be set by a tool response indicating tool request euc. Struct key is the function call id since one function call response (from model) could correspond to multiple function calls. Struct value is the required auth config, which can be another struct."""

    skip_summarization: Optional[bool]
    """Optional. If true, it won't call model to summarize function response. Only used for function_response event."""

    state_delta: Optional[dict[str, Any]]
    """Optional. Indicates that the event is updating the state with the given delta."""

    transfer_agent: Optional[str]
    """Optional. If set, the event transfers to the specified agent."""


EventActionsOrDict = Union[EventActions, EventActionsDict]


class EventMetadata(_common.BaseModel):
    """Metadata relating to a LLM response event."""

    grounding_metadata: Optional[genai_types.GroundingMetadata] = Field(
        default=None,
        description="""Optional. Metadata returned to client when grounding is enabled.""",
    )
    branch: Optional[str] = Field(
        default=None,
        description="""Optional. The branch of the event. The format is like agent_1.agent_2.agent_3, where agent_1 is the parent of agent_2, and agent_2 is the parent of agent_3. Branch is used when multiple child agents shouldn't see their siblings' conversation history.""",
    )
    custom_metadata: Optional[dict[str, Any]] = Field(
        default=None, description="""The custom metadata of the LlmResponse."""
    )
    interrupted: Optional[bool] = Field(
        default=None,
        description="""Optional. Flag indicating that LLM was interrupted when generating the content. Usually it's due to user interruption during a bidi streaming.""",
    )
    long_running_tool_ids: Optional[list[str]] = Field(
        default=None,
        description="""Optional. Set of ids of the long running function calls. Agent client will know from this field about which function call is long running. Only valid for function call event.""",
    )
    partial: Optional[bool] = Field(
        default=None,
        description="""Optional. Indicates whether the text content is part of a unfinished text stream. Only used for streaming mode and when the content is plain text.""",
    )
    turn_complete: Optional[bool] = Field(
        default=None,
        description="""Optional. Indicates whether the response from the model is complete. Only used for streaming mode.""",
    )


class EventMetadataDict(TypedDict, total=False):
    """Metadata relating to a LLM response event."""

    grounding_metadata: Optional[genai_types.GroundingMetadataDict]
    """Optional. Metadata returned to client when grounding is enabled."""

    branch: Optional[str]
    """Optional. The branch of the event. The format is like agent_1.agent_2.agent_3, where agent_1 is the parent of agent_2, and agent_2 is the parent of agent_3. Branch is used when multiple child agents shouldn't see their siblings' conversation history."""

    custom_metadata: Optional[dict[str, Any]]
    """The custom metadata of the LlmResponse."""

    interrupted: Optional[bool]
    """Optional. Flag indicating that LLM was interrupted when generating the content. Usually it's due to user interruption during a bidi streaming."""

    long_running_tool_ids: Optional[list[str]]
    """Optional. Set of ids of the long running function calls. Agent client will know from this field about which function call is long running. Only valid for function call event."""

    partial: Optional[bool]
    """Optional. Indicates whether the text content is part of a unfinished text stream. Only used for streaming mode and when the content is plain text."""

    turn_complete: Optional[bool]
    """Optional. Indicates whether the response from the model is complete. Only used for streaming mode."""


EventMetadataOrDict = Union[EventMetadata, EventMetadataDict]


class AppendAgentEngineSessionEventConfig(_common.BaseModel):
    """Config for appending agent engine session event."""

    http_options: Optional[genai_types.HttpOptions] = Field(
        default=None, description="""Used to override HTTP request options."""
    )
    content: Optional[genai_types.Content] = Field(
        default=None, description="""The content of the session event."""
    )
    actions: Optional[EventActions] = Field(
        default=None,
        description="""Actions are parts of events that are related to the session event.""",
    )
    error_code: Optional[str] = Field(
        default=None, description="""The error code of the session event."""
    )
    error_message: Optional[str] = Field(
        default=None, description="""The error message of the session event."""
    )
    event_metadata: Optional[EventMetadata] = Field(
        default=None, description="""Metadata relating to the session event."""
    )


class AppendAgentEngineSessionEventConfigDict(TypedDict, total=False):
    """Config for appending agent engine session event."""

    http_options: Optional[genai_types.HttpOptionsDict]
    """Used to override HTTP request options."""

    content: Optional[genai_types.ContentDict]
    """The content of the session event."""

    actions: Optional[EventActionsDict]
    """Actions are parts of events that are related to the session event."""

    error_code: Optional[str]
    """The error code of the session event."""

    error_message: Optional[str]
    """The error message of the session event."""

    event_metadata: Optional[EventMetadataDict]
    """Metadata relating to the session event."""


AppendAgentEngineSessionEventConfigOrDict = Union[
    AppendAgentEngineSessionEventConfig, AppendAgentEngineSessionEventConfigDict
]


class _AppendAgentEngineSessionEventRequestParameters(_common.BaseModel):
    """Parameters for appending agent engines."""

    name: Optional[str] = Field(
        default=None, description="""Name of the agent engine session."""
    )
    author: Optional[str] = Field(
        default=None, description="""Author of the agent engine session event."""
    )
    invocation_id: Optional[str] = Field(
        default=None, description="""Invocation ID of the agent engine."""
    )
    timestamp: Optional[datetime.datetime] = Field(
        default=None, description="""Timestamp indicating when the event was created."""
    )
    config: Optional[AppendAgentEngineSessionEventConfig] = Field(
        default=None, description=""""""
    )


class _AppendAgentEngineSessionEventRequestParametersDict(TypedDict, total=False):
    """Parameters for appending agent engines."""

    name: Optional[str]
    """Name of the agent engine session."""

    author: Optional[str]
    """Author of the agent engine session event."""

    invocation_id: Optional[str]
    """Invocation ID of the agent engine."""

    timestamp: Optional[datetime.datetime]
    """Timestamp indicating when the event was created."""

    config: Optional[AppendAgentEngineSessionEventConfigDict]
    """"""


_AppendAgentEngineSessionEventRequestParametersOrDict = Union[
    _AppendAgentEngineSessionEventRequestParameters,
    _AppendAgentEngineSessionEventRequestParametersDict,
]


class AppendAgentEngineSessionEventResponse(_common.BaseModel):
    """Response for appending agent engine session event."""

    pass


class AppendAgentEngineSessionEventResponseDict(TypedDict, total=False):
    """Response for appending agent engine session event."""

    pass


AppendAgentEngineSessionEventResponseOrDict = Union[
    AppendAgentEngineSessionEventResponse, AppendAgentEngineSessionEventResponseDict
]


class ListAgentEngineSessionEventsConfig(_common.BaseModel):
    """Config for listing agent engine session events."""

    http_options: Optional[genai_types.HttpOptions] = Field(
        default=None, description="""Used to override HTTP request options."""
    )
    page_size: Optional[int] = Field(default=None, description="""""")
    page_token: Optional[str] = Field(default=None, description="""""")
    filter: Optional[str] = Field(
        default=None,
        description="""An expression for filtering the results of the request.
      For field names both snake_case and camelCase are supported.""",
    )


class ListAgentEngineSessionEventsConfigDict(TypedDict, total=False):
    """Config for listing agent engine session events."""

    http_options: Optional[genai_types.HttpOptionsDict]
    """Used to override HTTP request options."""

    page_size: Optional[int]
    """"""

    page_token: Optional[str]
    """"""

    filter: Optional[str]
    """An expression for filtering the results of the request.
      For field names both snake_case and camelCase are supported."""


ListAgentEngineSessionEventsConfigOrDict = Union[
    ListAgentEngineSessionEventsConfig, ListAgentEngineSessionEventsConfigDict
]


class _ListAgentEngineSessionEventsRequestParameters(_common.BaseModel):
    """Parameters for listing agent engine session events."""

    name: Optional[str] = Field(
        default=None, description="""Name of the agent engine session."""
    )
    config: Optional[ListAgentEngineSessionEventsConfig] = Field(
        default=None, description=""""""
    )


class _ListAgentEngineSessionEventsRequestParametersDict(TypedDict, total=False):
    """Parameters for listing agent engine session events."""

    name: Optional[str]
    """Name of the agent engine session."""

    config: Optional[ListAgentEngineSessionEventsConfigDict]
    """"""


_ListAgentEngineSessionEventsRequestParametersOrDict = Union[
    _ListAgentEngineSessionEventsRequestParameters,
    _ListAgentEngineSessionEventsRequestParametersDict,
]


class SessionEvent(_common.BaseModel):
    """A session event."""

    content: Optional[genai_types.Content] = Field(
        default=None,
        description="""Optional. Content of the event provided by the author.""",
    )
    actions: Optional[EventActions] = Field(
        default=None, description="""Optional. Actions executed by the agent."""
    )
    author: Optional[str] = Field(
        default=None,
        description="""Required. The name of the agent that sent the event, or user.""",
    )
    error_code: Optional[str] = Field(
        default=None,
        description="""Optional. Error code if the response is an error. Code varies by model.""",
    )
    error_message: Optional[str] = Field(
        default=None,
        description="""Optional. Error message if the response is an error.""",
    )
    event_metadata: Optional[EventMetadata] = Field(
        default=None, description="""Optional. Metadata relating to this event."""
    )
    invocation_id: Optional[str] = Field(
        default=None,
        description="""Required. The invocation id of the event, multiple events can have the same invocation id.""",
    )
    name: Optional[str] = Field(
        default=None,
        description="""Identifier. The resource name of the event. Format:`projects/{project}/locations/{location}/reasoningEngines/{reasoning_engine}/sessions/{session}/events/{event}`.""",
    )
    timestamp: Optional[datetime.datetime] = Field(
        default=None,
        description="""Required. Timestamp when the event was created on client side.""",
    )


class SessionEventDict(TypedDict, total=False):
    """A session event."""

    content: Optional[genai_types.ContentDict]
    """Optional. Content of the event provided by the author."""

    actions: Optional[EventActionsDict]
    """Optional. Actions executed by the agent."""

    author: Optional[str]
    """Required. The name of the agent that sent the event, or user."""

    error_code: Optional[str]
    """Optional. Error code if the response is an error. Code varies by model."""

    error_message: Optional[str]
    """Optional. Error message if the response is an error."""

    event_metadata: Optional[EventMetadataDict]
    """Optional. Metadata relating to this event."""

    invocation_id: Optional[str]
    """Required. The invocation id of the event, multiple events can have the same invocation id."""

    name: Optional[str]
    """Identifier. The resource name of the event. Format:`projects/{project}/locations/{location}/reasoningEngines/{reasoning_engine}/sessions/{session}/events/{event}`."""

    timestamp: Optional[datetime.datetime]
    """Required. Timestamp when the event was created on client side."""


SessionEventOrDict = Union[SessionEvent, SessionEventDict]


class ListAgentEngineSessionEventsResponse(_common.BaseModel):
    """Response for listing agent engine session events."""

    sdk_http_response: Optional[genai_types.HttpResponse] = Field(
        default=None, description="""Used to retain the full HTTP response."""
    )
    next_page_token: Optional[str] = Field(default=None, description="""""")
    session_events: Optional[list[SessionEvent]] = Field(
        default=None, description="""List of session events."""
    )


class ListAgentEngineSessionEventsResponseDict(TypedDict, total=False):
    """Response for listing agent engine session events."""

    sdk_http_response: Optional[genai_types.HttpResponseDict]
    """Used to retain the full HTTP response."""

    next_page_token: Optional[str]
    """"""

    session_events: Optional[list[SessionEventDict]]
    """List of session events."""


ListAgentEngineSessionEventsResponseOrDict = Union[
    ListAgentEngineSessionEventsResponse, ListAgentEngineSessionEventsResponseDict
]


class GeminiExample(_common.BaseModel):
    """Represents a Gemini example."""

    model: Optional[str] = Field(
        default=None, description="""The model used to generate the Gemini example."""
    )
    contents: Optional[list[genai_types.Content]] = Field(
        default=None, description="""Contents of the Gemini example."""
    )
    system_instruction: Optional[genai_types.Content] = Field(
        default=None, description="""System instruction for the Gemini example."""
    )
    cached_content: Optional[str] = Field(
        default=None, description="""Cached content for the Gemini example."""
    )
    tools: Optional[genai_types.Tool] = Field(
        default=None, description="""Tools for the Gemini example."""
    )
    tool_config: Optional[genai_types.ToolConfig] = Field(
        default=None, description="""Tools for the Gemini example."""
    )
    safety_settings: Optional[genai_types.SafetySetting] = Field(
        default=None, description="""Safety settings for the Gemini example."""
    )
    labels: Optional[dict[str, str]] = Field(
        default=None, description="""Labels for the Gemini example."""
    )
    generation_config: Optional[genai_types.GenerationConfig] = Field(
        default=None, description="""Generation config for the Gemini example."""
    )


class GeminiExampleDict(TypedDict, total=False):
    """Represents a Gemini example."""

    model: Optional[str]
    """The model used to generate the Gemini example."""

    contents: Optional[list[genai_types.ContentDict]]
    """Contents of the Gemini example."""

    system_instruction: Optional[genai_types.ContentDict]
    """System instruction for the Gemini example."""

    cached_content: Optional[str]
    """Cached content for the Gemini example."""

    tools: Optional[genai_types.ToolDict]
    """Tools for the Gemini example."""

    tool_config: Optional[genai_types.ToolConfigDict]
    """Tools for the Gemini example."""

    safety_settings: Optional[genai_types.SafetySettingDict]
    """Safety settings for the Gemini example."""

    labels: Optional[dict[str, str]]
    """Labels for the Gemini example."""

    generation_config: Optional[genai_types.GenerationConfigDict]
    """Generation config for the Gemini example."""


GeminiExampleOrDict = Union[GeminiExample, GeminiExampleDict]


class GeminiTemplateConfig(_common.BaseModel):
    """Represents a Gemini template config."""

    gemini_example: Optional[GeminiExample] = Field(
        default=None,
        description="""Required. The template that will be used for assembling the request to use for downstream applications.""",
    )
    field_mapping: Optional[dict[str, str]] = Field(
        default=None,
        description="""Required. Map of template parameters to the columns in the dataset table.""",
    )


class GeminiTemplateConfigDict(TypedDict, total=False):
    """Represents a Gemini template config."""

    gemini_example: Optional[GeminiExampleDict]
    """Required. The template that will be used for assembling the request to use for downstream applications."""

    field_mapping: Optional[dict[str, str]]
    """Required. Map of template parameters to the columns in the dataset table."""


GeminiTemplateConfigOrDict = Union[GeminiTemplateConfig, GeminiTemplateConfigDict]


class GeminiRequestReadConfig(_common.BaseModel):
    """Represents the config for reading Gemini requests."""

    template_config: Optional[GeminiTemplateConfig] = Field(
        default=None, description="""Gemini request template with placeholders."""
    )
    assembled_request_column_name: Optional[str] = Field(
        default=None,
        description="""Optional. Column name in the dataset table that contains already fully assembled Gemini requests.""",
    )


class GeminiRequestReadConfigDict(TypedDict, total=False):
    """Represents the config for reading Gemini requests."""

    template_config: Optional[GeminiTemplateConfigDict]
    """Gemini request template with placeholders."""

    assembled_request_column_name: Optional[str]
    """Optional. Column name in the dataset table that contains already fully assembled Gemini requests."""


GeminiRequestReadConfigOrDict = Union[
    GeminiRequestReadConfig, GeminiRequestReadConfigDict
]


class AssembleDatasetConfig(_common.BaseModel):
    """Config for assembling a multimodal dataset resource."""

    http_options: Optional[genai_types.HttpOptions] = Field(
        default=None, description="""Used to override HTTP request options."""
    )
    timeout: Optional[int] = Field(
        default=90,
        description="""The timeout for the assemble dataset request in seconds. If not
      set, the default timeout is 90 seconds.""",
    )


class AssembleDatasetConfigDict(TypedDict, total=False):
    """Config for assembling a multimodal dataset resource."""

    http_options: Optional[genai_types.HttpOptionsDict]
    """Used to override HTTP request options."""

    timeout: Optional[int]
    """The timeout for the assemble dataset request in seconds. If not
      set, the default timeout is 90 seconds."""


AssembleDatasetConfigOrDict = Union[AssembleDatasetConfig, AssembleDatasetConfigDict]


class _AssembleDatasetParameters(_common.BaseModel):
    """Parameters for assembling a multimodal dataset resource."""

    name: Optional[str] = Field(default=None, description="""""")
    gemini_request_read_config: Optional[GeminiRequestReadConfig] = Field(
        default=None, description=""""""
    )
    config: Optional[AssembleDatasetConfig] = Field(default=None, description="""""")


class _AssembleDatasetParametersDict(TypedDict, total=False):
    """Parameters for assembling a multimodal dataset resource."""

    name: Optional[str]
    """"""

    gemini_request_read_config: Optional[GeminiRequestReadConfigDict]
    """"""

    config: Optional[AssembleDatasetConfigDict]
    """"""


_AssembleDatasetParametersOrDict = Union[
    _AssembleDatasetParameters, _AssembleDatasetParametersDict
]


class MultimodalDatasetOperation(_common.BaseModel):
    """Represents the create dataset operation."""

    name: Optional[str] = Field(
        default=None,
        description="""The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`.""",
    )
    metadata: Optional[dict[str, Any]] = Field(
        default=None,
        description="""Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata.  Any method that returns a long-running operation should document the metadata type, if any.""",
    )
    done: Optional[bool] = Field(
        default=None,
        description="""If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available.""",
    )
    error: Optional[dict[str, Any]] = Field(
        default=None,
        description="""The error result of the operation in case of failure or cancellation.""",
    )
    response: Optional[dict[str, Any]] = Field(
        default=None, description="""The result of the dataset operation."""
    )


class MultimodalDatasetOperationDict(TypedDict, total=False):
    """Represents the create dataset operation."""

    name: Optional[str]
    """The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`."""

    metadata: Optional[dict[str, Any]]
    """Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata.  Any method that returns a long-running operation should document the metadata type, if any."""

    done: Optional[bool]
    """If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available."""

    error: Optional[dict[str, Any]]
    """The error result of the operation in case of failure or cancellation."""

    response: Optional[dict[str, Any]]
    """The result of the dataset operation."""


MultimodalDatasetOperationOrDict = Union[
    MultimodalDatasetOperation, MultimodalDatasetOperationDict
]


class TuningResourceUsageAssessmentConfig(_common.BaseModel):
    """Config for tuning resource usage assessment."""

    model_name: Optional[str] = Field(default=None, description="""""")


class TuningResourceUsageAssessmentConfigDict(TypedDict, total=False):
    """Config for tuning resource usage assessment."""

    model_name: Optional[str]
    """"""


TuningResourceUsageAssessmentConfigOrDict = Union[
    TuningResourceUsageAssessmentConfig, TuningResourceUsageAssessmentConfigDict
]


class TuningValidationAssessmentConfig(_common.BaseModel):
    """Config for tuning validation assessment."""

    model_name: Optional[str] = Field(default=None, description="""""")
    dataset_usage: Optional[str] = Field(default=None, description="""""")


class TuningValidationAssessmentConfigDict(TypedDict, total=False):
    """Config for tuning validation assessment."""

    model_name: Optional[str]
    """"""

    dataset_usage: Optional[str]
    """"""


TuningValidationAssessmentConfigOrDict = Union[
    TuningValidationAssessmentConfig, TuningValidationAssessmentConfigDict
]


class BatchPredictionResourceUsageAssessmentConfig(_common.BaseModel):
    """Config for batch prediction resource usage assessment."""

    model_name: Optional[str] = Field(default=None, description="""""")


class BatchPredictionResourceUsageAssessmentConfigDict(TypedDict, total=False):
    """Config for batch prediction resource usage assessment."""

    model_name: Optional[str]
    """"""


BatchPredictionResourceUsageAssessmentConfigOrDict = Union[
    BatchPredictionResourceUsageAssessmentConfig,
    BatchPredictionResourceUsageAssessmentConfigDict,
]


class BatchPredictionValidationAssessmentConfig(_common.BaseModel):
    """Config for batch prediction validation assessment."""

    model_name: Optional[str] = Field(default=None, description="""""")


class BatchPredictionValidationAssessmentConfigDict(TypedDict, total=False):
    """Config for batch prediction validation assessment."""

    model_name: Optional[str]
    """"""


BatchPredictionValidationAssessmentConfigOrDict = Union[
    BatchPredictionValidationAssessmentConfig,
    BatchPredictionValidationAssessmentConfigDict,
]


class AssessDatasetConfig(_common.BaseModel):
    """Config for assessing a multimodal dataset resource."""

    http_options: Optional[genai_types.HttpOptions] = Field(
        default=None, description="""Used to override HTTP request options."""
    )
    timeout: Optional[int] = Field(
        default=90,
        description="""The timeout for the assess dataset request in seconds. If not set,
      the default timeout is 90 seconds.""",
    )


class AssessDatasetConfigDict(TypedDict, total=False):
    """Config for assessing a multimodal dataset resource."""

    http_options: Optional[genai_types.HttpOptionsDict]
    """Used to override HTTP request options."""

    timeout: Optional[int]
    """The timeout for the assess dataset request in seconds. If not set,
      the default timeout is 90 seconds."""


AssessDatasetConfigOrDict = Union[AssessDatasetConfig, AssessDatasetConfigDict]


class _AssessDatasetParameters(_common.BaseModel):
    """Parameters for assessing a multimodal dataset resource."""

    name: Optional[str] = Field(default=None, description="""""")
    gemini_request_read_config: Optional[GeminiRequestReadConfig] = Field(
        default=None, description=""""""
    )
    tuning_resource_usage_assessment_config: Optional[
        TuningResourceUsageAssessmentConfig
    ] = Field(default=None, description="""""")
    tuning_validation_assessment_config: Optional[TuningValidationAssessmentConfig] = (
        Field(default=None, description="""""")
    )
    batch_prediction_resource_usage_assessment_config: Optional[
        BatchPredictionResourceUsageAssessmentConfig
    ] = Field(default=None, description="""""")
    batch_prediction_validation_assessment_config: Optional[
        BatchPredictionValidationAssessmentConfig
    ] = Field(default=None, description="""""")
    config: Optional[AssessDatasetConfig] = Field(default=None, description="""""")


class _AssessDatasetParametersDict(TypedDict, total=False):
    """Parameters for assessing a multimodal dataset resource."""

    name: Optional[str]
    """"""

    gemini_request_read_config: Optional[GeminiRequestReadConfigDict]
    """"""

    tuning_resource_usage_assessment_config: Optional[
        TuningResourceUsageAssessmentConfigDict
    ]
    """"""

    tuning_validation_assessment_config: Optional[TuningValidationAssessmentConfigDict]
    """"""

    batch_prediction_resource_usage_assessment_config: Optional[
        BatchPredictionResourceUsageAssessmentConfigDict
    ]
    """"""

    batch_prediction_validation_assessment_config: Optional[
        BatchPredictionValidationAssessmentConfigDict
    ]
    """"""

    config: Optional[AssessDatasetConfigDict]
    """"""


_AssessDatasetParametersOrDict = Union[
    _AssessDatasetParameters, _AssessDatasetParametersDict
]


class SchemaTablesDatasetMetadataBigQuerySource(_common.BaseModel):
    """Represents the BigQuery source for multimodal dataset metadata."""

    uri: Optional[str] = Field(
        default=None,
        description="""The URI of the BigQuery table. This accepts the table name with or without the bq:// prefix.""",
    )


class SchemaTablesDatasetMetadataBigQuerySourceDict(TypedDict, total=False):
    """Represents the BigQuery source for multimodal dataset metadata."""

    uri: Optional[str]
    """The URI of the BigQuery table. This accepts the table name with or without the bq:// prefix."""


SchemaTablesDatasetMetadataBigQuerySourceOrDict = Union[
    SchemaTablesDatasetMetadataBigQuerySource,
    SchemaTablesDatasetMetadataBigQuerySourceDict,
]


class SchemaTablesDatasetMetadataInputConfig(_common.BaseModel):
    """Represents the input config for multimodal dataset metadata."""

    bigquery_source: Optional[SchemaTablesDatasetMetadataBigQuerySource] = Field(
        default=None,
        description="""The BigQuery source for multimodal dataset metadata.""",
    )


class SchemaTablesDatasetMetadataInputConfigDict(TypedDict, total=False):
    """Represents the input config for multimodal dataset metadata."""

    bigquery_source: Optional[SchemaTablesDatasetMetadataBigQuerySourceDict]
    """The BigQuery source for multimodal dataset metadata."""


SchemaTablesDatasetMetadataInputConfigOrDict = Union[
    SchemaTablesDatasetMetadataInputConfig, SchemaTablesDatasetMetadataInputConfigDict
]


class SchemaTablesDatasetMetadata(_common.BaseModel):
    """Represents the metadata schema for multimodal dataset metadata."""

    input_config: Optional[SchemaTablesDatasetMetadataInputConfig] = Field(
        default=None,
        description="""The input config for multimodal dataset metadata.""",
    )


class SchemaTablesDatasetMetadataDict(TypedDict, total=False):
    """Represents the metadata schema for multimodal dataset metadata."""

    input_config: Optional[SchemaTablesDatasetMetadataInputConfigDict]
    """The input config for multimodal dataset metadata."""


SchemaTablesDatasetMetadataOrDict = Union[
    SchemaTablesDatasetMetadata, SchemaTablesDatasetMetadataDict
]


class CreateMultimodalDatasetConfig(_common.BaseModel):
    """Config for creating a dataset resource to store multimodal dataset."""

    http_options: Optional[genai_types.HttpOptions] = Field(
        default=None, description="""Used to override HTTP request options."""
    )
    timeout: Optional[int] = Field(
        default=90,
        description="""The timeout for the create dataset request in seconds. If not set,
      the default timeout is 90 seconds.""",
    )


class CreateMultimodalDatasetConfigDict(TypedDict, total=False):
    """Config for creating a dataset resource to store multimodal dataset."""

    http_options: Optional[genai_types.HttpOptionsDict]
    """Used to override HTTP request options."""

    timeout: Optional[int]
    """The timeout for the create dataset request in seconds. If not set,
      the default timeout is 90 seconds."""


CreateMultimodalDatasetConfigOrDict = Union[
    CreateMultimodalDatasetConfig, CreateMultimodalDatasetConfigDict
]


class _CreateMultimodalDatasetParameters(_common.BaseModel):
    """Parameters for creating a dataset resource to store multimodal dataset."""

    name: Optional[str] = Field(default=None, description="""""")
    display_name: Optional[str] = Field(default=None, description="""""")
    metadata_schema_uri: Optional[str] = Field(default=None, description="""""")
    metadata: Optional[SchemaTablesDatasetMetadata] = Field(
        default=None, description=""""""
    )
    description: Optional[str] = Field(default=None, description="""""")
    encryption_spec: Optional[genai_types.EncryptionSpec] = Field(
        default=None, description=""""""
    )
    config: Optional[CreateMultimodalDatasetConfig] = Field(
        default=None, description=""""""
    )


class _CreateMultimodalDatasetParametersDict(TypedDict, total=False):
    """Parameters for creating a dataset resource to store multimodal dataset."""

    name: Optional[str]
    """"""

    display_name: Optional[str]
    """"""

    metadata_schema_uri: Optional[str]
    """"""

    metadata: Optional[SchemaTablesDatasetMetadataDict]
    """"""

    description: Optional[str]
    """"""

    encryption_spec: Optional[genai_types.EncryptionSpecDict]
    """"""

    config: Optional[CreateMultimodalDatasetConfigDict]
    """"""


_CreateMultimodalDatasetParametersOrDict = Union[
    _CreateMultimodalDatasetParameters, _CreateMultimodalDatasetParametersDict
]


class _DeleteMultimodalDatasetRequestParameters(_common.BaseModel):
    """Parameters for deleting a multimodal dataset."""

    name: Optional[str] = Field(
        default=None, description="""ID of the dataset to be deleted."""
    )
    config: Optional[VertexBaseConfig] = Field(default=None, description="""""")


class _DeleteMultimodalDatasetRequestParametersDict(TypedDict, total=False):
    """Parameters for deleting a multimodal dataset."""

    name: Optional[str]
    """ID of the dataset to be deleted."""

    config: Optional[VertexBaseConfigDict]
    """"""


_DeleteMultimodalDatasetRequestParametersOrDict = Union[
    _DeleteMultimodalDatasetRequestParameters,
    _DeleteMultimodalDatasetRequestParametersDict,
]


class _GetMultimodalDatasetParameters(_common.BaseModel):
    """Parameters for getting a multimodal dataset resource."""

    name: Optional[str] = Field(default=None, description="""""")
    config: Optional[VertexBaseConfig] = Field(default=None, description="""""")


class _GetMultimodalDatasetParametersDict(TypedDict, total=False):
    """Parameters for getting a multimodal dataset resource."""

    name: Optional[str]
    """"""

    config: Optional[VertexBaseConfigDict]
    """"""


_GetMultimodalDatasetParametersOrDict = Union[
    _GetMultimodalDatasetParameters, _GetMultimodalDatasetParametersDict
]


class MultimodalDataset(_common.BaseModel):
    """Represents a multimodal dataset."""

    name: Optional[str] = Field(
        default=None, description="""The ID of the multimodal dataset."""
    )
    display_name: Optional[str] = Field(
        default=None, description="""The display name of the multimodal dataset."""
    )
    metadata: Optional[SchemaTablesDatasetMetadata] = Field(
        default=None, description="""The metadata of the multimodal dataset."""
    )
    description: Optional[str] = Field(
        default=None, description="""The description of the multimodal dataset."""
    )


class MultimodalDatasetDict(TypedDict, total=False):
    """Represents a multimodal dataset."""

    name: Optional[str]
    """The ID of the multimodal dataset."""

    display_name: Optional[str]
    """The display name of the multimodal dataset."""

    metadata: Optional[SchemaTablesDatasetMetadataDict]
    """The metadata of the multimodal dataset."""

    description: Optional[str]
    """The description of the multimodal dataset."""


MultimodalDatasetOrDict = Union[MultimodalDataset, MultimodalDatasetDict]


class GetMultimodalDatasetOperationConfig(_common.BaseModel):
    """Config for getting a multimodal dataset operation."""

    http_options: Optional[genai_types.HttpOptions] = Field(
        default=None, description="""Used to override HTTP request options."""
    )


class GetMultimodalDatasetOperationConfigDict(TypedDict, total=False):
    """Config for getting a multimodal dataset operation."""

    http_options: Optional[genai_types.HttpOptionsDict]
    """Used to override HTTP request options."""


GetMultimodalDatasetOperationConfigOrDict = Union[
    GetMultimodalDatasetOperationConfig, GetMultimodalDatasetOperationConfigDict
]


class _GetMultimodalDatasetOperationParameters(_common.BaseModel):
    """Parameters for getting a dataset operation."""

    dataset_id: Optional[str] = Field(default=None, description="""""")
    operation_id: Optional[str] = Field(default=None, description="""""")
    config: Optional[GetMultimodalDatasetOperationConfig] = Field(
        default=None, description=""""""
    )


class _GetMultimodalDatasetOperationParametersDict(TypedDict, total=False):
    """Parameters for getting a dataset operation."""

    dataset_id: Optional[str]
    """"""

    operation_id: Optional[str]
    """"""

    config: Optional[GetMultimodalDatasetOperationConfigDict]
    """"""


_GetMultimodalDatasetOperationParametersOrDict = Union[
    _GetMultimodalDatasetOperationParameters,
    _GetMultimodalDatasetOperationParametersDict,
]


class ListMultimodalDatasetsConfig(_common.BaseModel):
    """Config for listing multimodal datasets."""

    http_options: Optional[genai_types.HttpOptions] = Field(
        default=None, description="""Used to override HTTP request options."""
    )
    page_size: Optional[int] = Field(default=None, description="""""")
    page_token: Optional[str] = Field(default=None, description="""""")
    filter: Optional[str] = Field(
        default=None,
        description="""An expression for filtering the results of the request.
      For field names both snake_case and camelCase are supported.""",
    )


class ListMultimodalDatasetsConfigDict(TypedDict, total=False):
    """Config for listing multimodal datasets."""

    http_options: Optional[genai_types.HttpOptionsDict]
    """Used to override HTTP request options."""

    page_size: Optional[int]
    """"""

    page_token: Optional[str]
    """"""

    filter: Optional[str]
    """An expression for filtering the results of the request.
      For field names both snake_case and camelCase are supported."""


ListMultimodalDatasetsConfigOrDict = Union[
    ListMultimodalDatasetsConfig, ListMultimodalDatasetsConfigDict
]


class _ListMultimodalDatasetsRequestParameters(_common.BaseModel):
    """Parameters for listing multimodal datasets."""

    config: Optional[ListMultimodalDatasetsConfig] = Field(
        default=None, description=""""""
    )


class _ListMultimodalDatasetsRequestParametersDict(TypedDict, total=False):
    """Parameters for listing multimodal datasets."""

    config: Optional[ListMultimodalDatasetsConfigDict]
    """"""


_ListMultimodalDatasetsRequestParametersOrDict = Union[
    _ListMultimodalDatasetsRequestParameters,
    _ListMultimodalDatasetsRequestParametersDict,
]


class ListMultimodalDatasetsResponse(_common.BaseModel):
    """Response for listing multimodal datasets."""

    sdk_http_response: Optional[genai_types.HttpResponse] = Field(
        default=None, description="""Used to retain the full HTTP response."""
    )
    next_page_token: Optional[str] = Field(default=None, description="""""")
    timeout: Optional[int] = Field(
        default=90,
        description="""The timeout for the list datasets request in seconds. If not set,
      the default timeout is 90 seconds.""",
    )
    datasets: Optional[list[MultimodalDataset]] = Field(
        default=None,
        description="""List of datasets for the project.
      """,
    )


class ListMultimodalDatasetsResponseDict(TypedDict, total=False):
    """Response for listing multimodal datasets."""

    sdk_http_response: Optional[genai_types.HttpResponseDict]
    """Used to retain the full HTTP response."""

    next_page_token: Optional[str]
    """"""

    timeout: Optional[int]
    """The timeout for the list datasets request in seconds. If not set,
      the default timeout is 90 seconds."""

    datasets: Optional[list[MultimodalDatasetDict]]
    """List of datasets for the project.
      """


ListMultimodalDatasetsResponseOrDict = Union[
    ListMultimodalDatasetsResponse, ListMultimodalDatasetsResponseDict
]


class UpdateMultimodalDatasetConfig(_common.BaseModel):
    """Config for updating a multimodal dataset resource."""

    http_options: Optional[genai_types.HttpOptions] = Field(
        default=None, description="""Used to override HTTP request options."""
    )
    timeout: Optional[int] = Field(
        default=90,
        description="""The timeout for the update dataset request in seconds. If not set,
      the default timeout is 90 seconds.""",
    )


class UpdateMultimodalDatasetConfigDict(TypedDict, total=False):
    """Config for updating a multimodal dataset resource."""

    http_options: Optional[genai_types.HttpOptionsDict]
    """Used to override HTTP request options."""

    timeout: Optional[int]
    """The timeout for the update dataset request in seconds. If not set,
      the default timeout is 90 seconds."""


UpdateMultimodalDatasetConfigOrDict = Union[
    UpdateMultimodalDatasetConfig, UpdateMultimodalDatasetConfigDict
]


class _UpdateMultimodalDatasetParameters(_common.BaseModel):
    """Parameters for updating a multimodal dataset resource."""

    name: Optional[str] = Field(default=None, description="""""")
    display_name: Optional[str] = Field(default=None, description="""""")
    metadata: Optional[SchemaTablesDatasetMetadata] = Field(
        default=None, description=""""""
    )
    description: Optional[str] = Field(default=None, description="""""")
    encryption_spec: Optional[genai_types.EncryptionSpec] = Field(
        default=None, description=""""""
    )
    config: Optional[UpdateMultimodalDatasetConfig] = Field(
        default=None, description=""""""
    )


class _UpdateMultimodalDatasetParametersDict(TypedDict, total=False):
    """Parameters for updating a multimodal dataset resource."""

    name: Optional[str]
    """"""

    display_name: Optional[str]
    """"""

    metadata: Optional[SchemaTablesDatasetMetadataDict]
    """"""

    description: Optional[str]
    """"""

    encryption_spec: Optional[genai_types.EncryptionSpecDict]
    """"""

    config: Optional[UpdateMultimodalDatasetConfigDict]
    """"""


_UpdateMultimodalDatasetParametersOrDict = Union[
    _UpdateMultimodalDatasetParameters, _UpdateMultimodalDatasetParametersDict
]


class SchemaPredictParamsGroundingConfigSourceEntry(_common.BaseModel):
    """Single source entry for the grounding checking."""

    enterprise_datastore: Optional[str] = Field(
        default=None,
        description="""The uri of the Vertex AI Search data source. Deprecated. Use vertex_ai_search_datastore instead.""",
    )
    inline_context: Optional[str] = Field(
        default=None,
        description="""The grounding text passed inline with the Predict API. It can support up to 1 million bytes.""",
    )
    type: Optional[
        Literal["UNSPECIFIED", "WEB", "ENTERPRISE", "VERTEX_AI_SEARCH", "INLINE"]
    ] = Field(
        default=None, description="""The type of the grounding checking source."""
    )
    vertex_ai_search_datastore: Optional[str] = Field(
        default=None, description="""The uri of the Vertex AI Search data source."""
    )


class SchemaPredictParamsGroundingConfigSourceEntryDict(TypedDict, total=False):
    """Single source entry for the grounding checking."""

    enterprise_datastore: Optional[str]
    """The uri of the Vertex AI Search data source. Deprecated. Use vertex_ai_search_datastore instead."""

    inline_context: Optional[str]
    """The grounding text passed inline with the Predict API. It can support up to 1 million bytes."""

    type: Optional[
        Literal["UNSPECIFIED", "WEB", "ENTERPRISE", "VERTEX_AI_SEARCH", "INLINE"]
    ]
    """The type of the grounding checking source."""

    vertex_ai_search_datastore: Optional[str]
    """The uri of the Vertex AI Search data source."""


SchemaPredictParamsGroundingConfigSourceEntryOrDict = Union[
    SchemaPredictParamsGroundingConfigSourceEntry,
    SchemaPredictParamsGroundingConfigSourceEntryDict,
]


class SchemaPredictParamsGroundingConfig(_common.BaseModel):
    """The configuration for grounding checking."""

    disable_attribution: Optional[bool] = Field(
        default=None,
        description="""If set, skip finding claim attributions (i.e not generate grounding citation).""",
    )
    sources: Optional[list[SchemaPredictParamsGroundingConfigSourceEntry]] = Field(
        default=None, description="""The sources for the grounding checking."""
    )


class SchemaPredictParamsGroundingConfigDict(TypedDict, total=False):
    """The configuration for grounding checking."""

    disable_attribution: Optional[bool]
    """If set, skip finding claim attributions (i.e not generate grounding citation)."""

    sources: Optional[list[SchemaPredictParamsGroundingConfigSourceEntryDict]]
    """The sources for the grounding checking."""


SchemaPredictParamsGroundingConfigOrDict = Union[
    SchemaPredictParamsGroundingConfig, SchemaPredictParamsGroundingConfigDict
]


class SchemaPromptInstancePromptExecution(_common.BaseModel):
    """A prompt instance's parameters set that contains a set of variable values."""

    arguments: Optional[dict[str, "SchemaPromptInstanceVariableValue"]] = Field(
        default=None, description="""Maps variable names to their value."""
    )


class SchemaPromptInstancePromptExecutionDict(TypedDict, total=False):
    """A prompt instance's parameters set that contains a set of variable values."""

    arguments: Optional[dict[str, "SchemaPromptInstanceVariableValueDict"]]
    """Maps variable names to their value."""


SchemaPromptInstancePromptExecutionOrDict = Union[
    SchemaPromptInstancePromptExecution, SchemaPromptInstancePromptExecutionDict
]


class SchemaPromptSpecPromptMessage(_common.BaseModel):
    """Represents a prompt message."""

    generation_config: Optional[genai_types.GenerationConfig] = Field(
        default=None, description="""Generation config."""
    )
    tool_config: Optional[genai_types.FunctionCallingConfig] = Field(
        default=None,
        description="""Tool config. This config is shared for all tools provided in the request.""",
    )
    tools: Optional[list[genai_types.Tool]] = Field(
        default=None,
        description="""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.""",
    )
    safety_settings: Optional[list[genai_types.SafetySetting]] = Field(
        default=None,
        description="""Per request settings for blocking unsafe content. Enforced on GenerateContentResponse.candidates.""",
    )
    contents: Optional[list[genai_types.Content]] = Field(
        default=None,
        description="""The content of 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 + latest request.""",
    )
    system_instruction: Optional[genai_types.Content] = Field(
        default=None,
        description="""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.""",
    )
    variables: Optional[list[dict[str, genai_types.Part]]] = Field(
        default=None, description=""""""
    )
    model: Optional[str] = Field(default=None, description="""The model name.""")


class SchemaPromptSpecPromptMessageDict(TypedDict, total=False):
    """Represents a prompt message."""

    generation_config: Optional[genai_types.GenerationConfigDict]
    """Generation config."""

    tool_config: Optional[genai_types.FunctionCallingConfigDict]
    """Tool config. This config is shared for all tools provided in the request."""

    tools: Optional[list[genai_types.ToolDict]]
    """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."""

    safety_settings: Optional[list[genai_types.SafetySettingDict]]
    """Per request settings for blocking unsafe content. Enforced on GenerateContentResponse.candidates."""

    contents: Optional[list[genai_types.ContentDict]]
    """The content of 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 + latest request."""

    system_instruction: Optional[genai_types.ContentDict]
    """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."""

    variables: Optional[list[dict[str, genai_types.PartDict]]]
    """"""

    model: Optional[str]
    """The model name."""


SchemaPromptSpecPromptMessageOrDict = Union[
    SchemaPromptSpecPromptMessage, SchemaPromptSpecPromptMessageDict
]


class SchemaPromptSpecMultimodalPrompt(_common.BaseModel):
    """Prompt variation that embeds preambles to prompt string."""

    prompt_message: Optional[SchemaPromptSpecPromptMessage] = Field(
        default=None, description="""The prompt message."""
    )


class SchemaPromptSpecMultimodalPromptDict(TypedDict, total=False):
    """Prompt variation that embeds preambles to prompt string."""

    prompt_message: Optional[SchemaPromptSpecPromptMessageDict]
    """The prompt message."""


SchemaPromptSpecMultimodalPromptOrDict = Union[
    SchemaPromptSpecMultimodalPrompt, SchemaPromptSpecMultimodalPromptDict
]


class SchemaPromptSpecPartList(_common.BaseModel):
    """Represents a prompt spec part list."""

    parts: Optional[list[genai_types.Part]] = Field(
        default=None, description="""A list of elements that can be part of a prompt."""
    )


class SchemaPromptSpecPartListDict(TypedDict, total=False):
    """Represents a prompt spec part list."""

    parts: Optional[list[genai_types.PartDict]]
    """A list of elements that can be part of a prompt."""


SchemaPromptSpecPartListOrDict = Union[
    SchemaPromptSpecPartList, SchemaPromptSpecPartListDict
]


class SchemaPromptSpecStructuredPrompt(_common.BaseModel):
    """Represents a structured prompt."""

    context: Optional[genai_types.Content] = Field(
        default=None, description="""Preamble: The context of the prompt."""
    )
    examples: Optional[list[SchemaPromptSpecPartList]] = Field(
        default=None,
        description="""Preamble: A set of examples for expected model response.""",
    )
    infill_prefix: Optional[str] = Field(
        default=None,
        description="""Preamble: For infill prompt, the prefix before expected model response.""",
    )
    infill_suffix: Optional[str] = Field(
        default=None,
        description="""Preamble: For infill prompt, the suffix after expected model response.""",
    )
    input_prefixes: Optional[list[str]] = Field(
        default=None,
        description="""Preamble: The input prefixes before each example input.""",
    )
    output_prefixes: Optional[list[str]] = Field(
        default=None,
        description="""Preamble: The output prefixes before each example output.""",
    )
    prediction_inputs: Optional[list[SchemaPromptSpecPartList]] = Field(
        default=None,
        description="""Preamble: The input test data for prediction. Each PartList in this field represents one text-only input set for a single model request.""",
    )
    prompt_message: Optional[SchemaPromptSpecPromptMessage] = Field(
        default=None, description="""The prompt message."""
    )


class SchemaPromptSpecStructuredPromptDict(TypedDict, total=False):
    """Represents a structured prompt."""

    context: Optional[genai_types.ContentDict]
    """Preamble: The context of the prompt."""

    examples: Optional[list[SchemaPromptSpecPartListDict]]
    """Preamble: A set of examples for expected model response."""

    infill_prefix: Optional[str]
    """Preamble: For infill prompt, the prefix before expected model response."""

    infill_suffix: Optional[str]
    """Preamble: For infill prompt, the suffix after expected model response."""

    input_prefixes: Optional[list[str]]
    """Preamble: The input prefixes before each example input."""

    output_prefixes: Optional[list[str]]
    """Preamble: The output prefixes before each example output."""

    prediction_inputs: Optional[list[SchemaPromptSpecPartListDict]]
    """Preamble: The input test data for prediction. Each PartList in this field represents one text-only input set for a single model request."""

    prompt_message: Optional[SchemaPromptSpecPromptMessageDict]
    """The prompt message."""


SchemaPromptSpecStructuredPromptOrDict = Union[
    SchemaPromptSpecStructuredPrompt, SchemaPromptSpecStructuredPromptDict
]


class SchemaPromptSpecReferenceSentencePair(_common.BaseModel):
    """A pair of sentences used as reference in source and target languages."""

    source_sentence: Optional[str] = Field(
        default=None, description="""Source sentence in the sentence pair."""
    )
    target_sentence: Optional[str] = Field(
        default=None, description="""Target sentence in the sentence pair."""
    )


class SchemaPromptSpecReferenceSentencePairDict(TypedDict, total=False):
    """A pair of sentences used as reference in source and target languages."""

    source_sentence: Optional[str]
    """Source sentence in the sentence pair."""

    target_sentence: Optional[str]
    """Target sentence in the sentence pair."""


SchemaPromptSpecReferenceSentencePairOrDict = Union[
    SchemaPromptSpecReferenceSentencePair, SchemaPromptSpecReferenceSentencePairDict
]


class SchemaPromptSpecReferenceSentencePairList(_common.BaseModel):
    """A list of reference sentence pairs."""

    reference_sentence_pairs: Optional[list[SchemaPromptSpecReferenceSentencePair]] = (
        Field(default=None, description="""Reference sentence pairs.""")
    )


class SchemaPromptSpecReferenceSentencePairListDict(TypedDict, total=False):
    """A list of reference sentence pairs."""

    reference_sentence_pairs: Optional[list[SchemaPromptSpecReferenceSentencePairDict]]
    """Reference sentence pairs."""


SchemaPromptSpecReferenceSentencePairListOrDict = Union[
    SchemaPromptSpecReferenceSentencePairList,
    SchemaPromptSpecReferenceSentencePairListDict,
]


class SchemaPromptSpecTranslationFileInputSource(_common.BaseModel):

    content: Optional[str] = Field(default=None, description="""The file's contents.""")
    display_name: Optional[str] = Field(
        default=None, description="""The file's display name."""
    )
    mime_type: Optional[str] = Field(
        default=None, description="""The file's mime type."""
    )


class SchemaPromptSpecTranslationFileInputSourceDict(TypedDict, total=False):

    content: Optional[str]
    """The file's contents."""

    display_name: Optional[str]
    """The file's display name."""

    mime_type: Optional[str]
    """The file's mime type."""


SchemaPromptSpecTranslationFileInputSourceOrDict = Union[
    SchemaPromptSpecTranslationFileInputSource,
    SchemaPromptSpecTranslationFileInputSourceDict,
]


class SchemaPromptSpecTranslationGcsInputSource(_common.BaseModel):

    input_uri: Optional[str] = Field(
        default=None,
        description="""Source data URI. For example, `gs://my_bucket/my_object`.""",
    )


class SchemaPromptSpecTranslationGcsInputSourceDict(TypedDict, total=False):

    input_uri: Optional[str]
    """Source data URI. For example, `gs://my_bucket/my_object`."""


SchemaPromptSpecTranslationGcsInputSourceOrDict = Union[
    SchemaPromptSpecTranslationGcsInputSource,
    SchemaPromptSpecTranslationGcsInputSourceDict,
]


class SchemaPromptSpecTranslationSentenceFileInput(_common.BaseModel):

    file_input_source: Optional[SchemaPromptSpecTranslationFileInputSource] = Field(
        default=None, description="""Inlined file source."""
    )
    gcs_input_source: Optional[SchemaPromptSpecTranslationGcsInputSource] = Field(
        default=None, description="""Cloud Storage file source."""
    )


class SchemaPromptSpecTranslationSentenceFileInputDict(TypedDict, total=False):

    file_input_source: Optional[SchemaPromptSpecTranslationFileInputSourceDict]
    """Inlined file source."""

    gcs_input_source: Optional[SchemaPromptSpecTranslationGcsInputSourceDict]
    """Cloud Storage file source."""


SchemaPromptSpecTranslationSentenceFileInputOrDict = Union[
    SchemaPromptSpecTranslationSentenceFileInput,
    SchemaPromptSpecTranslationSentenceFileInputDict,
]


class SchemaPromptSpecTranslationExample(_common.BaseModel):
    """The translation example that contains reference sentences from various sources."""

    reference_sentence_pair_lists: Optional[
        list[SchemaPromptSpecReferenceSentencePairList]
    ] = Field(default=None, description="""The reference sentences from inline text.""")
    reference_sentences_file_inputs: Optional[
        list[SchemaPromptSpecTranslationSentenceFileInput]
    ] = Field(default=None, description="""The reference sentences from file.""")


class SchemaPromptSpecTranslationExampleDict(TypedDict, total=False):
    """The translation example that contains reference sentences from various sources."""

    reference_sentence_pair_lists: Optional[
        list[SchemaPromptSpecReferenceSentencePairListDict]
    ]
    """The reference sentences from inline text."""

    reference_sentences_file_inputs: Optional[
        list[SchemaPromptSpecTranslationSentenceFileInputDict]
    ]
    """The reference sentences from file."""


SchemaPromptSpecTranslationExampleOrDict = Union[
    SchemaPromptSpecTranslationExample, SchemaPromptSpecTranslationExampleDict
]


class SchemaPromptSpecTranslationOption(_common.BaseModel):
    """Optional settings for translation prompt."""

    number_of_shots: Optional[int] = Field(
        default=None, description="""How many shots to use."""
    )


class SchemaPromptSpecTranslationOptionDict(TypedDict, total=False):
    """Optional settings for translation prompt."""

    number_of_shots: Optional[int]
    """How many shots to use."""


SchemaPromptSpecTranslationOptionOrDict = Union[
    SchemaPromptSpecTranslationOption, SchemaPromptSpecTranslationOptionDict
]


class SchemaPromptSpecTranslationPrompt(_common.BaseModel):
    """Prompt variation for Translation use case."""

    example: Optional[SchemaPromptSpecTranslationExample] = Field(
        default=None, description="""The translation example."""
    )
    option: Optional[SchemaPromptSpecTranslationOption] = Field(
        default=None, description="""The translation option."""
    )
    prompt_message: Optional[SchemaPromptSpecPromptMessage] = Field(
        default=None, description="""The prompt message."""
    )
    source_language_code: Optional[str] = Field(
        default=None, description="""The source language code."""
    )
    target_language_code: Optional[str] = Field(
        default=None, description="""The target language code."""
    )


class SchemaPromptSpecTranslationPromptDict(TypedDict, total=False):
    """Prompt variation for Translation use case."""

    example: Optional[SchemaPromptSpecTranslationExampleDict]
    """The translation example."""

    option: Optional[SchemaPromptSpecTranslationOptionDict]
    """The translation option."""

    prompt_message: Optional[SchemaPromptSpecPromptMessageDict]
    """The prompt message."""

    source_language_code: Optional[str]
    """The source language code."""

    target_language_code: Optional[str]
    """The target language code."""


SchemaPromptSpecTranslationPromptOrDict = Union[
    SchemaPromptSpecTranslationPrompt, SchemaPromptSpecTranslationPromptDict
]


class SchemaPromptApiSchema(_common.BaseModel):
    """The A2 schema of a prompt."""

    api_schema_version: Optional[str] = Field(
        default=None,
        description="""The Schema version that represents changes to the API behavior.""",
    )
    executions: Optional[list[SchemaPromptInstancePromptExecution]] = Field(
        default=None,
        description="""A list of execution instances for constructing a ready-to-use prompt.""",
    )
    multimodal_prompt: Optional[SchemaPromptSpecMultimodalPrompt] = Field(
        default=None,
        description="""Multimodal prompt which embeds preambles to prompt string.""",
    )
    structured_prompt: Optional[SchemaPromptSpecStructuredPrompt] = Field(
        default=None,
        description="""The prompt variation that stores preambles in separate fields.""",
    )
    translation_prompt: Optional[SchemaPromptSpecTranslationPrompt] = Field(
        default=None, description="""The prompt variation for Translation use case."""
    )


class SchemaPromptApiSchemaDict(TypedDict, total=False):
    """The A2 schema of a prompt."""

    api_schema_version: Optional[str]
    """The Schema version that represents changes to the API behavior."""

    executions: Optional[list[SchemaPromptInstancePromptExecutionDict]]
    """A list of execution instances for constructing a ready-to-use prompt."""

    multimodal_prompt: Optional[SchemaPromptSpecMultimodalPromptDict]
    """Multimodal prompt which embeds preambles to prompt string."""

    structured_prompt: Optional[SchemaPromptSpecStructuredPromptDict]
    """The prompt variation that stores preambles in separate fields."""

    translation_prompt: Optional[SchemaPromptSpecTranslationPromptDict]
    """The prompt variation for Translation use case."""


SchemaPromptApiSchemaOrDict = Union[SchemaPromptApiSchema, SchemaPromptApiSchemaDict]


class SchemaTextPromptDatasetMetadata(_common.BaseModel):
    """Represents the text prompt dataset metadata."""

    candidate_count: Optional[int] = Field(
        default=None, description="""Number of candidates."""
    )
    gcs_uri: Optional[str] = Field(
        default=None,
        description="""The Google Cloud Storage URI that stores the prompt data.""",
    )
    grounding_config: Optional[SchemaPredictParamsGroundingConfig] = Field(
        default=None, description="""Grounding checking configuration."""
    )
    has_prompt_variable: Optional[bool] = Field(
        default=None, description="""Whether the prompt dataset has prompt variable."""
    )
    logprobs: Optional[bool] = Field(
        default=None,
        description="""Whether or not the user has enabled logit probabilities in the model parameters.""",
    )
    max_output_tokens: Optional[int] = Field(
        default=None,
        description="""Value of the maximum number of tokens generated set when the dataset was saved.""",
    )
    note: Optional[str] = Field(
        default=None,
        description="""User-created prompt note. Note size limit is 2KB.""",
    )
    prompt_api_schema: Optional[SchemaPromptApiSchema] = Field(
        default=None,
        description="""The API schema of the prompt to support both UI and SDK usages.""",
    )
    prompt_type: Optional[str] = Field(
        default=None, description="""Type of the prompt dataset."""
    )
    seed_enabled: Optional[bool] = Field(
        default=None,
        description="""Seeding enables model to return a deterministic response on a best effort basis. Determinism isn't guaranteed. This field determines whether or not seeding is enabled.""",
    )
    seed_value: Optional[int] = Field(
        default=None, description="""The actual value of the seed."""
    )
    stop_sequences: Optional[list[str]] = Field(
        default=None, description="""Customized stop sequences."""
    )
    system_instruction: Optional[str] = Field(
        default=None,
        description="""The content of the prompt dataset system instruction.""",
    )
    system_instruction_gcs_uri: Optional[str] = Field(
        default=None,
        description="""The Google Cloud Storage URI that stores the system instruction, starting with gs://.""",
    )
    temperature: Optional[float] = Field(
        default=None,
        description="""Temperature value used for sampling set when the dataset was saved. This value is used to tune the degree of randomness.""",
    )
    text: Optional[str] = Field(
        default=None, description="""The content of the prompt dataset."""
    )
    top_k: Optional[int] = Field(
        default=None,
        description="""Top K value set when the dataset was saved. This value determines how many candidates with highest probability from the vocab would be selected for each decoding step.""",
    )
    top_p: Optional[float] = Field(
        default=None,
        description="""Top P value set when the dataset was saved. Given topK tokens for decoding, top candidates will be selected until the sum of their probabilities is topP.""",
    )


class SchemaTextPromptDatasetMetadataDict(TypedDict, total=False):
    """Represents the text prompt dataset metadata."""

    candidate_count: Optional[int]
    """Number of candidates."""

    gcs_uri: Optional[str]
    """The Google Cloud Storage URI that stores the prompt data."""

    grounding_config: Optional[SchemaPredictParamsGroundingConfigDict]
    """Grounding checking configuration."""

    has_prompt_variable: Optional[bool]
    """Whether the prompt dataset has prompt variable."""

    logprobs: Optional[bool]
    """Whether or not the user has enabled logit probabilities in the model parameters."""

    max_output_tokens: Optional[int]
    """Value of the maximum number of tokens generated set when the dataset was saved."""

    note: Optional[str]
    """User-created prompt note. Note size limit is 2KB."""

    prompt_api_schema: Optional[SchemaPromptApiSchemaDict]
    """The API schema of the prompt to support both UI and SDK usages."""

    prompt_type: Optional[str]
    """Type of the prompt dataset."""

    seed_enabled: Optional[bool]
    """Seeding enables model to return a deterministic response on a best effort basis. Determinism isn't guaranteed. This field determines whether or not seeding is enabled."""

    seed_value: Optional[int]
    """The actual value of the seed."""

    stop_sequences: Optional[list[str]]
    """Customized stop sequences."""

    system_instruction: Optional[str]
    """The content of the prompt dataset system instruction."""

    system_instruction_gcs_uri: Optional[str]
    """The Google Cloud Storage URI that stores the system instruction, starting with gs://."""

    temperature: Optional[float]
    """Temperature value used for sampling set when the dataset was saved. This value is used to tune the degree of randomness."""

    text: Optional[str]
    """The content of the prompt dataset."""

    top_k: Optional[int]
    """Top K value set when the dataset was saved. This value determines how many candidates with highest probability from the vocab would be selected for each decoding step."""

    top_p: Optional[float]
    """Top P value set when the dataset was saved. Given topK tokens for decoding, top candidates will be selected until the sum of their probabilities is topP."""


SchemaTextPromptDatasetMetadataOrDict = Union[
    SchemaTextPromptDatasetMetadata, SchemaTextPromptDatasetMetadataDict
]


class CreateDatasetConfig(_common.BaseModel):
    """Config for creating a dataset resource to store prompts."""

    http_options: Optional[genai_types.HttpOptions] = Field(
        default=None, description="""Used to override HTTP request options."""
    )


class CreateDatasetConfigDict(TypedDict, total=False):
    """Config for creating a dataset resource to store prompts."""

    http_options: Optional[genai_types.HttpOptionsDict]
    """Used to override HTTP request options."""


CreateDatasetConfigOrDict = Union[CreateDatasetConfig, CreateDatasetConfigDict]


class _CreateDatasetParameters(_common.BaseModel):
    """Parameters for creating a dataset resource to store prompts."""

    name: Optional[str] = Field(default=None, description="""""")
    display_name: Optional[str] = Field(default=None, description="""""")
    metadata_schema_uri: Optional[str] = Field(default=None, description="""""")
    metadata: Optional[SchemaTextPromptDatasetMetadata] = Field(
        default=None, description=""""""
    )
    description: Optional[str] = Field(default=None, description="""""")
    encryption_spec: Optional[genai_types.EncryptionSpec] = Field(
        default=None, description=""""""
    )
    model_reference: Optional[str] = Field(default=None, description="""""")
    config: Optional[CreateDatasetConfig] = Field(default=None, description="""""")


class _CreateDatasetParametersDict(TypedDict, total=False):
    """Parameters for creating a dataset resource to store prompts."""

    name: Optional[str]
    """"""

    display_name: Optional[str]
    """"""

    metadata_schema_uri: Optional[str]
    """"""

    metadata: Optional[SchemaTextPromptDatasetMetadataDict]
    """"""

    description: Optional[str]
    """"""

    encryption_spec: Optional[genai_types.EncryptionSpecDict]
    """"""

    model_reference: Optional[str]
    """"""

    config: Optional[CreateDatasetConfigDict]
    """"""


_CreateDatasetParametersOrDict = Union[
    _CreateDatasetParameters, _CreateDatasetParametersDict
]


class DatasetOperation(_common.BaseModel):
    """Represents the create dataset operation."""

    name: Optional[str] = Field(
        default=None,
        description="""The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`.""",
    )
    metadata: Optional[dict[str, Any]] = Field(
        default=None,
        description="""Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata.  Any method that returns a long-running operation should document the metadata type, if any.""",
    )
    done: Optional[bool] = Field(
        default=None,
        description="""If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available.""",
    )
    error: Optional[dict[str, Any]] = Field(
        default=None,
        description="""The error result of the operation in case of failure or cancellation.""",
    )
    response: Optional[dict[str, Any]] = Field(
        default=None, description="""The result of the dataset operation."""
    )


class DatasetOperationDict(TypedDict, total=False):
    """Represents the create dataset operation."""

    name: Optional[str]
    """The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`."""

    metadata: Optional[dict[str, Any]]
    """Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata.  Any method that returns a long-running operation should document the metadata type, if any."""

    done: Optional[bool]
    """If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available."""

    error: Optional[dict[str, Any]]
    """The error result of the operation in case of failure or cancellation."""

    response: Optional[dict[str, Any]]
    """The result of the dataset operation."""


DatasetOperationOrDict = Union[DatasetOperation, DatasetOperationDict]


class CreateDatasetVersionConfig(_common.BaseModel):
    """Config for creating a dataset version resource to store prompts."""

    http_options: Optional[genai_types.HttpOptions] = Field(
        default=None, description="""Used to override HTTP request options."""
    )


class CreateDatasetVersionConfigDict(TypedDict, total=False):
    """Config for creating a dataset version resource to store prompts."""

    http_options: Optional[genai_types.HttpOptionsDict]
    """Used to override HTTP request options."""


CreateDatasetVersionConfigOrDict = Union[
    CreateDatasetVersionConfig, CreateDatasetVersionConfigDict
]


class _CreateDatasetVersionParameters(_common.BaseModel):
    """Represents the create dataset version parameters."""

    dataset_name: Optional[str] = Field(default=None, description="""""")
    metadata: Optional[SchemaTextPromptDatasetMetadata] = Field(
        default=None, description=""""""
    )
    model_reference: Optional[str] = Field(default=None, description="""""")
    parent: Optional[str] = Field(default=None, description="""""")
    display_name: Optional[str] = Field(default=None, description="""""")
    config: Optional[CreateDatasetVersionConfig] = Field(
        default=None, description=""""""
    )


class _CreateDatasetVersionParametersDict(TypedDict, total=False):
    """Represents the create dataset version parameters."""

    dataset_name: Optional[str]
    """"""

    metadata: Optional[SchemaTextPromptDatasetMetadataDict]
    """"""

    model_reference: Optional[str]
    """"""

    parent: Optional[str]
    """"""

    display_name: Optional[str]
    """"""

    config: Optional[CreateDatasetVersionConfigDict]
    """"""


_CreateDatasetVersionParametersOrDict = Union[
    _CreateDatasetVersionParameters, _CreateDatasetVersionParametersDict
]


class _GetDatasetParameters(_common.BaseModel):
    """Parameters for getting a dataset resource to store prompts."""

    name: Optional[str] = Field(default=None, description="""""")
    config: Optional[VertexBaseConfig] = Field(default=None, description="""""")


class _GetDatasetParametersDict(TypedDict, total=False):
    """Parameters for getting a dataset resource to store prompts."""

    name: Optional[str]
    """"""

    config: Optional[VertexBaseConfigDict]
    """"""


_GetDatasetParametersOrDict = Union[_GetDatasetParameters, _GetDatasetParametersDict]


class SavedQuery(_common.BaseModel):
    """A SavedQuery is a view of the dataset. It references a subset of annotations by problem type and filters."""

    annotation_filter: Optional[str] = Field(
        default=None,
        description="""Output only. Filters on the Annotations in the dataset.""",
    )
    annotation_spec_count: Optional[int] = Field(
        default=None,
        description="""Output only. Number of AnnotationSpecs in the context of the SavedQuery.""",
    )
    create_time: Optional[datetime.datetime] = Field(
        default=None,
        description="""Output only. Timestamp when this SavedQuery was created.""",
    )
    display_name: Optional[str] = Field(
        default=None,
        description="""Required. The user-defined name of the SavedQuery. The name can be up to 128 characters long and can consist of any UTF-8 characters.""",
    )
    etag: Optional[str] = Field(
        default=None,
        description="""Used to perform a consistent read-modify-write update. If not set, a blind "overwrite" update happens.""",
    )
    metadata: Optional[Any] = Field(
        default=None,
        description="""Some additional information about the SavedQuery.""",
    )
    name: Optional[str] = Field(
        default=None, description="""Output only. Resource name of the SavedQuery."""
    )
    problem_type: Optional[str] = Field(
        default=None,
        description="""Required. Problem type of the SavedQuery. Allowed values: * IMAGE_CLASSIFICATION_SINGLE_LABEL * IMAGE_CLASSIFICATION_MULTI_LABEL * IMAGE_BOUNDING_POLY * IMAGE_BOUNDING_BOX * TEXT_CLASSIFICATION_SINGLE_LABEL * TEXT_CLASSIFICATION_MULTI_LABEL * TEXT_EXTRACTION * TEXT_SENTIMENT * VIDEO_CLASSIFICATION * VIDEO_OBJECT_TRACKING""",
    )
    support_automl_training: Optional[bool] = Field(
        default=None,
        description="""Output only. If the Annotations belonging to the SavedQuery can be used for AutoML training.""",
    )
    update_time: Optional[datetime.datetime] = Field(
        default=None,
        description="""Output only. Timestamp when SavedQuery was last updated.""",
    )


class SavedQueryDict(TypedDict, total=False):
    """A SavedQuery is a view of the dataset. It references a subset of annotations by problem type and filters."""

    annotation_filter: Optional[str]
    """Output only. Filters on the Annotations in the dataset."""

    annotation_spec_count: Optional[int]
    """Output only. Number of AnnotationSpecs in the context of the SavedQuery."""

    create_time: Optional[datetime.datetime]
    """Output only. Timestamp when this SavedQuery was created."""

    display_name: Optional[str]
    """Required. The user-defined name of the SavedQuery. The name can be up to 128 characters long and can consist of any UTF-8 characters."""

    etag: Optional[str]
    """Used to perform a consistent read-modify-write update. If not set, a blind "overwrite" update happens."""

    metadata: Optional[Any]
    """Some additional information about the SavedQuery."""

    name: Optional[str]
    """Output only. Resource name of the SavedQuery."""

    problem_type: Optional[str]
    """Required. Problem type of the SavedQuery. Allowed values: * IMAGE_CLASSIFICATION_SINGLE_LABEL * IMAGE_CLASSIFICATION_MULTI_LABEL * IMAGE_BOUNDING_POLY * IMAGE_BOUNDING_BOX * TEXT_CLASSIFICATION_SINGLE_LABEL * TEXT_CLASSIFICATION_MULTI_LABEL * TEXT_EXTRACTION * TEXT_SENTIMENT * VIDEO_CLASSIFICATION * VIDEO_OBJECT_TRACKING"""

    support_automl_training: Optional[bool]
    """Output only. If the Annotations belonging to the SavedQuery can be used for AutoML training."""

    update_time: Optional[datetime.datetime]
    """Output only. Timestamp when SavedQuery was last updated."""


SavedQueryOrDict = Union[SavedQuery, SavedQueryDict]


class Dataset(_common.BaseModel):
    """Represents a dataset resource to store prompts."""

    metadata: Optional[SchemaTextPromptDatasetMetadata] = Field(
        default=None,
        description="""Required. Additional information about the Dataset.""",
    )
    encryption_spec: Optional[genai_types.EncryptionSpec] = Field(
        default=None,
        description="""Customer-managed encryption key spec for a Dataset. If set, this Dataset and all sub-resources of this Dataset will be secured by this key.""",
    )
    create_time: Optional[datetime.datetime] = Field(
        default=None,
        description="""Output only. Timestamp when this Dataset was created.""",
    )
    data_item_count: Optional[int] = Field(
        default=None,
        description="""Output only. The number of DataItems in this Dataset. Only apply for non-structured Dataset.""",
    )
    description: Optional[str] = Field(
        default=None, description="""The description of the Dataset."""
    )
    display_name: Optional[str] = Field(
        default=None,
        description="""Required. The user-defined name of the Dataset. The name can be up to 128 characters long and can consist of any UTF-8 characters.""",
    )
    etag: Optional[str] = Field(
        default=None,
        description="""Used to perform consistent read-modify-write updates. If not set, a blind "overwrite" update happens.""",
    )
    labels: Optional[dict[str, str]] = Field(
        default=None,
        description="""The labels with user-defined metadata to organize your Datasets. Label keys and values can be no longer than 64 characters (Unicode codepoints), can only contain lowercase letters, numeric characters, underscores and dashes. International characters are allowed. No more than 64 user labels can be associated with one Dataset (System labels are excluded). See https://goo.gl/xmQnxf for more information and examples of labels. System reserved label keys are prefixed with "aiplatform.googleapis.com/" and are immutable. Following system labels exist for each Dataset: * "aiplatform.googleapis.com/dataset_metadata_schema": output only, its value is the metadata_schema's title.""",
    )
    metadata_artifact: Optional[str] = Field(
        default=None,
        description="""Output only. The resource name of the Artifact that was created in MetadataStore when creating the Dataset. The Artifact resource name pattern is `projects/{project}/locations/{location}/metadataStores/{metadata_store}/artifacts/{artifact}`.""",
    )
    metadata_schema_uri: Optional[str] = Field(
        default=None,
        description="""Required. Points to a YAML file stored on Google Cloud Storage describing additional information about the Dataset. The schema is defined as an OpenAPI 3.0.2 Schema Object. The schema files that can be used here are found in gs://google-cloud-aiplatform/schema/dataset/metadata/.""",
    )
    model_reference: Optional[str] = Field(
        default=None,
        description="""Optional. Reference to the public base model last used by the dataset. Only set for prompt datasets.""",
    )
    name: Optional[str] = Field(
        default=None,
        description="""Output only. Identifier. The resource name of the Dataset. Format: `projects/{project}/locations/{location}/datasets/{dataset}`""",
    )
    satisfies_pzi: Optional[bool] = Field(
        default=None, description="""Output only. Reserved for future use."""
    )
    satisfies_pzs: Optional[bool] = Field(
        default=None, description="""Output only. Reserved for future use."""
    )
    saved_queries: Optional[list[SavedQuery]] = Field(
        default=None,
        description="""All SavedQueries belong to the Dataset will be returned in List/Get Dataset response. The annotation_specs field will not be populated except for UI cases which will only use annotation_spec_count. In CreateDataset request, a SavedQuery is created together if this field is set, up to one SavedQuery can be set in CreateDatasetRequest. The SavedQuery should not contain any AnnotationSpec.""",
    )
    update_time: Optional[datetime.datetime] = Field(
        default=None,
        description="""Output only. Timestamp when this Dataset was last updated.""",
    )

    # TODO(b/448806531): Remove all the overridden _from_response methods once the
    # ticket is resolved and published.
    @classmethod
    def _from_response(
        cls: typing.Type["Dataset"],
        *,
        response: dict[str, object],
        kwargs: dict[str, object],
    ) -> "Dataset":
        """Converts a dictionary response into a Dataset object."""

        response = _camel_key_to_snake(response)
        result = super()._from_response(response=response, kwargs=kwargs)
        return result


class DatasetDict(TypedDict, total=False):
    """Represents a dataset resource to store prompts."""

    metadata: Optional[SchemaTextPromptDatasetMetadataDict]
    """Required. Additional information about the Dataset."""

    encryption_spec: Optional[genai_types.EncryptionSpecDict]
    """Customer-managed encryption key spec for a Dataset. If set, this Dataset and all sub-resources of this Dataset will be secured by this key."""

    create_time: Optional[datetime.datetime]
    """Output only. Timestamp when this Dataset was created."""

    data_item_count: Optional[int]
    """Output only. The number of DataItems in this Dataset. Only apply for non-structured Dataset."""

    description: Optional[str]
    """The description of the Dataset."""

    display_name: Optional[str]
    """Required. The user-defined name of the Dataset. The name can be up to 128 characters long and can consist of any UTF-8 characters."""

    etag: Optional[str]
    """Used to perform consistent read-modify-write updates. If not set, a blind "overwrite" update happens."""

    labels: Optional[dict[str, str]]
    """The labels with user-defined metadata to organize your Datasets. Label keys and values can be no longer than 64 characters (Unicode codepoints), can only contain lowercase letters, numeric characters, underscores and dashes. International characters are allowed. No more than 64 user labels can be associated with one Dataset (System labels are excluded). See https://goo.gl/xmQnxf for more information and examples of labels. System reserved label keys are prefixed with "aiplatform.googleapis.com/" and are immutable. Following system labels exist for each Dataset: * "aiplatform.googleapis.com/dataset_metadata_schema": output only, its value is the metadata_schema's title."""

    metadata_artifact: Optional[str]
    """Output only. The resource name of the Artifact that was created in MetadataStore when creating the Dataset. The Artifact resource name pattern is `projects/{project}/locations/{location}/metadataStores/{metadata_store}/artifacts/{artifact}`."""

    metadata_schema_uri: Optional[str]
    """Required. Points to a YAML file stored on Google Cloud Storage describing additional information about the Dataset. The schema is defined as an OpenAPI 3.0.2 Schema Object. The schema files that can be used here are found in gs://google-cloud-aiplatform/schema/dataset/metadata/."""

    model_reference: Optional[str]
    """Optional. Reference to the public base model last used by the dataset. Only set for prompt datasets."""

    name: Optional[str]
    """Output only. Identifier. The resource name of the Dataset. Format: `projects/{project}/locations/{location}/datasets/{dataset}`"""

    satisfies_pzi: Optional[bool]
    """Output only. Reserved for future use."""

    satisfies_pzs: Optional[bool]
    """Output only. Reserved for future use."""

    saved_queries: Optional[list[SavedQueryDict]]
    """All SavedQueries belong to the Dataset will be returned in List/Get Dataset response. The annotation_specs field will not be populated except for UI cases which will only use annotation_spec_count. In CreateDataset request, a SavedQuery is created together if this field is set, up to one SavedQuery can be set in CreateDatasetRequest. The SavedQuery should not contain any AnnotationSpec."""

    update_time: Optional[datetime.datetime]
    """Output only. Timestamp when this Dataset was last updated."""


DatasetOrDict = Union[Dataset, DatasetDict]


class _GetDatasetVersionParameters(_common.BaseModel):
    """Parameters for getting a dataset resource to store prompts."""

    dataset_id: Optional[str] = Field(default=None, description="""""")
    dataset_version_id: Optional[str] = Field(default=None, description="""""")
    config: Optional[VertexBaseConfig] = Field(default=None, description="""""")


class _GetDatasetVersionParametersDict(TypedDict, total=False):
    """Parameters for getting a dataset resource to store prompts."""

    dataset_id: Optional[str]
    """"""

    dataset_version_id: Optional[str]
    """"""

    config: Optional[VertexBaseConfigDict]
    """"""


_GetDatasetVersionParametersOrDict = Union[
    _GetDatasetVersionParameters, _GetDatasetVersionParametersDict
]


class DatasetVersion(_common.BaseModel):
    """Represents a dataset version resource to store prompts."""

    metadata: Optional[SchemaTextPromptDatasetMetadata] = Field(
        default=None,
        description="""Required. Output only. Additional information about the DatasetVersion.""",
    )
    big_query_dataset_name: Optional[str] = Field(
        default=None,
        description="""Output only. Name of the associated BigQuery dataset.""",
    )
    create_time: Optional[datetime.datetime] = Field(
        default=None,
        description="""Output only. Timestamp when this DatasetVersion was created.""",
    )
    display_name: Optional[str] = Field(
        default=None,
        description="""The user-defined name of the DatasetVersion. The name can be up to 128 characters long and can consist of any UTF-8 characters.""",
    )
    etag: Optional[str] = Field(
        default=None,
        description="""Used to perform consistent read-modify-write updates. If not set, a blind "overwrite" update happens.""",
    )
    model_reference: Optional[str] = Field(
        default=None,
        description="""Output only. Reference to the public base model last used by the dataset version. Only set for prompt dataset versions.""",
    )
    name: Optional[str] = Field(
        default=None,
        description="""Output only. Identifier. The resource name of the DatasetVersion. Format: `projects/{project}/locations/{location}/datasets/{dataset}/datasetVersions/{dataset_version}`""",
    )
    satisfies_pzi: Optional[bool] = Field(
        default=None, description="""Output only. Reserved for future use."""
    )
    satisfies_pzs: Optional[bool] = Field(
        default=None, description="""Output only. Reserved for future use."""
    )
    update_time: Optional[datetime.datetime] = Field(
        default=None,
        description="""Output only. Timestamp when this DatasetVersion was last updated.""",
    )

    # TODO(b/448806531): Remove all the overridden _from_response methods once the
    # ticket is resolved and published.
    @classmethod
    def _from_response(
        cls: typing.Type["DatasetVersion"],
        *,
        response: dict[str, object],
        kwargs: dict[str, object],
    ) -> "DatasetVersion":
        """Converts a dictionary response into a DatasetVersion object."""

        response = _camel_key_to_snake(response)
        result = super()._from_response(response=response, kwargs=kwargs)
        return result


class DatasetVersionDict(TypedDict, total=False):
    """Represents a dataset version resource to store prompts."""

    metadata: Optional[SchemaTextPromptDatasetMetadataDict]
    """Required. Output only. Additional information about the DatasetVersion."""

    big_query_dataset_name: Optional[str]
    """Output only. Name of the associated BigQuery dataset."""

    create_time: Optional[datetime.datetime]
    """Output only. Timestamp when this DatasetVersion was created."""

    display_name: Optional[str]
    """The user-defined name of the DatasetVersion. The name can be up to 128 characters long and can consist of any UTF-8 characters."""

    etag: Optional[str]
    """Used to perform consistent read-modify-write updates. If not set, a blind "overwrite" update happens."""

    model_reference: Optional[str]
    """Output only. Reference to the public base model last used by the dataset version. Only set for prompt dataset versions."""

    name: Optional[str]
    """Output only. Identifier. The resource name of the DatasetVersion. Format: `projects/{project}/locations/{location}/datasets/{dataset}/datasetVersions/{dataset_version}`"""

    satisfies_pzi: Optional[bool]
    """Output only. Reserved for future use."""

    satisfies_pzs: Optional[bool]
    """Output only. Reserved for future use."""

    update_time: Optional[datetime.datetime]
    """Output only. Timestamp when this DatasetVersion was last updated."""


DatasetVersionOrDict = Union[DatasetVersion, DatasetVersionDict]


class GetDatasetOperationConfig(_common.BaseModel):
    """Config for getting a dataset version operation."""

    http_options: Optional[genai_types.HttpOptions] = Field(
        default=None, description="""Used to override HTTP request options."""
    )


class GetDatasetOperationConfigDict(TypedDict, total=False):
    """Config for getting a dataset version operation."""

    http_options: Optional[genai_types.HttpOptionsDict]
    """Used to override HTTP request options."""


GetDatasetOperationConfigOrDict = Union[
    GetDatasetOperationConfig, GetDatasetOperationConfigDict
]


class _GetDatasetOperationParameters(_common.BaseModel):
    """Parameters for getting a dataset operation."""

    dataset_id: Optional[str] = Field(default=None, description="""""")
    operation_id: Optional[str] = Field(default=None, description="""""")
    config: Optional[GetDatasetOperationConfig] = Field(
        default=None, description=""""""
    )


class _GetDatasetOperationParametersDict(TypedDict, total=False):
    """Parameters for getting a dataset operation."""

    dataset_id: Optional[str]
    """"""

    operation_id: Optional[str]
    """"""

    config: Optional[GetDatasetOperationConfigDict]
    """"""


_GetDatasetOperationParametersOrDict = Union[
    _GetDatasetOperationParameters, _GetDatasetOperationParametersDict
]


class ListPromptsConfig(_common.BaseModel):
    """Config for listing prompt datasets and dataset versions."""

    http_options: Optional[genai_types.HttpOptions] = Field(
        default=None, description="""Used to override HTTP request options."""
    )
    page_size: Optional[int] = Field(default=None, description="""""")
    page_token: Optional[str] = Field(default=None, description="""""")
    filter: Optional[str] = Field(
        default=None,
        description="""An expression for filtering the results of the request.
      For field names both snake_case and camelCase are supported.""",
    )


class ListPromptsConfigDict(TypedDict, total=False):
    """Config for listing prompt datasets and dataset versions."""

    http_options: Optional[genai_types.HttpOptionsDict]
    """Used to override HTTP request options."""

    page_size: Optional[int]
    """"""

    page_token: Optional[str]
    """"""

    filter: Optional[str]
    """An expression for filtering the results of the request.
      For field names both snake_case and camelCase are supported."""


ListPromptsConfigOrDict = Union[ListPromptsConfig, ListPromptsConfigDict]


class _ListDatasetsRequestParameters(_common.BaseModel):
    """Parameters for listing prompt datasets."""

    config: Optional[ListPromptsConfig] = Field(default=None, description="""""")


class _ListDatasetsRequestParametersDict(TypedDict, total=False):
    """Parameters for listing prompt datasets."""

    config: Optional[ListPromptsConfigDict]
    """"""


_ListDatasetsRequestParametersOrDict = Union[
    _ListDatasetsRequestParameters, _ListDatasetsRequestParametersDict
]


class ListDatasetsResponse(_common.BaseModel):
    """Response for listing prompt datasets."""

    sdk_http_response: Optional[genai_types.HttpResponse] = Field(
        default=None, description="""Used to retain the full HTTP response."""
    )
    next_page_token: Optional[str] = Field(default=None, description="""""")
    datasets: Optional[list[Dataset]] = Field(
        default=None,
        description="""List of datasets for the project.
      """,
    )

    # TODO(b/448806531): Remove all the overridden _from_response methods once the
    # ticket is resolved and published.
    @classmethod
    def _from_response(
        cls: typing.Type["ListDatasetsResponse"],
        *,
        response: dict[str, object],
        kwargs: dict[str, object],
    ) -> "ListDatasetsResponse":
        """Converts a dictionary response into a ListDatasetsResponse object."""

        response = _camel_key_to_snake(response)
        result = super()._from_response(response=response, kwargs=kwargs)
        return result


class ListDatasetsResponseDict(TypedDict, total=False):
    """Response for listing prompt datasets."""

    sdk_http_response: Optional[genai_types.HttpResponseDict]
    """Used to retain the full HTTP response."""

    next_page_token: Optional[str]
    """"""

    datasets: Optional[list[DatasetDict]]
    """List of datasets for the project.
      """


ListDatasetsResponseOrDict = Union[ListDatasetsResponse, ListDatasetsResponseDict]


class _ListDatasetVersionsRequestParameters(_common.BaseModel):
    """Parameters for listing dataset versions."""

    read_mask: Optional[str] = Field(default=None, description="""""")
    dataset_id: Optional[str] = Field(default=None, description="""""")
    config: Optional[ListPromptsConfig] = Field(default=None, description="""""")


class _ListDatasetVersionsRequestParametersDict(TypedDict, total=False):
    """Parameters for listing dataset versions."""

    read_mask: Optional[str]
    """"""

    dataset_id: Optional[str]
    """"""

    config: Optional[ListPromptsConfigDict]
    """"""


_ListDatasetVersionsRequestParametersOrDict = Union[
    _ListDatasetVersionsRequestParameters, _ListDatasetVersionsRequestParametersDict
]


class ListDatasetVersionsResponse(_common.BaseModel):
    """Response for listing prompt datasets."""

    sdk_http_response: Optional[genai_types.HttpResponse] = Field(
        default=None, description="""Used to retain the full HTTP response."""
    )
    next_page_token: Optional[str] = Field(default=None, description="""""")
    dataset_versions: Optional[list[DatasetVersion]] = Field(
        default=None,
        description="""List of datasets for the project.
      """,
    )

    # TODO(b/448806531): Remove all the overridden _from_response methods once the
    # ticket is resolved and published.
    @classmethod
    def _from_response(
        cls: typing.Type["ListDatasetVersionsResponse"],
        *,
        response: dict[str, object],
        kwargs: dict[str, object],
    ) -> "ListDatasetVersionsResponse":
        """Converts a dictionary response into a ListDatasetVersionsResponse object."""

        response = _camel_key_to_snake(response)
        result = super()._from_response(response=response, kwargs=kwargs)
        return result


class ListDatasetVersionsResponseDict(TypedDict, total=False):
    """Response for listing prompt datasets."""

    sdk_http_response: Optional[genai_types.HttpResponseDict]
    """Used to retain the full HTTP response."""

    next_page_token: Optional[str]
    """"""

    dataset_versions: Optional[list[DatasetVersionDict]]
    """List of datasets for the project.
      """


ListDatasetVersionsResponseOrDict = Union[
    ListDatasetVersionsResponse, ListDatasetVersionsResponseDict
]


class DeletePromptConfig(_common.BaseModel):
    """Config for deleting a prompt."""

    http_options: Optional[genai_types.HttpOptions] = Field(
        default=None, description="""Used to override HTTP request options."""
    )
    timeout: Optional[int] = Field(
        default=90,
        description="""Timeout for the delete prompt operation in seconds. Defaults to 90.""",
    )


class DeletePromptConfigDict(TypedDict, total=False):
    """Config for deleting a prompt."""

    http_options: Optional[genai_types.HttpOptionsDict]
    """Used to override HTTP request options."""

    timeout: Optional[int]
    """Timeout for the delete prompt operation in seconds. Defaults to 90."""


DeletePromptConfigOrDict = Union[DeletePromptConfig, DeletePromptConfigDict]


class _DeleteDatasetRequestParameters(_common.BaseModel):
    """Parameters for deleting a prompt dataset."""

    prompt_id: Optional[str] = Field(
        default=None, description="""ID of the prompt dataset to be deleted."""
    )
    config: Optional[DeletePromptConfig] = Field(default=None, description="""""")


class _DeleteDatasetRequestParametersDict(TypedDict, total=False):
    """Parameters for deleting a prompt dataset."""

    prompt_id: Optional[str]
    """ID of the prompt dataset to be deleted."""

    config: Optional[DeletePromptConfigDict]
    """"""


_DeleteDatasetRequestParametersOrDict = Union[
    _DeleteDatasetRequestParameters, _DeleteDatasetRequestParametersDict
]


class DeletePromptOperation(_common.BaseModel):
    """Operation for deleting prompts."""

    name: Optional[str] = Field(
        default=None,
        description="""The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`.""",
    )
    metadata: Optional[dict[str, Any]] = Field(
        default=None,
        description="""Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata.  Any method that returns a long-running operation should document the metadata type, if any.""",
    )
    done: Optional[bool] = Field(
        default=None,
        description="""If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available.""",
    )
    error: Optional[dict[str, Any]] = Field(
        default=None,
        description="""The error result of the operation in case of failure or cancellation.""",
    )


class DeletePromptOperationDict(TypedDict, total=False):
    """Operation for deleting prompts."""

    name: Optional[str]
    """The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`."""

    metadata: Optional[dict[str, Any]]
    """Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata.  Any method that returns a long-running operation should document the metadata type, if any."""

    done: Optional[bool]
    """If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available."""

    error: Optional[dict[str, Any]]
    """The error result of the operation in case of failure or cancellation."""


DeletePromptOperationOrDict = Union[DeletePromptOperation, DeletePromptOperationDict]


class _DeletePromptVersionRequestParameters(_common.BaseModel):
    """Parameters for deleting a prompt version."""

    prompt_id: Optional[str] = Field(
        default=None, description="""ID of the prompt to be deleted."""
    )
    version_id: Optional[str] = Field(
        default=None,
        description="""ID of the prompt version to be deleted within the provided prompt_id.""",
    )
    config: Optional[DeletePromptConfig] = Field(default=None, description="""""")


class _DeletePromptVersionRequestParametersDict(TypedDict, total=False):
    """Parameters for deleting a prompt version."""

    prompt_id: Optional[str]
    """ID of the prompt to be deleted."""

    version_id: Optional[str]
    """ID of the prompt version to be deleted within the provided prompt_id."""

    config: Optional[DeletePromptConfigDict]
    """"""


_DeletePromptVersionRequestParametersOrDict = Union[
    _DeletePromptVersionRequestParameters, _DeletePromptVersionRequestParametersDict
]


class DeletePromptVersionOperation(_common.BaseModel):
    """Operation for deleting prompt versions."""

    name: Optional[str] = Field(
        default=None,
        description="""The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`.""",
    )
    metadata: Optional[dict[str, Any]] = Field(
        default=None,
        description="""Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata.  Any method that returns a long-running operation should document the metadata type, if any.""",
    )
    done: Optional[bool] = Field(
        default=None,
        description="""If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available.""",
    )
    error: Optional[dict[str, Any]] = Field(
        default=None,
        description="""The error result of the operation in case of failure or cancellation.""",
    )


class DeletePromptVersionOperationDict(TypedDict, total=False):
    """Operation for deleting prompt versions."""

    name: Optional[str]
    """The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`."""

    metadata: Optional[dict[str, Any]]
    """Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata.  Any method that returns a long-running operation should document the metadata type, if any."""

    done: Optional[bool]
    """If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available."""

    error: Optional[dict[str, Any]]
    """The error result of the operation in case of failure or cancellation."""


DeletePromptVersionOperationOrDict = Union[
    DeletePromptVersionOperation, DeletePromptVersionOperationDict
]


class RestoreVersionConfig(_common.BaseModel):
    """Config for restoring a prompt version."""

    http_options: Optional[genai_types.HttpOptions] = Field(
        default=None, description="""Used to override HTTP request options."""
    )


class RestoreVersionConfigDict(TypedDict, total=False):
    """Config for restoring a prompt version."""

    http_options: Optional[genai_types.HttpOptionsDict]
    """Used to override HTTP request options."""


RestoreVersionConfigOrDict = Union[RestoreVersionConfig, RestoreVersionConfigDict]


class _RestoreVersionRequestParameters(_common.BaseModel):
    """Parameters for restoring a prompt version."""

    dataset_id: Optional[str] = Field(
        default=None, description="""ID of the prompt dataset to be restored."""
    )
    version_id: Optional[str] = Field(
        default=None, description="""ID of the prompt dataset version to be restored."""
    )
    config: Optional[RestoreVersionConfig] = Field(default=None, description="""""")


class _RestoreVersionRequestParametersDict(TypedDict, total=False):
    """Parameters for restoring a prompt version."""

    dataset_id: Optional[str]
    """ID of the prompt dataset to be restored."""

    version_id: Optional[str]
    """ID of the prompt dataset version to be restored."""

    config: Optional[RestoreVersionConfigDict]
    """"""


_RestoreVersionRequestParametersOrDict = Union[
    _RestoreVersionRequestParameters, _RestoreVersionRequestParametersDict
]


class RestoreVersionOperation(_common.BaseModel):
    """Represents the restore version operation."""

    name: Optional[str] = Field(
        default=None,
        description="""The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`.""",
    )
    metadata: Optional[dict[str, Any]] = Field(
        default=None,
        description="""Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata.  Any method that returns a long-running operation should document the metadata type, if any.""",
    )
    done: Optional[bool] = Field(
        default=None,
        description="""If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available.""",
    )
    error: Optional[dict[str, Any]] = Field(
        default=None,
        description="""The error result of the operation in case of failure or cancellation.""",
    )


class RestoreVersionOperationDict(TypedDict, total=False):
    """Represents the restore version operation."""

    name: Optional[str]
    """The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`."""

    metadata: Optional[dict[str, Any]]
    """Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata.  Any method that returns a long-running operation should document the metadata type, if any."""

    done: Optional[bool]
    """If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available."""

    error: Optional[dict[str, Any]]
    """The error result of the operation in case of failure or cancellation."""


RestoreVersionOperationOrDict = Union[
    RestoreVersionOperation, RestoreVersionOperationDict
]


class UpdateDatasetConfig(_common.BaseModel):
    """Config for creating a dataset resource to store prompts."""

    http_options: Optional[genai_types.HttpOptions] = Field(
        default=None, description="""Used to override HTTP request options."""
    )


class UpdateDatasetConfigDict(TypedDict, total=False):
    """Config for creating a dataset resource to store prompts."""

    http_options: Optional[genai_types.HttpOptionsDict]
    """Used to override HTTP request options."""


UpdateDatasetConfigOrDict = Union[UpdateDatasetConfig, UpdateDatasetConfigDict]


class _UpdateDatasetParameters(_common.BaseModel):
    """Parameters for creating a dataset resource to store prompts."""

    name: Optional[str] = Field(default=None, description="""""")
    dataset_id: Optional[str] = Field(default=None, description="""""")
    display_name: Optional[str] = Field(default=None, description="""""")
    metadata: Optional[SchemaTextPromptDatasetMetadata] = Field(
        default=None, description=""""""
    )
    description: Optional[str] = Field(default=None, description="""""")
    encryption_spec: Optional[genai_types.EncryptionSpec] = Field(
        default=None, description=""""""
    )
    model_reference: Optional[str] = Field(default=None, description="""""")
    config: Optional[UpdateDatasetConfig] = Field(default=None, description="""""")


class _UpdateDatasetParametersDict(TypedDict, total=False):
    """Parameters for creating a dataset resource to store prompts."""

    name: Optional[str]
    """"""

    dataset_id: Optional[str]
    """"""

    display_name: Optional[str]
    """"""

    metadata: Optional[SchemaTextPromptDatasetMetadataDict]
    """"""

    description: Optional[str]
    """"""

    encryption_spec: Optional[genai_types.EncryptionSpecDict]
    """"""

    model_reference: Optional[str]
    """"""

    config: Optional[UpdateDatasetConfigDict]
    """"""


_UpdateDatasetParametersOrDict = Union[
    _UpdateDatasetParameters, _UpdateDatasetParametersDict
]


class PromptOptimizerConfig(_common.BaseModel):
    """VAPO Prompt Optimizer Config."""

    config_path: Optional[str] = Field(
        default=None,
        description="""The gcs path to the config file, e.g. gs://bucket/config.json.""",
    )
    service_account: Optional[str] = Field(
        default=None,
        description="""The service account to use for the custom job. Cannot be provided at the same time as service_account_project_number.""",
    )
    service_account_project_number: Optional[Union[int, str]] = Field(
        default=None,
        description="""The project number used to construct the default service account:{service_account_project_number}-compute@developer.gserviceaccount.comCannot be provided at the same time as "service_account".""",
    )
    wait_for_completion: Optional[bool] = Field(
        default=True,
        description="""Whether to wait for the job tocomplete. Ignored for async jobs.""",
    )
    optimizer_job_display_name: Optional[str] = Field(
        default=None,
        description="""The display name of the optimization job. If not provided, a display name in the format of "vapo-optimizer-{timestamp}" will be used.""",
    )


class PromptOptimizerConfigDict(TypedDict, total=False):
    """VAPO Prompt Optimizer Config."""

    config_path: Optional[str]
    """The gcs path to the config file, e.g. gs://bucket/config.json."""

    service_account: Optional[str]
    """The service account to use for the custom job. Cannot be provided at the same time as service_account_project_number."""

    service_account_project_number: Optional[Union[int, str]]
    """The project number used to construct the default service account:{service_account_project_number}-compute@developer.gserviceaccount.comCannot be provided at the same time as "service_account"."""

    wait_for_completion: Optional[bool]
    """Whether to wait for the job tocomplete. Ignored for async jobs."""

    optimizer_job_display_name: Optional[str]
    """The display name of the optimization job. If not provided, a display name in the format of "vapo-optimizer-{timestamp}" will be used."""


PromptOptimizerConfigOrDict = Union[PromptOptimizerConfig, PromptOptimizerConfigDict]


class ApplicableGuideline(_common.BaseModel):
    """Applicable guideline for the optimize_prompt method."""

    applicable_guideline: Optional[str] = Field(default=None, description="""""")
    suggested_improvement: Optional[str] = Field(default=None, description="""""")
    text_before_change: Optional[str] = Field(default=None, description="""""")
    text_after_change: Optional[str] = Field(default=None, description="""""")


class ApplicableGuidelineDict(TypedDict, total=False):
    """Applicable guideline for the optimize_prompt method."""

    applicable_guideline: Optional[str]
    """"""

    suggested_improvement: Optional[str]
    """"""

    text_before_change: Optional[str]
    """"""

    text_after_change: Optional[str]
    """"""


ApplicableGuidelineOrDict = Union[ApplicableGuideline, ApplicableGuidelineDict]


class ParsedResponse(_common.BaseModel):
    """Response for the optimize_prompt method."""

    optimization_type: Optional[str] = Field(default=None, description="""""")
    applicable_guidelines: Optional[list[ApplicableGuideline]] = Field(
        default=None, description=""""""
    )
    original_prompt: Optional[str] = Field(default=None, description="""""")
    suggested_prompt: Optional[str] = Field(default=None, description="""""")


class ParsedResponseDict(TypedDict, total=False):
    """Response for the optimize_prompt method."""

    optimization_type: Optional[str]
    """"""

    applicable_guidelines: Optional[list[ApplicableGuidelineDict]]
    """"""

    original_prompt: Optional[str]
    """"""

    suggested_prompt: Optional[str]
    """"""


ParsedResponseOrDict = Union[ParsedResponse, ParsedResponseDict]


class OptimizeResponse(_common.BaseModel):
    """Response for the optimize_prompt method."""

    raw_text_response: Optional[str] = Field(default=None, description="""""")
    parsed_response: Optional[ParsedResponse] = Field(default=None, description="""""")


class OptimizeResponseDict(TypedDict, total=False):
    """Response for the optimize_prompt method."""

    raw_text_response: Optional[str]
    """"""

    parsed_response: Optional[ParsedResponseDict]
    """"""


OptimizeResponseOrDict = Union[OptimizeResponse, OptimizeResponseDict]


class PromptTemplate(_common.BaseModel):
    """A prompt template for creating prompts with variables."""

    text: Optional[str] = Field(
        default=None, description="""The prompt template text."""
    )
    _VARIABLE_NAME_REGEX: ClassVar[str] = r"\{([_a-zA-Z][_a-zA-Z0-9]*)\}"

    @field_validator("text")
    @classmethod
    def text_must_not_be_empty(cls, value: str) -> str:
        if not value.strip():
            raise ValueError(
                "Prompt template text cannot be empty or consist only of" " whitespace."
            )
        return value

    @computed_field  # type: ignore[prop-decorator]
    @property
    def variables(self) -> set[str]:
        return set(re.findall(self._VARIABLE_NAME_REGEX, self.text))

    def _split_template_by_variables(self) -> list[Tuple[str, str]]:
        parts = []
        last_end = 0
        for match in re.finditer(self._VARIABLE_NAME_REGEX, self.text):
            start, end = match.span()
            var_name = match.group(1)
            if start > last_end and self.text:
                parts.append(("text", self.text[last_end:start]))
            parts.append(("var", var_name))
            last_end = end
        if last_end < len(self.text) and self.text:
            parts.append(("text", self.text[last_end:]))
        return parts

    def _merge_adjacent_text_parts(
        self, parts: list[genai_types.Part]
    ) -> list[genai_types.Part]:
        if not parts:
            return []

        merged = []
        current_text_buffer = []

        for part in parts:
            is_purely_text = part.text is not None and all(
                getattr(part, field) is None
                for field in part.model_fields
                if field != "text"
            )

            if is_purely_text:
                current_text_buffer.append(part.text)
            else:
                if current_text_buffer:
                    merged.append(genai_types.Part(text="".join(current_text_buffer)))
                    current_text_buffer = []
                merged.append(part)

        if current_text_buffer:
            merged.append(genai_types.Part(text="".join(current_text_buffer)))

        return merged

    def _is_multimodal_json_string(
        self,
        value: Any,
    ) -> bool:
        """Checks if the input value is a multimodal JSON string."""
        if not isinstance(value, str):
            return False
        try:
            data = json.loads(value)
            # Check for the specific structure: {"contents": [{"parts": [...]}]}
            # or {"parts": [...]} if assemble returns a single Content JSON
            if isinstance(data, dict):
                if "contents" in data and isinstance(data["contents"], list):
                    if not data["contents"]:
                        return False
                    first_content = data["contents"][0]
                    if isinstance(first_content, dict) and "parts" in first_content:
                        try:
                            genai_types.Content.model_validate(first_content)
                            return True
                        except ValueError:
                            return False
                # Adding a check if 'data' itself is a Content-like object with parts
                elif "parts" in data and isinstance(data["parts"], list):
                    try:
                        genai_types.Content.model_validate(data)
                        return True
                    except ValueError:
                        return False
            return False
        except json.JSONDecodeError:
            return False

    def _parse_multimodal_json_string_into_parts(
        self,
        value: str,
    ) -> list[genai_types.Part]:
        """Parses a multimodal JSON string and returns its list of Parts."""
        try:
            content = genai_types.Content.model_validate_json(value)
            return content.parts if content.parts is not None else [genai_types.Part()]
        except Exception:
            return [genai_types.Part(text=value)]

    def assemble(self, **kwargs: Any) -> str:
        """Assembles the prompt template with the given keyword arguments.

        Supports both text and multimodal content. The `assemble` method
        substitutes variables from the prompt template text with provided
        values.

        Key Behaviors of `assemble()`:
        1.  Variable Substitution: Replaces all defined variables with their
            corresponding keyword argument values. Raises ValueError if a
            template
            variable is missing a value or if an extraneous kwarg is provided.
        2.  Multimodal Handling:
            - Detects if any variable's value is a JSON string representing
            multimodal content (specifically, `{"contents": [{"parts": [...]}]}`
            or `{"role": "user", "parts": [...]}`).
            - If multimodal content is detected for a variable, its `Part`
            objects
            are extracted and inserted into the assembled sequence.
            - Text segments from the template and simple text variable values
            become `Part(text=...)`.
        3.  Output Format:
            - If ALL substituted variables were simple text AND the assembled
            result (after merging adjacent text parts) consists of a single,
            purely textual `Part`, `assemble()` returns a raw Python string.
            - Otherwise (if any variable was multimodal, or if the assembly
            results in multiple parts or non-textual parts), `assemble()`
            returns
            a JSON string representing a single `google.genai.types.Content`
            object with `role="user"` and the assembled parts.
        4.  Text Part Merging: Consecutively assembled text parts are
            automatically merged into a single text `Part` to create a more
            concise list of parts.

        This dual output format (raw string or JSON string of `Content`) allows
        the downstream inference functions to seamlessly handle both simple text
        prompts and more complex multimodal prompts generated from the same
        templating mechanism.
        """
        current_variables = self.variables
        for var_name_in_kwarg in kwargs:
            if var_name_in_kwarg not in current_variables:
                raise ValueError(
                    f"Invalid variable name '{var_name_in_kwarg}' provided to"
                    " assemble. Valid variables in template are:"
                    f" {current_variables}"
                )
        # Check if all template variables are provided in kwargs
        for tpl_var in current_variables:
            if tpl_var not in kwargs:
                raise ValueError(f"Missing value for template variable '{tpl_var}'.")

        template_segments = self._split_template_by_variables()

        raw_assembled_parts: list[genai_types.Part] = []
        contains_multimodal_variable_type = False

        for segment_type, segment_value in template_segments:
            if segment_type == "text":
                if segment_value:
                    raw_assembled_parts.append(genai_types.Part(text=segment_value))
            elif segment_type == "var":
                var_value = kwargs.get(segment_value)

                str_var_value = str(var_value)

                if self._is_multimodal_json_string(str_var_value):
                    multimodal_parts = self._parse_multimodal_json_string_into_parts(
                        str_var_value
                    )
                    if multimodal_parts:
                        contains_multimodal_variable_type = True
                        raw_assembled_parts.extend(multimodal_parts)
                    else:
                        raw_assembled_parts.append(genai_types.Part(text=str_var_value))
                else:
                    raw_assembled_parts.append(genai_types.Part(text=str_var_value))

        final_assembled_parts = self._merge_adjacent_text_parts(raw_assembled_parts)

        # Condition for returning raw text string:
        # 1. No multimodal variable was *originally* a multimodal JSON string.
        # 2. After merging, there's exactly one part.
        # 3. That single part is purely textual.
        if (
            not contains_multimodal_variable_type
            and len(final_assembled_parts) == 1
            and final_assembled_parts[0].text is not None
            and all(
                getattr(final_assembled_parts[0], field) is None
                for field in final_assembled_parts[0].model_fields
                if field not in ["text", "role"]
            )
        ):
            return final_assembled_parts[0].text

        # Otherwise, construct a Content object (as JSON string).
        final_content_obj = genai_types.Content(parts=final_assembled_parts)
        return final_content_obj.model_dump_json(exclude_none=True)

    def __str__(self) -> str:
        return self.text if self.text else ""

    def __repr__(self) -> str:
        return f"PromptTemplate(text='{self.text}')"


class MetricPromptBuilder(PromptTemplate):
    """Builder class for structured LLM-based metric prompt template."""

    criteria: Optional[dict[str, str]] = Field(
        None,
        description="""A dictionary of criteria used to evaluate the model responses.
      The keys are criterion names, and the values are the corresponding
      criterion definitions.
      """,
    )

    rating_scores: Optional[dict[str, str]] = Field(
        None,
        description="""A dictionary mapping of rating score names to their definitions.""",
    )

    @staticmethod
    def _get_default_instruction() -> str:
        """Returns the default instruction for evaluation."""
        return (
            "You are an expert evaluator. Your task is to evaluate the quality"
            " of the responses generated by AI models. We will provide you with"
            " the user prompt and an AI-generated responses.\nYou should first"
            " read the user input carefully for analyzing the task, and then"
            " evaluate the quality of the responses based on the Criteria"
            " provided in the Evaluation section below.\nYou will assign the"
            " response a rating following the Rating Scores and Evaluation"
            " Steps. Give step by step explanations for your rating, and only"
            " choose ratings from the Rating Scores."
        )

    instruction: Optional[str] = Field(
        default_factory=lambda: MetricPromptBuilder._get_default_instruction(),
        description="""The general instruction to guide the model in performing the evaluation.
    If not provided, a default instruction for evaluation will be used.
    """,
    )

    metric_definition: Optional[str] = Field(
        None,
        description="""An optional high-level description of the metric to be evaluated.
      If not provided, this field will not be included in the prompt template.
      """,
    )

    @staticmethod
    def _get_default_evaluation_steps() -> dict[str, str]:
        """Returns the default evaluation steps for metric evaluation."""
        return {
            "Step 1": (
                "Assess the response in aspects of all criteria provided. Provide"
                " assessment according to each criterion."
            ),
            "Step 2": (
                "Score based on the Rating Scores. Give a brief rationale to"
                " explain your evaluation considering each individual criterion."
            ),
        }

    evaluation_steps: Optional[dict[str, str]] = Field(
        default_factory=lambda: MetricPromptBuilder._get_default_evaluation_steps(),
        description="""An optional dictionary of evaluation steps.
      The keys are the names of the evaluation steps, and the values are
      descriptions of the corresponding evaluation steps. If not provided,
      default metric evaluation steps will be used.
      """,
    )

    few_shot_examples: Optional[list[str]] = Field(
        None,
        description="""An optional list of few-shot examples to guide the model's evaluation.
      These examples demonstrate how to apply the criteria, rating scores,
      and evaluation steps to assess model responses. Providing few-shot examples
      can improve the accuracy of the evaluation. If not provided, this field
      will not be included in the prompt template.
      """,
    )

    @staticmethod
    def _serialize_dict_in_order(elements: Optional[dict[str, str]]) -> str:
        """Serializes dictionary to ordered string value without brackets."""
        if elements is None:
            return ""
        return "\n".join(f"{key}: {value}" for key, value in sorted(elements.items()))

    @model_validator(mode="before")
    @classmethod
    def _prepare_fields_and_construct_text(cls, data: Any) -> Any:
        """Pydantic model validator (before mode) to prepare and construct prompt text.

        This validator performs the following actions:
          1. Apply default logic for fields (instruction, evaluation_steps).
          2. Construct the 'text' string from all components.
          3. Ensure 'text' is in the data dictionary for PromptTemplate
          initialization.

        Args:
            data: Input data for the model, either a dictionary or an existing model
              instance.

        Returns:
            Processed data dictionary with the 'text' field constructed.
        """
        if not isinstance(data, dict):
            return data

        if "text" in data:
            raise ValueError(
                "The 'text' field is automatically constructed and should not be"
                " provided manually."
            )

        if data.get("criteria") is None or data.get("rating_scores") is None:
            raise ValueError(
                "Both 'criteria' and 'rating_scores' are required to construct the"
                "LLM-based metric prompt template text."
            )

        instruction = data.get("instruction", cls._get_default_instruction())
        metric_definition = data.get("metric_definition")
        evaluation_steps = data.get(
            "evaluation_steps", cls._get_default_evaluation_steps()
        )
        criteria = data.get("criteria")
        rating_scores = data.get("rating_scores")
        few_shot_examples = data.get("few_shot_examples")

        template_parts = [
            "# Instruction",
            instruction,
            "\n",
            "# Evaluation",
        ]

        sections = {
            "Metric Definition": metric_definition,
            "Criteria": cls._serialize_dict_in_order(criteria),
            "Rating Scores": cls._serialize_dict_in_order(rating_scores),
            "Evaluation Steps": cls._serialize_dict_in_order(evaluation_steps),
            "Evaluation Examples": (
                "\n".join(few_shot_examples) if few_shot_examples else None
            ),
        }

        for title, content in sections.items():
            if content:
                template_parts.extend([f"## {title}", f"{content}\n"])

        template_parts.extend(
            [
                "\n",
                "# User Inputs and AI-generated Response",
                "## User Prompt",
                "<prompt>{prompt}</prompt>",
                "\n",
                "## AI-generated Response",
                "<response>{response}</response>",
            ]
        )

        constructed_text = "\n".join(template_parts)

        data["text"] = constructed_text
        return data

    def __str__(self) -> str:
        """Returns the fully constructed prompt template text."""
        return self.text if self.text else ""


class PromptTemplateDict(TypedDict, total=False):
    """A prompt template for creating prompts with variables."""

    text: Optional[str]
    """The prompt template text."""


PromptTemplateOrDict = Union[PromptTemplate, PromptTemplateDict]


class EvalRunInferenceConfig(_common.BaseModel):
    """Optional parameters for inference."""

    dest: Optional[str] = Field(
        default=None, description="""The destination path for the inference results."""
    )
    prompt_template: Optional[Union[str, PromptTemplate]] = Field(
        default=None, description="""The prompt template to use for inference."""
    )
    generate_content_config: Optional[genai_types.GenerateContentConfig] = Field(
        default=None, description="""The config for the generate content call."""
    )


class EvalRunInferenceConfigDict(TypedDict, total=False):
    """Optional parameters for inference."""

    dest: Optional[str]
    """The destination path for the inference results."""

    prompt_template: Optional[Union[str, PromptTemplateDict]]
    """The prompt template to use for inference."""

    generate_content_config: Optional[genai_types.GenerateContentConfigDict]
    """The config for the generate content call."""


EvalRunInferenceConfigOrDict = Union[EvalRunInferenceConfig, EvalRunInferenceConfigDict]


class ContentMapContents(_common.BaseModel):
    """Map of placeholder in metric prompt template to contents of model input."""

    contents: Optional[list[genai_types.Content]] = Field(
        default=None, description="""Contents of the model input."""
    )


class ContentMapContentsDict(TypedDict, total=False):
    """Map of placeholder in metric prompt template to contents of model input."""

    contents: Optional[list[genai_types.ContentDict]]
    """Contents of the model input."""


ContentMapContentsOrDict = Union[ContentMapContents, ContentMapContentsDict]


class EvalCaseMetricResult(_common.BaseModel):
    """Evaluation result for a single evaluation case for a single metric."""

    metric_name: Optional[str] = Field(
        default=None, description="""Name of the metric."""
    )
    score: Optional[float] = Field(default=None, description="""Score of the metric.""")
    explanation: Optional[str] = Field(
        default=None, description="""Explanation of the metric."""
    )
    rubric_verdicts: Optional[list[evals_types.RubricVerdict]] = Field(
        default=None,
        description="""The details of all the rubrics and their verdicts for rubric-based metrics.""",
    )
    raw_output: Optional[list[str]] = Field(
        default=None, description="""Raw output of the metric."""
    )
    error_message: Optional[str] = Field(
        default=None, description="""Error message for the metric."""
    )


class EvalCaseMetricResultDict(TypedDict, total=False):
    """Evaluation result for a single evaluation case for a single metric."""

    metric_name: Optional[str]
    """Name of the metric."""

    score: Optional[float]
    """Score of the metric."""

    explanation: Optional[str]
    """Explanation of the metric."""

    rubric_verdicts: Optional[list[evals_types.RubricVerdict]]
    """The details of all the rubrics and their verdicts for rubric-based metrics."""

    raw_output: Optional[list[str]]
    """Raw output of the metric."""

    error_message: Optional[str]
    """Error message for the metric."""


EvalCaseMetricResultOrDict = Union[EvalCaseMetricResult, EvalCaseMetricResultDict]


class EvaluationRunAgentConfig(_common.BaseModel):
    """This field is experimental and may change in future versions.

    Agent config for an evaluation run.
    """

    developer_instruction: Optional[genai_types.Content] = Field(
        default=None, description="""The developer instruction for the agent."""
    )
    tools: Optional[list[genai_types.Tool]] = Field(
        default=None, description="""The tools available to the agent."""
    )


class EvaluationRunAgentConfigDict(TypedDict, total=False):
    """This field is experimental and may change in future versions.

    Agent config for an evaluation run.
    """

    developer_instruction: Optional[genai_types.ContentDict]
    """The developer instruction for the agent."""

    tools: Optional[list[genai_types.ToolDict]]
    """The tools available to the agent."""


EvaluationRunAgentConfigOrDict = Union[
    EvaluationRunAgentConfig, EvaluationRunAgentConfigDict
]


class EvaluationRunInferenceConfig(_common.BaseModel):
    """This field is experimental and may change in future versions.

    Configuration that describes an agent.
    """

    agent_config: Optional[EvaluationRunAgentConfig] = Field(
        default=None, description="""The agent config."""
    )
    model: Optional[str] = Field(
        default=None,
        description="""The fully qualified name of the publisher model or endpoint to use for inference.""",
    )


class EvaluationRunInferenceConfigDict(TypedDict, total=False):
    """This field is experimental and may change in future versions.

    Configuration that describes an agent.
    """

    agent_config: Optional[EvaluationRunAgentConfigDict]
    """The agent config."""

    model: Optional[str]
    """The fully qualified name of the publisher model or endpoint to use for inference."""


EvaluationRunInferenceConfigOrDict = Union[
    EvaluationRunInferenceConfig, EvaluationRunInferenceConfigDict
]


class WinRateStats(_common.BaseModel):
    """Statistics for win rates for a single metric."""

    win_rates: Optional[list[float]] = Field(
        default=None,
        description="""Win rates for the metric, one for each candidate.""",
    )
    tie_rate: Optional[float] = Field(
        default=None, description="""Tie rate for the metric."""
    )


class WinRateStatsDict(TypedDict, total=False):
    """Statistics for win rates for a single metric."""

    win_rates: Optional[list[float]]
    """Win rates for the metric, one for each candidate."""

    tie_rate: Optional[float]
    """Tie rate for the metric."""


WinRateStatsOrDict = Union[WinRateStats, WinRateStatsDict]


class EvaluateMethodConfig(_common.BaseModel):
    """Optional parameters for the evaluate method."""

    http_options: Optional[genai_types.HttpOptions] = Field(
        default=None, description="""Used to override HTTP request options."""
    )
    dataset_schema: Optional[Literal["GEMINI", "FLATTEN", "OPENAI"]] = Field(
        default=None,
        description="""The schema to use for the dataset.
      If not specified, the dataset schema will be inferred from the first
      example in the dataset.""",
    )
    dest: Optional[str] = Field(
        default=None, description="""The destination path for the evaluation results."""
    )


class EvaluateMethodConfigDict(TypedDict, total=False):
    """Optional parameters for the evaluate method."""

    http_options: Optional[genai_types.HttpOptionsDict]
    """Used to override HTTP request options."""

    dataset_schema: Optional[Literal["GEMINI", "FLATTEN", "OPENAI"]]
    """The schema to use for the dataset.
      If not specified, the dataset schema will be inferred from the first
      example in the dataset."""

    dest: Optional[str]
    """The destination path for the evaluation results."""


EvaluateMethodConfigOrDict = Union[EvaluateMethodConfig, EvaluateMethodConfigDict]


class EvaluateDatasetConfig(_common.BaseModel):
    """Config for evaluate instances."""

    http_options: Optional[genai_types.HttpOptions] = Field(
        default=None, description="""Used to override HTTP request options."""
    )


class EvaluateDatasetConfigDict(TypedDict, total=False):
    """Config for evaluate instances."""

    http_options: Optional[genai_types.HttpOptionsDict]
    """Used to override HTTP request options."""


EvaluateDatasetConfigOrDict = Union[EvaluateDatasetConfig, EvaluateDatasetConfigDict]


class EvaluateDatasetRequestParameters(_common.BaseModel):
    """Parameters for batch dataset evaluation."""

    dataset: Optional[EvaluationDataset] = Field(default=None, description="""""")
    metrics: Optional[list[Metric]] = Field(default=None, description="""""")
    output_config: Optional[genai_types.OutputConfig] = Field(
        default=None, description=""""""
    )
    autorater_config: Optional[genai_types.AutoraterConfig] = Field(
        default=None, description=""""""
    )
    config: Optional[EvaluateDatasetConfig] = Field(default=None, description="""""")


class EvaluateDatasetRequestParametersDict(TypedDict, total=False):
    """Parameters for batch dataset evaluation."""

    dataset: Optional[EvaluationDatasetDict]
    """"""

    metrics: Optional[list[MetricDict]]
    """"""

    output_config: Optional[genai_types.OutputConfigDict]
    """"""

    autorater_config: Optional[genai_types.AutoraterConfigDict]
    """"""

    config: Optional[EvaluateDatasetConfigDict]
    """"""


EvaluateDatasetRequestParametersOrDict = Union[
    EvaluateDatasetRequestParameters, EvaluateDatasetRequestParametersDict
]


class EvaluateDatasetOperation(_common.BaseModel):

    name: Optional[str] = Field(
        default=None,
        description="""The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`.""",
    )
    metadata: Optional[dict[str, Any]] = Field(
        default=None,
        description="""Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata.  Any method that returns a long-running operation should document the metadata type, if any.""",
    )
    done: Optional[bool] = Field(
        default=None,
        description="""If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available.""",
    )
    error: Optional[dict[str, Any]] = Field(
        default=None,
        description="""The error result of the operation in case of failure or cancellation.""",
    )
    response: Optional[EvaluationDataset] = Field(default=None, description="""""")


class EvaluateDatasetOperationDict(TypedDict, total=False):

    name: Optional[str]
    """The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`."""

    metadata: Optional[dict[str, Any]]
    """Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata.  Any method that returns a long-running operation should document the metadata type, if any."""

    done: Optional[bool]
    """If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available."""

    error: Optional[dict[str, Any]]
    """The error result of the operation in case of failure or cancellation."""

    response: Optional[EvaluationDatasetDict]
    """"""


EvaluateDatasetOperationOrDict = Union[
    EvaluateDatasetOperation, EvaluateDatasetOperationDict
]


class ObservabilityEvalCase(_common.BaseModel):
    """A single evaluation case instance for data stored in GCP Observability."""

    input_src: Optional[str] = Field(
        default=None,
        description="""String containing the GCS reference to the GenAI input content.""",
    )
    output_src: Optional[str] = Field(
        default=None,
        description="""String containing the GCS reference to the GenAI response content.""",
    )
    system_instruction_src: Optional[str] = Field(
        default=None,
        description="""An optional string containing the GCS reference to the GenAI system instruction.""",
    )
    api_client: Optional[Any] = Field(
        default=None, description="""The underlying API client."""
    )


class ObservabilityEvalCaseDict(TypedDict, total=False):
    """A single evaluation case instance for data stored in GCP Observability."""

    input_src: Optional[str]
    """String containing the GCS reference to the GenAI input content."""

    output_src: Optional[str]
    """String containing the GCS reference to the GenAI response content."""

    system_instruction_src: Optional[str]
    """An optional string containing the GCS reference to the GenAI system instruction."""

    api_client: Optional[Any]
    """The underlying API client."""


ObservabilityEvalCaseOrDict = Union[ObservabilityEvalCase, ObservabilityEvalCaseDict]


class RubricGroup(_common.BaseModel):
    """A group of rubrics, used for grouping rubrics based on a metric or a version."""

    group_id: Optional[str] = Field(
        default=None, description="""Unique identifier for the group."""
    )
    display_name: Optional[str] = Field(
        default=None,
        description="""Human-readable name for the group. This should be unique
      within a given context if used for display or selection.
      Example: "Instruction Following V1", "Content Quality - Summarization
      Task".""",
    )
    rubrics: Optional[list[evals_types.Rubric]] = Field(
        default=None, description="""Rubrics that are part of this group."""
    )


class RubricGroupDict(TypedDict, total=False):
    """A group of rubrics, used for grouping rubrics based on a metric or a version."""

    group_id: Optional[str]
    """Unique identifier for the group."""

    display_name: Optional[str]
    """Human-readable name for the group. This should be unique
      within a given context if used for display or selection.
      Example: "Instruction Following V1", "Content Quality - Summarization
      Task"."""

    rubrics: Optional[list[evals_types.Rubric]]
    """Rubrics that are part of this group."""


RubricGroupOrDict = Union[RubricGroup, RubricGroupDict]


class AgentEngine(_common.BaseModel):
    """An agent engine instance."""

    api_client: Optional[Any] = Field(
        default=None, description="""The underlying API client."""
    )
    api_async_client: Optional[Any] = Field(
        default=None,
        description="""The underlying API client for asynchronous operations.""",
    )
    api_resource: Optional[ReasoningEngine] = Field(
        default=None,
        description="""The underlying API resource (i.e. ReasoningEngine).""",
    )

    # Allows dynamic binding of methods based on the registered operations.
    model_config = ConfigDict(extra="allow")

    def __repr__(self) -> str:
        return (
            f"AgentEngine(api_resource.name='{self.api_resource.name}')"
            if self.api_resource is not None
            else "AgentEngine(api_resource.name=None)"
        )

    def operation_schemas(self) -> Optional[list[Dict[str, Any]]]:
        """Returns the schemas of all registered operations for the agent."""
        if not isinstance(self.api_resource, ReasoningEngine):
            raise ValueError("api_resource is not initialized.")
        if not self.api_resource.spec:
            raise ValueError("api_resource.spec is not initialized.")
        return self.api_resource.spec.class_methods

    def delete(
        self,
        force: bool = False,
        config: Optional[DeleteAgentEngineConfigOrDict] = None,
    ) -> None:
        """Deletes the agent engine.

        Args:
          force (bool):
              Optional. If set to True, child resources will also be deleted.
              Otherwise, the request will fail with FAILED_PRECONDITION error when
              the Agent Engine has undeleted child resources. Defaults to False.
          config (DeleteAgentEngineConfig):
              Optional. Additional configurations for deleting the Agent Engine.
        """
        if not isinstance(self.api_resource, ReasoningEngine):
            raise ValueError("api_resource is not initialized.")
        self.api_client.delete(name=self.api_resource.name, force=force, config=config)  # type: ignore[union-attr]


RubricContentProperty = evals_types.RubricContentProperty
RubricContentPropertyDict = evals_types.RubricContentPropertyDict
RubricContentPropertyDictOrDict = evals_types.RubricContentPropertyOrDict

RubricContent = evals_types.RubricContent
RubricContentDict = evals_types.RubricContentDict
RubricContentDictOrDict = evals_types.RubricContentOrDict

Rubric = evals_types.Rubric
RubricDict = evals_types.RubricDict
RubricDictOrDict = evals_types.RubricOrDict

RubricVerdict = evals_types.RubricVerdict
RubricVerdictDict = evals_types.RubricVerdictDict
RubricVerdictDictOrDict = evals_types.RubricVerdictOrDict

CandidateResult = evals_types.CandidateResult
CandidateResultDict = evals_types.CandidateResultDict
CandidateResultDictOrDict = evals_types.CandidateResultOrDict

Event = evals_types.Event
EventDict = evals_types.EventDict
EventDictOrDict = evals_types.EventOrDict

Message = evals_types.Message
MessageDict = evals_types.MessageDict
MessageDictOrDict = evals_types.MessageOrDict

Importance = evals_types.Importance


class AgentEngineDict(TypedDict, total=False):
    """An agent engine instance."""

    api_client: Optional[Any]
    """The underlying API client."""

    api_async_client: Optional[Any]
    """The underlying API client for asynchronous operations."""

    api_resource: Optional[ReasoningEngineDict]
    """The underlying API resource (i.e. ReasoningEngine)."""


AgentEngineOrDict = Union[AgentEngine, AgentEngineDict]


class AgentEngineConfig(_common.BaseModel):
    """Config for agent engine methods."""

    http_options: Optional[genai_types.HttpOptions] = Field(
        default=None, description="""Used to override HTTP request options."""
    )
    staging_bucket: Optional[str] = Field(
        default=None,
        description="""The GCS bucket to use for staging the artifacts needed.

      It must be a valid GCS bucket name, e.g. "gs://bucket-name". It is
      required if `agent_engine` is specified.""",
    )
    requirements: Optional[Any] = Field(
        default=None,
        description="""The set of PyPI dependencies needed.

      It can either be the path to a single file (requirements.txt), or an
      ordered list of strings corresponding to each line of the requirements
      file.""",
    )
    display_name: Optional[str] = Field(
        default=None,
        description="""The user-defined name of the Agent Engine.

      The name can be up to 128 characters long and can comprise any UTF-8
      character.""",
    )
    description: Optional[str] = Field(
        default=None, description="""The description of the Agent Engine."""
    )
    gcs_dir_name: Optional[str] = Field(
        default=None,
        description="""The GCS bucket directory under `staging_bucket` to use for staging
      the artifacts needed.""",
    )
    extra_packages: Optional[list[str]] = Field(
        default=None,
        description="""The set of extra user-provided packages (if any).""",
    )
    env_vars: Optional[Any] = Field(
        default=None,
        description="""The environment variables to be set when running the Agent Engine.

      If it is a dictionary, the keys are the environment variable names, and
      the values are the corresponding values.""",
    )
    service_account: Optional[str] = Field(
        default=None,
        description="""The service account to be used for the Agent Engine.

      If not specified, the default Reasoning Engine P6SA service agent will be used.""",
    )
    identity_type: Optional[IdentityType] = Field(
        default=None, description="""The identity type to use for the Agent Engine."""
    )
    context_spec: Optional[ReasoningEngineContextSpec] = Field(
        default=None,
        description="""The context spec to be used for the Agent Engine.""",
    )
    psc_interface_config: Optional[PscInterfaceConfig] = Field(
        default=None,
        description="""The PSC interface config for PSC-I to be used for the Agent Engine.""",
    )
    min_instances: Optional[int] = Field(
        default=None,
        description="""The minimum number of instances to run for the Agent Engine.
      Defaults to 1. Range: [0, 10].
      """,
    )
    max_instances: Optional[int] = Field(
        default=None,
        description="""The maximum number of instances to run for the Agent Engine.
      Defaults to 100. Range: [1, 1000].
      If VPC-SC or PSC-I is enabled, the acceptable range is [1, 100].
      """,
    )
    resource_limits: Optional[dict[str, str]] = Field(
        default=None,
        description="""The resource limits to be applied to the Agent Engine.
      Required keys: 'cpu' and 'memory'.
      Supported values for 'cpu': '1', '2', '4', '6', '8'.
      Supported values for 'memory': '1Gi', '2Gi', ..., '32Gi'.
      """,
    )
    container_concurrency: Optional[int] = Field(
        default=None,
        description="""The container concurrency to be used for the Agent Engine.
      Recommended value: 2 * cpu + 1. Defaults to 9.
      """,
    )
    encryption_spec: Optional[genai_types.EncryptionSpec] = Field(
        default=None,
        description="""The encryption spec to be used for the Agent Engine.""",
    )
    labels: Optional[dict[str, str]] = Field(
        default=None, description="""The labels to be used for the Agent Engine."""
    )
    agent_server_mode: Optional[AgentServerMode] = Field(
        default=None, description="""The agent server mode to use for deployment."""
    )
    class_methods: Optional[list[dict[str, Any]]] = Field(
        default=None,
        description="""The class methods to be used for the Agent Engine.
      If specified, they'll override the class methods that are autogenerated by
      default. By default, methods are generated by inspecting the agent object
      and generating a corresponding method for each method defined on the
      agent class.
      """,
    )
    source_packages: Optional[list[str]] = Field(
        default=None,
        description="""The user-provided paths to the source packages (if any).
      If specified, the files in the source packages will be packed into a
      a tarball file, uploaded to Agent Engine's API, and deployed to the
      Agent Engine.
      The following fields will be ignored:
        - agent
        - extra_packages
        - staging_bucket
        - requirements
      The following fields will be used to install and use the agent from the
      source packages:
        - entrypoint_module (required)
        - entrypoint_object (required)
        - requirements_file (optional)
        - class_methods     (required)
      """,
    )
    entrypoint_module: Optional[str] = Field(
        default=None,
        description="""The entrypoint module to be used for the Agent Engine
      This field only used when source_packages is specified.""",
    )
    entrypoint_object: Optional[str] = Field(
        default=None,
        description="""The entrypoint object to be used for the Agent Engine.
      This field only used when source_packages is specified.""",
    )
    requirements_file: Optional[str] = Field(
        default=None,
        description="""The user-provided path to the requirements file (if any).
      This field is only used when source_packages is specified.
      If not specified, agent engine will find and use the `requirements.txt` in
      the source package.
      """,
    )
    agent_framework: Optional[
        Literal["google-adk", "langchain", "langgraph", "ag2", "llama-index", "custom"]
    ] = Field(
        default=None,
        description="""The agent framework to be used for the Agent Engine.
      The OSS agent framework used to develop the agent.
      Currently supported values: "google-adk", "langchain", "langgraph",
      "ag2", "llama-index", "custom".
      If not specified:
      - If `agent` is specified, the agent framework will be auto-detected.
      - If `source_packages` is specified, the agent framework will
        default to "custom".""",
    )
    python_version: Optional[Literal["3.9", "3.10", "3.11", "3.12", "3.13"]] = Field(
        default=None,
        description="""The Python version to be used for the Agent Engine.
      If not specified, it will use the current Python version of the environment.
      Supported versions: "3.9", "3.10", "3.11", "3.12", "3.13".
      """,
    )
    build_options: Optional[dict[str, list[str]]] = Field(
        default=None,
        description="""The build options for the Agent Engine.
      The following keys are supported:
      - installation_scripts:
          Optional. The paths to the installation scripts to be
          executed in the Docker image.
          The scripts must be located in the `installation_scripts`
          subdirectory and the path must be added to `extra_packages`.
      """,
    )


class AgentEngineConfigDict(TypedDict, total=False):
    """Config for agent engine methods."""

    http_options: Optional[genai_types.HttpOptionsDict]
    """Used to override HTTP request options."""

    staging_bucket: Optional[str]
    """The GCS bucket to use for staging the artifacts needed.

      It must be a valid GCS bucket name, e.g. "gs://bucket-name". It is
      required if `agent_engine` is specified."""

    requirements: Optional[Any]
    """The set of PyPI dependencies needed.

      It can either be the path to a single file (requirements.txt), or an
      ordered list of strings corresponding to each line of the requirements
      file."""

    display_name: Optional[str]
    """The user-defined name of the Agent Engine.

      The name can be up to 128 characters long and can comprise any UTF-8
      character."""

    description: Optional[str]
    """The description of the Agent Engine."""

    gcs_dir_name: Optional[str]
    """The GCS bucket directory under `staging_bucket` to use for staging
      the artifacts needed."""

    extra_packages: Optional[list[str]]
    """The set of extra user-provided packages (if any)."""

    env_vars: Optional[Any]
    """The environment variables to be set when running the Agent Engine.

      If it is a dictionary, the keys are the environment variable names, and
      the values are the corresponding values."""

    service_account: Optional[str]
    """The service account to be used for the Agent Engine.

      If not specified, the default Reasoning Engine P6SA service agent will be used."""

    identity_type: Optional[IdentityType]
    """The identity type to use for the Agent Engine."""

    context_spec: Optional[ReasoningEngineContextSpecDict]
    """The context spec to be used for the Agent Engine."""

    psc_interface_config: Optional[PscInterfaceConfigDict]
    """The PSC interface config for PSC-I to be used for the Agent Engine."""

    min_instances: Optional[int]
    """The minimum number of instances to run for the Agent Engine.
      Defaults to 1. Range: [0, 10].
      """

    max_instances: Optional[int]
    """The maximum number of instances to run for the Agent Engine.
      Defaults to 100. Range: [1, 1000].
      If VPC-SC or PSC-I is enabled, the acceptable range is [1, 100].
      """

    resource_limits: Optional[dict[str, str]]
    """The resource limits to be applied to the Agent Engine.
      Required keys: 'cpu' and 'memory'.
      Supported values for 'cpu': '1', '2', '4', '6', '8'.
      Supported values for 'memory': '1Gi', '2Gi', ..., '32Gi'.
      """

    container_concurrency: Optional[int]
    """The container concurrency to be used for the Agent Engine.
      Recommended value: 2 * cpu + 1. Defaults to 9.
      """

    encryption_spec: Optional[genai_types.EncryptionSpecDict]
    """The encryption spec to be used for the Agent Engine."""

    labels: Optional[dict[str, str]]
    """The labels to be used for the Agent Engine."""

    agent_server_mode: Optional[AgentServerMode]
    """The agent server mode to use for deployment."""

    class_methods: Optional[list[dict[str, Any]]]
    """The class methods to be used for the Agent Engine.
      If specified, they'll override the class methods that are autogenerated by
      default. By default, methods are generated by inspecting the agent object
      and generating a corresponding method for each method defined on the
      agent class.
      """

    source_packages: Optional[list[str]]
    """The user-provided paths to the source packages (if any).
      If specified, the files in the source packages will be packed into a
      a tarball file, uploaded to Agent Engine's API, and deployed to the
      Agent Engine.
      The following fields will be ignored:
        - agent
        - extra_packages
        - staging_bucket
        - requirements
      The following fields will be used to install and use the agent from the
      source packages:
        - entrypoint_module (required)
        - entrypoint_object (required)
        - requirements_file (optional)
        - class_methods     (required)
      """

    entrypoint_module: Optional[str]
    """The entrypoint module to be used for the Agent Engine
      This field only used when source_packages is specified."""

    entrypoint_object: Optional[str]
    """The entrypoint object to be used for the Agent Engine.
      This field only used when source_packages is specified."""

    requirements_file: Optional[str]
    """The user-provided path to the requirements file (if any).
      This field is only used when source_packages is specified.
      If not specified, agent engine will find and use the `requirements.txt` in
      the source package.
      """

    agent_framework: Optional[
        Literal["google-adk", "langchain", "langgraph", "ag2", "llama-index", "custom"]
    ]
    """The agent framework to be used for the Agent Engine.
      The OSS agent framework used to develop the agent.
      Currently supported values: "google-adk", "langchain", "langgraph",
      "ag2", "llama-index", "custom".
      If not specified:
      - If `agent` is specified, the agent framework will be auto-detected.
      - If `source_packages` is specified, the agent framework will
        default to "custom"."""

    python_version: Optional[Literal["3.9", "3.10", "3.11", "3.12", "3.13"]]
    """The Python version to be used for the Agent Engine.
      If not specified, it will use the current Python version of the environment.
      Supported versions: "3.9", "3.10", "3.11", "3.12", "3.13".
      """

    build_options: Optional[dict[str, list[str]]]
    """The build options for the Agent Engine.
      The following keys are supported:
      - installation_scripts:
          Optional. The paths to the installation scripts to be
          executed in the Docker image.
          The scripts must be located in the `installation_scripts`
          subdirectory and the path must be added to `extra_packages`.
      """


AgentEngineConfigOrDict = Union[AgentEngineConfig, AgentEngineConfigDict]


class AssembleDataset(_common.BaseModel):
    """Represents the assembled dataset."""

    bigquery_destination: Optional[str] = Field(
        default=None,
        description="""The BigQuery destination of the assembled dataset.""",
    )


class AssembleDatasetDict(TypedDict, total=False):
    """Represents the assembled dataset."""

    bigquery_destination: Optional[str]
    """The BigQuery destination of the assembled dataset."""


AssembleDatasetOrDict = Union[AssembleDataset, AssembleDatasetDict]


class BatchPredictionResourceUsageAssessmentResult(_common.BaseModel):
    """Result of batch prediction resource usage assessment."""

    token_count: Optional[int] = Field(
        default=None, description="""Number of tokens in the dataset."""
    )
    audio_token_count: Optional[int] = Field(
        default=None, description="""Number of audio tokens in the dataset."""
    )


class BatchPredictionResourceUsageAssessmentResultDict(TypedDict, total=False):
    """Result of batch prediction resource usage assessment."""

    token_count: Optional[int]
    """Number of tokens in the dataset."""

    audio_token_count: Optional[int]
    """Number of audio tokens in the dataset."""


BatchPredictionResourceUsageAssessmentResultOrDict = Union[
    BatchPredictionResourceUsageAssessmentResult,
    BatchPredictionResourceUsageAssessmentResultDict,
]


class TuningResourceUsageAssessmentResult(_common.BaseModel):
    """Result of tuning resource usage assessment."""

    token_count: Optional[int] = Field(
        default=None, description="""The number of tokens in the dataset."""
    )
    billable_character_count: Optional[int] = Field(
        default=None,
        description="""The number of billable characters in the dataset.""",
    )


class TuningResourceUsageAssessmentResultDict(TypedDict, total=False):
    """Result of tuning resource usage assessment."""

    token_count: Optional[int]
    """The number of tokens in the dataset."""

    billable_character_count: Optional[int]
    """The number of billable characters in the dataset."""


TuningResourceUsageAssessmentResultOrDict = Union[
    TuningResourceUsageAssessmentResult, TuningResourceUsageAssessmentResultDict
]


class TuningValidationAssessmentResult(_common.BaseModel):
    """The result of a tuning validation assessment."""

    errors: Optional[list[str]] = Field(
        default=None, description="""The list of errors found in the dataset."""
    )


class TuningValidationAssessmentResultDict(TypedDict, total=False):
    """The result of a tuning validation assessment."""

    errors: Optional[list[str]]
    """The list of errors found in the dataset."""


TuningValidationAssessmentResultOrDict = Union[
    TuningValidationAssessmentResult, TuningValidationAssessmentResultDict
]


class Prompt(_common.BaseModel):
    """Represents a prompt."""

    prompt_data: Optional["PromptData"] = Field(default=None, description="""""")
    _dataset: Optional["Dataset"] = PrivateAttr(default=None)
    _dataset_version: Optional["DatasetVersion"] = PrivateAttr(default=None)

    @property
    def dataset(self) -> "Dataset":
        return self._dataset

    @property
    def dataset_version(self) -> "DatasetVersion":
        return self._dataset_version

    @property
    def prompt_id(self) -> Optional[str]:
        """Returns the ID associated with the prompt resource."""
        if self._dataset and self._dataset.name:
            return self._dataset.name.split("/")[-1]
        elif not self._dataset and (
            self._dataset_version and self._dataset_version.name
        ):
            return self._dataset_version.name.split("datasets/")[1].split("/")[0]

    @property
    def version_id(self) -> Optional[str]:
        """Returns the ID associated with the prompt version resource."""
        if self._dataset_version and self._dataset_version.name:
            return self._dataset_version.name.split("/")[-1]

    def assemble_contents(self) -> list[genai_types.Content]:
        """Transforms a Prompt object into a list with a single genai_types.Content object.

        This method replaces the variables in the prompt template with the values provided in prompt.prompt_data.variables.
        If no variables are provided, prompt.prompt_data.contents is returned as is. Only single-turn prompts are supported.

        This can be used to call generate_content() in the Gen AI SDK.

        Example usage:

        my_prompt = types.Prompt(
            prompt_data=types.PromptData(
                model="gemini-2.0-flash-001",
                contents=[
                    genai_types.Content(
                        parts=[
                            genai_types.Part(text="Hello {name}!"),
                        ],
                    ),
                ],
                variables=[
                    {
                        "name": genai_types.Part(text="Alice"),
                    },
                ],
            ),
        )

        from google import genai

        genai_client = genai.Client(vertexai=True, project="my-project", location="us-central1")
        genai_client.models.generate_content(
            model=my_prompt.prompt_data.model,
            contents=my_prompt.assemble_contents(),
        )

        Returns:
            A list with a single Content object that can be used to call
            generate_content().
        """
        if not self.prompt_data or not self.prompt_data.contents:
            return []

        if not self.prompt_data.variables:
            return self.prompt_data.contents

        if len(self.prompt_data.contents) > 1:
            raise ValueError(
                "Multiple contents are not supported. Use assemble_contents() for a prompt with a single Content item."
            )

        parts_to_process = self.prompt_data.contents[0].parts
        if not isinstance(parts_to_process, list):
            parts_to_process = [parts_to_process]

        has_placeholders = False
        variable_regex = r"\{.*?\}"
        for item in parts_to_process:
            part = (
                item
                if isinstance(item, genai_types.Part)
                else genai_types.Part(text=str(item))
            )
            if part.text and re.search(variable_regex, part.text):
                has_placeholders = True
                break

        if not has_placeholders:
            return [genai_types.Content(parts=parts_to_process)]

        all_rendered_parts: list[genai_types.Part] = []

        for var_dict in self.prompt_data.variables:
            for template_item in parts_to_process:
                template_part = (
                    template_item
                    if isinstance(template_item, genai_types.Part)
                    else genai_types.Part(text=str(template_item))
                )
                if template_part.text:
                    rendered_text = template_part.text

                    for key, value in var_dict.items():
                        placeholder = f"{{{key}}}"
                        replacement_text = None

                        if isinstance(value, str):
                            replacement_text = value
                        elif isinstance(value, genai_types.Part):
                            if value.text:
                                replacement_text = value.text
                            else:
                                all_rendered_parts.append(value)
                        if (
                            replacement_text is not None
                            and placeholder in rendered_text
                        ):
                            rendered_text = rendered_text.replace(
                                placeholder, replacement_text
                            )
                    all_rendered_parts.append(genai_types.Part(text=rendered_text))
                else:
                    all_rendered_parts.append(template_part)
        return [genai_types.Content(parts=all_rendered_parts, role="user")]


PromptData = SchemaPromptSpecPromptMessage
PromptDataDict = SchemaPromptSpecPromptMessageDict
PromptDataOrDict = Union[PromptData, PromptDataDict]


class PromptDict(TypedDict, total=False):
    """Represents a prompt."""

    prompt_data: Optional["PromptDataDict"]
    """"""


PromptOrDict = Union[Prompt, PromptDict]


class SchemaPromptInstanceVariableValue(_common.BaseModel):
    """Represents a prompt instance variable."""

    part_list: Optional[SchemaPromptSpecPartList] = Field(
        default=None, description="""The parts of the variable value."""
    )


class SchemaPromptInstanceVariableValueDict(TypedDict, total=False):
    """Represents a prompt instance variable."""

    part_list: Optional[SchemaPromptSpecPartListDict]
    """The parts of the variable value."""


SchemaPromptInstanceVariableValueOrDict = Union[
    SchemaPromptInstanceVariableValue, SchemaPromptInstanceVariableValueDict
]


class CreatePromptConfig(_common.BaseModel):
    """Config for creating a prompt."""

    http_options: Optional[genai_types.HttpOptions] = Field(
        default=None, description="""Used to override HTTP request options."""
    )
    prompt_display_name: Optional[str] = Field(
        default=None,
        description="""The display name for the prompt. If not set, a default name with a timestamp will be used.""",
    )
    timeout: Optional[int] = Field(
        default=90,
        description="""The timeout for the create_version request in seconds. If not set, the default timeout is 90 seconds.""",
    )
    encryption_spec: Optional[genai_types.EncryptionSpec] = Field(
        default=None,
        description="""Customer-managed encryption key spec for a prompt dataset. If set, this prompt dataset and all sub-resources of this prompt dataset will be secured by this key.""",
    )


class CreatePromptConfigDict(TypedDict, total=False):
    """Config for creating a prompt."""

    http_options: Optional[genai_types.HttpOptionsDict]
    """Used to override HTTP request options."""

    prompt_display_name: Optional[str]
    """The display name for the prompt. If not set, a default name with a timestamp will be used."""

    timeout: Optional[int]
    """The timeout for the create_version request in seconds. If not set, the default timeout is 90 seconds."""

    encryption_spec: Optional[genai_types.EncryptionSpecDict]
    """Customer-managed encryption key spec for a prompt dataset. If set, this prompt dataset and all sub-resources of this prompt dataset will be secured by this key."""


CreatePromptConfigOrDict = Union[CreatePromptConfig, CreatePromptConfigDict]


class CreatePromptVersionConfig(_common.BaseModel):
    """Config for creating a prompt version."""

    http_options: Optional[genai_types.HttpOptions] = Field(
        default=None, description="""Used to override HTTP request options."""
    )
    version_display_name: Optional[str] = Field(
        default=None,
        description="""The display name for the prompt version. If not set, a default name with a timestamp will be used.""",
    )
    timeout: Optional[int] = Field(
        default=90,
        description="""The timeout for the create_version request in seconds. If not set, the default timeout is 90 seconds.""",
    )


class CreatePromptVersionConfigDict(TypedDict, total=False):
    """Config for creating a prompt version."""

    http_options: Optional[genai_types.HttpOptionsDict]
    """Used to override HTTP request options."""

    version_display_name: Optional[str]
    """The display name for the prompt version. If not set, a default name with a timestamp will be used."""

    timeout: Optional[int]
    """The timeout for the create_version request in seconds. If not set, the default timeout is 90 seconds."""


CreatePromptVersionConfigOrDict = Union[
    CreatePromptVersionConfig, CreatePromptVersionConfigDict
]


class GetPromptConfig(_common.BaseModel):
    """Config for getting a prompt."""

    http_options: Optional[genai_types.HttpOptions] = Field(
        default=None, description="""Used to override HTTP request options."""
    )


class GetPromptConfigDict(TypedDict, total=False):
    """Config for getting a prompt."""

    http_options: Optional[genai_types.HttpOptionsDict]
    """Used to override HTTP request options."""


GetPromptConfigOrDict = Union[GetPromptConfig, GetPromptConfigDict]


class PromptRef(_common.BaseModel):
    """Reference to a prompt."""

    prompt_id: Optional[str] = Field(default=None, description="""""")
    model: Optional[str] = Field(default=None, description="""""")


class PromptRefDict(TypedDict, total=False):
    """Reference to a prompt."""

    prompt_id: Optional[str]
    """"""

    model: Optional[str]
    """"""


PromptRefOrDict = Union[PromptRef, PromptRefDict]


class PromptVersionRef(_common.BaseModel):
    """Reference to a prompt version."""

    prompt_id: Optional[str] = Field(default=None, description="""""")
    version_id: Optional[str] = Field(default=None, description="""""")
    model: Optional[str] = Field(default=None, description="""""")


class PromptVersionRefDict(TypedDict, total=False):
    """Reference to a prompt version."""

    prompt_id: Optional[str]
    """"""

    version_id: Optional[str]
    """"""

    model: Optional[str]
    """"""


PromptVersionRefOrDict = Union[PromptVersionRef, PromptVersionRefDict]
