diff --git a/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/gapic_version.py b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/gapic_version.py new file mode 100644 index 0000000000000000000000000000000000000000..e51340f75942321a83eef7f8127be02a12dddf59 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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. +# +__version__ = "0.6.15" # {x-release-please-version} diff --git a/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/__init__.py b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8f6cf068242c282e78ed205a7a66af26b6f1928f --- /dev/null +++ b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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. +# diff --git a/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/cache_service/__init__.py b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/cache_service/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2f8bc2e1ba03381cc6cc1c2b6fd75599d1d08414 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/cache_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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. +# +from .async_client import CacheServiceAsyncClient +from .client import CacheServiceClient + +__all__ = ( + "CacheServiceClient", + "CacheServiceAsyncClient", +) diff --git a/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/cache_service/__pycache__/pagers.cpython-311.pyc b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/cache_service/__pycache__/pagers.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9cce0545f91fce13efd1bf4d61d4321e785a7934 Binary files /dev/null and b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/cache_service/__pycache__/pagers.cpython-311.pyc differ diff --git a/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/cache_service/async_client.py b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/cache_service/async_client.py new file mode 100644 index 0000000000000000000000000000000000000000..ff56bab132235fbafbe7baba1e208b120ad2d1a4 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/cache_service/async_client.py @@ -0,0 +1,950 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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. +# +from collections import OrderedDict +import logging as std_logging +import re +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) + +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.api_core.client_options import ClientOptions +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.ai.generativelanguage_v1alpha import gapic_version as package_version + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + +from google.ai.generativelanguage_v1alpha.services.cache_service import pagers +from google.ai.generativelanguage_v1alpha.types import ( + cached_content as gag_cached_content, +) +from google.ai.generativelanguage_v1alpha.types import cache_service +from google.ai.generativelanguage_v1alpha.types import cached_content +from google.ai.generativelanguage_v1alpha.types import content + +from .client import CacheServiceClient +from .transports.base import DEFAULT_CLIENT_INFO, CacheServiceTransport +from .transports.grpc_asyncio import CacheServiceGrpcAsyncIOTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class CacheServiceAsyncClient: + """API for managing cache of content (CachedContent resources) + that can be used in GenerativeService requests. This way + generate content requests can benefit from preprocessing work + being done earlier, possibly lowering their computational cost. + It is intended to be used with large contexts. + """ + + _client: CacheServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = CacheServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = CacheServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = CacheServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = CacheServiceClient._DEFAULT_UNIVERSE + + cached_content_path = staticmethod(CacheServiceClient.cached_content_path) + parse_cached_content_path = staticmethod( + CacheServiceClient.parse_cached_content_path + ) + model_path = staticmethod(CacheServiceClient.model_path) + parse_model_path = staticmethod(CacheServiceClient.parse_model_path) + common_billing_account_path = staticmethod( + CacheServiceClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + CacheServiceClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod(CacheServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(CacheServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(CacheServiceClient.common_organization_path) + parse_common_organization_path = staticmethod( + CacheServiceClient.parse_common_organization_path + ) + common_project_path = staticmethod(CacheServiceClient.common_project_path) + parse_common_project_path = staticmethod( + CacheServiceClient.parse_common_project_path + ) + common_location_path = staticmethod(CacheServiceClient.common_location_path) + parse_common_location_path = staticmethod( + CacheServiceClient.parse_common_location_path + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + CacheServiceAsyncClient: The constructed client. + """ + return CacheServiceClient.from_service_account_info.__func__(CacheServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + CacheServiceAsyncClient: The constructed client. + """ + return CacheServiceClient.from_service_account_file.__func__(CacheServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return CacheServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> CacheServiceTransport: + """Returns the transport used by the client instance. + + Returns: + CacheServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = CacheServiceClient.get_transport_class + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, CacheServiceTransport, Callable[..., CacheServiceTransport]] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the cache service async client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,CacheServiceTransport,Callable[..., CacheServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the CacheServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = CacheServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.ai.generativelanguage_v1alpha.CacheServiceAsyncClient`.", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.CacheService", + "universeDomain": getattr( + self._client._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._client._transport, "_credentials") + else { + "serviceName": "google.ai.generativelanguage.v1alpha.CacheService", + "credentialsType": None, + }, + ) + + async def list_cached_contents( + self, + request: Optional[Union[cache_service.ListCachedContentsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListCachedContentsAsyncPager: + r"""Lists CachedContents. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ai import generativelanguage_v1alpha + + async def sample_list_cached_contents(): + # Create a client + client = generativelanguage_v1alpha.CacheServiceAsyncClient() + + # Initialize request argument(s) + request = generativelanguage_v1alpha.ListCachedContentsRequest( + ) + + # Make the request + page_result = client.list_cached_contents(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.ai.generativelanguage_v1alpha.types.ListCachedContentsRequest, dict]]): + The request object. Request to list CachedContents. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ai.generativelanguage_v1alpha.services.cache_service.pagers.ListCachedContentsAsyncPager: + Response with CachedContents list. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, cache_service.ListCachedContentsRequest): + request = cache_service.ListCachedContentsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_cached_contents + ] + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListCachedContentsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_cached_content( + self, + request: Optional[Union[cache_service.CreateCachedContentRequest, dict]] = None, + *, + cached_content: Optional[gag_cached_content.CachedContent] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gag_cached_content.CachedContent: + r"""Creates CachedContent resource. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ai import generativelanguage_v1alpha + + async def sample_create_cached_content(): + # Create a client + client = generativelanguage_v1alpha.CacheServiceAsyncClient() + + # Initialize request argument(s) + request = generativelanguage_v1alpha.CreateCachedContentRequest( + ) + + # Make the request + response = await client.create_cached_content(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.ai.generativelanguage_v1alpha.types.CreateCachedContentRequest, dict]]): + The request object. Request to create CachedContent. + cached_content (:class:`google.ai.generativelanguage_v1alpha.types.CachedContent`): + Required. The cached content to + create. + + This corresponds to the ``cached_content`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ai.generativelanguage_v1alpha.types.CachedContent: + Content that has been preprocessed + and can be used in subsequent request to + GenerativeService. + + Cached content can be only used with + model it was created for. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([cached_content]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, cache_service.CreateCachedContentRequest): + request = cache_service.CreateCachedContentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if cached_content is not None: + request.cached_content = cached_content + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_cached_content + ] + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_cached_content( + self, + request: Optional[Union[cache_service.GetCachedContentRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> cached_content.CachedContent: + r"""Reads CachedContent resource. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ai import generativelanguage_v1alpha + + async def sample_get_cached_content(): + # Create a client + client = generativelanguage_v1alpha.CacheServiceAsyncClient() + + # Initialize request argument(s) + request = generativelanguage_v1alpha.GetCachedContentRequest( + name="name_value", + ) + + # Make the request + response = await client.get_cached_content(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.ai.generativelanguage_v1alpha.types.GetCachedContentRequest, dict]]): + The request object. Request to read CachedContent. + name (:class:`str`): + Required. The resource name referring to the content + cache entry. Format: ``cachedContents/{id}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ai.generativelanguage_v1alpha.types.CachedContent: + Content that has been preprocessed + and can be used in subsequent request to + GenerativeService. + + Cached content can be only used with + model it was created for. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, cache_service.GetCachedContentRequest): + request = cache_service.GetCachedContentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_cached_content + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_cached_content( + self, + request: Optional[Union[cache_service.UpdateCachedContentRequest, dict]] = None, + *, + cached_content: Optional[gag_cached_content.CachedContent] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gag_cached_content.CachedContent: + r"""Updates CachedContent resource (only expiration is + updatable). + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ai import generativelanguage_v1alpha + + async def sample_update_cached_content(): + # Create a client + client = generativelanguage_v1alpha.CacheServiceAsyncClient() + + # Initialize request argument(s) + request = generativelanguage_v1alpha.UpdateCachedContentRequest( + ) + + # Make the request + response = await client.update_cached_content(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.ai.generativelanguage_v1alpha.types.UpdateCachedContentRequest, dict]]): + The request object. Request to update CachedContent. + cached_content (:class:`google.ai.generativelanguage_v1alpha.types.CachedContent`): + Required. The content cache entry to + update + + This corresponds to the ``cached_content`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The list of fields to update. + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ai.generativelanguage_v1alpha.types.CachedContent: + Content that has been preprocessed + and can be used in subsequent request to + GenerativeService. + + Cached content can be only used with + model it was created for. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([cached_content, update_mask]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, cache_service.UpdateCachedContentRequest): + request = cache_service.UpdateCachedContentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if cached_content is not None: + request.cached_content = cached_content + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_cached_content + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("cached_content.name", request.cached_content.name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_cached_content( + self, + request: Optional[Union[cache_service.DeleteCachedContentRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes CachedContent resource. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ai import generativelanguage_v1alpha + + async def sample_delete_cached_content(): + # Create a client + client = generativelanguage_v1alpha.CacheServiceAsyncClient() + + # Initialize request argument(s) + request = generativelanguage_v1alpha.DeleteCachedContentRequest( + name="name_value", + ) + + # Make the request + await client.delete_cached_content(request=request) + + Args: + request (Optional[Union[google.ai.generativelanguage_v1alpha.types.DeleteCachedContentRequest, dict]]): + The request object. Request to delete CachedContent. + name (:class:`str`): + Required. The resource name referring to the content + cache entry Format: ``cachedContents/{id}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, cache_service.DeleteCachedContentRequest): + request = cache_service.DeleteCachedContentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_cached_content + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self) -> "CacheServiceAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + + +__all__ = ("CacheServiceAsyncClient",) diff --git a/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/cache_service/client.py b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/cache_service/client.py new file mode 100644 index 0000000000000000000000000000000000000000..ef87e6cbf854a3d2afac30988a39e85d4dc1b48a --- /dev/null +++ b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/cache_service/client.py @@ -0,0 +1,1340 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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. +# +from collections import OrderedDict +import logging as std_logging +import os +import re +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) +import warnings + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.ai.generativelanguage_v1alpha import gapic_version as package_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + +from google.ai.generativelanguage_v1alpha.services.cache_service import pagers +from google.ai.generativelanguage_v1alpha.types import ( + cached_content as gag_cached_content, +) +from google.ai.generativelanguage_v1alpha.types import cache_service +from google.ai.generativelanguage_v1alpha.types import cached_content +from google.ai.generativelanguage_v1alpha.types import content + +from .transports.base import DEFAULT_CLIENT_INFO, CacheServiceTransport +from .transports.grpc import CacheServiceGrpcTransport +from .transports.grpc_asyncio import CacheServiceGrpcAsyncIOTransport +from .transports.rest import CacheServiceRestTransport + + +class CacheServiceClientMeta(type): + """Metaclass for the CacheService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = OrderedDict() # type: Dict[str, Type[CacheServiceTransport]] + _transport_registry["grpc"] = CacheServiceGrpcTransport + _transport_registry["grpc_asyncio"] = CacheServiceGrpcAsyncIOTransport + _transport_registry["rest"] = CacheServiceRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[CacheServiceTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class CacheServiceClient(metaclass=CacheServiceClientMeta): + """API for managing cache of content (CachedContent resources) + that can be used in GenerativeService requests. This way + generate content requests can benefit from preprocessing work + being done earlier, possibly lowering their computational cost. + It is intended to be used with large contexts. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "generativelanguage.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "generativelanguage.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + CacheServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + CacheServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> CacheServiceTransport: + """Returns the transport used by the client instance. + + Returns: + CacheServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def cached_content_path( + id: str, + ) -> str: + """Returns a fully-qualified cached_content string.""" + return "cachedContents/{id}".format( + id=id, + ) + + @staticmethod + def parse_cached_content_path(path: str) -> Dict[str, str]: + """Parses a cached_content path into its component segments.""" + m = re.match(r"^cachedContents/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def model_path( + model: str, + ) -> str: + """Returns a fully-qualified model string.""" + return "models/{model}".format( + model=model, + ) + + @staticmethod + def parse_model_path(path: str) -> Dict[str, str]: + """Parses a model path into its component segments.""" + m = re.match(r"^models/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path( + billing_account: str, + ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path( + folder: str, + ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format( + folder=folder, + ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path( + organization: str, + ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format( + organization=organization, + ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path( + project: str, + ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format( + project=project, + ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path( + project: str, + location: str, + ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_client_cert not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ): + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + _default_universe = CacheServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = CacheServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = CacheServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) + return api_endpoint + + @staticmethod + def _get_universe_domain( + client_universe_domain: Optional[str], universe_domain_env: Optional[str] + ) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = CacheServiceClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, CacheServiceTransport, Callable[..., CacheServiceTransport]] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the cache service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,CacheServiceTransport,Callable[..., CacheServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the CacheServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) + + universe_domain_opt = getattr(self._client_options, "universe_domain", None) + + ( + self._use_client_cert, + self._use_mtls_endpoint, + self._universe_domain_env, + ) = CacheServiceClient._read_environment_variables() + self._client_cert_source = CacheServiceClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = CacheServiceClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + self._api_endpoint = None # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, CacheServiceTransport) + if transport_provided: + # transport is a CacheServiceTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = cast(CacheServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = self._api_endpoint or CacheServiceClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint, + ) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + + transport_init: Union[ + Type[CacheServiceTransport], Callable[..., CacheServiceTransport] + ] = ( + CacheServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., CacheServiceTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.ai.generativelanguage_v1alpha.CacheServiceClient`.", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.CacheService", + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { + "serviceName": "google.ai.generativelanguage.v1alpha.CacheService", + "credentialsType": None, + }, + ) + + def list_cached_contents( + self, + request: Optional[Union[cache_service.ListCachedContentsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListCachedContentsPager: + r"""Lists CachedContents. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ai import generativelanguage_v1alpha + + def sample_list_cached_contents(): + # Create a client + client = generativelanguage_v1alpha.CacheServiceClient() + + # Initialize request argument(s) + request = generativelanguage_v1alpha.ListCachedContentsRequest( + ) + + # Make the request + page_result = client.list_cached_contents(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.ai.generativelanguage_v1alpha.types.ListCachedContentsRequest, dict]): + The request object. Request to list CachedContents. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ai.generativelanguage_v1alpha.services.cache_service.pagers.ListCachedContentsPager: + Response with CachedContents list. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, cache_service.ListCachedContentsRequest): + request = cache_service.ListCachedContentsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_cached_contents] + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListCachedContentsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_cached_content( + self, + request: Optional[Union[cache_service.CreateCachedContentRequest, dict]] = None, + *, + cached_content: Optional[gag_cached_content.CachedContent] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gag_cached_content.CachedContent: + r"""Creates CachedContent resource. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ai import generativelanguage_v1alpha + + def sample_create_cached_content(): + # Create a client + client = generativelanguage_v1alpha.CacheServiceClient() + + # Initialize request argument(s) + request = generativelanguage_v1alpha.CreateCachedContentRequest( + ) + + # Make the request + response = client.create_cached_content(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.ai.generativelanguage_v1alpha.types.CreateCachedContentRequest, dict]): + The request object. Request to create CachedContent. + cached_content (google.ai.generativelanguage_v1alpha.types.CachedContent): + Required. The cached content to + create. + + This corresponds to the ``cached_content`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ai.generativelanguage_v1alpha.types.CachedContent: + Content that has been preprocessed + and can be used in subsequent request to + GenerativeService. + + Cached content can be only used with + model it was created for. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([cached_content]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, cache_service.CreateCachedContentRequest): + request = cache_service.CreateCachedContentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if cached_content is not None: + request.cached_content = cached_content + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_cached_content] + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_cached_content( + self, + request: Optional[Union[cache_service.GetCachedContentRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> cached_content.CachedContent: + r"""Reads CachedContent resource. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ai import generativelanguage_v1alpha + + def sample_get_cached_content(): + # Create a client + client = generativelanguage_v1alpha.CacheServiceClient() + + # Initialize request argument(s) + request = generativelanguage_v1alpha.GetCachedContentRequest( + name="name_value", + ) + + # Make the request + response = client.get_cached_content(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.ai.generativelanguage_v1alpha.types.GetCachedContentRequest, dict]): + The request object. Request to read CachedContent. + name (str): + Required. The resource name referring to the content + cache entry. Format: ``cachedContents/{id}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ai.generativelanguage_v1alpha.types.CachedContent: + Content that has been preprocessed + and can be used in subsequent request to + GenerativeService. + + Cached content can be only used with + model it was created for. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, cache_service.GetCachedContentRequest): + request = cache_service.GetCachedContentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_cached_content] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_cached_content( + self, + request: Optional[Union[cache_service.UpdateCachedContentRequest, dict]] = None, + *, + cached_content: Optional[gag_cached_content.CachedContent] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gag_cached_content.CachedContent: + r"""Updates CachedContent resource (only expiration is + updatable). + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ai import generativelanguage_v1alpha + + def sample_update_cached_content(): + # Create a client + client = generativelanguage_v1alpha.CacheServiceClient() + + # Initialize request argument(s) + request = generativelanguage_v1alpha.UpdateCachedContentRequest( + ) + + # Make the request + response = client.update_cached_content(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.ai.generativelanguage_v1alpha.types.UpdateCachedContentRequest, dict]): + The request object. Request to update CachedContent. + cached_content (google.ai.generativelanguage_v1alpha.types.CachedContent): + Required. The content cache entry to + update + + This corresponds to the ``cached_content`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The list of fields to update. + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ai.generativelanguage_v1alpha.types.CachedContent: + Content that has been preprocessed + and can be used in subsequent request to + GenerativeService. + + Cached content can be only used with + model it was created for. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([cached_content, update_mask]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, cache_service.UpdateCachedContentRequest): + request = cache_service.UpdateCachedContentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if cached_content is not None: + request.cached_content = cached_content + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_cached_content] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("cached_content.name", request.cached_content.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_cached_content( + self, + request: Optional[Union[cache_service.DeleteCachedContentRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes CachedContent resource. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ai import generativelanguage_v1alpha + + def sample_delete_cached_content(): + # Create a client + client = generativelanguage_v1alpha.CacheServiceClient() + + # Initialize request argument(s) + request = generativelanguage_v1alpha.DeleteCachedContentRequest( + name="name_value", + ) + + # Make the request + client.delete_cached_content(request=request) + + Args: + request (Union[google.ai.generativelanguage_v1alpha.types.DeleteCachedContentRequest, dict]): + The request object. Request to delete CachedContent. + name (str): + Required. The resource name referring to the content + cache entry Format: ``cachedContents/{id}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, cache_service.DeleteCachedContentRequest): + request = cache_service.DeleteCachedContentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_cached_content] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def __enter__(self) -> "CacheServiceClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_operations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + + +__all__ = ("CacheServiceClient",) diff --git a/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/cache_service/pagers.py b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/cache_service/pagers.py new file mode 100644 index 0000000000000000000000000000000000000000..0a43aadf2d533eaacf07b0159a2cb3cd517683f0 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/cache_service/pagers.py @@ -0,0 +1,197 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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. +# +from typing import ( + Any, + AsyncIterator, + Awaitable, + Callable, + Iterator, + Optional, + Sequence, + Tuple, + Union, +) + +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import retry_async as retries_async + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] + OptionalAsyncRetry = Union[ + retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None + ] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore + +from google.ai.generativelanguage_v1alpha.types import cache_service, cached_content + + +class ListCachedContentsPager: + """A pager for iterating through ``list_cached_contents`` requests. + + This class thinly wraps an initial + :class:`google.ai.generativelanguage_v1alpha.types.ListCachedContentsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``cached_contents`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListCachedContents`` requests and continue to iterate + through the ``cached_contents`` field on the + corresponding responses. + + All the usual :class:`google.ai.generativelanguage_v1alpha.types.ListCachedContentsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., cache_service.ListCachedContentsResponse], + request: cache_service.ListCachedContentsRequest, + response: cache_service.ListCachedContentsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.ai.generativelanguage_v1alpha.types.ListCachedContentsRequest): + The initial request object. + response (google.ai.generativelanguage_v1alpha.types.ListCachedContentsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = cache_service.ListCachedContentsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[cache_service.ListCachedContentsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[cached_content.CachedContent]: + for page in self.pages: + yield from page.cached_contents + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListCachedContentsAsyncPager: + """A pager for iterating through ``list_cached_contents`` requests. + + This class thinly wraps an initial + :class:`google.ai.generativelanguage_v1alpha.types.ListCachedContentsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``cached_contents`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListCachedContents`` requests and continue to iterate + through the ``cached_contents`` field on the + corresponding responses. + + All the usual :class:`google.ai.generativelanguage_v1alpha.types.ListCachedContentsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[cache_service.ListCachedContentsResponse]], + request: cache_service.ListCachedContentsRequest, + response: cache_service.ListCachedContentsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.ai.generativelanguage_v1alpha.types.ListCachedContentsRequest): + The initial request object. + response (google.ai.generativelanguage_v1alpha.types.ListCachedContentsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = cache_service.ListCachedContentsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[cache_service.ListCachedContentsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[cached_content.CachedContent]: + async def async_generator(): + async for page in self.pages: + for response in page.cached_contents: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/cache_service/transports/grpc.py b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/cache_service/transports/grpc.py new file mode 100644 index 0000000000000000000000000000000000000000..c337588e39d75d177ecf33d4d58e43383e13d915 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/cache_service/transports/grpc.py @@ -0,0 +1,517 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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. +# +import json +import logging as std_logging +import pickle +from typing import Callable, Dict, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import gapic_v1, grpc_helpers +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore + +from google.ai.generativelanguage_v1alpha.types import ( + cached_content as gag_cached_content, +) +from google.ai.generativelanguage_v1alpha.types import cache_service +from google.ai.generativelanguage_v1alpha.types import cached_content + +from .base import DEFAULT_CLIENT_INFO, CacheServiceTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER + def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.CacheService", + "rpcName": client_call_details.method, + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + + response = continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = response.result() + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response for {client_call_details.method}.", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.CacheService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class CacheServiceGrpcTransport(CacheServiceTransport): + """gRPC backend transport for CacheService. + + API for managing cache of content (CachedContent resources) + that can be used in GenerativeService requests. This way + generate content requests can benefit from preprocessing work + being done earlier, possibly lowering their computational cost. + It is intended to be used with large contexts. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _stubs: Dict[str, Callable] + + def __init__( + self, + *, + host: str = "generativelanguage.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'generativelanguage.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientInterceptor() + self._logged_channel = grpc.intercept_channel( + self._grpc_channel, self._interceptor + ) + + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel( + cls, + host: str = "generativelanguage.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service.""" + return self._grpc_channel + + @property + def list_cached_contents( + self, + ) -> Callable[ + [cache_service.ListCachedContentsRequest], + cache_service.ListCachedContentsResponse, + ]: + r"""Return a callable for the list cached contents method over gRPC. + + Lists CachedContents. + + Returns: + Callable[[~.ListCachedContentsRequest], + ~.ListCachedContentsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_cached_contents" not in self._stubs: + self._stubs["list_cached_contents"] = self._logged_channel.unary_unary( + "/google.ai.generativelanguage.v1alpha.CacheService/ListCachedContents", + request_serializer=cache_service.ListCachedContentsRequest.serialize, + response_deserializer=cache_service.ListCachedContentsResponse.deserialize, + ) + return self._stubs["list_cached_contents"] + + @property + def create_cached_content( + self, + ) -> Callable[ + [cache_service.CreateCachedContentRequest], gag_cached_content.CachedContent + ]: + r"""Return a callable for the create cached content method over gRPC. + + Creates CachedContent resource. + + Returns: + Callable[[~.CreateCachedContentRequest], + ~.CachedContent]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_cached_content" not in self._stubs: + self._stubs["create_cached_content"] = self._logged_channel.unary_unary( + "/google.ai.generativelanguage.v1alpha.CacheService/CreateCachedContent", + request_serializer=cache_service.CreateCachedContentRequest.serialize, + response_deserializer=gag_cached_content.CachedContent.deserialize, + ) + return self._stubs["create_cached_content"] + + @property + def get_cached_content( + self, + ) -> Callable[ + [cache_service.GetCachedContentRequest], cached_content.CachedContent + ]: + r"""Return a callable for the get cached content method over gRPC. + + Reads CachedContent resource. + + Returns: + Callable[[~.GetCachedContentRequest], + ~.CachedContent]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_cached_content" not in self._stubs: + self._stubs["get_cached_content"] = self._logged_channel.unary_unary( + "/google.ai.generativelanguage.v1alpha.CacheService/GetCachedContent", + request_serializer=cache_service.GetCachedContentRequest.serialize, + response_deserializer=cached_content.CachedContent.deserialize, + ) + return self._stubs["get_cached_content"] + + @property + def update_cached_content( + self, + ) -> Callable[ + [cache_service.UpdateCachedContentRequest], gag_cached_content.CachedContent + ]: + r"""Return a callable for the update cached content method over gRPC. + + Updates CachedContent resource (only expiration is + updatable). + + Returns: + Callable[[~.UpdateCachedContentRequest], + ~.CachedContent]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_cached_content" not in self._stubs: + self._stubs["update_cached_content"] = self._logged_channel.unary_unary( + "/google.ai.generativelanguage.v1alpha.CacheService/UpdateCachedContent", + request_serializer=cache_service.UpdateCachedContentRequest.serialize, + response_deserializer=gag_cached_content.CachedContent.deserialize, + ) + return self._stubs["update_cached_content"] + + @property + def delete_cached_content( + self, + ) -> Callable[[cache_service.DeleteCachedContentRequest], empty_pb2.Empty]: + r"""Return a callable for the delete cached content method over gRPC. + + Deletes CachedContent resource. + + Returns: + Callable[[~.DeleteCachedContentRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_cached_content" not in self._stubs: + self._stubs["delete_cached_content"] = self._logged_channel.unary_unary( + "/google.ai.generativelanguage.v1alpha.CacheService/DeleteCachedContent", + request_serializer=cache_service.DeleteCachedContentRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_cached_content"] + + def close(self): + self._logged_channel.close() + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ("CacheServiceGrpcTransport",) diff --git a/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/cache_service/transports/grpc_asyncio.py b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/cache_service/transports/grpc_asyncio.py new file mode 100644 index 0000000000000000000000000000000000000000..764e2a1cb29f2a5c658518aaa59fda2ce46e1212 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/cache_service/transports/grpc_asyncio.py @@ -0,0 +1,573 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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. +# +import inspect +import json +import logging as std_logging +import pickle +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, grpc_helpers_async +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson +import google.protobuf.message +import grpc # type: ignore +from grpc.experimental import aio # type: ignore +import proto # type: ignore + +from google.ai.generativelanguage_v1alpha.types import ( + cached_content as gag_cached_content, +) +from google.ai.generativelanguage_v1alpha.types import cache_service +from google.ai.generativelanguage_v1alpha.types import cached_content + +from .base import DEFAULT_CLIENT_INFO, CacheServiceTransport +from .grpc import CacheServiceGrpcTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientAIOInterceptor( + grpc.aio.UnaryUnaryClientInterceptor +): # pragma: NO COVER + async def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.CacheService", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = await continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = await response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = await response + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response to rpc {client_call_details.method}.", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.CacheService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class CacheServiceGrpcAsyncIOTransport(CacheServiceTransport): + """gRPC AsyncIO backend transport for CacheService. + + API for managing cache of content (CachedContent resources) + that can be used in GenerativeService requests. This way + generate content requests can benefit from preprocessing work + being done earlier, possibly lowering their computational cost. + It is intended to be used with large contexts. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel( + cls, + host: str = "generativelanguage.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "generativelanguage.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'generativelanguage.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientAIOInterceptor() + self._grpc_channel._unary_unary_interceptors.append(self._interceptor) + self._logged_channel = self._grpc_channel + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def list_cached_contents( + self, + ) -> Callable[ + [cache_service.ListCachedContentsRequest], + Awaitable[cache_service.ListCachedContentsResponse], + ]: + r"""Return a callable for the list cached contents method over gRPC. + + Lists CachedContents. + + Returns: + Callable[[~.ListCachedContentsRequest], + Awaitable[~.ListCachedContentsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_cached_contents" not in self._stubs: + self._stubs["list_cached_contents"] = self._logged_channel.unary_unary( + "/google.ai.generativelanguage.v1alpha.CacheService/ListCachedContents", + request_serializer=cache_service.ListCachedContentsRequest.serialize, + response_deserializer=cache_service.ListCachedContentsResponse.deserialize, + ) + return self._stubs["list_cached_contents"] + + @property + def create_cached_content( + self, + ) -> Callable[ + [cache_service.CreateCachedContentRequest], + Awaitable[gag_cached_content.CachedContent], + ]: + r"""Return a callable for the create cached content method over gRPC. + + Creates CachedContent resource. + + Returns: + Callable[[~.CreateCachedContentRequest], + Awaitable[~.CachedContent]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_cached_content" not in self._stubs: + self._stubs["create_cached_content"] = self._logged_channel.unary_unary( + "/google.ai.generativelanguage.v1alpha.CacheService/CreateCachedContent", + request_serializer=cache_service.CreateCachedContentRequest.serialize, + response_deserializer=gag_cached_content.CachedContent.deserialize, + ) + return self._stubs["create_cached_content"] + + @property + def get_cached_content( + self, + ) -> Callable[ + [cache_service.GetCachedContentRequest], Awaitable[cached_content.CachedContent] + ]: + r"""Return a callable for the get cached content method over gRPC. + + Reads CachedContent resource. + + Returns: + Callable[[~.GetCachedContentRequest], + Awaitable[~.CachedContent]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_cached_content" not in self._stubs: + self._stubs["get_cached_content"] = self._logged_channel.unary_unary( + "/google.ai.generativelanguage.v1alpha.CacheService/GetCachedContent", + request_serializer=cache_service.GetCachedContentRequest.serialize, + response_deserializer=cached_content.CachedContent.deserialize, + ) + return self._stubs["get_cached_content"] + + @property + def update_cached_content( + self, + ) -> Callable[ + [cache_service.UpdateCachedContentRequest], + Awaitable[gag_cached_content.CachedContent], + ]: + r"""Return a callable for the update cached content method over gRPC. + + Updates CachedContent resource (only expiration is + updatable). + + Returns: + Callable[[~.UpdateCachedContentRequest], + Awaitable[~.CachedContent]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_cached_content" not in self._stubs: + self._stubs["update_cached_content"] = self._logged_channel.unary_unary( + "/google.ai.generativelanguage.v1alpha.CacheService/UpdateCachedContent", + request_serializer=cache_service.UpdateCachedContentRequest.serialize, + response_deserializer=gag_cached_content.CachedContent.deserialize, + ) + return self._stubs["update_cached_content"] + + @property + def delete_cached_content( + self, + ) -> Callable[ + [cache_service.DeleteCachedContentRequest], Awaitable[empty_pb2.Empty] + ]: + r"""Return a callable for the delete cached content method over gRPC. + + Deletes CachedContent resource. + + Returns: + Callable[[~.DeleteCachedContentRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_cached_content" not in self._stubs: + self._stubs["delete_cached_content"] = self._logged_channel.unary_unary( + "/google.ai.generativelanguage.v1alpha.CacheService/DeleteCachedContent", + request_serializer=cache_service.DeleteCachedContentRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_cached_content"] + + def _prep_wrapped_messages(self, client_info): + """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.list_cached_contents: self._wrap_method( + self.list_cached_contents, + default_timeout=None, + client_info=client_info, + ), + self.create_cached_content: self._wrap_method( + self.create_cached_content, + default_timeout=None, + client_info=client_info, + ), + self.get_cached_content: self._wrap_method( + self.get_cached_content, + default_timeout=None, + client_info=client_info, + ), + self.update_cached_content: self._wrap_method( + self.update_cached_content, + default_timeout=None, + client_info=client_info, + ), + self.delete_cached_content: self._wrap_method( + self.delete_cached_content, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + } + + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + + def close(self): + return self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + +__all__ = ("CacheServiceGrpcAsyncIOTransport",) diff --git a/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/cache_service/transports/rest.py b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/cache_service/transports/rest.py new file mode 100644 index 0000000000000000000000000000000000000000..e89f49ec8994b37ec3cbca2592cb9072bd8dffe8 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/cache_service/transports/rest.py @@ -0,0 +1,1428 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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. +# +import dataclasses +import json # type: ignore +import logging +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, rest_helpers, rest_streaming +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import json_format +from requests import __version__ as requests_version + +from google.ai.generativelanguage_v1alpha.types import ( + cached_content as gag_cached_content, +) +from google.ai.generativelanguage_v1alpha.types import cache_service +from google.ai.generativelanguage_v1alpha.types import cached_content + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseCacheServiceRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = logging.getLogger(__name__) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=f"requests@{requests_version}", +) + + +class CacheServiceRestInterceptor: + """Interceptor for CacheService. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the CacheServiceRestTransport. + + .. code-block:: python + class MyCustomCacheServiceInterceptor(CacheServiceRestInterceptor): + def pre_create_cached_content(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_cached_content(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_cached_content(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_get_cached_content(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_cached_content(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_cached_contents(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_cached_contents(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_cached_content(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_cached_content(self, response): + logging.log(f"Received response: {response}") + return response + + transport = CacheServiceRestTransport(interceptor=MyCustomCacheServiceInterceptor()) + client = CacheServiceClient(transport=transport) + + + """ + + def pre_create_cached_content( + self, + request: cache_service.CreateCachedContentRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cache_service.CreateCachedContentRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for create_cached_content + + Override in a subclass to manipulate the request or metadata + before they are sent to the CacheService server. + """ + return request, metadata + + def post_create_cached_content( + self, response: gag_cached_content.CachedContent + ) -> gag_cached_content.CachedContent: + """Post-rpc interceptor for create_cached_content + + Override in a subclass to manipulate the response + after it is returned by the CacheService server but before + it is returned to user code. + """ + return response + + def pre_delete_cached_content( + self, + request: cache_service.DeleteCachedContentRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cache_service.DeleteCachedContentRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for delete_cached_content + + Override in a subclass to manipulate the request or metadata + before they are sent to the CacheService server. + """ + return request, metadata + + def pre_get_cached_content( + self, + request: cache_service.GetCachedContentRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cache_service.GetCachedContentRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_cached_content + + Override in a subclass to manipulate the request or metadata + before they are sent to the CacheService server. + """ + return request, metadata + + def post_get_cached_content( + self, response: cached_content.CachedContent + ) -> cached_content.CachedContent: + """Post-rpc interceptor for get_cached_content + + Override in a subclass to manipulate the response + after it is returned by the CacheService server but before + it is returned to user code. + """ + return response + + def pre_list_cached_contents( + self, + request: cache_service.ListCachedContentsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cache_service.ListCachedContentsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_cached_contents + + Override in a subclass to manipulate the request or metadata + before they are sent to the CacheService server. + """ + return request, metadata + + def post_list_cached_contents( + self, response: cache_service.ListCachedContentsResponse + ) -> cache_service.ListCachedContentsResponse: + """Post-rpc interceptor for list_cached_contents + + Override in a subclass to manipulate the response + after it is returned by the CacheService server but before + it is returned to user code. + """ + return response + + def pre_update_cached_content( + self, + request: cache_service.UpdateCachedContentRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + cache_service.UpdateCachedContentRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for update_cached_content + + Override in a subclass to manipulate the request or metadata + before they are sent to the CacheService server. + """ + return request, metadata + + def post_update_cached_content( + self, response: gag_cached_content.CachedContent + ) -> gag_cached_content.CachedContent: + """Post-rpc interceptor for update_cached_content + + Override in a subclass to manipulate the response + after it is returned by the CacheService server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, + request: operations_pb2.GetOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the CacheService server. + """ + return request, metadata + + def post_get_operation( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for get_operation + + Override in a subclass to manipulate the response + after it is returned by the CacheService server but before + it is returned to user code. + """ + return response + + def pre_list_operations( + self, + request: operations_pb2.ListOperationsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.ListOperationsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the CacheService server. + """ + return request, metadata + + def post_list_operations( + self, response: operations_pb2.ListOperationsResponse + ) -> operations_pb2.ListOperationsResponse: + """Post-rpc interceptor for list_operations + + Override in a subclass to manipulate the response + after it is returned by the CacheService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class CacheServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: CacheServiceRestInterceptor + + +class CacheServiceRestTransport(_BaseCacheServiceRestTransport): + """REST backend synchronous transport for CacheService. + + API for managing cache of content (CachedContent resources) + that can be used in GenerativeService requests. This way + generate content requests can benefit from preprocessing work + being done earlier, possibly lowering their computational cost. + It is intended to be used with large contexts. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "generativelanguage.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[CacheServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'generativelanguage.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + url_scheme=url_scheme, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or CacheServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _CreateCachedContent( + _BaseCacheServiceRestTransport._BaseCreateCachedContent, CacheServiceRestStub + ): + def __hash__(self): + return hash("CacheServiceRestTransport.CreateCachedContent") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: cache_service.CreateCachedContentRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gag_cached_content.CachedContent: + r"""Call the create cached content method over HTTP. + + Args: + request (~.cache_service.CreateCachedContentRequest): + The request object. Request to create CachedContent. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.gag_cached_content.CachedContent: + Content that has been preprocessed + and can be used in subsequent request to + GenerativeService. + + Cached content can be only used with + model it was created for. + + """ + + http_options = ( + _BaseCacheServiceRestTransport._BaseCreateCachedContent._get_http_options() + ) + + request, metadata = self._interceptor.pre_create_cached_content( + request, metadata + ) + transcoded_request = _BaseCacheServiceRestTransport._BaseCreateCachedContent._get_transcoded_request( + http_options, request + ) + + body = _BaseCacheServiceRestTransport._BaseCreateCachedContent._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseCacheServiceRestTransport._BaseCreateCachedContent._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ai.generativelanguage_v1alpha.CacheServiceClient.CreateCachedContent", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.CacheService", + "rpcName": "CreateCachedContent", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = CacheServiceRestTransport._CreateCachedContent._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gag_cached_content.CachedContent() + pb_resp = gag_cached_content.CachedContent.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_cached_content(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = gag_cached_content.CachedContent.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.ai.generativelanguage_v1alpha.CacheServiceClient.create_cached_content", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.CacheService", + "rpcName": "CreateCachedContent", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteCachedContent( + _BaseCacheServiceRestTransport._BaseDeleteCachedContent, CacheServiceRestStub + ): + def __hash__(self): + return hash("CacheServiceRestTransport.DeleteCachedContent") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: cache_service.DeleteCachedContentRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + r"""Call the delete cached content method over HTTP. + + Args: + request (~.cache_service.DeleteCachedContentRequest): + The request object. Request to delete CachedContent. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = ( + _BaseCacheServiceRestTransport._BaseDeleteCachedContent._get_http_options() + ) + + request, metadata = self._interceptor.pre_delete_cached_content( + request, metadata + ) + transcoded_request = _BaseCacheServiceRestTransport._BaseDeleteCachedContent._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseCacheServiceRestTransport._BaseDeleteCachedContent._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ai.generativelanguage_v1alpha.CacheServiceClient.DeleteCachedContent", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.CacheService", + "rpcName": "DeleteCachedContent", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = CacheServiceRestTransport._DeleteCachedContent._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _GetCachedContent( + _BaseCacheServiceRestTransport._BaseGetCachedContent, CacheServiceRestStub + ): + def __hash__(self): + return hash("CacheServiceRestTransport.GetCachedContent") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: cache_service.GetCachedContentRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> cached_content.CachedContent: + r"""Call the get cached content method over HTTP. + + Args: + request (~.cache_service.GetCachedContentRequest): + The request object. Request to read CachedContent. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.cached_content.CachedContent: + Content that has been preprocessed + and can be used in subsequent request to + GenerativeService. + + Cached content can be only used with + model it was created for. + + """ + + http_options = ( + _BaseCacheServiceRestTransport._BaseGetCachedContent._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_cached_content( + request, metadata + ) + transcoded_request = _BaseCacheServiceRestTransport._BaseGetCachedContent._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseCacheServiceRestTransport._BaseGetCachedContent._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ai.generativelanguage_v1alpha.CacheServiceClient.GetCachedContent", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.CacheService", + "rpcName": "GetCachedContent", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = CacheServiceRestTransport._GetCachedContent._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = cached_content.CachedContent() + pb_resp = cached_content.CachedContent.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_cached_content(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = cached_content.CachedContent.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.ai.generativelanguage_v1alpha.CacheServiceClient.get_cached_content", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.CacheService", + "rpcName": "GetCachedContent", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListCachedContents( + _BaseCacheServiceRestTransport._BaseListCachedContents, CacheServiceRestStub + ): + def __hash__(self): + return hash("CacheServiceRestTransport.ListCachedContents") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: cache_service.ListCachedContentsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> cache_service.ListCachedContentsResponse: + r"""Call the list cached contents method over HTTP. + + Args: + request (~.cache_service.ListCachedContentsRequest): + The request object. Request to list CachedContents. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.cache_service.ListCachedContentsResponse: + Response with CachedContents list. + """ + + http_options = ( + _BaseCacheServiceRestTransport._BaseListCachedContents._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_cached_contents( + request, metadata + ) + transcoded_request = _BaseCacheServiceRestTransport._BaseListCachedContents._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseCacheServiceRestTransport._BaseListCachedContents._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ai.generativelanguage_v1alpha.CacheServiceClient.ListCachedContents", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.CacheService", + "rpcName": "ListCachedContents", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = CacheServiceRestTransport._ListCachedContents._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = cache_service.ListCachedContentsResponse() + pb_resp = cache_service.ListCachedContentsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_cached_contents(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = cache_service.ListCachedContentsResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.ai.generativelanguage_v1alpha.CacheServiceClient.list_cached_contents", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.CacheService", + "rpcName": "ListCachedContents", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateCachedContent( + _BaseCacheServiceRestTransport._BaseUpdateCachedContent, CacheServiceRestStub + ): + def __hash__(self): + return hash("CacheServiceRestTransport.UpdateCachedContent") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: cache_service.UpdateCachedContentRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gag_cached_content.CachedContent: + r"""Call the update cached content method over HTTP. + + Args: + request (~.cache_service.UpdateCachedContentRequest): + The request object. Request to update CachedContent. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.gag_cached_content.CachedContent: + Content that has been preprocessed + and can be used in subsequent request to + GenerativeService. + + Cached content can be only used with + model it was created for. + + """ + + http_options = ( + _BaseCacheServiceRestTransport._BaseUpdateCachedContent._get_http_options() + ) + + request, metadata = self._interceptor.pre_update_cached_content( + request, metadata + ) + transcoded_request = _BaseCacheServiceRestTransport._BaseUpdateCachedContent._get_transcoded_request( + http_options, request + ) + + body = _BaseCacheServiceRestTransport._BaseUpdateCachedContent._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseCacheServiceRestTransport._BaseUpdateCachedContent._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ai.generativelanguage_v1alpha.CacheServiceClient.UpdateCachedContent", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.CacheService", + "rpcName": "UpdateCachedContent", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = CacheServiceRestTransport._UpdateCachedContent._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gag_cached_content.CachedContent() + pb_resp = gag_cached_content.CachedContent.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_cached_content(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = gag_cached_content.CachedContent.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.ai.generativelanguage_v1alpha.CacheServiceClient.update_cached_content", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.CacheService", + "rpcName": "UpdateCachedContent", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def create_cached_content( + self, + ) -> Callable[ + [cache_service.CreateCachedContentRequest], gag_cached_content.CachedContent + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateCachedContent(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_cached_content( + self, + ) -> Callable[[cache_service.DeleteCachedContentRequest], empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteCachedContent(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_cached_content( + self, + ) -> Callable[ + [cache_service.GetCachedContentRequest], cached_content.CachedContent + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetCachedContent(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_cached_contents( + self, + ) -> Callable[ + [cache_service.ListCachedContentsRequest], + cache_service.ListCachedContentsResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListCachedContents(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_cached_content( + self, + ) -> Callable[ + [cache_service.UpdateCachedContentRequest], gag_cached_content.CachedContent + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateCachedContent(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation( + _BaseCacheServiceRestTransport._BaseGetOperation, CacheServiceRestStub + ): + def __hash__(self): + return hash("CacheServiceRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.GetOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options = ( + _BaseCacheServiceRestTransport._BaseGetOperation._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + transcoded_request = _BaseCacheServiceRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = ( + _BaseCacheServiceRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ai.generativelanguage_v1alpha.CacheServiceClient.GetOperation", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.CacheService", + "rpcName": "GetOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = CacheServiceRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.Operation() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_operation(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.ai.generativelanguage_v1alpha.CacheServiceAsyncClient.GetOperation", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.CacheService", + "rpcName": "GetOperation", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations( + _BaseCacheServiceRestTransport._BaseListOperations, CacheServiceRestStub + ): + def __hash__(self): + return hash("CacheServiceRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.ListOperationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options = ( + _BaseCacheServiceRestTransport._BaseListOperations._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + transcoded_request = _BaseCacheServiceRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseCacheServiceRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ai.generativelanguage_v1alpha.CacheServiceClient.ListOperations", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.CacheService", + "rpcName": "ListOperations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = CacheServiceRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_list_operations(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.ai.generativelanguage_v1alpha.CacheServiceAsyncClient.ListOperations", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.CacheService", + "rpcName": "ListOperations", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("CacheServiceRestTransport",) diff --git a/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/cache_service/transports/rest_base.py b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/cache_service/transports/rest_base.py new file mode 100644 index 0000000000000000000000000000000000000000..cb05981f3fdd0b526588c76d748090dd38e15cbc --- /dev/null +++ b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/cache_service/transports/rest_base.py @@ -0,0 +1,399 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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. +# +import json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import json_format + +from google.ai.generativelanguage_v1alpha.types import ( + cached_content as gag_cached_content, +) +from google.ai.generativelanguage_v1alpha.types import cache_service +from google.ai.generativelanguage_v1alpha.types import cached_content + +from .base import DEFAULT_CLIENT_INFO, CacheServiceTransport + + +class _BaseCacheServiceRestTransport(CacheServiceTransport): + """Base REST backend transport for CacheService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "generativelanguage.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'generativelanguage.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + class _BaseCreateCachedContent: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1alpha/cachedContents", + "body": "cached_content", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = cache_service.CreateCachedContentRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCacheServiceRestTransport._BaseCreateCachedContent._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteCachedContent: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1alpha/{name=cachedContents/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = cache_service.DeleteCachedContentRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCacheServiceRestTransport._BaseDeleteCachedContent._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetCachedContent: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1alpha/{name=cachedContents/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = cache_service.GetCachedContentRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCacheServiceRestTransport._BaseGetCachedContent._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListCachedContents: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1alpha/cachedContents", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = cache_service.ListCachedContentsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateCachedContent: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1alpha/{cached_content.name=cachedContents/*}", + "body": "cached_content", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = cache_service.UpdateCachedContentRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseCacheServiceRestTransport._BaseUpdateCachedContent._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1alpha/{name=tunedModels/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1alpha/{name=generatedFiles/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1alpha/{name=models/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1alpha/{name=tunedModels/*}/operations", + }, + { + "method": "get", + "uri": "/v1alpha/{name=models/*}/operations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BaseCacheServiceRestTransport",) diff --git a/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/__init__.py b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..221b8e46bdaac3b4c26d1d73c875fa6b849cbcc8 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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. +# +from .async_client import GenerativeServiceAsyncClient +from .client import GenerativeServiceClient + +__all__ = ( + "GenerativeServiceClient", + "GenerativeServiceAsyncClient", +) diff --git a/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/__pycache__/__init__.cpython-311.pyc b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bc8f83ad88853d933cbe1e6c845cb35cdc2ac64d Binary files /dev/null and b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/__pycache__/__init__.cpython-311.pyc differ diff --git a/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/__pycache__/async_client.cpython-311.pyc b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/__pycache__/async_client.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a25b7245c26f9c0055c08a443333e82b296552b4 Binary files /dev/null and b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/__pycache__/async_client.cpython-311.pyc differ diff --git a/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/__pycache__/client.cpython-311.pyc b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/__pycache__/client.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fce7d4e5d3b1d6f95107da1c6aec6671915edd68 Binary files /dev/null and b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/__pycache__/client.cpython-311.pyc differ diff --git a/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/async_client.py b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/async_client.py new file mode 100644 index 0000000000000000000000000000000000000000..863c225af329d028ebf4a0552fbcb7569135d5ca --- /dev/null +++ b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/async_client.py @@ -0,0 +1,1366 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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. +# +from collections import OrderedDict +import logging as std_logging +import re +from typing import ( + AsyncIterable, + AsyncIterator, + Awaitable, + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) + +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.api_core.client_options import ClientOptions +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.ai.generativelanguage_v1alpha import gapic_version as package_version + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +from google.longrunning import operations_pb2 # type: ignore + +from google.ai.generativelanguage_v1alpha.types import generative_service, safety +from google.ai.generativelanguage_v1alpha.types import content +from google.ai.generativelanguage_v1alpha.types import content as gag_content + +from .client import GenerativeServiceClient +from .transports.base import DEFAULT_CLIENT_INFO, GenerativeServiceTransport +from .transports.grpc_asyncio import GenerativeServiceGrpcAsyncIOTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class GenerativeServiceAsyncClient: + """API for using Large Models that generate multimodal content + and have additional capabilities beyond text generation. + """ + + _client: GenerativeServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = GenerativeServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = GenerativeServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = GenerativeServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = GenerativeServiceClient._DEFAULT_UNIVERSE + + cached_content_path = staticmethod(GenerativeServiceClient.cached_content_path) + parse_cached_content_path = staticmethod( + GenerativeServiceClient.parse_cached_content_path + ) + model_path = staticmethod(GenerativeServiceClient.model_path) + parse_model_path = staticmethod(GenerativeServiceClient.parse_model_path) + common_billing_account_path = staticmethod( + GenerativeServiceClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + GenerativeServiceClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod(GenerativeServiceClient.common_folder_path) + parse_common_folder_path = staticmethod( + GenerativeServiceClient.parse_common_folder_path + ) + common_organization_path = staticmethod( + GenerativeServiceClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + GenerativeServiceClient.parse_common_organization_path + ) + common_project_path = staticmethod(GenerativeServiceClient.common_project_path) + parse_common_project_path = staticmethod( + GenerativeServiceClient.parse_common_project_path + ) + common_location_path = staticmethod(GenerativeServiceClient.common_location_path) + parse_common_location_path = staticmethod( + GenerativeServiceClient.parse_common_location_path + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + GenerativeServiceAsyncClient: The constructed client. + """ + return GenerativeServiceClient.from_service_account_info.__func__(GenerativeServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + GenerativeServiceAsyncClient: The constructed client. + """ + return GenerativeServiceClient.from_service_account_file.__func__(GenerativeServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return GenerativeServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> GenerativeServiceTransport: + """Returns the transport used by the client instance. + + Returns: + GenerativeServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = GenerativeServiceClient.get_transport_class + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[ + str, + GenerativeServiceTransport, + Callable[..., GenerativeServiceTransport], + ] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the generative service async client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,GenerativeServiceTransport,Callable[..., GenerativeServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the GenerativeServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = GenerativeServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.ai.generativelanguage_v1alpha.GenerativeServiceAsyncClient`.", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.GenerativeService", + "universeDomain": getattr( + self._client._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._client._transport, "_credentials") + else { + "serviceName": "google.ai.generativelanguage.v1alpha.GenerativeService", + "credentialsType": None, + }, + ) + + async def generate_content( + self, + request: Optional[ + Union[generative_service.GenerateContentRequest, dict] + ] = None, + *, + model: Optional[str] = None, + contents: Optional[MutableSequence[content.Content]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> generative_service.GenerateContentResponse: + r"""Generates a model response given an input + ``GenerateContentRequest``. Refer to the `text generation + guide `__ + for detailed usage information. Input capabilities differ + between models, including tuned models. Refer to the `model + guide `__ + and `tuning + guide `__ + for details. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ai import generativelanguage_v1alpha + + async def sample_generate_content(): + # Create a client + client = generativelanguage_v1alpha.GenerativeServiceAsyncClient() + + # Initialize request argument(s) + request = generativelanguage_v1alpha.GenerateContentRequest( + model="model_value", + ) + + # Make the request + response = await client.generate_content(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.ai.generativelanguage_v1alpha.types.GenerateContentRequest, dict]]): + The request object. Request to generate a completion from + the model. + model (:class:`str`): + Required. The name of the ``Model`` to use for + generating the completion. + + Format: ``models/{model}``. + + This corresponds to the ``model`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + contents (:class:`MutableSequence[google.ai.generativelanguage_v1alpha.types.Content]`): + Required. The content of the current conversation with + the model. + + For single-turn queries, this is a single instance. For + multi-turn queries like + `chat `__, + this is a repeated field that contains the conversation + history and the latest request. + + This corresponds to the ``contents`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ai.generativelanguage_v1alpha.types.GenerateContentResponse: + Response from the model supporting multiple candidate + responses. + + Safety ratings and content filtering are reported for + both prompt in + GenerateContentResponse.prompt_feedback and for each + candidate in finish_reason and in safety_ratings. The + API: - Returns either all requested candidates or + none of them - Returns no candidates at all only if + there was something wrong with the prompt (check + prompt_feedback) - Reports feedback on each candidate + in finish_reason and safety_ratings. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([model, contents]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, generative_service.GenerateContentRequest): + request = generative_service.GenerateContentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if model is not None: + request.model = model + if contents: + request.contents.extend(contents) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.generate_content + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("model", request.model),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def generate_answer( + self, + request: Optional[Union[generative_service.GenerateAnswerRequest, dict]] = None, + *, + model: Optional[str] = None, + contents: Optional[MutableSequence[content.Content]] = None, + safety_settings: Optional[MutableSequence[safety.SafetySetting]] = None, + answer_style: Optional[ + generative_service.GenerateAnswerRequest.AnswerStyle + ] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> generative_service.GenerateAnswerResponse: + r"""Generates a grounded answer from the model given an input + ``GenerateAnswerRequest``. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ai import generativelanguage_v1alpha + + async def sample_generate_answer(): + # Create a client + client = generativelanguage_v1alpha.GenerativeServiceAsyncClient() + + # Initialize request argument(s) + request = generativelanguage_v1alpha.GenerateAnswerRequest( + model="model_value", + answer_style="VERBOSE", + ) + + # Make the request + response = await client.generate_answer(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.ai.generativelanguage_v1alpha.types.GenerateAnswerRequest, dict]]): + The request object. Request to generate a grounded answer from the + ``Model``. + model (:class:`str`): + Required. The name of the ``Model`` to use for + generating the grounded response. + + Format: ``model=models/{model}``. + + This corresponds to the ``model`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + contents (:class:`MutableSequence[google.ai.generativelanguage_v1alpha.types.Content]`): + Required. The content of the current conversation with + the ``Model``. For single-turn queries, this is a single + question to answer. For multi-turn queries, this is a + repeated field that contains conversation history and + the last ``Content`` in the list containing the + question. + + Note: ``GenerateAnswer`` only supports queries in + English. + + This corresponds to the ``contents`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + safety_settings (:class:`MutableSequence[google.ai.generativelanguage_v1alpha.types.SafetySetting]`): + Optional. A list of unique ``SafetySetting`` instances + for blocking unsafe content. + + This will be enforced on the + ``GenerateAnswerRequest.contents`` and + ``GenerateAnswerResponse.candidate``. There should not + be more than one setting for each ``SafetyCategory`` + type. The API will block any contents and responses that + fail to meet the thresholds set by these settings. This + list overrides the default settings for each + ``SafetyCategory`` specified in the safety_settings. If + there is no ``SafetySetting`` for a given + ``SafetyCategory`` provided in the list, the API will + use the default safety setting for that category. Harm + categories HARM_CATEGORY_HATE_SPEECH, + HARM_CATEGORY_SEXUALLY_EXPLICIT, + HARM_CATEGORY_DANGEROUS_CONTENT, + HARM_CATEGORY_HARASSMENT are supported. Refer to the + `guide `__ + for detailed information on available safety settings. + Also refer to the `Safety + guidance `__ + to learn how to incorporate safety considerations in + your AI applications. + + This corresponds to the ``safety_settings`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + answer_style (:class:`google.ai.generativelanguage_v1alpha.types.GenerateAnswerRequest.AnswerStyle`): + Required. Style in which answers + should be returned. + + This corresponds to the ``answer_style`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ai.generativelanguage_v1alpha.types.GenerateAnswerResponse: + Response from the model for a + grounded answer. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([model, contents, safety_settings, answer_style]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, generative_service.GenerateAnswerRequest): + request = generative_service.GenerateAnswerRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if model is not None: + request.model = model + if answer_style is not None: + request.answer_style = answer_style + if contents: + request.contents.extend(contents) + if safety_settings: + request.safety_settings.extend(safety_settings) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.generate_answer + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("model", request.model),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def stream_generate_content( + self, + request: Optional[ + Union[generative_service.GenerateContentRequest, dict] + ] = None, + *, + model: Optional[str] = None, + contents: Optional[MutableSequence[content.Content]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> Awaitable[AsyncIterable[generative_service.GenerateContentResponse]]: + r"""Generates a `streamed + response `__ + from the model given an input ``GenerateContentRequest``. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ai import generativelanguage_v1alpha + + async def sample_stream_generate_content(): + # Create a client + client = generativelanguage_v1alpha.GenerativeServiceAsyncClient() + + # Initialize request argument(s) + request = generativelanguage_v1alpha.GenerateContentRequest( + model="model_value", + ) + + # Make the request + stream = await client.stream_generate_content(request=request) + + # Handle the response + async for response in stream: + print(response) + + Args: + request (Optional[Union[google.ai.generativelanguage_v1alpha.types.GenerateContentRequest, dict]]): + The request object. Request to generate a completion from + the model. + model (:class:`str`): + Required. The name of the ``Model`` to use for + generating the completion. + + Format: ``models/{model}``. + + This corresponds to the ``model`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + contents (:class:`MutableSequence[google.ai.generativelanguage_v1alpha.types.Content]`): + Required. The content of the current conversation with + the model. + + For single-turn queries, this is a single instance. For + multi-turn queries like + `chat `__, + this is a repeated field that contains the conversation + history and the latest request. + + This corresponds to the ``contents`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + AsyncIterable[google.ai.generativelanguage_v1alpha.types.GenerateContentResponse]: + Response from the model supporting multiple candidate + responses. + + Safety ratings and content filtering are reported for + both prompt in + GenerateContentResponse.prompt_feedback and for each + candidate in finish_reason and in safety_ratings. The + API: - Returns either all requested candidates or + none of them - Returns no candidates at all only if + there was something wrong with the prompt (check + prompt_feedback) - Reports feedback on each candidate + in finish_reason and safety_ratings. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([model, contents]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, generative_service.GenerateContentRequest): + request = generative_service.GenerateContentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if model is not None: + request.model = model + if contents: + request.contents.extend(contents) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.stream_generate_content + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("model", request.model),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def embed_content( + self, + request: Optional[Union[generative_service.EmbedContentRequest, dict]] = None, + *, + model: Optional[str] = None, + content: Optional[gag_content.Content] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> generative_service.EmbedContentResponse: + r"""Generates a text embedding vector from the input ``Content`` + using the specified `Gemini Embedding + model `__. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ai import generativelanguage_v1alpha + + async def sample_embed_content(): + # Create a client + client = generativelanguage_v1alpha.GenerativeServiceAsyncClient() + + # Initialize request argument(s) + request = generativelanguage_v1alpha.EmbedContentRequest( + model="model_value", + ) + + # Make the request + response = await client.embed_content(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.ai.generativelanguage_v1alpha.types.EmbedContentRequest, dict]]): + The request object. Request containing the ``Content`` for the model to + embed. + model (:class:`str`): + Required. The model's resource name. This serves as an + ID for the Model to use. + + This name should match a model name returned by the + ``ListModels`` method. + + Format: ``models/{model}`` + + This corresponds to the ``model`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + content (:class:`google.ai.generativelanguage_v1alpha.types.Content`): + Required. The content to embed. Only the ``parts.text`` + fields will be counted. + + This corresponds to the ``content`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ai.generativelanguage_v1alpha.types.EmbedContentResponse: + The response to an EmbedContentRequest. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([model, content]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, generative_service.EmbedContentRequest): + request = generative_service.EmbedContentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if model is not None: + request.model = model + if content is not None: + request.content = content + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.embed_content + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("model", request.model),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def batch_embed_contents( + self, + request: Optional[ + Union[generative_service.BatchEmbedContentsRequest, dict] + ] = None, + *, + model: Optional[str] = None, + requests: Optional[ + MutableSequence[generative_service.EmbedContentRequest] + ] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> generative_service.BatchEmbedContentsResponse: + r"""Generates multiple embedding vectors from the input ``Content`` + which consists of a batch of strings represented as + ``EmbedContentRequest`` objects. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ai import generativelanguage_v1alpha + + async def sample_batch_embed_contents(): + # Create a client + client = generativelanguage_v1alpha.GenerativeServiceAsyncClient() + + # Initialize request argument(s) + requests = generativelanguage_v1alpha.EmbedContentRequest() + requests.model = "model_value" + + request = generativelanguage_v1alpha.BatchEmbedContentsRequest( + model="model_value", + requests=requests, + ) + + # Make the request + response = await client.batch_embed_contents(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.ai.generativelanguage_v1alpha.types.BatchEmbedContentsRequest, dict]]): + The request object. Batch request to get embeddings from + the model for a list of prompts. + model (:class:`str`): + Required. The model's resource name. This serves as an + ID for the Model to use. + + This name should match a model name returned by the + ``ListModels`` method. + + Format: ``models/{model}`` + + This corresponds to the ``model`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + requests (:class:`MutableSequence[google.ai.generativelanguage_v1alpha.types.EmbedContentRequest]`): + Required. Embed requests for the batch. The model in + each of these requests must match the model specified + ``BatchEmbedContentsRequest.model``. + + This corresponds to the ``requests`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ai.generativelanguage_v1alpha.types.BatchEmbedContentsResponse: + The response to a BatchEmbedContentsRequest. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([model, requests]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, generative_service.BatchEmbedContentsRequest): + request = generative_service.BatchEmbedContentsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if model is not None: + request.model = model + if requests: + request.requests.extend(requests) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.batch_embed_contents + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("model", request.model),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def count_tokens( + self, + request: Optional[Union[generative_service.CountTokensRequest, dict]] = None, + *, + model: Optional[str] = None, + contents: Optional[MutableSequence[content.Content]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> generative_service.CountTokensResponse: + r"""Runs a model's tokenizer on input ``Content`` and returns the + token count. Refer to the `tokens + guide `__ to learn + more about tokens. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ai import generativelanguage_v1alpha + + async def sample_count_tokens(): + # Create a client + client = generativelanguage_v1alpha.GenerativeServiceAsyncClient() + + # Initialize request argument(s) + request = generativelanguage_v1alpha.CountTokensRequest( + model="model_value", + ) + + # Make the request + response = await client.count_tokens(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.ai.generativelanguage_v1alpha.types.CountTokensRequest, dict]]): + The request object. Counts the number of tokens in the ``prompt`` sent to a + model. + + Models may tokenize text differently, so each model may + return a different ``token_count``. + model (:class:`str`): + Required. The model's resource name. This serves as an + ID for the Model to use. + + This name should match a model name returned by the + ``ListModels`` method. + + Format: ``models/{model}`` + + This corresponds to the ``model`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + contents (:class:`MutableSequence[google.ai.generativelanguage_v1alpha.types.Content]`): + Optional. The input given to the model as a prompt. This + field is ignored when ``generate_content_request`` is + set. + + This corresponds to the ``contents`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ai.generativelanguage_v1alpha.types.CountTokensResponse: + A response from CountTokens. + + It returns the model's token_count for the prompt. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([model, contents]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, generative_service.CountTokensRequest): + request = generative_service.CountTokensRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if model is not None: + request.model = model + if contents: + request.contents.extend(contents) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.count_tokens + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("model", request.model),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def bidi_generate_content( + self, + requests: Optional[ + AsyncIterator[generative_service.BidiGenerateContentClientMessage] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> Awaitable[AsyncIterable[generative_service.BidiGenerateContentServerMessage]]: + r"""Low-Latency bidirectional streaming API that supports + audio and video streaming inputs can produce multimodal + output streams (audio and text). + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ai import generativelanguage_v1alpha + + async def sample_bidi_generate_content(): + # Create a client + client = generativelanguage_v1alpha.GenerativeServiceAsyncClient() + + # Initialize request argument(s) + setup = generativelanguage_v1alpha.BidiGenerateContentSetup() + setup.model = "model_value" + + request = generativelanguage_v1alpha.BidiGenerateContentClientMessage( + setup=setup, + ) + + # This method expects an iterator which contains + # 'generativelanguage_v1alpha.BidiGenerateContentClientMessage' objects + # Here we create a generator that yields a single `request` for + # demonstrative purposes. + requests = [request] + + def request_generator(): + for request in requests: + yield request + + # Make the request + stream = await client.bidi_generate_content(requests=request_generator()) + + # Handle the response + async for response in stream: + print(response) + + Args: + requests (AsyncIterator[`google.ai.generativelanguage_v1alpha.types.BidiGenerateContentClientMessage`]): + The request object AsyncIterator. Messages sent by the client in the + BidiGenerateContent call. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + AsyncIterable[google.ai.generativelanguage_v1alpha.types.BidiGenerateContentServerMessage]: + Response message for the + BidiGenerateContent call. + + """ + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.bidi_generate_content + ] + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = rpc( + requests, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self) -> "GenerativeServiceAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + + +__all__ = ("GenerativeServiceAsyncClient",) diff --git a/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/client.py b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/client.py new file mode 100644 index 0000000000000000000000000000000000000000..767855b5befbfa2270a2f7d8a4b8875ad2789ad5 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/client.py @@ -0,0 +1,1751 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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. +# +from collections import OrderedDict +import logging as std_logging +import os +import re +from typing import ( + Callable, + Dict, + Iterable, + Iterator, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) +import warnings + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.ai.generativelanguage_v1alpha import gapic_version as package_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +from google.longrunning import operations_pb2 # type: ignore + +from google.ai.generativelanguage_v1alpha.types import generative_service, safety +from google.ai.generativelanguage_v1alpha.types import content +from google.ai.generativelanguage_v1alpha.types import content as gag_content + +from .transports.base import DEFAULT_CLIENT_INFO, GenerativeServiceTransport +from .transports.grpc import GenerativeServiceGrpcTransport +from .transports.grpc_asyncio import GenerativeServiceGrpcAsyncIOTransport +from .transports.rest import GenerativeServiceRestTransport + + +class GenerativeServiceClientMeta(type): + """Metaclass for the GenerativeService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = ( + OrderedDict() + ) # type: Dict[str, Type[GenerativeServiceTransport]] + _transport_registry["grpc"] = GenerativeServiceGrpcTransport + _transport_registry["grpc_asyncio"] = GenerativeServiceGrpcAsyncIOTransport + _transport_registry["rest"] = GenerativeServiceRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[GenerativeServiceTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class GenerativeServiceClient(metaclass=GenerativeServiceClientMeta): + """API for using Large Models that generate multimodal content + and have additional capabilities beyond text generation. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "generativelanguage.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "generativelanguage.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + GenerativeServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + GenerativeServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> GenerativeServiceTransport: + """Returns the transport used by the client instance. + + Returns: + GenerativeServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def cached_content_path( + id: str, + ) -> str: + """Returns a fully-qualified cached_content string.""" + return "cachedContents/{id}".format( + id=id, + ) + + @staticmethod + def parse_cached_content_path(path: str) -> Dict[str, str]: + """Parses a cached_content path into its component segments.""" + m = re.match(r"^cachedContents/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def model_path( + model: str, + ) -> str: + """Returns a fully-qualified model string.""" + return "models/{model}".format( + model=model, + ) + + @staticmethod + def parse_model_path(path: str) -> Dict[str, str]: + """Parses a model path into its component segments.""" + m = re.match(r"^models/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path( + billing_account: str, + ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path( + folder: str, + ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format( + folder=folder, + ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path( + organization: str, + ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format( + organization=organization, + ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path( + project: str, + ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format( + project=project, + ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path( + project: str, + location: str, + ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_client_cert not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ): + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + _default_universe = GenerativeServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = GenerativeServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = GenerativeServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) + return api_endpoint + + @staticmethod + def _get_universe_domain( + client_universe_domain: Optional[str], universe_domain_env: Optional[str] + ) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = GenerativeServiceClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[ + str, + GenerativeServiceTransport, + Callable[..., GenerativeServiceTransport], + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the generative service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,GenerativeServiceTransport,Callable[..., GenerativeServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the GenerativeServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) + + universe_domain_opt = getattr(self._client_options, "universe_domain", None) + + ( + self._use_client_cert, + self._use_mtls_endpoint, + self._universe_domain_env, + ) = GenerativeServiceClient._read_environment_variables() + self._client_cert_source = GenerativeServiceClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = GenerativeServiceClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + self._api_endpoint = None # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, GenerativeServiceTransport) + if transport_provided: + # transport is a GenerativeServiceTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = cast(GenerativeServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = ( + self._api_endpoint + or GenerativeServiceClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint, + ) + ) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + + transport_init: Union[ + Type[GenerativeServiceTransport], + Callable[..., GenerativeServiceTransport], + ] = ( + GenerativeServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., GenerativeServiceTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.ai.generativelanguage_v1alpha.GenerativeServiceClient`.", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.GenerativeService", + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { + "serviceName": "google.ai.generativelanguage.v1alpha.GenerativeService", + "credentialsType": None, + }, + ) + + def generate_content( + self, + request: Optional[ + Union[generative_service.GenerateContentRequest, dict] + ] = None, + *, + model: Optional[str] = None, + contents: Optional[MutableSequence[content.Content]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> generative_service.GenerateContentResponse: + r"""Generates a model response given an input + ``GenerateContentRequest``. Refer to the `text generation + guide `__ + for detailed usage information. Input capabilities differ + between models, including tuned models. Refer to the `model + guide `__ + and `tuning + guide `__ + for details. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ai import generativelanguage_v1alpha + + def sample_generate_content(): + # Create a client + client = generativelanguage_v1alpha.GenerativeServiceClient() + + # Initialize request argument(s) + request = generativelanguage_v1alpha.GenerateContentRequest( + model="model_value", + ) + + # Make the request + response = client.generate_content(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.ai.generativelanguage_v1alpha.types.GenerateContentRequest, dict]): + The request object. Request to generate a completion from + the model. + model (str): + Required. The name of the ``Model`` to use for + generating the completion. + + Format: ``models/{model}``. + + This corresponds to the ``model`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + contents (MutableSequence[google.ai.generativelanguage_v1alpha.types.Content]): + Required. The content of the current conversation with + the model. + + For single-turn queries, this is a single instance. For + multi-turn queries like + `chat `__, + this is a repeated field that contains the conversation + history and the latest request. + + This corresponds to the ``contents`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ai.generativelanguage_v1alpha.types.GenerateContentResponse: + Response from the model supporting multiple candidate + responses. + + Safety ratings and content filtering are reported for + both prompt in + GenerateContentResponse.prompt_feedback and for each + candidate in finish_reason and in safety_ratings. The + API: - Returns either all requested candidates or + none of them - Returns no candidates at all only if + there was something wrong with the prompt (check + prompt_feedback) - Reports feedback on each candidate + in finish_reason and safety_ratings. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([model, contents]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, generative_service.GenerateContentRequest): + request = generative_service.GenerateContentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if model is not None: + request.model = model + if contents is not None: + request.contents = contents + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.generate_content] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("model", request.model),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def generate_answer( + self, + request: Optional[Union[generative_service.GenerateAnswerRequest, dict]] = None, + *, + model: Optional[str] = None, + contents: Optional[MutableSequence[content.Content]] = None, + safety_settings: Optional[MutableSequence[safety.SafetySetting]] = None, + answer_style: Optional[ + generative_service.GenerateAnswerRequest.AnswerStyle + ] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> generative_service.GenerateAnswerResponse: + r"""Generates a grounded answer from the model given an input + ``GenerateAnswerRequest``. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ai import generativelanguage_v1alpha + + def sample_generate_answer(): + # Create a client + client = generativelanguage_v1alpha.GenerativeServiceClient() + + # Initialize request argument(s) + request = generativelanguage_v1alpha.GenerateAnswerRequest( + model="model_value", + answer_style="VERBOSE", + ) + + # Make the request + response = client.generate_answer(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.ai.generativelanguage_v1alpha.types.GenerateAnswerRequest, dict]): + The request object. Request to generate a grounded answer from the + ``Model``. + model (str): + Required. The name of the ``Model`` to use for + generating the grounded response. + + Format: ``model=models/{model}``. + + This corresponds to the ``model`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + contents (MutableSequence[google.ai.generativelanguage_v1alpha.types.Content]): + Required. The content of the current conversation with + the ``Model``. For single-turn queries, this is a single + question to answer. For multi-turn queries, this is a + repeated field that contains conversation history and + the last ``Content`` in the list containing the + question. + + Note: ``GenerateAnswer`` only supports queries in + English. + + This corresponds to the ``contents`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + safety_settings (MutableSequence[google.ai.generativelanguage_v1alpha.types.SafetySetting]): + Optional. A list of unique ``SafetySetting`` instances + for blocking unsafe content. + + This will be enforced on the + ``GenerateAnswerRequest.contents`` and + ``GenerateAnswerResponse.candidate``. There should not + be more than one setting for each ``SafetyCategory`` + type. The API will block any contents and responses that + fail to meet the thresholds set by these settings. This + list overrides the default settings for each + ``SafetyCategory`` specified in the safety_settings. If + there is no ``SafetySetting`` for a given + ``SafetyCategory`` provided in the list, the API will + use the default safety setting for that category. Harm + categories HARM_CATEGORY_HATE_SPEECH, + HARM_CATEGORY_SEXUALLY_EXPLICIT, + HARM_CATEGORY_DANGEROUS_CONTENT, + HARM_CATEGORY_HARASSMENT are supported. Refer to the + `guide `__ + for detailed information on available safety settings. + Also refer to the `Safety + guidance `__ + to learn how to incorporate safety considerations in + your AI applications. + + This corresponds to the ``safety_settings`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + answer_style (google.ai.generativelanguage_v1alpha.types.GenerateAnswerRequest.AnswerStyle): + Required. Style in which answers + should be returned. + + This corresponds to the ``answer_style`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ai.generativelanguage_v1alpha.types.GenerateAnswerResponse: + Response from the model for a + grounded answer. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([model, contents, safety_settings, answer_style]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, generative_service.GenerateAnswerRequest): + request = generative_service.GenerateAnswerRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if model is not None: + request.model = model + if contents is not None: + request.contents = contents + if safety_settings is not None: + request.safety_settings = safety_settings + if answer_style is not None: + request.answer_style = answer_style + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.generate_answer] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("model", request.model),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def stream_generate_content( + self, + request: Optional[ + Union[generative_service.GenerateContentRequest, dict] + ] = None, + *, + model: Optional[str] = None, + contents: Optional[MutableSequence[content.Content]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> Iterable[generative_service.GenerateContentResponse]: + r"""Generates a `streamed + response `__ + from the model given an input ``GenerateContentRequest``. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ai import generativelanguage_v1alpha + + def sample_stream_generate_content(): + # Create a client + client = generativelanguage_v1alpha.GenerativeServiceClient() + + # Initialize request argument(s) + request = generativelanguage_v1alpha.GenerateContentRequest( + model="model_value", + ) + + # Make the request + stream = client.stream_generate_content(request=request) + + # Handle the response + for response in stream: + print(response) + + Args: + request (Union[google.ai.generativelanguage_v1alpha.types.GenerateContentRequest, dict]): + The request object. Request to generate a completion from + the model. + model (str): + Required. The name of the ``Model`` to use for + generating the completion. + + Format: ``models/{model}``. + + This corresponds to the ``model`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + contents (MutableSequence[google.ai.generativelanguage_v1alpha.types.Content]): + Required. The content of the current conversation with + the model. + + For single-turn queries, this is a single instance. For + multi-turn queries like + `chat `__, + this is a repeated field that contains the conversation + history and the latest request. + + This corresponds to the ``contents`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + Iterable[google.ai.generativelanguage_v1alpha.types.GenerateContentResponse]: + Response from the model supporting multiple candidate + responses. + + Safety ratings and content filtering are reported for + both prompt in + GenerateContentResponse.prompt_feedback and for each + candidate in finish_reason and in safety_ratings. The + API: - Returns either all requested candidates or + none of them - Returns no candidates at all only if + there was something wrong with the prompt (check + prompt_feedback) - Reports feedback on each candidate + in finish_reason and safety_ratings. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([model, contents]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, generative_service.GenerateContentRequest): + request = generative_service.GenerateContentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if model is not None: + request.model = model + if contents is not None: + request.contents = contents + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.stream_generate_content] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("model", request.model),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def embed_content( + self, + request: Optional[Union[generative_service.EmbedContentRequest, dict]] = None, + *, + model: Optional[str] = None, + content: Optional[gag_content.Content] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> generative_service.EmbedContentResponse: + r"""Generates a text embedding vector from the input ``Content`` + using the specified `Gemini Embedding + model `__. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ai import generativelanguage_v1alpha + + def sample_embed_content(): + # Create a client + client = generativelanguage_v1alpha.GenerativeServiceClient() + + # Initialize request argument(s) + request = generativelanguage_v1alpha.EmbedContentRequest( + model="model_value", + ) + + # Make the request + response = client.embed_content(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.ai.generativelanguage_v1alpha.types.EmbedContentRequest, dict]): + The request object. Request containing the ``Content`` for the model to + embed. + model (str): + Required. The model's resource name. This serves as an + ID for the Model to use. + + This name should match a model name returned by the + ``ListModels`` method. + + Format: ``models/{model}`` + + This corresponds to the ``model`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + content (google.ai.generativelanguage_v1alpha.types.Content): + Required. The content to embed. Only the ``parts.text`` + fields will be counted. + + This corresponds to the ``content`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ai.generativelanguage_v1alpha.types.EmbedContentResponse: + The response to an EmbedContentRequest. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([model, content]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, generative_service.EmbedContentRequest): + request = generative_service.EmbedContentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if model is not None: + request.model = model + if content is not None: + request.content = content + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.embed_content] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("model", request.model),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def batch_embed_contents( + self, + request: Optional[ + Union[generative_service.BatchEmbedContentsRequest, dict] + ] = None, + *, + model: Optional[str] = None, + requests: Optional[ + MutableSequence[generative_service.EmbedContentRequest] + ] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> generative_service.BatchEmbedContentsResponse: + r"""Generates multiple embedding vectors from the input ``Content`` + which consists of a batch of strings represented as + ``EmbedContentRequest`` objects. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ai import generativelanguage_v1alpha + + def sample_batch_embed_contents(): + # Create a client + client = generativelanguage_v1alpha.GenerativeServiceClient() + + # Initialize request argument(s) + requests = generativelanguage_v1alpha.EmbedContentRequest() + requests.model = "model_value" + + request = generativelanguage_v1alpha.BatchEmbedContentsRequest( + model="model_value", + requests=requests, + ) + + # Make the request + response = client.batch_embed_contents(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.ai.generativelanguage_v1alpha.types.BatchEmbedContentsRequest, dict]): + The request object. Batch request to get embeddings from + the model for a list of prompts. + model (str): + Required. The model's resource name. This serves as an + ID for the Model to use. + + This name should match a model name returned by the + ``ListModels`` method. + + Format: ``models/{model}`` + + This corresponds to the ``model`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + requests (MutableSequence[google.ai.generativelanguage_v1alpha.types.EmbedContentRequest]): + Required. Embed requests for the batch. The model in + each of these requests must match the model specified + ``BatchEmbedContentsRequest.model``. + + This corresponds to the ``requests`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ai.generativelanguage_v1alpha.types.BatchEmbedContentsResponse: + The response to a BatchEmbedContentsRequest. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([model, requests]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, generative_service.BatchEmbedContentsRequest): + request = generative_service.BatchEmbedContentsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if model is not None: + request.model = model + if requests is not None: + request.requests = requests + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.batch_embed_contents] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("model", request.model),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def count_tokens( + self, + request: Optional[Union[generative_service.CountTokensRequest, dict]] = None, + *, + model: Optional[str] = None, + contents: Optional[MutableSequence[content.Content]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> generative_service.CountTokensResponse: + r"""Runs a model's tokenizer on input ``Content`` and returns the + token count. Refer to the `tokens + guide `__ to learn + more about tokens. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ai import generativelanguage_v1alpha + + def sample_count_tokens(): + # Create a client + client = generativelanguage_v1alpha.GenerativeServiceClient() + + # Initialize request argument(s) + request = generativelanguage_v1alpha.CountTokensRequest( + model="model_value", + ) + + # Make the request + response = client.count_tokens(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.ai.generativelanguage_v1alpha.types.CountTokensRequest, dict]): + The request object. Counts the number of tokens in the ``prompt`` sent to a + model. + + Models may tokenize text differently, so each model may + return a different ``token_count``. + model (str): + Required. The model's resource name. This serves as an + ID for the Model to use. + + This name should match a model name returned by the + ``ListModels`` method. + + Format: ``models/{model}`` + + This corresponds to the ``model`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + contents (MutableSequence[google.ai.generativelanguage_v1alpha.types.Content]): + Optional. The input given to the model as a prompt. This + field is ignored when ``generate_content_request`` is + set. + + This corresponds to the ``contents`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ai.generativelanguage_v1alpha.types.CountTokensResponse: + A response from CountTokens. + + It returns the model's token_count for the prompt. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([model, contents]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, generative_service.CountTokensRequest): + request = generative_service.CountTokensRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if model is not None: + request.model = model + if contents is not None: + request.contents = contents + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.count_tokens] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("model", request.model),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def bidi_generate_content( + self, + requests: Optional[ + Iterator[generative_service.BidiGenerateContentClientMessage] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> Iterable[generative_service.BidiGenerateContentServerMessage]: + r"""Low-Latency bidirectional streaming API that supports + audio and video streaming inputs can produce multimodal + output streams (audio and text). + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ai import generativelanguage_v1alpha + + def sample_bidi_generate_content(): + # Create a client + client = generativelanguage_v1alpha.GenerativeServiceClient() + + # Initialize request argument(s) + setup = generativelanguage_v1alpha.BidiGenerateContentSetup() + setup.model = "model_value" + + request = generativelanguage_v1alpha.BidiGenerateContentClientMessage( + setup=setup, + ) + + # This method expects an iterator which contains + # 'generativelanguage_v1alpha.BidiGenerateContentClientMessage' objects + # Here we create a generator that yields a single `request` for + # demonstrative purposes. + requests = [request] + + def request_generator(): + for request in requests: + yield request + + # Make the request + stream = client.bidi_generate_content(requests=request_generator()) + + # Handle the response + for response in stream: + print(response) + + Args: + requests (Iterator[google.ai.generativelanguage_v1alpha.types.BidiGenerateContentClientMessage]): + The request object iterator. Messages sent by the client in the + BidiGenerateContent call. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + Iterable[google.ai.generativelanguage_v1alpha.types.BidiGenerateContentServerMessage]: + Response message for the + BidiGenerateContent call. + + """ + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.bidi_generate_content] + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + requests, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "GenerativeServiceClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_operations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + + +__all__ = ("GenerativeServiceClient",) diff --git a/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/transports/__init__.py b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/transports/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1321d30dc96724a2227b31254ddcdd1def3e6807 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/transports/__init__.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import GenerativeServiceTransport +from .grpc import GenerativeServiceGrpcTransport +from .grpc_asyncio import GenerativeServiceGrpcAsyncIOTransport +from .rest import GenerativeServiceRestInterceptor, GenerativeServiceRestTransport + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[GenerativeServiceTransport]] +_transport_registry["grpc"] = GenerativeServiceGrpcTransport +_transport_registry["grpc_asyncio"] = GenerativeServiceGrpcAsyncIOTransport +_transport_registry["rest"] = GenerativeServiceRestTransport + +__all__ = ( + "GenerativeServiceTransport", + "GenerativeServiceGrpcTransport", + "GenerativeServiceGrpcAsyncIOTransport", + "GenerativeServiceRestTransport", + "GenerativeServiceRestInterceptor", +) diff --git a/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/transports/__pycache__/__init__.cpython-311.pyc b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/transports/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6b16892ad2d65160f800982c66654e6f6fbd5fba Binary files /dev/null and b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/transports/__pycache__/__init__.cpython-311.pyc differ diff --git a/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/transports/__pycache__/base.cpython-311.pyc b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/transports/__pycache__/base.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d622e21e67dc21d882ce203b2477e7681a775552 Binary files /dev/null and b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/transports/__pycache__/base.cpython-311.pyc differ diff --git a/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/transports/__pycache__/grpc.cpython-311.pyc b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/transports/__pycache__/grpc.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1f7efe09a33188d759ea34488f260a73f5d3b5ba Binary files /dev/null and b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/transports/__pycache__/grpc.cpython-311.pyc differ diff --git a/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/transports/__pycache__/grpc_asyncio.cpython-311.pyc b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/transports/__pycache__/grpc_asyncio.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..39a07df65bd54926f701811abbadc24f35ea0544 Binary files /dev/null and b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/transports/__pycache__/grpc_asyncio.cpython-311.pyc differ diff --git a/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/transports/__pycache__/rest.cpython-311.pyc b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/transports/__pycache__/rest.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..94a536c6205e40c3aec2cf2f0cfc76e47fcc6eac Binary files /dev/null and b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/transports/__pycache__/rest.cpython-311.pyc differ diff --git a/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/transports/__pycache__/rest_base.cpython-311.pyc b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/transports/__pycache__/rest_base.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7ca20643989501ebd0def4c12c67dcd2e2e85140 Binary files /dev/null and b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/transports/__pycache__/rest_base.cpython-311.pyc differ diff --git a/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/transports/base.py b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/transports/base.py new file mode 100644 index 0000000000000000000000000000000000000000..f35e8e7c53df3759920ae0d68fa473ba56a6fcce --- /dev/null +++ b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/transports/base.py @@ -0,0 +1,298 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.ai.generativelanguage_v1alpha import gapic_version as package_version +from google.ai.generativelanguage_v1alpha.types import generative_service + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + + +class GenerativeServiceTransport(abc.ABC): + """Abstract transport class for GenerativeService.""" + + AUTH_SCOPES = () + + DEFAULT_HOST: str = "generativelanguage.googleapis.com" + + def __init__( + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'generativelanguage.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + if not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id + ) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.generate_content: gapic_v1.method.wrap_method( + self.generate_content, + default_timeout=None, + client_info=client_info, + ), + self.generate_answer: gapic_v1.method.wrap_method( + self.generate_answer, + default_timeout=None, + client_info=client_info, + ), + self.stream_generate_content: gapic_v1.method.wrap_method( + self.stream_generate_content, + default_timeout=None, + client_info=client_info, + ), + self.embed_content: gapic_v1.method.wrap_method( + self.embed_content, + default_timeout=None, + client_info=client_info, + ), + self.batch_embed_contents: gapic_v1.method.wrap_method( + self.batch_embed_contents, + default_timeout=None, + client_info=client_info, + ), + self.count_tokens: gapic_v1.method.wrap_method( + self.count_tokens, + default_timeout=None, + client_info=client_info, + ), + self.bidi_generate_content: gapic_v1.method.wrap_method( + self.bidi_generate_content, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def generate_content( + self, + ) -> Callable[ + [generative_service.GenerateContentRequest], + Union[ + generative_service.GenerateContentResponse, + Awaitable[generative_service.GenerateContentResponse], + ], + ]: + raise NotImplementedError() + + @property + def generate_answer( + self, + ) -> Callable[ + [generative_service.GenerateAnswerRequest], + Union[ + generative_service.GenerateAnswerResponse, + Awaitable[generative_service.GenerateAnswerResponse], + ], + ]: + raise NotImplementedError() + + @property + def stream_generate_content( + self, + ) -> Callable[ + [generative_service.GenerateContentRequest], + Union[ + generative_service.GenerateContentResponse, + Awaitable[generative_service.GenerateContentResponse], + ], + ]: + raise NotImplementedError() + + @property + def embed_content( + self, + ) -> Callable[ + [generative_service.EmbedContentRequest], + Union[ + generative_service.EmbedContentResponse, + Awaitable[generative_service.EmbedContentResponse], + ], + ]: + raise NotImplementedError() + + @property + def batch_embed_contents( + self, + ) -> Callable[ + [generative_service.BatchEmbedContentsRequest], + Union[ + generative_service.BatchEmbedContentsResponse, + Awaitable[generative_service.BatchEmbedContentsResponse], + ], + ]: + raise NotImplementedError() + + @property + def count_tokens( + self, + ) -> Callable[ + [generative_service.CountTokensRequest], + Union[ + generative_service.CountTokensResponse, + Awaitable[generative_service.CountTokensResponse], + ], + ]: + raise NotImplementedError() + + @property + def bidi_generate_content( + self, + ) -> Callable[ + [generative_service.BidiGenerateContentClientMessage], + Union[ + generative_service.BidiGenerateContentServerMessage, + Awaitable[generative_service.BidiGenerateContentServerMessage], + ], + ]: + raise NotImplementedError() + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], + Union[ + operations_pb2.ListOperationsResponse, + Awaitable[operations_pb2.ListOperationsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("GenerativeServiceTransport",) diff --git a/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/transports/grpc.py b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/transports/grpc.py new file mode 100644 index 0000000000000000000000000000000000000000..e17edf1c6a1d14d3be9a8df796adf3531e23acfb --- /dev/null +++ b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/transports/grpc.py @@ -0,0 +1,591 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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. +# +import json +import logging as std_logging +import pickle +from typing import Callable, Dict, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import gapic_v1, grpc_helpers +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore + +from google.ai.generativelanguage_v1alpha.types import generative_service + +from .base import DEFAULT_CLIENT_INFO, GenerativeServiceTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER + def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.GenerativeService", + "rpcName": client_call_details.method, + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + + response = continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = response.result() + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response for {client_call_details.method}.", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.GenerativeService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class GenerativeServiceGrpcTransport(GenerativeServiceTransport): + """gRPC backend transport for GenerativeService. + + API for using Large Models that generate multimodal content + and have additional capabilities beyond text generation. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _stubs: Dict[str, Callable] + + def __init__( + self, + *, + host: str = "generativelanguage.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'generativelanguage.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientInterceptor() + self._logged_channel = grpc.intercept_channel( + self._grpc_channel, self._interceptor + ) + + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel( + cls, + host: str = "generativelanguage.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service.""" + return self._grpc_channel + + @property + def generate_content( + self, + ) -> Callable[ + [generative_service.GenerateContentRequest], + generative_service.GenerateContentResponse, + ]: + r"""Return a callable for the generate content method over gRPC. + + Generates a model response given an input + ``GenerateContentRequest``. Refer to the `text generation + guide `__ + for detailed usage information. Input capabilities differ + between models, including tuned models. Refer to the `model + guide `__ + and `tuning + guide `__ + for details. + + Returns: + Callable[[~.GenerateContentRequest], + ~.GenerateContentResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "generate_content" not in self._stubs: + self._stubs["generate_content"] = self._logged_channel.unary_unary( + "/google.ai.generativelanguage.v1alpha.GenerativeService/GenerateContent", + request_serializer=generative_service.GenerateContentRequest.serialize, + response_deserializer=generative_service.GenerateContentResponse.deserialize, + ) + return self._stubs["generate_content"] + + @property + def generate_answer( + self, + ) -> Callable[ + [generative_service.GenerateAnswerRequest], + generative_service.GenerateAnswerResponse, + ]: + r"""Return a callable for the generate answer method over gRPC. + + Generates a grounded answer from the model given an input + ``GenerateAnswerRequest``. + + Returns: + Callable[[~.GenerateAnswerRequest], + ~.GenerateAnswerResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "generate_answer" not in self._stubs: + self._stubs["generate_answer"] = self._logged_channel.unary_unary( + "/google.ai.generativelanguage.v1alpha.GenerativeService/GenerateAnswer", + request_serializer=generative_service.GenerateAnswerRequest.serialize, + response_deserializer=generative_service.GenerateAnswerResponse.deserialize, + ) + return self._stubs["generate_answer"] + + @property + def stream_generate_content( + self, + ) -> Callable[ + [generative_service.GenerateContentRequest], + generative_service.GenerateContentResponse, + ]: + r"""Return a callable for the stream generate content method over gRPC. + + Generates a `streamed + response `__ + from the model given an input ``GenerateContentRequest``. + + Returns: + Callable[[~.GenerateContentRequest], + ~.GenerateContentResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "stream_generate_content" not in self._stubs: + self._stubs["stream_generate_content"] = self._logged_channel.unary_stream( + "/google.ai.generativelanguage.v1alpha.GenerativeService/StreamGenerateContent", + request_serializer=generative_service.GenerateContentRequest.serialize, + response_deserializer=generative_service.GenerateContentResponse.deserialize, + ) + return self._stubs["stream_generate_content"] + + @property + def embed_content( + self, + ) -> Callable[ + [generative_service.EmbedContentRequest], + generative_service.EmbedContentResponse, + ]: + r"""Return a callable for the embed content method over gRPC. + + Generates a text embedding vector from the input ``Content`` + using the specified `Gemini Embedding + model `__. + + Returns: + Callable[[~.EmbedContentRequest], + ~.EmbedContentResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "embed_content" not in self._stubs: + self._stubs["embed_content"] = self._logged_channel.unary_unary( + "/google.ai.generativelanguage.v1alpha.GenerativeService/EmbedContent", + request_serializer=generative_service.EmbedContentRequest.serialize, + response_deserializer=generative_service.EmbedContentResponse.deserialize, + ) + return self._stubs["embed_content"] + + @property + def batch_embed_contents( + self, + ) -> Callable[ + [generative_service.BatchEmbedContentsRequest], + generative_service.BatchEmbedContentsResponse, + ]: + r"""Return a callable for the batch embed contents method over gRPC. + + Generates multiple embedding vectors from the input ``Content`` + which consists of a batch of strings represented as + ``EmbedContentRequest`` objects. + + Returns: + Callable[[~.BatchEmbedContentsRequest], + ~.BatchEmbedContentsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "batch_embed_contents" not in self._stubs: + self._stubs["batch_embed_contents"] = self._logged_channel.unary_unary( + "/google.ai.generativelanguage.v1alpha.GenerativeService/BatchEmbedContents", + request_serializer=generative_service.BatchEmbedContentsRequest.serialize, + response_deserializer=generative_service.BatchEmbedContentsResponse.deserialize, + ) + return self._stubs["batch_embed_contents"] + + @property + def count_tokens( + self, + ) -> Callable[ + [generative_service.CountTokensRequest], generative_service.CountTokensResponse + ]: + r"""Return a callable for the count tokens method over gRPC. + + Runs a model's tokenizer on input ``Content`` and returns the + token count. Refer to the `tokens + guide `__ to learn + more about tokens. + + Returns: + Callable[[~.CountTokensRequest], + ~.CountTokensResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "count_tokens" not in self._stubs: + self._stubs["count_tokens"] = self._logged_channel.unary_unary( + "/google.ai.generativelanguage.v1alpha.GenerativeService/CountTokens", + request_serializer=generative_service.CountTokensRequest.serialize, + response_deserializer=generative_service.CountTokensResponse.deserialize, + ) + return self._stubs["count_tokens"] + + @property + def bidi_generate_content( + self, + ) -> Callable[ + [generative_service.BidiGenerateContentClientMessage], + generative_service.BidiGenerateContentServerMessage, + ]: + r"""Return a callable for the bidi generate content method over gRPC. + + Low-Latency bidirectional streaming API that supports + audio and video streaming inputs can produce multimodal + output streams (audio and text). + + Returns: + Callable[[~.BidiGenerateContentClientMessage], + ~.BidiGenerateContentServerMessage]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "bidi_generate_content" not in self._stubs: + self._stubs["bidi_generate_content"] = self._logged_channel.stream_stream( + "/google.ai.generativelanguage.v1alpha.GenerativeService/BidiGenerateContent", + request_serializer=generative_service.BidiGenerateContentClientMessage.serialize, + response_deserializer=generative_service.BidiGenerateContentServerMessage.deserialize, + ) + return self._stubs["bidi_generate_content"] + + def close(self): + self._logged_channel.close() + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ("GenerativeServiceGrpcTransport",) diff --git a/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/transports/grpc_asyncio.py b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/transports/grpc_asyncio.py new file mode 100644 index 0000000000000000000000000000000000000000..584719dd457258f4468c6b89743fadb39b410446 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/transports/grpc_asyncio.py @@ -0,0 +1,654 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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. +# +import inspect +import json +import logging as std_logging +import pickle +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, grpc_helpers_async +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson +import google.protobuf.message +import grpc # type: ignore +from grpc.experimental import aio # type: ignore +import proto # type: ignore + +from google.ai.generativelanguage_v1alpha.types import generative_service + +from .base import DEFAULT_CLIENT_INFO, GenerativeServiceTransport +from .grpc import GenerativeServiceGrpcTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientAIOInterceptor( + grpc.aio.UnaryUnaryClientInterceptor +): # pragma: NO COVER + async def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.GenerativeService", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = await continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = await response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = await response + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response to rpc {client_call_details.method}.", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.GenerativeService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class GenerativeServiceGrpcAsyncIOTransport(GenerativeServiceTransport): + """gRPC AsyncIO backend transport for GenerativeService. + + API for using Large Models that generate multimodal content + and have additional capabilities beyond text generation. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel( + cls, + host: str = "generativelanguage.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "generativelanguage.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'generativelanguage.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientAIOInterceptor() + self._grpc_channel._unary_unary_interceptors.append(self._interceptor) + self._logged_channel = self._grpc_channel + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def generate_content( + self, + ) -> Callable[ + [generative_service.GenerateContentRequest], + Awaitable[generative_service.GenerateContentResponse], + ]: + r"""Return a callable for the generate content method over gRPC. + + Generates a model response given an input + ``GenerateContentRequest``. Refer to the `text generation + guide `__ + for detailed usage information. Input capabilities differ + between models, including tuned models. Refer to the `model + guide `__ + and `tuning + guide `__ + for details. + + Returns: + Callable[[~.GenerateContentRequest], + Awaitable[~.GenerateContentResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "generate_content" not in self._stubs: + self._stubs["generate_content"] = self._logged_channel.unary_unary( + "/google.ai.generativelanguage.v1alpha.GenerativeService/GenerateContent", + request_serializer=generative_service.GenerateContentRequest.serialize, + response_deserializer=generative_service.GenerateContentResponse.deserialize, + ) + return self._stubs["generate_content"] + + @property + def generate_answer( + self, + ) -> Callable[ + [generative_service.GenerateAnswerRequest], + Awaitable[generative_service.GenerateAnswerResponse], + ]: + r"""Return a callable for the generate answer method over gRPC. + + Generates a grounded answer from the model given an input + ``GenerateAnswerRequest``. + + Returns: + Callable[[~.GenerateAnswerRequest], + Awaitable[~.GenerateAnswerResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "generate_answer" not in self._stubs: + self._stubs["generate_answer"] = self._logged_channel.unary_unary( + "/google.ai.generativelanguage.v1alpha.GenerativeService/GenerateAnswer", + request_serializer=generative_service.GenerateAnswerRequest.serialize, + response_deserializer=generative_service.GenerateAnswerResponse.deserialize, + ) + return self._stubs["generate_answer"] + + @property + def stream_generate_content( + self, + ) -> Callable[ + [generative_service.GenerateContentRequest], + Awaitable[generative_service.GenerateContentResponse], + ]: + r"""Return a callable for the stream generate content method over gRPC. + + Generates a `streamed + response `__ + from the model given an input ``GenerateContentRequest``. + + Returns: + Callable[[~.GenerateContentRequest], + Awaitable[~.GenerateContentResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "stream_generate_content" not in self._stubs: + self._stubs["stream_generate_content"] = self._logged_channel.unary_stream( + "/google.ai.generativelanguage.v1alpha.GenerativeService/StreamGenerateContent", + request_serializer=generative_service.GenerateContentRequest.serialize, + response_deserializer=generative_service.GenerateContentResponse.deserialize, + ) + return self._stubs["stream_generate_content"] + + @property + def embed_content( + self, + ) -> Callable[ + [generative_service.EmbedContentRequest], + Awaitable[generative_service.EmbedContentResponse], + ]: + r"""Return a callable for the embed content method over gRPC. + + Generates a text embedding vector from the input ``Content`` + using the specified `Gemini Embedding + model `__. + + Returns: + Callable[[~.EmbedContentRequest], + Awaitable[~.EmbedContentResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "embed_content" not in self._stubs: + self._stubs["embed_content"] = self._logged_channel.unary_unary( + "/google.ai.generativelanguage.v1alpha.GenerativeService/EmbedContent", + request_serializer=generative_service.EmbedContentRequest.serialize, + response_deserializer=generative_service.EmbedContentResponse.deserialize, + ) + return self._stubs["embed_content"] + + @property + def batch_embed_contents( + self, + ) -> Callable[ + [generative_service.BatchEmbedContentsRequest], + Awaitable[generative_service.BatchEmbedContentsResponse], + ]: + r"""Return a callable for the batch embed contents method over gRPC. + + Generates multiple embedding vectors from the input ``Content`` + which consists of a batch of strings represented as + ``EmbedContentRequest`` objects. + + Returns: + Callable[[~.BatchEmbedContentsRequest], + Awaitable[~.BatchEmbedContentsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "batch_embed_contents" not in self._stubs: + self._stubs["batch_embed_contents"] = self._logged_channel.unary_unary( + "/google.ai.generativelanguage.v1alpha.GenerativeService/BatchEmbedContents", + request_serializer=generative_service.BatchEmbedContentsRequest.serialize, + response_deserializer=generative_service.BatchEmbedContentsResponse.deserialize, + ) + return self._stubs["batch_embed_contents"] + + @property + def count_tokens( + self, + ) -> Callable[ + [generative_service.CountTokensRequest], + Awaitable[generative_service.CountTokensResponse], + ]: + r"""Return a callable for the count tokens method over gRPC. + + Runs a model's tokenizer on input ``Content`` and returns the + token count. Refer to the `tokens + guide `__ to learn + more about tokens. + + Returns: + Callable[[~.CountTokensRequest], + Awaitable[~.CountTokensResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "count_tokens" not in self._stubs: + self._stubs["count_tokens"] = self._logged_channel.unary_unary( + "/google.ai.generativelanguage.v1alpha.GenerativeService/CountTokens", + request_serializer=generative_service.CountTokensRequest.serialize, + response_deserializer=generative_service.CountTokensResponse.deserialize, + ) + return self._stubs["count_tokens"] + + @property + def bidi_generate_content( + self, + ) -> Callable[ + [generative_service.BidiGenerateContentClientMessage], + Awaitable[generative_service.BidiGenerateContentServerMessage], + ]: + r"""Return a callable for the bidi generate content method over gRPC. + + Low-Latency bidirectional streaming API that supports + audio and video streaming inputs can produce multimodal + output streams (audio and text). + + Returns: + Callable[[~.BidiGenerateContentClientMessage], + Awaitable[~.BidiGenerateContentServerMessage]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "bidi_generate_content" not in self._stubs: + self._stubs["bidi_generate_content"] = self._logged_channel.stream_stream( + "/google.ai.generativelanguage.v1alpha.GenerativeService/BidiGenerateContent", + request_serializer=generative_service.BidiGenerateContentClientMessage.serialize, + response_deserializer=generative_service.BidiGenerateContentServerMessage.deserialize, + ) + return self._stubs["bidi_generate_content"] + + def _prep_wrapped_messages(self, client_info): + """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.generate_content: self._wrap_method( + self.generate_content, + default_timeout=None, + client_info=client_info, + ), + self.generate_answer: self._wrap_method( + self.generate_answer, + default_timeout=None, + client_info=client_info, + ), + self.stream_generate_content: self._wrap_method( + self.stream_generate_content, + default_timeout=None, + client_info=client_info, + ), + self.embed_content: self._wrap_method( + self.embed_content, + default_timeout=None, + client_info=client_info, + ), + self.batch_embed_contents: self._wrap_method( + self.batch_embed_contents, + default_timeout=None, + client_info=client_info, + ), + self.count_tokens: self._wrap_method( + self.count_tokens, + default_timeout=None, + client_info=client_info, + ), + self.bidi_generate_content: self._wrap_method( + self.bidi_generate_content, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + } + + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + + def close(self): + return self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + +__all__ = ("GenerativeServiceGrpcAsyncIOTransport",) diff --git a/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/transports/rest.py b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/transports/rest.py new file mode 100644 index 0000000000000000000000000000000000000000..0c4361c7704c10fa0eb8784b3e13cec1f30e0e88 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/transports/rest.py @@ -0,0 +1,1726 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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. +# +import dataclasses +import json # type: ignore +import logging +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, rest_helpers, rest_streaming +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format +from requests import __version__ as requests_version + +from google.ai.generativelanguage_v1alpha.types import generative_service + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseGenerativeServiceRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = logging.getLogger(__name__) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=f"requests@{requests_version}", +) + + +class GenerativeServiceRestInterceptor: + """Interceptor for GenerativeService. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the GenerativeServiceRestTransport. + + .. code-block:: python + class MyCustomGenerativeServiceInterceptor(GenerativeServiceRestInterceptor): + def pre_batch_embed_contents(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_batch_embed_contents(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_count_tokens(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_count_tokens(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_embed_content(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_embed_content(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_generate_answer(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_generate_answer(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_generate_content(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_generate_content(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_stream_generate_content(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_stream_generate_content(self, response): + logging.log(f"Received response: {response}") + return response + + transport = GenerativeServiceRestTransport(interceptor=MyCustomGenerativeServiceInterceptor()) + client = GenerativeServiceClient(transport=transport) + + + """ + + def pre_batch_embed_contents( + self, + request: generative_service.BatchEmbedContentsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + generative_service.BatchEmbedContentsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for batch_embed_contents + + Override in a subclass to manipulate the request or metadata + before they are sent to the GenerativeService server. + """ + return request, metadata + + def post_batch_embed_contents( + self, response: generative_service.BatchEmbedContentsResponse + ) -> generative_service.BatchEmbedContentsResponse: + """Post-rpc interceptor for batch_embed_contents + + Override in a subclass to manipulate the response + after it is returned by the GenerativeService server but before + it is returned to user code. + """ + return response + + def pre_count_tokens( + self, + request: generative_service.CountTokensRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + generative_service.CountTokensRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for count_tokens + + Override in a subclass to manipulate the request or metadata + before they are sent to the GenerativeService server. + """ + return request, metadata + + def post_count_tokens( + self, response: generative_service.CountTokensResponse + ) -> generative_service.CountTokensResponse: + """Post-rpc interceptor for count_tokens + + Override in a subclass to manipulate the response + after it is returned by the GenerativeService server but before + it is returned to user code. + """ + return response + + def pre_embed_content( + self, + request: generative_service.EmbedContentRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + generative_service.EmbedContentRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for embed_content + + Override in a subclass to manipulate the request or metadata + before they are sent to the GenerativeService server. + """ + return request, metadata + + def post_embed_content( + self, response: generative_service.EmbedContentResponse + ) -> generative_service.EmbedContentResponse: + """Post-rpc interceptor for embed_content + + Override in a subclass to manipulate the response + after it is returned by the GenerativeService server but before + it is returned to user code. + """ + return response + + def pre_generate_answer( + self, + request: generative_service.GenerateAnswerRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + generative_service.GenerateAnswerRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for generate_answer + + Override in a subclass to manipulate the request or metadata + before they are sent to the GenerativeService server. + """ + return request, metadata + + def post_generate_answer( + self, response: generative_service.GenerateAnswerResponse + ) -> generative_service.GenerateAnswerResponse: + """Post-rpc interceptor for generate_answer + + Override in a subclass to manipulate the response + after it is returned by the GenerativeService server but before + it is returned to user code. + """ + return response + + def pre_generate_content( + self, + request: generative_service.GenerateContentRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + generative_service.GenerateContentRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for generate_content + + Override in a subclass to manipulate the request or metadata + before they are sent to the GenerativeService server. + """ + return request, metadata + + def post_generate_content( + self, response: generative_service.GenerateContentResponse + ) -> generative_service.GenerateContentResponse: + """Post-rpc interceptor for generate_content + + Override in a subclass to manipulate the response + after it is returned by the GenerativeService server but before + it is returned to user code. + """ + return response + + def pre_stream_generate_content( + self, + request: generative_service.GenerateContentRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + generative_service.GenerateContentRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for stream_generate_content + + Override in a subclass to manipulate the request or metadata + before they are sent to the GenerativeService server. + """ + return request, metadata + + def post_stream_generate_content( + self, response: rest_streaming.ResponseIterator + ) -> rest_streaming.ResponseIterator: + """Post-rpc interceptor for stream_generate_content + + Override in a subclass to manipulate the response + after it is returned by the GenerativeService server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, + request: operations_pb2.GetOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the GenerativeService server. + """ + return request, metadata + + def post_get_operation( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for get_operation + + Override in a subclass to manipulate the response + after it is returned by the GenerativeService server but before + it is returned to user code. + """ + return response + + def pre_list_operations( + self, + request: operations_pb2.ListOperationsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.ListOperationsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the GenerativeService server. + """ + return request, metadata + + def post_list_operations( + self, response: operations_pb2.ListOperationsResponse + ) -> operations_pb2.ListOperationsResponse: + """Post-rpc interceptor for list_operations + + Override in a subclass to manipulate the response + after it is returned by the GenerativeService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class GenerativeServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: GenerativeServiceRestInterceptor + + +class GenerativeServiceRestTransport(_BaseGenerativeServiceRestTransport): + """REST backend synchronous transport for GenerativeService. + + API for using Large Models that generate multimodal content + and have additional capabilities beyond text generation. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "generativelanguage.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[GenerativeServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'generativelanguage.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + url_scheme=url_scheme, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or GenerativeServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _BatchEmbedContents( + _BaseGenerativeServiceRestTransport._BaseBatchEmbedContents, + GenerativeServiceRestStub, + ): + def __hash__(self): + return hash("GenerativeServiceRestTransport.BatchEmbedContents") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: generative_service.BatchEmbedContentsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> generative_service.BatchEmbedContentsResponse: + r"""Call the batch embed contents method over HTTP. + + Args: + request (~.generative_service.BatchEmbedContentsRequest): + The request object. Batch request to get embeddings from + the model for a list of prompts. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.generative_service.BatchEmbedContentsResponse: + The response to a ``BatchEmbedContentsRequest``. + """ + + http_options = ( + _BaseGenerativeServiceRestTransport._BaseBatchEmbedContents._get_http_options() + ) + + request, metadata = self._interceptor.pre_batch_embed_contents( + request, metadata + ) + transcoded_request = _BaseGenerativeServiceRestTransport._BaseBatchEmbedContents._get_transcoded_request( + http_options, request + ) + + body = _BaseGenerativeServiceRestTransport._BaseBatchEmbedContents._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseGenerativeServiceRestTransport._BaseBatchEmbedContents._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ai.generativelanguage_v1alpha.GenerativeServiceClient.BatchEmbedContents", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.GenerativeService", + "rpcName": "BatchEmbedContents", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = GenerativeServiceRestTransport._BatchEmbedContents._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = generative_service.BatchEmbedContentsResponse() + pb_resp = generative_service.BatchEmbedContentsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_batch_embed_contents(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + generative_service.BatchEmbedContentsResponse.to_json(response) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.ai.generativelanguage_v1alpha.GenerativeServiceClient.batch_embed_contents", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.GenerativeService", + "rpcName": "BatchEmbedContents", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _BidiGenerateContent( + _BaseGenerativeServiceRestTransport._BaseBidiGenerateContent, + GenerativeServiceRestStub, + ): + def __hash__(self): + return hash("GenerativeServiceRestTransport.BidiGenerateContent") + + def __call__( + self, + request: generative_service.BidiGenerateContentClientMessage, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> rest_streaming.ResponseIterator: + raise NotImplementedError( + "Method BidiGenerateContent is not available over REST transport" + ) + + class _CountTokens( + _BaseGenerativeServiceRestTransport._BaseCountTokens, GenerativeServiceRestStub + ): + def __hash__(self): + return hash("GenerativeServiceRestTransport.CountTokens") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: generative_service.CountTokensRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> generative_service.CountTokensResponse: + r"""Call the count tokens method over HTTP. + + Args: + request (~.generative_service.CountTokensRequest): + The request object. Counts the number of tokens in the ``prompt`` sent to a + model. + + Models may tokenize text differently, so each model may + return a different ``token_count``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.generative_service.CountTokensResponse: + A response from ``CountTokens``. + + It returns the model's ``token_count`` for the + ``prompt``. + + """ + + http_options = ( + _BaseGenerativeServiceRestTransport._BaseCountTokens._get_http_options() + ) + + request, metadata = self._interceptor.pre_count_tokens(request, metadata) + transcoded_request = _BaseGenerativeServiceRestTransport._BaseCountTokens._get_transcoded_request( + http_options, request + ) + + body = _BaseGenerativeServiceRestTransport._BaseCountTokens._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseGenerativeServiceRestTransport._BaseCountTokens._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ai.generativelanguage_v1alpha.GenerativeServiceClient.CountTokens", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.GenerativeService", + "rpcName": "CountTokens", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = GenerativeServiceRestTransport._CountTokens._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = generative_service.CountTokensResponse() + pb_resp = generative_service.CountTokensResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_count_tokens(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = generative_service.CountTokensResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.ai.generativelanguage_v1alpha.GenerativeServiceClient.count_tokens", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.GenerativeService", + "rpcName": "CountTokens", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _EmbedContent( + _BaseGenerativeServiceRestTransport._BaseEmbedContent, GenerativeServiceRestStub + ): + def __hash__(self): + return hash("GenerativeServiceRestTransport.EmbedContent") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: generative_service.EmbedContentRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> generative_service.EmbedContentResponse: + r"""Call the embed content method over HTTP. + + Args: + request (~.generative_service.EmbedContentRequest): + The request object. Request containing the ``Content`` for the model to + embed. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.generative_service.EmbedContentResponse: + The response to an ``EmbedContentRequest``. + """ + + http_options = ( + _BaseGenerativeServiceRestTransport._BaseEmbedContent._get_http_options() + ) + + request, metadata = self._interceptor.pre_embed_content(request, metadata) + transcoded_request = _BaseGenerativeServiceRestTransport._BaseEmbedContent._get_transcoded_request( + http_options, request + ) + + body = _BaseGenerativeServiceRestTransport._BaseEmbedContent._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseGenerativeServiceRestTransport._BaseEmbedContent._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ai.generativelanguage_v1alpha.GenerativeServiceClient.EmbedContent", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.GenerativeService", + "rpcName": "EmbedContent", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = GenerativeServiceRestTransport._EmbedContent._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = generative_service.EmbedContentResponse() + pb_resp = generative_service.EmbedContentResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_embed_content(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = generative_service.EmbedContentResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.ai.generativelanguage_v1alpha.GenerativeServiceClient.embed_content", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.GenerativeService", + "rpcName": "EmbedContent", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GenerateAnswer( + _BaseGenerativeServiceRestTransport._BaseGenerateAnswer, + GenerativeServiceRestStub, + ): + def __hash__(self): + return hash("GenerativeServiceRestTransport.GenerateAnswer") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: generative_service.GenerateAnswerRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> generative_service.GenerateAnswerResponse: + r"""Call the generate answer method over HTTP. + + Args: + request (~.generative_service.GenerateAnswerRequest): + The request object. Request to generate a grounded answer from the + ``Model``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.generative_service.GenerateAnswerResponse: + Response from the model for a + grounded answer. + + """ + + http_options = ( + _BaseGenerativeServiceRestTransport._BaseGenerateAnswer._get_http_options() + ) + + request, metadata = self._interceptor.pre_generate_answer(request, metadata) + transcoded_request = _BaseGenerativeServiceRestTransport._BaseGenerateAnswer._get_transcoded_request( + http_options, request + ) + + body = _BaseGenerativeServiceRestTransport._BaseGenerateAnswer._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseGenerativeServiceRestTransport._BaseGenerateAnswer._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ai.generativelanguage_v1alpha.GenerativeServiceClient.GenerateAnswer", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.GenerativeService", + "rpcName": "GenerateAnswer", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = GenerativeServiceRestTransport._GenerateAnswer._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = generative_service.GenerateAnswerResponse() + pb_resp = generative_service.GenerateAnswerResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_generate_answer(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + generative_service.GenerateAnswerResponse.to_json(response) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.ai.generativelanguage_v1alpha.GenerativeServiceClient.generate_answer", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.GenerativeService", + "rpcName": "GenerateAnswer", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GenerateContent( + _BaseGenerativeServiceRestTransport._BaseGenerateContent, + GenerativeServiceRestStub, + ): + def __hash__(self): + return hash("GenerativeServiceRestTransport.GenerateContent") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: generative_service.GenerateContentRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> generative_service.GenerateContentResponse: + r"""Call the generate content method over HTTP. + + Args: + request (~.generative_service.GenerateContentRequest): + The request object. Request to generate a completion from + the model. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.generative_service.GenerateContentResponse: + Response from the model supporting multiple candidate + responses. + + Safety ratings and content filtering are reported for + both prompt in + ``GenerateContentResponse.prompt_feedback`` and for each + candidate in ``finish_reason`` and in + ``safety_ratings``. The API: + + - Returns either all requested candidates or none of + them + - Returns no candidates at all only if there was + something wrong with the prompt (check + ``prompt_feedback``) + - Reports feedback on each candidate in + ``finish_reason`` and ``safety_ratings``. + + """ + + http_options = ( + _BaseGenerativeServiceRestTransport._BaseGenerateContent._get_http_options() + ) + + request, metadata = self._interceptor.pre_generate_content( + request, metadata + ) + transcoded_request = _BaseGenerativeServiceRestTransport._BaseGenerateContent._get_transcoded_request( + http_options, request + ) + + body = _BaseGenerativeServiceRestTransport._BaseGenerateContent._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseGenerativeServiceRestTransport._BaseGenerateContent._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ai.generativelanguage_v1alpha.GenerativeServiceClient.GenerateContent", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.GenerativeService", + "rpcName": "GenerateContent", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = GenerativeServiceRestTransport._GenerateContent._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = generative_service.GenerateContentResponse() + pb_resp = generative_service.GenerateContentResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_generate_content(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + generative_service.GenerateContentResponse.to_json(response) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.ai.generativelanguage_v1alpha.GenerativeServiceClient.generate_content", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.GenerativeService", + "rpcName": "GenerateContent", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _StreamGenerateContent( + _BaseGenerativeServiceRestTransport._BaseStreamGenerateContent, + GenerativeServiceRestStub, + ): + def __hash__(self): + return hash("GenerativeServiceRestTransport.StreamGenerateContent") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + stream=True, + ) + return response + + def __call__( + self, + request: generative_service.GenerateContentRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> rest_streaming.ResponseIterator: + r"""Call the stream generate content method over HTTP. + + Args: + request (~.generative_service.GenerateContentRequest): + The request object. Request to generate a completion from + the model. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.generative_service.GenerateContentResponse: + Response from the model supporting multiple candidate + responses. + + Safety ratings and content filtering are reported for + both prompt in + ``GenerateContentResponse.prompt_feedback`` and for each + candidate in ``finish_reason`` and in + ``safety_ratings``. The API: + + - Returns either all requested candidates or none of + them + - Returns no candidates at all only if there was + something wrong with the prompt (check + ``prompt_feedback``) + - Reports feedback on each candidate in + ``finish_reason`` and ``safety_ratings``. + + """ + + http_options = ( + _BaseGenerativeServiceRestTransport._BaseStreamGenerateContent._get_http_options() + ) + + request, metadata = self._interceptor.pre_stream_generate_content( + request, metadata + ) + transcoded_request = _BaseGenerativeServiceRestTransport._BaseStreamGenerateContent._get_transcoded_request( + http_options, request + ) + + body = _BaseGenerativeServiceRestTransport._BaseStreamGenerateContent._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseGenerativeServiceRestTransport._BaseStreamGenerateContent._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ai.generativelanguage_v1alpha.GenerativeServiceClient.StreamGenerateContent", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.GenerativeService", + "rpcName": "StreamGenerateContent", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + GenerativeServiceRestTransport._StreamGenerateContent._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = rest_streaming.ResponseIterator( + response, generative_service.GenerateContentResponse + ) + + resp = self._interceptor.post_stream_generate_content(resp) + return resp + + @property + def batch_embed_contents( + self, + ) -> Callable[ + [generative_service.BatchEmbedContentsRequest], + generative_service.BatchEmbedContentsResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._BatchEmbedContents(self._session, self._host, self._interceptor) # type: ignore + + @property + def bidi_generate_content( + self, + ) -> Callable[ + [generative_service.BidiGenerateContentClientMessage], + generative_service.BidiGenerateContentServerMessage, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._BidiGenerateContent(self._session, self._host, self._interceptor) # type: ignore + + @property + def count_tokens( + self, + ) -> Callable[ + [generative_service.CountTokensRequest], generative_service.CountTokensResponse + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CountTokens(self._session, self._host, self._interceptor) # type: ignore + + @property + def embed_content( + self, + ) -> Callable[ + [generative_service.EmbedContentRequest], + generative_service.EmbedContentResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._EmbedContent(self._session, self._host, self._interceptor) # type: ignore + + @property + def generate_answer( + self, + ) -> Callable[ + [generative_service.GenerateAnswerRequest], + generative_service.GenerateAnswerResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GenerateAnswer(self._session, self._host, self._interceptor) # type: ignore + + @property + def generate_content( + self, + ) -> Callable[ + [generative_service.GenerateContentRequest], + generative_service.GenerateContentResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GenerateContent(self._session, self._host, self._interceptor) # type: ignore + + @property + def stream_generate_content( + self, + ) -> Callable[ + [generative_service.GenerateContentRequest], + generative_service.GenerateContentResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._StreamGenerateContent(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation( + _BaseGenerativeServiceRestTransport._BaseGetOperation, GenerativeServiceRestStub + ): + def __hash__(self): + return hash("GenerativeServiceRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.GetOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options = ( + _BaseGenerativeServiceRestTransport._BaseGetOperation._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + transcoded_request = _BaseGenerativeServiceRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseGenerativeServiceRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ai.generativelanguage_v1alpha.GenerativeServiceClient.GetOperation", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.GenerativeService", + "rpcName": "GetOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = GenerativeServiceRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.Operation() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_operation(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.ai.generativelanguage_v1alpha.GenerativeServiceAsyncClient.GetOperation", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.GenerativeService", + "rpcName": "GetOperation", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations( + _BaseGenerativeServiceRestTransport._BaseListOperations, + GenerativeServiceRestStub, + ): + def __hash__(self): + return hash("GenerativeServiceRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.ListOperationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options = ( + _BaseGenerativeServiceRestTransport._BaseListOperations._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + transcoded_request = _BaseGenerativeServiceRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseGenerativeServiceRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ai.generativelanguage_v1alpha.GenerativeServiceClient.ListOperations", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.GenerativeService", + "rpcName": "ListOperations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = GenerativeServiceRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_list_operations(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.ai.generativelanguage_v1alpha.GenerativeServiceAsyncClient.ListOperations", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.GenerativeService", + "rpcName": "ListOperations", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("GenerativeServiceRestTransport",) diff --git a/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/transports/rest_base.py b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/transports/rest_base.py new file mode 100644 index 0000000000000000000000000000000000000000..f622ef84db0df6fd138c2b72134e155a6287c4b2 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/transports/rest_base.py @@ -0,0 +1,510 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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. +# +import json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format + +from google.ai.generativelanguage_v1alpha.types import generative_service + +from .base import DEFAULT_CLIENT_INFO, GenerativeServiceTransport + + +class _BaseGenerativeServiceRestTransport(GenerativeServiceTransport): + """Base REST backend transport for GenerativeService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "generativelanguage.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'generativelanguage.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + class _BaseBatchEmbedContents: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1alpha/{model=models/*}:batchEmbedContents", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = generative_service.BatchEmbedContentsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseGenerativeServiceRestTransport._BaseBatchEmbedContents._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseBidiGenerateContent: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + class _BaseCountTokens: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1alpha/{model=models/*}:countTokens", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = generative_service.CountTokensRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseGenerativeServiceRestTransport._BaseCountTokens._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseEmbedContent: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1alpha/{model=models/*}:embedContent", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = generative_service.EmbedContentRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseGenerativeServiceRestTransport._BaseEmbedContent._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGenerateAnswer: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1alpha/{model=models/*}:generateAnswer", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = generative_service.GenerateAnswerRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseGenerativeServiceRestTransport._BaseGenerateAnswer._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGenerateContent: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1alpha/{model=models/*}:generateContent", + "body": "*", + }, + { + "method": "post", + "uri": "/v1alpha/{model=tunedModels/*}:generateContent", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = generative_service.GenerateContentRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseGenerativeServiceRestTransport._BaseGenerateContent._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseStreamGenerateContent: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1alpha/{model=models/*}:streamGenerateContent", + "body": "*", + }, + { + "method": "post", + "uri": "/v1alpha/{model=tunedModels/*}:streamGenerateContent", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = generative_service.GenerateContentRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseGenerativeServiceRestTransport._BaseStreamGenerateContent._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1alpha/{name=tunedModels/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1alpha/{name=generatedFiles/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1alpha/{name=models/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1alpha/{name=tunedModels/*}/operations", + }, + { + "method": "get", + "uri": "/v1alpha/{name=models/*}/operations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BaseGenerativeServiceRestTransport",) diff --git a/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/permission_service/__init__.py b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/permission_service/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ff0f9217fa0e90a2f614fa48c595aa762b7e91ef --- /dev/null +++ b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/permission_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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. +# +from .async_client import PermissionServiceAsyncClient +from .client import PermissionServiceClient + +__all__ = ( + "PermissionServiceClient", + "PermissionServiceAsyncClient", +) diff --git a/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/permission_service/transports/__init__.py b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/permission_service/transports/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..05310b85abe50444b025effbd0de643a76f343d6 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/permission_service/transports/__init__.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import PermissionServiceTransport +from .grpc import PermissionServiceGrpcTransport +from .grpc_asyncio import PermissionServiceGrpcAsyncIOTransport +from .rest import PermissionServiceRestInterceptor, PermissionServiceRestTransport + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[PermissionServiceTransport]] +_transport_registry["grpc"] = PermissionServiceGrpcTransport +_transport_registry["grpc_asyncio"] = PermissionServiceGrpcAsyncIOTransport +_transport_registry["rest"] = PermissionServiceRestTransport + +__all__ = ( + "PermissionServiceTransport", + "PermissionServiceGrpcTransport", + "PermissionServiceGrpcAsyncIOTransport", + "PermissionServiceRestTransport", + "PermissionServiceRestInterceptor", +) diff --git a/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/permission_service/transports/__pycache__/base.cpython-311.pyc b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/permission_service/transports/__pycache__/base.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5e4815c24b884b40f64c749c7686783be0bced6f Binary files /dev/null and b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/permission_service/transports/__pycache__/base.cpython-311.pyc differ diff --git a/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/permission_service/transports/__pycache__/grpc_asyncio.cpython-311.pyc b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/permission_service/transports/__pycache__/grpc_asyncio.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ece3b80047994e7ee75e367218ef592e4ef38e1d Binary files /dev/null and b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/permission_service/transports/__pycache__/grpc_asyncio.cpython-311.pyc differ diff --git a/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/permission_service/transports/base.py b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/permission_service/transports/base.py new file mode 100644 index 0000000000000000000000000000000000000000..b7201aa373aa7ba7949f32cbf5b31bb5fe5eb143 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/permission_service/transports/base.py @@ -0,0 +1,272 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account # type: ignore +from google.protobuf import empty_pb2 # type: ignore + +from google.ai.generativelanguage_v1alpha import gapic_version as package_version +from google.ai.generativelanguage_v1alpha.types import permission as gag_permission +from google.ai.generativelanguage_v1alpha.types import permission +from google.ai.generativelanguage_v1alpha.types import permission_service + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + + +class PermissionServiceTransport(abc.ABC): + """Abstract transport class for PermissionService.""" + + AUTH_SCOPES = () + + DEFAULT_HOST: str = "generativelanguage.googleapis.com" + + def __init__( + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'generativelanguage.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + if not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id + ) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_permission: gapic_v1.method.wrap_method( + self.create_permission, + default_timeout=None, + client_info=client_info, + ), + self.get_permission: gapic_v1.method.wrap_method( + self.get_permission, + default_timeout=None, + client_info=client_info, + ), + self.list_permissions: gapic_v1.method.wrap_method( + self.list_permissions, + default_timeout=None, + client_info=client_info, + ), + self.update_permission: gapic_v1.method.wrap_method( + self.update_permission, + default_timeout=None, + client_info=client_info, + ), + self.delete_permission: gapic_v1.method.wrap_method( + self.delete_permission, + default_timeout=None, + client_info=client_info, + ), + self.transfer_ownership: gapic_v1.method.wrap_method( + self.transfer_ownership, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def create_permission( + self, + ) -> Callable[ + [permission_service.CreatePermissionRequest], + Union[gag_permission.Permission, Awaitable[gag_permission.Permission]], + ]: + raise NotImplementedError() + + @property + def get_permission( + self, + ) -> Callable[ + [permission_service.GetPermissionRequest], + Union[permission.Permission, Awaitable[permission.Permission]], + ]: + raise NotImplementedError() + + @property + def list_permissions( + self, + ) -> Callable[ + [permission_service.ListPermissionsRequest], + Union[ + permission_service.ListPermissionsResponse, + Awaitable[permission_service.ListPermissionsResponse], + ], + ]: + raise NotImplementedError() + + @property + def update_permission( + self, + ) -> Callable[ + [permission_service.UpdatePermissionRequest], + Union[gag_permission.Permission, Awaitable[gag_permission.Permission]], + ]: + raise NotImplementedError() + + @property + def delete_permission( + self, + ) -> Callable[ + [permission_service.DeletePermissionRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + @property + def transfer_ownership( + self, + ) -> Callable[ + [permission_service.TransferOwnershipRequest], + Union[ + permission_service.TransferOwnershipResponse, + Awaitable[permission_service.TransferOwnershipResponse], + ], + ]: + raise NotImplementedError() + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], + Union[ + operations_pb2.ListOperationsResponse, + Awaitable[operations_pb2.ListOperationsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("PermissionServiceTransport",) diff --git a/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/permission_service/transports/grpc.py b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/permission_service/transports/grpc.py new file mode 100644 index 0000000000000000000000000000000000000000..c5f22f7aa880b8527d9a97e261f4585c5512e29e --- /dev/null +++ b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/permission_service/transports/grpc.py @@ -0,0 +1,541 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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. +# +import json +import logging as std_logging +import pickle +from typing import Callable, Dict, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import gapic_v1, grpc_helpers +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore + +from google.ai.generativelanguage_v1alpha.types import permission as gag_permission +from google.ai.generativelanguage_v1alpha.types import permission +from google.ai.generativelanguage_v1alpha.types import permission_service + +from .base import DEFAULT_CLIENT_INFO, PermissionServiceTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER + def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.PermissionService", + "rpcName": client_call_details.method, + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + + response = continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = response.result() + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response for {client_call_details.method}.", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.PermissionService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class PermissionServiceGrpcTransport(PermissionServiceTransport): + """gRPC backend transport for PermissionService. + + Provides methods for managing permissions to PaLM API + resources. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _stubs: Dict[str, Callable] + + def __init__( + self, + *, + host: str = "generativelanguage.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'generativelanguage.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientInterceptor() + self._logged_channel = grpc.intercept_channel( + self._grpc_channel, self._interceptor + ) + + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel( + cls, + host: str = "generativelanguage.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service.""" + return self._grpc_channel + + @property + def create_permission( + self, + ) -> Callable[ + [permission_service.CreatePermissionRequest], gag_permission.Permission + ]: + r"""Return a callable for the create permission method over gRPC. + + Create a permission to a specific resource. + + Returns: + Callable[[~.CreatePermissionRequest], + ~.Permission]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_permission" not in self._stubs: + self._stubs["create_permission"] = self._logged_channel.unary_unary( + "/google.ai.generativelanguage.v1alpha.PermissionService/CreatePermission", + request_serializer=permission_service.CreatePermissionRequest.serialize, + response_deserializer=gag_permission.Permission.deserialize, + ) + return self._stubs["create_permission"] + + @property + def get_permission( + self, + ) -> Callable[[permission_service.GetPermissionRequest], permission.Permission]: + r"""Return a callable for the get permission method over gRPC. + + Gets information about a specific Permission. + + Returns: + Callable[[~.GetPermissionRequest], + ~.Permission]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_permission" not in self._stubs: + self._stubs["get_permission"] = self._logged_channel.unary_unary( + "/google.ai.generativelanguage.v1alpha.PermissionService/GetPermission", + request_serializer=permission_service.GetPermissionRequest.serialize, + response_deserializer=permission.Permission.deserialize, + ) + return self._stubs["get_permission"] + + @property + def list_permissions( + self, + ) -> Callable[ + [permission_service.ListPermissionsRequest], + permission_service.ListPermissionsResponse, + ]: + r"""Return a callable for the list permissions method over gRPC. + + Lists permissions for the specific resource. + + Returns: + Callable[[~.ListPermissionsRequest], + ~.ListPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_permissions" not in self._stubs: + self._stubs["list_permissions"] = self._logged_channel.unary_unary( + "/google.ai.generativelanguage.v1alpha.PermissionService/ListPermissions", + request_serializer=permission_service.ListPermissionsRequest.serialize, + response_deserializer=permission_service.ListPermissionsResponse.deserialize, + ) + return self._stubs["list_permissions"] + + @property + def update_permission( + self, + ) -> Callable[ + [permission_service.UpdatePermissionRequest], gag_permission.Permission + ]: + r"""Return a callable for the update permission method over gRPC. + + Updates the permission. + + Returns: + Callable[[~.UpdatePermissionRequest], + ~.Permission]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_permission" not in self._stubs: + self._stubs["update_permission"] = self._logged_channel.unary_unary( + "/google.ai.generativelanguage.v1alpha.PermissionService/UpdatePermission", + request_serializer=permission_service.UpdatePermissionRequest.serialize, + response_deserializer=gag_permission.Permission.deserialize, + ) + return self._stubs["update_permission"] + + @property + def delete_permission( + self, + ) -> Callable[[permission_service.DeletePermissionRequest], empty_pb2.Empty]: + r"""Return a callable for the delete permission method over gRPC. + + Deletes the permission. + + Returns: + Callable[[~.DeletePermissionRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_permission" not in self._stubs: + self._stubs["delete_permission"] = self._logged_channel.unary_unary( + "/google.ai.generativelanguage.v1alpha.PermissionService/DeletePermission", + request_serializer=permission_service.DeletePermissionRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_permission"] + + @property + def transfer_ownership( + self, + ) -> Callable[ + [permission_service.TransferOwnershipRequest], + permission_service.TransferOwnershipResponse, + ]: + r"""Return a callable for the transfer ownership method over gRPC. + + Transfers ownership of the tuned model. + This is the only way to change ownership of the tuned + model. The current owner will be downgraded to writer + role. + + Returns: + Callable[[~.TransferOwnershipRequest], + ~.TransferOwnershipResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "transfer_ownership" not in self._stubs: + self._stubs["transfer_ownership"] = self._logged_channel.unary_unary( + "/google.ai.generativelanguage.v1alpha.PermissionService/TransferOwnership", + request_serializer=permission_service.TransferOwnershipRequest.serialize, + response_deserializer=permission_service.TransferOwnershipResponse.deserialize, + ) + return self._stubs["transfer_ownership"] + + def close(self): + self._logged_channel.close() + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ("PermissionServiceGrpcTransport",) diff --git a/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/permission_service/transports/grpc_asyncio.py b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/permission_service/transports/grpc_asyncio.py new file mode 100644 index 0000000000000000000000000000000000000000..134d9d3270436fbcbb998ba0fb2100c28ca087ca --- /dev/null +++ b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/permission_service/transports/grpc_asyncio.py @@ -0,0 +1,604 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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. +# +import inspect +import json +import logging as std_logging +import pickle +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, grpc_helpers_async +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson +import google.protobuf.message +import grpc # type: ignore +from grpc.experimental import aio # type: ignore +import proto # type: ignore + +from google.ai.generativelanguage_v1alpha.types import permission as gag_permission +from google.ai.generativelanguage_v1alpha.types import permission +from google.ai.generativelanguage_v1alpha.types import permission_service + +from .base import DEFAULT_CLIENT_INFO, PermissionServiceTransport +from .grpc import PermissionServiceGrpcTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientAIOInterceptor( + grpc.aio.UnaryUnaryClientInterceptor +): # pragma: NO COVER + async def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.PermissionService", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = await continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = await response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = await response + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response to rpc {client_call_details.method}.", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.PermissionService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class PermissionServiceGrpcAsyncIOTransport(PermissionServiceTransport): + """gRPC AsyncIO backend transport for PermissionService. + + Provides methods for managing permissions to PaLM API + resources. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel( + cls, + host: str = "generativelanguage.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "generativelanguage.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'generativelanguage.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientAIOInterceptor() + self._grpc_channel._unary_unary_interceptors.append(self._interceptor) + self._logged_channel = self._grpc_channel + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def create_permission( + self, + ) -> Callable[ + [permission_service.CreatePermissionRequest], + Awaitable[gag_permission.Permission], + ]: + r"""Return a callable for the create permission method over gRPC. + + Create a permission to a specific resource. + + Returns: + Callable[[~.CreatePermissionRequest], + Awaitable[~.Permission]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_permission" not in self._stubs: + self._stubs["create_permission"] = self._logged_channel.unary_unary( + "/google.ai.generativelanguage.v1alpha.PermissionService/CreatePermission", + request_serializer=permission_service.CreatePermissionRequest.serialize, + response_deserializer=gag_permission.Permission.deserialize, + ) + return self._stubs["create_permission"] + + @property + def get_permission( + self, + ) -> Callable[ + [permission_service.GetPermissionRequest], Awaitable[permission.Permission] + ]: + r"""Return a callable for the get permission method over gRPC. + + Gets information about a specific Permission. + + Returns: + Callable[[~.GetPermissionRequest], + Awaitable[~.Permission]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_permission" not in self._stubs: + self._stubs["get_permission"] = self._logged_channel.unary_unary( + "/google.ai.generativelanguage.v1alpha.PermissionService/GetPermission", + request_serializer=permission_service.GetPermissionRequest.serialize, + response_deserializer=permission.Permission.deserialize, + ) + return self._stubs["get_permission"] + + @property + def list_permissions( + self, + ) -> Callable[ + [permission_service.ListPermissionsRequest], + Awaitable[permission_service.ListPermissionsResponse], + ]: + r"""Return a callable for the list permissions method over gRPC. + + Lists permissions for the specific resource. + + Returns: + Callable[[~.ListPermissionsRequest], + Awaitable[~.ListPermissionsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_permissions" not in self._stubs: + self._stubs["list_permissions"] = self._logged_channel.unary_unary( + "/google.ai.generativelanguage.v1alpha.PermissionService/ListPermissions", + request_serializer=permission_service.ListPermissionsRequest.serialize, + response_deserializer=permission_service.ListPermissionsResponse.deserialize, + ) + return self._stubs["list_permissions"] + + @property + def update_permission( + self, + ) -> Callable[ + [permission_service.UpdatePermissionRequest], + Awaitable[gag_permission.Permission], + ]: + r"""Return a callable for the update permission method over gRPC. + + Updates the permission. + + Returns: + Callable[[~.UpdatePermissionRequest], + Awaitable[~.Permission]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_permission" not in self._stubs: + self._stubs["update_permission"] = self._logged_channel.unary_unary( + "/google.ai.generativelanguage.v1alpha.PermissionService/UpdatePermission", + request_serializer=permission_service.UpdatePermissionRequest.serialize, + response_deserializer=gag_permission.Permission.deserialize, + ) + return self._stubs["update_permission"] + + @property + def delete_permission( + self, + ) -> Callable[ + [permission_service.DeletePermissionRequest], Awaitable[empty_pb2.Empty] + ]: + r"""Return a callable for the delete permission method over gRPC. + + Deletes the permission. + + Returns: + Callable[[~.DeletePermissionRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_permission" not in self._stubs: + self._stubs["delete_permission"] = self._logged_channel.unary_unary( + "/google.ai.generativelanguage.v1alpha.PermissionService/DeletePermission", + request_serializer=permission_service.DeletePermissionRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_permission"] + + @property + def transfer_ownership( + self, + ) -> Callable[ + [permission_service.TransferOwnershipRequest], + Awaitable[permission_service.TransferOwnershipResponse], + ]: + r"""Return a callable for the transfer ownership method over gRPC. + + Transfers ownership of the tuned model. + This is the only way to change ownership of the tuned + model. The current owner will be downgraded to writer + role. + + Returns: + Callable[[~.TransferOwnershipRequest], + Awaitable[~.TransferOwnershipResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "transfer_ownership" not in self._stubs: + self._stubs["transfer_ownership"] = self._logged_channel.unary_unary( + "/google.ai.generativelanguage.v1alpha.PermissionService/TransferOwnership", + request_serializer=permission_service.TransferOwnershipRequest.serialize, + response_deserializer=permission_service.TransferOwnershipResponse.deserialize, + ) + return self._stubs["transfer_ownership"] + + def _prep_wrapped_messages(self, client_info): + """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.create_permission: self._wrap_method( + self.create_permission, + default_timeout=None, + client_info=client_info, + ), + self.get_permission: self._wrap_method( + self.get_permission, + default_timeout=None, + client_info=client_info, + ), + self.list_permissions: self._wrap_method( + self.list_permissions, + default_timeout=None, + client_info=client_info, + ), + self.update_permission: self._wrap_method( + self.update_permission, + default_timeout=None, + client_info=client_info, + ), + self.delete_permission: self._wrap_method( + self.delete_permission, + default_timeout=None, + client_info=client_info, + ), + self.transfer_ownership: self._wrap_method( + self.transfer_ownership, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + } + + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + + def close(self): + return self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + +__all__ = ("PermissionServiceGrpcAsyncIOTransport",) diff --git a/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/permission_service/transports/rest.py b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/permission_service/transports/rest.py new file mode 100644 index 0000000000000000000000000000000000000000..559cf0c08038c58c3e4a6dc2dce8f99b61a34b39 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/permission_service/transports/rest.py @@ -0,0 +1,1671 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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. +# +import dataclasses +import json # type: ignore +import logging +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, rest_helpers, rest_streaming +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import json_format +from requests import __version__ as requests_version + +from google.ai.generativelanguage_v1alpha.types import permission as gag_permission +from google.ai.generativelanguage_v1alpha.types import permission +from google.ai.generativelanguage_v1alpha.types import permission_service + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BasePermissionServiceRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = logging.getLogger(__name__) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=f"requests@{requests_version}", +) + + +class PermissionServiceRestInterceptor: + """Interceptor for PermissionService. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the PermissionServiceRestTransport. + + .. code-block:: python + class MyCustomPermissionServiceInterceptor(PermissionServiceRestInterceptor): + def pre_create_permission(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_permission(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_permission(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_get_permission(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_permission(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_permissions(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_permissions(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_transfer_ownership(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_transfer_ownership(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_permission(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_permission(self, response): + logging.log(f"Received response: {response}") + return response + + transport = PermissionServiceRestTransport(interceptor=MyCustomPermissionServiceInterceptor()) + client = PermissionServiceClient(transport=transport) + + + """ + + def pre_create_permission( + self, + request: permission_service.CreatePermissionRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + permission_service.CreatePermissionRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for create_permission + + Override in a subclass to manipulate the request or metadata + before they are sent to the PermissionService server. + """ + return request, metadata + + def post_create_permission( + self, response: gag_permission.Permission + ) -> gag_permission.Permission: + """Post-rpc interceptor for create_permission + + Override in a subclass to manipulate the response + after it is returned by the PermissionService server but before + it is returned to user code. + """ + return response + + def pre_delete_permission( + self, + request: permission_service.DeletePermissionRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + permission_service.DeletePermissionRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for delete_permission + + Override in a subclass to manipulate the request or metadata + before they are sent to the PermissionService server. + """ + return request, metadata + + def pre_get_permission( + self, + request: permission_service.GetPermissionRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + permission_service.GetPermissionRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_permission + + Override in a subclass to manipulate the request or metadata + before they are sent to the PermissionService server. + """ + return request, metadata + + def post_get_permission( + self, response: permission.Permission + ) -> permission.Permission: + """Post-rpc interceptor for get_permission + + Override in a subclass to manipulate the response + after it is returned by the PermissionService server but before + it is returned to user code. + """ + return response + + def pre_list_permissions( + self, + request: permission_service.ListPermissionsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + permission_service.ListPermissionsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for list_permissions + + Override in a subclass to manipulate the request or metadata + before they are sent to the PermissionService server. + """ + return request, metadata + + def post_list_permissions( + self, response: permission_service.ListPermissionsResponse + ) -> permission_service.ListPermissionsResponse: + """Post-rpc interceptor for list_permissions + + Override in a subclass to manipulate the response + after it is returned by the PermissionService server but before + it is returned to user code. + """ + return response + + def pre_transfer_ownership( + self, + request: permission_service.TransferOwnershipRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + permission_service.TransferOwnershipRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for transfer_ownership + + Override in a subclass to manipulate the request or metadata + before they are sent to the PermissionService server. + """ + return request, metadata + + def post_transfer_ownership( + self, response: permission_service.TransferOwnershipResponse + ) -> permission_service.TransferOwnershipResponse: + """Post-rpc interceptor for transfer_ownership + + Override in a subclass to manipulate the response + after it is returned by the PermissionService server but before + it is returned to user code. + """ + return response + + def pre_update_permission( + self, + request: permission_service.UpdatePermissionRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + permission_service.UpdatePermissionRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for update_permission + + Override in a subclass to manipulate the request or metadata + before they are sent to the PermissionService server. + """ + return request, metadata + + def post_update_permission( + self, response: gag_permission.Permission + ) -> gag_permission.Permission: + """Post-rpc interceptor for update_permission + + Override in a subclass to manipulate the response + after it is returned by the PermissionService server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, + request: operations_pb2.GetOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the PermissionService server. + """ + return request, metadata + + def post_get_operation( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for get_operation + + Override in a subclass to manipulate the response + after it is returned by the PermissionService server but before + it is returned to user code. + """ + return response + + def pre_list_operations( + self, + request: operations_pb2.ListOperationsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.ListOperationsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the PermissionService server. + """ + return request, metadata + + def post_list_operations( + self, response: operations_pb2.ListOperationsResponse + ) -> operations_pb2.ListOperationsResponse: + """Post-rpc interceptor for list_operations + + Override in a subclass to manipulate the response + after it is returned by the PermissionService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class PermissionServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: PermissionServiceRestInterceptor + + +class PermissionServiceRestTransport(_BasePermissionServiceRestTransport): + """REST backend synchronous transport for PermissionService. + + Provides methods for managing permissions to PaLM API + resources. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "generativelanguage.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[PermissionServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'generativelanguage.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + url_scheme=url_scheme, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or PermissionServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _CreatePermission( + _BasePermissionServiceRestTransport._BaseCreatePermission, + PermissionServiceRestStub, + ): + def __hash__(self): + return hash("PermissionServiceRestTransport.CreatePermission") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: permission_service.CreatePermissionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gag_permission.Permission: + r"""Call the create permission method over HTTP. + + Args: + request (~.permission_service.CreatePermissionRequest): + The request object. Request to create a ``Permission``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.gag_permission.Permission: + Permission resource grants user, + group or the rest of the world access to + the PaLM API resource (e.g. a tuned + model, corpus). + + A role is a collection of permitted + operations that allows users to perform + specific actions on PaLM API resources. + To make them available to users, groups, + or service accounts, you assign roles. + When you assign a role, you grant + permissions that the role contains. + + There are three concentric roles. Each + role is a superset of the previous + role's permitted operations: + + - reader can use the resource (e.g. + tuned model, corpus) for inference + - writer has reader's permissions and + additionally can edit and share + - owner has writer's permissions and + additionally can delete + + """ + + http_options = ( + _BasePermissionServiceRestTransport._BaseCreatePermission._get_http_options() + ) + + request, metadata = self._interceptor.pre_create_permission( + request, metadata + ) + transcoded_request = _BasePermissionServiceRestTransport._BaseCreatePermission._get_transcoded_request( + http_options, request + ) + + body = _BasePermissionServiceRestTransport._BaseCreatePermission._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BasePermissionServiceRestTransport._BaseCreatePermission._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ai.generativelanguage_v1alpha.PermissionServiceClient.CreatePermission", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.PermissionService", + "rpcName": "CreatePermission", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = PermissionServiceRestTransport._CreatePermission._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gag_permission.Permission() + pb_resp = gag_permission.Permission.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_permission(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = gag_permission.Permission.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.ai.generativelanguage_v1alpha.PermissionServiceClient.create_permission", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.PermissionService", + "rpcName": "CreatePermission", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeletePermission( + _BasePermissionServiceRestTransport._BaseDeletePermission, + PermissionServiceRestStub, + ): + def __hash__(self): + return hash("PermissionServiceRestTransport.DeletePermission") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: permission_service.DeletePermissionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + r"""Call the delete permission method over HTTP. + + Args: + request (~.permission_service.DeletePermissionRequest): + The request object. Request to delete the ``Permission``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = ( + _BasePermissionServiceRestTransport._BaseDeletePermission._get_http_options() + ) + + request, metadata = self._interceptor.pre_delete_permission( + request, metadata + ) + transcoded_request = _BasePermissionServiceRestTransport._BaseDeletePermission._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BasePermissionServiceRestTransport._BaseDeletePermission._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ai.generativelanguage_v1alpha.PermissionServiceClient.DeletePermission", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.PermissionService", + "rpcName": "DeletePermission", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = PermissionServiceRestTransport._DeletePermission._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _GetPermission( + _BasePermissionServiceRestTransport._BaseGetPermission, + PermissionServiceRestStub, + ): + def __hash__(self): + return hash("PermissionServiceRestTransport.GetPermission") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: permission_service.GetPermissionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> permission.Permission: + r"""Call the get permission method over HTTP. + + Args: + request (~.permission_service.GetPermissionRequest): + The request object. Request for getting information about a specific + ``Permission``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.permission.Permission: + Permission resource grants user, + group or the rest of the world access to + the PaLM API resource (e.g. a tuned + model, corpus). + + A role is a collection of permitted + operations that allows users to perform + specific actions on PaLM API resources. + To make them available to users, groups, + or service accounts, you assign roles. + When you assign a role, you grant + permissions that the role contains. + + There are three concentric roles. Each + role is a superset of the previous + role's permitted operations: + + - reader can use the resource (e.g. + tuned model, corpus) for inference + - writer has reader's permissions and + additionally can edit and share + - owner has writer's permissions and + additionally can delete + + """ + + http_options = ( + _BasePermissionServiceRestTransport._BaseGetPermission._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_permission(request, metadata) + transcoded_request = _BasePermissionServiceRestTransport._BaseGetPermission._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BasePermissionServiceRestTransport._BaseGetPermission._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ai.generativelanguage_v1alpha.PermissionServiceClient.GetPermission", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.PermissionService", + "rpcName": "GetPermission", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = PermissionServiceRestTransport._GetPermission._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = permission.Permission() + pb_resp = permission.Permission.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_permission(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = permission.Permission.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.ai.generativelanguage_v1alpha.PermissionServiceClient.get_permission", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.PermissionService", + "rpcName": "GetPermission", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListPermissions( + _BasePermissionServiceRestTransport._BaseListPermissions, + PermissionServiceRestStub, + ): + def __hash__(self): + return hash("PermissionServiceRestTransport.ListPermissions") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: permission_service.ListPermissionsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> permission_service.ListPermissionsResponse: + r"""Call the list permissions method over HTTP. + + Args: + request (~.permission_service.ListPermissionsRequest): + The request object. Request for listing permissions. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.permission_service.ListPermissionsResponse: + Response from ``ListPermissions`` containing a paginated + list of permissions. + + """ + + http_options = ( + _BasePermissionServiceRestTransport._BaseListPermissions._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_permissions( + request, metadata + ) + transcoded_request = _BasePermissionServiceRestTransport._BaseListPermissions._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BasePermissionServiceRestTransport._BaseListPermissions._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ai.generativelanguage_v1alpha.PermissionServiceClient.ListPermissions", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.PermissionService", + "rpcName": "ListPermissions", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = PermissionServiceRestTransport._ListPermissions._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = permission_service.ListPermissionsResponse() + pb_resp = permission_service.ListPermissionsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_permissions(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + permission_service.ListPermissionsResponse.to_json(response) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.ai.generativelanguage_v1alpha.PermissionServiceClient.list_permissions", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.PermissionService", + "rpcName": "ListPermissions", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _TransferOwnership( + _BasePermissionServiceRestTransport._BaseTransferOwnership, + PermissionServiceRestStub, + ): + def __hash__(self): + return hash("PermissionServiceRestTransport.TransferOwnership") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: permission_service.TransferOwnershipRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> permission_service.TransferOwnershipResponse: + r"""Call the transfer ownership method over HTTP. + + Args: + request (~.permission_service.TransferOwnershipRequest): + The request object. Request to transfer the ownership of + the tuned model. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.permission_service.TransferOwnershipResponse: + Response from ``TransferOwnership``. + """ + + http_options = ( + _BasePermissionServiceRestTransport._BaseTransferOwnership._get_http_options() + ) + + request, metadata = self._interceptor.pre_transfer_ownership( + request, metadata + ) + transcoded_request = _BasePermissionServiceRestTransport._BaseTransferOwnership._get_transcoded_request( + http_options, request + ) + + body = _BasePermissionServiceRestTransport._BaseTransferOwnership._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BasePermissionServiceRestTransport._BaseTransferOwnership._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ai.generativelanguage_v1alpha.PermissionServiceClient.TransferOwnership", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.PermissionService", + "rpcName": "TransferOwnership", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = PermissionServiceRestTransport._TransferOwnership._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = permission_service.TransferOwnershipResponse() + pb_resp = permission_service.TransferOwnershipResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_transfer_ownership(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + permission_service.TransferOwnershipResponse.to_json(response) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.ai.generativelanguage_v1alpha.PermissionServiceClient.transfer_ownership", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.PermissionService", + "rpcName": "TransferOwnership", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdatePermission( + _BasePermissionServiceRestTransport._BaseUpdatePermission, + PermissionServiceRestStub, + ): + def __hash__(self): + return hash("PermissionServiceRestTransport.UpdatePermission") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: permission_service.UpdatePermissionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gag_permission.Permission: + r"""Call the update permission method over HTTP. + + Args: + request (~.permission_service.UpdatePermissionRequest): + The request object. Request to update the ``Permission``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.gag_permission.Permission: + Permission resource grants user, + group or the rest of the world access to + the PaLM API resource (e.g. a tuned + model, corpus). + + A role is a collection of permitted + operations that allows users to perform + specific actions on PaLM API resources. + To make them available to users, groups, + or service accounts, you assign roles. + When you assign a role, you grant + permissions that the role contains. + + There are three concentric roles. Each + role is a superset of the previous + role's permitted operations: + + - reader can use the resource (e.g. + tuned model, corpus) for inference + - writer has reader's permissions and + additionally can edit and share + - owner has writer's permissions and + additionally can delete + + """ + + http_options = ( + _BasePermissionServiceRestTransport._BaseUpdatePermission._get_http_options() + ) + + request, metadata = self._interceptor.pre_update_permission( + request, metadata + ) + transcoded_request = _BasePermissionServiceRestTransport._BaseUpdatePermission._get_transcoded_request( + http_options, request + ) + + body = _BasePermissionServiceRestTransport._BaseUpdatePermission._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BasePermissionServiceRestTransport._BaseUpdatePermission._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ai.generativelanguage_v1alpha.PermissionServiceClient.UpdatePermission", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.PermissionService", + "rpcName": "UpdatePermission", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = PermissionServiceRestTransport._UpdatePermission._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gag_permission.Permission() + pb_resp = gag_permission.Permission.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_permission(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = gag_permission.Permission.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.ai.generativelanguage_v1alpha.PermissionServiceClient.update_permission", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.PermissionService", + "rpcName": "UpdatePermission", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def create_permission( + self, + ) -> Callable[ + [permission_service.CreatePermissionRequest], gag_permission.Permission + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreatePermission(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_permission( + self, + ) -> Callable[[permission_service.DeletePermissionRequest], empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeletePermission(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_permission( + self, + ) -> Callable[[permission_service.GetPermissionRequest], permission.Permission]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetPermission(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_permissions( + self, + ) -> Callable[ + [permission_service.ListPermissionsRequest], + permission_service.ListPermissionsResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListPermissions(self._session, self._host, self._interceptor) # type: ignore + + @property + def transfer_ownership( + self, + ) -> Callable[ + [permission_service.TransferOwnershipRequest], + permission_service.TransferOwnershipResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._TransferOwnership(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_permission( + self, + ) -> Callable[ + [permission_service.UpdatePermissionRequest], gag_permission.Permission + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdatePermission(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation( + _BasePermissionServiceRestTransport._BaseGetOperation, PermissionServiceRestStub + ): + def __hash__(self): + return hash("PermissionServiceRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.GetOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options = ( + _BasePermissionServiceRestTransport._BaseGetOperation._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + transcoded_request = _BasePermissionServiceRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BasePermissionServiceRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ai.generativelanguage_v1alpha.PermissionServiceClient.GetOperation", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.PermissionService", + "rpcName": "GetOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = PermissionServiceRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.Operation() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_operation(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.ai.generativelanguage_v1alpha.PermissionServiceAsyncClient.GetOperation", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.PermissionService", + "rpcName": "GetOperation", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations( + _BasePermissionServiceRestTransport._BaseListOperations, + PermissionServiceRestStub, + ): + def __hash__(self): + return hash("PermissionServiceRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.ListOperationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options = ( + _BasePermissionServiceRestTransport._BaseListOperations._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + transcoded_request = _BasePermissionServiceRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BasePermissionServiceRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ai.generativelanguage_v1alpha.PermissionServiceClient.ListOperations", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.PermissionService", + "rpcName": "ListOperations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = PermissionServiceRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_list_operations(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.ai.generativelanguage_v1alpha.PermissionServiceAsyncClient.ListOperations", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.PermissionService", + "rpcName": "ListOperations", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("PermissionServiceRestTransport",) diff --git a/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/permission_service/transports/rest_base.py b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/permission_service/transports/rest_base.py new file mode 100644 index 0000000000000000000000000000000000000000..56e09878b0232320d8660ca0f3cd613a1fa13cc8 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/permission_service/transports/rest_base.py @@ -0,0 +1,493 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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. +# +import json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import json_format + +from google.ai.generativelanguage_v1alpha.types import permission as gag_permission +from google.ai.generativelanguage_v1alpha.types import permission +from google.ai.generativelanguage_v1alpha.types import permission_service + +from .base import DEFAULT_CLIENT_INFO, PermissionServiceTransport + + +class _BasePermissionServiceRestTransport(PermissionServiceTransport): + """Base REST backend transport for PermissionService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "generativelanguage.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'generativelanguage.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + class _BaseCreatePermission: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1alpha/{parent=tunedModels/*}/permissions", + "body": "permission", + }, + { + "method": "post", + "uri": "/v1alpha/{parent=corpora/*}/permissions", + "body": "permission", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = permission_service.CreatePermissionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePermissionServiceRestTransport._BaseCreatePermission._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeletePermission: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1alpha/{name=tunedModels/*/permissions/*}", + }, + { + "method": "delete", + "uri": "/v1alpha/{name=corpora/*/permissions/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = permission_service.DeletePermissionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePermissionServiceRestTransport._BaseDeletePermission._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetPermission: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1alpha/{name=tunedModels/*/permissions/*}", + }, + { + "method": "get", + "uri": "/v1alpha/{name=corpora/*/permissions/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = permission_service.GetPermissionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePermissionServiceRestTransport._BaseGetPermission._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListPermissions: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1alpha/{parent=tunedModels/*}/permissions", + }, + { + "method": "get", + "uri": "/v1alpha/{parent=corpora/*}/permissions", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = permission_service.ListPermissionsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePermissionServiceRestTransport._BaseListPermissions._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseTransferOwnership: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1alpha/{name=tunedModels/*}:transferOwnership", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = permission_service.TransferOwnershipRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePermissionServiceRestTransport._BaseTransferOwnership._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdatePermission: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask": {}, + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1alpha/{permission.name=tunedModels/*/permissions/*}", + "body": "permission", + }, + { + "method": "patch", + "uri": "/v1alpha/{permission.name=corpora/*/permissions/*}", + "body": "permission", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = permission_service.UpdatePermissionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePermissionServiceRestTransport._BaseUpdatePermission._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1alpha/{name=tunedModels/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1alpha/{name=generatedFiles/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1alpha/{name=models/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1alpha/{name=tunedModels/*}/operations", + }, + { + "method": "get", + "uri": "/v1alpha/{name=models/*}/operations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BasePermissionServiceRestTransport",) diff --git a/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/retriever_service/__init__.py b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/retriever_service/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8c3e3ba77075b21168f0b696e7df23a715a60a9c --- /dev/null +++ b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/retriever_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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. +# +from .async_client import RetrieverServiceAsyncClient +from .client import RetrieverServiceClient + +__all__ = ( + "RetrieverServiceClient", + "RetrieverServiceAsyncClient", +) diff --git a/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/retriever_service/__pycache__/__init__.cpython-311.pyc b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/retriever_service/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ea14c2e56f3a5cbf793c1ce0213a7c61abbafc4d Binary files /dev/null and b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/retriever_service/__pycache__/__init__.cpython-311.pyc differ diff --git a/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/retriever_service/__pycache__/async_client.cpython-311.pyc b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/retriever_service/__pycache__/async_client.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dde7e4159697fdb9b83581abe04622bd41e747ac Binary files /dev/null and b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/retriever_service/__pycache__/async_client.cpython-311.pyc differ diff --git a/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/retriever_service/__pycache__/pagers.cpython-311.pyc b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/retriever_service/__pycache__/pagers.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..215a2920ef443f8b624740b108010a9e7487b8d1 Binary files /dev/null and b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/retriever_service/__pycache__/pagers.cpython-311.pyc differ diff --git a/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/retriever_service/async_client.py b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/retriever_service/async_client.py new file mode 100644 index 0000000000000000000000000000000000000000..e04f95549d7b614e9f0f589da784b3f81e110f7f --- /dev/null +++ b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/retriever_service/async_client.py @@ -0,0 +1,2499 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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. +# +from collections import OrderedDict +import logging as std_logging +import re +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) + +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.api_core.client_options import ClientOptions +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.ai.generativelanguage_v1alpha import gapic_version as package_version + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + +from google.ai.generativelanguage_v1alpha.services.retriever_service import pagers +from google.ai.generativelanguage_v1alpha.types import retriever, retriever_service + +from .client import RetrieverServiceClient +from .transports.base import DEFAULT_CLIENT_INFO, RetrieverServiceTransport +from .transports.grpc_asyncio import RetrieverServiceGrpcAsyncIOTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class RetrieverServiceAsyncClient: + """An API for semantic search over a corpus of user uploaded + content. + """ + + _client: RetrieverServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = RetrieverServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = RetrieverServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = RetrieverServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = RetrieverServiceClient._DEFAULT_UNIVERSE + + chunk_path = staticmethod(RetrieverServiceClient.chunk_path) + parse_chunk_path = staticmethod(RetrieverServiceClient.parse_chunk_path) + corpus_path = staticmethod(RetrieverServiceClient.corpus_path) + parse_corpus_path = staticmethod(RetrieverServiceClient.parse_corpus_path) + document_path = staticmethod(RetrieverServiceClient.document_path) + parse_document_path = staticmethod(RetrieverServiceClient.parse_document_path) + common_billing_account_path = staticmethod( + RetrieverServiceClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + RetrieverServiceClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod(RetrieverServiceClient.common_folder_path) + parse_common_folder_path = staticmethod( + RetrieverServiceClient.parse_common_folder_path + ) + common_organization_path = staticmethod( + RetrieverServiceClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + RetrieverServiceClient.parse_common_organization_path + ) + common_project_path = staticmethod(RetrieverServiceClient.common_project_path) + parse_common_project_path = staticmethod( + RetrieverServiceClient.parse_common_project_path + ) + common_location_path = staticmethod(RetrieverServiceClient.common_location_path) + parse_common_location_path = staticmethod( + RetrieverServiceClient.parse_common_location_path + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + RetrieverServiceAsyncClient: The constructed client. + """ + return RetrieverServiceClient.from_service_account_info.__func__(RetrieverServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + RetrieverServiceAsyncClient: The constructed client. + """ + return RetrieverServiceClient.from_service_account_file.__func__(RetrieverServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return RetrieverServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> RetrieverServiceTransport: + """Returns the transport used by the client instance. + + Returns: + RetrieverServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = RetrieverServiceClient.get_transport_class + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[ + str, RetrieverServiceTransport, Callable[..., RetrieverServiceTransport] + ] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the retriever service async client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,RetrieverServiceTransport,Callable[..., RetrieverServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the RetrieverServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = RetrieverServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.ai.generativelanguage_v1alpha.RetrieverServiceAsyncClient`.", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.RetrieverService", + "universeDomain": getattr( + self._client._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._client._transport, "_credentials") + else { + "serviceName": "google.ai.generativelanguage.v1alpha.RetrieverService", + "credentialsType": None, + }, + ) + + async def create_corpus( + self, + request: Optional[Union[retriever_service.CreateCorpusRequest, dict]] = None, + *, + corpus: Optional[retriever.Corpus] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> retriever.Corpus: + r"""Creates an empty ``Corpus``. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ai import generativelanguage_v1alpha + + async def sample_create_corpus(): + # Create a client + client = generativelanguage_v1alpha.RetrieverServiceAsyncClient() + + # Initialize request argument(s) + request = generativelanguage_v1alpha.CreateCorpusRequest( + ) + + # Make the request + response = await client.create_corpus(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.ai.generativelanguage_v1alpha.types.CreateCorpusRequest, dict]]): + The request object. Request to create a ``Corpus``. + corpus (:class:`google.ai.generativelanguage_v1alpha.types.Corpus`): + Required. The ``Corpus`` to create. + This corresponds to the ``corpus`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ai.generativelanguage_v1alpha.types.Corpus: + A Corpus is a collection of Documents. + A project can create up to 5 corpora. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([corpus]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, retriever_service.CreateCorpusRequest): + request = retriever_service.CreateCorpusRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if corpus is not None: + request.corpus = corpus + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_corpus + ] + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_corpus( + self, + request: Optional[Union[retriever_service.GetCorpusRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> retriever.Corpus: + r"""Gets information about a specific ``Corpus``. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ai import generativelanguage_v1alpha + + async def sample_get_corpus(): + # Create a client + client = generativelanguage_v1alpha.RetrieverServiceAsyncClient() + + # Initialize request argument(s) + request = generativelanguage_v1alpha.GetCorpusRequest( + name="name_value", + ) + + # Make the request + response = await client.get_corpus(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.ai.generativelanguage_v1alpha.types.GetCorpusRequest, dict]]): + The request object. Request for getting information about a specific + ``Corpus``. + name (:class:`str`): + Required. The name of the ``Corpus``. Example: + ``corpora/my-corpus-123`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ai.generativelanguage_v1alpha.types.Corpus: + A Corpus is a collection of Documents. + A project can create up to 5 corpora. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, retriever_service.GetCorpusRequest): + request = retriever_service.GetCorpusRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_corpus + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_corpus( + self, + request: Optional[Union[retriever_service.UpdateCorpusRequest, dict]] = None, + *, + corpus: Optional[retriever.Corpus] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> retriever.Corpus: + r"""Updates a ``Corpus``. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ai import generativelanguage_v1alpha + + async def sample_update_corpus(): + # Create a client + client = generativelanguage_v1alpha.RetrieverServiceAsyncClient() + + # Initialize request argument(s) + request = generativelanguage_v1alpha.UpdateCorpusRequest( + ) + + # Make the request + response = await client.update_corpus(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.ai.generativelanguage_v1alpha.types.UpdateCorpusRequest, dict]]): + The request object. Request to update a ``Corpus``. + corpus (:class:`google.ai.generativelanguage_v1alpha.types.Corpus`): + Required. The ``Corpus`` to update. + This corresponds to the ``corpus`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. The list of fields to update. Currently, this + only supports updating ``display_name``. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ai.generativelanguage_v1alpha.types.Corpus: + A Corpus is a collection of Documents. + A project can create up to 5 corpora. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([corpus, update_mask]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, retriever_service.UpdateCorpusRequest): + request = retriever_service.UpdateCorpusRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if corpus is not None: + request.corpus = corpus + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_corpus + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("corpus.name", request.corpus.name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_corpus( + self, + request: Optional[Union[retriever_service.DeleteCorpusRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a ``Corpus``. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ai import generativelanguage_v1alpha + + async def sample_delete_corpus(): + # Create a client + client = generativelanguage_v1alpha.RetrieverServiceAsyncClient() + + # Initialize request argument(s) + request = generativelanguage_v1alpha.DeleteCorpusRequest( + name="name_value", + ) + + # Make the request + await client.delete_corpus(request=request) + + Args: + request (Optional[Union[google.ai.generativelanguage_v1alpha.types.DeleteCorpusRequest, dict]]): + The request object. Request to delete a ``Corpus``. + name (:class:`str`): + Required. The resource name of the ``Corpus``. Example: + ``corpora/my-corpus-123`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, retriever_service.DeleteCorpusRequest): + request = retriever_service.DeleteCorpusRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_corpus + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def list_corpora( + self, + request: Optional[Union[retriever_service.ListCorporaRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListCorporaAsyncPager: + r"""Lists all ``Corpora`` owned by the user. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ai import generativelanguage_v1alpha + + async def sample_list_corpora(): + # Create a client + client = generativelanguage_v1alpha.RetrieverServiceAsyncClient() + + # Initialize request argument(s) + request = generativelanguage_v1alpha.ListCorporaRequest( + ) + + # Make the request + page_result = client.list_corpora(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.ai.generativelanguage_v1alpha.types.ListCorporaRequest, dict]]): + The request object. Request for listing ``Corpora``. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ai.generativelanguage_v1alpha.services.retriever_service.pagers.ListCorporaAsyncPager: + Response from ListCorpora containing a paginated list of Corpora. + The results are sorted by ascending + corpus.create_time. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, retriever_service.ListCorporaRequest): + request = retriever_service.ListCorporaRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_corpora + ] + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListCorporaAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def query_corpus( + self, + request: Optional[Union[retriever_service.QueryCorpusRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> retriever_service.QueryCorpusResponse: + r"""Performs semantic search over a ``Corpus``. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ai import generativelanguage_v1alpha + + async def sample_query_corpus(): + # Create a client + client = generativelanguage_v1alpha.RetrieverServiceAsyncClient() + + # Initialize request argument(s) + request = generativelanguage_v1alpha.QueryCorpusRequest( + name="name_value", + query="query_value", + ) + + # Make the request + response = await client.query_corpus(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.ai.generativelanguage_v1alpha.types.QueryCorpusRequest, dict]]): + The request object. Request for querying a ``Corpus``. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ai.generativelanguage_v1alpha.types.QueryCorpusResponse: + Response from QueryCorpus containing a list of relevant + chunks. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, retriever_service.QueryCorpusRequest): + request = retriever_service.QueryCorpusRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.query_corpus + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_document( + self, + request: Optional[Union[retriever_service.CreateDocumentRequest, dict]] = None, + *, + parent: Optional[str] = None, + document: Optional[retriever.Document] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> retriever.Document: + r"""Creates an empty ``Document``. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ai import generativelanguage_v1alpha + + async def sample_create_document(): + # Create a client + client = generativelanguage_v1alpha.RetrieverServiceAsyncClient() + + # Initialize request argument(s) + request = generativelanguage_v1alpha.CreateDocumentRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_document(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.ai.generativelanguage_v1alpha.types.CreateDocumentRequest, dict]]): + The request object. Request to create a ``Document``. + parent (:class:`str`): + Required. The name of the ``Corpus`` where this + ``Document`` will be created. Example: + ``corpora/my-corpus-123`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + document (:class:`google.ai.generativelanguage_v1alpha.types.Document`): + Required. The ``Document`` to create. + This corresponds to the ``document`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ai.generativelanguage_v1alpha.types.Document: + A Document is a collection of Chunks. + A Corpus can have a maximum of 10,000 Documents. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, document]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, retriever_service.CreateDocumentRequest): + request = retriever_service.CreateDocumentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if document is not None: + request.document = document + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_document + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_document( + self, + request: Optional[Union[retriever_service.GetDocumentRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> retriever.Document: + r"""Gets information about a specific ``Document``. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ai import generativelanguage_v1alpha + + async def sample_get_document(): + # Create a client + client = generativelanguage_v1alpha.RetrieverServiceAsyncClient() + + # Initialize request argument(s) + request = generativelanguage_v1alpha.GetDocumentRequest( + name="name_value", + ) + + # Make the request + response = await client.get_document(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.ai.generativelanguage_v1alpha.types.GetDocumentRequest, dict]]): + The request object. Request for getting information about a specific + ``Document``. + name (:class:`str`): + Required. The name of the ``Document`` to retrieve. + Example: ``corpora/my-corpus-123/documents/the-doc-abc`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ai.generativelanguage_v1alpha.types.Document: + A Document is a collection of Chunks. + A Corpus can have a maximum of 10,000 Documents. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, retriever_service.GetDocumentRequest): + request = retriever_service.GetDocumentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_document + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_document( + self, + request: Optional[Union[retriever_service.UpdateDocumentRequest, dict]] = None, + *, + document: Optional[retriever.Document] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> retriever.Document: + r"""Updates a ``Document``. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ai import generativelanguage_v1alpha + + async def sample_update_document(): + # Create a client + client = generativelanguage_v1alpha.RetrieverServiceAsyncClient() + + # Initialize request argument(s) + request = generativelanguage_v1alpha.UpdateDocumentRequest( + ) + + # Make the request + response = await client.update_document(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.ai.generativelanguage_v1alpha.types.UpdateDocumentRequest, dict]]): + The request object. Request to update a ``Document``. + document (:class:`google.ai.generativelanguage_v1alpha.types.Document`): + Required. The ``Document`` to update. + This corresponds to the ``document`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. The list of fields to update. Currently, this + only supports updating ``display_name`` and + ``custom_metadata``. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ai.generativelanguage_v1alpha.types.Document: + A Document is a collection of Chunks. + A Corpus can have a maximum of 10,000 Documents. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([document, update_mask]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, retriever_service.UpdateDocumentRequest): + request = retriever_service.UpdateDocumentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if document is not None: + request.document = document + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_document + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("document.name", request.document.name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_document( + self, + request: Optional[Union[retriever_service.DeleteDocumentRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a ``Document``. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ai import generativelanguage_v1alpha + + async def sample_delete_document(): + # Create a client + client = generativelanguage_v1alpha.RetrieverServiceAsyncClient() + + # Initialize request argument(s) + request = generativelanguage_v1alpha.DeleteDocumentRequest( + name="name_value", + ) + + # Make the request + await client.delete_document(request=request) + + Args: + request (Optional[Union[google.ai.generativelanguage_v1alpha.types.DeleteDocumentRequest, dict]]): + The request object. Request to delete a ``Document``. + name (:class:`str`): + Required. The resource name of the ``Document`` to + delete. Example: + ``corpora/my-corpus-123/documents/the-doc-abc`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, retriever_service.DeleteDocumentRequest): + request = retriever_service.DeleteDocumentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_document + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def list_documents( + self, + request: Optional[Union[retriever_service.ListDocumentsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListDocumentsAsyncPager: + r"""Lists all ``Document``\ s in a ``Corpus``. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ai import generativelanguage_v1alpha + + async def sample_list_documents(): + # Create a client + client = generativelanguage_v1alpha.RetrieverServiceAsyncClient() + + # Initialize request argument(s) + request = generativelanguage_v1alpha.ListDocumentsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_documents(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.ai.generativelanguage_v1alpha.types.ListDocumentsRequest, dict]]): + The request object. Request for listing ``Document``\ s. + parent (:class:`str`): + Required. The name of the ``Corpus`` containing + ``Document``\ s. Example: ``corpora/my-corpus-123`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ai.generativelanguage_v1alpha.services.retriever_service.pagers.ListDocumentsAsyncPager: + Response from ListDocuments containing a paginated list of Documents. + The Documents are sorted by ascending + document.create_time. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, retriever_service.ListDocumentsRequest): + request = retriever_service.ListDocumentsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_documents + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListDocumentsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def query_document( + self, + request: Optional[Union[retriever_service.QueryDocumentRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> retriever_service.QueryDocumentResponse: + r"""Performs semantic search over a ``Document``. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ai import generativelanguage_v1alpha + + async def sample_query_document(): + # Create a client + client = generativelanguage_v1alpha.RetrieverServiceAsyncClient() + + # Initialize request argument(s) + request = generativelanguage_v1alpha.QueryDocumentRequest( + name="name_value", + query="query_value", + ) + + # Make the request + response = await client.query_document(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.ai.generativelanguage_v1alpha.types.QueryDocumentRequest, dict]]): + The request object. Request for querying a ``Document``. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ai.generativelanguage_v1alpha.types.QueryDocumentResponse: + Response from QueryDocument containing a list of + relevant chunks. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, retriever_service.QueryDocumentRequest): + request = retriever_service.QueryDocumentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.query_document + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_chunk( + self, + request: Optional[Union[retriever_service.CreateChunkRequest, dict]] = None, + *, + parent: Optional[str] = None, + chunk: Optional[retriever.Chunk] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> retriever.Chunk: + r"""Creates a ``Chunk``. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ai import generativelanguage_v1alpha + + async def sample_create_chunk(): + # Create a client + client = generativelanguage_v1alpha.RetrieverServiceAsyncClient() + + # Initialize request argument(s) + chunk = generativelanguage_v1alpha.Chunk() + chunk.data.string_value = "string_value_value" + + request = generativelanguage_v1alpha.CreateChunkRequest( + parent="parent_value", + chunk=chunk, + ) + + # Make the request + response = await client.create_chunk(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.ai.generativelanguage_v1alpha.types.CreateChunkRequest, dict]]): + The request object. Request to create a ``Chunk``. + parent (:class:`str`): + Required. The name of the ``Document`` where this + ``Chunk`` will be created. Example: + ``corpora/my-corpus-123/documents/the-doc-abc`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + chunk (:class:`google.ai.generativelanguage_v1alpha.types.Chunk`): + Required. The ``Chunk`` to create. + This corresponds to the ``chunk`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ai.generativelanguage_v1alpha.types.Chunk: + A Chunk is a subpart of a Document that is treated as an independent unit + for the purposes of vector representation and + storage. A Corpus can have a maximum of 1 million + Chunks. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, chunk]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, retriever_service.CreateChunkRequest): + request = retriever_service.CreateChunkRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if chunk is not None: + request.chunk = chunk + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_chunk + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def batch_create_chunks( + self, + request: Optional[ + Union[retriever_service.BatchCreateChunksRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> retriever_service.BatchCreateChunksResponse: + r"""Batch create ``Chunk``\ s. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ai import generativelanguage_v1alpha + + async def sample_batch_create_chunks(): + # Create a client + client = generativelanguage_v1alpha.RetrieverServiceAsyncClient() + + # Initialize request argument(s) + requests = generativelanguage_v1alpha.CreateChunkRequest() + requests.parent = "parent_value" + requests.chunk.data.string_value = "string_value_value" + + request = generativelanguage_v1alpha.BatchCreateChunksRequest( + requests=requests, + ) + + # Make the request + response = await client.batch_create_chunks(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.ai.generativelanguage_v1alpha.types.BatchCreateChunksRequest, dict]]): + The request object. Request to batch create ``Chunk``\ s. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ai.generativelanguage_v1alpha.types.BatchCreateChunksResponse: + Response from BatchCreateChunks containing a list of + created Chunks. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, retriever_service.BatchCreateChunksRequest): + request = retriever_service.BatchCreateChunksRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.batch_create_chunks + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_chunk( + self, + request: Optional[Union[retriever_service.GetChunkRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> retriever.Chunk: + r"""Gets information about a specific ``Chunk``. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ai import generativelanguage_v1alpha + + async def sample_get_chunk(): + # Create a client + client = generativelanguage_v1alpha.RetrieverServiceAsyncClient() + + # Initialize request argument(s) + request = generativelanguage_v1alpha.GetChunkRequest( + name="name_value", + ) + + # Make the request + response = await client.get_chunk(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.ai.generativelanguage_v1alpha.types.GetChunkRequest, dict]]): + The request object. Request for getting information about a specific + ``Chunk``. + name (:class:`str`): + Required. The name of the ``Chunk`` to retrieve. + Example: + ``corpora/my-corpus-123/documents/the-doc-abc/chunks/some-chunk`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ai.generativelanguage_v1alpha.types.Chunk: + A Chunk is a subpart of a Document that is treated as an independent unit + for the purposes of vector representation and + storage. A Corpus can have a maximum of 1 million + Chunks. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, retriever_service.GetChunkRequest): + request = retriever_service.GetChunkRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_chunk + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_chunk( + self, + request: Optional[Union[retriever_service.UpdateChunkRequest, dict]] = None, + *, + chunk: Optional[retriever.Chunk] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> retriever.Chunk: + r"""Updates a ``Chunk``. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ai import generativelanguage_v1alpha + + async def sample_update_chunk(): + # Create a client + client = generativelanguage_v1alpha.RetrieverServiceAsyncClient() + + # Initialize request argument(s) + chunk = generativelanguage_v1alpha.Chunk() + chunk.data.string_value = "string_value_value" + + request = generativelanguage_v1alpha.UpdateChunkRequest( + chunk=chunk, + ) + + # Make the request + response = await client.update_chunk(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.ai.generativelanguage_v1alpha.types.UpdateChunkRequest, dict]]): + The request object. Request to update a ``Chunk``. + chunk (:class:`google.ai.generativelanguage_v1alpha.types.Chunk`): + Required. The ``Chunk`` to update. + This corresponds to the ``chunk`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. The list of fields to update. Currently, this + only supports updating ``custom_metadata`` and ``data``. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ai.generativelanguage_v1alpha.types.Chunk: + A Chunk is a subpart of a Document that is treated as an independent unit + for the purposes of vector representation and + storage. A Corpus can have a maximum of 1 million + Chunks. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([chunk, update_mask]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, retriever_service.UpdateChunkRequest): + request = retriever_service.UpdateChunkRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if chunk is not None: + request.chunk = chunk + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_chunk + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("chunk.name", request.chunk.name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def batch_update_chunks( + self, + request: Optional[ + Union[retriever_service.BatchUpdateChunksRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> retriever_service.BatchUpdateChunksResponse: + r"""Batch update ``Chunk``\ s. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ai import generativelanguage_v1alpha + + async def sample_batch_update_chunks(): + # Create a client + client = generativelanguage_v1alpha.RetrieverServiceAsyncClient() + + # Initialize request argument(s) + requests = generativelanguage_v1alpha.UpdateChunkRequest() + requests.chunk.data.string_value = "string_value_value" + + request = generativelanguage_v1alpha.BatchUpdateChunksRequest( + requests=requests, + ) + + # Make the request + response = await client.batch_update_chunks(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.ai.generativelanguage_v1alpha.types.BatchUpdateChunksRequest, dict]]): + The request object. Request to batch update ``Chunk``\ s. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ai.generativelanguage_v1alpha.types.BatchUpdateChunksResponse: + Response from BatchUpdateChunks containing a list of + updated Chunks. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, retriever_service.BatchUpdateChunksRequest): + request = retriever_service.BatchUpdateChunksRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.batch_update_chunks + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_chunk( + self, + request: Optional[Union[retriever_service.DeleteChunkRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a ``Chunk``. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ai import generativelanguage_v1alpha + + async def sample_delete_chunk(): + # Create a client + client = generativelanguage_v1alpha.RetrieverServiceAsyncClient() + + # Initialize request argument(s) + request = generativelanguage_v1alpha.DeleteChunkRequest( + name="name_value", + ) + + # Make the request + await client.delete_chunk(request=request) + + Args: + request (Optional[Union[google.ai.generativelanguage_v1alpha.types.DeleteChunkRequest, dict]]): + The request object. Request to delete a ``Chunk``. + name (:class:`str`): + Required. The resource name of the ``Chunk`` to delete. + Example: + ``corpora/my-corpus-123/documents/the-doc-abc/chunks/some-chunk`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, retriever_service.DeleteChunkRequest): + request = retriever_service.DeleteChunkRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_chunk + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def batch_delete_chunks( + self, + request: Optional[ + Union[retriever_service.BatchDeleteChunksRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Batch delete ``Chunk``\ s. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ai import generativelanguage_v1alpha + + async def sample_batch_delete_chunks(): + # Create a client + client = generativelanguage_v1alpha.RetrieverServiceAsyncClient() + + # Initialize request argument(s) + requests = generativelanguage_v1alpha.DeleteChunkRequest() + requests.name = "name_value" + + request = generativelanguage_v1alpha.BatchDeleteChunksRequest( + requests=requests, + ) + + # Make the request + await client.batch_delete_chunks(request=request) + + Args: + request (Optional[Union[google.ai.generativelanguage_v1alpha.types.BatchDeleteChunksRequest, dict]]): + The request object. Request to batch delete ``Chunk``\ s. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, retriever_service.BatchDeleteChunksRequest): + request = retriever_service.BatchDeleteChunksRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.batch_delete_chunks + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def list_chunks( + self, + request: Optional[Union[retriever_service.ListChunksRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListChunksAsyncPager: + r"""Lists all ``Chunk``\ s in a ``Document``. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ai import generativelanguage_v1alpha + + async def sample_list_chunks(): + # Create a client + client = generativelanguage_v1alpha.RetrieverServiceAsyncClient() + + # Initialize request argument(s) + request = generativelanguage_v1alpha.ListChunksRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_chunks(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.ai.generativelanguage_v1alpha.types.ListChunksRequest, dict]]): + The request object. Request for listing ``Chunk``\ s. + parent (:class:`str`): + Required. The name of the ``Document`` containing + ``Chunk``\ s. Example: + ``corpora/my-corpus-123/documents/the-doc-abc`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ai.generativelanguage_v1alpha.services.retriever_service.pagers.ListChunksAsyncPager: + Response from ListChunks containing a paginated list of Chunks. + The Chunks are sorted by ascending chunk.create_time. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, retriever_service.ListChunksRequest): + request = retriever_service.ListChunksRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_chunks + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListChunksAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self) -> "RetrieverServiceAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + + +__all__ = ("RetrieverServiceAsyncClient",) diff --git a/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/retriever_service/client.py b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/retriever_service/client.py new file mode 100644 index 0000000000000000000000000000000000000000..bfc549edba330d325afaeb99e6ec8fdb70a49b13 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/retriever_service/client.py @@ -0,0 +1,2875 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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. +# +from collections import OrderedDict +import logging as std_logging +import os +import re +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) +import warnings + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.ai.generativelanguage_v1alpha import gapic_version as package_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + +from google.ai.generativelanguage_v1alpha.services.retriever_service import pagers +from google.ai.generativelanguage_v1alpha.types import retriever, retriever_service + +from .transports.base import DEFAULT_CLIENT_INFO, RetrieverServiceTransport +from .transports.grpc import RetrieverServiceGrpcTransport +from .transports.grpc_asyncio import RetrieverServiceGrpcAsyncIOTransport +from .transports.rest import RetrieverServiceRestTransport + + +class RetrieverServiceClientMeta(type): + """Metaclass for the RetrieverService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = ( + OrderedDict() + ) # type: Dict[str, Type[RetrieverServiceTransport]] + _transport_registry["grpc"] = RetrieverServiceGrpcTransport + _transport_registry["grpc_asyncio"] = RetrieverServiceGrpcAsyncIOTransport + _transport_registry["rest"] = RetrieverServiceRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[RetrieverServiceTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class RetrieverServiceClient(metaclass=RetrieverServiceClientMeta): + """An API for semantic search over a corpus of user uploaded + content. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "generativelanguage.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "generativelanguage.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + RetrieverServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + RetrieverServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> RetrieverServiceTransport: + """Returns the transport used by the client instance. + + Returns: + RetrieverServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def chunk_path( + corpus: str, + document: str, + chunk: str, + ) -> str: + """Returns a fully-qualified chunk string.""" + return "corpora/{corpus}/documents/{document}/chunks/{chunk}".format( + corpus=corpus, + document=document, + chunk=chunk, + ) + + @staticmethod + def parse_chunk_path(path: str) -> Dict[str, str]: + """Parses a chunk path into its component segments.""" + m = re.match( + r"^corpora/(?P.+?)/documents/(?P.+?)/chunks/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def corpus_path( + corpus: str, + ) -> str: + """Returns a fully-qualified corpus string.""" + return "corpora/{corpus}".format( + corpus=corpus, + ) + + @staticmethod + def parse_corpus_path(path: str) -> Dict[str, str]: + """Parses a corpus path into its component segments.""" + m = re.match(r"^corpora/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def document_path( + corpus: str, + document: str, + ) -> str: + """Returns a fully-qualified document string.""" + return "corpora/{corpus}/documents/{document}".format( + corpus=corpus, + document=document, + ) + + @staticmethod + def parse_document_path(path: str) -> Dict[str, str]: + """Parses a document path into its component segments.""" + m = re.match(r"^corpora/(?P.+?)/documents/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path( + billing_account: str, + ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path( + folder: str, + ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format( + folder=folder, + ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path( + organization: str, + ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format( + organization=organization, + ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path( + project: str, + ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format( + project=project, + ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path( + project: str, + location: str, + ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_client_cert not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ): + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + _default_universe = RetrieverServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = RetrieverServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = RetrieverServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) + return api_endpoint + + @staticmethod + def _get_universe_domain( + client_universe_domain: Optional[str], universe_domain_env: Optional[str] + ) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = RetrieverServiceClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[ + str, RetrieverServiceTransport, Callable[..., RetrieverServiceTransport] + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the retriever service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,RetrieverServiceTransport,Callable[..., RetrieverServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the RetrieverServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) + + universe_domain_opt = getattr(self._client_options, "universe_domain", None) + + ( + self._use_client_cert, + self._use_mtls_endpoint, + self._universe_domain_env, + ) = RetrieverServiceClient._read_environment_variables() + self._client_cert_source = RetrieverServiceClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = RetrieverServiceClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + self._api_endpoint = None # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, RetrieverServiceTransport) + if transport_provided: + # transport is a RetrieverServiceTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = cast(RetrieverServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = ( + self._api_endpoint + or RetrieverServiceClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint, + ) + ) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + + transport_init: Union[ + Type[RetrieverServiceTransport], + Callable[..., RetrieverServiceTransport], + ] = ( + RetrieverServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., RetrieverServiceTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.ai.generativelanguage_v1alpha.RetrieverServiceClient`.", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.RetrieverService", + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { + "serviceName": "google.ai.generativelanguage.v1alpha.RetrieverService", + "credentialsType": None, + }, + ) + + def create_corpus( + self, + request: Optional[Union[retriever_service.CreateCorpusRequest, dict]] = None, + *, + corpus: Optional[retriever.Corpus] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> retriever.Corpus: + r"""Creates an empty ``Corpus``. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ai import generativelanguage_v1alpha + + def sample_create_corpus(): + # Create a client + client = generativelanguage_v1alpha.RetrieverServiceClient() + + # Initialize request argument(s) + request = generativelanguage_v1alpha.CreateCorpusRequest( + ) + + # Make the request + response = client.create_corpus(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.ai.generativelanguage_v1alpha.types.CreateCorpusRequest, dict]): + The request object. Request to create a ``Corpus``. + corpus (google.ai.generativelanguage_v1alpha.types.Corpus): + Required. The ``Corpus`` to create. + This corresponds to the ``corpus`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ai.generativelanguage_v1alpha.types.Corpus: + A Corpus is a collection of Documents. + A project can create up to 5 corpora. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([corpus]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, retriever_service.CreateCorpusRequest): + request = retriever_service.CreateCorpusRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if corpus is not None: + request.corpus = corpus + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_corpus] + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_corpus( + self, + request: Optional[Union[retriever_service.GetCorpusRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> retriever.Corpus: + r"""Gets information about a specific ``Corpus``. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ai import generativelanguage_v1alpha + + def sample_get_corpus(): + # Create a client + client = generativelanguage_v1alpha.RetrieverServiceClient() + + # Initialize request argument(s) + request = generativelanguage_v1alpha.GetCorpusRequest( + name="name_value", + ) + + # Make the request + response = client.get_corpus(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.ai.generativelanguage_v1alpha.types.GetCorpusRequest, dict]): + The request object. Request for getting information about a specific + ``Corpus``. + name (str): + Required. The name of the ``Corpus``. Example: + ``corpora/my-corpus-123`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ai.generativelanguage_v1alpha.types.Corpus: + A Corpus is a collection of Documents. + A project can create up to 5 corpora. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, retriever_service.GetCorpusRequest): + request = retriever_service.GetCorpusRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_corpus] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_corpus( + self, + request: Optional[Union[retriever_service.UpdateCorpusRequest, dict]] = None, + *, + corpus: Optional[retriever.Corpus] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> retriever.Corpus: + r"""Updates a ``Corpus``. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ai import generativelanguage_v1alpha + + def sample_update_corpus(): + # Create a client + client = generativelanguage_v1alpha.RetrieverServiceClient() + + # Initialize request argument(s) + request = generativelanguage_v1alpha.UpdateCorpusRequest( + ) + + # Make the request + response = client.update_corpus(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.ai.generativelanguage_v1alpha.types.UpdateCorpusRequest, dict]): + The request object. Request to update a ``Corpus``. + corpus (google.ai.generativelanguage_v1alpha.types.Corpus): + Required. The ``Corpus`` to update. + This corresponds to the ``corpus`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to update. Currently, this + only supports updating ``display_name``. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ai.generativelanguage_v1alpha.types.Corpus: + A Corpus is a collection of Documents. + A project can create up to 5 corpora. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([corpus, update_mask]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, retriever_service.UpdateCorpusRequest): + request = retriever_service.UpdateCorpusRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if corpus is not None: + request.corpus = corpus + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_corpus] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("corpus.name", request.corpus.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_corpus( + self, + request: Optional[Union[retriever_service.DeleteCorpusRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a ``Corpus``. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ai import generativelanguage_v1alpha + + def sample_delete_corpus(): + # Create a client + client = generativelanguage_v1alpha.RetrieverServiceClient() + + # Initialize request argument(s) + request = generativelanguage_v1alpha.DeleteCorpusRequest( + name="name_value", + ) + + # Make the request + client.delete_corpus(request=request) + + Args: + request (Union[google.ai.generativelanguage_v1alpha.types.DeleteCorpusRequest, dict]): + The request object. Request to delete a ``Corpus``. + name (str): + Required. The resource name of the ``Corpus``. Example: + ``corpora/my-corpus-123`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, retriever_service.DeleteCorpusRequest): + request = retriever_service.DeleteCorpusRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_corpus] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def list_corpora( + self, + request: Optional[Union[retriever_service.ListCorporaRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListCorporaPager: + r"""Lists all ``Corpora`` owned by the user. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ai import generativelanguage_v1alpha + + def sample_list_corpora(): + # Create a client + client = generativelanguage_v1alpha.RetrieverServiceClient() + + # Initialize request argument(s) + request = generativelanguage_v1alpha.ListCorporaRequest( + ) + + # Make the request + page_result = client.list_corpora(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.ai.generativelanguage_v1alpha.types.ListCorporaRequest, dict]): + The request object. Request for listing ``Corpora``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ai.generativelanguage_v1alpha.services.retriever_service.pagers.ListCorporaPager: + Response from ListCorpora containing a paginated list of Corpora. + The results are sorted by ascending + corpus.create_time. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, retriever_service.ListCorporaRequest): + request = retriever_service.ListCorporaRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_corpora] + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListCorporaPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def query_corpus( + self, + request: Optional[Union[retriever_service.QueryCorpusRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> retriever_service.QueryCorpusResponse: + r"""Performs semantic search over a ``Corpus``. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ai import generativelanguage_v1alpha + + def sample_query_corpus(): + # Create a client + client = generativelanguage_v1alpha.RetrieverServiceClient() + + # Initialize request argument(s) + request = generativelanguage_v1alpha.QueryCorpusRequest( + name="name_value", + query="query_value", + ) + + # Make the request + response = client.query_corpus(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.ai.generativelanguage_v1alpha.types.QueryCorpusRequest, dict]): + The request object. Request for querying a ``Corpus``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ai.generativelanguage_v1alpha.types.QueryCorpusResponse: + Response from QueryCorpus containing a list of relevant + chunks. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, retriever_service.QueryCorpusRequest): + request = retriever_service.QueryCorpusRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.query_corpus] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_document( + self, + request: Optional[Union[retriever_service.CreateDocumentRequest, dict]] = None, + *, + parent: Optional[str] = None, + document: Optional[retriever.Document] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> retriever.Document: + r"""Creates an empty ``Document``. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ai import generativelanguage_v1alpha + + def sample_create_document(): + # Create a client + client = generativelanguage_v1alpha.RetrieverServiceClient() + + # Initialize request argument(s) + request = generativelanguage_v1alpha.CreateDocumentRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_document(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.ai.generativelanguage_v1alpha.types.CreateDocumentRequest, dict]): + The request object. Request to create a ``Document``. + parent (str): + Required. The name of the ``Corpus`` where this + ``Document`` will be created. Example: + ``corpora/my-corpus-123`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + document (google.ai.generativelanguage_v1alpha.types.Document): + Required. The ``Document`` to create. + This corresponds to the ``document`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ai.generativelanguage_v1alpha.types.Document: + A Document is a collection of Chunks. + A Corpus can have a maximum of 10,000 Documents. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, document]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, retriever_service.CreateDocumentRequest): + request = retriever_service.CreateDocumentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if document is not None: + request.document = document + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_document] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_document( + self, + request: Optional[Union[retriever_service.GetDocumentRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> retriever.Document: + r"""Gets information about a specific ``Document``. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ai import generativelanguage_v1alpha + + def sample_get_document(): + # Create a client + client = generativelanguage_v1alpha.RetrieverServiceClient() + + # Initialize request argument(s) + request = generativelanguage_v1alpha.GetDocumentRequest( + name="name_value", + ) + + # Make the request + response = client.get_document(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.ai.generativelanguage_v1alpha.types.GetDocumentRequest, dict]): + The request object. Request for getting information about a specific + ``Document``. + name (str): + Required. The name of the ``Document`` to retrieve. + Example: ``corpora/my-corpus-123/documents/the-doc-abc`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ai.generativelanguage_v1alpha.types.Document: + A Document is a collection of Chunks. + A Corpus can have a maximum of 10,000 Documents. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, retriever_service.GetDocumentRequest): + request = retriever_service.GetDocumentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_document] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_document( + self, + request: Optional[Union[retriever_service.UpdateDocumentRequest, dict]] = None, + *, + document: Optional[retriever.Document] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> retriever.Document: + r"""Updates a ``Document``. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ai import generativelanguage_v1alpha + + def sample_update_document(): + # Create a client + client = generativelanguage_v1alpha.RetrieverServiceClient() + + # Initialize request argument(s) + request = generativelanguage_v1alpha.UpdateDocumentRequest( + ) + + # Make the request + response = client.update_document(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.ai.generativelanguage_v1alpha.types.UpdateDocumentRequest, dict]): + The request object. Request to update a ``Document``. + document (google.ai.generativelanguage_v1alpha.types.Document): + Required. The ``Document`` to update. + This corresponds to the ``document`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to update. Currently, this + only supports updating ``display_name`` and + ``custom_metadata``. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ai.generativelanguage_v1alpha.types.Document: + A Document is a collection of Chunks. + A Corpus can have a maximum of 10,000 Documents. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([document, update_mask]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, retriever_service.UpdateDocumentRequest): + request = retriever_service.UpdateDocumentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if document is not None: + request.document = document + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_document] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("document.name", request.document.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_document( + self, + request: Optional[Union[retriever_service.DeleteDocumentRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a ``Document``. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ai import generativelanguage_v1alpha + + def sample_delete_document(): + # Create a client + client = generativelanguage_v1alpha.RetrieverServiceClient() + + # Initialize request argument(s) + request = generativelanguage_v1alpha.DeleteDocumentRequest( + name="name_value", + ) + + # Make the request + client.delete_document(request=request) + + Args: + request (Union[google.ai.generativelanguage_v1alpha.types.DeleteDocumentRequest, dict]): + The request object. Request to delete a ``Document``. + name (str): + Required. The resource name of the ``Document`` to + delete. Example: + ``corpora/my-corpus-123/documents/the-doc-abc`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, retriever_service.DeleteDocumentRequest): + request = retriever_service.DeleteDocumentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_document] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def list_documents( + self, + request: Optional[Union[retriever_service.ListDocumentsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListDocumentsPager: + r"""Lists all ``Document``\ s in a ``Corpus``. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ai import generativelanguage_v1alpha + + def sample_list_documents(): + # Create a client + client = generativelanguage_v1alpha.RetrieverServiceClient() + + # Initialize request argument(s) + request = generativelanguage_v1alpha.ListDocumentsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_documents(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.ai.generativelanguage_v1alpha.types.ListDocumentsRequest, dict]): + The request object. Request for listing ``Document``\ s. + parent (str): + Required. The name of the ``Corpus`` containing + ``Document``\ s. Example: ``corpora/my-corpus-123`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ai.generativelanguage_v1alpha.services.retriever_service.pagers.ListDocumentsPager: + Response from ListDocuments containing a paginated list of Documents. + The Documents are sorted by ascending + document.create_time. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, retriever_service.ListDocumentsRequest): + request = retriever_service.ListDocumentsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_documents] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListDocumentsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def query_document( + self, + request: Optional[Union[retriever_service.QueryDocumentRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> retriever_service.QueryDocumentResponse: + r"""Performs semantic search over a ``Document``. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ai import generativelanguage_v1alpha + + def sample_query_document(): + # Create a client + client = generativelanguage_v1alpha.RetrieverServiceClient() + + # Initialize request argument(s) + request = generativelanguage_v1alpha.QueryDocumentRequest( + name="name_value", + query="query_value", + ) + + # Make the request + response = client.query_document(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.ai.generativelanguage_v1alpha.types.QueryDocumentRequest, dict]): + The request object. Request for querying a ``Document``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ai.generativelanguage_v1alpha.types.QueryDocumentResponse: + Response from QueryDocument containing a list of + relevant chunks. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, retriever_service.QueryDocumentRequest): + request = retriever_service.QueryDocumentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.query_document] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_chunk( + self, + request: Optional[Union[retriever_service.CreateChunkRequest, dict]] = None, + *, + parent: Optional[str] = None, + chunk: Optional[retriever.Chunk] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> retriever.Chunk: + r"""Creates a ``Chunk``. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ai import generativelanguage_v1alpha + + def sample_create_chunk(): + # Create a client + client = generativelanguage_v1alpha.RetrieverServiceClient() + + # Initialize request argument(s) + chunk = generativelanguage_v1alpha.Chunk() + chunk.data.string_value = "string_value_value" + + request = generativelanguage_v1alpha.CreateChunkRequest( + parent="parent_value", + chunk=chunk, + ) + + # Make the request + response = client.create_chunk(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.ai.generativelanguage_v1alpha.types.CreateChunkRequest, dict]): + The request object. Request to create a ``Chunk``. + parent (str): + Required. The name of the ``Document`` where this + ``Chunk`` will be created. Example: + ``corpora/my-corpus-123/documents/the-doc-abc`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + chunk (google.ai.generativelanguage_v1alpha.types.Chunk): + Required. The ``Chunk`` to create. + This corresponds to the ``chunk`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ai.generativelanguage_v1alpha.types.Chunk: + A Chunk is a subpart of a Document that is treated as an independent unit + for the purposes of vector representation and + storage. A Corpus can have a maximum of 1 million + Chunks. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, chunk]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, retriever_service.CreateChunkRequest): + request = retriever_service.CreateChunkRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if chunk is not None: + request.chunk = chunk + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_chunk] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def batch_create_chunks( + self, + request: Optional[ + Union[retriever_service.BatchCreateChunksRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> retriever_service.BatchCreateChunksResponse: + r"""Batch create ``Chunk``\ s. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ai import generativelanguage_v1alpha + + def sample_batch_create_chunks(): + # Create a client + client = generativelanguage_v1alpha.RetrieverServiceClient() + + # Initialize request argument(s) + requests = generativelanguage_v1alpha.CreateChunkRequest() + requests.parent = "parent_value" + requests.chunk.data.string_value = "string_value_value" + + request = generativelanguage_v1alpha.BatchCreateChunksRequest( + requests=requests, + ) + + # Make the request + response = client.batch_create_chunks(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.ai.generativelanguage_v1alpha.types.BatchCreateChunksRequest, dict]): + The request object. Request to batch create ``Chunk``\ s. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ai.generativelanguage_v1alpha.types.BatchCreateChunksResponse: + Response from BatchCreateChunks containing a list of + created Chunks. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, retriever_service.BatchCreateChunksRequest): + request = retriever_service.BatchCreateChunksRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.batch_create_chunks] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_chunk( + self, + request: Optional[Union[retriever_service.GetChunkRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> retriever.Chunk: + r"""Gets information about a specific ``Chunk``. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ai import generativelanguage_v1alpha + + def sample_get_chunk(): + # Create a client + client = generativelanguage_v1alpha.RetrieverServiceClient() + + # Initialize request argument(s) + request = generativelanguage_v1alpha.GetChunkRequest( + name="name_value", + ) + + # Make the request + response = client.get_chunk(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.ai.generativelanguage_v1alpha.types.GetChunkRequest, dict]): + The request object. Request for getting information about a specific + ``Chunk``. + name (str): + Required. The name of the ``Chunk`` to retrieve. + Example: + ``corpora/my-corpus-123/documents/the-doc-abc/chunks/some-chunk`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ai.generativelanguage_v1alpha.types.Chunk: + A Chunk is a subpart of a Document that is treated as an independent unit + for the purposes of vector representation and + storage. A Corpus can have a maximum of 1 million + Chunks. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, retriever_service.GetChunkRequest): + request = retriever_service.GetChunkRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_chunk] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_chunk( + self, + request: Optional[Union[retriever_service.UpdateChunkRequest, dict]] = None, + *, + chunk: Optional[retriever.Chunk] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> retriever.Chunk: + r"""Updates a ``Chunk``. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ai import generativelanguage_v1alpha + + def sample_update_chunk(): + # Create a client + client = generativelanguage_v1alpha.RetrieverServiceClient() + + # Initialize request argument(s) + chunk = generativelanguage_v1alpha.Chunk() + chunk.data.string_value = "string_value_value" + + request = generativelanguage_v1alpha.UpdateChunkRequest( + chunk=chunk, + ) + + # Make the request + response = client.update_chunk(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.ai.generativelanguage_v1alpha.types.UpdateChunkRequest, dict]): + The request object. Request to update a ``Chunk``. + chunk (google.ai.generativelanguage_v1alpha.types.Chunk): + Required. The ``Chunk`` to update. + This corresponds to the ``chunk`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to update. Currently, this + only supports updating ``custom_metadata`` and ``data``. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ai.generativelanguage_v1alpha.types.Chunk: + A Chunk is a subpart of a Document that is treated as an independent unit + for the purposes of vector representation and + storage. A Corpus can have a maximum of 1 million + Chunks. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([chunk, update_mask]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, retriever_service.UpdateChunkRequest): + request = retriever_service.UpdateChunkRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if chunk is not None: + request.chunk = chunk + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_chunk] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("chunk.name", request.chunk.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def batch_update_chunks( + self, + request: Optional[ + Union[retriever_service.BatchUpdateChunksRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> retriever_service.BatchUpdateChunksResponse: + r"""Batch update ``Chunk``\ s. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ai import generativelanguage_v1alpha + + def sample_batch_update_chunks(): + # Create a client + client = generativelanguage_v1alpha.RetrieverServiceClient() + + # Initialize request argument(s) + requests = generativelanguage_v1alpha.UpdateChunkRequest() + requests.chunk.data.string_value = "string_value_value" + + request = generativelanguage_v1alpha.BatchUpdateChunksRequest( + requests=requests, + ) + + # Make the request + response = client.batch_update_chunks(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.ai.generativelanguage_v1alpha.types.BatchUpdateChunksRequest, dict]): + The request object. Request to batch update ``Chunk``\ s. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ai.generativelanguage_v1alpha.types.BatchUpdateChunksResponse: + Response from BatchUpdateChunks containing a list of + updated Chunks. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, retriever_service.BatchUpdateChunksRequest): + request = retriever_service.BatchUpdateChunksRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.batch_update_chunks] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_chunk( + self, + request: Optional[Union[retriever_service.DeleteChunkRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a ``Chunk``. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ai import generativelanguage_v1alpha + + def sample_delete_chunk(): + # Create a client + client = generativelanguage_v1alpha.RetrieverServiceClient() + + # Initialize request argument(s) + request = generativelanguage_v1alpha.DeleteChunkRequest( + name="name_value", + ) + + # Make the request + client.delete_chunk(request=request) + + Args: + request (Union[google.ai.generativelanguage_v1alpha.types.DeleteChunkRequest, dict]): + The request object. Request to delete a ``Chunk``. + name (str): + Required. The resource name of the ``Chunk`` to delete. + Example: + ``corpora/my-corpus-123/documents/the-doc-abc/chunks/some-chunk`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, retriever_service.DeleteChunkRequest): + request = retriever_service.DeleteChunkRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_chunk] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def batch_delete_chunks( + self, + request: Optional[ + Union[retriever_service.BatchDeleteChunksRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Batch delete ``Chunk``\ s. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ai import generativelanguage_v1alpha + + def sample_batch_delete_chunks(): + # Create a client + client = generativelanguage_v1alpha.RetrieverServiceClient() + + # Initialize request argument(s) + requests = generativelanguage_v1alpha.DeleteChunkRequest() + requests.name = "name_value" + + request = generativelanguage_v1alpha.BatchDeleteChunksRequest( + requests=requests, + ) + + # Make the request + client.batch_delete_chunks(request=request) + + Args: + request (Union[google.ai.generativelanguage_v1alpha.types.BatchDeleteChunksRequest, dict]): + The request object. Request to batch delete ``Chunk``\ s. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, retriever_service.BatchDeleteChunksRequest): + request = retriever_service.BatchDeleteChunksRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.batch_delete_chunks] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def list_chunks( + self, + request: Optional[Union[retriever_service.ListChunksRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListChunksPager: + r"""Lists all ``Chunk``\ s in a ``Document``. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.ai import generativelanguage_v1alpha + + def sample_list_chunks(): + # Create a client + client = generativelanguage_v1alpha.RetrieverServiceClient() + + # Initialize request argument(s) + request = generativelanguage_v1alpha.ListChunksRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_chunks(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.ai.generativelanguage_v1alpha.types.ListChunksRequest, dict]): + The request object. Request for listing ``Chunk``\ s. + parent (str): + Required. The name of the ``Document`` containing + ``Chunk``\ s. Example: + ``corpora/my-corpus-123/documents/the-doc-abc`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.ai.generativelanguage_v1alpha.services.retriever_service.pagers.ListChunksPager: + Response from ListChunks containing a paginated list of Chunks. + The Chunks are sorted by ascending chunk.create_time. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, retriever_service.ListChunksRequest): + request = retriever_service.ListChunksRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_chunks] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListChunksPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "RetrieverServiceClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_operations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + + +__all__ = ("RetrieverServiceClient",) diff --git a/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/retriever_service/pagers.py b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/retriever_service/pagers.py new file mode 100644 index 0000000000000000000000000000000000000000..c2428ed2dca710adb49a365d8e7b9fa8d6c81913 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/retriever_service/pagers.py @@ -0,0 +1,509 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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. +# +from typing import ( + Any, + AsyncIterator, + Awaitable, + Callable, + Iterator, + Optional, + Sequence, + Tuple, + Union, +) + +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import retry_async as retries_async + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] + OptionalAsyncRetry = Union[ + retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None + ] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore + +from google.ai.generativelanguage_v1alpha.types import retriever, retriever_service + + +class ListCorporaPager: + """A pager for iterating through ``list_corpora`` requests. + + This class thinly wraps an initial + :class:`google.ai.generativelanguage_v1alpha.types.ListCorporaResponse` object, and + provides an ``__iter__`` method to iterate through its + ``corpora`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListCorpora`` requests and continue to iterate + through the ``corpora`` field on the + corresponding responses. + + All the usual :class:`google.ai.generativelanguage_v1alpha.types.ListCorporaResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., retriever_service.ListCorporaResponse], + request: retriever_service.ListCorporaRequest, + response: retriever_service.ListCorporaResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.ai.generativelanguage_v1alpha.types.ListCorporaRequest): + The initial request object. + response (google.ai.generativelanguage_v1alpha.types.ListCorporaResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = retriever_service.ListCorporaRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[retriever_service.ListCorporaResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[retriever.Corpus]: + for page in self.pages: + yield from page.corpora + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListCorporaAsyncPager: + """A pager for iterating through ``list_corpora`` requests. + + This class thinly wraps an initial + :class:`google.ai.generativelanguage_v1alpha.types.ListCorporaResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``corpora`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListCorpora`` requests and continue to iterate + through the ``corpora`` field on the + corresponding responses. + + All the usual :class:`google.ai.generativelanguage_v1alpha.types.ListCorporaResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[retriever_service.ListCorporaResponse]], + request: retriever_service.ListCorporaRequest, + response: retriever_service.ListCorporaResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.ai.generativelanguage_v1alpha.types.ListCorporaRequest): + The initial request object. + response (google.ai.generativelanguage_v1alpha.types.ListCorporaResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = retriever_service.ListCorporaRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[retriever_service.ListCorporaResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[retriever.Corpus]: + async def async_generator(): + async for page in self.pages: + for response in page.corpora: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListDocumentsPager: + """A pager for iterating through ``list_documents`` requests. + + This class thinly wraps an initial + :class:`google.ai.generativelanguage_v1alpha.types.ListDocumentsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``documents`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListDocuments`` requests and continue to iterate + through the ``documents`` field on the + corresponding responses. + + All the usual :class:`google.ai.generativelanguage_v1alpha.types.ListDocumentsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., retriever_service.ListDocumentsResponse], + request: retriever_service.ListDocumentsRequest, + response: retriever_service.ListDocumentsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.ai.generativelanguage_v1alpha.types.ListDocumentsRequest): + The initial request object. + response (google.ai.generativelanguage_v1alpha.types.ListDocumentsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = retriever_service.ListDocumentsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[retriever_service.ListDocumentsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[retriever.Document]: + for page in self.pages: + yield from page.documents + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListDocumentsAsyncPager: + """A pager for iterating through ``list_documents`` requests. + + This class thinly wraps an initial + :class:`google.ai.generativelanguage_v1alpha.types.ListDocumentsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``documents`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListDocuments`` requests and continue to iterate + through the ``documents`` field on the + corresponding responses. + + All the usual :class:`google.ai.generativelanguage_v1alpha.types.ListDocumentsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[retriever_service.ListDocumentsResponse]], + request: retriever_service.ListDocumentsRequest, + response: retriever_service.ListDocumentsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.ai.generativelanguage_v1alpha.types.ListDocumentsRequest): + The initial request object. + response (google.ai.generativelanguage_v1alpha.types.ListDocumentsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = retriever_service.ListDocumentsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[retriever_service.ListDocumentsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[retriever.Document]: + async def async_generator(): + async for page in self.pages: + for response in page.documents: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListChunksPager: + """A pager for iterating through ``list_chunks`` requests. + + This class thinly wraps an initial + :class:`google.ai.generativelanguage_v1alpha.types.ListChunksResponse` object, and + provides an ``__iter__`` method to iterate through its + ``chunks`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListChunks`` requests and continue to iterate + through the ``chunks`` field on the + corresponding responses. + + All the usual :class:`google.ai.generativelanguage_v1alpha.types.ListChunksResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., retriever_service.ListChunksResponse], + request: retriever_service.ListChunksRequest, + response: retriever_service.ListChunksResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.ai.generativelanguage_v1alpha.types.ListChunksRequest): + The initial request object. + response (google.ai.generativelanguage_v1alpha.types.ListChunksResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = retriever_service.ListChunksRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[retriever_service.ListChunksResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[retriever.Chunk]: + for page in self.pages: + yield from page.chunks + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListChunksAsyncPager: + """A pager for iterating through ``list_chunks`` requests. + + This class thinly wraps an initial + :class:`google.ai.generativelanguage_v1alpha.types.ListChunksResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``chunks`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListChunks`` requests and continue to iterate + through the ``chunks`` field on the + corresponding responses. + + All the usual :class:`google.ai.generativelanguage_v1alpha.types.ListChunksResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[retriever_service.ListChunksResponse]], + request: retriever_service.ListChunksRequest, + response: retriever_service.ListChunksResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.ai.generativelanguage_v1alpha.types.ListChunksRequest): + The initial request object. + response (google.ai.generativelanguage_v1alpha.types.ListChunksResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = retriever_service.ListChunksRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[retriever_service.ListChunksResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[retriever.Chunk]: + async def async_generator(): + async for page in self.pages: + for response in page.chunks: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/retriever_service/transports/__init__.py b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/retriever_service/transports/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..81046f3349050cbd039d4b90747647ba8685711b --- /dev/null +++ b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/retriever_service/transports/__init__.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import RetrieverServiceTransport +from .grpc import RetrieverServiceGrpcTransport +from .grpc_asyncio import RetrieverServiceGrpcAsyncIOTransport +from .rest import RetrieverServiceRestInterceptor, RetrieverServiceRestTransport + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[RetrieverServiceTransport]] +_transport_registry["grpc"] = RetrieverServiceGrpcTransport +_transport_registry["grpc_asyncio"] = RetrieverServiceGrpcAsyncIOTransport +_transport_registry["rest"] = RetrieverServiceRestTransport + +__all__ = ( + "RetrieverServiceTransport", + "RetrieverServiceGrpcTransport", + "RetrieverServiceGrpcAsyncIOTransport", + "RetrieverServiceRestTransport", + "RetrieverServiceRestInterceptor", +) diff --git a/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/retriever_service/transports/__pycache__/__init__.cpython-311.pyc b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/retriever_service/transports/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b22c3903b0c737cce238a87e1d33c738053ca9bc Binary files /dev/null and b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/retriever_service/transports/__pycache__/__init__.cpython-311.pyc differ diff --git a/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/retriever_service/transports/__pycache__/base.cpython-311.pyc b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/retriever_service/transports/__pycache__/base.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0a113321259b6c7adeafc1b230103f698add8990 Binary files /dev/null and b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/retriever_service/transports/__pycache__/base.cpython-311.pyc differ diff --git a/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/retriever_service/transports/__pycache__/grpc.cpython-311.pyc b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/retriever_service/transports/__pycache__/grpc.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0d872e7f6264967c883563b215ebb70fc92695e6 Binary files /dev/null and b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/retriever_service/transports/__pycache__/grpc.cpython-311.pyc differ diff --git a/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/retriever_service/transports/__pycache__/grpc_asyncio.cpython-311.pyc b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/retriever_service/transports/__pycache__/grpc_asyncio.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9b47c2dd7652c5a921cfc40170a2f66661371bef Binary files /dev/null and b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/retriever_service/transports/__pycache__/grpc_asyncio.cpython-311.pyc differ diff --git a/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/retriever_service/transports/__pycache__/rest_base.cpython-311.pyc b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/retriever_service/transports/__pycache__/rest_base.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..55702ccdee085d00ee5ef22504eeed4a171e70c9 Binary files /dev/null and b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/retriever_service/transports/__pycache__/rest_base.cpython-311.pyc differ diff --git a/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/retriever_service/transports/base.py b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/retriever_service/transports/base.py new file mode 100644 index 0000000000000000000000000000000000000000..92bec79278429583f1238d777c8c7133f6d69222 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/retriever_service/transports/base.py @@ -0,0 +1,481 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account # type: ignore +from google.protobuf import empty_pb2 # type: ignore + +from google.ai.generativelanguage_v1alpha import gapic_version as package_version +from google.ai.generativelanguage_v1alpha.types import retriever, retriever_service + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + + +class RetrieverServiceTransport(abc.ABC): + """Abstract transport class for RetrieverService.""" + + AUTH_SCOPES = () + + DEFAULT_HOST: str = "generativelanguage.googleapis.com" + + def __init__( + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'generativelanguage.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + if not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id + ) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_corpus: gapic_v1.method.wrap_method( + self.create_corpus, + default_timeout=None, + client_info=client_info, + ), + self.get_corpus: gapic_v1.method.wrap_method( + self.get_corpus, + default_timeout=None, + client_info=client_info, + ), + self.update_corpus: gapic_v1.method.wrap_method( + self.update_corpus, + default_timeout=None, + client_info=client_info, + ), + self.delete_corpus: gapic_v1.method.wrap_method( + self.delete_corpus, + default_timeout=None, + client_info=client_info, + ), + self.list_corpora: gapic_v1.method.wrap_method( + self.list_corpora, + default_timeout=None, + client_info=client_info, + ), + self.query_corpus: gapic_v1.method.wrap_method( + self.query_corpus, + default_timeout=None, + client_info=client_info, + ), + self.create_document: gapic_v1.method.wrap_method( + self.create_document, + default_timeout=None, + client_info=client_info, + ), + self.get_document: gapic_v1.method.wrap_method( + self.get_document, + default_timeout=None, + client_info=client_info, + ), + self.update_document: gapic_v1.method.wrap_method( + self.update_document, + default_timeout=None, + client_info=client_info, + ), + self.delete_document: gapic_v1.method.wrap_method( + self.delete_document, + default_timeout=None, + client_info=client_info, + ), + self.list_documents: gapic_v1.method.wrap_method( + self.list_documents, + default_timeout=None, + client_info=client_info, + ), + self.query_document: gapic_v1.method.wrap_method( + self.query_document, + default_timeout=None, + client_info=client_info, + ), + self.create_chunk: gapic_v1.method.wrap_method( + self.create_chunk, + default_timeout=None, + client_info=client_info, + ), + self.batch_create_chunks: gapic_v1.method.wrap_method( + self.batch_create_chunks, + default_timeout=None, + client_info=client_info, + ), + self.get_chunk: gapic_v1.method.wrap_method( + self.get_chunk, + default_timeout=None, + client_info=client_info, + ), + self.update_chunk: gapic_v1.method.wrap_method( + self.update_chunk, + default_timeout=None, + client_info=client_info, + ), + self.batch_update_chunks: gapic_v1.method.wrap_method( + self.batch_update_chunks, + default_timeout=None, + client_info=client_info, + ), + self.delete_chunk: gapic_v1.method.wrap_method( + self.delete_chunk, + default_timeout=None, + client_info=client_info, + ), + self.batch_delete_chunks: gapic_v1.method.wrap_method( + self.batch_delete_chunks, + default_timeout=None, + client_info=client_info, + ), + self.list_chunks: gapic_v1.method.wrap_method( + self.list_chunks, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def create_corpus( + self, + ) -> Callable[ + [retriever_service.CreateCorpusRequest], + Union[retriever.Corpus, Awaitable[retriever.Corpus]], + ]: + raise NotImplementedError() + + @property + def get_corpus( + self, + ) -> Callable[ + [retriever_service.GetCorpusRequest], + Union[retriever.Corpus, Awaitable[retriever.Corpus]], + ]: + raise NotImplementedError() + + @property + def update_corpus( + self, + ) -> Callable[ + [retriever_service.UpdateCorpusRequest], + Union[retriever.Corpus, Awaitable[retriever.Corpus]], + ]: + raise NotImplementedError() + + @property + def delete_corpus( + self, + ) -> Callable[ + [retriever_service.DeleteCorpusRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + @property + def list_corpora( + self, + ) -> Callable[ + [retriever_service.ListCorporaRequest], + Union[ + retriever_service.ListCorporaResponse, + Awaitable[retriever_service.ListCorporaResponse], + ], + ]: + raise NotImplementedError() + + @property + def query_corpus( + self, + ) -> Callable[ + [retriever_service.QueryCorpusRequest], + Union[ + retriever_service.QueryCorpusResponse, + Awaitable[retriever_service.QueryCorpusResponse], + ], + ]: + raise NotImplementedError() + + @property + def create_document( + self, + ) -> Callable[ + [retriever_service.CreateDocumentRequest], + Union[retriever.Document, Awaitable[retriever.Document]], + ]: + raise NotImplementedError() + + @property + def get_document( + self, + ) -> Callable[ + [retriever_service.GetDocumentRequest], + Union[retriever.Document, Awaitable[retriever.Document]], + ]: + raise NotImplementedError() + + @property + def update_document( + self, + ) -> Callable[ + [retriever_service.UpdateDocumentRequest], + Union[retriever.Document, Awaitable[retriever.Document]], + ]: + raise NotImplementedError() + + @property + def delete_document( + self, + ) -> Callable[ + [retriever_service.DeleteDocumentRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + @property + def list_documents( + self, + ) -> Callable[ + [retriever_service.ListDocumentsRequest], + Union[ + retriever_service.ListDocumentsResponse, + Awaitable[retriever_service.ListDocumentsResponse], + ], + ]: + raise NotImplementedError() + + @property + def query_document( + self, + ) -> Callable[ + [retriever_service.QueryDocumentRequest], + Union[ + retriever_service.QueryDocumentResponse, + Awaitable[retriever_service.QueryDocumentResponse], + ], + ]: + raise NotImplementedError() + + @property + def create_chunk( + self, + ) -> Callable[ + [retriever_service.CreateChunkRequest], + Union[retriever.Chunk, Awaitable[retriever.Chunk]], + ]: + raise NotImplementedError() + + @property + def batch_create_chunks( + self, + ) -> Callable[ + [retriever_service.BatchCreateChunksRequest], + Union[ + retriever_service.BatchCreateChunksResponse, + Awaitable[retriever_service.BatchCreateChunksResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_chunk( + self, + ) -> Callable[ + [retriever_service.GetChunkRequest], + Union[retriever.Chunk, Awaitable[retriever.Chunk]], + ]: + raise NotImplementedError() + + @property + def update_chunk( + self, + ) -> Callable[ + [retriever_service.UpdateChunkRequest], + Union[retriever.Chunk, Awaitable[retriever.Chunk]], + ]: + raise NotImplementedError() + + @property + def batch_update_chunks( + self, + ) -> Callable[ + [retriever_service.BatchUpdateChunksRequest], + Union[ + retriever_service.BatchUpdateChunksResponse, + Awaitable[retriever_service.BatchUpdateChunksResponse], + ], + ]: + raise NotImplementedError() + + @property + def delete_chunk( + self, + ) -> Callable[ + [retriever_service.DeleteChunkRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + @property + def batch_delete_chunks( + self, + ) -> Callable[ + [retriever_service.BatchDeleteChunksRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + @property + def list_chunks( + self, + ) -> Callable[ + [retriever_service.ListChunksRequest], + Union[ + retriever_service.ListChunksResponse, + Awaitable[retriever_service.ListChunksResponse], + ], + ]: + raise NotImplementedError() + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], + Union[ + operations_pb2.ListOperationsResponse, + Awaitable[operations_pb2.ListOperationsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("RetrieverServiceTransport",) diff --git a/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/retriever_service/transports/grpc.py b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/retriever_service/transports/grpc.py new file mode 100644 index 0000000000000000000000000000000000000000..5467ec9eb43961ba961fe94c90c716a22a2da922 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/retriever_service/transports/grpc.py @@ -0,0 +1,908 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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. +# +import json +import logging as std_logging +import pickle +from typing import Callable, Dict, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import gapic_v1, grpc_helpers +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore + +from google.ai.generativelanguage_v1alpha.types import retriever, retriever_service + +from .base import DEFAULT_CLIENT_INFO, RetrieverServiceTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER + def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.RetrieverService", + "rpcName": client_call_details.method, + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + + response = continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = response.result() + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response for {client_call_details.method}.", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.RetrieverService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class RetrieverServiceGrpcTransport(RetrieverServiceTransport): + """gRPC backend transport for RetrieverService. + + An API for semantic search over a corpus of user uploaded + content. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _stubs: Dict[str, Callable] + + def __init__( + self, + *, + host: str = "generativelanguage.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'generativelanguage.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientInterceptor() + self._logged_channel = grpc.intercept_channel( + self._grpc_channel, self._interceptor + ) + + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel( + cls, + host: str = "generativelanguage.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service.""" + return self._grpc_channel + + @property + def create_corpus( + self, + ) -> Callable[[retriever_service.CreateCorpusRequest], retriever.Corpus]: + r"""Return a callable for the create corpus method over gRPC. + + Creates an empty ``Corpus``. + + Returns: + Callable[[~.CreateCorpusRequest], + ~.Corpus]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_corpus" not in self._stubs: + self._stubs["create_corpus"] = self._logged_channel.unary_unary( + "/google.ai.generativelanguage.v1alpha.RetrieverService/CreateCorpus", + request_serializer=retriever_service.CreateCorpusRequest.serialize, + response_deserializer=retriever.Corpus.deserialize, + ) + return self._stubs["create_corpus"] + + @property + def get_corpus( + self, + ) -> Callable[[retriever_service.GetCorpusRequest], retriever.Corpus]: + r"""Return a callable for the get corpus method over gRPC. + + Gets information about a specific ``Corpus``. + + Returns: + Callable[[~.GetCorpusRequest], + ~.Corpus]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_corpus" not in self._stubs: + self._stubs["get_corpus"] = self._logged_channel.unary_unary( + "/google.ai.generativelanguage.v1alpha.RetrieverService/GetCorpus", + request_serializer=retriever_service.GetCorpusRequest.serialize, + response_deserializer=retriever.Corpus.deserialize, + ) + return self._stubs["get_corpus"] + + @property + def update_corpus( + self, + ) -> Callable[[retriever_service.UpdateCorpusRequest], retriever.Corpus]: + r"""Return a callable for the update corpus method over gRPC. + + Updates a ``Corpus``. + + Returns: + Callable[[~.UpdateCorpusRequest], + ~.Corpus]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_corpus" not in self._stubs: + self._stubs["update_corpus"] = self._logged_channel.unary_unary( + "/google.ai.generativelanguage.v1alpha.RetrieverService/UpdateCorpus", + request_serializer=retriever_service.UpdateCorpusRequest.serialize, + response_deserializer=retriever.Corpus.deserialize, + ) + return self._stubs["update_corpus"] + + @property + def delete_corpus( + self, + ) -> Callable[[retriever_service.DeleteCorpusRequest], empty_pb2.Empty]: + r"""Return a callable for the delete corpus method over gRPC. + + Deletes a ``Corpus``. + + Returns: + Callable[[~.DeleteCorpusRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_corpus" not in self._stubs: + self._stubs["delete_corpus"] = self._logged_channel.unary_unary( + "/google.ai.generativelanguage.v1alpha.RetrieverService/DeleteCorpus", + request_serializer=retriever_service.DeleteCorpusRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_corpus"] + + @property + def list_corpora( + self, + ) -> Callable[ + [retriever_service.ListCorporaRequest], retriever_service.ListCorporaResponse + ]: + r"""Return a callable for the list corpora method over gRPC. + + Lists all ``Corpora`` owned by the user. + + Returns: + Callable[[~.ListCorporaRequest], + ~.ListCorporaResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_corpora" not in self._stubs: + self._stubs["list_corpora"] = self._logged_channel.unary_unary( + "/google.ai.generativelanguage.v1alpha.RetrieverService/ListCorpora", + request_serializer=retriever_service.ListCorporaRequest.serialize, + response_deserializer=retriever_service.ListCorporaResponse.deserialize, + ) + return self._stubs["list_corpora"] + + @property + def query_corpus( + self, + ) -> Callable[ + [retriever_service.QueryCorpusRequest], retriever_service.QueryCorpusResponse + ]: + r"""Return a callable for the query corpus method over gRPC. + + Performs semantic search over a ``Corpus``. + + Returns: + Callable[[~.QueryCorpusRequest], + ~.QueryCorpusResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "query_corpus" not in self._stubs: + self._stubs["query_corpus"] = self._logged_channel.unary_unary( + "/google.ai.generativelanguage.v1alpha.RetrieverService/QueryCorpus", + request_serializer=retriever_service.QueryCorpusRequest.serialize, + response_deserializer=retriever_service.QueryCorpusResponse.deserialize, + ) + return self._stubs["query_corpus"] + + @property + def create_document( + self, + ) -> Callable[[retriever_service.CreateDocumentRequest], retriever.Document]: + r"""Return a callable for the create document method over gRPC. + + Creates an empty ``Document``. + + Returns: + Callable[[~.CreateDocumentRequest], + ~.Document]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_document" not in self._stubs: + self._stubs["create_document"] = self._logged_channel.unary_unary( + "/google.ai.generativelanguage.v1alpha.RetrieverService/CreateDocument", + request_serializer=retriever_service.CreateDocumentRequest.serialize, + response_deserializer=retriever.Document.deserialize, + ) + return self._stubs["create_document"] + + @property + def get_document( + self, + ) -> Callable[[retriever_service.GetDocumentRequest], retriever.Document]: + r"""Return a callable for the get document method over gRPC. + + Gets information about a specific ``Document``. + + Returns: + Callable[[~.GetDocumentRequest], + ~.Document]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_document" not in self._stubs: + self._stubs["get_document"] = self._logged_channel.unary_unary( + "/google.ai.generativelanguage.v1alpha.RetrieverService/GetDocument", + request_serializer=retriever_service.GetDocumentRequest.serialize, + response_deserializer=retriever.Document.deserialize, + ) + return self._stubs["get_document"] + + @property + def update_document( + self, + ) -> Callable[[retriever_service.UpdateDocumentRequest], retriever.Document]: + r"""Return a callable for the update document method over gRPC. + + Updates a ``Document``. + + Returns: + Callable[[~.UpdateDocumentRequest], + ~.Document]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_document" not in self._stubs: + self._stubs["update_document"] = self._logged_channel.unary_unary( + "/google.ai.generativelanguage.v1alpha.RetrieverService/UpdateDocument", + request_serializer=retriever_service.UpdateDocumentRequest.serialize, + response_deserializer=retriever.Document.deserialize, + ) + return self._stubs["update_document"] + + @property + def delete_document( + self, + ) -> Callable[[retriever_service.DeleteDocumentRequest], empty_pb2.Empty]: + r"""Return a callable for the delete document method over gRPC. + + Deletes a ``Document``. + + Returns: + Callable[[~.DeleteDocumentRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_document" not in self._stubs: + self._stubs["delete_document"] = self._logged_channel.unary_unary( + "/google.ai.generativelanguage.v1alpha.RetrieverService/DeleteDocument", + request_serializer=retriever_service.DeleteDocumentRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_document"] + + @property + def list_documents( + self, + ) -> Callable[ + [retriever_service.ListDocumentsRequest], + retriever_service.ListDocumentsResponse, + ]: + r"""Return a callable for the list documents method over gRPC. + + Lists all ``Document``\ s in a ``Corpus``. + + Returns: + Callable[[~.ListDocumentsRequest], + ~.ListDocumentsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_documents" not in self._stubs: + self._stubs["list_documents"] = self._logged_channel.unary_unary( + "/google.ai.generativelanguage.v1alpha.RetrieverService/ListDocuments", + request_serializer=retriever_service.ListDocumentsRequest.serialize, + response_deserializer=retriever_service.ListDocumentsResponse.deserialize, + ) + return self._stubs["list_documents"] + + @property + def query_document( + self, + ) -> Callable[ + [retriever_service.QueryDocumentRequest], + retriever_service.QueryDocumentResponse, + ]: + r"""Return a callable for the query document method over gRPC. + + Performs semantic search over a ``Document``. + + Returns: + Callable[[~.QueryDocumentRequest], + ~.QueryDocumentResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "query_document" not in self._stubs: + self._stubs["query_document"] = self._logged_channel.unary_unary( + "/google.ai.generativelanguage.v1alpha.RetrieverService/QueryDocument", + request_serializer=retriever_service.QueryDocumentRequest.serialize, + response_deserializer=retriever_service.QueryDocumentResponse.deserialize, + ) + return self._stubs["query_document"] + + @property + def create_chunk( + self, + ) -> Callable[[retriever_service.CreateChunkRequest], retriever.Chunk]: + r"""Return a callable for the create chunk method over gRPC. + + Creates a ``Chunk``. + + Returns: + Callable[[~.CreateChunkRequest], + ~.Chunk]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_chunk" not in self._stubs: + self._stubs["create_chunk"] = self._logged_channel.unary_unary( + "/google.ai.generativelanguage.v1alpha.RetrieverService/CreateChunk", + request_serializer=retriever_service.CreateChunkRequest.serialize, + response_deserializer=retriever.Chunk.deserialize, + ) + return self._stubs["create_chunk"] + + @property + def batch_create_chunks( + self, + ) -> Callable[ + [retriever_service.BatchCreateChunksRequest], + retriever_service.BatchCreateChunksResponse, + ]: + r"""Return a callable for the batch create chunks method over gRPC. + + Batch create ``Chunk``\ s. + + Returns: + Callable[[~.BatchCreateChunksRequest], + ~.BatchCreateChunksResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "batch_create_chunks" not in self._stubs: + self._stubs["batch_create_chunks"] = self._logged_channel.unary_unary( + "/google.ai.generativelanguage.v1alpha.RetrieverService/BatchCreateChunks", + request_serializer=retriever_service.BatchCreateChunksRequest.serialize, + response_deserializer=retriever_service.BatchCreateChunksResponse.deserialize, + ) + return self._stubs["batch_create_chunks"] + + @property + def get_chunk( + self, + ) -> Callable[[retriever_service.GetChunkRequest], retriever.Chunk]: + r"""Return a callable for the get chunk method over gRPC. + + Gets information about a specific ``Chunk``. + + Returns: + Callable[[~.GetChunkRequest], + ~.Chunk]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_chunk" not in self._stubs: + self._stubs["get_chunk"] = self._logged_channel.unary_unary( + "/google.ai.generativelanguage.v1alpha.RetrieverService/GetChunk", + request_serializer=retriever_service.GetChunkRequest.serialize, + response_deserializer=retriever.Chunk.deserialize, + ) + return self._stubs["get_chunk"] + + @property + def update_chunk( + self, + ) -> Callable[[retriever_service.UpdateChunkRequest], retriever.Chunk]: + r"""Return a callable for the update chunk method over gRPC. + + Updates a ``Chunk``. + + Returns: + Callable[[~.UpdateChunkRequest], + ~.Chunk]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_chunk" not in self._stubs: + self._stubs["update_chunk"] = self._logged_channel.unary_unary( + "/google.ai.generativelanguage.v1alpha.RetrieverService/UpdateChunk", + request_serializer=retriever_service.UpdateChunkRequest.serialize, + response_deserializer=retriever.Chunk.deserialize, + ) + return self._stubs["update_chunk"] + + @property + def batch_update_chunks( + self, + ) -> Callable[ + [retriever_service.BatchUpdateChunksRequest], + retriever_service.BatchUpdateChunksResponse, + ]: + r"""Return a callable for the batch update chunks method over gRPC. + + Batch update ``Chunk``\ s. + + Returns: + Callable[[~.BatchUpdateChunksRequest], + ~.BatchUpdateChunksResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "batch_update_chunks" not in self._stubs: + self._stubs["batch_update_chunks"] = self._logged_channel.unary_unary( + "/google.ai.generativelanguage.v1alpha.RetrieverService/BatchUpdateChunks", + request_serializer=retriever_service.BatchUpdateChunksRequest.serialize, + response_deserializer=retriever_service.BatchUpdateChunksResponse.deserialize, + ) + return self._stubs["batch_update_chunks"] + + @property + def delete_chunk( + self, + ) -> Callable[[retriever_service.DeleteChunkRequest], empty_pb2.Empty]: + r"""Return a callable for the delete chunk method over gRPC. + + Deletes a ``Chunk``. + + Returns: + Callable[[~.DeleteChunkRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_chunk" not in self._stubs: + self._stubs["delete_chunk"] = self._logged_channel.unary_unary( + "/google.ai.generativelanguage.v1alpha.RetrieverService/DeleteChunk", + request_serializer=retriever_service.DeleteChunkRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_chunk"] + + @property + def batch_delete_chunks( + self, + ) -> Callable[[retriever_service.BatchDeleteChunksRequest], empty_pb2.Empty]: + r"""Return a callable for the batch delete chunks method over gRPC. + + Batch delete ``Chunk``\ s. + + Returns: + Callable[[~.BatchDeleteChunksRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "batch_delete_chunks" not in self._stubs: + self._stubs["batch_delete_chunks"] = self._logged_channel.unary_unary( + "/google.ai.generativelanguage.v1alpha.RetrieverService/BatchDeleteChunks", + request_serializer=retriever_service.BatchDeleteChunksRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["batch_delete_chunks"] + + @property + def list_chunks( + self, + ) -> Callable[ + [retriever_service.ListChunksRequest], retriever_service.ListChunksResponse + ]: + r"""Return a callable for the list chunks method over gRPC. + + Lists all ``Chunk``\ s in a ``Document``. + + Returns: + Callable[[~.ListChunksRequest], + ~.ListChunksResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_chunks" not in self._stubs: + self._stubs["list_chunks"] = self._logged_channel.unary_unary( + "/google.ai.generativelanguage.v1alpha.RetrieverService/ListChunks", + request_serializer=retriever_service.ListChunksRequest.serialize, + response_deserializer=retriever_service.ListChunksResponse.deserialize, + ) + return self._stubs["list_chunks"] + + def close(self): + self._logged_channel.close() + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ("RetrieverServiceGrpcTransport",) diff --git a/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/retriever_service/transports/grpc_asyncio.py b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/retriever_service/transports/grpc_asyncio.py new file mode 100644 index 0000000000000000000000000000000000000000..19135680af8d4a651a938f88c9e5193c7242f8c4 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/retriever_service/transports/grpc_asyncio.py @@ -0,0 +1,1048 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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. +# +import inspect +import json +import logging as std_logging +import pickle +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, grpc_helpers_async +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson +import google.protobuf.message +import grpc # type: ignore +from grpc.experimental import aio # type: ignore +import proto # type: ignore + +from google.ai.generativelanguage_v1alpha.types import retriever, retriever_service + +from .base import DEFAULT_CLIENT_INFO, RetrieverServiceTransport +from .grpc import RetrieverServiceGrpcTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientAIOInterceptor( + grpc.aio.UnaryUnaryClientInterceptor +): # pragma: NO COVER + async def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.RetrieverService", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = await continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = await response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = await response + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response to rpc {client_call_details.method}.", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.RetrieverService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class RetrieverServiceGrpcAsyncIOTransport(RetrieverServiceTransport): + """gRPC AsyncIO backend transport for RetrieverService. + + An API for semantic search over a corpus of user uploaded + content. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel( + cls, + host: str = "generativelanguage.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "generativelanguage.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'generativelanguage.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientAIOInterceptor() + self._grpc_channel._unary_unary_interceptors.append(self._interceptor) + self._logged_channel = self._grpc_channel + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def create_corpus( + self, + ) -> Callable[[retriever_service.CreateCorpusRequest], Awaitable[retriever.Corpus]]: + r"""Return a callable for the create corpus method over gRPC. + + Creates an empty ``Corpus``. + + Returns: + Callable[[~.CreateCorpusRequest], + Awaitable[~.Corpus]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_corpus" not in self._stubs: + self._stubs["create_corpus"] = self._logged_channel.unary_unary( + "/google.ai.generativelanguage.v1alpha.RetrieverService/CreateCorpus", + request_serializer=retriever_service.CreateCorpusRequest.serialize, + response_deserializer=retriever.Corpus.deserialize, + ) + return self._stubs["create_corpus"] + + @property + def get_corpus( + self, + ) -> Callable[[retriever_service.GetCorpusRequest], Awaitable[retriever.Corpus]]: + r"""Return a callable for the get corpus method over gRPC. + + Gets information about a specific ``Corpus``. + + Returns: + Callable[[~.GetCorpusRequest], + Awaitable[~.Corpus]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_corpus" not in self._stubs: + self._stubs["get_corpus"] = self._logged_channel.unary_unary( + "/google.ai.generativelanguage.v1alpha.RetrieverService/GetCorpus", + request_serializer=retriever_service.GetCorpusRequest.serialize, + response_deserializer=retriever.Corpus.deserialize, + ) + return self._stubs["get_corpus"] + + @property + def update_corpus( + self, + ) -> Callable[[retriever_service.UpdateCorpusRequest], Awaitable[retriever.Corpus]]: + r"""Return a callable for the update corpus method over gRPC. + + Updates a ``Corpus``. + + Returns: + Callable[[~.UpdateCorpusRequest], + Awaitable[~.Corpus]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_corpus" not in self._stubs: + self._stubs["update_corpus"] = self._logged_channel.unary_unary( + "/google.ai.generativelanguage.v1alpha.RetrieverService/UpdateCorpus", + request_serializer=retriever_service.UpdateCorpusRequest.serialize, + response_deserializer=retriever.Corpus.deserialize, + ) + return self._stubs["update_corpus"] + + @property + def delete_corpus( + self, + ) -> Callable[[retriever_service.DeleteCorpusRequest], Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete corpus method over gRPC. + + Deletes a ``Corpus``. + + Returns: + Callable[[~.DeleteCorpusRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_corpus" not in self._stubs: + self._stubs["delete_corpus"] = self._logged_channel.unary_unary( + "/google.ai.generativelanguage.v1alpha.RetrieverService/DeleteCorpus", + request_serializer=retriever_service.DeleteCorpusRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_corpus"] + + @property + def list_corpora( + self, + ) -> Callable[ + [retriever_service.ListCorporaRequest], + Awaitable[retriever_service.ListCorporaResponse], + ]: + r"""Return a callable for the list corpora method over gRPC. + + Lists all ``Corpora`` owned by the user. + + Returns: + Callable[[~.ListCorporaRequest], + Awaitable[~.ListCorporaResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_corpora" not in self._stubs: + self._stubs["list_corpora"] = self._logged_channel.unary_unary( + "/google.ai.generativelanguage.v1alpha.RetrieverService/ListCorpora", + request_serializer=retriever_service.ListCorporaRequest.serialize, + response_deserializer=retriever_service.ListCorporaResponse.deserialize, + ) + return self._stubs["list_corpora"] + + @property + def query_corpus( + self, + ) -> Callable[ + [retriever_service.QueryCorpusRequest], + Awaitable[retriever_service.QueryCorpusResponse], + ]: + r"""Return a callable for the query corpus method over gRPC. + + Performs semantic search over a ``Corpus``. + + Returns: + Callable[[~.QueryCorpusRequest], + Awaitable[~.QueryCorpusResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "query_corpus" not in self._stubs: + self._stubs["query_corpus"] = self._logged_channel.unary_unary( + "/google.ai.generativelanguage.v1alpha.RetrieverService/QueryCorpus", + request_serializer=retriever_service.QueryCorpusRequest.serialize, + response_deserializer=retriever_service.QueryCorpusResponse.deserialize, + ) + return self._stubs["query_corpus"] + + @property + def create_document( + self, + ) -> Callable[ + [retriever_service.CreateDocumentRequest], Awaitable[retriever.Document] + ]: + r"""Return a callable for the create document method over gRPC. + + Creates an empty ``Document``. + + Returns: + Callable[[~.CreateDocumentRequest], + Awaitable[~.Document]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_document" not in self._stubs: + self._stubs["create_document"] = self._logged_channel.unary_unary( + "/google.ai.generativelanguage.v1alpha.RetrieverService/CreateDocument", + request_serializer=retriever_service.CreateDocumentRequest.serialize, + response_deserializer=retriever.Document.deserialize, + ) + return self._stubs["create_document"] + + @property + def get_document( + self, + ) -> Callable[ + [retriever_service.GetDocumentRequest], Awaitable[retriever.Document] + ]: + r"""Return a callable for the get document method over gRPC. + + Gets information about a specific ``Document``. + + Returns: + Callable[[~.GetDocumentRequest], + Awaitable[~.Document]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_document" not in self._stubs: + self._stubs["get_document"] = self._logged_channel.unary_unary( + "/google.ai.generativelanguage.v1alpha.RetrieverService/GetDocument", + request_serializer=retriever_service.GetDocumentRequest.serialize, + response_deserializer=retriever.Document.deserialize, + ) + return self._stubs["get_document"] + + @property + def update_document( + self, + ) -> Callable[ + [retriever_service.UpdateDocumentRequest], Awaitable[retriever.Document] + ]: + r"""Return a callable for the update document method over gRPC. + + Updates a ``Document``. + + Returns: + Callable[[~.UpdateDocumentRequest], + Awaitable[~.Document]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_document" not in self._stubs: + self._stubs["update_document"] = self._logged_channel.unary_unary( + "/google.ai.generativelanguage.v1alpha.RetrieverService/UpdateDocument", + request_serializer=retriever_service.UpdateDocumentRequest.serialize, + response_deserializer=retriever.Document.deserialize, + ) + return self._stubs["update_document"] + + @property + def delete_document( + self, + ) -> Callable[ + [retriever_service.DeleteDocumentRequest], Awaitable[empty_pb2.Empty] + ]: + r"""Return a callable for the delete document method over gRPC. + + Deletes a ``Document``. + + Returns: + Callable[[~.DeleteDocumentRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_document" not in self._stubs: + self._stubs["delete_document"] = self._logged_channel.unary_unary( + "/google.ai.generativelanguage.v1alpha.RetrieverService/DeleteDocument", + request_serializer=retriever_service.DeleteDocumentRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_document"] + + @property + def list_documents( + self, + ) -> Callable[ + [retriever_service.ListDocumentsRequest], + Awaitable[retriever_service.ListDocumentsResponse], + ]: + r"""Return a callable for the list documents method over gRPC. + + Lists all ``Document``\ s in a ``Corpus``. + + Returns: + Callable[[~.ListDocumentsRequest], + Awaitable[~.ListDocumentsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_documents" not in self._stubs: + self._stubs["list_documents"] = self._logged_channel.unary_unary( + "/google.ai.generativelanguage.v1alpha.RetrieverService/ListDocuments", + request_serializer=retriever_service.ListDocumentsRequest.serialize, + response_deserializer=retriever_service.ListDocumentsResponse.deserialize, + ) + return self._stubs["list_documents"] + + @property + def query_document( + self, + ) -> Callable[ + [retriever_service.QueryDocumentRequest], + Awaitable[retriever_service.QueryDocumentResponse], + ]: + r"""Return a callable for the query document method over gRPC. + + Performs semantic search over a ``Document``. + + Returns: + Callable[[~.QueryDocumentRequest], + Awaitable[~.QueryDocumentResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "query_document" not in self._stubs: + self._stubs["query_document"] = self._logged_channel.unary_unary( + "/google.ai.generativelanguage.v1alpha.RetrieverService/QueryDocument", + request_serializer=retriever_service.QueryDocumentRequest.serialize, + response_deserializer=retriever_service.QueryDocumentResponse.deserialize, + ) + return self._stubs["query_document"] + + @property + def create_chunk( + self, + ) -> Callable[[retriever_service.CreateChunkRequest], Awaitable[retriever.Chunk]]: + r"""Return a callable for the create chunk method over gRPC. + + Creates a ``Chunk``. + + Returns: + Callable[[~.CreateChunkRequest], + Awaitable[~.Chunk]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_chunk" not in self._stubs: + self._stubs["create_chunk"] = self._logged_channel.unary_unary( + "/google.ai.generativelanguage.v1alpha.RetrieverService/CreateChunk", + request_serializer=retriever_service.CreateChunkRequest.serialize, + response_deserializer=retriever.Chunk.deserialize, + ) + return self._stubs["create_chunk"] + + @property + def batch_create_chunks( + self, + ) -> Callable[ + [retriever_service.BatchCreateChunksRequest], + Awaitable[retriever_service.BatchCreateChunksResponse], + ]: + r"""Return a callable for the batch create chunks method over gRPC. + + Batch create ``Chunk``\ s. + + Returns: + Callable[[~.BatchCreateChunksRequest], + Awaitable[~.BatchCreateChunksResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "batch_create_chunks" not in self._stubs: + self._stubs["batch_create_chunks"] = self._logged_channel.unary_unary( + "/google.ai.generativelanguage.v1alpha.RetrieverService/BatchCreateChunks", + request_serializer=retriever_service.BatchCreateChunksRequest.serialize, + response_deserializer=retriever_service.BatchCreateChunksResponse.deserialize, + ) + return self._stubs["batch_create_chunks"] + + @property + def get_chunk( + self, + ) -> Callable[[retriever_service.GetChunkRequest], Awaitable[retriever.Chunk]]: + r"""Return a callable for the get chunk method over gRPC. + + Gets information about a specific ``Chunk``. + + Returns: + Callable[[~.GetChunkRequest], + Awaitable[~.Chunk]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_chunk" not in self._stubs: + self._stubs["get_chunk"] = self._logged_channel.unary_unary( + "/google.ai.generativelanguage.v1alpha.RetrieverService/GetChunk", + request_serializer=retriever_service.GetChunkRequest.serialize, + response_deserializer=retriever.Chunk.deserialize, + ) + return self._stubs["get_chunk"] + + @property + def update_chunk( + self, + ) -> Callable[[retriever_service.UpdateChunkRequest], Awaitable[retriever.Chunk]]: + r"""Return a callable for the update chunk method over gRPC. + + Updates a ``Chunk``. + + Returns: + Callable[[~.UpdateChunkRequest], + Awaitable[~.Chunk]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_chunk" not in self._stubs: + self._stubs["update_chunk"] = self._logged_channel.unary_unary( + "/google.ai.generativelanguage.v1alpha.RetrieverService/UpdateChunk", + request_serializer=retriever_service.UpdateChunkRequest.serialize, + response_deserializer=retriever.Chunk.deserialize, + ) + return self._stubs["update_chunk"] + + @property + def batch_update_chunks( + self, + ) -> Callable[ + [retriever_service.BatchUpdateChunksRequest], + Awaitable[retriever_service.BatchUpdateChunksResponse], + ]: + r"""Return a callable for the batch update chunks method over gRPC. + + Batch update ``Chunk``\ s. + + Returns: + Callable[[~.BatchUpdateChunksRequest], + Awaitable[~.BatchUpdateChunksResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "batch_update_chunks" not in self._stubs: + self._stubs["batch_update_chunks"] = self._logged_channel.unary_unary( + "/google.ai.generativelanguage.v1alpha.RetrieverService/BatchUpdateChunks", + request_serializer=retriever_service.BatchUpdateChunksRequest.serialize, + response_deserializer=retriever_service.BatchUpdateChunksResponse.deserialize, + ) + return self._stubs["batch_update_chunks"] + + @property + def delete_chunk( + self, + ) -> Callable[[retriever_service.DeleteChunkRequest], Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete chunk method over gRPC. + + Deletes a ``Chunk``. + + Returns: + Callable[[~.DeleteChunkRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_chunk" not in self._stubs: + self._stubs["delete_chunk"] = self._logged_channel.unary_unary( + "/google.ai.generativelanguage.v1alpha.RetrieverService/DeleteChunk", + request_serializer=retriever_service.DeleteChunkRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_chunk"] + + @property + def batch_delete_chunks( + self, + ) -> Callable[ + [retriever_service.BatchDeleteChunksRequest], Awaitable[empty_pb2.Empty] + ]: + r"""Return a callable for the batch delete chunks method over gRPC. + + Batch delete ``Chunk``\ s. + + Returns: + Callable[[~.BatchDeleteChunksRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "batch_delete_chunks" not in self._stubs: + self._stubs["batch_delete_chunks"] = self._logged_channel.unary_unary( + "/google.ai.generativelanguage.v1alpha.RetrieverService/BatchDeleteChunks", + request_serializer=retriever_service.BatchDeleteChunksRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["batch_delete_chunks"] + + @property + def list_chunks( + self, + ) -> Callable[ + [retriever_service.ListChunksRequest], + Awaitable[retriever_service.ListChunksResponse], + ]: + r"""Return a callable for the list chunks method over gRPC. + + Lists all ``Chunk``\ s in a ``Document``. + + Returns: + Callable[[~.ListChunksRequest], + Awaitable[~.ListChunksResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_chunks" not in self._stubs: + self._stubs["list_chunks"] = self._logged_channel.unary_unary( + "/google.ai.generativelanguage.v1alpha.RetrieverService/ListChunks", + request_serializer=retriever_service.ListChunksRequest.serialize, + response_deserializer=retriever_service.ListChunksResponse.deserialize, + ) + return self._stubs["list_chunks"] + + def _prep_wrapped_messages(self, client_info): + """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.create_corpus: self._wrap_method( + self.create_corpus, + default_timeout=None, + client_info=client_info, + ), + self.get_corpus: self._wrap_method( + self.get_corpus, + default_timeout=None, + client_info=client_info, + ), + self.update_corpus: self._wrap_method( + self.update_corpus, + default_timeout=None, + client_info=client_info, + ), + self.delete_corpus: self._wrap_method( + self.delete_corpus, + default_timeout=None, + client_info=client_info, + ), + self.list_corpora: self._wrap_method( + self.list_corpora, + default_timeout=None, + client_info=client_info, + ), + self.query_corpus: self._wrap_method( + self.query_corpus, + default_timeout=None, + client_info=client_info, + ), + self.create_document: self._wrap_method( + self.create_document, + default_timeout=None, + client_info=client_info, + ), + self.get_document: self._wrap_method( + self.get_document, + default_timeout=None, + client_info=client_info, + ), + self.update_document: self._wrap_method( + self.update_document, + default_timeout=None, + client_info=client_info, + ), + self.delete_document: self._wrap_method( + self.delete_document, + default_timeout=None, + client_info=client_info, + ), + self.list_documents: self._wrap_method( + self.list_documents, + default_timeout=None, + client_info=client_info, + ), + self.query_document: self._wrap_method( + self.query_document, + default_timeout=None, + client_info=client_info, + ), + self.create_chunk: self._wrap_method( + self.create_chunk, + default_timeout=None, + client_info=client_info, + ), + self.batch_create_chunks: self._wrap_method( + self.batch_create_chunks, + default_timeout=None, + client_info=client_info, + ), + self.get_chunk: self._wrap_method( + self.get_chunk, + default_timeout=None, + client_info=client_info, + ), + self.update_chunk: self._wrap_method( + self.update_chunk, + default_timeout=None, + client_info=client_info, + ), + self.batch_update_chunks: self._wrap_method( + self.batch_update_chunks, + default_timeout=None, + client_info=client_info, + ), + self.delete_chunk: self._wrap_method( + self.delete_chunk, + default_timeout=None, + client_info=client_info, + ), + self.batch_delete_chunks: self._wrap_method( + self.batch_delete_chunks, + default_timeout=None, + client_info=client_info, + ), + self.list_chunks: self._wrap_method( + self.list_chunks, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + } + + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + + def close(self): + return self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + +__all__ = ("RetrieverServiceGrpcAsyncIOTransport",) diff --git a/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/retriever_service/transports/rest.py b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/retriever_service/transports/rest.py new file mode 100644 index 0000000000000000000000000000000000000000..a53b3ac01460eb312396e64b24e2633e351e7f64 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/retriever_service/transports/rest.py @@ -0,0 +1,4067 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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. +# +import dataclasses +import json # type: ignore +import logging +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, rest_helpers, rest_streaming +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import json_format +from requests import __version__ as requests_version + +from google.ai.generativelanguage_v1alpha.types import retriever, retriever_service + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseRetrieverServiceRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = logging.getLogger(__name__) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=f"requests@{requests_version}", +) + + +class RetrieverServiceRestInterceptor: + """Interceptor for RetrieverService. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the RetrieverServiceRestTransport. + + .. code-block:: python + class MyCustomRetrieverServiceInterceptor(RetrieverServiceRestInterceptor): + def pre_batch_create_chunks(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_batch_create_chunks(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_batch_delete_chunks(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_batch_update_chunks(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_batch_update_chunks(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_chunk(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_chunk(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_corpus(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_corpus(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_document(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_document(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_chunk(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_corpus(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_document(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_get_chunk(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_chunk(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_corpus(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_corpus(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_document(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_document(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_chunks(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_chunks(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_corpora(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_corpora(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_documents(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_documents(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_query_corpus(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_query_corpus(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_query_document(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_query_document(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_chunk(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_chunk(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_corpus(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_corpus(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_document(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_document(self, response): + logging.log(f"Received response: {response}") + return response + + transport = RetrieverServiceRestTransport(interceptor=MyCustomRetrieverServiceInterceptor()) + client = RetrieverServiceClient(transport=transport) + + + """ + + def pre_batch_create_chunks( + self, + request: retriever_service.BatchCreateChunksRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + retriever_service.BatchCreateChunksRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for batch_create_chunks + + Override in a subclass to manipulate the request or metadata + before they are sent to the RetrieverService server. + """ + return request, metadata + + def post_batch_create_chunks( + self, response: retriever_service.BatchCreateChunksResponse + ) -> retriever_service.BatchCreateChunksResponse: + """Post-rpc interceptor for batch_create_chunks + + Override in a subclass to manipulate the response + after it is returned by the RetrieverService server but before + it is returned to user code. + """ + return response + + def pre_batch_delete_chunks( + self, + request: retriever_service.BatchDeleteChunksRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + retriever_service.BatchDeleteChunksRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for batch_delete_chunks + + Override in a subclass to manipulate the request or metadata + before they are sent to the RetrieverService server. + """ + return request, metadata + + def pre_batch_update_chunks( + self, + request: retriever_service.BatchUpdateChunksRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + retriever_service.BatchUpdateChunksRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for batch_update_chunks + + Override in a subclass to manipulate the request or metadata + before they are sent to the RetrieverService server. + """ + return request, metadata + + def post_batch_update_chunks( + self, response: retriever_service.BatchUpdateChunksResponse + ) -> retriever_service.BatchUpdateChunksResponse: + """Post-rpc interceptor for batch_update_chunks + + Override in a subclass to manipulate the response + after it is returned by the RetrieverService server but before + it is returned to user code. + """ + return response + + def pre_create_chunk( + self, + request: retriever_service.CreateChunkRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + retriever_service.CreateChunkRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for create_chunk + + Override in a subclass to manipulate the request or metadata + before they are sent to the RetrieverService server. + """ + return request, metadata + + def post_create_chunk(self, response: retriever.Chunk) -> retriever.Chunk: + """Post-rpc interceptor for create_chunk + + Override in a subclass to manipulate the response + after it is returned by the RetrieverService server but before + it is returned to user code. + """ + return response + + def pre_create_corpus( + self, + request: retriever_service.CreateCorpusRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + retriever_service.CreateCorpusRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for create_corpus + + Override in a subclass to manipulate the request or metadata + before they are sent to the RetrieverService server. + """ + return request, metadata + + def post_create_corpus(self, response: retriever.Corpus) -> retriever.Corpus: + """Post-rpc interceptor for create_corpus + + Override in a subclass to manipulate the response + after it is returned by the RetrieverService server but before + it is returned to user code. + """ + return response + + def pre_create_document( + self, + request: retriever_service.CreateDocumentRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + retriever_service.CreateDocumentRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for create_document + + Override in a subclass to manipulate the request or metadata + before they are sent to the RetrieverService server. + """ + return request, metadata + + def post_create_document(self, response: retriever.Document) -> retriever.Document: + """Post-rpc interceptor for create_document + + Override in a subclass to manipulate the response + after it is returned by the RetrieverService server but before + it is returned to user code. + """ + return response + + def pre_delete_chunk( + self, + request: retriever_service.DeleteChunkRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + retriever_service.DeleteChunkRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for delete_chunk + + Override in a subclass to manipulate the request or metadata + before they are sent to the RetrieverService server. + """ + return request, metadata + + def pre_delete_corpus( + self, + request: retriever_service.DeleteCorpusRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + retriever_service.DeleteCorpusRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for delete_corpus + + Override in a subclass to manipulate the request or metadata + before they are sent to the RetrieverService server. + """ + return request, metadata + + def pre_delete_document( + self, + request: retriever_service.DeleteDocumentRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + retriever_service.DeleteDocumentRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for delete_document + + Override in a subclass to manipulate the request or metadata + before they are sent to the RetrieverService server. + """ + return request, metadata + + def pre_get_chunk( + self, + request: retriever_service.GetChunkRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + retriever_service.GetChunkRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_chunk + + Override in a subclass to manipulate the request or metadata + before they are sent to the RetrieverService server. + """ + return request, metadata + + def post_get_chunk(self, response: retriever.Chunk) -> retriever.Chunk: + """Post-rpc interceptor for get_chunk + + Override in a subclass to manipulate the response + after it is returned by the RetrieverService server but before + it is returned to user code. + """ + return response + + def pre_get_corpus( + self, + request: retriever_service.GetCorpusRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + retriever_service.GetCorpusRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_corpus + + Override in a subclass to manipulate the request or metadata + before they are sent to the RetrieverService server. + """ + return request, metadata + + def post_get_corpus(self, response: retriever.Corpus) -> retriever.Corpus: + """Post-rpc interceptor for get_corpus + + Override in a subclass to manipulate the response + after it is returned by the RetrieverService server but before + it is returned to user code. + """ + return response + + def pre_get_document( + self, + request: retriever_service.GetDocumentRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + retriever_service.GetDocumentRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_document + + Override in a subclass to manipulate the request or metadata + before they are sent to the RetrieverService server. + """ + return request, metadata + + def post_get_document(self, response: retriever.Document) -> retriever.Document: + """Post-rpc interceptor for get_document + + Override in a subclass to manipulate the response + after it is returned by the RetrieverService server but before + it is returned to user code. + """ + return response + + def pre_list_chunks( + self, + request: retriever_service.ListChunksRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + retriever_service.ListChunksRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_chunks + + Override in a subclass to manipulate the request or metadata + before they are sent to the RetrieverService server. + """ + return request, metadata + + def post_list_chunks( + self, response: retriever_service.ListChunksResponse + ) -> retriever_service.ListChunksResponse: + """Post-rpc interceptor for list_chunks + + Override in a subclass to manipulate the response + after it is returned by the RetrieverService server but before + it is returned to user code. + """ + return response + + def pre_list_corpora( + self, + request: retriever_service.ListCorporaRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + retriever_service.ListCorporaRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_corpora + + Override in a subclass to manipulate the request or metadata + before they are sent to the RetrieverService server. + """ + return request, metadata + + def post_list_corpora( + self, response: retriever_service.ListCorporaResponse + ) -> retriever_service.ListCorporaResponse: + """Post-rpc interceptor for list_corpora + + Override in a subclass to manipulate the response + after it is returned by the RetrieverService server but before + it is returned to user code. + """ + return response + + def pre_list_documents( + self, + request: retriever_service.ListDocumentsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + retriever_service.ListDocumentsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_documents + + Override in a subclass to manipulate the request or metadata + before they are sent to the RetrieverService server. + """ + return request, metadata + + def post_list_documents( + self, response: retriever_service.ListDocumentsResponse + ) -> retriever_service.ListDocumentsResponse: + """Post-rpc interceptor for list_documents + + Override in a subclass to manipulate the response + after it is returned by the RetrieverService server but before + it is returned to user code. + """ + return response + + def pre_query_corpus( + self, + request: retriever_service.QueryCorpusRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + retriever_service.QueryCorpusRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for query_corpus + + Override in a subclass to manipulate the request or metadata + before they are sent to the RetrieverService server. + """ + return request, metadata + + def post_query_corpus( + self, response: retriever_service.QueryCorpusResponse + ) -> retriever_service.QueryCorpusResponse: + """Post-rpc interceptor for query_corpus + + Override in a subclass to manipulate the response + after it is returned by the RetrieverService server but before + it is returned to user code. + """ + return response + + def pre_query_document( + self, + request: retriever_service.QueryDocumentRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + retriever_service.QueryDocumentRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for query_document + + Override in a subclass to manipulate the request or metadata + before they are sent to the RetrieverService server. + """ + return request, metadata + + def post_query_document( + self, response: retriever_service.QueryDocumentResponse + ) -> retriever_service.QueryDocumentResponse: + """Post-rpc interceptor for query_document + + Override in a subclass to manipulate the response + after it is returned by the RetrieverService server but before + it is returned to user code. + """ + return response + + def pre_update_chunk( + self, + request: retriever_service.UpdateChunkRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + retriever_service.UpdateChunkRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for update_chunk + + Override in a subclass to manipulate the request or metadata + before they are sent to the RetrieverService server. + """ + return request, metadata + + def post_update_chunk(self, response: retriever.Chunk) -> retriever.Chunk: + """Post-rpc interceptor for update_chunk + + Override in a subclass to manipulate the response + after it is returned by the RetrieverService server but before + it is returned to user code. + """ + return response + + def pre_update_corpus( + self, + request: retriever_service.UpdateCorpusRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + retriever_service.UpdateCorpusRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for update_corpus + + Override in a subclass to manipulate the request or metadata + before they are sent to the RetrieverService server. + """ + return request, metadata + + def post_update_corpus(self, response: retriever.Corpus) -> retriever.Corpus: + """Post-rpc interceptor for update_corpus + + Override in a subclass to manipulate the response + after it is returned by the RetrieverService server but before + it is returned to user code. + """ + return response + + def pre_update_document( + self, + request: retriever_service.UpdateDocumentRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + retriever_service.UpdateDocumentRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for update_document + + Override in a subclass to manipulate the request or metadata + before they are sent to the RetrieverService server. + """ + return request, metadata + + def post_update_document(self, response: retriever.Document) -> retriever.Document: + """Post-rpc interceptor for update_document + + Override in a subclass to manipulate the response + after it is returned by the RetrieverService server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, + request: operations_pb2.GetOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the RetrieverService server. + """ + return request, metadata + + def post_get_operation( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for get_operation + + Override in a subclass to manipulate the response + after it is returned by the RetrieverService server but before + it is returned to user code. + """ + return response + + def pre_list_operations( + self, + request: operations_pb2.ListOperationsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.ListOperationsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the RetrieverService server. + """ + return request, metadata + + def post_list_operations( + self, response: operations_pb2.ListOperationsResponse + ) -> operations_pb2.ListOperationsResponse: + """Post-rpc interceptor for list_operations + + Override in a subclass to manipulate the response + after it is returned by the RetrieverService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class RetrieverServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: RetrieverServiceRestInterceptor + + +class RetrieverServiceRestTransport(_BaseRetrieverServiceRestTransport): + """REST backend synchronous transport for RetrieverService. + + An API for semantic search over a corpus of user uploaded + content. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "generativelanguage.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[RetrieverServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'generativelanguage.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + url_scheme=url_scheme, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or RetrieverServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _BatchCreateChunks( + _BaseRetrieverServiceRestTransport._BaseBatchCreateChunks, + RetrieverServiceRestStub, + ): + def __hash__(self): + return hash("RetrieverServiceRestTransport.BatchCreateChunks") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: retriever_service.BatchCreateChunksRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> retriever_service.BatchCreateChunksResponse: + r"""Call the batch create chunks method over HTTP. + + Args: + request (~.retriever_service.BatchCreateChunksRequest): + The request object. Request to batch create ``Chunk``\ s. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.retriever_service.BatchCreateChunksResponse: + Response from ``BatchCreateChunks`` containing a list of + created ``Chunk``\ s. + + """ + + http_options = ( + _BaseRetrieverServiceRestTransport._BaseBatchCreateChunks._get_http_options() + ) + + request, metadata = self._interceptor.pre_batch_create_chunks( + request, metadata + ) + transcoded_request = _BaseRetrieverServiceRestTransport._BaseBatchCreateChunks._get_transcoded_request( + http_options, request + ) + + body = _BaseRetrieverServiceRestTransport._BaseBatchCreateChunks._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseRetrieverServiceRestTransport._BaseBatchCreateChunks._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ai.generativelanguage_v1alpha.RetrieverServiceClient.BatchCreateChunks", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.RetrieverService", + "rpcName": "BatchCreateChunks", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RetrieverServiceRestTransport._BatchCreateChunks._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = retriever_service.BatchCreateChunksResponse() + pb_resp = retriever_service.BatchCreateChunksResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_batch_create_chunks(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + retriever_service.BatchCreateChunksResponse.to_json(response) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.ai.generativelanguage_v1alpha.RetrieverServiceClient.batch_create_chunks", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.RetrieverService", + "rpcName": "BatchCreateChunks", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _BatchDeleteChunks( + _BaseRetrieverServiceRestTransport._BaseBatchDeleteChunks, + RetrieverServiceRestStub, + ): + def __hash__(self): + return hash("RetrieverServiceRestTransport.BatchDeleteChunks") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: retriever_service.BatchDeleteChunksRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + r"""Call the batch delete chunks method over HTTP. + + Args: + request (~.retriever_service.BatchDeleteChunksRequest): + The request object. Request to batch delete ``Chunk``\ s. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = ( + _BaseRetrieverServiceRestTransport._BaseBatchDeleteChunks._get_http_options() + ) + + request, metadata = self._interceptor.pre_batch_delete_chunks( + request, metadata + ) + transcoded_request = _BaseRetrieverServiceRestTransport._BaseBatchDeleteChunks._get_transcoded_request( + http_options, request + ) + + body = _BaseRetrieverServiceRestTransport._BaseBatchDeleteChunks._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseRetrieverServiceRestTransport._BaseBatchDeleteChunks._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ai.generativelanguage_v1alpha.RetrieverServiceClient.BatchDeleteChunks", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.RetrieverService", + "rpcName": "BatchDeleteChunks", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RetrieverServiceRestTransport._BatchDeleteChunks._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _BatchUpdateChunks( + _BaseRetrieverServiceRestTransport._BaseBatchUpdateChunks, + RetrieverServiceRestStub, + ): + def __hash__(self): + return hash("RetrieverServiceRestTransport.BatchUpdateChunks") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: retriever_service.BatchUpdateChunksRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> retriever_service.BatchUpdateChunksResponse: + r"""Call the batch update chunks method over HTTP. + + Args: + request (~.retriever_service.BatchUpdateChunksRequest): + The request object. Request to batch update ``Chunk``\ s. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.retriever_service.BatchUpdateChunksResponse: + Response from ``BatchUpdateChunks`` containing a list of + updated ``Chunk``\ s. + + """ + + http_options = ( + _BaseRetrieverServiceRestTransport._BaseBatchUpdateChunks._get_http_options() + ) + + request, metadata = self._interceptor.pre_batch_update_chunks( + request, metadata + ) + transcoded_request = _BaseRetrieverServiceRestTransport._BaseBatchUpdateChunks._get_transcoded_request( + http_options, request + ) + + body = _BaseRetrieverServiceRestTransport._BaseBatchUpdateChunks._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseRetrieverServiceRestTransport._BaseBatchUpdateChunks._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ai.generativelanguage_v1alpha.RetrieverServiceClient.BatchUpdateChunks", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.RetrieverService", + "rpcName": "BatchUpdateChunks", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RetrieverServiceRestTransport._BatchUpdateChunks._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = retriever_service.BatchUpdateChunksResponse() + pb_resp = retriever_service.BatchUpdateChunksResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_batch_update_chunks(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + retriever_service.BatchUpdateChunksResponse.to_json(response) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.ai.generativelanguage_v1alpha.RetrieverServiceClient.batch_update_chunks", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.RetrieverService", + "rpcName": "BatchUpdateChunks", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateChunk( + _BaseRetrieverServiceRestTransport._BaseCreateChunk, RetrieverServiceRestStub + ): + def __hash__(self): + return hash("RetrieverServiceRestTransport.CreateChunk") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: retriever_service.CreateChunkRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> retriever.Chunk: + r"""Call the create chunk method over HTTP. + + Args: + request (~.retriever_service.CreateChunkRequest): + The request object. Request to create a ``Chunk``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.retriever.Chunk: + A ``Chunk`` is a subpart of a ``Document`` that is + treated as an independent unit for the purposes of + vector representation and storage. A ``Corpus`` can have + a maximum of 1 million ``Chunk``\ s. + + """ + + http_options = ( + _BaseRetrieverServiceRestTransport._BaseCreateChunk._get_http_options() + ) + + request, metadata = self._interceptor.pre_create_chunk(request, metadata) + transcoded_request = _BaseRetrieverServiceRestTransport._BaseCreateChunk._get_transcoded_request( + http_options, request + ) + + body = _BaseRetrieverServiceRestTransport._BaseCreateChunk._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseRetrieverServiceRestTransport._BaseCreateChunk._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ai.generativelanguage_v1alpha.RetrieverServiceClient.CreateChunk", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.RetrieverService", + "rpcName": "CreateChunk", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RetrieverServiceRestTransport._CreateChunk._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = retriever.Chunk() + pb_resp = retriever.Chunk.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_chunk(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = retriever.Chunk.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.ai.generativelanguage_v1alpha.RetrieverServiceClient.create_chunk", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.RetrieverService", + "rpcName": "CreateChunk", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateCorpus( + _BaseRetrieverServiceRestTransport._BaseCreateCorpus, RetrieverServiceRestStub + ): + def __hash__(self): + return hash("RetrieverServiceRestTransport.CreateCorpus") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: retriever_service.CreateCorpusRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> retriever.Corpus: + r"""Call the create corpus method over HTTP. + + Args: + request (~.retriever_service.CreateCorpusRequest): + The request object. Request to create a ``Corpus``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.retriever.Corpus: + A ``Corpus`` is a collection of ``Document``\ s. A + project can create up to 5 corpora. + + """ + + http_options = ( + _BaseRetrieverServiceRestTransport._BaseCreateCorpus._get_http_options() + ) + + request, metadata = self._interceptor.pre_create_corpus(request, metadata) + transcoded_request = _BaseRetrieverServiceRestTransport._BaseCreateCorpus._get_transcoded_request( + http_options, request + ) + + body = _BaseRetrieverServiceRestTransport._BaseCreateCorpus._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseRetrieverServiceRestTransport._BaseCreateCorpus._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ai.generativelanguage_v1alpha.RetrieverServiceClient.CreateCorpus", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.RetrieverService", + "rpcName": "CreateCorpus", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RetrieverServiceRestTransport._CreateCorpus._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = retriever.Corpus() + pb_resp = retriever.Corpus.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_corpus(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = retriever.Corpus.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.ai.generativelanguage_v1alpha.RetrieverServiceClient.create_corpus", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.RetrieverService", + "rpcName": "CreateCorpus", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateDocument( + _BaseRetrieverServiceRestTransport._BaseCreateDocument, RetrieverServiceRestStub + ): + def __hash__(self): + return hash("RetrieverServiceRestTransport.CreateDocument") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: retriever_service.CreateDocumentRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> retriever.Document: + r"""Call the create document method over HTTP. + + Args: + request (~.retriever_service.CreateDocumentRequest): + The request object. Request to create a ``Document``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.retriever.Document: + A ``Document`` is a collection of ``Chunk``\ s. A + ``Corpus`` can have a maximum of 10,000 ``Document``\ s. + + """ + + http_options = ( + _BaseRetrieverServiceRestTransport._BaseCreateDocument._get_http_options() + ) + + request, metadata = self._interceptor.pre_create_document(request, metadata) + transcoded_request = _BaseRetrieverServiceRestTransport._BaseCreateDocument._get_transcoded_request( + http_options, request + ) + + body = _BaseRetrieverServiceRestTransport._BaseCreateDocument._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseRetrieverServiceRestTransport._BaseCreateDocument._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ai.generativelanguage_v1alpha.RetrieverServiceClient.CreateDocument", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.RetrieverService", + "rpcName": "CreateDocument", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RetrieverServiceRestTransport._CreateDocument._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = retriever.Document() + pb_resp = retriever.Document.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_document(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = retriever.Document.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.ai.generativelanguage_v1alpha.RetrieverServiceClient.create_document", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.RetrieverService", + "rpcName": "CreateDocument", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteChunk( + _BaseRetrieverServiceRestTransport._BaseDeleteChunk, RetrieverServiceRestStub + ): + def __hash__(self): + return hash("RetrieverServiceRestTransport.DeleteChunk") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: retriever_service.DeleteChunkRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + r"""Call the delete chunk method over HTTP. + + Args: + request (~.retriever_service.DeleteChunkRequest): + The request object. Request to delete a ``Chunk``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = ( + _BaseRetrieverServiceRestTransport._BaseDeleteChunk._get_http_options() + ) + + request, metadata = self._interceptor.pre_delete_chunk(request, metadata) + transcoded_request = _BaseRetrieverServiceRestTransport._BaseDeleteChunk._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseRetrieverServiceRestTransport._BaseDeleteChunk._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ai.generativelanguage_v1alpha.RetrieverServiceClient.DeleteChunk", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.RetrieverService", + "rpcName": "DeleteChunk", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RetrieverServiceRestTransport._DeleteChunk._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _DeleteCorpus( + _BaseRetrieverServiceRestTransport._BaseDeleteCorpus, RetrieverServiceRestStub + ): + def __hash__(self): + return hash("RetrieverServiceRestTransport.DeleteCorpus") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: retriever_service.DeleteCorpusRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + r"""Call the delete corpus method over HTTP. + + Args: + request (~.retriever_service.DeleteCorpusRequest): + The request object. Request to delete a ``Corpus``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = ( + _BaseRetrieverServiceRestTransport._BaseDeleteCorpus._get_http_options() + ) + + request, metadata = self._interceptor.pre_delete_corpus(request, metadata) + transcoded_request = _BaseRetrieverServiceRestTransport._BaseDeleteCorpus._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseRetrieverServiceRestTransport._BaseDeleteCorpus._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ai.generativelanguage_v1alpha.RetrieverServiceClient.DeleteCorpus", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.RetrieverService", + "rpcName": "DeleteCorpus", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RetrieverServiceRestTransport._DeleteCorpus._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _DeleteDocument( + _BaseRetrieverServiceRestTransport._BaseDeleteDocument, RetrieverServiceRestStub + ): + def __hash__(self): + return hash("RetrieverServiceRestTransport.DeleteDocument") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: retriever_service.DeleteDocumentRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + r"""Call the delete document method over HTTP. + + Args: + request (~.retriever_service.DeleteDocumentRequest): + The request object. Request to delete a ``Document``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = ( + _BaseRetrieverServiceRestTransport._BaseDeleteDocument._get_http_options() + ) + + request, metadata = self._interceptor.pre_delete_document(request, metadata) + transcoded_request = _BaseRetrieverServiceRestTransport._BaseDeleteDocument._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseRetrieverServiceRestTransport._BaseDeleteDocument._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ai.generativelanguage_v1alpha.RetrieverServiceClient.DeleteDocument", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.RetrieverService", + "rpcName": "DeleteDocument", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RetrieverServiceRestTransport._DeleteDocument._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _GetChunk( + _BaseRetrieverServiceRestTransport._BaseGetChunk, RetrieverServiceRestStub + ): + def __hash__(self): + return hash("RetrieverServiceRestTransport.GetChunk") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: retriever_service.GetChunkRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> retriever.Chunk: + r"""Call the get chunk method over HTTP. + + Args: + request (~.retriever_service.GetChunkRequest): + The request object. Request for getting information about a specific + ``Chunk``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.retriever.Chunk: + A ``Chunk`` is a subpart of a ``Document`` that is + treated as an independent unit for the purposes of + vector representation and storage. A ``Corpus`` can have + a maximum of 1 million ``Chunk``\ s. + + """ + + http_options = ( + _BaseRetrieverServiceRestTransport._BaseGetChunk._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_chunk(request, metadata) + transcoded_request = _BaseRetrieverServiceRestTransport._BaseGetChunk._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = ( + _BaseRetrieverServiceRestTransport._BaseGetChunk._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ai.generativelanguage_v1alpha.RetrieverServiceClient.GetChunk", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.RetrieverService", + "rpcName": "GetChunk", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RetrieverServiceRestTransport._GetChunk._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = retriever.Chunk() + pb_resp = retriever.Chunk.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_chunk(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = retriever.Chunk.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.ai.generativelanguage_v1alpha.RetrieverServiceClient.get_chunk", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.RetrieverService", + "rpcName": "GetChunk", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetCorpus( + _BaseRetrieverServiceRestTransport._BaseGetCorpus, RetrieverServiceRestStub + ): + def __hash__(self): + return hash("RetrieverServiceRestTransport.GetCorpus") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: retriever_service.GetCorpusRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> retriever.Corpus: + r"""Call the get corpus method over HTTP. + + Args: + request (~.retriever_service.GetCorpusRequest): + The request object. Request for getting information about a specific + ``Corpus``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.retriever.Corpus: + A ``Corpus`` is a collection of ``Document``\ s. A + project can create up to 5 corpora. + + """ + + http_options = ( + _BaseRetrieverServiceRestTransport._BaseGetCorpus._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_corpus(request, metadata) + transcoded_request = _BaseRetrieverServiceRestTransport._BaseGetCorpus._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseRetrieverServiceRestTransport._BaseGetCorpus._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ai.generativelanguage_v1alpha.RetrieverServiceClient.GetCorpus", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.RetrieverService", + "rpcName": "GetCorpus", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RetrieverServiceRestTransport._GetCorpus._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = retriever.Corpus() + pb_resp = retriever.Corpus.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_corpus(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = retriever.Corpus.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.ai.generativelanguage_v1alpha.RetrieverServiceClient.get_corpus", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.RetrieverService", + "rpcName": "GetCorpus", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetDocument( + _BaseRetrieverServiceRestTransport._BaseGetDocument, RetrieverServiceRestStub + ): + def __hash__(self): + return hash("RetrieverServiceRestTransport.GetDocument") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: retriever_service.GetDocumentRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> retriever.Document: + r"""Call the get document method over HTTP. + + Args: + request (~.retriever_service.GetDocumentRequest): + The request object. Request for getting information about a specific + ``Document``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.retriever.Document: + A ``Document`` is a collection of ``Chunk``\ s. A + ``Corpus`` can have a maximum of 10,000 ``Document``\ s. + + """ + + http_options = ( + _BaseRetrieverServiceRestTransport._BaseGetDocument._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_document(request, metadata) + transcoded_request = _BaseRetrieverServiceRestTransport._BaseGetDocument._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseRetrieverServiceRestTransport._BaseGetDocument._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ai.generativelanguage_v1alpha.RetrieverServiceClient.GetDocument", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.RetrieverService", + "rpcName": "GetDocument", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RetrieverServiceRestTransport._GetDocument._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = retriever.Document() + pb_resp = retriever.Document.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_document(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = retriever.Document.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.ai.generativelanguage_v1alpha.RetrieverServiceClient.get_document", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.RetrieverService", + "rpcName": "GetDocument", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListChunks( + _BaseRetrieverServiceRestTransport._BaseListChunks, RetrieverServiceRestStub + ): + def __hash__(self): + return hash("RetrieverServiceRestTransport.ListChunks") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: retriever_service.ListChunksRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> retriever_service.ListChunksResponse: + r"""Call the list chunks method over HTTP. + + Args: + request (~.retriever_service.ListChunksRequest): + The request object. Request for listing ``Chunk``\ s. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.retriever_service.ListChunksResponse: + Response from ``ListChunks`` containing a paginated list + of ``Chunk``\ s. The ``Chunk``\ s are sorted by + ascending ``chunk.create_time``. + + """ + + http_options = ( + _BaseRetrieverServiceRestTransport._BaseListChunks._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_chunks(request, metadata) + transcoded_request = _BaseRetrieverServiceRestTransport._BaseListChunks._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseRetrieverServiceRestTransport._BaseListChunks._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ai.generativelanguage_v1alpha.RetrieverServiceClient.ListChunks", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.RetrieverService", + "rpcName": "ListChunks", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RetrieverServiceRestTransport._ListChunks._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = retriever_service.ListChunksResponse() + pb_resp = retriever_service.ListChunksResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_chunks(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = retriever_service.ListChunksResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.ai.generativelanguage_v1alpha.RetrieverServiceClient.list_chunks", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.RetrieverService", + "rpcName": "ListChunks", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListCorpora( + _BaseRetrieverServiceRestTransport._BaseListCorpora, RetrieverServiceRestStub + ): + def __hash__(self): + return hash("RetrieverServiceRestTransport.ListCorpora") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: retriever_service.ListCorporaRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> retriever_service.ListCorporaResponse: + r"""Call the list corpora method over HTTP. + + Args: + request (~.retriever_service.ListCorporaRequest): + The request object. Request for listing ``Corpora``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.retriever_service.ListCorporaResponse: + Response from ``ListCorpora`` containing a paginated + list of ``Corpora``. The results are sorted by ascending + ``corpus.create_time``. + + """ + + http_options = ( + _BaseRetrieverServiceRestTransport._BaseListCorpora._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_corpora(request, metadata) + transcoded_request = _BaseRetrieverServiceRestTransport._BaseListCorpora._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseRetrieverServiceRestTransport._BaseListCorpora._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ai.generativelanguage_v1alpha.RetrieverServiceClient.ListCorpora", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.RetrieverService", + "rpcName": "ListCorpora", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RetrieverServiceRestTransport._ListCorpora._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = retriever_service.ListCorporaResponse() + pb_resp = retriever_service.ListCorporaResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_corpora(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = retriever_service.ListCorporaResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.ai.generativelanguage_v1alpha.RetrieverServiceClient.list_corpora", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.RetrieverService", + "rpcName": "ListCorpora", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListDocuments( + _BaseRetrieverServiceRestTransport._BaseListDocuments, RetrieverServiceRestStub + ): + def __hash__(self): + return hash("RetrieverServiceRestTransport.ListDocuments") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: retriever_service.ListDocumentsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> retriever_service.ListDocumentsResponse: + r"""Call the list documents method over HTTP. + + Args: + request (~.retriever_service.ListDocumentsRequest): + The request object. Request for listing ``Document``\ s. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.retriever_service.ListDocumentsResponse: + Response from ``ListDocuments`` containing a paginated + list of ``Document``\ s. The ``Document``\ s are sorted + by ascending ``document.create_time``. + + """ + + http_options = ( + _BaseRetrieverServiceRestTransport._BaseListDocuments._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_documents(request, metadata) + transcoded_request = _BaseRetrieverServiceRestTransport._BaseListDocuments._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseRetrieverServiceRestTransport._BaseListDocuments._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ai.generativelanguage_v1alpha.RetrieverServiceClient.ListDocuments", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.RetrieverService", + "rpcName": "ListDocuments", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RetrieverServiceRestTransport._ListDocuments._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = retriever_service.ListDocumentsResponse() + pb_resp = retriever_service.ListDocumentsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_documents(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = retriever_service.ListDocumentsResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.ai.generativelanguage_v1alpha.RetrieverServiceClient.list_documents", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.RetrieverService", + "rpcName": "ListDocuments", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _QueryCorpus( + _BaseRetrieverServiceRestTransport._BaseQueryCorpus, RetrieverServiceRestStub + ): + def __hash__(self): + return hash("RetrieverServiceRestTransport.QueryCorpus") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: retriever_service.QueryCorpusRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> retriever_service.QueryCorpusResponse: + r"""Call the query corpus method over HTTP. + + Args: + request (~.retriever_service.QueryCorpusRequest): + The request object. Request for querying a ``Corpus``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.retriever_service.QueryCorpusResponse: + Response from ``QueryCorpus`` containing a list of + relevant chunks. + + """ + + http_options = ( + _BaseRetrieverServiceRestTransport._BaseQueryCorpus._get_http_options() + ) + + request, metadata = self._interceptor.pre_query_corpus(request, metadata) + transcoded_request = _BaseRetrieverServiceRestTransport._BaseQueryCorpus._get_transcoded_request( + http_options, request + ) + + body = _BaseRetrieverServiceRestTransport._BaseQueryCorpus._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseRetrieverServiceRestTransport._BaseQueryCorpus._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ai.generativelanguage_v1alpha.RetrieverServiceClient.QueryCorpus", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.RetrieverService", + "rpcName": "QueryCorpus", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RetrieverServiceRestTransport._QueryCorpus._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = retriever_service.QueryCorpusResponse() + pb_resp = retriever_service.QueryCorpusResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_query_corpus(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = retriever_service.QueryCorpusResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.ai.generativelanguage_v1alpha.RetrieverServiceClient.query_corpus", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.RetrieverService", + "rpcName": "QueryCorpus", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _QueryDocument( + _BaseRetrieverServiceRestTransport._BaseQueryDocument, RetrieverServiceRestStub + ): + def __hash__(self): + return hash("RetrieverServiceRestTransport.QueryDocument") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: retriever_service.QueryDocumentRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> retriever_service.QueryDocumentResponse: + r"""Call the query document method over HTTP. + + Args: + request (~.retriever_service.QueryDocumentRequest): + The request object. Request for querying a ``Document``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.retriever_service.QueryDocumentResponse: + Response from ``QueryDocument`` containing a list of + relevant chunks. + + """ + + http_options = ( + _BaseRetrieverServiceRestTransport._BaseQueryDocument._get_http_options() + ) + + request, metadata = self._interceptor.pre_query_document(request, metadata) + transcoded_request = _BaseRetrieverServiceRestTransport._BaseQueryDocument._get_transcoded_request( + http_options, request + ) + + body = _BaseRetrieverServiceRestTransport._BaseQueryDocument._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseRetrieverServiceRestTransport._BaseQueryDocument._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ai.generativelanguage_v1alpha.RetrieverServiceClient.QueryDocument", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.RetrieverService", + "rpcName": "QueryDocument", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RetrieverServiceRestTransport._QueryDocument._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = retriever_service.QueryDocumentResponse() + pb_resp = retriever_service.QueryDocumentResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_query_document(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = retriever_service.QueryDocumentResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.ai.generativelanguage_v1alpha.RetrieverServiceClient.query_document", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.RetrieverService", + "rpcName": "QueryDocument", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateChunk( + _BaseRetrieverServiceRestTransport._BaseUpdateChunk, RetrieverServiceRestStub + ): + def __hash__(self): + return hash("RetrieverServiceRestTransport.UpdateChunk") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: retriever_service.UpdateChunkRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> retriever.Chunk: + r"""Call the update chunk method over HTTP. + + Args: + request (~.retriever_service.UpdateChunkRequest): + The request object. Request to update a ``Chunk``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.retriever.Chunk: + A ``Chunk`` is a subpart of a ``Document`` that is + treated as an independent unit for the purposes of + vector representation and storage. A ``Corpus`` can have + a maximum of 1 million ``Chunk``\ s. + + """ + + http_options = ( + _BaseRetrieverServiceRestTransport._BaseUpdateChunk._get_http_options() + ) + + request, metadata = self._interceptor.pre_update_chunk(request, metadata) + transcoded_request = _BaseRetrieverServiceRestTransport._BaseUpdateChunk._get_transcoded_request( + http_options, request + ) + + body = _BaseRetrieverServiceRestTransport._BaseUpdateChunk._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseRetrieverServiceRestTransport._BaseUpdateChunk._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ai.generativelanguage_v1alpha.RetrieverServiceClient.UpdateChunk", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.RetrieverService", + "rpcName": "UpdateChunk", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RetrieverServiceRestTransport._UpdateChunk._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = retriever.Chunk() + pb_resp = retriever.Chunk.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_chunk(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = retriever.Chunk.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.ai.generativelanguage_v1alpha.RetrieverServiceClient.update_chunk", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.RetrieverService", + "rpcName": "UpdateChunk", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateCorpus( + _BaseRetrieverServiceRestTransport._BaseUpdateCorpus, RetrieverServiceRestStub + ): + def __hash__(self): + return hash("RetrieverServiceRestTransport.UpdateCorpus") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: retriever_service.UpdateCorpusRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> retriever.Corpus: + r"""Call the update corpus method over HTTP. + + Args: + request (~.retriever_service.UpdateCorpusRequest): + The request object. Request to update a ``Corpus``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.retriever.Corpus: + A ``Corpus`` is a collection of ``Document``\ s. A + project can create up to 5 corpora. + + """ + + http_options = ( + _BaseRetrieverServiceRestTransport._BaseUpdateCorpus._get_http_options() + ) + + request, metadata = self._interceptor.pre_update_corpus(request, metadata) + transcoded_request = _BaseRetrieverServiceRestTransport._BaseUpdateCorpus._get_transcoded_request( + http_options, request + ) + + body = _BaseRetrieverServiceRestTransport._BaseUpdateCorpus._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseRetrieverServiceRestTransport._BaseUpdateCorpus._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ai.generativelanguage_v1alpha.RetrieverServiceClient.UpdateCorpus", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.RetrieverService", + "rpcName": "UpdateCorpus", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RetrieverServiceRestTransport._UpdateCorpus._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = retriever.Corpus() + pb_resp = retriever.Corpus.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_corpus(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = retriever.Corpus.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.ai.generativelanguage_v1alpha.RetrieverServiceClient.update_corpus", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.RetrieverService", + "rpcName": "UpdateCorpus", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateDocument( + _BaseRetrieverServiceRestTransport._BaseUpdateDocument, RetrieverServiceRestStub + ): + def __hash__(self): + return hash("RetrieverServiceRestTransport.UpdateDocument") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: retriever_service.UpdateDocumentRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> retriever.Document: + r"""Call the update document method over HTTP. + + Args: + request (~.retriever_service.UpdateDocumentRequest): + The request object. Request to update a ``Document``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.retriever.Document: + A ``Document`` is a collection of ``Chunk``\ s. A + ``Corpus`` can have a maximum of 10,000 ``Document``\ s. + + """ + + http_options = ( + _BaseRetrieverServiceRestTransport._BaseUpdateDocument._get_http_options() + ) + + request, metadata = self._interceptor.pre_update_document(request, metadata) + transcoded_request = _BaseRetrieverServiceRestTransport._BaseUpdateDocument._get_transcoded_request( + http_options, request + ) + + body = _BaseRetrieverServiceRestTransport._BaseUpdateDocument._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseRetrieverServiceRestTransport._BaseUpdateDocument._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ai.generativelanguage_v1alpha.RetrieverServiceClient.UpdateDocument", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.RetrieverService", + "rpcName": "UpdateDocument", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RetrieverServiceRestTransport._UpdateDocument._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = retriever.Document() + pb_resp = retriever.Document.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_document(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = retriever.Document.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.ai.generativelanguage_v1alpha.RetrieverServiceClient.update_document", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.RetrieverService", + "rpcName": "UpdateDocument", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def batch_create_chunks( + self, + ) -> Callable[ + [retriever_service.BatchCreateChunksRequest], + retriever_service.BatchCreateChunksResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._BatchCreateChunks(self._session, self._host, self._interceptor) # type: ignore + + @property + def batch_delete_chunks( + self, + ) -> Callable[[retriever_service.BatchDeleteChunksRequest], empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._BatchDeleteChunks(self._session, self._host, self._interceptor) # type: ignore + + @property + def batch_update_chunks( + self, + ) -> Callable[ + [retriever_service.BatchUpdateChunksRequest], + retriever_service.BatchUpdateChunksResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._BatchUpdateChunks(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_chunk( + self, + ) -> Callable[[retriever_service.CreateChunkRequest], retriever.Chunk]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateChunk(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_corpus( + self, + ) -> Callable[[retriever_service.CreateCorpusRequest], retriever.Corpus]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateCorpus(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_document( + self, + ) -> Callable[[retriever_service.CreateDocumentRequest], retriever.Document]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateDocument(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_chunk( + self, + ) -> Callable[[retriever_service.DeleteChunkRequest], empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteChunk(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_corpus( + self, + ) -> Callable[[retriever_service.DeleteCorpusRequest], empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteCorpus(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_document( + self, + ) -> Callable[[retriever_service.DeleteDocumentRequest], empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteDocument(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_chunk( + self, + ) -> Callable[[retriever_service.GetChunkRequest], retriever.Chunk]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetChunk(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_corpus( + self, + ) -> Callable[[retriever_service.GetCorpusRequest], retriever.Corpus]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetCorpus(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_document( + self, + ) -> Callable[[retriever_service.GetDocumentRequest], retriever.Document]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetDocument(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_chunks( + self, + ) -> Callable[ + [retriever_service.ListChunksRequest], retriever_service.ListChunksResponse + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListChunks(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_corpora( + self, + ) -> Callable[ + [retriever_service.ListCorporaRequest], retriever_service.ListCorporaResponse + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListCorpora(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_documents( + self, + ) -> Callable[ + [retriever_service.ListDocumentsRequest], + retriever_service.ListDocumentsResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListDocuments(self._session, self._host, self._interceptor) # type: ignore + + @property + def query_corpus( + self, + ) -> Callable[ + [retriever_service.QueryCorpusRequest], retriever_service.QueryCorpusResponse + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._QueryCorpus(self._session, self._host, self._interceptor) # type: ignore + + @property + def query_document( + self, + ) -> Callable[ + [retriever_service.QueryDocumentRequest], + retriever_service.QueryDocumentResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._QueryDocument(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_chunk( + self, + ) -> Callable[[retriever_service.UpdateChunkRequest], retriever.Chunk]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateChunk(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_corpus( + self, + ) -> Callable[[retriever_service.UpdateCorpusRequest], retriever.Corpus]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateCorpus(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_document( + self, + ) -> Callable[[retriever_service.UpdateDocumentRequest], retriever.Document]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateDocument(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation( + _BaseRetrieverServiceRestTransport._BaseGetOperation, RetrieverServiceRestStub + ): + def __hash__(self): + return hash("RetrieverServiceRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.GetOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options = ( + _BaseRetrieverServiceRestTransport._BaseGetOperation._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + transcoded_request = _BaseRetrieverServiceRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseRetrieverServiceRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ai.generativelanguage_v1alpha.RetrieverServiceClient.GetOperation", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.RetrieverService", + "rpcName": "GetOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RetrieverServiceRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.Operation() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_operation(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.ai.generativelanguage_v1alpha.RetrieverServiceAsyncClient.GetOperation", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.RetrieverService", + "rpcName": "GetOperation", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations( + _BaseRetrieverServiceRestTransport._BaseListOperations, RetrieverServiceRestStub + ): + def __hash__(self): + return hash("RetrieverServiceRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.ListOperationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options = ( + _BaseRetrieverServiceRestTransport._BaseListOperations._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + transcoded_request = _BaseRetrieverServiceRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseRetrieverServiceRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.ai.generativelanguage_v1alpha.RetrieverServiceClient.ListOperations", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.RetrieverService", + "rpcName": "ListOperations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RetrieverServiceRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_list_operations(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.ai.generativelanguage_v1alpha.RetrieverServiceAsyncClient.ListOperations", + extra={ + "serviceName": "google.ai.generativelanguage.v1alpha.RetrieverService", + "rpcName": "ListOperations", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("RetrieverServiceRestTransport",) diff --git a/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/retriever_service/transports/rest_base.py b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/retriever_service/transports/rest_base.py new file mode 100644 index 0000000000000000000000000000000000000000..b5fb721e220f71909cecf2780658e6fd2e90b4b6 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/retriever_service/transports/rest_base.py @@ -0,0 +1,1196 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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. +# +import json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import json_format + +from google.ai.generativelanguage_v1alpha.types import retriever, retriever_service + +from .base import DEFAULT_CLIENT_INFO, RetrieverServiceTransport + + +class _BaseRetrieverServiceRestTransport(RetrieverServiceTransport): + """Base REST backend transport for RetrieverService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "generativelanguage.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'generativelanguage.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + class _BaseBatchCreateChunks: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1alpha/{parent=corpora/*/documents/*}/chunks:batchCreate", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = retriever_service.BatchCreateChunksRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseRetrieverServiceRestTransport._BaseBatchCreateChunks._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseBatchDeleteChunks: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1alpha/{parent=corpora/*/documents/*}/chunks:batchDelete", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = retriever_service.BatchDeleteChunksRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseRetrieverServiceRestTransport._BaseBatchDeleteChunks._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseBatchUpdateChunks: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1alpha/{parent=corpora/*/documents/*}/chunks:batchUpdate", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = retriever_service.BatchUpdateChunksRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseRetrieverServiceRestTransport._BaseBatchUpdateChunks._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateChunk: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1alpha/{parent=corpora/*/documents/*}/chunks", + "body": "chunk", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = retriever_service.CreateChunkRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseRetrieverServiceRestTransport._BaseCreateChunk._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateCorpus: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1alpha/corpora", + "body": "corpus", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = retriever_service.CreateCorpusRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseRetrieverServiceRestTransport._BaseCreateCorpus._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateDocument: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1alpha/{parent=corpora/*}/documents", + "body": "document", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = retriever_service.CreateDocumentRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseRetrieverServiceRestTransport._BaseCreateDocument._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteChunk: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1alpha/{name=corpora/*/documents/*/chunks/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = retriever_service.DeleteChunkRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseRetrieverServiceRestTransport._BaseDeleteChunk._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteCorpus: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1alpha/{name=corpora/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = retriever_service.DeleteCorpusRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseRetrieverServiceRestTransport._BaseDeleteCorpus._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteDocument: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1alpha/{name=corpora/*/documents/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = retriever_service.DeleteDocumentRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseRetrieverServiceRestTransport._BaseDeleteDocument._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetChunk: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1alpha/{name=corpora/*/documents/*/chunks/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = retriever_service.GetChunkRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseRetrieverServiceRestTransport._BaseGetChunk._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetCorpus: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1alpha/{name=corpora/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = retriever_service.GetCorpusRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseRetrieverServiceRestTransport._BaseGetCorpus._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetDocument: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1alpha/{name=corpora/*/documents/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = retriever_service.GetDocumentRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseRetrieverServiceRestTransport._BaseGetDocument._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListChunks: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1alpha/{parent=corpora/*/documents/*}/chunks", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = retriever_service.ListChunksRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseRetrieverServiceRestTransport._BaseListChunks._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListCorpora: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1alpha/corpora", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = retriever_service.ListCorporaRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListDocuments: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1alpha/{parent=corpora/*}/documents", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = retriever_service.ListDocumentsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseRetrieverServiceRestTransport._BaseListDocuments._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseQueryCorpus: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1alpha/{name=corpora/*}:query", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = retriever_service.QueryCorpusRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseRetrieverServiceRestTransport._BaseQueryCorpus._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseQueryDocument: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1alpha/{name=corpora/*/documents/*}:query", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = retriever_service.QueryDocumentRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseRetrieverServiceRestTransport._BaseQueryDocument._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateChunk: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask": {}, + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1alpha/{chunk.name=corpora/*/documents/*/chunks/*}", + "body": "chunk", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = retriever_service.UpdateChunkRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseRetrieverServiceRestTransport._BaseUpdateChunk._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateCorpus: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask": {}, + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1alpha/{corpus.name=corpora/*}", + "body": "corpus", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = retriever_service.UpdateCorpusRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseRetrieverServiceRestTransport._BaseUpdateCorpus._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateDocument: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask": {}, + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1alpha/{document.name=corpora/*/documents/*}", + "body": "document", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = retriever_service.UpdateDocumentRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseRetrieverServiceRestTransport._BaseUpdateDocument._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1alpha/{name=tunedModels/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1alpha/{name=generatedFiles/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1alpha/{name=models/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1alpha/{name=tunedModels/*}/operations", + }, + { + "method": "get", + "uri": "/v1alpha/{name=models/*}/operations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BaseRetrieverServiceRestTransport",) diff --git a/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/types/__pycache__/__init__.cpython-311.pyc b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/types/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1e397414637da0f54be959cc30e3a444270d9a7b Binary files /dev/null and b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/types/__pycache__/__init__.cpython-311.pyc differ diff --git a/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/types/__pycache__/cache_service.cpython-311.pyc b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/types/__pycache__/cache_service.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b37f83631aba02d0f89817458c1e93bea75f146a Binary files /dev/null and b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/types/__pycache__/cache_service.cpython-311.pyc differ diff --git a/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/types/__pycache__/citation.cpython-311.pyc b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/types/__pycache__/citation.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..067f2655c5c714c818c6bf1195e91a2d6234cfbe Binary files /dev/null and b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/types/__pycache__/citation.cpython-311.pyc differ diff --git a/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/types/__pycache__/content.cpython-311.pyc b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/types/__pycache__/content.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d142b839b9fa0c25ceb0a231a410dac56dc19647 Binary files /dev/null and b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/types/__pycache__/content.cpython-311.pyc differ diff --git a/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/types/__pycache__/file_service.cpython-311.pyc b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/types/__pycache__/file_service.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8f671ca14f83468bc3f06f87319874807c62727d Binary files /dev/null and b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/types/__pycache__/file_service.cpython-311.pyc differ diff --git a/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/types/__pycache__/model.cpython-311.pyc b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/types/__pycache__/model.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b254a644bfca3efc32e6fe37413e5fe718170104 Binary files /dev/null and b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/types/__pycache__/model.cpython-311.pyc differ diff --git a/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/types/__pycache__/permission_service.cpython-311.pyc b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/types/__pycache__/permission_service.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b2dfbb7fd9c01d77a690baed65e184d549381f20 Binary files /dev/null and b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/types/__pycache__/permission_service.cpython-311.pyc differ diff --git a/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/types/__pycache__/prediction_service.cpython-311.pyc b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/types/__pycache__/prediction_service.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b0219315d9f797cec2569e503bedef01b9208388 Binary files /dev/null and b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/types/__pycache__/prediction_service.cpython-311.pyc differ diff --git a/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/types/__pycache__/retriever_service.cpython-311.pyc b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/types/__pycache__/retriever_service.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d3f84f2eae2051c80522db329266f87d96226ec8 Binary files /dev/null and b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/types/__pycache__/retriever_service.cpython-311.pyc differ diff --git a/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/types/__pycache__/text_service.cpython-311.pyc b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/types/__pycache__/text_service.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..652b091bf46cdb41eefc5f1094bf3192f3550426 Binary files /dev/null and b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/types/__pycache__/text_service.cpython-311.pyc differ diff --git a/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/types/cached_content.py b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/types/cached_content.py new file mode 100644 index 0000000000000000000000000000000000000000..3eeed986fcc904e50081e2702bc8977829b0c0dd --- /dev/null +++ b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/types/cached_content.py @@ -0,0 +1,182 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import proto # type: ignore + +from google.ai.generativelanguage_v1alpha.types import content + +__protobuf__ = proto.module( + package="google.ai.generativelanguage.v1alpha", + manifest={ + "CachedContent", + }, +) + + +class CachedContent(proto.Message): + r"""Content that has been preprocessed and can be used in + subsequent request to GenerativeService. + + Cached content can be only used with model it was created for. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + expire_time (google.protobuf.timestamp_pb2.Timestamp): + Timestamp in UTC of when this resource is considered + expired. This is *always* provided on output, regardless of + what was sent on input. + + This field is a member of `oneof`_ ``expiration``. + ttl (google.protobuf.duration_pb2.Duration): + Input only. New TTL for this resource, input + only. + + This field is a member of `oneof`_ ``expiration``. + name (str): + Optional. Identifier. The resource name referring to the + cached content. Format: ``cachedContents/{id}`` + + This field is a member of `oneof`_ ``_name``. + display_name (str): + Optional. Immutable. The user-generated + meaningful display name of the cached content. + Maximum 128 Unicode characters. + + This field is a member of `oneof`_ ``_display_name``. + model (str): + Required. Immutable. The name of the ``Model`` to use for + cached content Format: ``models/{model}`` + + This field is a member of `oneof`_ ``_model``. + system_instruction (google.ai.generativelanguage_v1alpha.types.Content): + Optional. Input only. Immutable. Developer + set system instruction. Currently text only. + + This field is a member of `oneof`_ ``_system_instruction``. + contents (MutableSequence[google.ai.generativelanguage_v1alpha.types.Content]): + Optional. Input only. Immutable. The content + to cache. + tools (MutableSequence[google.ai.generativelanguage_v1alpha.types.Tool]): + Optional. Input only. Immutable. A list of ``Tools`` the + model may use to generate the next response + tool_config (google.ai.generativelanguage_v1alpha.types.ToolConfig): + Optional. Input only. Immutable. Tool config. + This config is shared for all tools. + + This field is a member of `oneof`_ ``_tool_config``. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Creation time of the cache + entry. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. When the cache entry was last + updated in UTC time. + usage_metadata (google.ai.generativelanguage_v1alpha.types.CachedContent.UsageMetadata): + Output only. Metadata on the usage of the + cached content. + """ + + class UsageMetadata(proto.Message): + r"""Metadata on the usage of the cached content. + + Attributes: + total_token_count (int): + Total number of tokens that the cached + content consumes. + """ + + total_token_count: int = proto.Field( + proto.INT32, + number=1, + ) + + expire_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=9, + oneof="expiration", + message=timestamp_pb2.Timestamp, + ) + ttl: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=10, + oneof="expiration", + message=duration_pb2.Duration, + ) + name: str = proto.Field( + proto.STRING, + number=1, + optional=True, + ) + display_name: str = proto.Field( + proto.STRING, + number=11, + optional=True, + ) + model: str = proto.Field( + proto.STRING, + number=2, + optional=True, + ) + system_instruction: content.Content = proto.Field( + proto.MESSAGE, + number=3, + optional=True, + message=content.Content, + ) + contents: MutableSequence[content.Content] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=content.Content, + ) + tools: MutableSequence[content.Tool] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=content.Tool, + ) + tool_config: content.ToolConfig = proto.Field( + proto.MESSAGE, + number=6, + optional=True, + message=content.ToolConfig, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=8, + message=timestamp_pb2.Timestamp, + ) + usage_metadata: UsageMetadata = proto.Field( + proto.MESSAGE, + number=12, + message=UsageMetadata, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/types/citation.py b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/types/citation.py new file mode 100644 index 0000000000000000000000000000000000000000..837bd3f4b2ea7562d2a2be18f011b68b1906f4ed --- /dev/null +++ b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/types/citation.py @@ -0,0 +1,101 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.ai.generativelanguage.v1alpha", + manifest={ + "CitationMetadata", + "CitationSource", + }, +) + + +class CitationMetadata(proto.Message): + r"""A collection of source attributions for a piece of content. + + Attributes: + citation_sources (MutableSequence[google.ai.generativelanguage_v1alpha.types.CitationSource]): + Citations to sources for a specific response. + """ + + citation_sources: MutableSequence["CitationSource"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="CitationSource", + ) + + +class CitationSource(proto.Message): + r"""A citation to a source for a portion of a specific response. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + start_index (int): + Optional. Start of segment of the response + that is attributed to this source. + + Index indicates the start of the segment, + measured in bytes. + + This field is a member of `oneof`_ ``_start_index``. + end_index (int): + Optional. End of the attributed segment, + exclusive. + + This field is a member of `oneof`_ ``_end_index``. + uri (str): + Optional. URI that is attributed as a source + for a portion of the text. + + This field is a member of `oneof`_ ``_uri``. + license_ (str): + Optional. License for the GitHub project that + is attributed as a source for segment. + + License info is required for code citations. + + This field is a member of `oneof`_ ``_license``. + """ + + start_index: int = proto.Field( + proto.INT32, + number=1, + optional=True, + ) + end_index: int = proto.Field( + proto.INT32, + number=2, + optional=True, + ) + uri: str = proto.Field( + proto.STRING, + number=3, + optional=True, + ) + license_: str = proto.Field( + proto.STRING, + number=4, + optional=True, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/types/discuss_service.py b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/types/discuss_service.py new file mode 100644 index 0000000000000000000000000000000000000000..2ce5d18dc6b16a37fd52df939df60e51b2c41a30 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/types/discuss_service.py @@ -0,0 +1,356 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.ai.generativelanguage_v1alpha.types import citation, safety + +__protobuf__ = proto.module( + package="google.ai.generativelanguage.v1alpha", + manifest={ + "GenerateMessageRequest", + "GenerateMessageResponse", + "Message", + "MessagePrompt", + "Example", + "CountMessageTokensRequest", + "CountMessageTokensResponse", + }, +) + + +class GenerateMessageRequest(proto.Message): + r"""Request to generate a message response from the model. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + model (str): + Required. The name of the model to use. + + Format: ``name=models/{model}``. + prompt (google.ai.generativelanguage_v1alpha.types.MessagePrompt): + Required. The structured textual input given + to the model as a prompt. + Given a + prompt, the model will return what it predicts + is the next message in the discussion. + temperature (float): + Optional. Controls the randomness of the output. + + Values can range over ``[0.0,1.0]``, inclusive. A value + closer to ``1.0`` will produce responses that are more + varied, while a value closer to ``0.0`` will typically + result in less surprising responses from the model. + + This field is a member of `oneof`_ ``_temperature``. + candidate_count (int): + Optional. The number of generated response messages to + return. + + This value must be between ``[1, 8]``, inclusive. If unset, + this will default to ``1``. + + This field is a member of `oneof`_ ``_candidate_count``. + top_p (float): + Optional. The maximum cumulative probability of tokens to + consider when sampling. + + The model uses combined Top-k and nucleus sampling. + + Nucleus sampling considers the smallest set of tokens whose + probability sum is at least ``top_p``. + + This field is a member of `oneof`_ ``_top_p``. + top_k (int): + Optional. The maximum number of tokens to consider when + sampling. + + The model uses combined Top-k and nucleus sampling. + + Top-k sampling considers the set of ``top_k`` most probable + tokens. + + This field is a member of `oneof`_ ``_top_k``. + """ + + model: str = proto.Field( + proto.STRING, + number=1, + ) + prompt: "MessagePrompt" = proto.Field( + proto.MESSAGE, + number=2, + message="MessagePrompt", + ) + temperature: float = proto.Field( + proto.FLOAT, + number=3, + optional=True, + ) + candidate_count: int = proto.Field( + proto.INT32, + number=4, + optional=True, + ) + top_p: float = proto.Field( + proto.FLOAT, + number=5, + optional=True, + ) + top_k: int = proto.Field( + proto.INT32, + number=6, + optional=True, + ) + + +class GenerateMessageResponse(proto.Message): + r"""The response from the model. + + This includes candidate messages and + conversation history in the form of chronologically-ordered + messages. + + Attributes: + candidates (MutableSequence[google.ai.generativelanguage_v1alpha.types.Message]): + Candidate response messages from the model. + messages (MutableSequence[google.ai.generativelanguage_v1alpha.types.Message]): + The conversation history used by the model. + filters (MutableSequence[google.ai.generativelanguage_v1alpha.types.ContentFilter]): + A set of content filtering metadata for the prompt and + response text. + + This indicates which ``SafetyCategory``\ (s) blocked a + candidate from this response, the lowest ``HarmProbability`` + that triggered a block, and the HarmThreshold setting for + that category. + """ + + candidates: MutableSequence["Message"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Message", + ) + messages: MutableSequence["Message"] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="Message", + ) + filters: MutableSequence[safety.ContentFilter] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=safety.ContentFilter, + ) + + +class Message(proto.Message): + r"""The base unit of structured text. + + A ``Message`` includes an ``author`` and the ``content`` of the + ``Message``. + + The ``author`` is used to tag messages when they are fed to the + model as text. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + author (str): + Optional. The author of this Message. + + This serves as a key for tagging + the content of this Message when it is fed to + the model as text. + + The author can be any alphanumeric string. + content (str): + Required. The text content of the structured ``Message``. + citation_metadata (google.ai.generativelanguage_v1alpha.types.CitationMetadata): + Output only. Citation information for model-generated + ``content`` in this ``Message``. + + If this ``Message`` was generated as output from the model, + this field may be populated with attribution information for + any text included in the ``content``. This field is used + only on output. + + This field is a member of `oneof`_ ``_citation_metadata``. + """ + + author: str = proto.Field( + proto.STRING, + number=1, + ) + content: str = proto.Field( + proto.STRING, + number=2, + ) + citation_metadata: citation.CitationMetadata = proto.Field( + proto.MESSAGE, + number=3, + optional=True, + message=citation.CitationMetadata, + ) + + +class MessagePrompt(proto.Message): + r"""All of the structured input text passed to the model as a prompt. + + A ``MessagePrompt`` contains a structured set of fields that provide + context for the conversation, examples of user input/model output + message pairs that prime the model to respond in different ways, and + the conversation history or list of messages representing the + alternating turns of the conversation between the user and the + model. + + Attributes: + context (str): + Optional. Text that should be provided to the model first to + ground the response. + + If not empty, this ``context`` will be given to the model + first before the ``examples`` and ``messages``. When using a + ``context`` be sure to provide it with every request to + maintain continuity. + + This field can be a description of your prompt to the model + to help provide context and guide the responses. Examples: + "Translate the phrase from English to French." or "Given a + statement, classify the sentiment as happy, sad or neutral." + + Anything included in this field will take precedence over + message history if the total input size exceeds the model's + ``input_token_limit`` and the input request is truncated. + examples (MutableSequence[google.ai.generativelanguage_v1alpha.types.Example]): + Optional. Examples of what the model should generate. + + This includes both user input and the response that the + model should emulate. + + These ``examples`` are treated identically to conversation + messages except that they take precedence over the history + in ``messages``: If the total input size exceeds the model's + ``input_token_limit`` the input will be truncated. Items + will be dropped from ``messages`` before ``examples``. + messages (MutableSequence[google.ai.generativelanguage_v1alpha.types.Message]): + Required. A snapshot of the recent conversation history + sorted chronologically. + + Turns alternate between two authors. + + If the total input size exceeds the model's + ``input_token_limit`` the input will be truncated: The + oldest items will be dropped from ``messages``. + """ + + context: str = proto.Field( + proto.STRING, + number=1, + ) + examples: MutableSequence["Example"] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="Example", + ) + messages: MutableSequence["Message"] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message="Message", + ) + + +class Example(proto.Message): + r"""An input/output example used to instruct the Model. + + It demonstrates how the model should respond or format its + response. + + Attributes: + input (google.ai.generativelanguage_v1alpha.types.Message): + Required. An example of an input ``Message`` from the user. + output (google.ai.generativelanguage_v1alpha.types.Message): + Required. An example of what the model should + output given the input. + """ + + input: "Message" = proto.Field( + proto.MESSAGE, + number=1, + message="Message", + ) + output: "Message" = proto.Field( + proto.MESSAGE, + number=2, + message="Message", + ) + + +class CountMessageTokensRequest(proto.Message): + r"""Counts the number of tokens in the ``prompt`` sent to a model. + + Models may tokenize text differently, so each model may return a + different ``token_count``. + + Attributes: + model (str): + Required. The model's resource name. This serves as an ID + for the Model to use. + + This name should match a model name returned by the + ``ListModels`` method. + + Format: ``models/{model}`` + prompt (google.ai.generativelanguage_v1alpha.types.MessagePrompt): + Required. The prompt, whose token count is to + be returned. + """ + + model: str = proto.Field( + proto.STRING, + number=1, + ) + prompt: "MessagePrompt" = proto.Field( + proto.MESSAGE, + number=2, + message="MessagePrompt", + ) + + +class CountMessageTokensResponse(proto.Message): + r"""A response from ``CountMessageTokens``. + + It returns the model's ``token_count`` for the ``prompt``. + + Attributes: + token_count (int): + The number of tokens that the ``model`` tokenizes the + ``prompt`` into. + + Always non-negative. + """ + + token_count: int = proto.Field( + proto.INT32, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/types/file.py b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/types/file.py new file mode 100644 index 0000000000000000000000000000000000000000..8a3fdac30930f3fb1ef9c469364ce2515ce851c3 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/types/file.py @@ -0,0 +1,174 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.ai.generativelanguage.v1alpha", + manifest={ + "File", + "VideoMetadata", + }, +) + + +class File(proto.Message): + r"""A file uploaded to the API. + Next ID: 15 + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + video_metadata (google.ai.generativelanguage_v1alpha.types.VideoMetadata): + Output only. Metadata for a video. + + This field is a member of `oneof`_ ``metadata``. + name (str): + Immutable. Identifier. The ``File`` resource name. The ID + (name excluding the "files/" prefix) can contain up to 40 + characters that are lowercase alphanumeric or dashes (-). + The ID cannot start or end with a dash. If the name is empty + on create, a unique name will be generated. Example: + ``files/123-456`` + display_name (str): + Optional. The human-readable display name for the ``File``. + The display name must be no more than 512 characters in + length, including spaces. Example: "Welcome Image". + mime_type (str): + Output only. MIME type of the file. + size_bytes (int): + Output only. Size of the file in bytes. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The timestamp of when the ``File`` was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The timestamp of when the ``File`` was last + updated. + expiration_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The timestamp of when the ``File`` will be + deleted. Only set if the ``File`` is scheduled to expire. + sha256_hash (bytes): + Output only. SHA-256 hash of the uploaded + bytes. + uri (str): + Output only. The uri of the ``File``. + state (google.ai.generativelanguage_v1alpha.types.File.State): + Output only. Processing state of the File. + error (google.rpc.status_pb2.Status): + Output only. Error status if File processing + failed. + """ + + class State(proto.Enum): + r"""States for the lifecycle of a File. + + Values: + STATE_UNSPECIFIED (0): + The default value. This value is used if the + state is omitted. + PROCESSING (1): + File is being processed and cannot be used + for inference yet. + ACTIVE (2): + File is processed and available for + inference. + FAILED (10): + File failed processing. + """ + STATE_UNSPECIFIED = 0 + PROCESSING = 1 + ACTIVE = 2 + FAILED = 10 + + video_metadata: "VideoMetadata" = proto.Field( + proto.MESSAGE, + number=12, + oneof="metadata", + message="VideoMetadata", + ) + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + mime_type: str = proto.Field( + proto.STRING, + number=3, + ) + size_bytes: int = proto.Field( + proto.INT64, + number=4, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + expiration_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + sha256_hash: bytes = proto.Field( + proto.BYTES, + number=8, + ) + uri: str = proto.Field( + proto.STRING, + number=9, + ) + state: State = proto.Field( + proto.ENUM, + number=10, + enum=State, + ) + error: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=11, + message=status_pb2.Status, + ) + + +class VideoMetadata(proto.Message): + r"""Metadata for a video ``File``. + + Attributes: + video_duration (google.protobuf.duration_pb2.Duration): + Duration of the video. + """ + + video_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=1, + message=duration_pb2.Duration, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/types/file_service.py b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/types/file_service.py new file mode 100644 index 0000000000000000000000000000000000000000..6398c075f2d303cd9c8d5674a1abc87cc8ea4c41 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/types/file_service.py @@ -0,0 +1,145 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.ai.generativelanguage_v1alpha.types import file as gag_file + +__protobuf__ = proto.module( + package="google.ai.generativelanguage.v1alpha", + manifest={ + "CreateFileRequest", + "CreateFileResponse", + "ListFilesRequest", + "ListFilesResponse", + "GetFileRequest", + "DeleteFileRequest", + }, +) + + +class CreateFileRequest(proto.Message): + r"""Request for ``CreateFile``. + + Attributes: + file (google.ai.generativelanguage_v1alpha.types.File): + Optional. Metadata for the file to create. + """ + + file: gag_file.File = proto.Field( + proto.MESSAGE, + number=1, + message=gag_file.File, + ) + + +class CreateFileResponse(proto.Message): + r"""Response for ``CreateFile``. + + Attributes: + file (google.ai.generativelanguage_v1alpha.types.File): + Metadata for the created file. + """ + + file: gag_file.File = proto.Field( + proto.MESSAGE, + number=1, + message=gag_file.File, + ) + + +class ListFilesRequest(proto.Message): + r"""Request for ``ListFiles``. + + Attributes: + page_size (int): + Optional. Maximum number of ``File``\ s to return per page. + If unspecified, defaults to 10. Maximum ``page_size`` is + 100. + page_token (str): + Optional. A page token from a previous ``ListFiles`` call. + """ + + page_size: int = proto.Field( + proto.INT32, + number=1, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListFilesResponse(proto.Message): + r"""Response for ``ListFiles``. + + Attributes: + files (MutableSequence[google.ai.generativelanguage_v1alpha.types.File]): + The list of ``File``\ s. + next_page_token (str): + A token that can be sent as a ``page_token`` into a + subsequent ``ListFiles`` call. + """ + + @property + def raw_page(self): + return self + + files: MutableSequence[gag_file.File] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gag_file.File, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetFileRequest(proto.Message): + r"""Request for ``GetFile``. + + Attributes: + name (str): + Required. The name of the ``File`` to get. Example: + ``files/abc-123`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class DeleteFileRequest(proto.Message): + r"""Request for ``DeleteFile``. + + Attributes: + name (str): + Required. The name of the ``File`` to delete. Example: + ``files/abc-123`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/types/generative_service.py b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/types/generative_service.py new file mode 100644 index 0000000000000000000000000000000000000000..c1088ab1682c6d287daf3130f5fa812f12519614 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/types/generative_service.py @@ -0,0 +1,2139 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.ai.generativelanguage_v1alpha.types import citation +from google.ai.generativelanguage_v1alpha.types import content as gag_content +from google.ai.generativelanguage_v1alpha.types import retriever, safety + +__protobuf__ = proto.module( + package="google.ai.generativelanguage.v1alpha", + manifest={ + "TaskType", + "GenerateContentRequest", + "PrebuiltVoiceConfig", + "VoiceConfig", + "SpeechConfig", + "GenerationConfig", + "SemanticRetrieverConfig", + "GenerateContentResponse", + "Candidate", + "LogprobsResult", + "AttributionSourceId", + "GroundingAttribution", + "RetrievalMetadata", + "GroundingMetadata", + "SearchEntryPoint", + "GroundingChunk", + "Segment", + "GroundingSupport", + "GenerateAnswerRequest", + "GenerateAnswerResponse", + "EmbedContentRequest", + "ContentEmbedding", + "EmbedContentResponse", + "BatchEmbedContentsRequest", + "BatchEmbedContentsResponse", + "CountTokensRequest", + "CountTokensResponse", + "BidiGenerateContentSetup", + "BidiGenerateContentClientContent", + "BidiGenerateContentRealtimeInput", + "BidiGenerateContentToolResponse", + "BidiGenerateContentClientMessage", + "BidiGenerateContentSetupComplete", + "BidiGenerateContentServerContent", + "BidiGenerateContentToolCall", + "BidiGenerateContentToolCallCancellation", + "BidiGenerateContentServerMessage", + }, +) + + +class TaskType(proto.Enum): + r"""Type of task for which the embedding will be used. + + Values: + TASK_TYPE_UNSPECIFIED (0): + Unset value, which will default to one of the + other enum values. + RETRIEVAL_QUERY (1): + Specifies the given text is a query in a + search/retrieval setting. + RETRIEVAL_DOCUMENT (2): + Specifies the given text is a document from + the corpus being searched. + SEMANTIC_SIMILARITY (3): + Specifies the given text will be used for + STS. + CLASSIFICATION (4): + Specifies that the given text will be + classified. + CLUSTERING (5): + Specifies that the embeddings will be used + for clustering. + QUESTION_ANSWERING (6): + Specifies that the given text will be used + for question answering. + FACT_VERIFICATION (7): + Specifies that the given text will be used + for fact verification. + """ + TASK_TYPE_UNSPECIFIED = 0 + RETRIEVAL_QUERY = 1 + RETRIEVAL_DOCUMENT = 2 + SEMANTIC_SIMILARITY = 3 + CLASSIFICATION = 4 + CLUSTERING = 5 + QUESTION_ANSWERING = 6 + FACT_VERIFICATION = 7 + + +class GenerateContentRequest(proto.Message): + r"""Request to generate a completion from the model. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + model (str): + Required. The name of the ``Model`` to use for generating + the completion. + + Format: ``models/{model}``. + system_instruction (google.ai.generativelanguage_v1alpha.types.Content): + Optional. Developer set `system + instruction(s) `__. + Currently, text only. + + This field is a member of `oneof`_ ``_system_instruction``. + contents (MutableSequence[google.ai.generativelanguage_v1alpha.types.Content]): + Required. The content of the current conversation with the + model. + + For single-turn queries, this is a single instance. For + multi-turn queries like + `chat `__, + this is a repeated field that contains the conversation + history and the latest request. + tools (MutableSequence[google.ai.generativelanguage_v1alpha.types.Tool]): + Optional. A list of ``Tools`` the ``Model`` may use to + generate the next response. + + A ``Tool`` is a piece of code that enables the system to + interact with external systems to perform an action, or set + of actions, outside of knowledge and scope of the ``Model``. + Supported ``Tool``\ s are ``Function`` and + ``code_execution``. Refer to the `Function + calling `__ + and the `Code + execution `__ + guides to learn more. + tool_config (google.ai.generativelanguage_v1alpha.types.ToolConfig): + Optional. Tool configuration for any ``Tool`` specified in + the request. Refer to the `Function calling + guide `__ + for a usage example. + safety_settings (MutableSequence[google.ai.generativelanguage_v1alpha.types.SafetySetting]): + Optional. A list of unique ``SafetySetting`` instances for + blocking unsafe content. + + This will be enforced on the + ``GenerateContentRequest.contents`` and + ``GenerateContentResponse.candidates``. There should not be + more than one setting for each ``SafetyCategory`` type. The + API will block any contents and responses that fail to meet + the thresholds set by these settings. This list overrides + the default settings for each ``SafetyCategory`` specified + in the safety_settings. If there is no ``SafetySetting`` for + a given ``SafetyCategory`` provided in the list, the API + will use the default safety setting for that category. Harm + categories HARM_CATEGORY_HATE_SPEECH, + HARM_CATEGORY_SEXUALLY_EXPLICIT, + HARM_CATEGORY_DANGEROUS_CONTENT, HARM_CATEGORY_HARASSMENT, + HARM_CATEGORY_CIVIC_INTEGRITY are supported. Refer to the + `guide `__ + for detailed information on available safety settings. Also + refer to the `Safety + guidance `__ + to learn how to incorporate safety considerations in your AI + applications. + generation_config (google.ai.generativelanguage_v1alpha.types.GenerationConfig): + Optional. Configuration options for model + generation and outputs. + + This field is a member of `oneof`_ ``_generation_config``. + cached_content (str): + Optional. The name of the content + `cached `__ + to use as context to serve the prediction. Format: + ``cachedContents/{cachedContent}`` + + This field is a member of `oneof`_ ``_cached_content``. + """ + + model: str = proto.Field( + proto.STRING, + number=1, + ) + system_instruction: gag_content.Content = proto.Field( + proto.MESSAGE, + number=8, + optional=True, + message=gag_content.Content, + ) + contents: MutableSequence[gag_content.Content] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=gag_content.Content, + ) + tools: MutableSequence[gag_content.Tool] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=gag_content.Tool, + ) + tool_config: gag_content.ToolConfig = proto.Field( + proto.MESSAGE, + number=7, + message=gag_content.ToolConfig, + ) + safety_settings: MutableSequence[safety.SafetySetting] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=safety.SafetySetting, + ) + generation_config: "GenerationConfig" = proto.Field( + proto.MESSAGE, + number=4, + optional=True, + message="GenerationConfig", + ) + cached_content: str = proto.Field( + proto.STRING, + number=9, + optional=True, + ) + + +class PrebuiltVoiceConfig(proto.Message): + r"""The configuration for the prebuilt speaker to use. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + voice_name (str): + The name of the preset voice to use. + + This field is a member of `oneof`_ ``_voice_name``. + """ + + voice_name: str = proto.Field( + proto.STRING, + number=1, + optional=True, + ) + + +class VoiceConfig(proto.Message): + r"""The configuration for the voice to use. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + prebuilt_voice_config (google.ai.generativelanguage_v1alpha.types.PrebuiltVoiceConfig): + The configuration for the prebuilt voice to + use. + + This field is a member of `oneof`_ ``voice_config``. + """ + + prebuilt_voice_config: "PrebuiltVoiceConfig" = proto.Field( + proto.MESSAGE, + number=1, + oneof="voice_config", + message="PrebuiltVoiceConfig", + ) + + +class SpeechConfig(proto.Message): + r"""The speech generation config. + + Attributes: + voice_config (google.ai.generativelanguage_v1alpha.types.VoiceConfig): + The configuration for the speaker to use. + """ + + voice_config: "VoiceConfig" = proto.Field( + proto.MESSAGE, + number=1, + message="VoiceConfig", + ) + + +class GenerationConfig(proto.Message): + r"""Configuration options for model generation and outputs. Not + all parameters are configurable for every model. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + candidate_count (int): + Optional. Number of generated responses to + return. + Currently, this value can only be set to 1. If + unset, this will default to 1. + + This field is a member of `oneof`_ ``_candidate_count``. + stop_sequences (MutableSequence[str]): + Optional. The set of character sequences (up to 5) that will + stop output generation. If specified, the API will stop at + the first appearance of a ``stop_sequence``. The stop + sequence will not be included as part of the response. + max_output_tokens (int): + Optional. The maximum number of tokens to include in a + response candidate. + + Note: The default value varies by model, see the + ``Model.output_token_limit`` attribute of the ``Model`` + returned from the ``getModel`` function. + + This field is a member of `oneof`_ ``_max_output_tokens``. + temperature (float): + Optional. Controls the randomness of the output. + + Note: The default value varies by model, see the + ``Model.temperature`` attribute of the ``Model`` returned + from the ``getModel`` function. + + Values can range from [0.0, 2.0]. + + This field is a member of `oneof`_ ``_temperature``. + top_p (float): + Optional. The maximum cumulative probability of tokens to + consider when sampling. + + The model uses combined Top-k and Top-p (nucleus) sampling. + + Tokens are sorted based on their assigned probabilities so + that only the most likely tokens are considered. Top-k + sampling directly limits the maximum number of tokens to + consider, while Nucleus sampling limits the number of tokens + based on the cumulative probability. + + Note: The default value varies by ``Model`` and is specified + by the\ ``Model.top_p`` attribute returned from the + ``getModel`` function. An empty ``top_k`` attribute + indicates that the model doesn't apply top-k sampling and + doesn't allow setting ``top_k`` on requests. + + This field is a member of `oneof`_ ``_top_p``. + top_k (int): + Optional. The maximum number of tokens to consider when + sampling. + + Gemini models use Top-p (nucleus) sampling or a combination + of Top-k and nucleus sampling. Top-k sampling considers the + set of ``top_k`` most probable tokens. Models running with + nucleus sampling don't allow top_k setting. + + Note: The default value varies by ``Model`` and is specified + by the\ ``Model.top_p`` attribute returned from the + ``getModel`` function. An empty ``top_k`` attribute + indicates that the model doesn't apply top-k sampling and + doesn't allow setting ``top_k`` on requests. + + This field is a member of `oneof`_ ``_top_k``. + response_mime_type (str): + Optional. MIME type of the generated candidate text. + Supported MIME types are: ``text/plain``: (default) Text + output. ``application/json``: JSON response in the response + candidates. ``text/x.enum``: ENUM as a string response in + the response candidates. Refer to the + `docs `__ + for a list of all supported text MIME types. + response_schema (google.ai.generativelanguage_v1alpha.types.Schema): + Optional. Output schema of the generated candidate text. + Schemas must be a subset of the `OpenAPI + schema `__ and + can be objects, primitives or arrays. + + If set, a compatible ``response_mime_type`` must also be + set. Compatible MIME types: ``application/json``: Schema for + JSON response. Refer to the `JSON text generation + guide `__ + for more details. + presence_penalty (float): + Optional. Presence penalty applied to the next token's + logprobs if the token has already been seen in the response. + + This penalty is binary on/off and not dependant on the + number of times the token is used (after the first). Use + [frequency_penalty][google.ai.generativelanguage.v1alpha.GenerationConfig.frequency_penalty] + for a penalty that increases with each use. + + A positive penalty will discourage the use of tokens that + have already been used in the response, increasing the + vocabulary. + + A negative penalty will encourage the use of tokens that + have already been used in the response, decreasing the + vocabulary. + + This field is a member of `oneof`_ ``_presence_penalty``. + frequency_penalty (float): + Optional. Frequency penalty applied to the next token's + logprobs, multiplied by the number of times each token has + been seen in the respponse so far. + + A positive penalty will discourage the use of tokens that + have already been used, proportional to the number of times + the token has been used: The more a token is used, the more + dificult it is for the model to use that token again + increasing the vocabulary of responses. + + Caution: A *negative* penalty will encourage the model to + reuse tokens proportional to the number of times the token + has been used. Small negative values will reduce the + vocabulary of a response. Larger negative values will cause + the model to start repeating a common token until it hits + the + [max_output_tokens][google.ai.generativelanguage.v1alpha.GenerationConfig.max_output_tokens] + limit. + + This field is a member of `oneof`_ ``_frequency_penalty``. + response_logprobs (bool): + Optional. If true, export the logprobs + results in response. + + This field is a member of `oneof`_ ``_response_logprobs``. + logprobs (int): + Optional. Only valid if + [response_logprobs=True][google.ai.generativelanguage.v1alpha.GenerationConfig.response_logprobs]. + This sets the number of top logprobs to return at each + decoding step in the + [Candidate.logprobs_result][google.ai.generativelanguage.v1alpha.Candidate.logprobs_result]. + + This field is a member of `oneof`_ ``_logprobs``. + enable_enhanced_civic_answers (bool): + Optional. Enables enhanced civic answers. It + may not be available for all models. + + This field is a member of `oneof`_ ``_enable_enhanced_civic_answers``. + response_modalities (MutableSequence[google.ai.generativelanguage_v1alpha.types.GenerationConfig.Modality]): + Optional. The requested modalities of the + response. Represents the set of modalities that + the model can return, and should be expected in + the response. This is an exact match to the + modalities of the response. + + A model may have multiple combinations of + supported modalities. If the requested + modalities do not match any of the supported + combinations, an error will be returned. + + An empty list is equivalent to requesting only + text. + speech_config (google.ai.generativelanguage_v1alpha.types.SpeechConfig): + Optional. The speech generation config. + + This field is a member of `oneof`_ ``_speech_config``. + """ + + class Modality(proto.Enum): + r"""Supported modalities of the response. + + Values: + MODALITY_UNSPECIFIED (0): + Default value. + TEXT (1): + Indicates the model should return text. + IMAGE (2): + Indicates the model should return images. + AUDIO (3): + Indicates the model should return audio. + """ + MODALITY_UNSPECIFIED = 0 + TEXT = 1 + IMAGE = 2 + AUDIO = 3 + + candidate_count: int = proto.Field( + proto.INT32, + number=1, + optional=True, + ) + stop_sequences: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + max_output_tokens: int = proto.Field( + proto.INT32, + number=4, + optional=True, + ) + temperature: float = proto.Field( + proto.FLOAT, + number=5, + optional=True, + ) + top_p: float = proto.Field( + proto.FLOAT, + number=6, + optional=True, + ) + top_k: int = proto.Field( + proto.INT32, + number=7, + optional=True, + ) + response_mime_type: str = proto.Field( + proto.STRING, + number=13, + ) + response_schema: gag_content.Schema = proto.Field( + proto.MESSAGE, + number=14, + message=gag_content.Schema, + ) + presence_penalty: float = proto.Field( + proto.FLOAT, + number=15, + optional=True, + ) + frequency_penalty: float = proto.Field( + proto.FLOAT, + number=16, + optional=True, + ) + response_logprobs: bool = proto.Field( + proto.BOOL, + number=17, + optional=True, + ) + logprobs: int = proto.Field( + proto.INT32, + number=18, + optional=True, + ) + enable_enhanced_civic_answers: bool = proto.Field( + proto.BOOL, + number=19, + optional=True, + ) + response_modalities: MutableSequence[Modality] = proto.RepeatedField( + proto.ENUM, + number=20, + enum=Modality, + ) + speech_config: "SpeechConfig" = proto.Field( + proto.MESSAGE, + number=21, + optional=True, + message="SpeechConfig", + ) + + +class SemanticRetrieverConfig(proto.Message): + r"""Configuration for retrieving grounding content from a ``Corpus`` or + ``Document`` created using the Semantic Retriever API. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + source (str): + Required. Name of the resource for retrieval. Example: + ``corpora/123`` or ``corpora/123/documents/abc``. + query (google.ai.generativelanguage_v1alpha.types.Content): + Required. Query to use for matching ``Chunk``\ s in the + given resource by similarity. + metadata_filters (MutableSequence[google.ai.generativelanguage_v1alpha.types.MetadataFilter]): + Optional. Filters for selecting ``Document``\ s and/or + ``Chunk``\ s from the resource. + max_chunks_count (int): + Optional. Maximum number of relevant ``Chunk``\ s to + retrieve. + + This field is a member of `oneof`_ ``_max_chunks_count``. + minimum_relevance_score (float): + Optional. Minimum relevance score for retrieved relevant + ``Chunk``\ s. + + This field is a member of `oneof`_ ``_minimum_relevance_score``. + """ + + source: str = proto.Field( + proto.STRING, + number=1, + ) + query: gag_content.Content = proto.Field( + proto.MESSAGE, + number=2, + message=gag_content.Content, + ) + metadata_filters: MutableSequence[retriever.MetadataFilter] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=retriever.MetadataFilter, + ) + max_chunks_count: int = proto.Field( + proto.INT32, + number=4, + optional=True, + ) + minimum_relevance_score: float = proto.Field( + proto.FLOAT, + number=5, + optional=True, + ) + + +class GenerateContentResponse(proto.Message): + r"""Response from the model supporting multiple candidate responses. + + Safety ratings and content filtering are reported for both prompt in + ``GenerateContentResponse.prompt_feedback`` and for each candidate + in ``finish_reason`` and in ``safety_ratings``. The API: + + - Returns either all requested candidates or none of them + - Returns no candidates at all only if there was something wrong + with the prompt (check ``prompt_feedback``) + - Reports feedback on each candidate in ``finish_reason`` and + ``safety_ratings``. + + Attributes: + candidates (MutableSequence[google.ai.generativelanguage_v1alpha.types.Candidate]): + Candidate responses from the model. + prompt_feedback (google.ai.generativelanguage_v1alpha.types.GenerateContentResponse.PromptFeedback): + Returns the prompt's feedback related to the + content filters. + usage_metadata (google.ai.generativelanguage_v1alpha.types.GenerateContentResponse.UsageMetadata): + Output only. Metadata on the generation + requests' token usage. + model_version (str): + Output only. The model version used to + generate the response. + """ + + class PromptFeedback(proto.Message): + r"""A set of the feedback metadata the prompt specified in + ``GenerateContentRequest.content``. + + Attributes: + block_reason (google.ai.generativelanguage_v1alpha.types.GenerateContentResponse.PromptFeedback.BlockReason): + Optional. If set, the prompt was blocked and + no candidates are returned. Rephrase the prompt. + safety_ratings (MutableSequence[google.ai.generativelanguage_v1alpha.types.SafetyRating]): + Ratings for safety of the prompt. + There is at most one rating per category. + """ + + class BlockReason(proto.Enum): + r"""Specifies the reason why the prompt was blocked. + + Values: + BLOCK_REASON_UNSPECIFIED (0): + Default value. This value is unused. + SAFETY (1): + Prompt was blocked due to safety reasons. Inspect + ``safety_ratings`` to understand which safety category + blocked it. + OTHER (2): + Prompt was blocked due to unknown reasons. + BLOCKLIST (3): + Prompt was blocked due to the terms which are + included from the terminology blocklist. + PROHIBITED_CONTENT (4): + Prompt was blocked due to prohibited content. + IMAGE_SAFETY (5): + Candidates blocked due to unsafe image + generation content. + """ + BLOCK_REASON_UNSPECIFIED = 0 + SAFETY = 1 + OTHER = 2 + BLOCKLIST = 3 + PROHIBITED_CONTENT = 4 + IMAGE_SAFETY = 5 + + block_reason: "GenerateContentResponse.PromptFeedback.BlockReason" = ( + proto.Field( + proto.ENUM, + number=1, + enum="GenerateContentResponse.PromptFeedback.BlockReason", + ) + ) + safety_ratings: MutableSequence[safety.SafetyRating] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=safety.SafetyRating, + ) + + class UsageMetadata(proto.Message): + r"""Metadata on the generation request's token usage. + + Attributes: + prompt_token_count (int): + Number of tokens in the prompt. When ``cached_content`` is + set, this is still the total effective prompt size meaning + this includes the number of tokens in the cached content. + cached_content_token_count (int): + Number of tokens in the cached part of the + prompt (the cached content) + candidates_token_count (int): + Total number of tokens across all the + generated response candidates. + total_token_count (int): + Total token count for the generation request + (prompt + response candidates). + """ + + prompt_token_count: int = proto.Field( + proto.INT32, + number=1, + ) + cached_content_token_count: int = proto.Field( + proto.INT32, + number=4, + ) + candidates_token_count: int = proto.Field( + proto.INT32, + number=2, + ) + total_token_count: int = proto.Field( + proto.INT32, + number=3, + ) + + candidates: MutableSequence["Candidate"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Candidate", + ) + prompt_feedback: PromptFeedback = proto.Field( + proto.MESSAGE, + number=2, + message=PromptFeedback, + ) + usage_metadata: UsageMetadata = proto.Field( + proto.MESSAGE, + number=3, + message=UsageMetadata, + ) + model_version: str = proto.Field( + proto.STRING, + number=4, + ) + + +class Candidate(proto.Message): + r"""A response candidate generated from the model. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + index (int): + Output only. Index of the candidate in the + list of response candidates. + + This field is a member of `oneof`_ ``_index``. + content (google.ai.generativelanguage_v1alpha.types.Content): + Output only. Generated content returned from + the model. + finish_reason (google.ai.generativelanguage_v1alpha.types.Candidate.FinishReason): + Optional. Output only. The reason why the + model stopped generating tokens. + If empty, the model has not stopped generating + tokens. + safety_ratings (MutableSequence[google.ai.generativelanguage_v1alpha.types.SafetyRating]): + List of ratings for the safety of a response + candidate. + There is at most one rating per category. + citation_metadata (google.ai.generativelanguage_v1alpha.types.CitationMetadata): + Output only. Citation information for model-generated + candidate. + + This field may be populated with recitation information for + any text included in the ``content``. These are passages + that are "recited" from copyrighted material in the + foundational LLM's training data. + token_count (int): + Output only. Token count for this candidate. + grounding_attributions (MutableSequence[google.ai.generativelanguage_v1alpha.types.GroundingAttribution]): + Output only. Attribution information for sources that + contributed to a grounded answer. + + This field is populated for ``GenerateAnswer`` calls. + grounding_metadata (google.ai.generativelanguage_v1alpha.types.GroundingMetadata): + Output only. Grounding metadata for the candidate. + + This field is populated for ``GenerateContent`` calls. + avg_logprobs (float): + Output only. Average log probability score of + the candidate. + logprobs_result (google.ai.generativelanguage_v1alpha.types.LogprobsResult): + Output only. Log-likelihood scores for the + response tokens and top tokens + """ + + class FinishReason(proto.Enum): + r"""Defines the reason why the model stopped generating tokens. + + Values: + FINISH_REASON_UNSPECIFIED (0): + Default value. This value is unused. + STOP (1): + Natural stop point of the model or provided + stop sequence. + MAX_TOKENS (2): + The maximum number of tokens as specified in + the request was reached. + SAFETY (3): + The response candidate content was flagged + for safety reasons. + RECITATION (4): + The response candidate content was flagged + for recitation reasons. + LANGUAGE (6): + The response candidate content was flagged + for using an unsupported language. + OTHER (5): + Unknown reason. + BLOCKLIST (7): + Token generation stopped because the content + contains forbidden terms. + PROHIBITED_CONTENT (8): + Token generation stopped for potentially + containing prohibited content. + SPII (9): + Token generation stopped because the content + potentially contains Sensitive Personally + Identifiable Information (SPII). + MALFORMED_FUNCTION_CALL (10): + The function call generated by the model is + invalid. + IMAGE_SAFETY (11): + Token generation stopped because generated + images contain safety violations. + """ + FINISH_REASON_UNSPECIFIED = 0 + STOP = 1 + MAX_TOKENS = 2 + SAFETY = 3 + RECITATION = 4 + LANGUAGE = 6 + OTHER = 5 + BLOCKLIST = 7 + PROHIBITED_CONTENT = 8 + SPII = 9 + MALFORMED_FUNCTION_CALL = 10 + IMAGE_SAFETY = 11 + + index: int = proto.Field( + proto.INT32, + number=3, + optional=True, + ) + content: gag_content.Content = proto.Field( + proto.MESSAGE, + number=1, + message=gag_content.Content, + ) + finish_reason: FinishReason = proto.Field( + proto.ENUM, + number=2, + enum=FinishReason, + ) + safety_ratings: MutableSequence[safety.SafetyRating] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=safety.SafetyRating, + ) + citation_metadata: citation.CitationMetadata = proto.Field( + proto.MESSAGE, + number=6, + message=citation.CitationMetadata, + ) + token_count: int = proto.Field( + proto.INT32, + number=7, + ) + grounding_attributions: MutableSequence[ + "GroundingAttribution" + ] = proto.RepeatedField( + proto.MESSAGE, + number=8, + message="GroundingAttribution", + ) + grounding_metadata: "GroundingMetadata" = proto.Field( + proto.MESSAGE, + number=9, + message="GroundingMetadata", + ) + avg_logprobs: float = proto.Field( + proto.DOUBLE, + number=10, + ) + logprobs_result: "LogprobsResult" = proto.Field( + proto.MESSAGE, + number=11, + message="LogprobsResult", + ) + + +class LogprobsResult(proto.Message): + r"""Logprobs Result + + Attributes: + top_candidates (MutableSequence[google.ai.generativelanguage_v1alpha.types.LogprobsResult.TopCandidates]): + Length = total number of decoding steps. + chosen_candidates (MutableSequence[google.ai.generativelanguage_v1alpha.types.LogprobsResult.Candidate]): + Length = total number of decoding steps. The chosen + candidates may or may not be in top_candidates. + """ + + class Candidate(proto.Message): + r"""Candidate for the logprobs token and score. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + token (str): + The candidate’s token string value. + + This field is a member of `oneof`_ ``_token``. + token_id (int): + The candidate’s token id value. + + This field is a member of `oneof`_ ``_token_id``. + log_probability (float): + The candidate's log probability. + + This field is a member of `oneof`_ ``_log_probability``. + """ + + token: str = proto.Field( + proto.STRING, + number=1, + optional=True, + ) + token_id: int = proto.Field( + proto.INT32, + number=3, + optional=True, + ) + log_probability: float = proto.Field( + proto.FLOAT, + number=2, + optional=True, + ) + + class TopCandidates(proto.Message): + r"""Candidates with top log probabilities at each decoding step. + + Attributes: + candidates (MutableSequence[google.ai.generativelanguage_v1alpha.types.LogprobsResult.Candidate]): + Sorted by log probability in descending + order. + """ + + candidates: MutableSequence["LogprobsResult.Candidate"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="LogprobsResult.Candidate", + ) + + top_candidates: MutableSequence[TopCandidates] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=TopCandidates, + ) + chosen_candidates: MutableSequence[Candidate] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=Candidate, + ) + + +class AttributionSourceId(proto.Message): + r"""Identifier for the source contributing to this attribution. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + grounding_passage (google.ai.generativelanguage_v1alpha.types.AttributionSourceId.GroundingPassageId): + Identifier for an inline passage. + + This field is a member of `oneof`_ ``source``. + semantic_retriever_chunk (google.ai.generativelanguage_v1alpha.types.AttributionSourceId.SemanticRetrieverChunk): + Identifier for a ``Chunk`` fetched via Semantic Retriever. + + This field is a member of `oneof`_ ``source``. + """ + + class GroundingPassageId(proto.Message): + r"""Identifier for a part within a ``GroundingPassage``. + + Attributes: + passage_id (str): + Output only. ID of the passage matching the + ``GenerateAnswerRequest``'s ``GroundingPassage.id``. + part_index (int): + Output only. Index of the part within the + ``GenerateAnswerRequest``'s ``GroundingPassage.content``. + """ + + passage_id: str = proto.Field( + proto.STRING, + number=1, + ) + part_index: int = proto.Field( + proto.INT32, + number=2, + ) + + class SemanticRetrieverChunk(proto.Message): + r"""Identifier for a ``Chunk`` retrieved via Semantic Retriever + specified in the ``GenerateAnswerRequest`` using + ``SemanticRetrieverConfig``. + + Attributes: + source (str): + Output only. Name of the source matching the request's + ``SemanticRetrieverConfig.source``. Example: ``corpora/123`` + or ``corpora/123/documents/abc`` + chunk (str): + Output only. Name of the ``Chunk`` containing the attributed + text. Example: ``corpora/123/documents/abc/chunks/xyz`` + """ + + source: str = proto.Field( + proto.STRING, + number=1, + ) + chunk: str = proto.Field( + proto.STRING, + number=2, + ) + + grounding_passage: GroundingPassageId = proto.Field( + proto.MESSAGE, + number=1, + oneof="source", + message=GroundingPassageId, + ) + semantic_retriever_chunk: SemanticRetrieverChunk = proto.Field( + proto.MESSAGE, + number=2, + oneof="source", + message=SemanticRetrieverChunk, + ) + + +class GroundingAttribution(proto.Message): + r"""Attribution for a source that contributed to an answer. + + Attributes: + source_id (google.ai.generativelanguage_v1alpha.types.AttributionSourceId): + Output only. Identifier for the source + contributing to this attribution. + content (google.ai.generativelanguage_v1alpha.types.Content): + Grounding source content that makes up this + attribution. + """ + + source_id: "AttributionSourceId" = proto.Field( + proto.MESSAGE, + number=3, + message="AttributionSourceId", + ) + content: gag_content.Content = proto.Field( + proto.MESSAGE, + number=2, + message=gag_content.Content, + ) + + +class RetrievalMetadata(proto.Message): + r"""Metadata related to retrieval in the grounding flow. + + Attributes: + google_search_dynamic_retrieval_score (float): + Optional. Score indicating how likely information from + google search could help answer the prompt. The score is in + the range [0, 1], where 0 is the least likely and 1 is the + most likely. This score is only populated when google search + grounding and dynamic retrieval is enabled. It will be + compared to the threshold to determine whether to trigger + google search. + """ + + google_search_dynamic_retrieval_score: float = proto.Field( + proto.FLOAT, + number=2, + ) + + +class GroundingMetadata(proto.Message): + r"""Metadata returned to client when grounding is enabled. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + search_entry_point (google.ai.generativelanguage_v1alpha.types.SearchEntryPoint): + Optional. Google search entry for the + following-up web searches. + + This field is a member of `oneof`_ ``_search_entry_point``. + grounding_chunks (MutableSequence[google.ai.generativelanguage_v1alpha.types.GroundingChunk]): + List of supporting references retrieved from + specified grounding source. + grounding_supports (MutableSequence[google.ai.generativelanguage_v1alpha.types.GroundingSupport]): + List of grounding support. + retrieval_metadata (google.ai.generativelanguage_v1alpha.types.RetrievalMetadata): + Metadata related to retrieval in the + grounding flow. + + This field is a member of `oneof`_ ``_retrieval_metadata``. + web_search_queries (MutableSequence[str]): + Web search queries for the following-up web + search. + """ + + search_entry_point: "SearchEntryPoint" = proto.Field( + proto.MESSAGE, + number=1, + optional=True, + message="SearchEntryPoint", + ) + grounding_chunks: MutableSequence["GroundingChunk"] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="GroundingChunk", + ) + grounding_supports: MutableSequence["GroundingSupport"] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message="GroundingSupport", + ) + retrieval_metadata: "RetrievalMetadata" = proto.Field( + proto.MESSAGE, + number=4, + optional=True, + message="RetrievalMetadata", + ) + web_search_queries: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=5, + ) + + +class SearchEntryPoint(proto.Message): + r"""Google search entry point. + + Attributes: + rendered_content (str): + Optional. Web content snippet that can be + embedded in a web page or an app webview. + sdk_blob (bytes): + Optional. Base64 encoded JSON representing + array of tuple. + """ + + rendered_content: str = proto.Field( + proto.STRING, + number=1, + ) + sdk_blob: bytes = proto.Field( + proto.BYTES, + number=2, + ) + + +class GroundingChunk(proto.Message): + r"""Grounding chunk. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + web (google.ai.generativelanguage_v1alpha.types.GroundingChunk.Web): + Grounding chunk from the web. + + This field is a member of `oneof`_ ``chunk_type``. + """ + + class Web(proto.Message): + r"""Chunk from the web. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + uri (str): + URI reference of the chunk. + + This field is a member of `oneof`_ ``_uri``. + title (str): + Title of the chunk. + + This field is a member of `oneof`_ ``_title``. + """ + + uri: str = proto.Field( + proto.STRING, + number=1, + optional=True, + ) + title: str = proto.Field( + proto.STRING, + number=2, + optional=True, + ) + + web: Web = proto.Field( + proto.MESSAGE, + number=1, + oneof="chunk_type", + message=Web, + ) + + +class Segment(proto.Message): + r"""Segment of the content. + + Attributes: + part_index (int): + Output only. The index of a Part object + within its parent Content object. + start_index (int): + Output only. Start index in the given Part, + measured in bytes. Offset from the start of the + Part, inclusive, starting at zero. + end_index (int): + Output only. End index in the given Part, + measured in bytes. Offset from the start of the + Part, exclusive, starting at zero. + text (str): + Output only. The text corresponding to the + segment from the response. + """ + + part_index: int = proto.Field( + proto.INT32, + number=1, + ) + start_index: int = proto.Field( + proto.INT32, + number=2, + ) + end_index: int = proto.Field( + proto.INT32, + number=3, + ) + text: str = proto.Field( + proto.STRING, + number=4, + ) + + +class GroundingSupport(proto.Message): + r"""Grounding support. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + segment (google.ai.generativelanguage_v1alpha.types.Segment): + Segment of the content this support belongs + to. + + This field is a member of `oneof`_ ``_segment``. + grounding_chunk_indices (MutableSequence[int]): + A list of indices (into 'grounding_chunk') specifying the + citations associated with the claim. For instance [1,3,4] + means that grounding_chunk[1], grounding_chunk[3], + grounding_chunk[4] are the retrieved content attributed to + the claim. + confidence_scores (MutableSequence[float]): + Confidence score of the support references. Ranges from 0 to + 1. 1 is the most confident. This list must have the same + size as the grounding_chunk_indices. + """ + + segment: "Segment" = proto.Field( + proto.MESSAGE, + number=1, + optional=True, + message="Segment", + ) + grounding_chunk_indices: MutableSequence[int] = proto.RepeatedField( + proto.INT32, + number=2, + ) + confidence_scores: MutableSequence[float] = proto.RepeatedField( + proto.FLOAT, + number=3, + ) + + +class GenerateAnswerRequest(proto.Message): + r"""Request to generate a grounded answer from the ``Model``. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + inline_passages (google.ai.generativelanguage_v1alpha.types.GroundingPassages): + Passages provided inline with the request. + + This field is a member of `oneof`_ ``grounding_source``. + semantic_retriever (google.ai.generativelanguage_v1alpha.types.SemanticRetrieverConfig): + Content retrieved from resources created via + the Semantic Retriever API. + + This field is a member of `oneof`_ ``grounding_source``. + model (str): + Required. The name of the ``Model`` to use for generating + the grounded response. + + Format: ``model=models/{model}``. + contents (MutableSequence[google.ai.generativelanguage_v1alpha.types.Content]): + Required. The content of the current conversation with the + ``Model``. For single-turn queries, this is a single + question to answer. For multi-turn queries, this is a + repeated field that contains conversation history and the + last ``Content`` in the list containing the question. + + Note: ``GenerateAnswer`` only supports queries in English. + answer_style (google.ai.generativelanguage_v1alpha.types.GenerateAnswerRequest.AnswerStyle): + Required. Style in which answers should be + returned. + safety_settings (MutableSequence[google.ai.generativelanguage_v1alpha.types.SafetySetting]): + Optional. A list of unique ``SafetySetting`` instances for + blocking unsafe content. + + This will be enforced on the + ``GenerateAnswerRequest.contents`` and + ``GenerateAnswerResponse.candidate``. There should not be + more than one setting for each ``SafetyCategory`` type. The + API will block any contents and responses that fail to meet + the thresholds set by these settings. This list overrides + the default settings for each ``SafetyCategory`` specified + in the safety_settings. If there is no ``SafetySetting`` for + a given ``SafetyCategory`` provided in the list, the API + will use the default safety setting for that category. Harm + categories HARM_CATEGORY_HATE_SPEECH, + HARM_CATEGORY_SEXUALLY_EXPLICIT, + HARM_CATEGORY_DANGEROUS_CONTENT, HARM_CATEGORY_HARASSMENT + are supported. Refer to the + `guide `__ + for detailed information on available safety settings. Also + refer to the `Safety + guidance `__ + to learn how to incorporate safety considerations in your AI + applications. + temperature (float): + Optional. Controls the randomness of the output. + + Values can range from [0.0,1.0], inclusive. A value closer + to 1.0 will produce responses that are more varied and + creative, while a value closer to 0.0 will typically result + in more straightforward responses from the model. A low + temperature (~0.2) is usually recommended for + Attributed-Question-Answering use cases. + + This field is a member of `oneof`_ ``_temperature``. + """ + + class AnswerStyle(proto.Enum): + r"""Style for grounded answers. + + Values: + ANSWER_STYLE_UNSPECIFIED (0): + Unspecified answer style. + ABSTRACTIVE (1): + Succint but abstract style. + EXTRACTIVE (2): + Very brief and extractive style. + VERBOSE (3): + Verbose style including extra details. The + response may be formatted as a sentence, + paragraph, multiple paragraphs, or bullet + points, etc. + """ + ANSWER_STYLE_UNSPECIFIED = 0 + ABSTRACTIVE = 1 + EXTRACTIVE = 2 + VERBOSE = 3 + + inline_passages: gag_content.GroundingPassages = proto.Field( + proto.MESSAGE, + number=6, + oneof="grounding_source", + message=gag_content.GroundingPassages, + ) + semantic_retriever: "SemanticRetrieverConfig" = proto.Field( + proto.MESSAGE, + number=7, + oneof="grounding_source", + message="SemanticRetrieverConfig", + ) + model: str = proto.Field( + proto.STRING, + number=1, + ) + contents: MutableSequence[gag_content.Content] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=gag_content.Content, + ) + answer_style: AnswerStyle = proto.Field( + proto.ENUM, + number=5, + enum=AnswerStyle, + ) + safety_settings: MutableSequence[safety.SafetySetting] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=safety.SafetySetting, + ) + temperature: float = proto.Field( + proto.FLOAT, + number=4, + optional=True, + ) + + +class GenerateAnswerResponse(proto.Message): + r"""Response from the model for a grounded answer. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + answer (google.ai.generativelanguage_v1alpha.types.Candidate): + Candidate answer from the model. + + Note: The model *always* attempts to provide a grounded + answer, even when the answer is unlikely to be answerable + from the given passages. In that case, a low-quality or + ungrounded answer may be provided, along with a low + ``answerable_probability``. + answerable_probability (float): + Output only. The model's estimate of the probability that + its answer is correct and grounded in the input passages. + + A low ``answerable_probability`` indicates that the answer + might not be grounded in the sources. + + When ``answerable_probability`` is low, you may want to: + + - Display a message to the effect of "We couldn’t answer + that question" to the user. + - Fall back to a general-purpose LLM that answers the + question from world knowledge. The threshold and nature + of such fallbacks will depend on individual use cases. + ``0.5`` is a good starting threshold. + + This field is a member of `oneof`_ ``_answerable_probability``. + input_feedback (google.ai.generativelanguage_v1alpha.types.GenerateAnswerResponse.InputFeedback): + Output only. Feedback related to the input data used to + answer the question, as opposed to the model-generated + response to the question. + + The input data can be one or more of the following: + + - Question specified by the last entry in + ``GenerateAnswerRequest.content`` + - Conversation history specified by the other entries in + ``GenerateAnswerRequest.content`` + - Grounding sources + (``GenerateAnswerRequest.semantic_retriever`` or + ``GenerateAnswerRequest.inline_passages``) + + This field is a member of `oneof`_ ``_input_feedback``. + """ + + class InputFeedback(proto.Message): + r"""Feedback related to the input data used to answer the + question, as opposed to the model-generated response to the + question. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + block_reason (google.ai.generativelanguage_v1alpha.types.GenerateAnswerResponse.InputFeedback.BlockReason): + Optional. If set, the input was blocked and + no candidates are returned. Rephrase the input. + + This field is a member of `oneof`_ ``_block_reason``. + safety_ratings (MutableSequence[google.ai.generativelanguage_v1alpha.types.SafetyRating]): + Ratings for safety of the input. + There is at most one rating per category. + """ + + class BlockReason(proto.Enum): + r"""Specifies what was the reason why input was blocked. + + Values: + BLOCK_REASON_UNSPECIFIED (0): + Default value. This value is unused. + SAFETY (1): + Input was blocked due to safety reasons. Inspect + ``safety_ratings`` to understand which safety category + blocked it. + OTHER (2): + Input was blocked due to other reasons. + """ + BLOCK_REASON_UNSPECIFIED = 0 + SAFETY = 1 + OTHER = 2 + + block_reason: "GenerateAnswerResponse.InputFeedback.BlockReason" = proto.Field( + proto.ENUM, + number=1, + optional=True, + enum="GenerateAnswerResponse.InputFeedback.BlockReason", + ) + safety_ratings: MutableSequence[safety.SafetyRating] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=safety.SafetyRating, + ) + + answer: "Candidate" = proto.Field( + proto.MESSAGE, + number=1, + message="Candidate", + ) + answerable_probability: float = proto.Field( + proto.FLOAT, + number=2, + optional=True, + ) + input_feedback: InputFeedback = proto.Field( + proto.MESSAGE, + number=3, + optional=True, + message=InputFeedback, + ) + + +class EmbedContentRequest(proto.Message): + r"""Request containing the ``Content`` for the model to embed. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + model (str): + Required. The model's resource name. This serves as an ID + for the Model to use. + + This name should match a model name returned by the + ``ListModels`` method. + + Format: ``models/{model}`` + content (google.ai.generativelanguage_v1alpha.types.Content): + Required. The content to embed. Only the ``parts.text`` + fields will be counted. + task_type (google.ai.generativelanguage_v1alpha.types.TaskType): + Optional. Optional task type for which the embeddings will + be used. Can only be set for ``models/embedding-001``. + + This field is a member of `oneof`_ ``_task_type``. + title (str): + Optional. An optional title for the text. Only applicable + when TaskType is ``RETRIEVAL_DOCUMENT``. + + Note: Specifying a ``title`` for ``RETRIEVAL_DOCUMENT`` + provides better quality embeddings for retrieval. + + This field is a member of `oneof`_ ``_title``. + output_dimensionality (int): + Optional. Optional reduced dimension for the output + embedding. If set, excessive values in the output embedding + are truncated from the end. Supported by newer models since + 2024 only. You cannot set this value if using the earlier + model (``models/embedding-001``). + + This field is a member of `oneof`_ ``_output_dimensionality``. + """ + + model: str = proto.Field( + proto.STRING, + number=1, + ) + content: gag_content.Content = proto.Field( + proto.MESSAGE, + number=2, + message=gag_content.Content, + ) + task_type: "TaskType" = proto.Field( + proto.ENUM, + number=3, + optional=True, + enum="TaskType", + ) + title: str = proto.Field( + proto.STRING, + number=4, + optional=True, + ) + output_dimensionality: int = proto.Field( + proto.INT32, + number=5, + optional=True, + ) + + +class ContentEmbedding(proto.Message): + r"""A list of floats representing an embedding. + + Attributes: + values (MutableSequence[float]): + The embedding values. + """ + + values: MutableSequence[float] = proto.RepeatedField( + proto.FLOAT, + number=1, + ) + + +class EmbedContentResponse(proto.Message): + r"""The response to an ``EmbedContentRequest``. + + Attributes: + embedding (google.ai.generativelanguage_v1alpha.types.ContentEmbedding): + Output only. The embedding generated from the + input content. + """ + + embedding: "ContentEmbedding" = proto.Field( + proto.MESSAGE, + number=1, + message="ContentEmbedding", + ) + + +class BatchEmbedContentsRequest(proto.Message): + r"""Batch request to get embeddings from the model for a list of + prompts. + + Attributes: + model (str): + Required. The model's resource name. This serves as an ID + for the Model to use. + + This name should match a model name returned by the + ``ListModels`` method. + + Format: ``models/{model}`` + requests (MutableSequence[google.ai.generativelanguage_v1alpha.types.EmbedContentRequest]): + Required. Embed requests for the batch. The model in each of + these requests must match the model specified + ``BatchEmbedContentsRequest.model``. + """ + + model: str = proto.Field( + proto.STRING, + number=1, + ) + requests: MutableSequence["EmbedContentRequest"] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="EmbedContentRequest", + ) + + +class BatchEmbedContentsResponse(proto.Message): + r"""The response to a ``BatchEmbedContentsRequest``. + + Attributes: + embeddings (MutableSequence[google.ai.generativelanguage_v1alpha.types.ContentEmbedding]): + Output only. The embeddings for each request, + in the same order as provided in the batch + request. + """ + + embeddings: MutableSequence["ContentEmbedding"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="ContentEmbedding", + ) + + +class CountTokensRequest(proto.Message): + r"""Counts the number of tokens in the ``prompt`` sent to a model. + + Models may tokenize text differently, so each model may return a + different ``token_count``. + + Attributes: + model (str): + Required. The model's resource name. This serves as an ID + for the Model to use. + + This name should match a model name returned by the + ``ListModels`` method. + + Format: ``models/{model}`` + contents (MutableSequence[google.ai.generativelanguage_v1alpha.types.Content]): + Optional. The input given to the model as a prompt. This + field is ignored when ``generate_content_request`` is set. + generate_content_request (google.ai.generativelanguage_v1alpha.types.GenerateContentRequest): + Optional. The overall input given to the ``Model``. This + includes the prompt as well as other model steering + information like `system + instructions `__, + and/or function declarations for `function + calling `__. + ``Model``\ s/\ ``Content``\ s and + ``generate_content_request``\ s are mutually exclusive. You + can either send ``Model`` + ``Content``\ s or a + ``generate_content_request``, but never both. + """ + + model: str = proto.Field( + proto.STRING, + number=1, + ) + contents: MutableSequence[gag_content.Content] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=gag_content.Content, + ) + generate_content_request: "GenerateContentRequest" = proto.Field( + proto.MESSAGE, + number=3, + message="GenerateContentRequest", + ) + + +class CountTokensResponse(proto.Message): + r"""A response from ``CountTokens``. + + It returns the model's ``token_count`` for the ``prompt``. + + Attributes: + total_tokens (int): + The number of tokens that the ``Model`` tokenizes the + ``prompt`` into. Always non-negative. + cached_content_token_count (int): + Number of tokens in the cached part of the + prompt (the cached content). + """ + + total_tokens: int = proto.Field( + proto.INT32, + number=1, + ) + cached_content_token_count: int = proto.Field( + proto.INT32, + number=5, + ) + + +class BidiGenerateContentSetup(proto.Message): + r"""Message to be sent in the first and only first + ``BidiGenerateContentClientMessage``. Contains configuration that + will apply for the duration of the streaming RPC. + + Clients should wait for a ``BidiGenerateContentSetupComplete`` + message before sending any additional messages. + + Attributes: + model (str): + Required. The model's resource name. This serves as an ID + for the Model to use. + + Format: ``models/{model}`` + generation_config (google.ai.generativelanguage_v1alpha.types.GenerationConfig): + Optional. Generation config. + + The following fields are not supported: + + - ``response_logprobs`` + - ``response_mime_type`` + - ``logprobs`` + - ``response_schema`` + - ``stop_sequence`` + - ``routing_config`` + - ``audio_timestamp`` + system_instruction (google.ai.generativelanguage_v1alpha.types.Content): + Optional. The user provided system + instructions for the model. + Note: Only text should be used in parts and + content in each part will be in a separate + paragraph. + tools (MutableSequence[google.ai.generativelanguage_v1alpha.types.Tool]): + Optional. A list of ``Tools`` the model may use to generate + the next response. + + A ``Tool`` is a piece of code that enables the system to + interact with external systems to perform an action, or set + of actions, outside of knowledge and scope of the model. + """ + + model: str = proto.Field( + proto.STRING, + number=1, + ) + generation_config: "GenerationConfig" = proto.Field( + proto.MESSAGE, + number=2, + message="GenerationConfig", + ) + system_instruction: gag_content.Content = proto.Field( + proto.MESSAGE, + number=3, + message=gag_content.Content, + ) + tools: MutableSequence[gag_content.Tool] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=gag_content.Tool, + ) + + +class BidiGenerateContentClientContent(proto.Message): + r"""Incremental update of the current conversation delivered from + the client. All of the content here is unconditionally appended + to the conversation history and used as part of the prompt to + the model to generate content. + + A message here will interrupt any current model generation. + + Attributes: + turns (MutableSequence[google.ai.generativelanguage_v1alpha.types.Content]): + Optional. The content appended to the current + conversation with the model. + For single-turn queries, this is a single + instance. For multi-turn queries, this is a + repeated field that contains conversation + history and the latest request. + turn_complete (bool): + Optional. If true, indicates that the server + content generation should start with the + currently accumulated prompt. Otherwise, the + server awaits additional messages before + starting generation. + """ + + turns: MutableSequence[gag_content.Content] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gag_content.Content, + ) + turn_complete: bool = proto.Field( + proto.BOOL, + number=2, + ) + + +class BidiGenerateContentRealtimeInput(proto.Message): + r"""User input that is sent in real time. + + This is different from + [BidiGenerateContentClientContent][google.ai.generativelanguage.v1alpha.BidiGenerateContentClientContent] + in a few ways: + + - Can be sent continuously without interruption to model + generation. + - If there is a need to mix data interleaved across the + [BidiGenerateContentClientContent][google.ai.generativelanguage.v1alpha.BidiGenerateContentClientContent] + and the + [BidiGenerateContentRealtimeInput][google.ai.generativelanguage.v1alpha.BidiGenerateContentRealtimeInput], + the server attempts to optimize for best response, but there are + no guarantees. + - End of turn is not explicitly specified, but is rather derived + from user activity (for example, end of speech). + - Even before the end of turn, the data is processed incrementally + to optimize for a fast start of the response from the model. + - Is always direct user input that is sent in real time. Can be + sent continuously without interruptions. The model automatically + detects the beginning and the end of user speech and starts or + terminates streaming the response accordingly. Data is processed + incrementally as it arrives, minimizing latency. + + Attributes: + media_chunks (MutableSequence[google.ai.generativelanguage_v1alpha.types.Blob]): + Optional. Inlined bytes data for media input. + """ + + media_chunks: MutableSequence[gag_content.Blob] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gag_content.Blob, + ) + + +class BidiGenerateContentToolResponse(proto.Message): + r"""Client generated response to a ``ToolCall`` received from the + server. Individual ``FunctionResponse`` objects are matched to the + respective ``FunctionCall`` objects by the ``id`` field. + + Note that in the unary and server-streaming GenerateContent APIs + function calling happens by exchanging the ``Content`` parts, while + in the bidi GenerateContent APIs function calling happens over these + dedicated set of messages. + + Attributes: + function_responses (MutableSequence[google.ai.generativelanguage_v1alpha.types.FunctionResponse]): + Optional. The response to the function calls. + """ + + function_responses: MutableSequence[ + gag_content.FunctionResponse + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gag_content.FunctionResponse, + ) + + +class BidiGenerateContentClientMessage(proto.Message): + r"""Messages sent by the client in the BidiGenerateContent call. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + setup (google.ai.generativelanguage_v1alpha.types.BidiGenerateContentSetup): + Optional. Session configuration sent in the + first and only first client message. + + This field is a member of `oneof`_ ``message_type``. + client_content (google.ai.generativelanguage_v1alpha.types.BidiGenerateContentClientContent): + Optional. Incremental update of the current + conversation delivered from the client. + + This field is a member of `oneof`_ ``message_type``. + realtime_input (google.ai.generativelanguage_v1alpha.types.BidiGenerateContentRealtimeInput): + Optional. User input that is sent in real + time. + + This field is a member of `oneof`_ ``message_type``. + tool_response (google.ai.generativelanguage_v1alpha.types.BidiGenerateContentToolResponse): + Optional. Response to a ``ToolCallMessage`` received from + the server. + + This field is a member of `oneof`_ ``message_type``. + """ + + setup: "BidiGenerateContentSetup" = proto.Field( + proto.MESSAGE, + number=1, + oneof="message_type", + message="BidiGenerateContentSetup", + ) + client_content: "BidiGenerateContentClientContent" = proto.Field( + proto.MESSAGE, + number=2, + oneof="message_type", + message="BidiGenerateContentClientContent", + ) + realtime_input: "BidiGenerateContentRealtimeInput" = proto.Field( + proto.MESSAGE, + number=3, + oneof="message_type", + message="BidiGenerateContentRealtimeInput", + ) + tool_response: "BidiGenerateContentToolResponse" = proto.Field( + proto.MESSAGE, + number=4, + oneof="message_type", + message="BidiGenerateContentToolResponse", + ) + + +class BidiGenerateContentSetupComplete(proto.Message): + r"""Sent in response to a ``BidiGenerateContentSetup`` message from the + client. + + """ + + +class BidiGenerateContentServerContent(proto.Message): + r"""Incremental server update generated by the model in response + to client messages. + + Content is generated as quickly as possible, and not in real + time. Clients may choose to buffer and play it out in real time. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + model_turn (google.ai.generativelanguage_v1alpha.types.Content): + Output only. The content that the model has + generated as part of the current conversation + with the user. + + This field is a member of `oneof`_ ``_model_turn``. + turn_complete (bool): + Output only. If true, indicates that the model is done + generating. Generation will only start in response to + additional client messages. Can be set alongside + ``content``, indicating that the ``content`` is the last in + the turn. + interrupted (bool): + Output only. If true, indicates that a client + message has interrupted current model + generation. If the client is playing out the + content in real time, this is a good signal to + stop and empty the current playback queue. + grounding_metadata (google.ai.generativelanguage_v1alpha.types.GroundingMetadata): + Output only. Grounding metadata for the + generated content. + """ + + model_turn: gag_content.Content = proto.Field( + proto.MESSAGE, + number=1, + optional=True, + message=gag_content.Content, + ) + turn_complete: bool = proto.Field( + proto.BOOL, + number=2, + ) + interrupted: bool = proto.Field( + proto.BOOL, + number=3, + ) + grounding_metadata: "GroundingMetadata" = proto.Field( + proto.MESSAGE, + number=4, + message="GroundingMetadata", + ) + + +class BidiGenerateContentToolCall(proto.Message): + r"""Request for the client to execute the ``function_calls`` and return + the responses with the matching ``id``\ s. + + Attributes: + function_calls (MutableSequence[google.ai.generativelanguage_v1alpha.types.FunctionCall]): + Output only. The function call to be + executed. + """ + + function_calls: MutableSequence[gag_content.FunctionCall] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=gag_content.FunctionCall, + ) + + +class BidiGenerateContentToolCallCancellation(proto.Message): + r"""Notification for the client that a previously issued + ``ToolCallMessage`` with the specified ``id``\ s should have been + not executed and should be cancelled. If there were side-effects to + those tool calls, clients may attempt to undo the tool calls. This + message occurs only in cases where the clients interrupt server + turns. + + Attributes: + ids (MutableSequence[str]): + Output only. The ids of the tool calls to be + cancelled. + """ + + ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + + +class BidiGenerateContentServerMessage(proto.Message): + r"""Response message for the BidiGenerateContent call. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + setup_complete (google.ai.generativelanguage_v1alpha.types.BidiGenerateContentSetupComplete): + Output only. Sent in response to a + ``BidiGenerateContentSetup`` message from the client when + setup is complete. + + This field is a member of `oneof`_ ``message_type``. + server_content (google.ai.generativelanguage_v1alpha.types.BidiGenerateContentServerContent): + Output only. Content generated by the model + in response to client messages. + + This field is a member of `oneof`_ ``message_type``. + tool_call (google.ai.generativelanguage_v1alpha.types.BidiGenerateContentToolCall): + Output only. Request for the client to execute the + ``function_calls`` and return the responses with the + matching ``id``\ s. + + This field is a member of `oneof`_ ``message_type``. + tool_call_cancellation (google.ai.generativelanguage_v1alpha.types.BidiGenerateContentToolCallCancellation): + Output only. Notification for the client that a previously + issued ``ToolCallMessage`` with the specified ``id``\ s + should be cancelled. + + This field is a member of `oneof`_ ``message_type``. + """ + + setup_complete: "BidiGenerateContentSetupComplete" = proto.Field( + proto.MESSAGE, + number=2, + oneof="message_type", + message="BidiGenerateContentSetupComplete", + ) + server_content: "BidiGenerateContentServerContent" = proto.Field( + proto.MESSAGE, + number=3, + oneof="message_type", + message="BidiGenerateContentServerContent", + ) + tool_call: "BidiGenerateContentToolCall" = proto.Field( + proto.MESSAGE, + number=4, + oneof="message_type", + message="BidiGenerateContentToolCall", + ) + tool_call_cancellation: "BidiGenerateContentToolCallCancellation" = proto.Field( + proto.MESSAGE, + number=5, + oneof="message_type", + message="BidiGenerateContentToolCallCancellation", + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/types/permission.py b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/types/permission.py new file mode 100644 index 0000000000000000000000000000000000000000..a73758c6c688d0ee02b5907b7b6d1e182df652f3 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/types/permission.py @@ -0,0 +1,141 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.ai.generativelanguage.v1alpha", + manifest={ + "Permission", + }, +) + + +class Permission(proto.Message): + r"""Permission resource grants user, group or the rest of the + world access to the PaLM API resource (e.g. a tuned model, + corpus). + + A role is a collection of permitted operations that allows users + to perform specific actions on PaLM API resources. To make them + available to users, groups, or service accounts, you assign + roles. When you assign a role, you grant permissions that the + role contains. + + There are three concentric roles. Each role is a superset of the + previous role's permitted operations: + + - reader can use the resource (e.g. tuned model, corpus) for + inference + - writer has reader's permissions and additionally can edit and + share + - owner has writer's permissions and additionally can delete + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Output only. Identifier. The permission name. A unique name + will be generated on create. Examples: + tunedModels/{tuned_model}/permissions/{permission} + corpora/{corpus}/permissions/{permission} Output only. + grantee_type (google.ai.generativelanguage_v1alpha.types.Permission.GranteeType): + Optional. Immutable. The type of the grantee. + + This field is a member of `oneof`_ ``_grantee_type``. + email_address (str): + Optional. Immutable. The email address of the + user of group which this permission refers. + Field is not set when permission's grantee type + is EVERYONE. + + This field is a member of `oneof`_ ``_email_address``. + role (google.ai.generativelanguage_v1alpha.types.Permission.Role): + Required. The role granted by this + permission. + + This field is a member of `oneof`_ ``_role``. + """ + + class GranteeType(proto.Enum): + r"""Defines types of the grantee of this permission. + + Values: + GRANTEE_TYPE_UNSPECIFIED (0): + The default value. This value is unused. + USER (1): + Represents a user. When set, you must provide email_address + for the user. + GROUP (2): + Represents a group. When set, you must provide email_address + for the group. + EVERYONE (3): + Represents access to everyone. No extra + information is required. + """ + GRANTEE_TYPE_UNSPECIFIED = 0 + USER = 1 + GROUP = 2 + EVERYONE = 3 + + class Role(proto.Enum): + r"""Defines the role granted by this permission. + + Values: + ROLE_UNSPECIFIED (0): + The default value. This value is unused. + OWNER (1): + Owner can use, update, share and delete the + resource. + WRITER (2): + Writer can use, update and share the + resource. + READER (3): + Reader can use the resource. + """ + ROLE_UNSPECIFIED = 0 + OWNER = 1 + WRITER = 2 + READER = 3 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + grantee_type: GranteeType = proto.Field( + proto.ENUM, + number=2, + optional=True, + enum=GranteeType, + ) + email_address: str = proto.Field( + proto.STRING, + number=3, + optional=True, + ) + role: Role = proto.Field( + proto.ENUM, + number=4, + optional=True, + enum=Role, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/types/permission_service.py b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/types/permission_service.py new file mode 100644 index 0000000000000000000000000000000000000000..1e64faf3fe0dc8652b84471cc6e99782dd8f8926 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/types/permission_service.py @@ -0,0 +1,220 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +from google.protobuf import field_mask_pb2 # type: ignore +import proto # type: ignore + +from google.ai.generativelanguage_v1alpha.types import permission as gag_permission + +__protobuf__ = proto.module( + package="google.ai.generativelanguage.v1alpha", + manifest={ + "CreatePermissionRequest", + "GetPermissionRequest", + "ListPermissionsRequest", + "ListPermissionsResponse", + "UpdatePermissionRequest", + "DeletePermissionRequest", + "TransferOwnershipRequest", + "TransferOwnershipResponse", + }, +) + + +class CreatePermissionRequest(proto.Message): + r"""Request to create a ``Permission``. + + Attributes: + parent (str): + Required. The parent resource of the ``Permission``. + Formats: ``tunedModels/{tuned_model}`` ``corpora/{corpus}`` + permission (google.ai.generativelanguage_v1alpha.types.Permission): + Required. The permission to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + permission: gag_permission.Permission = proto.Field( + proto.MESSAGE, + number=2, + message=gag_permission.Permission, + ) + + +class GetPermissionRequest(proto.Message): + r"""Request for getting information about a specific ``Permission``. + + Attributes: + name (str): + Required. The resource name of the permission. + + Formats: + ``tunedModels/{tuned_model}/permissions/{permission}`` + ``corpora/{corpus}/permissions/{permission}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListPermissionsRequest(proto.Message): + r"""Request for listing permissions. + + Attributes: + parent (str): + Required. The parent resource of the permissions. Formats: + ``tunedModels/{tuned_model}`` ``corpora/{corpus}`` + page_size (int): + Optional. The maximum number of ``Permission``\ s to return + (per page). The service may return fewer permissions. + + If unspecified, at most 10 permissions will be returned. + This method returns at most 1000 permissions per page, even + if you pass larger page_size. + page_token (str): + Optional. A page token, received from a previous + ``ListPermissions`` call. + + Provide the ``page_token`` returned by one request as an + argument to the next request to retrieve the next page. + + When paginating, all other parameters provided to + ``ListPermissions`` must match the call that provided the + page token. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListPermissionsResponse(proto.Message): + r"""Response from ``ListPermissions`` containing a paginated list of + permissions. + + Attributes: + permissions (MutableSequence[google.ai.generativelanguage_v1alpha.types.Permission]): + Returned permissions. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. + + If this field is omitted, there are no more pages. + """ + + @property + def raw_page(self): + return self + + permissions: MutableSequence[gag_permission.Permission] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gag_permission.Permission, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class UpdatePermissionRequest(proto.Message): + r"""Request to update the ``Permission``. + + Attributes: + permission (google.ai.generativelanguage_v1alpha.types.Permission): + Required. The permission to update. + + The permission's ``name`` field is used to identify the + permission to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to update. Accepted ones: + + - role (``Permission.role`` field) + """ + + permission: gag_permission.Permission = proto.Field( + proto.MESSAGE, + number=1, + message=gag_permission.Permission, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeletePermissionRequest(proto.Message): + r"""Request to delete the ``Permission``. + + Attributes: + name (str): + Required. The resource name of the permission. Formats: + ``tunedModels/{tuned_model}/permissions/{permission}`` + ``corpora/{corpus}/permissions/{permission}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class TransferOwnershipRequest(proto.Message): + r"""Request to transfer the ownership of the tuned model. + + Attributes: + name (str): + Required. The resource name of the tuned model to transfer + ownership. + + Format: ``tunedModels/my-model-id`` + email_address (str): + Required. The email address of the user to + whom the tuned model is being transferred to. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + email_address: str = proto.Field( + proto.STRING, + number=2, + ) + + +class TransferOwnershipResponse(proto.Message): + r"""Response from ``TransferOwnership``.""" + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/types/safety.py b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/types/safety.py new file mode 100644 index 0000000000000000000000000000000000000000..3fbad41feeff9529613e1c8095f9124bfc27804e --- /dev/null +++ b/.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/types/safety.py @@ -0,0 +1,276 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.ai.generativelanguage.v1alpha", + manifest={ + "HarmCategory", + "ContentFilter", + "SafetyFeedback", + "SafetyRating", + "SafetySetting", + }, +) + + +class HarmCategory(proto.Enum): + r"""The category of a rating. + + These categories cover various kinds of harms that developers + may wish to adjust. + + Values: + HARM_CATEGORY_UNSPECIFIED (0): + Category is unspecified. + HARM_CATEGORY_DEROGATORY (1): + **PaLM** - Negative or harmful comments targeting identity + and/or protected attribute. + HARM_CATEGORY_TOXICITY (2): + **PaLM** - Content that is rude, disrespectful, or profane. + HARM_CATEGORY_VIOLENCE (3): + **PaLM** - Describes scenarios depicting violence against an + individual or group, or general descriptions of gore. + HARM_CATEGORY_SEXUAL (4): + **PaLM** - Contains references to sexual acts or other lewd + content. + HARM_CATEGORY_MEDICAL (5): + **PaLM** - Promotes unchecked medical advice. + HARM_CATEGORY_DANGEROUS (6): + **PaLM** - Dangerous content that promotes, facilitates, or + encourages harmful acts. + HARM_CATEGORY_HARASSMENT (7): + **Gemini** - Harassment content. + HARM_CATEGORY_HATE_SPEECH (8): + **Gemini** - Hate speech and content. + HARM_CATEGORY_SEXUALLY_EXPLICIT (9): + **Gemini** - Sexually explicit content. + HARM_CATEGORY_DANGEROUS_CONTENT (10): + **Gemini** - Dangerous content. + HARM_CATEGORY_CIVIC_INTEGRITY (11): + **Gemini** - Content that may be used to harm civic + integrity. + """ + HARM_CATEGORY_UNSPECIFIED = 0 + HARM_CATEGORY_DEROGATORY = 1 + HARM_CATEGORY_TOXICITY = 2 + HARM_CATEGORY_VIOLENCE = 3 + HARM_CATEGORY_SEXUAL = 4 + HARM_CATEGORY_MEDICAL = 5 + HARM_CATEGORY_DANGEROUS = 6 + HARM_CATEGORY_HARASSMENT = 7 + HARM_CATEGORY_HATE_SPEECH = 8 + HARM_CATEGORY_SEXUALLY_EXPLICIT = 9 + HARM_CATEGORY_DANGEROUS_CONTENT = 10 + HARM_CATEGORY_CIVIC_INTEGRITY = 11 + + +class ContentFilter(proto.Message): + r"""Content filtering metadata associated with processing a + single request. + ContentFilter contains a reason and an optional supporting + string. The reason may be unspecified. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + reason (google.ai.generativelanguage_v1alpha.types.ContentFilter.BlockedReason): + The reason content was blocked during request + processing. + message (str): + A string that describes the filtering + behavior in more detail. + + This field is a member of `oneof`_ ``_message``. + """ + + class BlockedReason(proto.Enum): + r"""A list of reasons why content may have been blocked. + + Values: + BLOCKED_REASON_UNSPECIFIED (0): + A blocked reason was not specified. + SAFETY (1): + Content was blocked by safety settings. + OTHER (2): + Content was blocked, but the reason is + uncategorized. + """ + BLOCKED_REASON_UNSPECIFIED = 0 + SAFETY = 1 + OTHER = 2 + + reason: BlockedReason = proto.Field( + proto.ENUM, + number=1, + enum=BlockedReason, + ) + message: str = proto.Field( + proto.STRING, + number=2, + optional=True, + ) + + +class SafetyFeedback(proto.Message): + r"""Safety feedback for an entire request. + + This field is populated if content in the input and/or response + is blocked due to safety settings. SafetyFeedback may not exist + for every HarmCategory. Each SafetyFeedback will return the + safety settings used by the request as well as the lowest + HarmProbability that should be allowed in order to return a + result. + + Attributes: + rating (google.ai.generativelanguage_v1alpha.types.SafetyRating): + Safety rating evaluated from content. + setting (google.ai.generativelanguage_v1alpha.types.SafetySetting): + Safety settings applied to the request. + """ + + rating: "SafetyRating" = proto.Field( + proto.MESSAGE, + number=1, + message="SafetyRating", + ) + setting: "SafetySetting" = proto.Field( + proto.MESSAGE, + number=2, + message="SafetySetting", + ) + + +class SafetyRating(proto.Message): + r"""Safety rating for a piece of content. + + The safety rating contains the category of harm and the harm + probability level in that category for a piece of content. + Content is classified for safety across a number of harm + categories and the probability of the harm classification is + included here. + + Attributes: + category (google.ai.generativelanguage_v1alpha.types.HarmCategory): + Required. The category for this rating. + probability (google.ai.generativelanguage_v1alpha.types.SafetyRating.HarmProbability): + Required. The probability of harm for this + content. + blocked (bool): + Was this content blocked because of this + rating? + """ + + class HarmProbability(proto.Enum): + r"""The probability that a piece of content is harmful. + + The classification system gives the probability of the content + being unsafe. This does not indicate the severity of harm for a + piece of content. + + Values: + HARM_PROBABILITY_UNSPECIFIED (0): + Probability is unspecified. + NEGLIGIBLE (1): + Content has a negligible chance of being + unsafe. + LOW (2): + Content has a low chance of being unsafe. + MEDIUM (3): + Content has a medium chance of being unsafe. + HIGH (4): + Content has a high chance of being unsafe. + """ + HARM_PROBABILITY_UNSPECIFIED = 0 + NEGLIGIBLE = 1 + LOW = 2 + MEDIUM = 3 + HIGH = 4 + + category: "HarmCategory" = proto.Field( + proto.ENUM, + number=3, + enum="HarmCategory", + ) + probability: HarmProbability = proto.Field( + proto.ENUM, + number=4, + enum=HarmProbability, + ) + blocked: bool = proto.Field( + proto.BOOL, + number=5, + ) + + +class SafetySetting(proto.Message): + r"""Safety setting, affecting the safety-blocking behavior. + + Passing a safety setting for a category changes the allowed + probability that content is blocked. + + Attributes: + category (google.ai.generativelanguage_v1alpha.types.HarmCategory): + Required. The category for this setting. + threshold (google.ai.generativelanguage_v1alpha.types.SafetySetting.HarmBlockThreshold): + Required. Controls the probability threshold + at which harm is blocked. + """ + + class HarmBlockThreshold(proto.Enum): + r"""Block at and beyond a specified harm probability. + + Values: + HARM_BLOCK_THRESHOLD_UNSPECIFIED (0): + Threshold is unspecified. + BLOCK_LOW_AND_ABOVE (1): + Content with NEGLIGIBLE will be allowed. + BLOCK_MEDIUM_AND_ABOVE (2): + Content with NEGLIGIBLE and LOW will be + allowed. + BLOCK_ONLY_HIGH (3): + Content with NEGLIGIBLE, LOW, and MEDIUM will + be allowed. + BLOCK_NONE (4): + All content will be allowed. + OFF (5): + Turn off the safety filter. + """ + HARM_BLOCK_THRESHOLD_UNSPECIFIED = 0 + BLOCK_LOW_AND_ABOVE = 1 + BLOCK_MEDIUM_AND_ABOVE = 2 + BLOCK_ONLY_HIGH = 3 + BLOCK_NONE = 4 + OFF = 5 + + category: "HarmCategory" = proto.Field( + proto.ENUM, + number=3, + enum="HarmCategory", + ) + threshold: HarmBlockThreshold = proto.Field( + proto.ENUM, + number=4, + enum=HarmBlockThreshold, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest))