# 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 json
import logging
from typing import Any, Optional, Union
from urllib.parse import urlencode

from . import _api_module
from . import _common
from . import _transformers as t
from . import types
from ._api_client import BaseApiClient
from ._common import get_value_by_path as getv
from ._common import set_value_by_path as setv
from .pagers import AsyncPager, Pager


logger = logging.getLogger('google_genai.caches')


def _Blob_to_mldev(
    from_object: Union[dict[str, Any], object],
    parent_object: Optional[dict[str, Any]] = None,
) -> dict[str, Any]:
  to_object: dict[str, Any] = {}
  if getv(from_object, ['data']) is not None:
    setv(to_object, ['data'], getv(from_object, ['data']))

  if getv(from_object, ['display_name']) is not None:
    raise ValueError('display_name parameter is not supported in Gemini API.')

  if getv(from_object, ['mime_type']) is not None:
    setv(to_object, ['mimeType'], getv(from_object, ['mime_type']))

  return to_object


def _Content_to_mldev(
    from_object: Union[dict[str, Any], object],
    parent_object: Optional[dict[str, Any]] = None,
) -> dict[str, Any]:
  to_object: dict[str, Any] = {}
  if getv(from_object, ['parts']) is not None:
    setv(
        to_object,
        ['parts'],
        [
            _Part_to_mldev(item, to_object)
            for item in getv(from_object, ['parts'])
        ],
    )

  if getv(from_object, ['role']) is not None:
    setv(to_object, ['role'], getv(from_object, ['role']))

  return to_object


def _CreateCachedContentConfig_to_mldev(
    from_object: Union[dict[str, Any], object],
    parent_object: Optional[dict[str, Any]] = None,
) -> dict[str, Any]:
  to_object: dict[str, Any] = {}

  if getv(from_object, ['ttl']) is not None:
    setv(parent_object, ['ttl'], getv(from_object, ['ttl']))

  if getv(from_object, ['expire_time']) is not None:
    setv(parent_object, ['expireTime'], getv(from_object, ['expire_time']))

  if getv(from_object, ['display_name']) is not None:
    setv(parent_object, ['displayName'], getv(from_object, ['display_name']))

  if getv(from_object, ['contents']) is not None:
    setv(
        parent_object,
        ['contents'],
        [
            _Content_to_mldev(item, to_object)
            for item in t.t_contents(getv(from_object, ['contents']))
        ],
    )

  if getv(from_object, ['system_instruction']) is not None:
    setv(
        parent_object,
        ['systemInstruction'],
        _Content_to_mldev(
            t.t_content(getv(from_object, ['system_instruction'])), to_object
        ),
    )

  if getv(from_object, ['tools']) is not None:
    setv(
        parent_object,
        ['tools'],
        [
            _Tool_to_mldev(item, to_object)
            for item in getv(from_object, ['tools'])
        ],
    )

  if getv(from_object, ['tool_config']) is not None:
    setv(parent_object, ['toolConfig'], getv(from_object, ['tool_config']))

  if getv(from_object, ['kms_key_name']) is not None:
    raise ValueError('kms_key_name parameter is not supported in Gemini API.')

  return to_object


def _CreateCachedContentConfig_to_vertex(
    from_object: Union[dict[str, Any], object],
    parent_object: Optional[dict[str, Any]] = None,
) -> dict[str, Any]:
  to_object: dict[str, Any] = {}

  if getv(from_object, ['ttl']) is not None:
    setv(parent_object, ['ttl'], getv(from_object, ['ttl']))

  if getv(from_object, ['expire_time']) is not None:
    setv(parent_object, ['expireTime'], getv(from_object, ['expire_time']))

  if getv(from_object, ['display_name']) is not None:
    setv(parent_object, ['displayName'], getv(from_object, ['display_name']))

  if getv(from_object, ['contents']) is not None:
    setv(
        parent_object,
        ['contents'],
        [item for item in t.t_contents(getv(from_object, ['contents']))],
    )

  if getv(from_object, ['system_instruction']) is not None:
    setv(
        parent_object,
        ['systemInstruction'],
        t.t_content(getv(from_object, ['system_instruction'])),
    )

  if getv(from_object, ['tools']) is not None:
    setv(
        parent_object,
        ['tools'],
        [
            _Tool_to_vertex(item, to_object)
            for item in getv(from_object, ['tools'])
        ],
    )

  if getv(from_object, ['tool_config']) is not None:
    setv(parent_object, ['toolConfig'], getv(from_object, ['tool_config']))

  if getv(from_object, ['kms_key_name']) is not None:
    setv(
        parent_object,
        ['encryption_spec', 'kmsKeyName'],
        getv(from_object, ['kms_key_name']),
    )

  return to_object


def _CreateCachedContentParameters_to_mldev(
    api_client: BaseApiClient,
    from_object: Union[dict[str, Any], object],
    parent_object: Optional[dict[str, Any]] = None,
) -> dict[str, Any]:
  to_object: dict[str, Any] = {}
  if getv(from_object, ['model']) is not None:
    setv(
        to_object,
        ['model'],
        t.t_caches_model(api_client, getv(from_object, ['model'])),
    )

  if getv(from_object, ['config']) is not None:
    _CreateCachedContentConfig_to_mldev(
        getv(from_object, ['config']), to_object
    )

  return to_object


def _CreateCachedContentParameters_to_vertex(
    api_client: BaseApiClient,
    from_object: Union[dict[str, Any], object],
    parent_object: Optional[dict[str, Any]] = None,
) -> dict[str, Any]:
  to_object: dict[str, Any] = {}
  if getv(from_object, ['model']) is not None:
    setv(
        to_object,
        ['model'],
        t.t_caches_model(api_client, getv(from_object, ['model'])),
    )

  if getv(from_object, ['config']) is not None:
    _CreateCachedContentConfig_to_vertex(
        getv(from_object, ['config']), to_object
    )

  return to_object


def _DeleteCachedContentParameters_to_mldev(
    api_client: BaseApiClient,
    from_object: Union[dict[str, Any], object],
    parent_object: Optional[dict[str, Any]] = None,
) -> dict[str, Any]:
  to_object: dict[str, Any] = {}
  if getv(from_object, ['name']) is not None:
    setv(
        to_object,
        ['_url', 'name'],
        t.t_cached_content_name(api_client, getv(from_object, ['name'])),
    )

  return to_object


def _DeleteCachedContentParameters_to_vertex(
    api_client: BaseApiClient,
    from_object: Union[dict[str, Any], object],
    parent_object: Optional[dict[str, Any]] = None,
) -> dict[str, Any]:
  to_object: dict[str, Any] = {}
  if getv(from_object, ['name']) is not None:
    setv(
        to_object,
        ['_url', 'name'],
        t.t_cached_content_name(api_client, getv(from_object, ['name'])),
    )

  return to_object


def _DeleteCachedContentResponse_from_mldev(
    from_object: Union[dict[str, Any], object],
    parent_object: Optional[dict[str, Any]] = None,
) -> dict[str, Any]:
  to_object: dict[str, Any] = {}
  if getv(from_object, ['sdkHttpResponse']) is not None:
    setv(
        to_object, ['sdk_http_response'], getv(from_object, ['sdkHttpResponse'])
    )

  return to_object


def _DeleteCachedContentResponse_from_vertex(
    from_object: Union[dict[str, Any], object],
    parent_object: Optional[dict[str, Any]] = None,
) -> dict[str, Any]:
  to_object: dict[str, Any] = {}
  if getv(from_object, ['sdkHttpResponse']) is not None:
    setv(
        to_object, ['sdk_http_response'], getv(from_object, ['sdkHttpResponse'])
    )

  return to_object


def _FileData_to_mldev(
    from_object: Union[dict[str, Any], object],
    parent_object: Optional[dict[str, Any]] = None,
) -> dict[str, Any]:
  to_object: dict[str, Any] = {}
  if getv(from_object, ['display_name']) is not None:
    raise ValueError('display_name parameter is not supported in Gemini API.')

  if getv(from_object, ['file_uri']) is not None:
    setv(to_object, ['fileUri'], getv(from_object, ['file_uri']))

  if getv(from_object, ['mime_type']) is not None:
    setv(to_object, ['mimeType'], getv(from_object, ['mime_type']))

  return to_object


def _FunctionDeclaration_to_vertex(
    from_object: Union[dict[str, Any], object],
    parent_object: Optional[dict[str, Any]] = None,
) -> dict[str, Any]:
  to_object: dict[str, Any] = {}
  if getv(from_object, ['behavior']) is not None:
    raise ValueError('behavior parameter is not supported in Vertex AI.')

  if getv(from_object, ['description']) is not None:
    setv(to_object, ['description'], getv(from_object, ['description']))

  if getv(from_object, ['name']) is not None:
    setv(to_object, ['name'], getv(from_object, ['name']))

  if getv(from_object, ['parameters']) is not None:
    setv(to_object, ['parameters'], getv(from_object, ['parameters']))

  if getv(from_object, ['parameters_json_schema']) is not None:
    setv(
        to_object,
        ['parametersJsonSchema'],
        getv(from_object, ['parameters_json_schema']),
    )

  if getv(from_object, ['response']) is not None:
    setv(to_object, ['response'], getv(from_object, ['response']))

  if getv(from_object, ['response_json_schema']) is not None:
    setv(
        to_object,
        ['responseJsonSchema'],
        getv(from_object, ['response_json_schema']),
    )

  return to_object


def _GetCachedContentParameters_to_mldev(
    api_client: BaseApiClient,
    from_object: Union[dict[str, Any], object],
    parent_object: Optional[dict[str, Any]] = None,
) -> dict[str, Any]:
  to_object: dict[str, Any] = {}
  if getv(from_object, ['name']) is not None:
    setv(
        to_object,
        ['_url', 'name'],
        t.t_cached_content_name(api_client, getv(from_object, ['name'])),
    )

  return to_object


def _GetCachedContentParameters_to_vertex(
    api_client: BaseApiClient,
    from_object: Union[dict[str, Any], object],
    parent_object: Optional[dict[str, Any]] = None,
) -> dict[str, Any]:
  to_object: dict[str, Any] = {}
  if getv(from_object, ['name']) is not None:
    setv(
        to_object,
        ['_url', 'name'],
        t.t_cached_content_name(api_client, getv(from_object, ['name'])),
    )

  return to_object


def _GoogleMaps_to_mldev(
    from_object: Union[dict[str, Any], object],
    parent_object: Optional[dict[str, Any]] = None,
) -> dict[str, Any]:
  to_object: dict[str, Any] = {}
  if getv(from_object, ['auth_config']) is not None:
    raise ValueError('auth_config parameter is not supported in Gemini API.')

  if getv(from_object, ['enable_widget']) is not None:
    setv(to_object, ['enableWidget'], getv(from_object, ['enable_widget']))

  return to_object


def _GoogleSearch_to_mldev(
    from_object: Union[dict[str, Any], object],
    parent_object: Optional[dict[str, Any]] = None,
) -> dict[str, Any]:
  to_object: dict[str, Any] = {}
  if getv(from_object, ['exclude_domains']) is not None:
    raise ValueError(
        'exclude_domains parameter is not supported in Gemini API.'
    )

  if getv(from_object, ['blocking_confidence']) is not None:
    raise ValueError(
        'blocking_confidence parameter is not supported in Gemini API.'
    )

  if getv(from_object, ['time_range_filter']) is not None:
    setv(
        to_object, ['timeRangeFilter'], getv(from_object, ['time_range_filter'])
    )

  return to_object


def _ListCachedContentsConfig_to_mldev(
    from_object: Union[dict[str, Any], object],
    parent_object: Optional[dict[str, Any]] = None,
) -> dict[str, Any]:
  to_object: dict[str, Any] = {}

  if getv(from_object, ['page_size']) is not None:
    setv(
        parent_object, ['_query', 'pageSize'], getv(from_object, ['page_size'])
    )

  if getv(from_object, ['page_token']) is not None:
    setv(
        parent_object,
        ['_query', 'pageToken'],
        getv(from_object, ['page_token']),
    )

  return to_object


def _ListCachedContentsConfig_to_vertex(
    from_object: Union[dict[str, Any], object],
    parent_object: Optional[dict[str, Any]] = None,
) -> dict[str, Any]:
  to_object: dict[str, Any] = {}

  if getv(from_object, ['page_size']) is not None:
    setv(
        parent_object, ['_query', 'pageSize'], getv(from_object, ['page_size'])
    )

  if getv(from_object, ['page_token']) is not None:
    setv(
        parent_object,
        ['_query', 'pageToken'],
        getv(from_object, ['page_token']),
    )

  return to_object


def _ListCachedContentsParameters_to_mldev(
    from_object: Union[dict[str, Any], object],
    parent_object: Optional[dict[str, Any]] = None,
) -> dict[str, Any]:
  to_object: dict[str, Any] = {}
  if getv(from_object, ['config']) is not None:
    _ListCachedContentsConfig_to_mldev(getv(from_object, ['config']), to_object)

  return to_object


def _ListCachedContentsParameters_to_vertex(
    from_object: Union[dict[str, Any], object],
    parent_object: Optional[dict[str, Any]] = None,
) -> dict[str, Any]:
  to_object: dict[str, Any] = {}
  if getv(from_object, ['config']) is not None:
    _ListCachedContentsConfig_to_vertex(
        getv(from_object, ['config']), to_object
    )

  return to_object


def _ListCachedContentsResponse_from_mldev(
    from_object: Union[dict[str, Any], object],
    parent_object: Optional[dict[str, Any]] = None,
) -> dict[str, Any]:
  to_object: dict[str, Any] = {}
  if getv(from_object, ['sdkHttpResponse']) is not None:
    setv(
        to_object, ['sdk_http_response'], getv(from_object, ['sdkHttpResponse'])
    )

  if getv(from_object, ['nextPageToken']) is not None:
    setv(to_object, ['next_page_token'], getv(from_object, ['nextPageToken']))

  if getv(from_object, ['cachedContents']) is not None:
    setv(
        to_object,
        ['cached_contents'],
        [item for item in getv(from_object, ['cachedContents'])],
    )

  return to_object


def _ListCachedContentsResponse_from_vertex(
    from_object: Union[dict[str, Any], object],
    parent_object: Optional[dict[str, Any]] = None,
) -> dict[str, Any]:
  to_object: dict[str, Any] = {}
  if getv(from_object, ['sdkHttpResponse']) is not None:
    setv(
        to_object, ['sdk_http_response'], getv(from_object, ['sdkHttpResponse'])
    )

  if getv(from_object, ['nextPageToken']) is not None:
    setv(to_object, ['next_page_token'], getv(from_object, ['nextPageToken']))

  if getv(from_object, ['cachedContents']) is not None:
    setv(
        to_object,
        ['cached_contents'],
        [item for item in getv(from_object, ['cachedContents'])],
    )

  return to_object


def _Part_to_mldev(
    from_object: Union[dict[str, Any], object],
    parent_object: Optional[dict[str, Any]] = None,
) -> dict[str, Any]:
  to_object: dict[str, Any] = {}
  if getv(from_object, ['function_call']) is not None:
    setv(to_object, ['functionCall'], getv(from_object, ['function_call']))

  if getv(from_object, ['code_execution_result']) is not None:
    setv(
        to_object,
        ['codeExecutionResult'],
        getv(from_object, ['code_execution_result']),
    )

  if getv(from_object, ['executable_code']) is not None:
    setv(to_object, ['executableCode'], getv(from_object, ['executable_code']))

  if getv(from_object, ['file_data']) is not None:
    setv(
        to_object,
        ['fileData'],
        _FileData_to_mldev(getv(from_object, ['file_data']), to_object),
    )

  if getv(from_object, ['function_response']) is not None:
    setv(
        to_object,
        ['functionResponse'],
        getv(from_object, ['function_response']),
    )

  if getv(from_object, ['inline_data']) is not None:
    setv(
        to_object,
        ['inlineData'],
        _Blob_to_mldev(getv(from_object, ['inline_data']), to_object),
    )

  if getv(from_object, ['text']) is not None:
    setv(to_object, ['text'], getv(from_object, ['text']))

  if getv(from_object, ['thought']) is not None:
    setv(to_object, ['thought'], getv(from_object, ['thought']))

  if getv(from_object, ['thought_signature']) is not None:
    setv(
        to_object,
        ['thoughtSignature'],
        getv(from_object, ['thought_signature']),
    )

  if getv(from_object, ['video_metadata']) is not None:
    setv(to_object, ['videoMetadata'], getv(from_object, ['video_metadata']))

  return to_object


def _Tool_to_mldev(
    from_object: Union[dict[str, Any], object],
    parent_object: Optional[dict[str, Any]] = None,
) -> dict[str, Any]:
  to_object: dict[str, Any] = {}
  if getv(from_object, ['function_declarations']) is not None:
    setv(
        to_object,
        ['functionDeclarations'],
        [item for item in getv(from_object, ['function_declarations'])],
    )

  if getv(from_object, ['retrieval']) is not None:
    raise ValueError('retrieval parameter is not supported in Gemini API.')

  if getv(from_object, ['google_search_retrieval']) is not None:
    setv(
        to_object,
        ['googleSearchRetrieval'],
        getv(from_object, ['google_search_retrieval']),
    )

  if getv(from_object, ['computer_use']) is not None:
    setv(to_object, ['computerUse'], getv(from_object, ['computer_use']))

  if getv(from_object, ['file_search']) is not None:
    setv(to_object, ['fileSearch'], getv(from_object, ['file_search']))

  if getv(from_object, ['code_execution']) is not None:
    setv(to_object, ['codeExecution'], getv(from_object, ['code_execution']))

  if getv(from_object, ['enterprise_web_search']) is not None:
    raise ValueError(
        'enterprise_web_search parameter is not supported in Gemini API.'
    )

  if getv(from_object, ['google_maps']) is not None:
    setv(
        to_object,
        ['googleMaps'],
        _GoogleMaps_to_mldev(getv(from_object, ['google_maps']), to_object),
    )

  if getv(from_object, ['google_search']) is not None:
    setv(
        to_object,
        ['googleSearch'],
        _GoogleSearch_to_mldev(getv(from_object, ['google_search']), to_object),
    )

  if getv(from_object, ['url_context']) is not None:
    setv(to_object, ['urlContext'], getv(from_object, ['url_context']))

  return to_object


def _Tool_to_vertex(
    from_object: Union[dict[str, Any], object],
    parent_object: Optional[dict[str, Any]] = None,
) -> dict[str, Any]:
  to_object: dict[str, Any] = {}
  if getv(from_object, ['function_declarations']) is not None:
    setv(
        to_object,
        ['functionDeclarations'],
        [
            _FunctionDeclaration_to_vertex(item, to_object)
            for item in getv(from_object, ['function_declarations'])
        ],
    )

  if getv(from_object, ['retrieval']) is not None:
    setv(to_object, ['retrieval'], getv(from_object, ['retrieval']))

  if getv(from_object, ['google_search_retrieval']) is not None:
    setv(
        to_object,
        ['googleSearchRetrieval'],
        getv(from_object, ['google_search_retrieval']),
    )

  if getv(from_object, ['computer_use']) is not None:
    setv(to_object, ['computerUse'], getv(from_object, ['computer_use']))

  if getv(from_object, ['file_search']) is not None:
    raise ValueError('file_search parameter is not supported in Vertex AI.')

  if getv(from_object, ['code_execution']) is not None:
    setv(to_object, ['codeExecution'], getv(from_object, ['code_execution']))

  if getv(from_object, ['enterprise_web_search']) is not None:
    setv(
        to_object,
        ['enterpriseWebSearch'],
        getv(from_object, ['enterprise_web_search']),
    )

  if getv(from_object, ['google_maps']) is not None:
    setv(to_object, ['googleMaps'], getv(from_object, ['google_maps']))

  if getv(from_object, ['google_search']) is not None:
    setv(to_object, ['googleSearch'], getv(from_object, ['google_search']))

  if getv(from_object, ['url_context']) is not None:
    setv(to_object, ['urlContext'], getv(from_object, ['url_context']))

  return to_object


def _UpdateCachedContentConfig_to_mldev(
    from_object: Union[dict[str, Any], object],
    parent_object: Optional[dict[str, Any]] = None,
) -> dict[str, Any]:
  to_object: dict[str, Any] = {}

  if getv(from_object, ['ttl']) is not None:
    setv(parent_object, ['ttl'], getv(from_object, ['ttl']))

  if getv(from_object, ['expire_time']) is not None:
    setv(parent_object, ['expireTime'], getv(from_object, ['expire_time']))

  return to_object


def _UpdateCachedContentConfig_to_vertex(
    from_object: Union[dict[str, Any], object],
    parent_object: Optional[dict[str, Any]] = None,
) -> dict[str, Any]:
  to_object: dict[str, Any] = {}

  if getv(from_object, ['ttl']) is not None:
    setv(parent_object, ['ttl'], getv(from_object, ['ttl']))

  if getv(from_object, ['expire_time']) is not None:
    setv(parent_object, ['expireTime'], getv(from_object, ['expire_time']))

  return to_object


def _UpdateCachedContentParameters_to_mldev(
    api_client: BaseApiClient,
    from_object: Union[dict[str, Any], object],
    parent_object: Optional[dict[str, Any]] = None,
) -> dict[str, Any]:
  to_object: dict[str, Any] = {}
  if getv(from_object, ['name']) is not None:
    setv(
        to_object,
        ['_url', 'name'],
        t.t_cached_content_name(api_client, getv(from_object, ['name'])),
    )

  if getv(from_object, ['config']) is not None:
    _UpdateCachedContentConfig_to_mldev(
        getv(from_object, ['config']), to_object
    )

  return to_object


def _UpdateCachedContentParameters_to_vertex(
    api_client: BaseApiClient,
    from_object: Union[dict[str, Any], object],
    parent_object: Optional[dict[str, Any]] = None,
) -> dict[str, Any]:
  to_object: dict[str, Any] = {}
  if getv(from_object, ['name']) is not None:
    setv(
        to_object,
        ['_url', 'name'],
        t.t_cached_content_name(api_client, getv(from_object, ['name'])),
    )

  if getv(from_object, ['config']) is not None:
    _UpdateCachedContentConfig_to_vertex(
        getv(from_object, ['config']), to_object
    )

  return to_object


class Caches(_api_module.BaseModule):

  def create(
      self,
      *,
      model: str,
      config: Optional[types.CreateCachedContentConfigOrDict] = None,
  ) -> types.CachedContent:
    """Creates a cached contents resource.

    Usage:

    .. code-block:: python

      contents = ... // Initialize the content to cache.
      response = client.caches.create(
          model= ... // The publisher model id
          contents=contents,
          config={
              'display_name': 'test cache',
              'system_instruction': 'What is the sum of the two pdfs?',
              'ttl': '86400s',
          },
      )
    """

    parameter_model = types._CreateCachedContentParameters(
        model=model,
        config=config,
    )

    request_url_dict: Optional[dict[str, str]]

    if self._api_client.vertexai:
      request_dict = _CreateCachedContentParameters_to_vertex(
          self._api_client, parameter_model
      )
      request_url_dict = request_dict.get('_url')
      if request_url_dict:
        path = 'cachedContents'.format_map(request_url_dict)
      else:
        path = 'cachedContents'
    else:
      request_dict = _CreateCachedContentParameters_to_mldev(
          self._api_client, parameter_model
      )
      request_url_dict = request_dict.get('_url')
      if request_url_dict:
        path = 'cachedContents'.format_map(request_url_dict)
      else:
        path = 'cachedContents'
    query_params = request_dict.get('_query')
    if query_params:
      path = f'{path}?{urlencode(query_params)}'
    # TODO: remove the hack that pops config.
    request_dict.pop('config', None)

    http_options: Optional[types.HttpOptions] = None
    if (
        parameter_model.config is not None
        and parameter_model.config.http_options is not None
    ):
      http_options = parameter_model.config.http_options

    request_dict = _common.convert_to_dict(request_dict)
    request_dict = _common.encode_unserializable_types(request_dict)

    response = self._api_client.request(
        'post', path, request_dict, http_options
    )

    response_dict = {} if not response.body else json.loads(response.body)

    return_value = types.CachedContent._from_response(
        response=response_dict, kwargs=parameter_model.model_dump()
    )

    self._api_client._verify_response(return_value)
    return return_value

  def get(
      self,
      *,
      name: str,
      config: Optional[types.GetCachedContentConfigOrDict] = None,
  ) -> types.CachedContent:
    """Gets cached content configurations.

    .. code-block:: python

      client.caches.get(name= ... ) // The server-generated resource name.
    """

    parameter_model = types._GetCachedContentParameters(
        name=name,
        config=config,
    )

    request_url_dict: Optional[dict[str, str]]

    if self._api_client.vertexai:
      request_dict = _GetCachedContentParameters_to_vertex(
          self._api_client, parameter_model
      )
      request_url_dict = request_dict.get('_url')
      if request_url_dict:
        path = '{name}'.format_map(request_url_dict)
      else:
        path = '{name}'
    else:
      request_dict = _GetCachedContentParameters_to_mldev(
          self._api_client, parameter_model
      )
      request_url_dict = request_dict.get('_url')
      if request_url_dict:
        path = '{name}'.format_map(request_url_dict)
      else:
        path = '{name}'
    query_params = request_dict.get('_query')
    if query_params:
      path = f'{path}?{urlencode(query_params)}'
    # TODO: remove the hack that pops config.
    request_dict.pop('config', None)

    http_options: Optional[types.HttpOptions] = None
    if (
        parameter_model.config is not None
        and parameter_model.config.http_options is not None
    ):
      http_options = parameter_model.config.http_options

    request_dict = _common.convert_to_dict(request_dict)
    request_dict = _common.encode_unserializable_types(request_dict)

    response = self._api_client.request('get', path, request_dict, http_options)

    response_dict = {} if not response.body else json.loads(response.body)

    return_value = types.CachedContent._from_response(
        response=response_dict, kwargs=parameter_model.model_dump()
    )

    self._api_client._verify_response(return_value)
    return return_value

  def delete(
      self,
      *,
      name: str,
      config: Optional[types.DeleteCachedContentConfigOrDict] = None,
  ) -> types.DeleteCachedContentResponse:
    """Deletes cached content.

    Usage:

    .. code-block:: python

      client.caches.delete(name= ... ) // The server-generated resource name.
    """

    parameter_model = types._DeleteCachedContentParameters(
        name=name,
        config=config,
    )

    request_url_dict: Optional[dict[str, str]]

    if self._api_client.vertexai:
      request_dict = _DeleteCachedContentParameters_to_vertex(
          self._api_client, parameter_model
      )
      request_url_dict = request_dict.get('_url')
      if request_url_dict:
        path = '{name}'.format_map(request_url_dict)
      else:
        path = '{name}'
    else:
      request_dict = _DeleteCachedContentParameters_to_mldev(
          self._api_client, parameter_model
      )
      request_url_dict = request_dict.get('_url')
      if request_url_dict:
        path = '{name}'.format_map(request_url_dict)
      else:
        path = '{name}'
    query_params = request_dict.get('_query')
    if query_params:
      path = f'{path}?{urlencode(query_params)}'
    # TODO: remove the hack that pops config.
    request_dict.pop('config', None)

    http_options: Optional[types.HttpOptions] = None
    if (
        parameter_model.config is not None
        and parameter_model.config.http_options is not None
    ):
      http_options = parameter_model.config.http_options

    request_dict = _common.convert_to_dict(request_dict)
    request_dict = _common.encode_unserializable_types(request_dict)

    response = self._api_client.request(
        'delete', path, request_dict, http_options
    )

    response_dict = {} if not response.body else json.loads(response.body)

    if self._api_client.vertexai:
      response_dict = _DeleteCachedContentResponse_from_vertex(response_dict)

    if not self._api_client.vertexai:
      response_dict = _DeleteCachedContentResponse_from_mldev(response_dict)

    return_value = types.DeleteCachedContentResponse._from_response(
        response=response_dict, kwargs=parameter_model.model_dump()
    )
    return_value.sdk_http_response = types.HttpResponse(
        headers=response.headers
    )
    self._api_client._verify_response(return_value)
    return return_value

  def update(
      self,
      *,
      name: str,
      config: Optional[types.UpdateCachedContentConfigOrDict] = None,
  ) -> types.CachedContent:
    """Updates cached content configurations.

    .. code-block:: python

      response = client.caches.update(
          name= ... // The server-generated resource name.
          config={
              'ttl': '7600s',
          },
      )
    """

    parameter_model = types._UpdateCachedContentParameters(
        name=name,
        config=config,
    )

    request_url_dict: Optional[dict[str, str]]

    if self._api_client.vertexai:
      request_dict = _UpdateCachedContentParameters_to_vertex(
          self._api_client, parameter_model
      )
      request_url_dict = request_dict.get('_url')
      if request_url_dict:
        path = '{name}'.format_map(request_url_dict)
      else:
        path = '{name}'
    else:
      request_dict = _UpdateCachedContentParameters_to_mldev(
          self._api_client, parameter_model
      )
      request_url_dict = request_dict.get('_url')
      if request_url_dict:
        path = '{name}'.format_map(request_url_dict)
      else:
        path = '{name}'
    query_params = request_dict.get('_query')
    if query_params:
      path = f'{path}?{urlencode(query_params)}'
    # TODO: remove the hack that pops config.
    request_dict.pop('config', None)

    http_options: Optional[types.HttpOptions] = None
    if (
        parameter_model.config is not None
        and parameter_model.config.http_options is not None
    ):
      http_options = parameter_model.config.http_options

    request_dict = _common.convert_to_dict(request_dict)
    request_dict = _common.encode_unserializable_types(request_dict)

    response = self._api_client.request(
        'patch', path, request_dict, http_options
    )

    response_dict = {} if not response.body else json.loads(response.body)

    return_value = types.CachedContent._from_response(
        response=response_dict, kwargs=parameter_model.model_dump()
    )

    self._api_client._verify_response(return_value)
    return return_value

  def _list(
      self, *, config: Optional[types.ListCachedContentsConfigOrDict] = None
  ) -> types.ListCachedContentsResponse:
    """Lists cached content configurations.

    .. code-block:: python

      cached_contents = client.caches.list(config={'page_size': 2})
      for cached_content in cached_contents:
        print(cached_content)
    """

    parameter_model = types._ListCachedContentsParameters(
        config=config,
    )

    request_url_dict: Optional[dict[str, str]]

    if self._api_client.vertexai:
      request_dict = _ListCachedContentsParameters_to_vertex(parameter_model)
      request_url_dict = request_dict.get('_url')
      if request_url_dict:
        path = 'cachedContents'.format_map(request_url_dict)
      else:
        path = 'cachedContents'
    else:
      request_dict = _ListCachedContentsParameters_to_mldev(parameter_model)
      request_url_dict = request_dict.get('_url')
      if request_url_dict:
        path = 'cachedContents'.format_map(request_url_dict)
      else:
        path = 'cachedContents'
    query_params = request_dict.get('_query')
    if query_params:
      path = f'{path}?{urlencode(query_params)}'
    # TODO: remove the hack that pops config.
    request_dict.pop('config', None)

    http_options: Optional[types.HttpOptions] = None
    if (
        parameter_model.config is not None
        and parameter_model.config.http_options is not None
    ):
      http_options = parameter_model.config.http_options

    request_dict = _common.convert_to_dict(request_dict)
    request_dict = _common.encode_unserializable_types(request_dict)

    response = self._api_client.request('get', path, request_dict, http_options)

    response_dict = {} if not response.body else json.loads(response.body)

    if self._api_client.vertexai:
      response_dict = _ListCachedContentsResponse_from_vertex(response_dict)

    if not self._api_client.vertexai:
      response_dict = _ListCachedContentsResponse_from_mldev(response_dict)

    return_value = types.ListCachedContentsResponse._from_response(
        response=response_dict, kwargs=parameter_model.model_dump()
    )
    return_value.sdk_http_response = types.HttpResponse(
        headers=response.headers
    )
    self._api_client._verify_response(return_value)
    return return_value

  def list(
      self, *, config: Optional[types.ListCachedContentsConfigOrDict] = None
  ) -> Pager[types.CachedContent]:
    return Pager(
        'cached_contents',
        self._list,
        self._list(config=config),
        config,
    )


class AsyncCaches(_api_module.BaseModule):

  async def create(
      self,
      *,
      model: str,
      config: Optional[types.CreateCachedContentConfigOrDict] = None,
  ) -> types.CachedContent:
    """Creates a cached contents resource.

    Usage:

    .. code-block:: python

      contents = ... // Initialize the content to cache.
      response = await client.aio.caches.create(
          model= ... // The publisher model id
          contents=contents,
          config={
              'display_name': 'test cache',
              'system_instruction': 'What is the sum of the two pdfs?',
              'ttl': '86400s',
          },
      )
    """

    parameter_model = types._CreateCachedContentParameters(
        model=model,
        config=config,
    )

    request_url_dict: Optional[dict[str, str]]

    if self._api_client.vertexai:
      request_dict = _CreateCachedContentParameters_to_vertex(
          self._api_client, parameter_model
      )
      request_url_dict = request_dict.get('_url')
      if request_url_dict:
        path = 'cachedContents'.format_map(request_url_dict)
      else:
        path = 'cachedContents'
    else:
      request_dict = _CreateCachedContentParameters_to_mldev(
          self._api_client, parameter_model
      )
      request_url_dict = request_dict.get('_url')
      if request_url_dict:
        path = 'cachedContents'.format_map(request_url_dict)
      else:
        path = 'cachedContents'
    query_params = request_dict.get('_query')
    if query_params:
      path = f'{path}?{urlencode(query_params)}'
    # TODO: remove the hack that pops config.
    request_dict.pop('config', None)

    http_options: Optional[types.HttpOptions] = None
    if (
        parameter_model.config is not None
        and parameter_model.config.http_options is not None
    ):
      http_options = parameter_model.config.http_options

    request_dict = _common.convert_to_dict(request_dict)
    request_dict = _common.encode_unserializable_types(request_dict)

    response = await self._api_client.async_request(
        'post', path, request_dict, http_options
    )

    response_dict = {} if not response.body else json.loads(response.body)

    return_value = types.CachedContent._from_response(
        response=response_dict, kwargs=parameter_model.model_dump()
    )

    self._api_client._verify_response(return_value)
    return return_value

  async def get(
      self,
      *,
      name: str,
      config: Optional[types.GetCachedContentConfigOrDict] = None,
  ) -> types.CachedContent:
    """Gets cached content configurations.

    .. code-block:: python

      await client.aio.caches.get(name= ... ) // The server-generated resource
      name.
    """

    parameter_model = types._GetCachedContentParameters(
        name=name,
        config=config,
    )

    request_url_dict: Optional[dict[str, str]]

    if self._api_client.vertexai:
      request_dict = _GetCachedContentParameters_to_vertex(
          self._api_client, parameter_model
      )
      request_url_dict = request_dict.get('_url')
      if request_url_dict:
        path = '{name}'.format_map(request_url_dict)
      else:
        path = '{name}'
    else:
      request_dict = _GetCachedContentParameters_to_mldev(
          self._api_client, parameter_model
      )
      request_url_dict = request_dict.get('_url')
      if request_url_dict:
        path = '{name}'.format_map(request_url_dict)
      else:
        path = '{name}'
    query_params = request_dict.get('_query')
    if query_params:
      path = f'{path}?{urlencode(query_params)}'
    # TODO: remove the hack that pops config.
    request_dict.pop('config', None)

    http_options: Optional[types.HttpOptions] = None
    if (
        parameter_model.config is not None
        and parameter_model.config.http_options is not None
    ):
      http_options = parameter_model.config.http_options

    request_dict = _common.convert_to_dict(request_dict)
    request_dict = _common.encode_unserializable_types(request_dict)

    response = await self._api_client.async_request(
        'get', path, request_dict, http_options
    )

    response_dict = {} if not response.body else json.loads(response.body)

    return_value = types.CachedContent._from_response(
        response=response_dict, kwargs=parameter_model.model_dump()
    )

    self._api_client._verify_response(return_value)
    return return_value

  async def delete(
      self,
      *,
      name: str,
      config: Optional[types.DeleteCachedContentConfigOrDict] = None,
  ) -> types.DeleteCachedContentResponse:
    """Deletes cached content.

    Usage:

    .. code-block:: python

      await client.aio.caches.delete(name= ... ) // The server-generated
      resource name.
    """

    parameter_model = types._DeleteCachedContentParameters(
        name=name,
        config=config,
    )

    request_url_dict: Optional[dict[str, str]]

    if self._api_client.vertexai:
      request_dict = _DeleteCachedContentParameters_to_vertex(
          self._api_client, parameter_model
      )
      request_url_dict = request_dict.get('_url')
      if request_url_dict:
        path = '{name}'.format_map(request_url_dict)
      else:
        path = '{name}'
    else:
      request_dict = _DeleteCachedContentParameters_to_mldev(
          self._api_client, parameter_model
      )
      request_url_dict = request_dict.get('_url')
      if request_url_dict:
        path = '{name}'.format_map(request_url_dict)
      else:
        path = '{name}'
    query_params = request_dict.get('_query')
    if query_params:
      path = f'{path}?{urlencode(query_params)}'
    # TODO: remove the hack that pops config.
    request_dict.pop('config', None)

    http_options: Optional[types.HttpOptions] = None
    if (
        parameter_model.config is not None
        and parameter_model.config.http_options is not None
    ):
      http_options = parameter_model.config.http_options

    request_dict = _common.convert_to_dict(request_dict)
    request_dict = _common.encode_unserializable_types(request_dict)

    response = await self._api_client.async_request(
        'delete', path, request_dict, http_options
    )

    response_dict = {} if not response.body else json.loads(response.body)

    if self._api_client.vertexai:
      response_dict = _DeleteCachedContentResponse_from_vertex(response_dict)

    if not self._api_client.vertexai:
      response_dict = _DeleteCachedContentResponse_from_mldev(response_dict)

    return_value = types.DeleteCachedContentResponse._from_response(
        response=response_dict, kwargs=parameter_model.model_dump()
    )
    return_value.sdk_http_response = types.HttpResponse(
        headers=response.headers
    )
    self._api_client._verify_response(return_value)
    return return_value

  async def update(
      self,
      *,
      name: str,
      config: Optional[types.UpdateCachedContentConfigOrDict] = None,
  ) -> types.CachedContent:
    """Updates cached content configurations.

    .. code-block:: python

      response = await client.aio.caches.update(
          name= ... // The server-generated resource name.
          config={
              'ttl': '7600s',
          },
      )
    """

    parameter_model = types._UpdateCachedContentParameters(
        name=name,
        config=config,
    )

    request_url_dict: Optional[dict[str, str]]

    if self._api_client.vertexai:
      request_dict = _UpdateCachedContentParameters_to_vertex(
          self._api_client, parameter_model
      )
      request_url_dict = request_dict.get('_url')
      if request_url_dict:
        path = '{name}'.format_map(request_url_dict)
      else:
        path = '{name}'
    else:
      request_dict = _UpdateCachedContentParameters_to_mldev(
          self._api_client, parameter_model
      )
      request_url_dict = request_dict.get('_url')
      if request_url_dict:
        path = '{name}'.format_map(request_url_dict)
      else:
        path = '{name}'
    query_params = request_dict.get('_query')
    if query_params:
      path = f'{path}?{urlencode(query_params)}'
    # TODO: remove the hack that pops config.
    request_dict.pop('config', None)

    http_options: Optional[types.HttpOptions] = None
    if (
        parameter_model.config is not None
        and parameter_model.config.http_options is not None
    ):
      http_options = parameter_model.config.http_options

    request_dict = _common.convert_to_dict(request_dict)
    request_dict = _common.encode_unserializable_types(request_dict)

    response = await self._api_client.async_request(
        'patch', path, request_dict, http_options
    )

    response_dict = {} if not response.body else json.loads(response.body)

    return_value = types.CachedContent._from_response(
        response=response_dict, kwargs=parameter_model.model_dump()
    )

    self._api_client._verify_response(return_value)
    return return_value

  async def _list(
      self, *, config: Optional[types.ListCachedContentsConfigOrDict] = None
  ) -> types.ListCachedContentsResponse:
    """Lists cached content configurations.

    .. code-block:: python

      cached_contents = await client.aio.caches.list(config={'page_size': 2})
      async for cached_content in cached_contents:
        print(cached_content)
    """

    parameter_model = types._ListCachedContentsParameters(
        config=config,
    )

    request_url_dict: Optional[dict[str, str]]

    if self._api_client.vertexai:
      request_dict = _ListCachedContentsParameters_to_vertex(parameter_model)
      request_url_dict = request_dict.get('_url')
      if request_url_dict:
        path = 'cachedContents'.format_map(request_url_dict)
      else:
        path = 'cachedContents'
    else:
      request_dict = _ListCachedContentsParameters_to_mldev(parameter_model)
      request_url_dict = request_dict.get('_url')
      if request_url_dict:
        path = 'cachedContents'.format_map(request_url_dict)
      else:
        path = 'cachedContents'
    query_params = request_dict.get('_query')
    if query_params:
      path = f'{path}?{urlencode(query_params)}'
    # TODO: remove the hack that pops config.
    request_dict.pop('config', None)

    http_options: Optional[types.HttpOptions] = None
    if (
        parameter_model.config is not None
        and parameter_model.config.http_options is not None
    ):
      http_options = parameter_model.config.http_options

    request_dict = _common.convert_to_dict(request_dict)
    request_dict = _common.encode_unserializable_types(request_dict)

    response = await self._api_client.async_request(
        'get', path, request_dict, http_options
    )

    response_dict = {} if not response.body else json.loads(response.body)

    if self._api_client.vertexai:
      response_dict = _ListCachedContentsResponse_from_vertex(response_dict)

    if not self._api_client.vertexai:
      response_dict = _ListCachedContentsResponse_from_mldev(response_dict)

    return_value = types.ListCachedContentsResponse._from_response(
        response=response_dict, kwargs=parameter_model.model_dump()
    )
    return_value.sdk_http_response = types.HttpResponse(
        headers=response.headers
    )
    self._api_client._verify_response(return_value)
    return return_value

  async def list(
      self, *, config: Optional[types.ListCachedContentsConfigOrDict] = None
  ) -> AsyncPager[types.CachedContent]:
    return AsyncPager(
        'cached_contents',
        self._list,
        await self._list(config=config),
        config,
    )
