Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .gitattributes +1 -0
- .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/retriever_service/transports/__pycache__/rest.cpython-311.pyc +3 -0
- .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/__init__.py +15 -0
- .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/cache_service/__init__.py +22 -0
- .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/cache_service/__pycache__/async_client.cpython-311.pyc +0 -0
- .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/cache_service/__pycache__/client.cpython-311.pyc +0 -0
- .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/cache_service/__pycache__/pagers.cpython-311.pyc +0 -0
- .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/cache_service/async_client.py +950 -0
- .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/cache_service/client.py +1340 -0
- .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/cache_service/pagers.py +197 -0
- .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/cache_service/transports/__init__.py +36 -0
- .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/cache_service/transports/__pycache__/__init__.cpython-311.pyc +0 -0
- .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/cache_service/transports/__pycache__/base.cpython-311.pyc +0 -0
- .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/cache_service/transports/__pycache__/grpc.cpython-311.pyc +0 -0
- .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/cache_service/transports/__pycache__/grpc_asyncio.cpython-311.pyc +0 -0
- .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/cache_service/transports/__pycache__/rest.cpython-311.pyc +0 -0
- .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/cache_service/transports/__pycache__/rest_base.cpython-311.pyc +0 -0
- .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/cache_service/transports/base.py +263 -0
- .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/cache_service/transports/grpc.py +517 -0
- .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/cache_service/transports/grpc_asyncio.py +573 -0
- .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/cache_service/transports/rest.py +1428 -0
- .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/cache_service/transports/rest_base.py +399 -0
- .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/generative_service/__init__.py +22 -0
- .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/generative_service/__pycache__/__init__.cpython-311.pyc +0 -0
- .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/generative_service/__pycache__/async_client.cpython-311.pyc +0 -0
- .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/generative_service/__pycache__/client.cpython-311.pyc +0 -0
- .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/generative_service/async_client.py +1272 -0
- .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/generative_service/client.py +1659 -0
- .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/generative_service/transports/__init__.py +36 -0
- .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/generative_service/transports/__pycache__/__init__.cpython-311.pyc +0 -0
- .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/generative_service/transports/__pycache__/base.cpython-311.pyc +0 -0
- .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/generative_service/transports/__pycache__/grpc.cpython-311.pyc +0 -0
- .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/generative_service/transports/__pycache__/grpc_asyncio.cpython-311.pyc +0 -0
- .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/generative_service/transports/__pycache__/rest.cpython-311.pyc +0 -0
- .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/generative_service/transports/__pycache__/rest_base.cpython-311.pyc +0 -0
- .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/generative_service/transports/base.py +335 -0
- .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/generative_service/transports/grpc.py +560 -0
- .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/generative_service/transports/grpc_asyncio.py +672 -0
- .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/generative_service/transports/rest.py +1696 -0
- .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/generative_service/transports/rest_base.py +506 -0
- .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/retriever_service/__init__.py +22 -0
- .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/retriever_service/__pycache__/__init__.cpython-311.pyc +0 -0
- .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/retriever_service/__pycache__/async_client.cpython-311.pyc +0 -0
- .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/retriever_service/__pycache__/pagers.cpython-311.pyc +0 -0
- .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/retriever_service/async_client.py +0 -0
- .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/retriever_service/client.py +0 -0
- .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/retriever_service/pagers.py +509 -0
- .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/retriever_service/transports/__init__.py +36 -0
- .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/retriever_service/transports/__pycache__/__init__.cpython-311.pyc +0 -0
- .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/retriever_service/transports/__pycache__/base.cpython-311.pyc +0 -0
.gitattributes
CHANGED
|
@@ -193,3 +193,4 @@ tuning-competition-baseline/.venv/lib/python3.11/site-packages/torch/_inductor/_
|
|
| 193 |
.venv/lib/python3.11/site-packages/pillow.libs/libjpeg-77ae51ab.so.62.4.0 filter=lfs diff=lfs merge=lfs -text
|
| 194 |
.venv/lib/python3.11/site-packages/pillow.libs/libharfbuzz-89381d8f.so.0.60850.0 filter=lfs diff=lfs merge=lfs -text
|
| 195 |
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/retriever_service/__pycache__/client.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 193 |
.venv/lib/python3.11/site-packages/pillow.libs/libjpeg-77ae51ab.so.62.4.0 filter=lfs diff=lfs merge=lfs -text
|
| 194 |
.venv/lib/python3.11/site-packages/pillow.libs/libharfbuzz-89381d8f.so.0.60850.0 filter=lfs diff=lfs merge=lfs -text
|
| 195 |
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/retriever_service/__pycache__/client.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
|
| 196 |
+
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/retriever_service/transports/__pycache__/rest.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
|
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/retriever_service/transports/__pycache__/rest.cpython-311.pyc
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:edc24a05bb320631e7e716a9b0f060a929be81e24c2a8707a615fd50ca3bf3f3
|
| 3 |
+
size 146113
|
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/__init__.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Copyright 2024 Google LLC
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
#
|
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/cache_service/__init__.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Copyright 2024 Google LLC
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
#
|
| 16 |
+
from .async_client import CacheServiceAsyncClient
|
| 17 |
+
from .client import CacheServiceClient
|
| 18 |
+
|
| 19 |
+
__all__ = (
|
| 20 |
+
"CacheServiceClient",
|
| 21 |
+
"CacheServiceAsyncClient",
|
| 22 |
+
)
|
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/cache_service/__pycache__/async_client.cpython-311.pyc
ADDED
|
Binary file (38.7 kB). View file
|
|
|
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/cache_service/__pycache__/client.cpython-311.pyc
ADDED
|
Binary file (55.3 kB). View file
|
|
|
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/cache_service/__pycache__/pagers.cpython-311.pyc
ADDED
|
Binary file (10.3 kB). View file
|
|
|
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/cache_service/async_client.py
ADDED
|
@@ -0,0 +1,950 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Copyright 2024 Google LLC
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
#
|
| 16 |
+
from collections import OrderedDict
|
| 17 |
+
import logging as std_logging
|
| 18 |
+
import re
|
| 19 |
+
from typing import (
|
| 20 |
+
Callable,
|
| 21 |
+
Dict,
|
| 22 |
+
Mapping,
|
| 23 |
+
MutableMapping,
|
| 24 |
+
MutableSequence,
|
| 25 |
+
Optional,
|
| 26 |
+
Sequence,
|
| 27 |
+
Tuple,
|
| 28 |
+
Type,
|
| 29 |
+
Union,
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
from google.api_core import exceptions as core_exceptions
|
| 33 |
+
from google.api_core import gapic_v1
|
| 34 |
+
from google.api_core import retry_async as retries
|
| 35 |
+
from google.api_core.client_options import ClientOptions
|
| 36 |
+
from google.auth import credentials as ga_credentials # type: ignore
|
| 37 |
+
from google.oauth2 import service_account # type: ignore
|
| 38 |
+
|
| 39 |
+
from google.ai.generativelanguage_v1beta import gapic_version as package_version
|
| 40 |
+
|
| 41 |
+
try:
|
| 42 |
+
OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None]
|
| 43 |
+
except AttributeError: # pragma: NO COVER
|
| 44 |
+
OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore
|
| 45 |
+
|
| 46 |
+
from google.longrunning import operations_pb2 # type: ignore
|
| 47 |
+
from google.protobuf import duration_pb2 # type: ignore
|
| 48 |
+
from google.protobuf import field_mask_pb2 # type: ignore
|
| 49 |
+
from google.protobuf import timestamp_pb2 # type: ignore
|
| 50 |
+
|
| 51 |
+
from google.ai.generativelanguage_v1beta.services.cache_service import pagers
|
| 52 |
+
from google.ai.generativelanguage_v1beta.types import (
|
| 53 |
+
cached_content as gag_cached_content,
|
| 54 |
+
)
|
| 55 |
+
from google.ai.generativelanguage_v1beta.types import cache_service
|
| 56 |
+
from google.ai.generativelanguage_v1beta.types import cached_content
|
| 57 |
+
from google.ai.generativelanguage_v1beta.types import content
|
| 58 |
+
|
| 59 |
+
from .client import CacheServiceClient
|
| 60 |
+
from .transports.base import DEFAULT_CLIENT_INFO, CacheServiceTransport
|
| 61 |
+
from .transports.grpc_asyncio import CacheServiceGrpcAsyncIOTransport
|
| 62 |
+
|
| 63 |
+
try:
|
| 64 |
+
from google.api_core import client_logging # type: ignore
|
| 65 |
+
|
| 66 |
+
CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER
|
| 67 |
+
except ImportError: # pragma: NO COVER
|
| 68 |
+
CLIENT_LOGGING_SUPPORTED = False
|
| 69 |
+
|
| 70 |
+
_LOGGER = std_logging.getLogger(__name__)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
class CacheServiceAsyncClient:
|
| 74 |
+
"""API for managing cache of content (CachedContent resources)
|
| 75 |
+
that can be used in GenerativeService requests. This way
|
| 76 |
+
generate content requests can benefit from preprocessing work
|
| 77 |
+
being done earlier, possibly lowering their computational cost.
|
| 78 |
+
It is intended to be used with large contexts.
|
| 79 |
+
"""
|
| 80 |
+
|
| 81 |
+
_client: CacheServiceClient
|
| 82 |
+
|
| 83 |
+
# Copy defaults from the synchronous client for use here.
|
| 84 |
+
# Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead.
|
| 85 |
+
DEFAULT_ENDPOINT = CacheServiceClient.DEFAULT_ENDPOINT
|
| 86 |
+
DEFAULT_MTLS_ENDPOINT = CacheServiceClient.DEFAULT_MTLS_ENDPOINT
|
| 87 |
+
_DEFAULT_ENDPOINT_TEMPLATE = CacheServiceClient._DEFAULT_ENDPOINT_TEMPLATE
|
| 88 |
+
_DEFAULT_UNIVERSE = CacheServiceClient._DEFAULT_UNIVERSE
|
| 89 |
+
|
| 90 |
+
cached_content_path = staticmethod(CacheServiceClient.cached_content_path)
|
| 91 |
+
parse_cached_content_path = staticmethod(
|
| 92 |
+
CacheServiceClient.parse_cached_content_path
|
| 93 |
+
)
|
| 94 |
+
model_path = staticmethod(CacheServiceClient.model_path)
|
| 95 |
+
parse_model_path = staticmethod(CacheServiceClient.parse_model_path)
|
| 96 |
+
common_billing_account_path = staticmethod(
|
| 97 |
+
CacheServiceClient.common_billing_account_path
|
| 98 |
+
)
|
| 99 |
+
parse_common_billing_account_path = staticmethod(
|
| 100 |
+
CacheServiceClient.parse_common_billing_account_path
|
| 101 |
+
)
|
| 102 |
+
common_folder_path = staticmethod(CacheServiceClient.common_folder_path)
|
| 103 |
+
parse_common_folder_path = staticmethod(CacheServiceClient.parse_common_folder_path)
|
| 104 |
+
common_organization_path = staticmethod(CacheServiceClient.common_organization_path)
|
| 105 |
+
parse_common_organization_path = staticmethod(
|
| 106 |
+
CacheServiceClient.parse_common_organization_path
|
| 107 |
+
)
|
| 108 |
+
common_project_path = staticmethod(CacheServiceClient.common_project_path)
|
| 109 |
+
parse_common_project_path = staticmethod(
|
| 110 |
+
CacheServiceClient.parse_common_project_path
|
| 111 |
+
)
|
| 112 |
+
common_location_path = staticmethod(CacheServiceClient.common_location_path)
|
| 113 |
+
parse_common_location_path = staticmethod(
|
| 114 |
+
CacheServiceClient.parse_common_location_path
|
| 115 |
+
)
|
| 116 |
+
|
| 117 |
+
@classmethod
|
| 118 |
+
def from_service_account_info(cls, info: dict, *args, **kwargs):
|
| 119 |
+
"""Creates an instance of this client using the provided credentials
|
| 120 |
+
info.
|
| 121 |
+
|
| 122 |
+
Args:
|
| 123 |
+
info (dict): The service account private key info.
|
| 124 |
+
args: Additional arguments to pass to the constructor.
|
| 125 |
+
kwargs: Additional arguments to pass to the constructor.
|
| 126 |
+
|
| 127 |
+
Returns:
|
| 128 |
+
CacheServiceAsyncClient: The constructed client.
|
| 129 |
+
"""
|
| 130 |
+
return CacheServiceClient.from_service_account_info.__func__(CacheServiceAsyncClient, info, *args, **kwargs) # type: ignore
|
| 131 |
+
|
| 132 |
+
@classmethod
|
| 133 |
+
def from_service_account_file(cls, filename: str, *args, **kwargs):
|
| 134 |
+
"""Creates an instance of this client using the provided credentials
|
| 135 |
+
file.
|
| 136 |
+
|
| 137 |
+
Args:
|
| 138 |
+
filename (str): The path to the service account private key json
|
| 139 |
+
file.
|
| 140 |
+
args: Additional arguments to pass to the constructor.
|
| 141 |
+
kwargs: Additional arguments to pass to the constructor.
|
| 142 |
+
|
| 143 |
+
Returns:
|
| 144 |
+
CacheServiceAsyncClient: The constructed client.
|
| 145 |
+
"""
|
| 146 |
+
return CacheServiceClient.from_service_account_file.__func__(CacheServiceAsyncClient, filename, *args, **kwargs) # type: ignore
|
| 147 |
+
|
| 148 |
+
from_service_account_json = from_service_account_file
|
| 149 |
+
|
| 150 |
+
@classmethod
|
| 151 |
+
def get_mtls_endpoint_and_cert_source(
|
| 152 |
+
cls, client_options: Optional[ClientOptions] = None
|
| 153 |
+
):
|
| 154 |
+
"""Return the API endpoint and client cert source for mutual TLS.
|
| 155 |
+
|
| 156 |
+
The client cert source is determined in the following order:
|
| 157 |
+
(1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the
|
| 158 |
+
client cert source is None.
|
| 159 |
+
(2) if `client_options.client_cert_source` is provided, use the provided one; if the
|
| 160 |
+
default client cert source exists, use the default one; otherwise the client cert
|
| 161 |
+
source is None.
|
| 162 |
+
|
| 163 |
+
The API endpoint is determined in the following order:
|
| 164 |
+
(1) if `client_options.api_endpoint` if provided, use the provided one.
|
| 165 |
+
(2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the
|
| 166 |
+
default mTLS endpoint; if the environment variable is "never", use the default API
|
| 167 |
+
endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise
|
| 168 |
+
use the default API endpoint.
|
| 169 |
+
|
| 170 |
+
More details can be found at https://google.aip.dev/auth/4114.
|
| 171 |
+
|
| 172 |
+
Args:
|
| 173 |
+
client_options (google.api_core.client_options.ClientOptions): Custom options for the
|
| 174 |
+
client. Only the `api_endpoint` and `client_cert_source` properties may be used
|
| 175 |
+
in this method.
|
| 176 |
+
|
| 177 |
+
Returns:
|
| 178 |
+
Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the
|
| 179 |
+
client cert source to use.
|
| 180 |
+
|
| 181 |
+
Raises:
|
| 182 |
+
google.auth.exceptions.MutualTLSChannelError: If any errors happen.
|
| 183 |
+
"""
|
| 184 |
+
return CacheServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore
|
| 185 |
+
|
| 186 |
+
@property
|
| 187 |
+
def transport(self) -> CacheServiceTransport:
|
| 188 |
+
"""Returns the transport used by the client instance.
|
| 189 |
+
|
| 190 |
+
Returns:
|
| 191 |
+
CacheServiceTransport: The transport used by the client instance.
|
| 192 |
+
"""
|
| 193 |
+
return self._client.transport
|
| 194 |
+
|
| 195 |
+
@property
|
| 196 |
+
def api_endpoint(self):
|
| 197 |
+
"""Return the API endpoint used by the client instance.
|
| 198 |
+
|
| 199 |
+
Returns:
|
| 200 |
+
str: The API endpoint used by the client instance.
|
| 201 |
+
"""
|
| 202 |
+
return self._client._api_endpoint
|
| 203 |
+
|
| 204 |
+
@property
|
| 205 |
+
def universe_domain(self) -> str:
|
| 206 |
+
"""Return the universe domain used by the client instance.
|
| 207 |
+
|
| 208 |
+
Returns:
|
| 209 |
+
str: The universe domain used
|
| 210 |
+
by the client instance.
|
| 211 |
+
"""
|
| 212 |
+
return self._client._universe_domain
|
| 213 |
+
|
| 214 |
+
get_transport_class = CacheServiceClient.get_transport_class
|
| 215 |
+
|
| 216 |
+
def __init__(
|
| 217 |
+
self,
|
| 218 |
+
*,
|
| 219 |
+
credentials: Optional[ga_credentials.Credentials] = None,
|
| 220 |
+
transport: Optional[
|
| 221 |
+
Union[str, CacheServiceTransport, Callable[..., CacheServiceTransport]]
|
| 222 |
+
] = "grpc_asyncio",
|
| 223 |
+
client_options: Optional[ClientOptions] = None,
|
| 224 |
+
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
|
| 225 |
+
) -> None:
|
| 226 |
+
"""Instantiates the cache service async client.
|
| 227 |
+
|
| 228 |
+
Args:
|
| 229 |
+
credentials (Optional[google.auth.credentials.Credentials]): The
|
| 230 |
+
authorization credentials to attach to requests. These
|
| 231 |
+
credentials identify the application to the service; if none
|
| 232 |
+
are specified, the client will attempt to ascertain the
|
| 233 |
+
credentials from the environment.
|
| 234 |
+
transport (Optional[Union[str,CacheServiceTransport,Callable[..., CacheServiceTransport]]]):
|
| 235 |
+
The transport to use, or a Callable that constructs and returns a new transport to use.
|
| 236 |
+
If a Callable is given, it will be called with the same set of initialization
|
| 237 |
+
arguments as used in the CacheServiceTransport constructor.
|
| 238 |
+
If set to None, a transport is chosen automatically.
|
| 239 |
+
client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]):
|
| 240 |
+
Custom options for the client.
|
| 241 |
+
|
| 242 |
+
1. The ``api_endpoint`` property can be used to override the
|
| 243 |
+
default endpoint provided by the client when ``transport`` is
|
| 244 |
+
not explicitly provided. Only if this property is not set and
|
| 245 |
+
``transport`` was not explicitly provided, the endpoint is
|
| 246 |
+
determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment
|
| 247 |
+
variable, which have one of the following values:
|
| 248 |
+
"always" (always use the default mTLS endpoint), "never" (always
|
| 249 |
+
use the default regular endpoint) and "auto" (auto-switch to the
|
| 250 |
+
default mTLS endpoint if client certificate is present; this is
|
| 251 |
+
the default value).
|
| 252 |
+
|
| 253 |
+
2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable
|
| 254 |
+
is "true", then the ``client_cert_source`` property can be used
|
| 255 |
+
to provide a client certificate for mTLS transport. If
|
| 256 |
+
not provided, the default SSL client certificate will be used if
|
| 257 |
+
present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not
|
| 258 |
+
set, no client certificate will be used.
|
| 259 |
+
|
| 260 |
+
3. The ``universe_domain`` property can be used to override the
|
| 261 |
+
default "googleapis.com" universe. Note that ``api_endpoint``
|
| 262 |
+
property still takes precedence; and ``universe_domain`` is
|
| 263 |
+
currently not supported for mTLS.
|
| 264 |
+
|
| 265 |
+
client_info (google.api_core.gapic_v1.client_info.ClientInfo):
|
| 266 |
+
The client info used to send a user-agent string along with
|
| 267 |
+
API requests. If ``None``, then default info will be used.
|
| 268 |
+
Generally, you only need to set this if you're developing
|
| 269 |
+
your own client library.
|
| 270 |
+
|
| 271 |
+
Raises:
|
| 272 |
+
google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
|
| 273 |
+
creation failed for any reason.
|
| 274 |
+
"""
|
| 275 |
+
self._client = CacheServiceClient(
|
| 276 |
+
credentials=credentials,
|
| 277 |
+
transport=transport,
|
| 278 |
+
client_options=client_options,
|
| 279 |
+
client_info=client_info,
|
| 280 |
+
)
|
| 281 |
+
|
| 282 |
+
if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
|
| 283 |
+
std_logging.DEBUG
|
| 284 |
+
): # pragma: NO COVER
|
| 285 |
+
_LOGGER.debug(
|
| 286 |
+
"Created client `google.ai.generativelanguage_v1beta.CacheServiceAsyncClient`.",
|
| 287 |
+
extra={
|
| 288 |
+
"serviceName": "google.ai.generativelanguage.v1beta.CacheService",
|
| 289 |
+
"universeDomain": getattr(
|
| 290 |
+
self._client._transport._credentials, "universe_domain", ""
|
| 291 |
+
),
|
| 292 |
+
"credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}",
|
| 293 |
+
"credentialsInfo": getattr(
|
| 294 |
+
self.transport._credentials, "get_cred_info", lambda: None
|
| 295 |
+
)(),
|
| 296 |
+
}
|
| 297 |
+
if hasattr(self._client._transport, "_credentials")
|
| 298 |
+
else {
|
| 299 |
+
"serviceName": "google.ai.generativelanguage.v1beta.CacheService",
|
| 300 |
+
"credentialsType": None,
|
| 301 |
+
},
|
| 302 |
+
)
|
| 303 |
+
|
| 304 |
+
async def list_cached_contents(
|
| 305 |
+
self,
|
| 306 |
+
request: Optional[Union[cache_service.ListCachedContentsRequest, dict]] = None,
|
| 307 |
+
*,
|
| 308 |
+
retry: OptionalRetry = gapic_v1.method.DEFAULT,
|
| 309 |
+
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
|
| 310 |
+
metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
|
| 311 |
+
) -> pagers.ListCachedContentsAsyncPager:
|
| 312 |
+
r"""Lists CachedContents.
|
| 313 |
+
|
| 314 |
+
.. code-block:: python
|
| 315 |
+
|
| 316 |
+
# This snippet has been automatically generated and should be regarded as a
|
| 317 |
+
# code template only.
|
| 318 |
+
# It will require modifications to work:
|
| 319 |
+
# - It may require correct/in-range values for request initialization.
|
| 320 |
+
# - It may require specifying regional endpoints when creating the service
|
| 321 |
+
# client as shown in:
|
| 322 |
+
# https://googleapis.dev/python/google-api-core/latest/client_options.html
|
| 323 |
+
from google.ai import generativelanguage_v1beta
|
| 324 |
+
|
| 325 |
+
async def sample_list_cached_contents():
|
| 326 |
+
# Create a client
|
| 327 |
+
client = generativelanguage_v1beta.CacheServiceAsyncClient()
|
| 328 |
+
|
| 329 |
+
# Initialize request argument(s)
|
| 330 |
+
request = generativelanguage_v1beta.ListCachedContentsRequest(
|
| 331 |
+
)
|
| 332 |
+
|
| 333 |
+
# Make the request
|
| 334 |
+
page_result = client.list_cached_contents(request=request)
|
| 335 |
+
|
| 336 |
+
# Handle the response
|
| 337 |
+
async for response in page_result:
|
| 338 |
+
print(response)
|
| 339 |
+
|
| 340 |
+
Args:
|
| 341 |
+
request (Optional[Union[google.ai.generativelanguage_v1beta.types.ListCachedContentsRequest, dict]]):
|
| 342 |
+
The request object. Request to list CachedContents.
|
| 343 |
+
retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any,
|
| 344 |
+
should be retried.
|
| 345 |
+
timeout (float): The timeout for this request.
|
| 346 |
+
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
|
| 347 |
+
sent along with the request as metadata. Normally, each value must be of type `str`,
|
| 348 |
+
but for metadata keys ending with the suffix `-bin`, the corresponding values must
|
| 349 |
+
be of type `bytes`.
|
| 350 |
+
|
| 351 |
+
Returns:
|
| 352 |
+
google.ai.generativelanguage_v1beta.services.cache_service.pagers.ListCachedContentsAsyncPager:
|
| 353 |
+
Response with CachedContents list.
|
| 354 |
+
|
| 355 |
+
Iterating over this object will yield
|
| 356 |
+
results and resolve additional pages
|
| 357 |
+
automatically.
|
| 358 |
+
|
| 359 |
+
"""
|
| 360 |
+
# Create or coerce a protobuf request object.
|
| 361 |
+
# - Use the request object if provided (there's no risk of modifying the input as
|
| 362 |
+
# there are no flattened fields), or create one.
|
| 363 |
+
if not isinstance(request, cache_service.ListCachedContentsRequest):
|
| 364 |
+
request = cache_service.ListCachedContentsRequest(request)
|
| 365 |
+
|
| 366 |
+
# Wrap the RPC method; this adds retry and timeout information,
|
| 367 |
+
# and friendly error handling.
|
| 368 |
+
rpc = self._client._transport._wrapped_methods[
|
| 369 |
+
self._client._transport.list_cached_contents
|
| 370 |
+
]
|
| 371 |
+
|
| 372 |
+
# Validate the universe domain.
|
| 373 |
+
self._client._validate_universe_domain()
|
| 374 |
+
|
| 375 |
+
# Send the request.
|
| 376 |
+
response = await rpc(
|
| 377 |
+
request,
|
| 378 |
+
retry=retry,
|
| 379 |
+
timeout=timeout,
|
| 380 |
+
metadata=metadata,
|
| 381 |
+
)
|
| 382 |
+
|
| 383 |
+
# This method is paged; wrap the response in a pager, which provides
|
| 384 |
+
# an `__aiter__` convenience method.
|
| 385 |
+
response = pagers.ListCachedContentsAsyncPager(
|
| 386 |
+
method=rpc,
|
| 387 |
+
request=request,
|
| 388 |
+
response=response,
|
| 389 |
+
retry=retry,
|
| 390 |
+
timeout=timeout,
|
| 391 |
+
metadata=metadata,
|
| 392 |
+
)
|
| 393 |
+
|
| 394 |
+
# Done; return the response.
|
| 395 |
+
return response
|
| 396 |
+
|
| 397 |
+
async def create_cached_content(
|
| 398 |
+
self,
|
| 399 |
+
request: Optional[Union[cache_service.CreateCachedContentRequest, dict]] = None,
|
| 400 |
+
*,
|
| 401 |
+
cached_content: Optional[gag_cached_content.CachedContent] = None,
|
| 402 |
+
retry: OptionalRetry = gapic_v1.method.DEFAULT,
|
| 403 |
+
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
|
| 404 |
+
metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
|
| 405 |
+
) -> gag_cached_content.CachedContent:
|
| 406 |
+
r"""Creates CachedContent resource.
|
| 407 |
+
|
| 408 |
+
.. code-block:: python
|
| 409 |
+
|
| 410 |
+
# This snippet has been automatically generated and should be regarded as a
|
| 411 |
+
# code template only.
|
| 412 |
+
# It will require modifications to work:
|
| 413 |
+
# - It may require correct/in-range values for request initialization.
|
| 414 |
+
# - It may require specifying regional endpoints when creating the service
|
| 415 |
+
# client as shown in:
|
| 416 |
+
# https://googleapis.dev/python/google-api-core/latest/client_options.html
|
| 417 |
+
from google.ai import generativelanguage_v1beta
|
| 418 |
+
|
| 419 |
+
async def sample_create_cached_content():
|
| 420 |
+
# Create a client
|
| 421 |
+
client = generativelanguage_v1beta.CacheServiceAsyncClient()
|
| 422 |
+
|
| 423 |
+
# Initialize request argument(s)
|
| 424 |
+
request = generativelanguage_v1beta.CreateCachedContentRequest(
|
| 425 |
+
)
|
| 426 |
+
|
| 427 |
+
# Make the request
|
| 428 |
+
response = await client.create_cached_content(request=request)
|
| 429 |
+
|
| 430 |
+
# Handle the response
|
| 431 |
+
print(response)
|
| 432 |
+
|
| 433 |
+
Args:
|
| 434 |
+
request (Optional[Union[google.ai.generativelanguage_v1beta.types.CreateCachedContentRequest, dict]]):
|
| 435 |
+
The request object. Request to create CachedContent.
|
| 436 |
+
cached_content (:class:`google.ai.generativelanguage_v1beta.types.CachedContent`):
|
| 437 |
+
Required. The cached content to
|
| 438 |
+
create.
|
| 439 |
+
|
| 440 |
+
This corresponds to the ``cached_content`` field
|
| 441 |
+
on the ``request`` instance; if ``request`` is provided, this
|
| 442 |
+
should not be set.
|
| 443 |
+
retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any,
|
| 444 |
+
should be retried.
|
| 445 |
+
timeout (float): The timeout for this request.
|
| 446 |
+
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
|
| 447 |
+
sent along with the request as metadata. Normally, each value must be of type `str`,
|
| 448 |
+
but for metadata keys ending with the suffix `-bin`, the corresponding values must
|
| 449 |
+
be of type `bytes`.
|
| 450 |
+
|
| 451 |
+
Returns:
|
| 452 |
+
google.ai.generativelanguage_v1beta.types.CachedContent:
|
| 453 |
+
Content that has been preprocessed
|
| 454 |
+
and can be used in subsequent request to
|
| 455 |
+
GenerativeService.
|
| 456 |
+
|
| 457 |
+
Cached content can be only used with
|
| 458 |
+
model it was created for.
|
| 459 |
+
|
| 460 |
+
"""
|
| 461 |
+
# Create or coerce a protobuf request object.
|
| 462 |
+
# - Quick check: If we got a request object, we should *not* have
|
| 463 |
+
# gotten any keyword arguments that map to the request.
|
| 464 |
+
has_flattened_params = any([cached_content])
|
| 465 |
+
if request is not None and has_flattened_params:
|
| 466 |
+
raise ValueError(
|
| 467 |
+
"If the `request` argument is set, then none of "
|
| 468 |
+
"the individual field arguments should be set."
|
| 469 |
+
)
|
| 470 |
+
|
| 471 |
+
# - Use the request object if provided (there's no risk of modifying the input as
|
| 472 |
+
# there are no flattened fields), or create one.
|
| 473 |
+
if not isinstance(request, cache_service.CreateCachedContentRequest):
|
| 474 |
+
request = cache_service.CreateCachedContentRequest(request)
|
| 475 |
+
|
| 476 |
+
# If we have keyword arguments corresponding to fields on the
|
| 477 |
+
# request, apply these.
|
| 478 |
+
if cached_content is not None:
|
| 479 |
+
request.cached_content = cached_content
|
| 480 |
+
|
| 481 |
+
# Wrap the RPC method; this adds retry and timeout information,
|
| 482 |
+
# and friendly error handling.
|
| 483 |
+
rpc = self._client._transport._wrapped_methods[
|
| 484 |
+
self._client._transport.create_cached_content
|
| 485 |
+
]
|
| 486 |
+
|
| 487 |
+
# Validate the universe domain.
|
| 488 |
+
self._client._validate_universe_domain()
|
| 489 |
+
|
| 490 |
+
# Send the request.
|
| 491 |
+
response = await rpc(
|
| 492 |
+
request,
|
| 493 |
+
retry=retry,
|
| 494 |
+
timeout=timeout,
|
| 495 |
+
metadata=metadata,
|
| 496 |
+
)
|
| 497 |
+
|
| 498 |
+
# Done; return the response.
|
| 499 |
+
return response
|
| 500 |
+
|
| 501 |
+
async def get_cached_content(
|
| 502 |
+
self,
|
| 503 |
+
request: Optional[Union[cache_service.GetCachedContentRequest, dict]] = None,
|
| 504 |
+
*,
|
| 505 |
+
name: Optional[str] = None,
|
| 506 |
+
retry: OptionalRetry = gapic_v1.method.DEFAULT,
|
| 507 |
+
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
|
| 508 |
+
metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
|
| 509 |
+
) -> cached_content.CachedContent:
|
| 510 |
+
r"""Reads CachedContent resource.
|
| 511 |
+
|
| 512 |
+
.. code-block:: python
|
| 513 |
+
|
| 514 |
+
# This snippet has been automatically generated and should be regarded as a
|
| 515 |
+
# code template only.
|
| 516 |
+
# It will require modifications to work:
|
| 517 |
+
# - It may require correct/in-range values for request initialization.
|
| 518 |
+
# - It may require specifying regional endpoints when creating the service
|
| 519 |
+
# client as shown in:
|
| 520 |
+
# https://googleapis.dev/python/google-api-core/latest/client_options.html
|
| 521 |
+
from google.ai import generativelanguage_v1beta
|
| 522 |
+
|
| 523 |
+
async def sample_get_cached_content():
|
| 524 |
+
# Create a client
|
| 525 |
+
client = generativelanguage_v1beta.CacheServiceAsyncClient()
|
| 526 |
+
|
| 527 |
+
# Initialize request argument(s)
|
| 528 |
+
request = generativelanguage_v1beta.GetCachedContentRequest(
|
| 529 |
+
name="name_value",
|
| 530 |
+
)
|
| 531 |
+
|
| 532 |
+
# Make the request
|
| 533 |
+
response = await client.get_cached_content(request=request)
|
| 534 |
+
|
| 535 |
+
# Handle the response
|
| 536 |
+
print(response)
|
| 537 |
+
|
| 538 |
+
Args:
|
| 539 |
+
request (Optional[Union[google.ai.generativelanguage_v1beta.types.GetCachedContentRequest, dict]]):
|
| 540 |
+
The request object. Request to read CachedContent.
|
| 541 |
+
name (:class:`str`):
|
| 542 |
+
Required. The resource name referring to the content
|
| 543 |
+
cache entry. Format: ``cachedContents/{id}``
|
| 544 |
+
|
| 545 |
+
This corresponds to the ``name`` field
|
| 546 |
+
on the ``request`` instance; if ``request`` is provided, this
|
| 547 |
+
should not be set.
|
| 548 |
+
retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any,
|
| 549 |
+
should be retried.
|
| 550 |
+
timeout (float): The timeout for this request.
|
| 551 |
+
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
|
| 552 |
+
sent along with the request as metadata. Normally, each value must be of type `str`,
|
| 553 |
+
but for metadata keys ending with the suffix `-bin`, the corresponding values must
|
| 554 |
+
be of type `bytes`.
|
| 555 |
+
|
| 556 |
+
Returns:
|
| 557 |
+
google.ai.generativelanguage_v1beta.types.CachedContent:
|
| 558 |
+
Content that has been preprocessed
|
| 559 |
+
and can be used in subsequent request to
|
| 560 |
+
GenerativeService.
|
| 561 |
+
|
| 562 |
+
Cached content can be only used with
|
| 563 |
+
model it was created for.
|
| 564 |
+
|
| 565 |
+
"""
|
| 566 |
+
# Create or coerce a protobuf request object.
|
| 567 |
+
# - Quick check: If we got a request object, we should *not* have
|
| 568 |
+
# gotten any keyword arguments that map to the request.
|
| 569 |
+
has_flattened_params = any([name])
|
| 570 |
+
if request is not None and has_flattened_params:
|
| 571 |
+
raise ValueError(
|
| 572 |
+
"If the `request` argument is set, then none of "
|
| 573 |
+
"the individual field arguments should be set."
|
| 574 |
+
)
|
| 575 |
+
|
| 576 |
+
# - Use the request object if provided (there's no risk of modifying the input as
|
| 577 |
+
# there are no flattened fields), or create one.
|
| 578 |
+
if not isinstance(request, cache_service.GetCachedContentRequest):
|
| 579 |
+
request = cache_service.GetCachedContentRequest(request)
|
| 580 |
+
|
| 581 |
+
# If we have keyword arguments corresponding to fields on the
|
| 582 |
+
# request, apply these.
|
| 583 |
+
if name is not None:
|
| 584 |
+
request.name = name
|
| 585 |
+
|
| 586 |
+
# Wrap the RPC method; this adds retry and timeout information,
|
| 587 |
+
# and friendly error handling.
|
| 588 |
+
rpc = self._client._transport._wrapped_methods[
|
| 589 |
+
self._client._transport.get_cached_content
|
| 590 |
+
]
|
| 591 |
+
|
| 592 |
+
# Certain fields should be provided within the metadata header;
|
| 593 |
+
# add these here.
|
| 594 |
+
metadata = tuple(metadata) + (
|
| 595 |
+
gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
|
| 596 |
+
)
|
| 597 |
+
|
| 598 |
+
# Validate the universe domain.
|
| 599 |
+
self._client._validate_universe_domain()
|
| 600 |
+
|
| 601 |
+
# Send the request.
|
| 602 |
+
response = await rpc(
|
| 603 |
+
request,
|
| 604 |
+
retry=retry,
|
| 605 |
+
timeout=timeout,
|
| 606 |
+
metadata=metadata,
|
| 607 |
+
)
|
| 608 |
+
|
| 609 |
+
# Done; return the response.
|
| 610 |
+
return response
|
| 611 |
+
|
| 612 |
+
async def update_cached_content(
|
| 613 |
+
self,
|
| 614 |
+
request: Optional[Union[cache_service.UpdateCachedContentRequest, dict]] = None,
|
| 615 |
+
*,
|
| 616 |
+
cached_content: Optional[gag_cached_content.CachedContent] = None,
|
| 617 |
+
update_mask: Optional[field_mask_pb2.FieldMask] = None,
|
| 618 |
+
retry: OptionalRetry = gapic_v1.method.DEFAULT,
|
| 619 |
+
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
|
| 620 |
+
metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
|
| 621 |
+
) -> gag_cached_content.CachedContent:
|
| 622 |
+
r"""Updates CachedContent resource (only expiration is
|
| 623 |
+
updatable).
|
| 624 |
+
|
| 625 |
+
.. code-block:: python
|
| 626 |
+
|
| 627 |
+
# This snippet has been automatically generated and should be regarded as a
|
| 628 |
+
# code template only.
|
| 629 |
+
# It will require modifications to work:
|
| 630 |
+
# - It may require correct/in-range values for request initialization.
|
| 631 |
+
# - It may require specifying regional endpoints when creating the service
|
| 632 |
+
# client as shown in:
|
| 633 |
+
# https://googleapis.dev/python/google-api-core/latest/client_options.html
|
| 634 |
+
from google.ai import generativelanguage_v1beta
|
| 635 |
+
|
| 636 |
+
async def sample_update_cached_content():
|
| 637 |
+
# Create a client
|
| 638 |
+
client = generativelanguage_v1beta.CacheServiceAsyncClient()
|
| 639 |
+
|
| 640 |
+
# Initialize request argument(s)
|
| 641 |
+
request = generativelanguage_v1beta.UpdateCachedContentRequest(
|
| 642 |
+
)
|
| 643 |
+
|
| 644 |
+
# Make the request
|
| 645 |
+
response = await client.update_cached_content(request=request)
|
| 646 |
+
|
| 647 |
+
# Handle the response
|
| 648 |
+
print(response)
|
| 649 |
+
|
| 650 |
+
Args:
|
| 651 |
+
request (Optional[Union[google.ai.generativelanguage_v1beta.types.UpdateCachedContentRequest, dict]]):
|
| 652 |
+
The request object. Request to update CachedContent.
|
| 653 |
+
cached_content (:class:`google.ai.generativelanguage_v1beta.types.CachedContent`):
|
| 654 |
+
Required. The content cache entry to
|
| 655 |
+
update
|
| 656 |
+
|
| 657 |
+
This corresponds to the ``cached_content`` field
|
| 658 |
+
on the ``request`` instance; if ``request`` is provided, this
|
| 659 |
+
should not be set.
|
| 660 |
+
update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`):
|
| 661 |
+
The list of fields to update.
|
| 662 |
+
This corresponds to the ``update_mask`` field
|
| 663 |
+
on the ``request`` instance; if ``request`` is provided, this
|
| 664 |
+
should not be set.
|
| 665 |
+
retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any,
|
| 666 |
+
should be retried.
|
| 667 |
+
timeout (float): The timeout for this request.
|
| 668 |
+
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
|
| 669 |
+
sent along with the request as metadata. Normally, each value must be of type `str`,
|
| 670 |
+
but for metadata keys ending with the suffix `-bin`, the corresponding values must
|
| 671 |
+
be of type `bytes`.
|
| 672 |
+
|
| 673 |
+
Returns:
|
| 674 |
+
google.ai.generativelanguage_v1beta.types.CachedContent:
|
| 675 |
+
Content that has been preprocessed
|
| 676 |
+
and can be used in subsequent request to
|
| 677 |
+
GenerativeService.
|
| 678 |
+
|
| 679 |
+
Cached content can be only used with
|
| 680 |
+
model it was created for.
|
| 681 |
+
|
| 682 |
+
"""
|
| 683 |
+
# Create or coerce a protobuf request object.
|
| 684 |
+
# - Quick check: If we got a request object, we should *not* have
|
| 685 |
+
# gotten any keyword arguments that map to the request.
|
| 686 |
+
has_flattened_params = any([cached_content, update_mask])
|
| 687 |
+
if request is not None and has_flattened_params:
|
| 688 |
+
raise ValueError(
|
| 689 |
+
"If the `request` argument is set, then none of "
|
| 690 |
+
"the individual field arguments should be set."
|
| 691 |
+
)
|
| 692 |
+
|
| 693 |
+
# - Use the request object if provided (there's no risk of modifying the input as
|
| 694 |
+
# there are no flattened fields), or create one.
|
| 695 |
+
if not isinstance(request, cache_service.UpdateCachedContentRequest):
|
| 696 |
+
request = cache_service.UpdateCachedContentRequest(request)
|
| 697 |
+
|
| 698 |
+
# If we have keyword arguments corresponding to fields on the
|
| 699 |
+
# request, apply these.
|
| 700 |
+
if cached_content is not None:
|
| 701 |
+
request.cached_content = cached_content
|
| 702 |
+
if update_mask is not None:
|
| 703 |
+
request.update_mask = update_mask
|
| 704 |
+
|
| 705 |
+
# Wrap the RPC method; this adds retry and timeout information,
|
| 706 |
+
# and friendly error handling.
|
| 707 |
+
rpc = self._client._transport._wrapped_methods[
|
| 708 |
+
self._client._transport.update_cached_content
|
| 709 |
+
]
|
| 710 |
+
|
| 711 |
+
# Certain fields should be provided within the metadata header;
|
| 712 |
+
# add these here.
|
| 713 |
+
metadata = tuple(metadata) + (
|
| 714 |
+
gapic_v1.routing_header.to_grpc_metadata(
|
| 715 |
+
(("cached_content.name", request.cached_content.name),)
|
| 716 |
+
),
|
| 717 |
+
)
|
| 718 |
+
|
| 719 |
+
# Validate the universe domain.
|
| 720 |
+
self._client._validate_universe_domain()
|
| 721 |
+
|
| 722 |
+
# Send the request.
|
| 723 |
+
response = await rpc(
|
| 724 |
+
request,
|
| 725 |
+
retry=retry,
|
| 726 |
+
timeout=timeout,
|
| 727 |
+
metadata=metadata,
|
| 728 |
+
)
|
| 729 |
+
|
| 730 |
+
# Done; return the response.
|
| 731 |
+
return response
|
| 732 |
+
|
| 733 |
+
async def delete_cached_content(
|
| 734 |
+
self,
|
| 735 |
+
request: Optional[Union[cache_service.DeleteCachedContentRequest, dict]] = None,
|
| 736 |
+
*,
|
| 737 |
+
name: Optional[str] = None,
|
| 738 |
+
retry: OptionalRetry = gapic_v1.method.DEFAULT,
|
| 739 |
+
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
|
| 740 |
+
metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
|
| 741 |
+
) -> None:
|
| 742 |
+
r"""Deletes CachedContent resource.
|
| 743 |
+
|
| 744 |
+
.. code-block:: python
|
| 745 |
+
|
| 746 |
+
# This snippet has been automatically generated and should be regarded as a
|
| 747 |
+
# code template only.
|
| 748 |
+
# It will require modifications to work:
|
| 749 |
+
# - It may require correct/in-range values for request initialization.
|
| 750 |
+
# - It may require specifying regional endpoints when creating the service
|
| 751 |
+
# client as shown in:
|
| 752 |
+
# https://googleapis.dev/python/google-api-core/latest/client_options.html
|
| 753 |
+
from google.ai import generativelanguage_v1beta
|
| 754 |
+
|
| 755 |
+
async def sample_delete_cached_content():
|
| 756 |
+
# Create a client
|
| 757 |
+
client = generativelanguage_v1beta.CacheServiceAsyncClient()
|
| 758 |
+
|
| 759 |
+
# Initialize request argument(s)
|
| 760 |
+
request = generativelanguage_v1beta.DeleteCachedContentRequest(
|
| 761 |
+
name="name_value",
|
| 762 |
+
)
|
| 763 |
+
|
| 764 |
+
# Make the request
|
| 765 |
+
await client.delete_cached_content(request=request)
|
| 766 |
+
|
| 767 |
+
Args:
|
| 768 |
+
request (Optional[Union[google.ai.generativelanguage_v1beta.types.DeleteCachedContentRequest, dict]]):
|
| 769 |
+
The request object. Request to delete CachedContent.
|
| 770 |
+
name (:class:`str`):
|
| 771 |
+
Required. The resource name referring to the content
|
| 772 |
+
cache entry Format: ``cachedContents/{id}``
|
| 773 |
+
|
| 774 |
+
This corresponds to the ``name`` field
|
| 775 |
+
on the ``request`` instance; if ``request`` is provided, this
|
| 776 |
+
should not be set.
|
| 777 |
+
retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any,
|
| 778 |
+
should be retried.
|
| 779 |
+
timeout (float): The timeout for this request.
|
| 780 |
+
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
|
| 781 |
+
sent along with the request as metadata. Normally, each value must be of type `str`,
|
| 782 |
+
but for metadata keys ending with the suffix `-bin`, the corresponding values must
|
| 783 |
+
be of type `bytes`.
|
| 784 |
+
"""
|
| 785 |
+
# Create or coerce a protobuf request object.
|
| 786 |
+
# - Quick check: If we got a request object, we should *not* have
|
| 787 |
+
# gotten any keyword arguments that map to the request.
|
| 788 |
+
has_flattened_params = any([name])
|
| 789 |
+
if request is not None and has_flattened_params:
|
| 790 |
+
raise ValueError(
|
| 791 |
+
"If the `request` argument is set, then none of "
|
| 792 |
+
"the individual field arguments should be set."
|
| 793 |
+
)
|
| 794 |
+
|
| 795 |
+
# - Use the request object if provided (there's no risk of modifying the input as
|
| 796 |
+
# there are no flattened fields), or create one.
|
| 797 |
+
if not isinstance(request, cache_service.DeleteCachedContentRequest):
|
| 798 |
+
request = cache_service.DeleteCachedContentRequest(request)
|
| 799 |
+
|
| 800 |
+
# If we have keyword arguments corresponding to fields on the
|
| 801 |
+
# request, apply these.
|
| 802 |
+
if name is not None:
|
| 803 |
+
request.name = name
|
| 804 |
+
|
| 805 |
+
# Wrap the RPC method; this adds retry and timeout information,
|
| 806 |
+
# and friendly error handling.
|
| 807 |
+
rpc = self._client._transport._wrapped_methods[
|
| 808 |
+
self._client._transport.delete_cached_content
|
| 809 |
+
]
|
| 810 |
+
|
| 811 |
+
# Certain fields should be provided within the metadata header;
|
| 812 |
+
# add these here.
|
| 813 |
+
metadata = tuple(metadata) + (
|
| 814 |
+
gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
|
| 815 |
+
)
|
| 816 |
+
|
| 817 |
+
# Validate the universe domain.
|
| 818 |
+
self._client._validate_universe_domain()
|
| 819 |
+
|
| 820 |
+
# Send the request.
|
| 821 |
+
await rpc(
|
| 822 |
+
request,
|
| 823 |
+
retry=retry,
|
| 824 |
+
timeout=timeout,
|
| 825 |
+
metadata=metadata,
|
| 826 |
+
)
|
| 827 |
+
|
| 828 |
+
async def list_operations(
|
| 829 |
+
self,
|
| 830 |
+
request: Optional[operations_pb2.ListOperationsRequest] = None,
|
| 831 |
+
*,
|
| 832 |
+
retry: OptionalRetry = gapic_v1.method.DEFAULT,
|
| 833 |
+
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
|
| 834 |
+
metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
|
| 835 |
+
) -> operations_pb2.ListOperationsResponse:
|
| 836 |
+
r"""Lists operations that match the specified filter in the request.
|
| 837 |
+
|
| 838 |
+
Args:
|
| 839 |
+
request (:class:`~.operations_pb2.ListOperationsRequest`):
|
| 840 |
+
The request object. Request message for
|
| 841 |
+
`ListOperations` method.
|
| 842 |
+
retry (google.api_core.retry_async.AsyncRetry): Designation of what errors,
|
| 843 |
+
if any, should be retried.
|
| 844 |
+
timeout (float): The timeout for this request.
|
| 845 |
+
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
|
| 846 |
+
sent along with the request as metadata. Normally, each value must be of type `str`,
|
| 847 |
+
but for metadata keys ending with the suffix `-bin`, the corresponding values must
|
| 848 |
+
be of type `bytes`.
|
| 849 |
+
Returns:
|
| 850 |
+
~.operations_pb2.ListOperationsResponse:
|
| 851 |
+
Response message for ``ListOperations`` method.
|
| 852 |
+
"""
|
| 853 |
+
# Create or coerce a protobuf request object.
|
| 854 |
+
# The request isn't a proto-plus wrapped type,
|
| 855 |
+
# so it must be constructed via keyword expansion.
|
| 856 |
+
if isinstance(request, dict):
|
| 857 |
+
request = operations_pb2.ListOperationsRequest(**request)
|
| 858 |
+
|
| 859 |
+
# Wrap the RPC method; this adds retry and timeout information,
|
| 860 |
+
# and friendly error handling.
|
| 861 |
+
rpc = self.transport._wrapped_methods[self._client._transport.list_operations]
|
| 862 |
+
|
| 863 |
+
# Certain fields should be provided within the metadata header;
|
| 864 |
+
# add these here.
|
| 865 |
+
metadata = tuple(metadata) + (
|
| 866 |
+
gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
|
| 867 |
+
)
|
| 868 |
+
|
| 869 |
+
# Validate the universe domain.
|
| 870 |
+
self._client._validate_universe_domain()
|
| 871 |
+
|
| 872 |
+
# Send the request.
|
| 873 |
+
response = await rpc(
|
| 874 |
+
request,
|
| 875 |
+
retry=retry,
|
| 876 |
+
timeout=timeout,
|
| 877 |
+
metadata=metadata,
|
| 878 |
+
)
|
| 879 |
+
|
| 880 |
+
# Done; return the response.
|
| 881 |
+
return response
|
| 882 |
+
|
| 883 |
+
async def get_operation(
|
| 884 |
+
self,
|
| 885 |
+
request: Optional[operations_pb2.GetOperationRequest] = None,
|
| 886 |
+
*,
|
| 887 |
+
retry: OptionalRetry = gapic_v1.method.DEFAULT,
|
| 888 |
+
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
|
| 889 |
+
metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
|
| 890 |
+
) -> operations_pb2.Operation:
|
| 891 |
+
r"""Gets the latest state of a long-running operation.
|
| 892 |
+
|
| 893 |
+
Args:
|
| 894 |
+
request (:class:`~.operations_pb2.GetOperationRequest`):
|
| 895 |
+
The request object. Request message for
|
| 896 |
+
`GetOperation` method.
|
| 897 |
+
retry (google.api_core.retry_async.AsyncRetry): Designation of what errors,
|
| 898 |
+
if any, should be retried.
|
| 899 |
+
timeout (float): The timeout for this request.
|
| 900 |
+
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
|
| 901 |
+
sent along with the request as metadata. Normally, each value must be of type `str`,
|
| 902 |
+
but for metadata keys ending with the suffix `-bin`, the corresponding values must
|
| 903 |
+
be of type `bytes`.
|
| 904 |
+
Returns:
|
| 905 |
+
~.operations_pb2.Operation:
|
| 906 |
+
An ``Operation`` object.
|
| 907 |
+
"""
|
| 908 |
+
# Create or coerce a protobuf request object.
|
| 909 |
+
# The request isn't a proto-plus wrapped type,
|
| 910 |
+
# so it must be constructed via keyword expansion.
|
| 911 |
+
if isinstance(request, dict):
|
| 912 |
+
request = operations_pb2.GetOperationRequest(**request)
|
| 913 |
+
|
| 914 |
+
# Wrap the RPC method; this adds retry and timeout information,
|
| 915 |
+
# and friendly error handling.
|
| 916 |
+
rpc = self.transport._wrapped_methods[self._client._transport.get_operation]
|
| 917 |
+
|
| 918 |
+
# Certain fields should be provided within the metadata header;
|
| 919 |
+
# add these here.
|
| 920 |
+
metadata = tuple(metadata) + (
|
| 921 |
+
gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
|
| 922 |
+
)
|
| 923 |
+
|
| 924 |
+
# Validate the universe domain.
|
| 925 |
+
self._client._validate_universe_domain()
|
| 926 |
+
|
| 927 |
+
# Send the request.
|
| 928 |
+
response = await rpc(
|
| 929 |
+
request,
|
| 930 |
+
retry=retry,
|
| 931 |
+
timeout=timeout,
|
| 932 |
+
metadata=metadata,
|
| 933 |
+
)
|
| 934 |
+
|
| 935 |
+
# Done; return the response.
|
| 936 |
+
return response
|
| 937 |
+
|
| 938 |
+
async def __aenter__(self) -> "CacheServiceAsyncClient":
|
| 939 |
+
return self
|
| 940 |
+
|
| 941 |
+
async def __aexit__(self, exc_type, exc, tb):
|
| 942 |
+
await self.transport.close()
|
| 943 |
+
|
| 944 |
+
|
| 945 |
+
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
|
| 946 |
+
gapic_version=package_version.__version__
|
| 947 |
+
)
|
| 948 |
+
|
| 949 |
+
|
| 950 |
+
__all__ = ("CacheServiceAsyncClient",)
|
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/cache_service/client.py
ADDED
|
@@ -0,0 +1,1340 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Copyright 2024 Google LLC
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
#
|
| 16 |
+
from collections import OrderedDict
|
| 17 |
+
import logging as std_logging
|
| 18 |
+
import os
|
| 19 |
+
import re
|
| 20 |
+
from typing import (
|
| 21 |
+
Callable,
|
| 22 |
+
Dict,
|
| 23 |
+
Mapping,
|
| 24 |
+
MutableMapping,
|
| 25 |
+
MutableSequence,
|
| 26 |
+
Optional,
|
| 27 |
+
Sequence,
|
| 28 |
+
Tuple,
|
| 29 |
+
Type,
|
| 30 |
+
Union,
|
| 31 |
+
cast,
|
| 32 |
+
)
|
| 33 |
+
import warnings
|
| 34 |
+
|
| 35 |
+
from google.api_core import client_options as client_options_lib
|
| 36 |
+
from google.api_core import exceptions as core_exceptions
|
| 37 |
+
from google.api_core import gapic_v1
|
| 38 |
+
from google.api_core import retry as retries
|
| 39 |
+
from google.auth import credentials as ga_credentials # type: ignore
|
| 40 |
+
from google.auth.exceptions import MutualTLSChannelError # type: ignore
|
| 41 |
+
from google.auth.transport import mtls # type: ignore
|
| 42 |
+
from google.auth.transport.grpc import SslCredentials # type: ignore
|
| 43 |
+
from google.oauth2 import service_account # type: ignore
|
| 44 |
+
|
| 45 |
+
from google.ai.generativelanguage_v1beta import gapic_version as package_version
|
| 46 |
+
|
| 47 |
+
try:
|
| 48 |
+
OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None]
|
| 49 |
+
except AttributeError: # pragma: NO COVER
|
| 50 |
+
OptionalRetry = Union[retries.Retry, object, None] # type: ignore
|
| 51 |
+
|
| 52 |
+
try:
|
| 53 |
+
from google.api_core import client_logging # type: ignore
|
| 54 |
+
|
| 55 |
+
CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER
|
| 56 |
+
except ImportError: # pragma: NO COVER
|
| 57 |
+
CLIENT_LOGGING_SUPPORTED = False
|
| 58 |
+
|
| 59 |
+
_LOGGER = std_logging.getLogger(__name__)
|
| 60 |
+
|
| 61 |
+
from google.longrunning import operations_pb2 # type: ignore
|
| 62 |
+
from google.protobuf import duration_pb2 # type: ignore
|
| 63 |
+
from google.protobuf import field_mask_pb2 # type: ignore
|
| 64 |
+
from google.protobuf import timestamp_pb2 # type: ignore
|
| 65 |
+
|
| 66 |
+
from google.ai.generativelanguage_v1beta.services.cache_service import pagers
|
| 67 |
+
from google.ai.generativelanguage_v1beta.types import (
|
| 68 |
+
cached_content as gag_cached_content,
|
| 69 |
+
)
|
| 70 |
+
from google.ai.generativelanguage_v1beta.types import cache_service
|
| 71 |
+
from google.ai.generativelanguage_v1beta.types import cached_content
|
| 72 |
+
from google.ai.generativelanguage_v1beta.types import content
|
| 73 |
+
|
| 74 |
+
from .transports.base import DEFAULT_CLIENT_INFO, CacheServiceTransport
|
| 75 |
+
from .transports.grpc import CacheServiceGrpcTransport
|
| 76 |
+
from .transports.grpc_asyncio import CacheServiceGrpcAsyncIOTransport
|
| 77 |
+
from .transports.rest import CacheServiceRestTransport
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
class CacheServiceClientMeta(type):
|
| 81 |
+
"""Metaclass for the CacheService client.
|
| 82 |
+
|
| 83 |
+
This provides class-level methods for building and retrieving
|
| 84 |
+
support objects (e.g. transport) without polluting the client instance
|
| 85 |
+
objects.
|
| 86 |
+
"""
|
| 87 |
+
|
| 88 |
+
_transport_registry = OrderedDict() # type: Dict[str, Type[CacheServiceTransport]]
|
| 89 |
+
_transport_registry["grpc"] = CacheServiceGrpcTransport
|
| 90 |
+
_transport_registry["grpc_asyncio"] = CacheServiceGrpcAsyncIOTransport
|
| 91 |
+
_transport_registry["rest"] = CacheServiceRestTransport
|
| 92 |
+
|
| 93 |
+
def get_transport_class(
|
| 94 |
+
cls,
|
| 95 |
+
label: Optional[str] = None,
|
| 96 |
+
) -> Type[CacheServiceTransport]:
|
| 97 |
+
"""Returns an appropriate transport class.
|
| 98 |
+
|
| 99 |
+
Args:
|
| 100 |
+
label: The name of the desired transport. If none is
|
| 101 |
+
provided, then the first transport in the registry is used.
|
| 102 |
+
|
| 103 |
+
Returns:
|
| 104 |
+
The transport class to use.
|
| 105 |
+
"""
|
| 106 |
+
# If a specific transport is requested, return that one.
|
| 107 |
+
if label:
|
| 108 |
+
return cls._transport_registry[label]
|
| 109 |
+
|
| 110 |
+
# No transport is requested; return the default (that is, the first one
|
| 111 |
+
# in the dictionary).
|
| 112 |
+
return next(iter(cls._transport_registry.values()))
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
class CacheServiceClient(metaclass=CacheServiceClientMeta):
|
| 116 |
+
"""API for managing cache of content (CachedContent resources)
|
| 117 |
+
that can be used in GenerativeService requests. This way
|
| 118 |
+
generate content requests can benefit from preprocessing work
|
| 119 |
+
being done earlier, possibly lowering their computational cost.
|
| 120 |
+
It is intended to be used with large contexts.
|
| 121 |
+
"""
|
| 122 |
+
|
| 123 |
+
@staticmethod
|
| 124 |
+
def _get_default_mtls_endpoint(api_endpoint):
|
| 125 |
+
"""Converts api endpoint to mTLS endpoint.
|
| 126 |
+
|
| 127 |
+
Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to
|
| 128 |
+
"*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively.
|
| 129 |
+
Args:
|
| 130 |
+
api_endpoint (Optional[str]): the api endpoint to convert.
|
| 131 |
+
Returns:
|
| 132 |
+
str: converted mTLS api endpoint.
|
| 133 |
+
"""
|
| 134 |
+
if not api_endpoint:
|
| 135 |
+
return api_endpoint
|
| 136 |
+
|
| 137 |
+
mtls_endpoint_re = re.compile(
|
| 138 |
+
r"(?P<name>[^.]+)(?P<mtls>\.mtls)?(?P<sandbox>\.sandbox)?(?P<googledomain>\.googleapis\.com)?"
|
| 139 |
+
)
|
| 140 |
+
|
| 141 |
+
m = mtls_endpoint_re.match(api_endpoint)
|
| 142 |
+
name, mtls, sandbox, googledomain = m.groups()
|
| 143 |
+
if mtls or not googledomain:
|
| 144 |
+
return api_endpoint
|
| 145 |
+
|
| 146 |
+
if sandbox:
|
| 147 |
+
return api_endpoint.replace(
|
| 148 |
+
"sandbox.googleapis.com", "mtls.sandbox.googleapis.com"
|
| 149 |
+
)
|
| 150 |
+
|
| 151 |
+
return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com")
|
| 152 |
+
|
| 153 |
+
# Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead.
|
| 154 |
+
DEFAULT_ENDPOINT = "generativelanguage.googleapis.com"
|
| 155 |
+
DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore
|
| 156 |
+
DEFAULT_ENDPOINT
|
| 157 |
+
)
|
| 158 |
+
|
| 159 |
+
_DEFAULT_ENDPOINT_TEMPLATE = "generativelanguage.{UNIVERSE_DOMAIN}"
|
| 160 |
+
_DEFAULT_UNIVERSE = "googleapis.com"
|
| 161 |
+
|
| 162 |
+
@classmethod
|
| 163 |
+
def from_service_account_info(cls, info: dict, *args, **kwargs):
|
| 164 |
+
"""Creates an instance of this client using the provided credentials
|
| 165 |
+
info.
|
| 166 |
+
|
| 167 |
+
Args:
|
| 168 |
+
info (dict): The service account private key info.
|
| 169 |
+
args: Additional arguments to pass to the constructor.
|
| 170 |
+
kwargs: Additional arguments to pass to the constructor.
|
| 171 |
+
|
| 172 |
+
Returns:
|
| 173 |
+
CacheServiceClient: The constructed client.
|
| 174 |
+
"""
|
| 175 |
+
credentials = service_account.Credentials.from_service_account_info(info)
|
| 176 |
+
kwargs["credentials"] = credentials
|
| 177 |
+
return cls(*args, **kwargs)
|
| 178 |
+
|
| 179 |
+
@classmethod
|
| 180 |
+
def from_service_account_file(cls, filename: str, *args, **kwargs):
|
| 181 |
+
"""Creates an instance of this client using the provided credentials
|
| 182 |
+
file.
|
| 183 |
+
|
| 184 |
+
Args:
|
| 185 |
+
filename (str): The path to the service account private key json
|
| 186 |
+
file.
|
| 187 |
+
args: Additional arguments to pass to the constructor.
|
| 188 |
+
kwargs: Additional arguments to pass to the constructor.
|
| 189 |
+
|
| 190 |
+
Returns:
|
| 191 |
+
CacheServiceClient: The constructed client.
|
| 192 |
+
"""
|
| 193 |
+
credentials = service_account.Credentials.from_service_account_file(filename)
|
| 194 |
+
kwargs["credentials"] = credentials
|
| 195 |
+
return cls(*args, **kwargs)
|
| 196 |
+
|
| 197 |
+
from_service_account_json = from_service_account_file
|
| 198 |
+
|
| 199 |
+
@property
|
| 200 |
+
def transport(self) -> CacheServiceTransport:
|
| 201 |
+
"""Returns the transport used by the client instance.
|
| 202 |
+
|
| 203 |
+
Returns:
|
| 204 |
+
CacheServiceTransport: The transport used by the client
|
| 205 |
+
instance.
|
| 206 |
+
"""
|
| 207 |
+
return self._transport
|
| 208 |
+
|
| 209 |
+
@staticmethod
|
| 210 |
+
def cached_content_path(
|
| 211 |
+
id: str,
|
| 212 |
+
) -> str:
|
| 213 |
+
"""Returns a fully-qualified cached_content string."""
|
| 214 |
+
return "cachedContents/{id}".format(
|
| 215 |
+
id=id,
|
| 216 |
+
)
|
| 217 |
+
|
| 218 |
+
@staticmethod
|
| 219 |
+
def parse_cached_content_path(path: str) -> Dict[str, str]:
|
| 220 |
+
"""Parses a cached_content path into its component segments."""
|
| 221 |
+
m = re.match(r"^cachedContents/(?P<id>.+?)$", path)
|
| 222 |
+
return m.groupdict() if m else {}
|
| 223 |
+
|
| 224 |
+
@staticmethod
|
| 225 |
+
def model_path(
|
| 226 |
+
model: str,
|
| 227 |
+
) -> str:
|
| 228 |
+
"""Returns a fully-qualified model string."""
|
| 229 |
+
return "models/{model}".format(
|
| 230 |
+
model=model,
|
| 231 |
+
)
|
| 232 |
+
|
| 233 |
+
@staticmethod
|
| 234 |
+
def parse_model_path(path: str) -> Dict[str, str]:
|
| 235 |
+
"""Parses a model path into its component segments."""
|
| 236 |
+
m = re.match(r"^models/(?P<model>.+?)$", path)
|
| 237 |
+
return m.groupdict() if m else {}
|
| 238 |
+
|
| 239 |
+
@staticmethod
|
| 240 |
+
def common_billing_account_path(
|
| 241 |
+
billing_account: str,
|
| 242 |
+
) -> str:
|
| 243 |
+
"""Returns a fully-qualified billing_account string."""
|
| 244 |
+
return "billingAccounts/{billing_account}".format(
|
| 245 |
+
billing_account=billing_account,
|
| 246 |
+
)
|
| 247 |
+
|
| 248 |
+
@staticmethod
|
| 249 |
+
def parse_common_billing_account_path(path: str) -> Dict[str, str]:
|
| 250 |
+
"""Parse a billing_account path into its component segments."""
|
| 251 |
+
m = re.match(r"^billingAccounts/(?P<billing_account>.+?)$", path)
|
| 252 |
+
return m.groupdict() if m else {}
|
| 253 |
+
|
| 254 |
+
@staticmethod
|
| 255 |
+
def common_folder_path(
|
| 256 |
+
folder: str,
|
| 257 |
+
) -> str:
|
| 258 |
+
"""Returns a fully-qualified folder string."""
|
| 259 |
+
return "folders/{folder}".format(
|
| 260 |
+
folder=folder,
|
| 261 |
+
)
|
| 262 |
+
|
| 263 |
+
@staticmethod
|
| 264 |
+
def parse_common_folder_path(path: str) -> Dict[str, str]:
|
| 265 |
+
"""Parse a folder path into its component segments."""
|
| 266 |
+
m = re.match(r"^folders/(?P<folder>.+?)$", path)
|
| 267 |
+
return m.groupdict() if m else {}
|
| 268 |
+
|
| 269 |
+
@staticmethod
|
| 270 |
+
def common_organization_path(
|
| 271 |
+
organization: str,
|
| 272 |
+
) -> str:
|
| 273 |
+
"""Returns a fully-qualified organization string."""
|
| 274 |
+
return "organizations/{organization}".format(
|
| 275 |
+
organization=organization,
|
| 276 |
+
)
|
| 277 |
+
|
| 278 |
+
@staticmethod
|
| 279 |
+
def parse_common_organization_path(path: str) -> Dict[str, str]:
|
| 280 |
+
"""Parse a organization path into its component segments."""
|
| 281 |
+
m = re.match(r"^organizations/(?P<organization>.+?)$", path)
|
| 282 |
+
return m.groupdict() if m else {}
|
| 283 |
+
|
| 284 |
+
@staticmethod
|
| 285 |
+
def common_project_path(
|
| 286 |
+
project: str,
|
| 287 |
+
) -> str:
|
| 288 |
+
"""Returns a fully-qualified project string."""
|
| 289 |
+
return "projects/{project}".format(
|
| 290 |
+
project=project,
|
| 291 |
+
)
|
| 292 |
+
|
| 293 |
+
@staticmethod
|
| 294 |
+
def parse_common_project_path(path: str) -> Dict[str, str]:
|
| 295 |
+
"""Parse a project path into its component segments."""
|
| 296 |
+
m = re.match(r"^projects/(?P<project>.+?)$", path)
|
| 297 |
+
return m.groupdict() if m else {}
|
| 298 |
+
|
| 299 |
+
@staticmethod
|
| 300 |
+
def common_location_path(
|
| 301 |
+
project: str,
|
| 302 |
+
location: str,
|
| 303 |
+
) -> str:
|
| 304 |
+
"""Returns a fully-qualified location string."""
|
| 305 |
+
return "projects/{project}/locations/{location}".format(
|
| 306 |
+
project=project,
|
| 307 |
+
location=location,
|
| 308 |
+
)
|
| 309 |
+
|
| 310 |
+
@staticmethod
|
| 311 |
+
def parse_common_location_path(path: str) -> Dict[str, str]:
|
| 312 |
+
"""Parse a location path into its component segments."""
|
| 313 |
+
m = re.match(r"^projects/(?P<project>.+?)/locations/(?P<location>.+?)$", path)
|
| 314 |
+
return m.groupdict() if m else {}
|
| 315 |
+
|
| 316 |
+
@classmethod
|
| 317 |
+
def get_mtls_endpoint_and_cert_source(
|
| 318 |
+
cls, client_options: Optional[client_options_lib.ClientOptions] = None
|
| 319 |
+
):
|
| 320 |
+
"""Deprecated. Return the API endpoint and client cert source for mutual TLS.
|
| 321 |
+
|
| 322 |
+
The client cert source is determined in the following order:
|
| 323 |
+
(1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the
|
| 324 |
+
client cert source is None.
|
| 325 |
+
(2) if `client_options.client_cert_source` is provided, use the provided one; if the
|
| 326 |
+
default client cert source exists, use the default one; otherwise the client cert
|
| 327 |
+
source is None.
|
| 328 |
+
|
| 329 |
+
The API endpoint is determined in the following order:
|
| 330 |
+
(1) if `client_options.api_endpoint` if provided, use the provided one.
|
| 331 |
+
(2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the
|
| 332 |
+
default mTLS endpoint; if the environment variable is "never", use the default API
|
| 333 |
+
endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise
|
| 334 |
+
use the default API endpoint.
|
| 335 |
+
|
| 336 |
+
More details can be found at https://google.aip.dev/auth/4114.
|
| 337 |
+
|
| 338 |
+
Args:
|
| 339 |
+
client_options (google.api_core.client_options.ClientOptions): Custom options for the
|
| 340 |
+
client. Only the `api_endpoint` and `client_cert_source` properties may be used
|
| 341 |
+
in this method.
|
| 342 |
+
|
| 343 |
+
Returns:
|
| 344 |
+
Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the
|
| 345 |
+
client cert source to use.
|
| 346 |
+
|
| 347 |
+
Raises:
|
| 348 |
+
google.auth.exceptions.MutualTLSChannelError: If any errors happen.
|
| 349 |
+
"""
|
| 350 |
+
|
| 351 |
+
warnings.warn(
|
| 352 |
+
"get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.",
|
| 353 |
+
DeprecationWarning,
|
| 354 |
+
)
|
| 355 |
+
if client_options is None:
|
| 356 |
+
client_options = client_options_lib.ClientOptions()
|
| 357 |
+
use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false")
|
| 358 |
+
use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto")
|
| 359 |
+
if use_client_cert not in ("true", "false"):
|
| 360 |
+
raise ValueError(
|
| 361 |
+
"Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`"
|
| 362 |
+
)
|
| 363 |
+
if use_mtls_endpoint not in ("auto", "never", "always"):
|
| 364 |
+
raise MutualTLSChannelError(
|
| 365 |
+
"Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`"
|
| 366 |
+
)
|
| 367 |
+
|
| 368 |
+
# Figure out the client cert source to use.
|
| 369 |
+
client_cert_source = None
|
| 370 |
+
if use_client_cert == "true":
|
| 371 |
+
if client_options.client_cert_source:
|
| 372 |
+
client_cert_source = client_options.client_cert_source
|
| 373 |
+
elif mtls.has_default_client_cert_source():
|
| 374 |
+
client_cert_source = mtls.default_client_cert_source()
|
| 375 |
+
|
| 376 |
+
# Figure out which api endpoint to use.
|
| 377 |
+
if client_options.api_endpoint is not None:
|
| 378 |
+
api_endpoint = client_options.api_endpoint
|
| 379 |
+
elif use_mtls_endpoint == "always" or (
|
| 380 |
+
use_mtls_endpoint == "auto" and client_cert_source
|
| 381 |
+
):
|
| 382 |
+
api_endpoint = cls.DEFAULT_MTLS_ENDPOINT
|
| 383 |
+
else:
|
| 384 |
+
api_endpoint = cls.DEFAULT_ENDPOINT
|
| 385 |
+
|
| 386 |
+
return api_endpoint, client_cert_source
|
| 387 |
+
|
| 388 |
+
@staticmethod
|
| 389 |
+
def _read_environment_variables():
|
| 390 |
+
"""Returns the environment variables used by the client.
|
| 391 |
+
|
| 392 |
+
Returns:
|
| 393 |
+
Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE,
|
| 394 |
+
GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables.
|
| 395 |
+
|
| 396 |
+
Raises:
|
| 397 |
+
ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not
|
| 398 |
+
any of ["true", "false"].
|
| 399 |
+
google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT
|
| 400 |
+
is not any of ["auto", "never", "always"].
|
| 401 |
+
"""
|
| 402 |
+
use_client_cert = os.getenv(
|
| 403 |
+
"GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"
|
| 404 |
+
).lower()
|
| 405 |
+
use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower()
|
| 406 |
+
universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN")
|
| 407 |
+
if use_client_cert not in ("true", "false"):
|
| 408 |
+
raise ValueError(
|
| 409 |
+
"Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`"
|
| 410 |
+
)
|
| 411 |
+
if use_mtls_endpoint not in ("auto", "never", "always"):
|
| 412 |
+
raise MutualTLSChannelError(
|
| 413 |
+
"Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`"
|
| 414 |
+
)
|
| 415 |
+
return use_client_cert == "true", use_mtls_endpoint, universe_domain_env
|
| 416 |
+
|
| 417 |
+
@staticmethod
|
| 418 |
+
def _get_client_cert_source(provided_cert_source, use_cert_flag):
|
| 419 |
+
"""Return the client cert source to be used by the client.
|
| 420 |
+
|
| 421 |
+
Args:
|
| 422 |
+
provided_cert_source (bytes): The client certificate source provided.
|
| 423 |
+
use_cert_flag (bool): A flag indicating whether to use the client certificate.
|
| 424 |
+
|
| 425 |
+
Returns:
|
| 426 |
+
bytes or None: The client cert source to be used by the client.
|
| 427 |
+
"""
|
| 428 |
+
client_cert_source = None
|
| 429 |
+
if use_cert_flag:
|
| 430 |
+
if provided_cert_source:
|
| 431 |
+
client_cert_source = provided_cert_source
|
| 432 |
+
elif mtls.has_default_client_cert_source():
|
| 433 |
+
client_cert_source = mtls.default_client_cert_source()
|
| 434 |
+
return client_cert_source
|
| 435 |
+
|
| 436 |
+
@staticmethod
|
| 437 |
+
def _get_api_endpoint(
|
| 438 |
+
api_override, client_cert_source, universe_domain, use_mtls_endpoint
|
| 439 |
+
):
|
| 440 |
+
"""Return the API endpoint used by the client.
|
| 441 |
+
|
| 442 |
+
Args:
|
| 443 |
+
api_override (str): The API endpoint override. If specified, this is always
|
| 444 |
+
the return value of this function and the other arguments are not used.
|
| 445 |
+
client_cert_source (bytes): The client certificate source used by the client.
|
| 446 |
+
universe_domain (str): The universe domain used by the client.
|
| 447 |
+
use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters.
|
| 448 |
+
Possible values are "always", "auto", or "never".
|
| 449 |
+
|
| 450 |
+
Returns:
|
| 451 |
+
str: The API endpoint to be used by the client.
|
| 452 |
+
"""
|
| 453 |
+
if api_override is not None:
|
| 454 |
+
api_endpoint = api_override
|
| 455 |
+
elif use_mtls_endpoint == "always" or (
|
| 456 |
+
use_mtls_endpoint == "auto" and client_cert_source
|
| 457 |
+
):
|
| 458 |
+
_default_universe = CacheServiceClient._DEFAULT_UNIVERSE
|
| 459 |
+
if universe_domain != _default_universe:
|
| 460 |
+
raise MutualTLSChannelError(
|
| 461 |
+
f"mTLS is not supported in any universe other than {_default_universe}."
|
| 462 |
+
)
|
| 463 |
+
api_endpoint = CacheServiceClient.DEFAULT_MTLS_ENDPOINT
|
| 464 |
+
else:
|
| 465 |
+
api_endpoint = CacheServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(
|
| 466 |
+
UNIVERSE_DOMAIN=universe_domain
|
| 467 |
+
)
|
| 468 |
+
return api_endpoint
|
| 469 |
+
|
| 470 |
+
@staticmethod
|
| 471 |
+
def _get_universe_domain(
|
| 472 |
+
client_universe_domain: Optional[str], universe_domain_env: Optional[str]
|
| 473 |
+
) -> str:
|
| 474 |
+
"""Return the universe domain used by the client.
|
| 475 |
+
|
| 476 |
+
Args:
|
| 477 |
+
client_universe_domain (Optional[str]): The universe domain configured via the client options.
|
| 478 |
+
universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable.
|
| 479 |
+
|
| 480 |
+
Returns:
|
| 481 |
+
str: The universe domain to be used by the client.
|
| 482 |
+
|
| 483 |
+
Raises:
|
| 484 |
+
ValueError: If the universe domain is an empty string.
|
| 485 |
+
"""
|
| 486 |
+
universe_domain = CacheServiceClient._DEFAULT_UNIVERSE
|
| 487 |
+
if client_universe_domain is not None:
|
| 488 |
+
universe_domain = client_universe_domain
|
| 489 |
+
elif universe_domain_env is not None:
|
| 490 |
+
universe_domain = universe_domain_env
|
| 491 |
+
if len(universe_domain.strip()) == 0:
|
| 492 |
+
raise ValueError("Universe Domain cannot be an empty string.")
|
| 493 |
+
return universe_domain
|
| 494 |
+
|
| 495 |
+
def _validate_universe_domain(self):
|
| 496 |
+
"""Validates client's and credentials' universe domains are consistent.
|
| 497 |
+
|
| 498 |
+
Returns:
|
| 499 |
+
bool: True iff the configured universe domain is valid.
|
| 500 |
+
|
| 501 |
+
Raises:
|
| 502 |
+
ValueError: If the configured universe domain is not valid.
|
| 503 |
+
"""
|
| 504 |
+
|
| 505 |
+
# NOTE (b/349488459): universe validation is disabled until further notice.
|
| 506 |
+
return True
|
| 507 |
+
|
| 508 |
+
@property
|
| 509 |
+
def api_endpoint(self):
|
| 510 |
+
"""Return the API endpoint used by the client instance.
|
| 511 |
+
|
| 512 |
+
Returns:
|
| 513 |
+
str: The API endpoint used by the client instance.
|
| 514 |
+
"""
|
| 515 |
+
return self._api_endpoint
|
| 516 |
+
|
| 517 |
+
@property
|
| 518 |
+
def universe_domain(self) -> str:
|
| 519 |
+
"""Return the universe domain used by the client instance.
|
| 520 |
+
|
| 521 |
+
Returns:
|
| 522 |
+
str: The universe domain used by the client instance.
|
| 523 |
+
"""
|
| 524 |
+
return self._universe_domain
|
| 525 |
+
|
| 526 |
+
def __init__(
|
| 527 |
+
self,
|
| 528 |
+
*,
|
| 529 |
+
credentials: Optional[ga_credentials.Credentials] = None,
|
| 530 |
+
transport: Optional[
|
| 531 |
+
Union[str, CacheServiceTransport, Callable[..., CacheServiceTransport]]
|
| 532 |
+
] = None,
|
| 533 |
+
client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None,
|
| 534 |
+
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
|
| 535 |
+
) -> None:
|
| 536 |
+
"""Instantiates the cache service client.
|
| 537 |
+
|
| 538 |
+
Args:
|
| 539 |
+
credentials (Optional[google.auth.credentials.Credentials]): The
|
| 540 |
+
authorization credentials to attach to requests. These
|
| 541 |
+
credentials identify the application to the service; if none
|
| 542 |
+
are specified, the client will attempt to ascertain the
|
| 543 |
+
credentials from the environment.
|
| 544 |
+
transport (Optional[Union[str,CacheServiceTransport,Callable[..., CacheServiceTransport]]]):
|
| 545 |
+
The transport to use, or a Callable that constructs and returns a new transport.
|
| 546 |
+
If a Callable is given, it will be called with the same set of initialization
|
| 547 |
+
arguments as used in the CacheServiceTransport constructor.
|
| 548 |
+
If set to None, a transport is chosen automatically.
|
| 549 |
+
client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]):
|
| 550 |
+
Custom options for the client.
|
| 551 |
+
|
| 552 |
+
1. The ``api_endpoint`` property can be used to override the
|
| 553 |
+
default endpoint provided by the client when ``transport`` is
|
| 554 |
+
not explicitly provided. Only if this property is not set and
|
| 555 |
+
``transport`` was not explicitly provided, the endpoint is
|
| 556 |
+
determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment
|
| 557 |
+
variable, which have one of the following values:
|
| 558 |
+
"always" (always use the default mTLS endpoint), "never" (always
|
| 559 |
+
use the default regular endpoint) and "auto" (auto-switch to the
|
| 560 |
+
default mTLS endpoint if client certificate is present; this is
|
| 561 |
+
the default value).
|
| 562 |
+
|
| 563 |
+
2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable
|
| 564 |
+
is "true", then the ``client_cert_source`` property can be used
|
| 565 |
+
to provide a client certificate for mTLS transport. If
|
| 566 |
+
not provided, the default SSL client certificate will be used if
|
| 567 |
+
present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not
|
| 568 |
+
set, no client certificate will be used.
|
| 569 |
+
|
| 570 |
+
3. The ``universe_domain`` property can be used to override the
|
| 571 |
+
default "googleapis.com" universe. Note that the ``api_endpoint``
|
| 572 |
+
property still takes precedence; and ``universe_domain`` is
|
| 573 |
+
currently not supported for mTLS.
|
| 574 |
+
|
| 575 |
+
client_info (google.api_core.gapic_v1.client_info.ClientInfo):
|
| 576 |
+
The client info used to send a user-agent string along with
|
| 577 |
+
API requests. If ``None``, then default info will be used.
|
| 578 |
+
Generally, you only need to set this if you're developing
|
| 579 |
+
your own client library.
|
| 580 |
+
|
| 581 |
+
Raises:
|
| 582 |
+
google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
|
| 583 |
+
creation failed for any reason.
|
| 584 |
+
"""
|
| 585 |
+
self._client_options = client_options
|
| 586 |
+
if isinstance(self._client_options, dict):
|
| 587 |
+
self._client_options = client_options_lib.from_dict(self._client_options)
|
| 588 |
+
if self._client_options is None:
|
| 589 |
+
self._client_options = client_options_lib.ClientOptions()
|
| 590 |
+
self._client_options = cast(
|
| 591 |
+
client_options_lib.ClientOptions, self._client_options
|
| 592 |
+
)
|
| 593 |
+
|
| 594 |
+
universe_domain_opt = getattr(self._client_options, "universe_domain", None)
|
| 595 |
+
|
| 596 |
+
(
|
| 597 |
+
self._use_client_cert,
|
| 598 |
+
self._use_mtls_endpoint,
|
| 599 |
+
self._universe_domain_env,
|
| 600 |
+
) = CacheServiceClient._read_environment_variables()
|
| 601 |
+
self._client_cert_source = CacheServiceClient._get_client_cert_source(
|
| 602 |
+
self._client_options.client_cert_source, self._use_client_cert
|
| 603 |
+
)
|
| 604 |
+
self._universe_domain = CacheServiceClient._get_universe_domain(
|
| 605 |
+
universe_domain_opt, self._universe_domain_env
|
| 606 |
+
)
|
| 607 |
+
self._api_endpoint = None # updated below, depending on `transport`
|
| 608 |
+
|
| 609 |
+
# Initialize the universe domain validation.
|
| 610 |
+
self._is_universe_domain_valid = False
|
| 611 |
+
|
| 612 |
+
if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER
|
| 613 |
+
# Setup logging.
|
| 614 |
+
client_logging.initialize_logging()
|
| 615 |
+
|
| 616 |
+
api_key_value = getattr(self._client_options, "api_key", None)
|
| 617 |
+
if api_key_value and credentials:
|
| 618 |
+
raise ValueError(
|
| 619 |
+
"client_options.api_key and credentials are mutually exclusive"
|
| 620 |
+
)
|
| 621 |
+
|
| 622 |
+
# Save or instantiate the transport.
|
| 623 |
+
# Ordinarily, we provide the transport, but allowing a custom transport
|
| 624 |
+
# instance provides an extensibility point for unusual situations.
|
| 625 |
+
transport_provided = isinstance(transport, CacheServiceTransport)
|
| 626 |
+
if transport_provided:
|
| 627 |
+
# transport is a CacheServiceTransport instance.
|
| 628 |
+
if credentials or self._client_options.credentials_file or api_key_value:
|
| 629 |
+
raise ValueError(
|
| 630 |
+
"When providing a transport instance, "
|
| 631 |
+
"provide its credentials directly."
|
| 632 |
+
)
|
| 633 |
+
if self._client_options.scopes:
|
| 634 |
+
raise ValueError(
|
| 635 |
+
"When providing a transport instance, provide its scopes "
|
| 636 |
+
"directly."
|
| 637 |
+
)
|
| 638 |
+
self._transport = cast(CacheServiceTransport, transport)
|
| 639 |
+
self._api_endpoint = self._transport.host
|
| 640 |
+
|
| 641 |
+
self._api_endpoint = self._api_endpoint or CacheServiceClient._get_api_endpoint(
|
| 642 |
+
self._client_options.api_endpoint,
|
| 643 |
+
self._client_cert_source,
|
| 644 |
+
self._universe_domain,
|
| 645 |
+
self._use_mtls_endpoint,
|
| 646 |
+
)
|
| 647 |
+
|
| 648 |
+
if not transport_provided:
|
| 649 |
+
import google.auth._default # type: ignore
|
| 650 |
+
|
| 651 |
+
if api_key_value and hasattr(
|
| 652 |
+
google.auth._default, "get_api_key_credentials"
|
| 653 |
+
):
|
| 654 |
+
credentials = google.auth._default.get_api_key_credentials(
|
| 655 |
+
api_key_value
|
| 656 |
+
)
|
| 657 |
+
|
| 658 |
+
transport_init: Union[
|
| 659 |
+
Type[CacheServiceTransport], Callable[..., CacheServiceTransport]
|
| 660 |
+
] = (
|
| 661 |
+
CacheServiceClient.get_transport_class(transport)
|
| 662 |
+
if isinstance(transport, str) or transport is None
|
| 663 |
+
else cast(Callable[..., CacheServiceTransport], transport)
|
| 664 |
+
)
|
| 665 |
+
# initialize with the provided callable or the passed in class
|
| 666 |
+
self._transport = transport_init(
|
| 667 |
+
credentials=credentials,
|
| 668 |
+
credentials_file=self._client_options.credentials_file,
|
| 669 |
+
host=self._api_endpoint,
|
| 670 |
+
scopes=self._client_options.scopes,
|
| 671 |
+
client_cert_source_for_mtls=self._client_cert_source,
|
| 672 |
+
quota_project_id=self._client_options.quota_project_id,
|
| 673 |
+
client_info=client_info,
|
| 674 |
+
always_use_jwt_access=True,
|
| 675 |
+
api_audience=self._client_options.api_audience,
|
| 676 |
+
)
|
| 677 |
+
|
| 678 |
+
if "async" not in str(self._transport):
|
| 679 |
+
if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
|
| 680 |
+
std_logging.DEBUG
|
| 681 |
+
): # pragma: NO COVER
|
| 682 |
+
_LOGGER.debug(
|
| 683 |
+
"Created client `google.ai.generativelanguage_v1beta.CacheServiceClient`.",
|
| 684 |
+
extra={
|
| 685 |
+
"serviceName": "google.ai.generativelanguage.v1beta.CacheService",
|
| 686 |
+
"universeDomain": getattr(
|
| 687 |
+
self._transport._credentials, "universe_domain", ""
|
| 688 |
+
),
|
| 689 |
+
"credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}",
|
| 690 |
+
"credentialsInfo": getattr(
|
| 691 |
+
self.transport._credentials, "get_cred_info", lambda: None
|
| 692 |
+
)(),
|
| 693 |
+
}
|
| 694 |
+
if hasattr(self._transport, "_credentials")
|
| 695 |
+
else {
|
| 696 |
+
"serviceName": "google.ai.generativelanguage.v1beta.CacheService",
|
| 697 |
+
"credentialsType": None,
|
| 698 |
+
},
|
| 699 |
+
)
|
| 700 |
+
|
| 701 |
+
def list_cached_contents(
|
| 702 |
+
self,
|
| 703 |
+
request: Optional[Union[cache_service.ListCachedContentsRequest, dict]] = None,
|
| 704 |
+
*,
|
| 705 |
+
retry: OptionalRetry = gapic_v1.method.DEFAULT,
|
| 706 |
+
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
|
| 707 |
+
metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
|
| 708 |
+
) -> pagers.ListCachedContentsPager:
|
| 709 |
+
r"""Lists CachedContents.
|
| 710 |
+
|
| 711 |
+
.. code-block:: python
|
| 712 |
+
|
| 713 |
+
# This snippet has been automatically generated and should be regarded as a
|
| 714 |
+
# code template only.
|
| 715 |
+
# It will require modifications to work:
|
| 716 |
+
# - It may require correct/in-range values for request initialization.
|
| 717 |
+
# - It may require specifying regional endpoints when creating the service
|
| 718 |
+
# client as shown in:
|
| 719 |
+
# https://googleapis.dev/python/google-api-core/latest/client_options.html
|
| 720 |
+
from google.ai import generativelanguage_v1beta
|
| 721 |
+
|
| 722 |
+
def sample_list_cached_contents():
|
| 723 |
+
# Create a client
|
| 724 |
+
client = generativelanguage_v1beta.CacheServiceClient()
|
| 725 |
+
|
| 726 |
+
# Initialize request argument(s)
|
| 727 |
+
request = generativelanguage_v1beta.ListCachedContentsRequest(
|
| 728 |
+
)
|
| 729 |
+
|
| 730 |
+
# Make the request
|
| 731 |
+
page_result = client.list_cached_contents(request=request)
|
| 732 |
+
|
| 733 |
+
# Handle the response
|
| 734 |
+
for response in page_result:
|
| 735 |
+
print(response)
|
| 736 |
+
|
| 737 |
+
Args:
|
| 738 |
+
request (Union[google.ai.generativelanguage_v1beta.types.ListCachedContentsRequest, dict]):
|
| 739 |
+
The request object. Request to list CachedContents.
|
| 740 |
+
retry (google.api_core.retry.Retry): Designation of what errors, if any,
|
| 741 |
+
should be retried.
|
| 742 |
+
timeout (float): The timeout for this request.
|
| 743 |
+
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
|
| 744 |
+
sent along with the request as metadata. Normally, each value must be of type `str`,
|
| 745 |
+
but for metadata keys ending with the suffix `-bin`, the corresponding values must
|
| 746 |
+
be of type `bytes`.
|
| 747 |
+
|
| 748 |
+
Returns:
|
| 749 |
+
google.ai.generativelanguage_v1beta.services.cache_service.pagers.ListCachedContentsPager:
|
| 750 |
+
Response with CachedContents list.
|
| 751 |
+
|
| 752 |
+
Iterating over this object will yield
|
| 753 |
+
results and resolve additional pages
|
| 754 |
+
automatically.
|
| 755 |
+
|
| 756 |
+
"""
|
| 757 |
+
# Create or coerce a protobuf request object.
|
| 758 |
+
# - Use the request object if provided (there's no risk of modifying the input as
|
| 759 |
+
# there are no flattened fields), or create one.
|
| 760 |
+
if not isinstance(request, cache_service.ListCachedContentsRequest):
|
| 761 |
+
request = cache_service.ListCachedContentsRequest(request)
|
| 762 |
+
|
| 763 |
+
# Wrap the RPC method; this adds retry and timeout information,
|
| 764 |
+
# and friendly error handling.
|
| 765 |
+
rpc = self._transport._wrapped_methods[self._transport.list_cached_contents]
|
| 766 |
+
|
| 767 |
+
# Validate the universe domain.
|
| 768 |
+
self._validate_universe_domain()
|
| 769 |
+
|
| 770 |
+
# Send the request.
|
| 771 |
+
response = rpc(
|
| 772 |
+
request,
|
| 773 |
+
retry=retry,
|
| 774 |
+
timeout=timeout,
|
| 775 |
+
metadata=metadata,
|
| 776 |
+
)
|
| 777 |
+
|
| 778 |
+
# This method is paged; wrap the response in a pager, which provides
|
| 779 |
+
# an `__iter__` convenience method.
|
| 780 |
+
response = pagers.ListCachedContentsPager(
|
| 781 |
+
method=rpc,
|
| 782 |
+
request=request,
|
| 783 |
+
response=response,
|
| 784 |
+
retry=retry,
|
| 785 |
+
timeout=timeout,
|
| 786 |
+
metadata=metadata,
|
| 787 |
+
)
|
| 788 |
+
|
| 789 |
+
# Done; return the response.
|
| 790 |
+
return response
|
| 791 |
+
|
| 792 |
+
def create_cached_content(
|
| 793 |
+
self,
|
| 794 |
+
request: Optional[Union[cache_service.CreateCachedContentRequest, dict]] = None,
|
| 795 |
+
*,
|
| 796 |
+
cached_content: Optional[gag_cached_content.CachedContent] = None,
|
| 797 |
+
retry: OptionalRetry = gapic_v1.method.DEFAULT,
|
| 798 |
+
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
|
| 799 |
+
metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
|
| 800 |
+
) -> gag_cached_content.CachedContent:
|
| 801 |
+
r"""Creates CachedContent resource.
|
| 802 |
+
|
| 803 |
+
.. code-block:: python
|
| 804 |
+
|
| 805 |
+
# This snippet has been automatically generated and should be regarded as a
|
| 806 |
+
# code template only.
|
| 807 |
+
# It will require modifications to work:
|
| 808 |
+
# - It may require correct/in-range values for request initialization.
|
| 809 |
+
# - It may require specifying regional endpoints when creating the service
|
| 810 |
+
# client as shown in:
|
| 811 |
+
# https://googleapis.dev/python/google-api-core/latest/client_options.html
|
| 812 |
+
from google.ai import generativelanguage_v1beta
|
| 813 |
+
|
| 814 |
+
def sample_create_cached_content():
|
| 815 |
+
# Create a client
|
| 816 |
+
client = generativelanguage_v1beta.CacheServiceClient()
|
| 817 |
+
|
| 818 |
+
# Initialize request argument(s)
|
| 819 |
+
request = generativelanguage_v1beta.CreateCachedContentRequest(
|
| 820 |
+
)
|
| 821 |
+
|
| 822 |
+
# Make the request
|
| 823 |
+
response = client.create_cached_content(request=request)
|
| 824 |
+
|
| 825 |
+
# Handle the response
|
| 826 |
+
print(response)
|
| 827 |
+
|
| 828 |
+
Args:
|
| 829 |
+
request (Union[google.ai.generativelanguage_v1beta.types.CreateCachedContentRequest, dict]):
|
| 830 |
+
The request object. Request to create CachedContent.
|
| 831 |
+
cached_content (google.ai.generativelanguage_v1beta.types.CachedContent):
|
| 832 |
+
Required. The cached content to
|
| 833 |
+
create.
|
| 834 |
+
|
| 835 |
+
This corresponds to the ``cached_content`` field
|
| 836 |
+
on the ``request`` instance; if ``request`` is provided, this
|
| 837 |
+
should not be set.
|
| 838 |
+
retry (google.api_core.retry.Retry): Designation of what errors, if any,
|
| 839 |
+
should be retried.
|
| 840 |
+
timeout (float): The timeout for this request.
|
| 841 |
+
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
|
| 842 |
+
sent along with the request as metadata. Normally, each value must be of type `str`,
|
| 843 |
+
but for metadata keys ending with the suffix `-bin`, the corresponding values must
|
| 844 |
+
be of type `bytes`.
|
| 845 |
+
|
| 846 |
+
Returns:
|
| 847 |
+
google.ai.generativelanguage_v1beta.types.CachedContent:
|
| 848 |
+
Content that has been preprocessed
|
| 849 |
+
and can be used in subsequent request to
|
| 850 |
+
GenerativeService.
|
| 851 |
+
|
| 852 |
+
Cached content can be only used with
|
| 853 |
+
model it was created for.
|
| 854 |
+
|
| 855 |
+
"""
|
| 856 |
+
# Create or coerce a protobuf request object.
|
| 857 |
+
# - Quick check: If we got a request object, we should *not* have
|
| 858 |
+
# gotten any keyword arguments that map to the request.
|
| 859 |
+
has_flattened_params = any([cached_content])
|
| 860 |
+
if request is not None and has_flattened_params:
|
| 861 |
+
raise ValueError(
|
| 862 |
+
"If the `request` argument is set, then none of "
|
| 863 |
+
"the individual field arguments should be set."
|
| 864 |
+
)
|
| 865 |
+
|
| 866 |
+
# - Use the request object if provided (there's no risk of modifying the input as
|
| 867 |
+
# there are no flattened fields), or create one.
|
| 868 |
+
if not isinstance(request, cache_service.CreateCachedContentRequest):
|
| 869 |
+
request = cache_service.CreateCachedContentRequest(request)
|
| 870 |
+
# If we have keyword arguments corresponding to fields on the
|
| 871 |
+
# request, apply these.
|
| 872 |
+
if cached_content is not None:
|
| 873 |
+
request.cached_content = cached_content
|
| 874 |
+
|
| 875 |
+
# Wrap the RPC method; this adds retry and timeout information,
|
| 876 |
+
# and friendly error handling.
|
| 877 |
+
rpc = self._transport._wrapped_methods[self._transport.create_cached_content]
|
| 878 |
+
|
| 879 |
+
# Validate the universe domain.
|
| 880 |
+
self._validate_universe_domain()
|
| 881 |
+
|
| 882 |
+
# Send the request.
|
| 883 |
+
response = rpc(
|
| 884 |
+
request,
|
| 885 |
+
retry=retry,
|
| 886 |
+
timeout=timeout,
|
| 887 |
+
metadata=metadata,
|
| 888 |
+
)
|
| 889 |
+
|
| 890 |
+
# Done; return the response.
|
| 891 |
+
return response
|
| 892 |
+
|
| 893 |
+
def get_cached_content(
|
| 894 |
+
self,
|
| 895 |
+
request: Optional[Union[cache_service.GetCachedContentRequest, dict]] = None,
|
| 896 |
+
*,
|
| 897 |
+
name: Optional[str] = None,
|
| 898 |
+
retry: OptionalRetry = gapic_v1.method.DEFAULT,
|
| 899 |
+
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
|
| 900 |
+
metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
|
| 901 |
+
) -> cached_content.CachedContent:
|
| 902 |
+
r"""Reads CachedContent resource.
|
| 903 |
+
|
| 904 |
+
.. code-block:: python
|
| 905 |
+
|
| 906 |
+
# This snippet has been automatically generated and should be regarded as a
|
| 907 |
+
# code template only.
|
| 908 |
+
# It will require modifications to work:
|
| 909 |
+
# - It may require correct/in-range values for request initialization.
|
| 910 |
+
# - It may require specifying regional endpoints when creating the service
|
| 911 |
+
# client as shown in:
|
| 912 |
+
# https://googleapis.dev/python/google-api-core/latest/client_options.html
|
| 913 |
+
from google.ai import generativelanguage_v1beta
|
| 914 |
+
|
| 915 |
+
def sample_get_cached_content():
|
| 916 |
+
# Create a client
|
| 917 |
+
client = generativelanguage_v1beta.CacheServiceClient()
|
| 918 |
+
|
| 919 |
+
# Initialize request argument(s)
|
| 920 |
+
request = generativelanguage_v1beta.GetCachedContentRequest(
|
| 921 |
+
name="name_value",
|
| 922 |
+
)
|
| 923 |
+
|
| 924 |
+
# Make the request
|
| 925 |
+
response = client.get_cached_content(request=request)
|
| 926 |
+
|
| 927 |
+
# Handle the response
|
| 928 |
+
print(response)
|
| 929 |
+
|
| 930 |
+
Args:
|
| 931 |
+
request (Union[google.ai.generativelanguage_v1beta.types.GetCachedContentRequest, dict]):
|
| 932 |
+
The request object. Request to read CachedContent.
|
| 933 |
+
name (str):
|
| 934 |
+
Required. The resource name referring to the content
|
| 935 |
+
cache entry. Format: ``cachedContents/{id}``
|
| 936 |
+
|
| 937 |
+
This corresponds to the ``name`` field
|
| 938 |
+
on the ``request`` instance; if ``request`` is provided, this
|
| 939 |
+
should not be set.
|
| 940 |
+
retry (google.api_core.retry.Retry): Designation of what errors, if any,
|
| 941 |
+
should be retried.
|
| 942 |
+
timeout (float): The timeout for this request.
|
| 943 |
+
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
|
| 944 |
+
sent along with the request as metadata. Normally, each value must be of type `str`,
|
| 945 |
+
but for metadata keys ending with the suffix `-bin`, the corresponding values must
|
| 946 |
+
be of type `bytes`.
|
| 947 |
+
|
| 948 |
+
Returns:
|
| 949 |
+
google.ai.generativelanguage_v1beta.types.CachedContent:
|
| 950 |
+
Content that has been preprocessed
|
| 951 |
+
and can be used in subsequent request to
|
| 952 |
+
GenerativeService.
|
| 953 |
+
|
| 954 |
+
Cached content can be only used with
|
| 955 |
+
model it was created for.
|
| 956 |
+
|
| 957 |
+
"""
|
| 958 |
+
# Create or coerce a protobuf request object.
|
| 959 |
+
# - Quick check: If we got a request object, we should *not* have
|
| 960 |
+
# gotten any keyword arguments that map to the request.
|
| 961 |
+
has_flattened_params = any([name])
|
| 962 |
+
if request is not None and has_flattened_params:
|
| 963 |
+
raise ValueError(
|
| 964 |
+
"If the `request` argument is set, then none of "
|
| 965 |
+
"the individual field arguments should be set."
|
| 966 |
+
)
|
| 967 |
+
|
| 968 |
+
# - Use the request object if provided (there's no risk of modifying the input as
|
| 969 |
+
# there are no flattened fields), or create one.
|
| 970 |
+
if not isinstance(request, cache_service.GetCachedContentRequest):
|
| 971 |
+
request = cache_service.GetCachedContentRequest(request)
|
| 972 |
+
# If we have keyword arguments corresponding to fields on the
|
| 973 |
+
# request, apply these.
|
| 974 |
+
if name is not None:
|
| 975 |
+
request.name = name
|
| 976 |
+
|
| 977 |
+
# Wrap the RPC method; this adds retry and timeout information,
|
| 978 |
+
# and friendly error handling.
|
| 979 |
+
rpc = self._transport._wrapped_methods[self._transport.get_cached_content]
|
| 980 |
+
|
| 981 |
+
# Certain fields should be provided within the metadata header;
|
| 982 |
+
# add these here.
|
| 983 |
+
metadata = tuple(metadata) + (
|
| 984 |
+
gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
|
| 985 |
+
)
|
| 986 |
+
|
| 987 |
+
# Validate the universe domain.
|
| 988 |
+
self._validate_universe_domain()
|
| 989 |
+
|
| 990 |
+
# Send the request.
|
| 991 |
+
response = rpc(
|
| 992 |
+
request,
|
| 993 |
+
retry=retry,
|
| 994 |
+
timeout=timeout,
|
| 995 |
+
metadata=metadata,
|
| 996 |
+
)
|
| 997 |
+
|
| 998 |
+
# Done; return the response.
|
| 999 |
+
return response
|
| 1000 |
+
|
| 1001 |
+
def update_cached_content(
|
| 1002 |
+
self,
|
| 1003 |
+
request: Optional[Union[cache_service.UpdateCachedContentRequest, dict]] = None,
|
| 1004 |
+
*,
|
| 1005 |
+
cached_content: Optional[gag_cached_content.CachedContent] = None,
|
| 1006 |
+
update_mask: Optional[field_mask_pb2.FieldMask] = None,
|
| 1007 |
+
retry: OptionalRetry = gapic_v1.method.DEFAULT,
|
| 1008 |
+
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
|
| 1009 |
+
metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
|
| 1010 |
+
) -> gag_cached_content.CachedContent:
|
| 1011 |
+
r"""Updates CachedContent resource (only expiration is
|
| 1012 |
+
updatable).
|
| 1013 |
+
|
| 1014 |
+
.. code-block:: python
|
| 1015 |
+
|
| 1016 |
+
# This snippet has been automatically generated and should be regarded as a
|
| 1017 |
+
# code template only.
|
| 1018 |
+
# It will require modifications to work:
|
| 1019 |
+
# - It may require correct/in-range values for request initialization.
|
| 1020 |
+
# - It may require specifying regional endpoints when creating the service
|
| 1021 |
+
# client as shown in:
|
| 1022 |
+
# https://googleapis.dev/python/google-api-core/latest/client_options.html
|
| 1023 |
+
from google.ai import generativelanguage_v1beta
|
| 1024 |
+
|
| 1025 |
+
def sample_update_cached_content():
|
| 1026 |
+
# Create a client
|
| 1027 |
+
client = generativelanguage_v1beta.CacheServiceClient()
|
| 1028 |
+
|
| 1029 |
+
# Initialize request argument(s)
|
| 1030 |
+
request = generativelanguage_v1beta.UpdateCachedContentRequest(
|
| 1031 |
+
)
|
| 1032 |
+
|
| 1033 |
+
# Make the request
|
| 1034 |
+
response = client.update_cached_content(request=request)
|
| 1035 |
+
|
| 1036 |
+
# Handle the response
|
| 1037 |
+
print(response)
|
| 1038 |
+
|
| 1039 |
+
Args:
|
| 1040 |
+
request (Union[google.ai.generativelanguage_v1beta.types.UpdateCachedContentRequest, dict]):
|
| 1041 |
+
The request object. Request to update CachedContent.
|
| 1042 |
+
cached_content (google.ai.generativelanguage_v1beta.types.CachedContent):
|
| 1043 |
+
Required. The content cache entry to
|
| 1044 |
+
update
|
| 1045 |
+
|
| 1046 |
+
This corresponds to the ``cached_content`` field
|
| 1047 |
+
on the ``request`` instance; if ``request`` is provided, this
|
| 1048 |
+
should not be set.
|
| 1049 |
+
update_mask (google.protobuf.field_mask_pb2.FieldMask):
|
| 1050 |
+
The list of fields to update.
|
| 1051 |
+
This corresponds to the ``update_mask`` field
|
| 1052 |
+
on the ``request`` instance; if ``request`` is provided, this
|
| 1053 |
+
should not be set.
|
| 1054 |
+
retry (google.api_core.retry.Retry): Designation of what errors, if any,
|
| 1055 |
+
should be retried.
|
| 1056 |
+
timeout (float): The timeout for this request.
|
| 1057 |
+
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
|
| 1058 |
+
sent along with the request as metadata. Normally, each value must be of type `str`,
|
| 1059 |
+
but for metadata keys ending with the suffix `-bin`, the corresponding values must
|
| 1060 |
+
be of type `bytes`.
|
| 1061 |
+
|
| 1062 |
+
Returns:
|
| 1063 |
+
google.ai.generativelanguage_v1beta.types.CachedContent:
|
| 1064 |
+
Content that has been preprocessed
|
| 1065 |
+
and can be used in subsequent request to
|
| 1066 |
+
GenerativeService.
|
| 1067 |
+
|
| 1068 |
+
Cached content can be only used with
|
| 1069 |
+
model it was created for.
|
| 1070 |
+
|
| 1071 |
+
"""
|
| 1072 |
+
# Create or coerce a protobuf request object.
|
| 1073 |
+
# - Quick check: If we got a request object, we should *not* have
|
| 1074 |
+
# gotten any keyword arguments that map to the request.
|
| 1075 |
+
has_flattened_params = any([cached_content, update_mask])
|
| 1076 |
+
if request is not None and has_flattened_params:
|
| 1077 |
+
raise ValueError(
|
| 1078 |
+
"If the `request` argument is set, then none of "
|
| 1079 |
+
"the individual field arguments should be set."
|
| 1080 |
+
)
|
| 1081 |
+
|
| 1082 |
+
# - Use the request object if provided (there's no risk of modifying the input as
|
| 1083 |
+
# there are no flattened fields), or create one.
|
| 1084 |
+
if not isinstance(request, cache_service.UpdateCachedContentRequest):
|
| 1085 |
+
request = cache_service.UpdateCachedContentRequest(request)
|
| 1086 |
+
# If we have keyword arguments corresponding to fields on the
|
| 1087 |
+
# request, apply these.
|
| 1088 |
+
if cached_content is not None:
|
| 1089 |
+
request.cached_content = cached_content
|
| 1090 |
+
if update_mask is not None:
|
| 1091 |
+
request.update_mask = update_mask
|
| 1092 |
+
|
| 1093 |
+
# Wrap the RPC method; this adds retry and timeout information,
|
| 1094 |
+
# and friendly error handling.
|
| 1095 |
+
rpc = self._transport._wrapped_methods[self._transport.update_cached_content]
|
| 1096 |
+
|
| 1097 |
+
# Certain fields should be provided within the metadata header;
|
| 1098 |
+
# add these here.
|
| 1099 |
+
metadata = tuple(metadata) + (
|
| 1100 |
+
gapic_v1.routing_header.to_grpc_metadata(
|
| 1101 |
+
(("cached_content.name", request.cached_content.name),)
|
| 1102 |
+
),
|
| 1103 |
+
)
|
| 1104 |
+
|
| 1105 |
+
# Validate the universe domain.
|
| 1106 |
+
self._validate_universe_domain()
|
| 1107 |
+
|
| 1108 |
+
# Send the request.
|
| 1109 |
+
response = rpc(
|
| 1110 |
+
request,
|
| 1111 |
+
retry=retry,
|
| 1112 |
+
timeout=timeout,
|
| 1113 |
+
metadata=metadata,
|
| 1114 |
+
)
|
| 1115 |
+
|
| 1116 |
+
# Done; return the response.
|
| 1117 |
+
return response
|
| 1118 |
+
|
| 1119 |
+
def delete_cached_content(
|
| 1120 |
+
self,
|
| 1121 |
+
request: Optional[Union[cache_service.DeleteCachedContentRequest, dict]] = None,
|
| 1122 |
+
*,
|
| 1123 |
+
name: Optional[str] = None,
|
| 1124 |
+
retry: OptionalRetry = gapic_v1.method.DEFAULT,
|
| 1125 |
+
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
|
| 1126 |
+
metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
|
| 1127 |
+
) -> None:
|
| 1128 |
+
r"""Deletes CachedContent resource.
|
| 1129 |
+
|
| 1130 |
+
.. code-block:: python
|
| 1131 |
+
|
| 1132 |
+
# This snippet has been automatically generated and should be regarded as a
|
| 1133 |
+
# code template only.
|
| 1134 |
+
# It will require modifications to work:
|
| 1135 |
+
# - It may require correct/in-range values for request initialization.
|
| 1136 |
+
# - It may require specifying regional endpoints when creating the service
|
| 1137 |
+
# client as shown in:
|
| 1138 |
+
# https://googleapis.dev/python/google-api-core/latest/client_options.html
|
| 1139 |
+
from google.ai import generativelanguage_v1beta
|
| 1140 |
+
|
| 1141 |
+
def sample_delete_cached_content():
|
| 1142 |
+
# Create a client
|
| 1143 |
+
client = generativelanguage_v1beta.CacheServiceClient()
|
| 1144 |
+
|
| 1145 |
+
# Initialize request argument(s)
|
| 1146 |
+
request = generativelanguage_v1beta.DeleteCachedContentRequest(
|
| 1147 |
+
name="name_value",
|
| 1148 |
+
)
|
| 1149 |
+
|
| 1150 |
+
# Make the request
|
| 1151 |
+
client.delete_cached_content(request=request)
|
| 1152 |
+
|
| 1153 |
+
Args:
|
| 1154 |
+
request (Union[google.ai.generativelanguage_v1beta.types.DeleteCachedContentRequest, dict]):
|
| 1155 |
+
The request object. Request to delete CachedContent.
|
| 1156 |
+
name (str):
|
| 1157 |
+
Required. The resource name referring to the content
|
| 1158 |
+
cache entry Format: ``cachedContents/{id}``
|
| 1159 |
+
|
| 1160 |
+
This corresponds to the ``name`` field
|
| 1161 |
+
on the ``request`` instance; if ``request`` is provided, this
|
| 1162 |
+
should not be set.
|
| 1163 |
+
retry (google.api_core.retry.Retry): Designation of what errors, if any,
|
| 1164 |
+
should be retried.
|
| 1165 |
+
timeout (float): The timeout for this request.
|
| 1166 |
+
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
|
| 1167 |
+
sent along with the request as metadata. Normally, each value must be of type `str`,
|
| 1168 |
+
but for metadata keys ending with the suffix `-bin`, the corresponding values must
|
| 1169 |
+
be of type `bytes`.
|
| 1170 |
+
"""
|
| 1171 |
+
# Create or coerce a protobuf request object.
|
| 1172 |
+
# - Quick check: If we got a request object, we should *not* have
|
| 1173 |
+
# gotten any keyword arguments that map to the request.
|
| 1174 |
+
has_flattened_params = any([name])
|
| 1175 |
+
if request is not None and has_flattened_params:
|
| 1176 |
+
raise ValueError(
|
| 1177 |
+
"If the `request` argument is set, then none of "
|
| 1178 |
+
"the individual field arguments should be set."
|
| 1179 |
+
)
|
| 1180 |
+
|
| 1181 |
+
# - Use the request object if provided (there's no risk of modifying the input as
|
| 1182 |
+
# there are no flattened fields), or create one.
|
| 1183 |
+
if not isinstance(request, cache_service.DeleteCachedContentRequest):
|
| 1184 |
+
request = cache_service.DeleteCachedContentRequest(request)
|
| 1185 |
+
# If we have keyword arguments corresponding to fields on the
|
| 1186 |
+
# request, apply these.
|
| 1187 |
+
if name is not None:
|
| 1188 |
+
request.name = name
|
| 1189 |
+
|
| 1190 |
+
# Wrap the RPC method; this adds retry and timeout information,
|
| 1191 |
+
# and friendly error handling.
|
| 1192 |
+
rpc = self._transport._wrapped_methods[self._transport.delete_cached_content]
|
| 1193 |
+
|
| 1194 |
+
# Certain fields should be provided within the metadata header;
|
| 1195 |
+
# add these here.
|
| 1196 |
+
metadata = tuple(metadata) + (
|
| 1197 |
+
gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
|
| 1198 |
+
)
|
| 1199 |
+
|
| 1200 |
+
# Validate the universe domain.
|
| 1201 |
+
self._validate_universe_domain()
|
| 1202 |
+
|
| 1203 |
+
# Send the request.
|
| 1204 |
+
rpc(
|
| 1205 |
+
request,
|
| 1206 |
+
retry=retry,
|
| 1207 |
+
timeout=timeout,
|
| 1208 |
+
metadata=metadata,
|
| 1209 |
+
)
|
| 1210 |
+
|
| 1211 |
+
def __enter__(self) -> "CacheServiceClient":
|
| 1212 |
+
return self
|
| 1213 |
+
|
| 1214 |
+
def __exit__(self, type, value, traceback):
|
| 1215 |
+
"""Releases underlying transport's resources.
|
| 1216 |
+
|
| 1217 |
+
.. warning::
|
| 1218 |
+
ONLY use as a context manager if the transport is NOT shared
|
| 1219 |
+
with other clients! Exiting the with block will CLOSE the transport
|
| 1220 |
+
and may cause errors in other clients!
|
| 1221 |
+
"""
|
| 1222 |
+
self.transport.close()
|
| 1223 |
+
|
| 1224 |
+
def list_operations(
|
| 1225 |
+
self,
|
| 1226 |
+
request: Optional[operations_pb2.ListOperationsRequest] = None,
|
| 1227 |
+
*,
|
| 1228 |
+
retry: OptionalRetry = gapic_v1.method.DEFAULT,
|
| 1229 |
+
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
|
| 1230 |
+
metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
|
| 1231 |
+
) -> operations_pb2.ListOperationsResponse:
|
| 1232 |
+
r"""Lists operations that match the specified filter in the request.
|
| 1233 |
+
|
| 1234 |
+
Args:
|
| 1235 |
+
request (:class:`~.operations_pb2.ListOperationsRequest`):
|
| 1236 |
+
The request object. Request message for
|
| 1237 |
+
`ListOperations` method.
|
| 1238 |
+
retry (google.api_core.retry.Retry): Designation of what errors,
|
| 1239 |
+
if any, should be retried.
|
| 1240 |
+
timeout (float): The timeout for this request.
|
| 1241 |
+
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
|
| 1242 |
+
sent along with the request as metadata. Normally, each value must be of type `str`,
|
| 1243 |
+
but for metadata keys ending with the suffix `-bin`, the corresponding values must
|
| 1244 |
+
be of type `bytes`.
|
| 1245 |
+
Returns:
|
| 1246 |
+
~.operations_pb2.ListOperationsResponse:
|
| 1247 |
+
Response message for ``ListOperations`` method.
|
| 1248 |
+
"""
|
| 1249 |
+
# Create or coerce a protobuf request object.
|
| 1250 |
+
# The request isn't a proto-plus wrapped type,
|
| 1251 |
+
# so it must be constructed via keyword expansion.
|
| 1252 |
+
if isinstance(request, dict):
|
| 1253 |
+
request = operations_pb2.ListOperationsRequest(**request)
|
| 1254 |
+
|
| 1255 |
+
# Wrap the RPC method; this adds retry and timeout information,
|
| 1256 |
+
# and friendly error handling.
|
| 1257 |
+
rpc = self._transport._wrapped_methods[self._transport.list_operations]
|
| 1258 |
+
|
| 1259 |
+
# Certain fields should be provided within the metadata header;
|
| 1260 |
+
# add these here.
|
| 1261 |
+
metadata = tuple(metadata) + (
|
| 1262 |
+
gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
|
| 1263 |
+
)
|
| 1264 |
+
|
| 1265 |
+
# Validate the universe domain.
|
| 1266 |
+
self._validate_universe_domain()
|
| 1267 |
+
|
| 1268 |
+
# Send the request.
|
| 1269 |
+
response = rpc(
|
| 1270 |
+
request,
|
| 1271 |
+
retry=retry,
|
| 1272 |
+
timeout=timeout,
|
| 1273 |
+
metadata=metadata,
|
| 1274 |
+
)
|
| 1275 |
+
|
| 1276 |
+
# Done; return the response.
|
| 1277 |
+
return response
|
| 1278 |
+
|
| 1279 |
+
def get_operation(
|
| 1280 |
+
self,
|
| 1281 |
+
request: Optional[operations_pb2.GetOperationRequest] = None,
|
| 1282 |
+
*,
|
| 1283 |
+
retry: OptionalRetry = gapic_v1.method.DEFAULT,
|
| 1284 |
+
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
|
| 1285 |
+
metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
|
| 1286 |
+
) -> operations_pb2.Operation:
|
| 1287 |
+
r"""Gets the latest state of a long-running operation.
|
| 1288 |
+
|
| 1289 |
+
Args:
|
| 1290 |
+
request (:class:`~.operations_pb2.GetOperationRequest`):
|
| 1291 |
+
The request object. Request message for
|
| 1292 |
+
`GetOperation` method.
|
| 1293 |
+
retry (google.api_core.retry.Retry): Designation of what errors,
|
| 1294 |
+
if any, should be retried.
|
| 1295 |
+
timeout (float): The timeout for this request.
|
| 1296 |
+
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
|
| 1297 |
+
sent along with the request as metadata. Normally, each value must be of type `str`,
|
| 1298 |
+
but for metadata keys ending with the suffix `-bin`, the corresponding values must
|
| 1299 |
+
be of type `bytes`.
|
| 1300 |
+
Returns:
|
| 1301 |
+
~.operations_pb2.Operation:
|
| 1302 |
+
An ``Operation`` object.
|
| 1303 |
+
"""
|
| 1304 |
+
# Create or coerce a protobuf request object.
|
| 1305 |
+
# The request isn't a proto-plus wrapped type,
|
| 1306 |
+
# so it must be constructed via keyword expansion.
|
| 1307 |
+
if isinstance(request, dict):
|
| 1308 |
+
request = operations_pb2.GetOperationRequest(**request)
|
| 1309 |
+
|
| 1310 |
+
# Wrap the RPC method; this adds retry and timeout information,
|
| 1311 |
+
# and friendly error handling.
|
| 1312 |
+
rpc = self._transport._wrapped_methods[self._transport.get_operation]
|
| 1313 |
+
|
| 1314 |
+
# Certain fields should be provided within the metadata header;
|
| 1315 |
+
# add these here.
|
| 1316 |
+
metadata = tuple(metadata) + (
|
| 1317 |
+
gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
|
| 1318 |
+
)
|
| 1319 |
+
|
| 1320 |
+
# Validate the universe domain.
|
| 1321 |
+
self._validate_universe_domain()
|
| 1322 |
+
|
| 1323 |
+
# Send the request.
|
| 1324 |
+
response = rpc(
|
| 1325 |
+
request,
|
| 1326 |
+
retry=retry,
|
| 1327 |
+
timeout=timeout,
|
| 1328 |
+
metadata=metadata,
|
| 1329 |
+
)
|
| 1330 |
+
|
| 1331 |
+
# Done; return the response.
|
| 1332 |
+
return response
|
| 1333 |
+
|
| 1334 |
+
|
| 1335 |
+
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
|
| 1336 |
+
gapic_version=package_version.__version__
|
| 1337 |
+
)
|
| 1338 |
+
|
| 1339 |
+
|
| 1340 |
+
__all__ = ("CacheServiceClient",)
|
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/cache_service/pagers.py
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Copyright 2024 Google LLC
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
#
|
| 16 |
+
from typing import (
|
| 17 |
+
Any,
|
| 18 |
+
AsyncIterator,
|
| 19 |
+
Awaitable,
|
| 20 |
+
Callable,
|
| 21 |
+
Iterator,
|
| 22 |
+
Optional,
|
| 23 |
+
Sequence,
|
| 24 |
+
Tuple,
|
| 25 |
+
Union,
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
from google.api_core import gapic_v1
|
| 29 |
+
from google.api_core import retry as retries
|
| 30 |
+
from google.api_core import retry_async as retries_async
|
| 31 |
+
|
| 32 |
+
try:
|
| 33 |
+
OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None]
|
| 34 |
+
OptionalAsyncRetry = Union[
|
| 35 |
+
retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None
|
| 36 |
+
]
|
| 37 |
+
except AttributeError: # pragma: NO COVER
|
| 38 |
+
OptionalRetry = Union[retries.Retry, object, None] # type: ignore
|
| 39 |
+
OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore
|
| 40 |
+
|
| 41 |
+
from google.ai.generativelanguage_v1beta.types import cache_service, cached_content
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class ListCachedContentsPager:
|
| 45 |
+
"""A pager for iterating through ``list_cached_contents`` requests.
|
| 46 |
+
|
| 47 |
+
This class thinly wraps an initial
|
| 48 |
+
:class:`google.ai.generativelanguage_v1beta.types.ListCachedContentsResponse` object, and
|
| 49 |
+
provides an ``__iter__`` method to iterate through its
|
| 50 |
+
``cached_contents`` field.
|
| 51 |
+
|
| 52 |
+
If there are more pages, the ``__iter__`` method will make additional
|
| 53 |
+
``ListCachedContents`` requests and continue to iterate
|
| 54 |
+
through the ``cached_contents`` field on the
|
| 55 |
+
corresponding responses.
|
| 56 |
+
|
| 57 |
+
All the usual :class:`google.ai.generativelanguage_v1beta.types.ListCachedContentsResponse`
|
| 58 |
+
attributes are available on the pager. If multiple requests are made, only
|
| 59 |
+
the most recent response is retained, and thus used for attribute lookup.
|
| 60 |
+
"""
|
| 61 |
+
|
| 62 |
+
def __init__(
|
| 63 |
+
self,
|
| 64 |
+
method: Callable[..., cache_service.ListCachedContentsResponse],
|
| 65 |
+
request: cache_service.ListCachedContentsRequest,
|
| 66 |
+
response: cache_service.ListCachedContentsResponse,
|
| 67 |
+
*,
|
| 68 |
+
retry: OptionalRetry = gapic_v1.method.DEFAULT,
|
| 69 |
+
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
|
| 70 |
+
metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()
|
| 71 |
+
):
|
| 72 |
+
"""Instantiate the pager.
|
| 73 |
+
|
| 74 |
+
Args:
|
| 75 |
+
method (Callable): The method that was originally called, and
|
| 76 |
+
which instantiated this pager.
|
| 77 |
+
request (google.ai.generativelanguage_v1beta.types.ListCachedContentsRequest):
|
| 78 |
+
The initial request object.
|
| 79 |
+
response (google.ai.generativelanguage_v1beta.types.ListCachedContentsResponse):
|
| 80 |
+
The initial response object.
|
| 81 |
+
retry (google.api_core.retry.Retry): Designation of what errors,
|
| 82 |
+
if any, should be retried.
|
| 83 |
+
timeout (float): The timeout for this request.
|
| 84 |
+
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
|
| 85 |
+
sent along with the request as metadata. Normally, each value must be of type `str`,
|
| 86 |
+
but for metadata keys ending with the suffix `-bin`, the corresponding values must
|
| 87 |
+
be of type `bytes`.
|
| 88 |
+
"""
|
| 89 |
+
self._method = method
|
| 90 |
+
self._request = cache_service.ListCachedContentsRequest(request)
|
| 91 |
+
self._response = response
|
| 92 |
+
self._retry = retry
|
| 93 |
+
self._timeout = timeout
|
| 94 |
+
self._metadata = metadata
|
| 95 |
+
|
| 96 |
+
def __getattr__(self, name: str) -> Any:
|
| 97 |
+
return getattr(self._response, name)
|
| 98 |
+
|
| 99 |
+
@property
|
| 100 |
+
def pages(self) -> Iterator[cache_service.ListCachedContentsResponse]:
|
| 101 |
+
yield self._response
|
| 102 |
+
while self._response.next_page_token:
|
| 103 |
+
self._request.page_token = self._response.next_page_token
|
| 104 |
+
self._response = self._method(
|
| 105 |
+
self._request,
|
| 106 |
+
retry=self._retry,
|
| 107 |
+
timeout=self._timeout,
|
| 108 |
+
metadata=self._metadata,
|
| 109 |
+
)
|
| 110 |
+
yield self._response
|
| 111 |
+
|
| 112 |
+
def __iter__(self) -> Iterator[cached_content.CachedContent]:
|
| 113 |
+
for page in self.pages:
|
| 114 |
+
yield from page.cached_contents
|
| 115 |
+
|
| 116 |
+
def __repr__(self) -> str:
|
| 117 |
+
return "{0}<{1!r}>".format(self.__class__.__name__, self._response)
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
class ListCachedContentsAsyncPager:
|
| 121 |
+
"""A pager for iterating through ``list_cached_contents`` requests.
|
| 122 |
+
|
| 123 |
+
This class thinly wraps an initial
|
| 124 |
+
:class:`google.ai.generativelanguage_v1beta.types.ListCachedContentsResponse` object, and
|
| 125 |
+
provides an ``__aiter__`` method to iterate through its
|
| 126 |
+
``cached_contents`` field.
|
| 127 |
+
|
| 128 |
+
If there are more pages, the ``__aiter__`` method will make additional
|
| 129 |
+
``ListCachedContents`` requests and continue to iterate
|
| 130 |
+
through the ``cached_contents`` field on the
|
| 131 |
+
corresponding responses.
|
| 132 |
+
|
| 133 |
+
All the usual :class:`google.ai.generativelanguage_v1beta.types.ListCachedContentsResponse`
|
| 134 |
+
attributes are available on the pager. If multiple requests are made, only
|
| 135 |
+
the most recent response is retained, and thus used for attribute lookup.
|
| 136 |
+
"""
|
| 137 |
+
|
| 138 |
+
def __init__(
|
| 139 |
+
self,
|
| 140 |
+
method: Callable[..., Awaitable[cache_service.ListCachedContentsResponse]],
|
| 141 |
+
request: cache_service.ListCachedContentsRequest,
|
| 142 |
+
response: cache_service.ListCachedContentsResponse,
|
| 143 |
+
*,
|
| 144 |
+
retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT,
|
| 145 |
+
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
|
| 146 |
+
metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()
|
| 147 |
+
):
|
| 148 |
+
"""Instantiates the pager.
|
| 149 |
+
|
| 150 |
+
Args:
|
| 151 |
+
method (Callable): The method that was originally called, and
|
| 152 |
+
which instantiated this pager.
|
| 153 |
+
request (google.ai.generativelanguage_v1beta.types.ListCachedContentsRequest):
|
| 154 |
+
The initial request object.
|
| 155 |
+
response (google.ai.generativelanguage_v1beta.types.ListCachedContentsResponse):
|
| 156 |
+
The initial response object.
|
| 157 |
+
retry (google.api_core.retry.AsyncRetry): Designation of what errors,
|
| 158 |
+
if any, should be retried.
|
| 159 |
+
timeout (float): The timeout for this request.
|
| 160 |
+
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
|
| 161 |
+
sent along with the request as metadata. Normally, each value must be of type `str`,
|
| 162 |
+
but for metadata keys ending with the suffix `-bin`, the corresponding values must
|
| 163 |
+
be of type `bytes`.
|
| 164 |
+
"""
|
| 165 |
+
self._method = method
|
| 166 |
+
self._request = cache_service.ListCachedContentsRequest(request)
|
| 167 |
+
self._response = response
|
| 168 |
+
self._retry = retry
|
| 169 |
+
self._timeout = timeout
|
| 170 |
+
self._metadata = metadata
|
| 171 |
+
|
| 172 |
+
def __getattr__(self, name: str) -> Any:
|
| 173 |
+
return getattr(self._response, name)
|
| 174 |
+
|
| 175 |
+
@property
|
| 176 |
+
async def pages(self) -> AsyncIterator[cache_service.ListCachedContentsResponse]:
|
| 177 |
+
yield self._response
|
| 178 |
+
while self._response.next_page_token:
|
| 179 |
+
self._request.page_token = self._response.next_page_token
|
| 180 |
+
self._response = await self._method(
|
| 181 |
+
self._request,
|
| 182 |
+
retry=self._retry,
|
| 183 |
+
timeout=self._timeout,
|
| 184 |
+
metadata=self._metadata,
|
| 185 |
+
)
|
| 186 |
+
yield self._response
|
| 187 |
+
|
| 188 |
+
def __aiter__(self) -> AsyncIterator[cached_content.CachedContent]:
|
| 189 |
+
async def async_generator():
|
| 190 |
+
async for page in self.pages:
|
| 191 |
+
for response in page.cached_contents:
|
| 192 |
+
yield response
|
| 193 |
+
|
| 194 |
+
return async_generator()
|
| 195 |
+
|
| 196 |
+
def __repr__(self) -> str:
|
| 197 |
+
return "{0}<{1!r}>".format(self.__class__.__name__, self._response)
|
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/cache_service/transports/__init__.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Copyright 2024 Google LLC
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
#
|
| 16 |
+
from collections import OrderedDict
|
| 17 |
+
from typing import Dict, Type
|
| 18 |
+
|
| 19 |
+
from .base import CacheServiceTransport
|
| 20 |
+
from .grpc import CacheServiceGrpcTransport
|
| 21 |
+
from .grpc_asyncio import CacheServiceGrpcAsyncIOTransport
|
| 22 |
+
from .rest import CacheServiceRestInterceptor, CacheServiceRestTransport
|
| 23 |
+
|
| 24 |
+
# Compile a registry of transports.
|
| 25 |
+
_transport_registry = OrderedDict() # type: Dict[str, Type[CacheServiceTransport]]
|
| 26 |
+
_transport_registry["grpc"] = CacheServiceGrpcTransport
|
| 27 |
+
_transport_registry["grpc_asyncio"] = CacheServiceGrpcAsyncIOTransport
|
| 28 |
+
_transport_registry["rest"] = CacheServiceRestTransport
|
| 29 |
+
|
| 30 |
+
__all__ = (
|
| 31 |
+
"CacheServiceTransport",
|
| 32 |
+
"CacheServiceGrpcTransport",
|
| 33 |
+
"CacheServiceGrpcAsyncIOTransport",
|
| 34 |
+
"CacheServiceRestTransport",
|
| 35 |
+
"CacheServiceRestInterceptor",
|
| 36 |
+
)
|
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/cache_service/transports/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (895 Bytes). View file
|
|
|
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/cache_service/transports/__pycache__/base.cpython-311.pyc
ADDED
|
Binary file (10.3 kB). View file
|
|
|
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/cache_service/transports/__pycache__/grpc.cpython-311.pyc
ADDED
|
Binary file (22.6 kB). View file
|
|
|
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/cache_service/transports/__pycache__/grpc_asyncio.cpython-311.pyc
ADDED
|
Binary file (25.1 kB). View file
|
|
|
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/cache_service/transports/__pycache__/rest.cpython-311.pyc
ADDED
|
Binary file (53.9 kB). View file
|
|
|
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/cache_service/transports/__pycache__/rest_base.cpython-311.pyc
ADDED
|
Binary file (18.8 kB). View file
|
|
|
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/cache_service/transports/base.py
ADDED
|
@@ -0,0 +1,263 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Copyright 2024 Google LLC
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
#
|
| 16 |
+
import abc
|
| 17 |
+
from typing import Awaitable, Callable, Dict, Optional, Sequence, Union
|
| 18 |
+
|
| 19 |
+
import google.api_core
|
| 20 |
+
from google.api_core import exceptions as core_exceptions
|
| 21 |
+
from google.api_core import gapic_v1
|
| 22 |
+
from google.api_core import retry as retries
|
| 23 |
+
import google.auth # type: ignore
|
| 24 |
+
from google.auth import credentials as ga_credentials # type: ignore
|
| 25 |
+
from google.longrunning import operations_pb2 # type: ignore
|
| 26 |
+
from google.oauth2 import service_account # type: ignore
|
| 27 |
+
from google.protobuf import empty_pb2 # type: ignore
|
| 28 |
+
|
| 29 |
+
from google.ai.generativelanguage_v1beta import gapic_version as package_version
|
| 30 |
+
from google.ai.generativelanguage_v1beta.types import (
|
| 31 |
+
cached_content as gag_cached_content,
|
| 32 |
+
)
|
| 33 |
+
from google.ai.generativelanguage_v1beta.types import cache_service
|
| 34 |
+
from google.ai.generativelanguage_v1beta.types import cached_content
|
| 35 |
+
|
| 36 |
+
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
|
| 37 |
+
gapic_version=package_version.__version__
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class CacheServiceTransport(abc.ABC):
|
| 42 |
+
"""Abstract transport class for CacheService."""
|
| 43 |
+
|
| 44 |
+
AUTH_SCOPES = ()
|
| 45 |
+
|
| 46 |
+
DEFAULT_HOST: str = "generativelanguage.googleapis.com"
|
| 47 |
+
|
| 48 |
+
def __init__(
|
| 49 |
+
self,
|
| 50 |
+
*,
|
| 51 |
+
host: str = DEFAULT_HOST,
|
| 52 |
+
credentials: Optional[ga_credentials.Credentials] = None,
|
| 53 |
+
credentials_file: Optional[str] = None,
|
| 54 |
+
scopes: Optional[Sequence[str]] = None,
|
| 55 |
+
quota_project_id: Optional[str] = None,
|
| 56 |
+
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
|
| 57 |
+
always_use_jwt_access: Optional[bool] = False,
|
| 58 |
+
api_audience: Optional[str] = None,
|
| 59 |
+
**kwargs,
|
| 60 |
+
) -> None:
|
| 61 |
+
"""Instantiate the transport.
|
| 62 |
+
|
| 63 |
+
Args:
|
| 64 |
+
host (Optional[str]):
|
| 65 |
+
The hostname to connect to (default: 'generativelanguage.googleapis.com').
|
| 66 |
+
credentials (Optional[google.auth.credentials.Credentials]): The
|
| 67 |
+
authorization credentials to attach to requests. These
|
| 68 |
+
credentials identify the application to the service; if none
|
| 69 |
+
are specified, the client will attempt to ascertain the
|
| 70 |
+
credentials from the environment.
|
| 71 |
+
credentials_file (Optional[str]): A file with credentials that can
|
| 72 |
+
be loaded with :func:`google.auth.load_credentials_from_file`.
|
| 73 |
+
This argument is mutually exclusive with credentials.
|
| 74 |
+
scopes (Optional[Sequence[str]]): A list of scopes.
|
| 75 |
+
quota_project_id (Optional[str]): An optional project to use for billing
|
| 76 |
+
and quota.
|
| 77 |
+
client_info (google.api_core.gapic_v1.client_info.ClientInfo):
|
| 78 |
+
The client info used to send a user-agent string along with
|
| 79 |
+
API requests. If ``None``, then default info will be used.
|
| 80 |
+
Generally, you only need to set this if you're developing
|
| 81 |
+
your own client library.
|
| 82 |
+
always_use_jwt_access (Optional[bool]): Whether self signed JWT should
|
| 83 |
+
be used for service account credentials.
|
| 84 |
+
"""
|
| 85 |
+
|
| 86 |
+
scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES}
|
| 87 |
+
|
| 88 |
+
# Save the scopes.
|
| 89 |
+
self._scopes = scopes
|
| 90 |
+
if not hasattr(self, "_ignore_credentials"):
|
| 91 |
+
self._ignore_credentials: bool = False
|
| 92 |
+
|
| 93 |
+
# If no credentials are provided, then determine the appropriate
|
| 94 |
+
# defaults.
|
| 95 |
+
if credentials and credentials_file:
|
| 96 |
+
raise core_exceptions.DuplicateCredentialArgs(
|
| 97 |
+
"'credentials_file' and 'credentials' are mutually exclusive"
|
| 98 |
+
)
|
| 99 |
+
|
| 100 |
+
if credentials_file is not None:
|
| 101 |
+
credentials, _ = google.auth.load_credentials_from_file(
|
| 102 |
+
credentials_file, **scopes_kwargs, quota_project_id=quota_project_id
|
| 103 |
+
)
|
| 104 |
+
elif credentials is None and not self._ignore_credentials:
|
| 105 |
+
credentials, _ = google.auth.default(
|
| 106 |
+
**scopes_kwargs, quota_project_id=quota_project_id
|
| 107 |
+
)
|
| 108 |
+
# Don't apply audience if the credentials file passed from user.
|
| 109 |
+
if hasattr(credentials, "with_gdch_audience"):
|
| 110 |
+
credentials = credentials.with_gdch_audience(
|
| 111 |
+
api_audience if api_audience else host
|
| 112 |
+
)
|
| 113 |
+
|
| 114 |
+
# If the credentials are service account credentials, then always try to use self signed JWT.
|
| 115 |
+
if (
|
| 116 |
+
always_use_jwt_access
|
| 117 |
+
and isinstance(credentials, service_account.Credentials)
|
| 118 |
+
and hasattr(service_account.Credentials, "with_always_use_jwt_access")
|
| 119 |
+
):
|
| 120 |
+
credentials = credentials.with_always_use_jwt_access(True)
|
| 121 |
+
|
| 122 |
+
# Save the credentials.
|
| 123 |
+
self._credentials = credentials
|
| 124 |
+
|
| 125 |
+
# Save the hostname. Default to port 443 (HTTPS) if none is specified.
|
| 126 |
+
if ":" not in host:
|
| 127 |
+
host += ":443"
|
| 128 |
+
self._host = host
|
| 129 |
+
|
| 130 |
+
@property
|
| 131 |
+
def host(self):
|
| 132 |
+
return self._host
|
| 133 |
+
|
| 134 |
+
def _prep_wrapped_messages(self, client_info):
|
| 135 |
+
# Precompute the wrapped methods.
|
| 136 |
+
self._wrapped_methods = {
|
| 137 |
+
self.list_cached_contents: gapic_v1.method.wrap_method(
|
| 138 |
+
self.list_cached_contents,
|
| 139 |
+
default_timeout=None,
|
| 140 |
+
client_info=client_info,
|
| 141 |
+
),
|
| 142 |
+
self.create_cached_content: gapic_v1.method.wrap_method(
|
| 143 |
+
self.create_cached_content,
|
| 144 |
+
default_timeout=None,
|
| 145 |
+
client_info=client_info,
|
| 146 |
+
),
|
| 147 |
+
self.get_cached_content: gapic_v1.method.wrap_method(
|
| 148 |
+
self.get_cached_content,
|
| 149 |
+
default_timeout=None,
|
| 150 |
+
client_info=client_info,
|
| 151 |
+
),
|
| 152 |
+
self.update_cached_content: gapic_v1.method.wrap_method(
|
| 153 |
+
self.update_cached_content,
|
| 154 |
+
default_timeout=None,
|
| 155 |
+
client_info=client_info,
|
| 156 |
+
),
|
| 157 |
+
self.delete_cached_content: gapic_v1.method.wrap_method(
|
| 158 |
+
self.delete_cached_content,
|
| 159 |
+
default_timeout=None,
|
| 160 |
+
client_info=client_info,
|
| 161 |
+
),
|
| 162 |
+
self.get_operation: gapic_v1.method.wrap_method(
|
| 163 |
+
self.get_operation,
|
| 164 |
+
default_timeout=None,
|
| 165 |
+
client_info=client_info,
|
| 166 |
+
),
|
| 167 |
+
self.list_operations: gapic_v1.method.wrap_method(
|
| 168 |
+
self.list_operations,
|
| 169 |
+
default_timeout=None,
|
| 170 |
+
client_info=client_info,
|
| 171 |
+
),
|
| 172 |
+
}
|
| 173 |
+
|
| 174 |
+
def close(self):
|
| 175 |
+
"""Closes resources associated with the transport.
|
| 176 |
+
|
| 177 |
+
.. warning::
|
| 178 |
+
Only call this method if the transport is NOT shared
|
| 179 |
+
with other clients - this may cause errors in other clients!
|
| 180 |
+
"""
|
| 181 |
+
raise NotImplementedError()
|
| 182 |
+
|
| 183 |
+
@property
|
| 184 |
+
def list_cached_contents(
|
| 185 |
+
self,
|
| 186 |
+
) -> Callable[
|
| 187 |
+
[cache_service.ListCachedContentsRequest],
|
| 188 |
+
Union[
|
| 189 |
+
cache_service.ListCachedContentsResponse,
|
| 190 |
+
Awaitable[cache_service.ListCachedContentsResponse],
|
| 191 |
+
],
|
| 192 |
+
]:
|
| 193 |
+
raise NotImplementedError()
|
| 194 |
+
|
| 195 |
+
@property
|
| 196 |
+
def create_cached_content(
|
| 197 |
+
self,
|
| 198 |
+
) -> Callable[
|
| 199 |
+
[cache_service.CreateCachedContentRequest],
|
| 200 |
+
Union[
|
| 201 |
+
gag_cached_content.CachedContent,
|
| 202 |
+
Awaitable[gag_cached_content.CachedContent],
|
| 203 |
+
],
|
| 204 |
+
]:
|
| 205 |
+
raise NotImplementedError()
|
| 206 |
+
|
| 207 |
+
@property
|
| 208 |
+
def get_cached_content(
|
| 209 |
+
self,
|
| 210 |
+
) -> Callable[
|
| 211 |
+
[cache_service.GetCachedContentRequest],
|
| 212 |
+
Union[cached_content.CachedContent, Awaitable[cached_content.CachedContent]],
|
| 213 |
+
]:
|
| 214 |
+
raise NotImplementedError()
|
| 215 |
+
|
| 216 |
+
@property
|
| 217 |
+
def update_cached_content(
|
| 218 |
+
self,
|
| 219 |
+
) -> Callable[
|
| 220 |
+
[cache_service.UpdateCachedContentRequest],
|
| 221 |
+
Union[
|
| 222 |
+
gag_cached_content.CachedContent,
|
| 223 |
+
Awaitable[gag_cached_content.CachedContent],
|
| 224 |
+
],
|
| 225 |
+
]:
|
| 226 |
+
raise NotImplementedError()
|
| 227 |
+
|
| 228 |
+
@property
|
| 229 |
+
def delete_cached_content(
|
| 230 |
+
self,
|
| 231 |
+
) -> Callable[
|
| 232 |
+
[cache_service.DeleteCachedContentRequest],
|
| 233 |
+
Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]],
|
| 234 |
+
]:
|
| 235 |
+
raise NotImplementedError()
|
| 236 |
+
|
| 237 |
+
@property
|
| 238 |
+
def list_operations(
|
| 239 |
+
self,
|
| 240 |
+
) -> Callable[
|
| 241 |
+
[operations_pb2.ListOperationsRequest],
|
| 242 |
+
Union[
|
| 243 |
+
operations_pb2.ListOperationsResponse,
|
| 244 |
+
Awaitable[operations_pb2.ListOperationsResponse],
|
| 245 |
+
],
|
| 246 |
+
]:
|
| 247 |
+
raise NotImplementedError()
|
| 248 |
+
|
| 249 |
+
@property
|
| 250 |
+
def get_operation(
|
| 251 |
+
self,
|
| 252 |
+
) -> Callable[
|
| 253 |
+
[operations_pb2.GetOperationRequest],
|
| 254 |
+
Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]],
|
| 255 |
+
]:
|
| 256 |
+
raise NotImplementedError()
|
| 257 |
+
|
| 258 |
+
@property
|
| 259 |
+
def kind(self) -> str:
|
| 260 |
+
raise NotImplementedError()
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
__all__ = ("CacheServiceTransport",)
|
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/cache_service/transports/grpc.py
ADDED
|
@@ -0,0 +1,517 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Copyright 2024 Google LLC
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
#
|
| 16 |
+
import json
|
| 17 |
+
import logging as std_logging
|
| 18 |
+
import pickle
|
| 19 |
+
from typing import Callable, Dict, Optional, Sequence, Tuple, Union
|
| 20 |
+
import warnings
|
| 21 |
+
|
| 22 |
+
from google.api_core import gapic_v1, grpc_helpers
|
| 23 |
+
import google.auth # type: ignore
|
| 24 |
+
from google.auth import credentials as ga_credentials # type: ignore
|
| 25 |
+
from google.auth.transport.grpc import SslCredentials # type: ignore
|
| 26 |
+
from google.longrunning import operations_pb2 # type: ignore
|
| 27 |
+
from google.protobuf import empty_pb2 # type: ignore
|
| 28 |
+
from google.protobuf.json_format import MessageToJson
|
| 29 |
+
import google.protobuf.message
|
| 30 |
+
import grpc # type: ignore
|
| 31 |
+
import proto # type: ignore
|
| 32 |
+
|
| 33 |
+
from google.ai.generativelanguage_v1beta.types import (
|
| 34 |
+
cached_content as gag_cached_content,
|
| 35 |
+
)
|
| 36 |
+
from google.ai.generativelanguage_v1beta.types import cache_service
|
| 37 |
+
from google.ai.generativelanguage_v1beta.types import cached_content
|
| 38 |
+
|
| 39 |
+
from .base import DEFAULT_CLIENT_INFO, CacheServiceTransport
|
| 40 |
+
|
| 41 |
+
try:
|
| 42 |
+
from google.api_core import client_logging # type: ignore
|
| 43 |
+
|
| 44 |
+
CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER
|
| 45 |
+
except ImportError: # pragma: NO COVER
|
| 46 |
+
CLIENT_LOGGING_SUPPORTED = False
|
| 47 |
+
|
| 48 |
+
_LOGGER = std_logging.getLogger(__name__)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER
|
| 52 |
+
def intercept_unary_unary(self, continuation, client_call_details, request):
|
| 53 |
+
logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
|
| 54 |
+
std_logging.DEBUG
|
| 55 |
+
)
|
| 56 |
+
if logging_enabled: # pragma: NO COVER
|
| 57 |
+
request_metadata = client_call_details.metadata
|
| 58 |
+
if isinstance(request, proto.Message):
|
| 59 |
+
request_payload = type(request).to_json(request)
|
| 60 |
+
elif isinstance(request, google.protobuf.message.Message):
|
| 61 |
+
request_payload = MessageToJson(request)
|
| 62 |
+
else:
|
| 63 |
+
request_payload = f"{type(request).__name__}: {pickle.dumps(request)}"
|
| 64 |
+
|
| 65 |
+
request_metadata = {
|
| 66 |
+
key: value.decode("utf-8") if isinstance(value, bytes) else value
|
| 67 |
+
for key, value in request_metadata
|
| 68 |
+
}
|
| 69 |
+
grpc_request = {
|
| 70 |
+
"payload": request_payload,
|
| 71 |
+
"requestMethod": "grpc",
|
| 72 |
+
"metadata": dict(request_metadata),
|
| 73 |
+
}
|
| 74 |
+
_LOGGER.debug(
|
| 75 |
+
f"Sending request for {client_call_details.method}",
|
| 76 |
+
extra={
|
| 77 |
+
"serviceName": "google.ai.generativelanguage.v1beta.CacheService",
|
| 78 |
+
"rpcName": client_call_details.method,
|
| 79 |
+
"request": grpc_request,
|
| 80 |
+
"metadata": grpc_request["metadata"],
|
| 81 |
+
},
|
| 82 |
+
)
|
| 83 |
+
|
| 84 |
+
response = continuation(client_call_details, request)
|
| 85 |
+
if logging_enabled: # pragma: NO COVER
|
| 86 |
+
response_metadata = response.trailing_metadata()
|
| 87 |
+
# Convert gRPC metadata `<class 'grpc.aio._metadata.Metadata'>` to list of tuples
|
| 88 |
+
metadata = (
|
| 89 |
+
dict([(k, str(v)) for k, v in response_metadata])
|
| 90 |
+
if response_metadata
|
| 91 |
+
else None
|
| 92 |
+
)
|
| 93 |
+
result = response.result()
|
| 94 |
+
if isinstance(result, proto.Message):
|
| 95 |
+
response_payload = type(result).to_json(result)
|
| 96 |
+
elif isinstance(result, google.protobuf.message.Message):
|
| 97 |
+
response_payload = MessageToJson(result)
|
| 98 |
+
else:
|
| 99 |
+
response_payload = f"{type(result).__name__}: {pickle.dumps(result)}"
|
| 100 |
+
grpc_response = {
|
| 101 |
+
"payload": response_payload,
|
| 102 |
+
"metadata": metadata,
|
| 103 |
+
"status": "OK",
|
| 104 |
+
}
|
| 105 |
+
_LOGGER.debug(
|
| 106 |
+
f"Received response for {client_call_details.method}.",
|
| 107 |
+
extra={
|
| 108 |
+
"serviceName": "google.ai.generativelanguage.v1beta.CacheService",
|
| 109 |
+
"rpcName": client_call_details.method,
|
| 110 |
+
"response": grpc_response,
|
| 111 |
+
"metadata": grpc_response["metadata"],
|
| 112 |
+
},
|
| 113 |
+
)
|
| 114 |
+
return response
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
class CacheServiceGrpcTransport(CacheServiceTransport):
|
| 118 |
+
"""gRPC backend transport for CacheService.
|
| 119 |
+
|
| 120 |
+
API for managing cache of content (CachedContent resources)
|
| 121 |
+
that can be used in GenerativeService requests. This way
|
| 122 |
+
generate content requests can benefit from preprocessing work
|
| 123 |
+
being done earlier, possibly lowering their computational cost.
|
| 124 |
+
It is intended to be used with large contexts.
|
| 125 |
+
|
| 126 |
+
This class defines the same methods as the primary client, so the
|
| 127 |
+
primary client can load the underlying transport implementation
|
| 128 |
+
and call it.
|
| 129 |
+
|
| 130 |
+
It sends protocol buffers over the wire using gRPC (which is built on
|
| 131 |
+
top of HTTP/2); the ``grpcio`` package must be installed.
|
| 132 |
+
"""
|
| 133 |
+
|
| 134 |
+
_stubs: Dict[str, Callable]
|
| 135 |
+
|
| 136 |
+
def __init__(
|
| 137 |
+
self,
|
| 138 |
+
*,
|
| 139 |
+
host: str = "generativelanguage.googleapis.com",
|
| 140 |
+
credentials: Optional[ga_credentials.Credentials] = None,
|
| 141 |
+
credentials_file: Optional[str] = None,
|
| 142 |
+
scopes: Optional[Sequence[str]] = None,
|
| 143 |
+
channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None,
|
| 144 |
+
api_mtls_endpoint: Optional[str] = None,
|
| 145 |
+
client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None,
|
| 146 |
+
ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None,
|
| 147 |
+
client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None,
|
| 148 |
+
quota_project_id: Optional[str] = None,
|
| 149 |
+
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
|
| 150 |
+
always_use_jwt_access: Optional[bool] = False,
|
| 151 |
+
api_audience: Optional[str] = None,
|
| 152 |
+
) -> None:
|
| 153 |
+
"""Instantiate the transport.
|
| 154 |
+
|
| 155 |
+
Args:
|
| 156 |
+
host (Optional[str]):
|
| 157 |
+
The hostname to connect to (default: 'generativelanguage.googleapis.com').
|
| 158 |
+
credentials (Optional[google.auth.credentials.Credentials]): The
|
| 159 |
+
authorization credentials to attach to requests. These
|
| 160 |
+
credentials identify the application to the service; if none
|
| 161 |
+
are specified, the client will attempt to ascertain the
|
| 162 |
+
credentials from the environment.
|
| 163 |
+
This argument is ignored if a ``channel`` instance is provided.
|
| 164 |
+
credentials_file (Optional[str]): A file with credentials that can
|
| 165 |
+
be loaded with :func:`google.auth.load_credentials_from_file`.
|
| 166 |
+
This argument is ignored if a ``channel`` instance is provided.
|
| 167 |
+
scopes (Optional(Sequence[str])): A list of scopes. This argument is
|
| 168 |
+
ignored if a ``channel`` instance is provided.
|
| 169 |
+
channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]):
|
| 170 |
+
A ``Channel`` instance through which to make calls, or a Callable
|
| 171 |
+
that constructs and returns one. If set to None, ``self.create_channel``
|
| 172 |
+
is used to create the channel. If a Callable is given, it will be called
|
| 173 |
+
with the same arguments as used in ``self.create_channel``.
|
| 174 |
+
api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint.
|
| 175 |
+
If provided, it overrides the ``host`` argument and tries to create
|
| 176 |
+
a mutual TLS channel with client SSL credentials from
|
| 177 |
+
``client_cert_source`` or application default SSL credentials.
|
| 178 |
+
client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]):
|
| 179 |
+
Deprecated. A callback to provide client SSL certificate bytes and
|
| 180 |
+
private key bytes, both in PEM format. It is ignored if
|
| 181 |
+
``api_mtls_endpoint`` is None.
|
| 182 |
+
ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials
|
| 183 |
+
for the grpc channel. It is ignored if a ``channel`` instance is provided.
|
| 184 |
+
client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]):
|
| 185 |
+
A callback to provide client certificate bytes and private key bytes,
|
| 186 |
+
both in PEM format. It is used to configure a mutual TLS channel. It is
|
| 187 |
+
ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided.
|
| 188 |
+
quota_project_id (Optional[str]): An optional project to use for billing
|
| 189 |
+
and quota.
|
| 190 |
+
client_info (google.api_core.gapic_v1.client_info.ClientInfo):
|
| 191 |
+
The client info used to send a user-agent string along with
|
| 192 |
+
API requests. If ``None``, then default info will be used.
|
| 193 |
+
Generally, you only need to set this if you're developing
|
| 194 |
+
your own client library.
|
| 195 |
+
always_use_jwt_access (Optional[bool]): Whether self signed JWT should
|
| 196 |
+
be used for service account credentials.
|
| 197 |
+
|
| 198 |
+
Raises:
|
| 199 |
+
google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
|
| 200 |
+
creation failed for any reason.
|
| 201 |
+
google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
|
| 202 |
+
and ``credentials_file`` are passed.
|
| 203 |
+
"""
|
| 204 |
+
self._grpc_channel = None
|
| 205 |
+
self._ssl_channel_credentials = ssl_channel_credentials
|
| 206 |
+
self._stubs: Dict[str, Callable] = {}
|
| 207 |
+
|
| 208 |
+
if api_mtls_endpoint:
|
| 209 |
+
warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning)
|
| 210 |
+
if client_cert_source:
|
| 211 |
+
warnings.warn("client_cert_source is deprecated", DeprecationWarning)
|
| 212 |
+
|
| 213 |
+
if isinstance(channel, grpc.Channel):
|
| 214 |
+
# Ignore credentials if a channel was passed.
|
| 215 |
+
credentials = None
|
| 216 |
+
self._ignore_credentials = True
|
| 217 |
+
# If a channel was explicitly provided, set it.
|
| 218 |
+
self._grpc_channel = channel
|
| 219 |
+
self._ssl_channel_credentials = None
|
| 220 |
+
|
| 221 |
+
else:
|
| 222 |
+
if api_mtls_endpoint:
|
| 223 |
+
host = api_mtls_endpoint
|
| 224 |
+
|
| 225 |
+
# Create SSL credentials with client_cert_source or application
|
| 226 |
+
# default SSL credentials.
|
| 227 |
+
if client_cert_source:
|
| 228 |
+
cert, key = client_cert_source()
|
| 229 |
+
self._ssl_channel_credentials = grpc.ssl_channel_credentials(
|
| 230 |
+
certificate_chain=cert, private_key=key
|
| 231 |
+
)
|
| 232 |
+
else:
|
| 233 |
+
self._ssl_channel_credentials = SslCredentials().ssl_credentials
|
| 234 |
+
|
| 235 |
+
else:
|
| 236 |
+
if client_cert_source_for_mtls and not ssl_channel_credentials:
|
| 237 |
+
cert, key = client_cert_source_for_mtls()
|
| 238 |
+
self._ssl_channel_credentials = grpc.ssl_channel_credentials(
|
| 239 |
+
certificate_chain=cert, private_key=key
|
| 240 |
+
)
|
| 241 |
+
|
| 242 |
+
# The base transport sets the host, credentials and scopes
|
| 243 |
+
super().__init__(
|
| 244 |
+
host=host,
|
| 245 |
+
credentials=credentials,
|
| 246 |
+
credentials_file=credentials_file,
|
| 247 |
+
scopes=scopes,
|
| 248 |
+
quota_project_id=quota_project_id,
|
| 249 |
+
client_info=client_info,
|
| 250 |
+
always_use_jwt_access=always_use_jwt_access,
|
| 251 |
+
api_audience=api_audience,
|
| 252 |
+
)
|
| 253 |
+
|
| 254 |
+
if not self._grpc_channel:
|
| 255 |
+
# initialize with the provided callable or the default channel
|
| 256 |
+
channel_init = channel or type(self).create_channel
|
| 257 |
+
self._grpc_channel = channel_init(
|
| 258 |
+
self._host,
|
| 259 |
+
# use the credentials which are saved
|
| 260 |
+
credentials=self._credentials,
|
| 261 |
+
# Set ``credentials_file`` to ``None`` here as
|
| 262 |
+
# the credentials that we saved earlier should be used.
|
| 263 |
+
credentials_file=None,
|
| 264 |
+
scopes=self._scopes,
|
| 265 |
+
ssl_credentials=self._ssl_channel_credentials,
|
| 266 |
+
quota_project_id=quota_project_id,
|
| 267 |
+
options=[
|
| 268 |
+
("grpc.max_send_message_length", -1),
|
| 269 |
+
("grpc.max_receive_message_length", -1),
|
| 270 |
+
],
|
| 271 |
+
)
|
| 272 |
+
|
| 273 |
+
self._interceptor = _LoggingClientInterceptor()
|
| 274 |
+
self._logged_channel = grpc.intercept_channel(
|
| 275 |
+
self._grpc_channel, self._interceptor
|
| 276 |
+
)
|
| 277 |
+
|
| 278 |
+
# Wrap messages. This must be done after self._logged_channel exists
|
| 279 |
+
self._prep_wrapped_messages(client_info)
|
| 280 |
+
|
| 281 |
+
@classmethod
|
| 282 |
+
def create_channel(
|
| 283 |
+
cls,
|
| 284 |
+
host: str = "generativelanguage.googleapis.com",
|
| 285 |
+
credentials: Optional[ga_credentials.Credentials] = None,
|
| 286 |
+
credentials_file: Optional[str] = None,
|
| 287 |
+
scopes: Optional[Sequence[str]] = None,
|
| 288 |
+
quota_project_id: Optional[str] = None,
|
| 289 |
+
**kwargs,
|
| 290 |
+
) -> grpc.Channel:
|
| 291 |
+
"""Create and return a gRPC channel object.
|
| 292 |
+
Args:
|
| 293 |
+
host (Optional[str]): The host for the channel to use.
|
| 294 |
+
credentials (Optional[~.Credentials]): The
|
| 295 |
+
authorization credentials to attach to requests. These
|
| 296 |
+
credentials identify this application to the service. If
|
| 297 |
+
none are specified, the client will attempt to ascertain
|
| 298 |
+
the credentials from the environment.
|
| 299 |
+
credentials_file (Optional[str]): A file with credentials that can
|
| 300 |
+
be loaded with :func:`google.auth.load_credentials_from_file`.
|
| 301 |
+
This argument is mutually exclusive with credentials.
|
| 302 |
+
scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
|
| 303 |
+
service. These are only used when credentials are not specified and
|
| 304 |
+
are passed to :func:`google.auth.default`.
|
| 305 |
+
quota_project_id (Optional[str]): An optional project to use for billing
|
| 306 |
+
and quota.
|
| 307 |
+
kwargs (Optional[dict]): Keyword arguments, which are passed to the
|
| 308 |
+
channel creation.
|
| 309 |
+
Returns:
|
| 310 |
+
grpc.Channel: A gRPC channel object.
|
| 311 |
+
|
| 312 |
+
Raises:
|
| 313 |
+
google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
|
| 314 |
+
and ``credentials_file`` are passed.
|
| 315 |
+
"""
|
| 316 |
+
|
| 317 |
+
return grpc_helpers.create_channel(
|
| 318 |
+
host,
|
| 319 |
+
credentials=credentials,
|
| 320 |
+
credentials_file=credentials_file,
|
| 321 |
+
quota_project_id=quota_project_id,
|
| 322 |
+
default_scopes=cls.AUTH_SCOPES,
|
| 323 |
+
scopes=scopes,
|
| 324 |
+
default_host=cls.DEFAULT_HOST,
|
| 325 |
+
**kwargs,
|
| 326 |
+
)
|
| 327 |
+
|
| 328 |
+
@property
|
| 329 |
+
def grpc_channel(self) -> grpc.Channel:
|
| 330 |
+
"""Return the channel designed to connect to this service."""
|
| 331 |
+
return self._grpc_channel
|
| 332 |
+
|
| 333 |
+
@property
|
| 334 |
+
def list_cached_contents(
|
| 335 |
+
self,
|
| 336 |
+
) -> Callable[
|
| 337 |
+
[cache_service.ListCachedContentsRequest],
|
| 338 |
+
cache_service.ListCachedContentsResponse,
|
| 339 |
+
]:
|
| 340 |
+
r"""Return a callable for the list cached contents method over gRPC.
|
| 341 |
+
|
| 342 |
+
Lists CachedContents.
|
| 343 |
+
|
| 344 |
+
Returns:
|
| 345 |
+
Callable[[~.ListCachedContentsRequest],
|
| 346 |
+
~.ListCachedContentsResponse]:
|
| 347 |
+
A function that, when called, will call the underlying RPC
|
| 348 |
+
on the server.
|
| 349 |
+
"""
|
| 350 |
+
# Generate a "stub function" on-the-fly which will actually make
|
| 351 |
+
# the request.
|
| 352 |
+
# gRPC handles serialization and deserialization, so we just need
|
| 353 |
+
# to pass in the functions for each.
|
| 354 |
+
if "list_cached_contents" not in self._stubs:
|
| 355 |
+
self._stubs["list_cached_contents"] = self._logged_channel.unary_unary(
|
| 356 |
+
"/google.ai.generativelanguage.v1beta.CacheService/ListCachedContents",
|
| 357 |
+
request_serializer=cache_service.ListCachedContentsRequest.serialize,
|
| 358 |
+
response_deserializer=cache_service.ListCachedContentsResponse.deserialize,
|
| 359 |
+
)
|
| 360 |
+
return self._stubs["list_cached_contents"]
|
| 361 |
+
|
| 362 |
+
@property
|
| 363 |
+
def create_cached_content(
|
| 364 |
+
self,
|
| 365 |
+
) -> Callable[
|
| 366 |
+
[cache_service.CreateCachedContentRequest], gag_cached_content.CachedContent
|
| 367 |
+
]:
|
| 368 |
+
r"""Return a callable for the create cached content method over gRPC.
|
| 369 |
+
|
| 370 |
+
Creates CachedContent resource.
|
| 371 |
+
|
| 372 |
+
Returns:
|
| 373 |
+
Callable[[~.CreateCachedContentRequest],
|
| 374 |
+
~.CachedContent]:
|
| 375 |
+
A function that, when called, will call the underlying RPC
|
| 376 |
+
on the server.
|
| 377 |
+
"""
|
| 378 |
+
# Generate a "stub function" on-the-fly which will actually make
|
| 379 |
+
# the request.
|
| 380 |
+
# gRPC handles serialization and deserialization, so we just need
|
| 381 |
+
# to pass in the functions for each.
|
| 382 |
+
if "create_cached_content" not in self._stubs:
|
| 383 |
+
self._stubs["create_cached_content"] = self._logged_channel.unary_unary(
|
| 384 |
+
"/google.ai.generativelanguage.v1beta.CacheService/CreateCachedContent",
|
| 385 |
+
request_serializer=cache_service.CreateCachedContentRequest.serialize,
|
| 386 |
+
response_deserializer=gag_cached_content.CachedContent.deserialize,
|
| 387 |
+
)
|
| 388 |
+
return self._stubs["create_cached_content"]
|
| 389 |
+
|
| 390 |
+
@property
|
| 391 |
+
def get_cached_content(
|
| 392 |
+
self,
|
| 393 |
+
) -> Callable[
|
| 394 |
+
[cache_service.GetCachedContentRequest], cached_content.CachedContent
|
| 395 |
+
]:
|
| 396 |
+
r"""Return a callable for the get cached content method over gRPC.
|
| 397 |
+
|
| 398 |
+
Reads CachedContent resource.
|
| 399 |
+
|
| 400 |
+
Returns:
|
| 401 |
+
Callable[[~.GetCachedContentRequest],
|
| 402 |
+
~.CachedContent]:
|
| 403 |
+
A function that, when called, will call the underlying RPC
|
| 404 |
+
on the server.
|
| 405 |
+
"""
|
| 406 |
+
# Generate a "stub function" on-the-fly which will actually make
|
| 407 |
+
# the request.
|
| 408 |
+
# gRPC handles serialization and deserialization, so we just need
|
| 409 |
+
# to pass in the functions for each.
|
| 410 |
+
if "get_cached_content" not in self._stubs:
|
| 411 |
+
self._stubs["get_cached_content"] = self._logged_channel.unary_unary(
|
| 412 |
+
"/google.ai.generativelanguage.v1beta.CacheService/GetCachedContent",
|
| 413 |
+
request_serializer=cache_service.GetCachedContentRequest.serialize,
|
| 414 |
+
response_deserializer=cached_content.CachedContent.deserialize,
|
| 415 |
+
)
|
| 416 |
+
return self._stubs["get_cached_content"]
|
| 417 |
+
|
| 418 |
+
@property
|
| 419 |
+
def update_cached_content(
|
| 420 |
+
self,
|
| 421 |
+
) -> Callable[
|
| 422 |
+
[cache_service.UpdateCachedContentRequest], gag_cached_content.CachedContent
|
| 423 |
+
]:
|
| 424 |
+
r"""Return a callable for the update cached content method over gRPC.
|
| 425 |
+
|
| 426 |
+
Updates CachedContent resource (only expiration is
|
| 427 |
+
updatable).
|
| 428 |
+
|
| 429 |
+
Returns:
|
| 430 |
+
Callable[[~.UpdateCachedContentRequest],
|
| 431 |
+
~.CachedContent]:
|
| 432 |
+
A function that, when called, will call the underlying RPC
|
| 433 |
+
on the server.
|
| 434 |
+
"""
|
| 435 |
+
# Generate a "stub function" on-the-fly which will actually make
|
| 436 |
+
# the request.
|
| 437 |
+
# gRPC handles serialization and deserialization, so we just need
|
| 438 |
+
# to pass in the functions for each.
|
| 439 |
+
if "update_cached_content" not in self._stubs:
|
| 440 |
+
self._stubs["update_cached_content"] = self._logged_channel.unary_unary(
|
| 441 |
+
"/google.ai.generativelanguage.v1beta.CacheService/UpdateCachedContent",
|
| 442 |
+
request_serializer=cache_service.UpdateCachedContentRequest.serialize,
|
| 443 |
+
response_deserializer=gag_cached_content.CachedContent.deserialize,
|
| 444 |
+
)
|
| 445 |
+
return self._stubs["update_cached_content"]
|
| 446 |
+
|
| 447 |
+
@property
|
| 448 |
+
def delete_cached_content(
|
| 449 |
+
self,
|
| 450 |
+
) -> Callable[[cache_service.DeleteCachedContentRequest], empty_pb2.Empty]:
|
| 451 |
+
r"""Return a callable for the delete cached content method over gRPC.
|
| 452 |
+
|
| 453 |
+
Deletes CachedContent resource.
|
| 454 |
+
|
| 455 |
+
Returns:
|
| 456 |
+
Callable[[~.DeleteCachedContentRequest],
|
| 457 |
+
~.Empty]:
|
| 458 |
+
A function that, when called, will call the underlying RPC
|
| 459 |
+
on the server.
|
| 460 |
+
"""
|
| 461 |
+
# Generate a "stub function" on-the-fly which will actually make
|
| 462 |
+
# the request.
|
| 463 |
+
# gRPC handles serialization and deserialization, so we just need
|
| 464 |
+
# to pass in the functions for each.
|
| 465 |
+
if "delete_cached_content" not in self._stubs:
|
| 466 |
+
self._stubs["delete_cached_content"] = self._logged_channel.unary_unary(
|
| 467 |
+
"/google.ai.generativelanguage.v1beta.CacheService/DeleteCachedContent",
|
| 468 |
+
request_serializer=cache_service.DeleteCachedContentRequest.serialize,
|
| 469 |
+
response_deserializer=empty_pb2.Empty.FromString,
|
| 470 |
+
)
|
| 471 |
+
return self._stubs["delete_cached_content"]
|
| 472 |
+
|
| 473 |
+
def close(self):
|
| 474 |
+
self._logged_channel.close()
|
| 475 |
+
|
| 476 |
+
@property
|
| 477 |
+
def get_operation(
|
| 478 |
+
self,
|
| 479 |
+
) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]:
|
| 480 |
+
r"""Return a callable for the get_operation method over gRPC."""
|
| 481 |
+
# Generate a "stub function" on-the-fly which will actually make
|
| 482 |
+
# the request.
|
| 483 |
+
# gRPC handles serialization and deserialization, so we just need
|
| 484 |
+
# to pass in the functions for each.
|
| 485 |
+
if "get_operation" not in self._stubs:
|
| 486 |
+
self._stubs["get_operation"] = self._logged_channel.unary_unary(
|
| 487 |
+
"/google.longrunning.Operations/GetOperation",
|
| 488 |
+
request_serializer=operations_pb2.GetOperationRequest.SerializeToString,
|
| 489 |
+
response_deserializer=operations_pb2.Operation.FromString,
|
| 490 |
+
)
|
| 491 |
+
return self._stubs["get_operation"]
|
| 492 |
+
|
| 493 |
+
@property
|
| 494 |
+
def list_operations(
|
| 495 |
+
self,
|
| 496 |
+
) -> Callable[
|
| 497 |
+
[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse
|
| 498 |
+
]:
|
| 499 |
+
r"""Return a callable for the list_operations method over gRPC."""
|
| 500 |
+
# Generate a "stub function" on-the-fly which will actually make
|
| 501 |
+
# the request.
|
| 502 |
+
# gRPC handles serialization and deserialization, so we just need
|
| 503 |
+
# to pass in the functions for each.
|
| 504 |
+
if "list_operations" not in self._stubs:
|
| 505 |
+
self._stubs["list_operations"] = self._logged_channel.unary_unary(
|
| 506 |
+
"/google.longrunning.Operations/ListOperations",
|
| 507 |
+
request_serializer=operations_pb2.ListOperationsRequest.SerializeToString,
|
| 508 |
+
response_deserializer=operations_pb2.ListOperationsResponse.FromString,
|
| 509 |
+
)
|
| 510 |
+
return self._stubs["list_operations"]
|
| 511 |
+
|
| 512 |
+
@property
|
| 513 |
+
def kind(self) -> str:
|
| 514 |
+
return "grpc"
|
| 515 |
+
|
| 516 |
+
|
| 517 |
+
__all__ = ("CacheServiceGrpcTransport",)
|
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/cache_service/transports/grpc_asyncio.py
ADDED
|
@@ -0,0 +1,573 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Copyright 2024 Google LLC
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
#
|
| 16 |
+
import inspect
|
| 17 |
+
import json
|
| 18 |
+
import logging as std_logging
|
| 19 |
+
import pickle
|
| 20 |
+
from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union
|
| 21 |
+
import warnings
|
| 22 |
+
|
| 23 |
+
from google.api_core import exceptions as core_exceptions
|
| 24 |
+
from google.api_core import gapic_v1, grpc_helpers_async
|
| 25 |
+
from google.api_core import retry_async as retries
|
| 26 |
+
from google.auth import credentials as ga_credentials # type: ignore
|
| 27 |
+
from google.auth.transport.grpc import SslCredentials # type: ignore
|
| 28 |
+
from google.longrunning import operations_pb2 # type: ignore
|
| 29 |
+
from google.protobuf import empty_pb2 # type: ignore
|
| 30 |
+
from google.protobuf.json_format import MessageToJson
|
| 31 |
+
import google.protobuf.message
|
| 32 |
+
import grpc # type: ignore
|
| 33 |
+
from grpc.experimental import aio # type: ignore
|
| 34 |
+
import proto # type: ignore
|
| 35 |
+
|
| 36 |
+
from google.ai.generativelanguage_v1beta.types import (
|
| 37 |
+
cached_content as gag_cached_content,
|
| 38 |
+
)
|
| 39 |
+
from google.ai.generativelanguage_v1beta.types import cache_service
|
| 40 |
+
from google.ai.generativelanguage_v1beta.types import cached_content
|
| 41 |
+
|
| 42 |
+
from .base import DEFAULT_CLIENT_INFO, CacheServiceTransport
|
| 43 |
+
from .grpc import CacheServiceGrpcTransport
|
| 44 |
+
|
| 45 |
+
try:
|
| 46 |
+
from google.api_core import client_logging # type: ignore
|
| 47 |
+
|
| 48 |
+
CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER
|
| 49 |
+
except ImportError: # pragma: NO COVER
|
| 50 |
+
CLIENT_LOGGING_SUPPORTED = False
|
| 51 |
+
|
| 52 |
+
_LOGGER = std_logging.getLogger(__name__)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
class _LoggingClientAIOInterceptor(
|
| 56 |
+
grpc.aio.UnaryUnaryClientInterceptor
|
| 57 |
+
): # pragma: NO COVER
|
| 58 |
+
async def intercept_unary_unary(self, continuation, client_call_details, request):
|
| 59 |
+
logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
|
| 60 |
+
std_logging.DEBUG
|
| 61 |
+
)
|
| 62 |
+
if logging_enabled: # pragma: NO COVER
|
| 63 |
+
request_metadata = client_call_details.metadata
|
| 64 |
+
if isinstance(request, proto.Message):
|
| 65 |
+
request_payload = type(request).to_json(request)
|
| 66 |
+
elif isinstance(request, google.protobuf.message.Message):
|
| 67 |
+
request_payload = MessageToJson(request)
|
| 68 |
+
else:
|
| 69 |
+
request_payload = f"{type(request).__name__}: {pickle.dumps(request)}"
|
| 70 |
+
|
| 71 |
+
request_metadata = {
|
| 72 |
+
key: value.decode("utf-8") if isinstance(value, bytes) else value
|
| 73 |
+
for key, value in request_metadata
|
| 74 |
+
}
|
| 75 |
+
grpc_request = {
|
| 76 |
+
"payload": request_payload,
|
| 77 |
+
"requestMethod": "grpc",
|
| 78 |
+
"metadata": dict(request_metadata),
|
| 79 |
+
}
|
| 80 |
+
_LOGGER.debug(
|
| 81 |
+
f"Sending request for {client_call_details.method}",
|
| 82 |
+
extra={
|
| 83 |
+
"serviceName": "google.ai.generativelanguage.v1beta.CacheService",
|
| 84 |
+
"rpcName": str(client_call_details.method),
|
| 85 |
+
"request": grpc_request,
|
| 86 |
+
"metadata": grpc_request["metadata"],
|
| 87 |
+
},
|
| 88 |
+
)
|
| 89 |
+
response = await continuation(client_call_details, request)
|
| 90 |
+
if logging_enabled: # pragma: NO COVER
|
| 91 |
+
response_metadata = await response.trailing_metadata()
|
| 92 |
+
# Convert gRPC metadata `<class 'grpc.aio._metadata.Metadata'>` to list of tuples
|
| 93 |
+
metadata = (
|
| 94 |
+
dict([(k, str(v)) for k, v in response_metadata])
|
| 95 |
+
if response_metadata
|
| 96 |
+
else None
|
| 97 |
+
)
|
| 98 |
+
result = await response
|
| 99 |
+
if isinstance(result, proto.Message):
|
| 100 |
+
response_payload = type(result).to_json(result)
|
| 101 |
+
elif isinstance(result, google.protobuf.message.Message):
|
| 102 |
+
response_payload = MessageToJson(result)
|
| 103 |
+
else:
|
| 104 |
+
response_payload = f"{type(result).__name__}: {pickle.dumps(result)}"
|
| 105 |
+
grpc_response = {
|
| 106 |
+
"payload": response_payload,
|
| 107 |
+
"metadata": metadata,
|
| 108 |
+
"status": "OK",
|
| 109 |
+
}
|
| 110 |
+
_LOGGER.debug(
|
| 111 |
+
f"Received response to rpc {client_call_details.method}.",
|
| 112 |
+
extra={
|
| 113 |
+
"serviceName": "google.ai.generativelanguage.v1beta.CacheService",
|
| 114 |
+
"rpcName": str(client_call_details.method),
|
| 115 |
+
"response": grpc_response,
|
| 116 |
+
"metadata": grpc_response["metadata"],
|
| 117 |
+
},
|
| 118 |
+
)
|
| 119 |
+
return response
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
class CacheServiceGrpcAsyncIOTransport(CacheServiceTransport):
|
| 123 |
+
"""gRPC AsyncIO backend transport for CacheService.
|
| 124 |
+
|
| 125 |
+
API for managing cache of content (CachedContent resources)
|
| 126 |
+
that can be used in GenerativeService requests. This way
|
| 127 |
+
generate content requests can benefit from preprocessing work
|
| 128 |
+
being done earlier, possibly lowering their computational cost.
|
| 129 |
+
It is intended to be used with large contexts.
|
| 130 |
+
|
| 131 |
+
This class defines the same methods as the primary client, so the
|
| 132 |
+
primary client can load the underlying transport implementation
|
| 133 |
+
and call it.
|
| 134 |
+
|
| 135 |
+
It sends protocol buffers over the wire using gRPC (which is built on
|
| 136 |
+
top of HTTP/2); the ``grpcio`` package must be installed.
|
| 137 |
+
"""
|
| 138 |
+
|
| 139 |
+
_grpc_channel: aio.Channel
|
| 140 |
+
_stubs: Dict[str, Callable] = {}
|
| 141 |
+
|
| 142 |
+
@classmethod
|
| 143 |
+
def create_channel(
|
| 144 |
+
cls,
|
| 145 |
+
host: str = "generativelanguage.googleapis.com",
|
| 146 |
+
credentials: Optional[ga_credentials.Credentials] = None,
|
| 147 |
+
credentials_file: Optional[str] = None,
|
| 148 |
+
scopes: Optional[Sequence[str]] = None,
|
| 149 |
+
quota_project_id: Optional[str] = None,
|
| 150 |
+
**kwargs,
|
| 151 |
+
) -> aio.Channel:
|
| 152 |
+
"""Create and return a gRPC AsyncIO channel object.
|
| 153 |
+
Args:
|
| 154 |
+
host (Optional[str]): The host for the channel to use.
|
| 155 |
+
credentials (Optional[~.Credentials]): The
|
| 156 |
+
authorization credentials to attach to requests. These
|
| 157 |
+
credentials identify this application to the service. If
|
| 158 |
+
none are specified, the client will attempt to ascertain
|
| 159 |
+
the credentials from the environment.
|
| 160 |
+
credentials_file (Optional[str]): A file with credentials that can
|
| 161 |
+
be loaded with :func:`google.auth.load_credentials_from_file`.
|
| 162 |
+
scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
|
| 163 |
+
service. These are only used when credentials are not specified and
|
| 164 |
+
are passed to :func:`google.auth.default`.
|
| 165 |
+
quota_project_id (Optional[str]): An optional project to use for billing
|
| 166 |
+
and quota.
|
| 167 |
+
kwargs (Optional[dict]): Keyword arguments, which are passed to the
|
| 168 |
+
channel creation.
|
| 169 |
+
Returns:
|
| 170 |
+
aio.Channel: A gRPC AsyncIO channel object.
|
| 171 |
+
"""
|
| 172 |
+
|
| 173 |
+
return grpc_helpers_async.create_channel(
|
| 174 |
+
host,
|
| 175 |
+
credentials=credentials,
|
| 176 |
+
credentials_file=credentials_file,
|
| 177 |
+
quota_project_id=quota_project_id,
|
| 178 |
+
default_scopes=cls.AUTH_SCOPES,
|
| 179 |
+
scopes=scopes,
|
| 180 |
+
default_host=cls.DEFAULT_HOST,
|
| 181 |
+
**kwargs,
|
| 182 |
+
)
|
| 183 |
+
|
| 184 |
+
def __init__(
|
| 185 |
+
self,
|
| 186 |
+
*,
|
| 187 |
+
host: str = "generativelanguage.googleapis.com",
|
| 188 |
+
credentials: Optional[ga_credentials.Credentials] = None,
|
| 189 |
+
credentials_file: Optional[str] = None,
|
| 190 |
+
scopes: Optional[Sequence[str]] = None,
|
| 191 |
+
channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None,
|
| 192 |
+
api_mtls_endpoint: Optional[str] = None,
|
| 193 |
+
client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None,
|
| 194 |
+
ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None,
|
| 195 |
+
client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None,
|
| 196 |
+
quota_project_id: Optional[str] = None,
|
| 197 |
+
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
|
| 198 |
+
always_use_jwt_access: Optional[bool] = False,
|
| 199 |
+
api_audience: Optional[str] = None,
|
| 200 |
+
) -> None:
|
| 201 |
+
"""Instantiate the transport.
|
| 202 |
+
|
| 203 |
+
Args:
|
| 204 |
+
host (Optional[str]):
|
| 205 |
+
The hostname to connect to (default: 'generativelanguage.googleapis.com').
|
| 206 |
+
credentials (Optional[google.auth.credentials.Credentials]): The
|
| 207 |
+
authorization credentials to attach to requests. These
|
| 208 |
+
credentials identify the application to the service; if none
|
| 209 |
+
are specified, the client will attempt to ascertain the
|
| 210 |
+
credentials from the environment.
|
| 211 |
+
This argument is ignored if a ``channel`` instance is provided.
|
| 212 |
+
credentials_file (Optional[str]): A file with credentials that can
|
| 213 |
+
be loaded with :func:`google.auth.load_credentials_from_file`.
|
| 214 |
+
This argument is ignored if a ``channel`` instance is provided.
|
| 215 |
+
scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
|
| 216 |
+
service. These are only used when credentials are not specified and
|
| 217 |
+
are passed to :func:`google.auth.default`.
|
| 218 |
+
channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]):
|
| 219 |
+
A ``Channel`` instance through which to make calls, or a Callable
|
| 220 |
+
that constructs and returns one. If set to None, ``self.create_channel``
|
| 221 |
+
is used to create the channel. If a Callable is given, it will be called
|
| 222 |
+
with the same arguments as used in ``self.create_channel``.
|
| 223 |
+
api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint.
|
| 224 |
+
If provided, it overrides the ``host`` argument and tries to create
|
| 225 |
+
a mutual TLS channel with client SSL credentials from
|
| 226 |
+
``client_cert_source`` or application default SSL credentials.
|
| 227 |
+
client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]):
|
| 228 |
+
Deprecated. A callback to provide client SSL certificate bytes and
|
| 229 |
+
private key bytes, both in PEM format. It is ignored if
|
| 230 |
+
``api_mtls_endpoint`` is None.
|
| 231 |
+
ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials
|
| 232 |
+
for the grpc channel. It is ignored if a ``channel`` instance is provided.
|
| 233 |
+
client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]):
|
| 234 |
+
A callback to provide client certificate bytes and private key bytes,
|
| 235 |
+
both in PEM format. It is used to configure a mutual TLS channel. It is
|
| 236 |
+
ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided.
|
| 237 |
+
quota_project_id (Optional[str]): An optional project to use for billing
|
| 238 |
+
and quota.
|
| 239 |
+
client_info (google.api_core.gapic_v1.client_info.ClientInfo):
|
| 240 |
+
The client info used to send a user-agent string along with
|
| 241 |
+
API requests. If ``None``, then default info will be used.
|
| 242 |
+
Generally, you only need to set this if you're developing
|
| 243 |
+
your own client library.
|
| 244 |
+
always_use_jwt_access (Optional[bool]): Whether self signed JWT should
|
| 245 |
+
be used for service account credentials.
|
| 246 |
+
|
| 247 |
+
Raises:
|
| 248 |
+
google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
|
| 249 |
+
creation failed for any reason.
|
| 250 |
+
google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
|
| 251 |
+
and ``credentials_file`` are passed.
|
| 252 |
+
"""
|
| 253 |
+
self._grpc_channel = None
|
| 254 |
+
self._ssl_channel_credentials = ssl_channel_credentials
|
| 255 |
+
self._stubs: Dict[str, Callable] = {}
|
| 256 |
+
|
| 257 |
+
if api_mtls_endpoint:
|
| 258 |
+
warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning)
|
| 259 |
+
if client_cert_source:
|
| 260 |
+
warnings.warn("client_cert_source is deprecated", DeprecationWarning)
|
| 261 |
+
|
| 262 |
+
if isinstance(channel, aio.Channel):
|
| 263 |
+
# Ignore credentials if a channel was passed.
|
| 264 |
+
credentials = None
|
| 265 |
+
self._ignore_credentials = True
|
| 266 |
+
# If a channel was explicitly provided, set it.
|
| 267 |
+
self._grpc_channel = channel
|
| 268 |
+
self._ssl_channel_credentials = None
|
| 269 |
+
else:
|
| 270 |
+
if api_mtls_endpoint:
|
| 271 |
+
host = api_mtls_endpoint
|
| 272 |
+
|
| 273 |
+
# Create SSL credentials with client_cert_source or application
|
| 274 |
+
# default SSL credentials.
|
| 275 |
+
if client_cert_source:
|
| 276 |
+
cert, key = client_cert_source()
|
| 277 |
+
self._ssl_channel_credentials = grpc.ssl_channel_credentials(
|
| 278 |
+
certificate_chain=cert, private_key=key
|
| 279 |
+
)
|
| 280 |
+
else:
|
| 281 |
+
self._ssl_channel_credentials = SslCredentials().ssl_credentials
|
| 282 |
+
|
| 283 |
+
else:
|
| 284 |
+
if client_cert_source_for_mtls and not ssl_channel_credentials:
|
| 285 |
+
cert, key = client_cert_source_for_mtls()
|
| 286 |
+
self._ssl_channel_credentials = grpc.ssl_channel_credentials(
|
| 287 |
+
certificate_chain=cert, private_key=key
|
| 288 |
+
)
|
| 289 |
+
|
| 290 |
+
# The base transport sets the host, credentials and scopes
|
| 291 |
+
super().__init__(
|
| 292 |
+
host=host,
|
| 293 |
+
credentials=credentials,
|
| 294 |
+
credentials_file=credentials_file,
|
| 295 |
+
scopes=scopes,
|
| 296 |
+
quota_project_id=quota_project_id,
|
| 297 |
+
client_info=client_info,
|
| 298 |
+
always_use_jwt_access=always_use_jwt_access,
|
| 299 |
+
api_audience=api_audience,
|
| 300 |
+
)
|
| 301 |
+
|
| 302 |
+
if not self._grpc_channel:
|
| 303 |
+
# initialize with the provided callable or the default channel
|
| 304 |
+
channel_init = channel or type(self).create_channel
|
| 305 |
+
self._grpc_channel = channel_init(
|
| 306 |
+
self._host,
|
| 307 |
+
# use the credentials which are saved
|
| 308 |
+
credentials=self._credentials,
|
| 309 |
+
# Set ``credentials_file`` to ``None`` here as
|
| 310 |
+
# the credentials that we saved earlier should be used.
|
| 311 |
+
credentials_file=None,
|
| 312 |
+
scopes=self._scopes,
|
| 313 |
+
ssl_credentials=self._ssl_channel_credentials,
|
| 314 |
+
quota_project_id=quota_project_id,
|
| 315 |
+
options=[
|
| 316 |
+
("grpc.max_send_message_length", -1),
|
| 317 |
+
("grpc.max_receive_message_length", -1),
|
| 318 |
+
],
|
| 319 |
+
)
|
| 320 |
+
|
| 321 |
+
self._interceptor = _LoggingClientAIOInterceptor()
|
| 322 |
+
self._grpc_channel._unary_unary_interceptors.append(self._interceptor)
|
| 323 |
+
self._logged_channel = self._grpc_channel
|
| 324 |
+
self._wrap_with_kind = (
|
| 325 |
+
"kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters
|
| 326 |
+
)
|
| 327 |
+
# Wrap messages. This must be done after self._logged_channel exists
|
| 328 |
+
self._prep_wrapped_messages(client_info)
|
| 329 |
+
|
| 330 |
+
@property
|
| 331 |
+
def grpc_channel(self) -> aio.Channel:
|
| 332 |
+
"""Create the channel designed to connect to this service.
|
| 333 |
+
|
| 334 |
+
This property caches on the instance; repeated calls return
|
| 335 |
+
the same channel.
|
| 336 |
+
"""
|
| 337 |
+
# Return the channel from cache.
|
| 338 |
+
return self._grpc_channel
|
| 339 |
+
|
| 340 |
+
@property
|
| 341 |
+
def list_cached_contents(
|
| 342 |
+
self,
|
| 343 |
+
) -> Callable[
|
| 344 |
+
[cache_service.ListCachedContentsRequest],
|
| 345 |
+
Awaitable[cache_service.ListCachedContentsResponse],
|
| 346 |
+
]:
|
| 347 |
+
r"""Return a callable for the list cached contents method over gRPC.
|
| 348 |
+
|
| 349 |
+
Lists CachedContents.
|
| 350 |
+
|
| 351 |
+
Returns:
|
| 352 |
+
Callable[[~.ListCachedContentsRequest],
|
| 353 |
+
Awaitable[~.ListCachedContentsResponse]]:
|
| 354 |
+
A function that, when called, will call the underlying RPC
|
| 355 |
+
on the server.
|
| 356 |
+
"""
|
| 357 |
+
# Generate a "stub function" on-the-fly which will actually make
|
| 358 |
+
# the request.
|
| 359 |
+
# gRPC handles serialization and deserialization, so we just need
|
| 360 |
+
# to pass in the functions for each.
|
| 361 |
+
if "list_cached_contents" not in self._stubs:
|
| 362 |
+
self._stubs["list_cached_contents"] = self._logged_channel.unary_unary(
|
| 363 |
+
"/google.ai.generativelanguage.v1beta.CacheService/ListCachedContents",
|
| 364 |
+
request_serializer=cache_service.ListCachedContentsRequest.serialize,
|
| 365 |
+
response_deserializer=cache_service.ListCachedContentsResponse.deserialize,
|
| 366 |
+
)
|
| 367 |
+
return self._stubs["list_cached_contents"]
|
| 368 |
+
|
| 369 |
+
@property
|
| 370 |
+
def create_cached_content(
|
| 371 |
+
self,
|
| 372 |
+
) -> Callable[
|
| 373 |
+
[cache_service.CreateCachedContentRequest],
|
| 374 |
+
Awaitable[gag_cached_content.CachedContent],
|
| 375 |
+
]:
|
| 376 |
+
r"""Return a callable for the create cached content method over gRPC.
|
| 377 |
+
|
| 378 |
+
Creates CachedContent resource.
|
| 379 |
+
|
| 380 |
+
Returns:
|
| 381 |
+
Callable[[~.CreateCachedContentRequest],
|
| 382 |
+
Awaitable[~.CachedContent]]:
|
| 383 |
+
A function that, when called, will call the underlying RPC
|
| 384 |
+
on the server.
|
| 385 |
+
"""
|
| 386 |
+
# Generate a "stub function" on-the-fly which will actually make
|
| 387 |
+
# the request.
|
| 388 |
+
# gRPC handles serialization and deserialization, so we just need
|
| 389 |
+
# to pass in the functions for each.
|
| 390 |
+
if "create_cached_content" not in self._stubs:
|
| 391 |
+
self._stubs["create_cached_content"] = self._logged_channel.unary_unary(
|
| 392 |
+
"/google.ai.generativelanguage.v1beta.CacheService/CreateCachedContent",
|
| 393 |
+
request_serializer=cache_service.CreateCachedContentRequest.serialize,
|
| 394 |
+
response_deserializer=gag_cached_content.CachedContent.deserialize,
|
| 395 |
+
)
|
| 396 |
+
return self._stubs["create_cached_content"]
|
| 397 |
+
|
| 398 |
+
@property
|
| 399 |
+
def get_cached_content(
|
| 400 |
+
self,
|
| 401 |
+
) -> Callable[
|
| 402 |
+
[cache_service.GetCachedContentRequest], Awaitable[cached_content.CachedContent]
|
| 403 |
+
]:
|
| 404 |
+
r"""Return a callable for the get cached content method over gRPC.
|
| 405 |
+
|
| 406 |
+
Reads CachedContent resource.
|
| 407 |
+
|
| 408 |
+
Returns:
|
| 409 |
+
Callable[[~.GetCachedContentRequest],
|
| 410 |
+
Awaitable[~.CachedContent]]:
|
| 411 |
+
A function that, when called, will call the underlying RPC
|
| 412 |
+
on the server.
|
| 413 |
+
"""
|
| 414 |
+
# Generate a "stub function" on-the-fly which will actually make
|
| 415 |
+
# the request.
|
| 416 |
+
# gRPC handles serialization and deserialization, so we just need
|
| 417 |
+
# to pass in the functions for each.
|
| 418 |
+
if "get_cached_content" not in self._stubs:
|
| 419 |
+
self._stubs["get_cached_content"] = self._logged_channel.unary_unary(
|
| 420 |
+
"/google.ai.generativelanguage.v1beta.CacheService/GetCachedContent",
|
| 421 |
+
request_serializer=cache_service.GetCachedContentRequest.serialize,
|
| 422 |
+
response_deserializer=cached_content.CachedContent.deserialize,
|
| 423 |
+
)
|
| 424 |
+
return self._stubs["get_cached_content"]
|
| 425 |
+
|
| 426 |
+
@property
|
| 427 |
+
def update_cached_content(
|
| 428 |
+
self,
|
| 429 |
+
) -> Callable[
|
| 430 |
+
[cache_service.UpdateCachedContentRequest],
|
| 431 |
+
Awaitable[gag_cached_content.CachedContent],
|
| 432 |
+
]:
|
| 433 |
+
r"""Return a callable for the update cached content method over gRPC.
|
| 434 |
+
|
| 435 |
+
Updates CachedContent resource (only expiration is
|
| 436 |
+
updatable).
|
| 437 |
+
|
| 438 |
+
Returns:
|
| 439 |
+
Callable[[~.UpdateCachedContentRequest],
|
| 440 |
+
Awaitable[~.CachedContent]]:
|
| 441 |
+
A function that, when called, will call the underlying RPC
|
| 442 |
+
on the server.
|
| 443 |
+
"""
|
| 444 |
+
# Generate a "stub function" on-the-fly which will actually make
|
| 445 |
+
# the request.
|
| 446 |
+
# gRPC handles serialization and deserialization, so we just need
|
| 447 |
+
# to pass in the functions for each.
|
| 448 |
+
if "update_cached_content" not in self._stubs:
|
| 449 |
+
self._stubs["update_cached_content"] = self._logged_channel.unary_unary(
|
| 450 |
+
"/google.ai.generativelanguage.v1beta.CacheService/UpdateCachedContent",
|
| 451 |
+
request_serializer=cache_service.UpdateCachedContentRequest.serialize,
|
| 452 |
+
response_deserializer=gag_cached_content.CachedContent.deserialize,
|
| 453 |
+
)
|
| 454 |
+
return self._stubs["update_cached_content"]
|
| 455 |
+
|
| 456 |
+
@property
|
| 457 |
+
def delete_cached_content(
|
| 458 |
+
self,
|
| 459 |
+
) -> Callable[
|
| 460 |
+
[cache_service.DeleteCachedContentRequest], Awaitable[empty_pb2.Empty]
|
| 461 |
+
]:
|
| 462 |
+
r"""Return a callable for the delete cached content method over gRPC.
|
| 463 |
+
|
| 464 |
+
Deletes CachedContent resource.
|
| 465 |
+
|
| 466 |
+
Returns:
|
| 467 |
+
Callable[[~.DeleteCachedContentRequest],
|
| 468 |
+
Awaitable[~.Empty]]:
|
| 469 |
+
A function that, when called, will call the underlying RPC
|
| 470 |
+
on the server.
|
| 471 |
+
"""
|
| 472 |
+
# Generate a "stub function" on-the-fly which will actually make
|
| 473 |
+
# the request.
|
| 474 |
+
# gRPC handles serialization and deserialization, so we just need
|
| 475 |
+
# to pass in the functions for each.
|
| 476 |
+
if "delete_cached_content" not in self._stubs:
|
| 477 |
+
self._stubs["delete_cached_content"] = self._logged_channel.unary_unary(
|
| 478 |
+
"/google.ai.generativelanguage.v1beta.CacheService/DeleteCachedContent",
|
| 479 |
+
request_serializer=cache_service.DeleteCachedContentRequest.serialize,
|
| 480 |
+
response_deserializer=empty_pb2.Empty.FromString,
|
| 481 |
+
)
|
| 482 |
+
return self._stubs["delete_cached_content"]
|
| 483 |
+
|
| 484 |
+
def _prep_wrapped_messages(self, client_info):
|
| 485 |
+
"""Precompute the wrapped methods, overriding the base class method to use async wrappers."""
|
| 486 |
+
self._wrapped_methods = {
|
| 487 |
+
self.list_cached_contents: self._wrap_method(
|
| 488 |
+
self.list_cached_contents,
|
| 489 |
+
default_timeout=None,
|
| 490 |
+
client_info=client_info,
|
| 491 |
+
),
|
| 492 |
+
self.create_cached_content: self._wrap_method(
|
| 493 |
+
self.create_cached_content,
|
| 494 |
+
default_timeout=None,
|
| 495 |
+
client_info=client_info,
|
| 496 |
+
),
|
| 497 |
+
self.get_cached_content: self._wrap_method(
|
| 498 |
+
self.get_cached_content,
|
| 499 |
+
default_timeout=None,
|
| 500 |
+
client_info=client_info,
|
| 501 |
+
),
|
| 502 |
+
self.update_cached_content: self._wrap_method(
|
| 503 |
+
self.update_cached_content,
|
| 504 |
+
default_timeout=None,
|
| 505 |
+
client_info=client_info,
|
| 506 |
+
),
|
| 507 |
+
self.delete_cached_content: self._wrap_method(
|
| 508 |
+
self.delete_cached_content,
|
| 509 |
+
default_timeout=None,
|
| 510 |
+
client_info=client_info,
|
| 511 |
+
),
|
| 512 |
+
self.get_operation: self._wrap_method(
|
| 513 |
+
self.get_operation,
|
| 514 |
+
default_timeout=None,
|
| 515 |
+
client_info=client_info,
|
| 516 |
+
),
|
| 517 |
+
self.list_operations: self._wrap_method(
|
| 518 |
+
self.list_operations,
|
| 519 |
+
default_timeout=None,
|
| 520 |
+
client_info=client_info,
|
| 521 |
+
),
|
| 522 |
+
}
|
| 523 |
+
|
| 524 |
+
def _wrap_method(self, func, *args, **kwargs):
|
| 525 |
+
if self._wrap_with_kind: # pragma: NO COVER
|
| 526 |
+
kwargs["kind"] = self.kind
|
| 527 |
+
return gapic_v1.method_async.wrap_method(func, *args, **kwargs)
|
| 528 |
+
|
| 529 |
+
def close(self):
|
| 530 |
+
return self._logged_channel.close()
|
| 531 |
+
|
| 532 |
+
@property
|
| 533 |
+
def kind(self) -> str:
|
| 534 |
+
return "grpc_asyncio"
|
| 535 |
+
|
| 536 |
+
@property
|
| 537 |
+
def get_operation(
|
| 538 |
+
self,
|
| 539 |
+
) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]:
|
| 540 |
+
r"""Return a callable for the get_operation method over gRPC."""
|
| 541 |
+
# Generate a "stub function" on-the-fly which will actually make
|
| 542 |
+
# the request.
|
| 543 |
+
# gRPC handles serialization and deserialization, so we just need
|
| 544 |
+
# to pass in the functions for each.
|
| 545 |
+
if "get_operation" not in self._stubs:
|
| 546 |
+
self._stubs["get_operation"] = self._logged_channel.unary_unary(
|
| 547 |
+
"/google.longrunning.Operations/GetOperation",
|
| 548 |
+
request_serializer=operations_pb2.GetOperationRequest.SerializeToString,
|
| 549 |
+
response_deserializer=operations_pb2.Operation.FromString,
|
| 550 |
+
)
|
| 551 |
+
return self._stubs["get_operation"]
|
| 552 |
+
|
| 553 |
+
@property
|
| 554 |
+
def list_operations(
|
| 555 |
+
self,
|
| 556 |
+
) -> Callable[
|
| 557 |
+
[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse
|
| 558 |
+
]:
|
| 559 |
+
r"""Return a callable for the list_operations method over gRPC."""
|
| 560 |
+
# Generate a "stub function" on-the-fly which will actually make
|
| 561 |
+
# the request.
|
| 562 |
+
# gRPC handles serialization and deserialization, so we just need
|
| 563 |
+
# to pass in the functions for each.
|
| 564 |
+
if "list_operations" not in self._stubs:
|
| 565 |
+
self._stubs["list_operations"] = self._logged_channel.unary_unary(
|
| 566 |
+
"/google.longrunning.Operations/ListOperations",
|
| 567 |
+
request_serializer=operations_pb2.ListOperationsRequest.SerializeToString,
|
| 568 |
+
response_deserializer=operations_pb2.ListOperationsResponse.FromString,
|
| 569 |
+
)
|
| 570 |
+
return self._stubs["list_operations"]
|
| 571 |
+
|
| 572 |
+
|
| 573 |
+
__all__ = ("CacheServiceGrpcAsyncIOTransport",)
|
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/cache_service/transports/rest.py
ADDED
|
@@ -0,0 +1,1428 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Copyright 2024 Google LLC
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
#
|
| 16 |
+
import dataclasses
|
| 17 |
+
import json # type: ignore
|
| 18 |
+
import logging
|
| 19 |
+
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union
|
| 20 |
+
import warnings
|
| 21 |
+
|
| 22 |
+
from google.api_core import exceptions as core_exceptions
|
| 23 |
+
from google.api_core import gapic_v1, rest_helpers, rest_streaming
|
| 24 |
+
from google.api_core import retry as retries
|
| 25 |
+
from google.auth import credentials as ga_credentials # type: ignore
|
| 26 |
+
from google.auth.transport.requests import AuthorizedSession # type: ignore
|
| 27 |
+
from google.longrunning import operations_pb2 # type: ignore
|
| 28 |
+
from google.protobuf import empty_pb2 # type: ignore
|
| 29 |
+
from google.protobuf import json_format
|
| 30 |
+
from requests import __version__ as requests_version
|
| 31 |
+
|
| 32 |
+
from google.ai.generativelanguage_v1beta.types import (
|
| 33 |
+
cached_content as gag_cached_content,
|
| 34 |
+
)
|
| 35 |
+
from google.ai.generativelanguage_v1beta.types import cache_service
|
| 36 |
+
from google.ai.generativelanguage_v1beta.types import cached_content
|
| 37 |
+
|
| 38 |
+
from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO
|
| 39 |
+
from .rest_base import _BaseCacheServiceRestTransport
|
| 40 |
+
|
| 41 |
+
try:
|
| 42 |
+
OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None]
|
| 43 |
+
except AttributeError: # pragma: NO COVER
|
| 44 |
+
OptionalRetry = Union[retries.Retry, object, None] # type: ignore
|
| 45 |
+
|
| 46 |
+
try:
|
| 47 |
+
from google.api_core import client_logging # type: ignore
|
| 48 |
+
|
| 49 |
+
CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER
|
| 50 |
+
except ImportError: # pragma: NO COVER
|
| 51 |
+
CLIENT_LOGGING_SUPPORTED = False
|
| 52 |
+
|
| 53 |
+
_LOGGER = logging.getLogger(__name__)
|
| 54 |
+
|
| 55 |
+
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
|
| 56 |
+
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
|
| 57 |
+
grpc_version=None,
|
| 58 |
+
rest_version=f"requests@{requests_version}",
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
class CacheServiceRestInterceptor:
|
| 63 |
+
"""Interceptor for CacheService.
|
| 64 |
+
|
| 65 |
+
Interceptors are used to manipulate requests, request metadata, and responses
|
| 66 |
+
in arbitrary ways.
|
| 67 |
+
Example use cases include:
|
| 68 |
+
* Logging
|
| 69 |
+
* Verifying requests according to service or custom semantics
|
| 70 |
+
* Stripping extraneous information from responses
|
| 71 |
+
|
| 72 |
+
These use cases and more can be enabled by injecting an
|
| 73 |
+
instance of a custom subclass when constructing the CacheServiceRestTransport.
|
| 74 |
+
|
| 75 |
+
.. code-block:: python
|
| 76 |
+
class MyCustomCacheServiceInterceptor(CacheServiceRestInterceptor):
|
| 77 |
+
def pre_create_cached_content(self, request, metadata):
|
| 78 |
+
logging.log(f"Received request: {request}")
|
| 79 |
+
return request, metadata
|
| 80 |
+
|
| 81 |
+
def post_create_cached_content(self, response):
|
| 82 |
+
logging.log(f"Received response: {response}")
|
| 83 |
+
return response
|
| 84 |
+
|
| 85 |
+
def pre_delete_cached_content(self, request, metadata):
|
| 86 |
+
logging.log(f"Received request: {request}")
|
| 87 |
+
return request, metadata
|
| 88 |
+
|
| 89 |
+
def pre_get_cached_content(self, request, metadata):
|
| 90 |
+
logging.log(f"Received request: {request}")
|
| 91 |
+
return request, metadata
|
| 92 |
+
|
| 93 |
+
def post_get_cached_content(self, response):
|
| 94 |
+
logging.log(f"Received response: {response}")
|
| 95 |
+
return response
|
| 96 |
+
|
| 97 |
+
def pre_list_cached_contents(self, request, metadata):
|
| 98 |
+
logging.log(f"Received request: {request}")
|
| 99 |
+
return request, metadata
|
| 100 |
+
|
| 101 |
+
def post_list_cached_contents(self, response):
|
| 102 |
+
logging.log(f"Received response: {response}")
|
| 103 |
+
return response
|
| 104 |
+
|
| 105 |
+
def pre_update_cached_content(self, request, metadata):
|
| 106 |
+
logging.log(f"Received request: {request}")
|
| 107 |
+
return request, metadata
|
| 108 |
+
|
| 109 |
+
def post_update_cached_content(self, response):
|
| 110 |
+
logging.log(f"Received response: {response}")
|
| 111 |
+
return response
|
| 112 |
+
|
| 113 |
+
transport = CacheServiceRestTransport(interceptor=MyCustomCacheServiceInterceptor())
|
| 114 |
+
client = CacheServiceClient(transport=transport)
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
"""
|
| 118 |
+
|
| 119 |
+
def pre_create_cached_content(
|
| 120 |
+
self,
|
| 121 |
+
request: cache_service.CreateCachedContentRequest,
|
| 122 |
+
metadata: Sequence[Tuple[str, Union[str, bytes]]],
|
| 123 |
+
) -> Tuple[
|
| 124 |
+
cache_service.CreateCachedContentRequest,
|
| 125 |
+
Sequence[Tuple[str, Union[str, bytes]]],
|
| 126 |
+
]:
|
| 127 |
+
"""Pre-rpc interceptor for create_cached_content
|
| 128 |
+
|
| 129 |
+
Override in a subclass to manipulate the request or metadata
|
| 130 |
+
before they are sent to the CacheService server.
|
| 131 |
+
"""
|
| 132 |
+
return request, metadata
|
| 133 |
+
|
| 134 |
+
def post_create_cached_content(
|
| 135 |
+
self, response: gag_cached_content.CachedContent
|
| 136 |
+
) -> gag_cached_content.CachedContent:
|
| 137 |
+
"""Post-rpc interceptor for create_cached_content
|
| 138 |
+
|
| 139 |
+
Override in a subclass to manipulate the response
|
| 140 |
+
after it is returned by the CacheService server but before
|
| 141 |
+
it is returned to user code.
|
| 142 |
+
"""
|
| 143 |
+
return response
|
| 144 |
+
|
| 145 |
+
def pre_delete_cached_content(
|
| 146 |
+
self,
|
| 147 |
+
request: cache_service.DeleteCachedContentRequest,
|
| 148 |
+
metadata: Sequence[Tuple[str, Union[str, bytes]]],
|
| 149 |
+
) -> Tuple[
|
| 150 |
+
cache_service.DeleteCachedContentRequest,
|
| 151 |
+
Sequence[Tuple[str, Union[str, bytes]]],
|
| 152 |
+
]:
|
| 153 |
+
"""Pre-rpc interceptor for delete_cached_content
|
| 154 |
+
|
| 155 |
+
Override in a subclass to manipulate the request or metadata
|
| 156 |
+
before they are sent to the CacheService server.
|
| 157 |
+
"""
|
| 158 |
+
return request, metadata
|
| 159 |
+
|
| 160 |
+
def pre_get_cached_content(
|
| 161 |
+
self,
|
| 162 |
+
request: cache_service.GetCachedContentRequest,
|
| 163 |
+
metadata: Sequence[Tuple[str, Union[str, bytes]]],
|
| 164 |
+
) -> Tuple[
|
| 165 |
+
cache_service.GetCachedContentRequest, Sequence[Tuple[str, Union[str, bytes]]]
|
| 166 |
+
]:
|
| 167 |
+
"""Pre-rpc interceptor for get_cached_content
|
| 168 |
+
|
| 169 |
+
Override in a subclass to manipulate the request or metadata
|
| 170 |
+
before they are sent to the CacheService server.
|
| 171 |
+
"""
|
| 172 |
+
return request, metadata
|
| 173 |
+
|
| 174 |
+
def post_get_cached_content(
|
| 175 |
+
self, response: cached_content.CachedContent
|
| 176 |
+
) -> cached_content.CachedContent:
|
| 177 |
+
"""Post-rpc interceptor for get_cached_content
|
| 178 |
+
|
| 179 |
+
Override in a subclass to manipulate the response
|
| 180 |
+
after it is returned by the CacheService server but before
|
| 181 |
+
it is returned to user code.
|
| 182 |
+
"""
|
| 183 |
+
return response
|
| 184 |
+
|
| 185 |
+
def pre_list_cached_contents(
|
| 186 |
+
self,
|
| 187 |
+
request: cache_service.ListCachedContentsRequest,
|
| 188 |
+
metadata: Sequence[Tuple[str, Union[str, bytes]]],
|
| 189 |
+
) -> Tuple[
|
| 190 |
+
cache_service.ListCachedContentsRequest, Sequence[Tuple[str, Union[str, bytes]]]
|
| 191 |
+
]:
|
| 192 |
+
"""Pre-rpc interceptor for list_cached_contents
|
| 193 |
+
|
| 194 |
+
Override in a subclass to manipulate the request or metadata
|
| 195 |
+
before they are sent to the CacheService server.
|
| 196 |
+
"""
|
| 197 |
+
return request, metadata
|
| 198 |
+
|
| 199 |
+
def post_list_cached_contents(
|
| 200 |
+
self, response: cache_service.ListCachedContentsResponse
|
| 201 |
+
) -> cache_service.ListCachedContentsResponse:
|
| 202 |
+
"""Post-rpc interceptor for list_cached_contents
|
| 203 |
+
|
| 204 |
+
Override in a subclass to manipulate the response
|
| 205 |
+
after it is returned by the CacheService server but before
|
| 206 |
+
it is returned to user code.
|
| 207 |
+
"""
|
| 208 |
+
return response
|
| 209 |
+
|
| 210 |
+
def pre_update_cached_content(
|
| 211 |
+
self,
|
| 212 |
+
request: cache_service.UpdateCachedContentRequest,
|
| 213 |
+
metadata: Sequence[Tuple[str, Union[str, bytes]]],
|
| 214 |
+
) -> Tuple[
|
| 215 |
+
cache_service.UpdateCachedContentRequest,
|
| 216 |
+
Sequence[Tuple[str, Union[str, bytes]]],
|
| 217 |
+
]:
|
| 218 |
+
"""Pre-rpc interceptor for update_cached_content
|
| 219 |
+
|
| 220 |
+
Override in a subclass to manipulate the request or metadata
|
| 221 |
+
before they are sent to the CacheService server.
|
| 222 |
+
"""
|
| 223 |
+
return request, metadata
|
| 224 |
+
|
| 225 |
+
def post_update_cached_content(
|
| 226 |
+
self, response: gag_cached_content.CachedContent
|
| 227 |
+
) -> gag_cached_content.CachedContent:
|
| 228 |
+
"""Post-rpc interceptor for update_cached_content
|
| 229 |
+
|
| 230 |
+
Override in a subclass to manipulate the response
|
| 231 |
+
after it is returned by the CacheService server but before
|
| 232 |
+
it is returned to user code.
|
| 233 |
+
"""
|
| 234 |
+
return response
|
| 235 |
+
|
| 236 |
+
def pre_get_operation(
|
| 237 |
+
self,
|
| 238 |
+
request: operations_pb2.GetOperationRequest,
|
| 239 |
+
metadata: Sequence[Tuple[str, Union[str, bytes]]],
|
| 240 |
+
) -> Tuple[
|
| 241 |
+
operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]
|
| 242 |
+
]:
|
| 243 |
+
"""Pre-rpc interceptor for get_operation
|
| 244 |
+
|
| 245 |
+
Override in a subclass to manipulate the request or metadata
|
| 246 |
+
before they are sent to the CacheService server.
|
| 247 |
+
"""
|
| 248 |
+
return request, metadata
|
| 249 |
+
|
| 250 |
+
def post_get_operation(
|
| 251 |
+
self, response: operations_pb2.Operation
|
| 252 |
+
) -> operations_pb2.Operation:
|
| 253 |
+
"""Post-rpc interceptor for get_operation
|
| 254 |
+
|
| 255 |
+
Override in a subclass to manipulate the response
|
| 256 |
+
after it is returned by the CacheService server but before
|
| 257 |
+
it is returned to user code.
|
| 258 |
+
"""
|
| 259 |
+
return response
|
| 260 |
+
|
| 261 |
+
def pre_list_operations(
|
| 262 |
+
self,
|
| 263 |
+
request: operations_pb2.ListOperationsRequest,
|
| 264 |
+
metadata: Sequence[Tuple[str, Union[str, bytes]]],
|
| 265 |
+
) -> Tuple[
|
| 266 |
+
operations_pb2.ListOperationsRequest, Sequence[Tuple[str, Union[str, bytes]]]
|
| 267 |
+
]:
|
| 268 |
+
"""Pre-rpc interceptor for list_operations
|
| 269 |
+
|
| 270 |
+
Override in a subclass to manipulate the request or metadata
|
| 271 |
+
before they are sent to the CacheService server.
|
| 272 |
+
"""
|
| 273 |
+
return request, metadata
|
| 274 |
+
|
| 275 |
+
def post_list_operations(
|
| 276 |
+
self, response: operations_pb2.ListOperationsResponse
|
| 277 |
+
) -> operations_pb2.ListOperationsResponse:
|
| 278 |
+
"""Post-rpc interceptor for list_operations
|
| 279 |
+
|
| 280 |
+
Override in a subclass to manipulate the response
|
| 281 |
+
after it is returned by the CacheService server but before
|
| 282 |
+
it is returned to user code.
|
| 283 |
+
"""
|
| 284 |
+
return response
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
@dataclasses.dataclass
|
| 288 |
+
class CacheServiceRestStub:
|
| 289 |
+
_session: AuthorizedSession
|
| 290 |
+
_host: str
|
| 291 |
+
_interceptor: CacheServiceRestInterceptor
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
class CacheServiceRestTransport(_BaseCacheServiceRestTransport):
|
| 295 |
+
"""REST backend synchronous transport for CacheService.
|
| 296 |
+
|
| 297 |
+
API for managing cache of content (CachedContent resources)
|
| 298 |
+
that can be used in GenerativeService requests. This way
|
| 299 |
+
generate content requests can benefit from preprocessing work
|
| 300 |
+
being done earlier, possibly lowering their computational cost.
|
| 301 |
+
It is intended to be used with large contexts.
|
| 302 |
+
|
| 303 |
+
This class defines the same methods as the primary client, so the
|
| 304 |
+
primary client can load the underlying transport implementation
|
| 305 |
+
and call it.
|
| 306 |
+
|
| 307 |
+
It sends JSON representations of protocol buffers over HTTP/1.1
|
| 308 |
+
"""
|
| 309 |
+
|
| 310 |
+
def __init__(
|
| 311 |
+
self,
|
| 312 |
+
*,
|
| 313 |
+
host: str = "generativelanguage.googleapis.com",
|
| 314 |
+
credentials: Optional[ga_credentials.Credentials] = None,
|
| 315 |
+
credentials_file: Optional[str] = None,
|
| 316 |
+
scopes: Optional[Sequence[str]] = None,
|
| 317 |
+
client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None,
|
| 318 |
+
quota_project_id: Optional[str] = None,
|
| 319 |
+
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
|
| 320 |
+
always_use_jwt_access: Optional[bool] = False,
|
| 321 |
+
url_scheme: str = "https",
|
| 322 |
+
interceptor: Optional[CacheServiceRestInterceptor] = None,
|
| 323 |
+
api_audience: Optional[str] = None,
|
| 324 |
+
) -> None:
|
| 325 |
+
"""Instantiate the transport.
|
| 326 |
+
|
| 327 |
+
Args:
|
| 328 |
+
host (Optional[str]):
|
| 329 |
+
The hostname to connect to (default: 'generativelanguage.googleapis.com').
|
| 330 |
+
credentials (Optional[google.auth.credentials.Credentials]): The
|
| 331 |
+
authorization credentials to attach to requests. These
|
| 332 |
+
credentials identify the application to the service; if none
|
| 333 |
+
are specified, the client will attempt to ascertain the
|
| 334 |
+
credentials from the environment.
|
| 335 |
+
|
| 336 |
+
credentials_file (Optional[str]): A file with credentials that can
|
| 337 |
+
be loaded with :func:`google.auth.load_credentials_from_file`.
|
| 338 |
+
This argument is ignored if ``channel`` is provided.
|
| 339 |
+
scopes (Optional(Sequence[str])): A list of scopes. This argument is
|
| 340 |
+
ignored if ``channel`` is provided.
|
| 341 |
+
client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client
|
| 342 |
+
certificate to configure mutual TLS HTTP channel. It is ignored
|
| 343 |
+
if ``channel`` is provided.
|
| 344 |
+
quota_project_id (Optional[str]): An optional project to use for billing
|
| 345 |
+
and quota.
|
| 346 |
+
client_info (google.api_core.gapic_v1.client_info.ClientInfo):
|
| 347 |
+
The client info used to send a user-agent string along with
|
| 348 |
+
API requests. If ``None``, then default info will be used.
|
| 349 |
+
Generally, you only need to set this if you are developing
|
| 350 |
+
your own client library.
|
| 351 |
+
always_use_jwt_access (Optional[bool]): Whether self signed JWT should
|
| 352 |
+
be used for service account credentials.
|
| 353 |
+
url_scheme: the protocol scheme for the API endpoint. Normally
|
| 354 |
+
"https", but for testing or local servers,
|
| 355 |
+
"http" can be specified.
|
| 356 |
+
"""
|
| 357 |
+
# Run the base constructor
|
| 358 |
+
# TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc.
|
| 359 |
+
# TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the
|
| 360 |
+
# credentials object
|
| 361 |
+
super().__init__(
|
| 362 |
+
host=host,
|
| 363 |
+
credentials=credentials,
|
| 364 |
+
client_info=client_info,
|
| 365 |
+
always_use_jwt_access=always_use_jwt_access,
|
| 366 |
+
url_scheme=url_scheme,
|
| 367 |
+
api_audience=api_audience,
|
| 368 |
+
)
|
| 369 |
+
self._session = AuthorizedSession(
|
| 370 |
+
self._credentials, default_host=self.DEFAULT_HOST
|
| 371 |
+
)
|
| 372 |
+
if client_cert_source_for_mtls:
|
| 373 |
+
self._session.configure_mtls_channel(client_cert_source_for_mtls)
|
| 374 |
+
self._interceptor = interceptor or CacheServiceRestInterceptor()
|
| 375 |
+
self._prep_wrapped_messages(client_info)
|
| 376 |
+
|
| 377 |
+
class _CreateCachedContent(
|
| 378 |
+
_BaseCacheServiceRestTransport._BaseCreateCachedContent, CacheServiceRestStub
|
| 379 |
+
):
|
| 380 |
+
def __hash__(self):
|
| 381 |
+
return hash("CacheServiceRestTransport.CreateCachedContent")
|
| 382 |
+
|
| 383 |
+
@staticmethod
|
| 384 |
+
def _get_response(
|
| 385 |
+
host,
|
| 386 |
+
metadata,
|
| 387 |
+
query_params,
|
| 388 |
+
session,
|
| 389 |
+
timeout,
|
| 390 |
+
transcoded_request,
|
| 391 |
+
body=None,
|
| 392 |
+
):
|
| 393 |
+
uri = transcoded_request["uri"]
|
| 394 |
+
method = transcoded_request["method"]
|
| 395 |
+
headers = dict(metadata)
|
| 396 |
+
headers["Content-Type"] = "application/json"
|
| 397 |
+
response = getattr(session, method)(
|
| 398 |
+
"{host}{uri}".format(host=host, uri=uri),
|
| 399 |
+
timeout=timeout,
|
| 400 |
+
headers=headers,
|
| 401 |
+
params=rest_helpers.flatten_query_params(query_params, strict=True),
|
| 402 |
+
data=body,
|
| 403 |
+
)
|
| 404 |
+
return response
|
| 405 |
+
|
| 406 |
+
def __call__(
|
| 407 |
+
self,
|
| 408 |
+
request: cache_service.CreateCachedContentRequest,
|
| 409 |
+
*,
|
| 410 |
+
retry: OptionalRetry = gapic_v1.method.DEFAULT,
|
| 411 |
+
timeout: Optional[float] = None,
|
| 412 |
+
metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
|
| 413 |
+
) -> gag_cached_content.CachedContent:
|
| 414 |
+
r"""Call the create cached content method over HTTP.
|
| 415 |
+
|
| 416 |
+
Args:
|
| 417 |
+
request (~.cache_service.CreateCachedContentRequest):
|
| 418 |
+
The request object. Request to create CachedContent.
|
| 419 |
+
retry (google.api_core.retry.Retry): Designation of what errors, if any,
|
| 420 |
+
should be retried.
|
| 421 |
+
timeout (float): The timeout for this request.
|
| 422 |
+
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
|
| 423 |
+
sent along with the request as metadata. Normally, each value must be of type `str`,
|
| 424 |
+
but for metadata keys ending with the suffix `-bin`, the corresponding values must
|
| 425 |
+
be of type `bytes`.
|
| 426 |
+
|
| 427 |
+
Returns:
|
| 428 |
+
~.gag_cached_content.CachedContent:
|
| 429 |
+
Content that has been preprocessed
|
| 430 |
+
and can be used in subsequent request to
|
| 431 |
+
GenerativeService.
|
| 432 |
+
|
| 433 |
+
Cached content can be only used with
|
| 434 |
+
model it was created for.
|
| 435 |
+
|
| 436 |
+
"""
|
| 437 |
+
|
| 438 |
+
http_options = (
|
| 439 |
+
_BaseCacheServiceRestTransport._BaseCreateCachedContent._get_http_options()
|
| 440 |
+
)
|
| 441 |
+
|
| 442 |
+
request, metadata = self._interceptor.pre_create_cached_content(
|
| 443 |
+
request, metadata
|
| 444 |
+
)
|
| 445 |
+
transcoded_request = _BaseCacheServiceRestTransport._BaseCreateCachedContent._get_transcoded_request(
|
| 446 |
+
http_options, request
|
| 447 |
+
)
|
| 448 |
+
|
| 449 |
+
body = _BaseCacheServiceRestTransport._BaseCreateCachedContent._get_request_body_json(
|
| 450 |
+
transcoded_request
|
| 451 |
+
)
|
| 452 |
+
|
| 453 |
+
# Jsonify the query params
|
| 454 |
+
query_params = _BaseCacheServiceRestTransport._BaseCreateCachedContent._get_query_params_json(
|
| 455 |
+
transcoded_request
|
| 456 |
+
)
|
| 457 |
+
|
| 458 |
+
if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
|
| 459 |
+
logging.DEBUG
|
| 460 |
+
): # pragma: NO COVER
|
| 461 |
+
request_url = "{host}{uri}".format(
|
| 462 |
+
host=self._host, uri=transcoded_request["uri"]
|
| 463 |
+
)
|
| 464 |
+
method = transcoded_request["method"]
|
| 465 |
+
try:
|
| 466 |
+
request_payload = type(request).to_json(request)
|
| 467 |
+
except:
|
| 468 |
+
request_payload = None
|
| 469 |
+
http_request = {
|
| 470 |
+
"payload": request_payload,
|
| 471 |
+
"requestMethod": method,
|
| 472 |
+
"requestUrl": request_url,
|
| 473 |
+
"headers": dict(metadata),
|
| 474 |
+
}
|
| 475 |
+
_LOGGER.debug(
|
| 476 |
+
f"Sending request for google.ai.generativelanguage_v1beta.CacheServiceClient.CreateCachedContent",
|
| 477 |
+
extra={
|
| 478 |
+
"serviceName": "google.ai.generativelanguage.v1beta.CacheService",
|
| 479 |
+
"rpcName": "CreateCachedContent",
|
| 480 |
+
"httpRequest": http_request,
|
| 481 |
+
"metadata": http_request["headers"],
|
| 482 |
+
},
|
| 483 |
+
)
|
| 484 |
+
|
| 485 |
+
# Send the request
|
| 486 |
+
response = CacheServiceRestTransport._CreateCachedContent._get_response(
|
| 487 |
+
self._host,
|
| 488 |
+
metadata,
|
| 489 |
+
query_params,
|
| 490 |
+
self._session,
|
| 491 |
+
timeout,
|
| 492 |
+
transcoded_request,
|
| 493 |
+
body,
|
| 494 |
+
)
|
| 495 |
+
|
| 496 |
+
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
|
| 497 |
+
# subclass.
|
| 498 |
+
if response.status_code >= 400:
|
| 499 |
+
raise core_exceptions.from_http_response(response)
|
| 500 |
+
|
| 501 |
+
# Return the response
|
| 502 |
+
resp = gag_cached_content.CachedContent()
|
| 503 |
+
pb_resp = gag_cached_content.CachedContent.pb(resp)
|
| 504 |
+
|
| 505 |
+
json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
|
| 506 |
+
|
| 507 |
+
resp = self._interceptor.post_create_cached_content(resp)
|
| 508 |
+
if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
|
| 509 |
+
logging.DEBUG
|
| 510 |
+
): # pragma: NO COVER
|
| 511 |
+
try:
|
| 512 |
+
response_payload = gag_cached_content.CachedContent.to_json(
|
| 513 |
+
response
|
| 514 |
+
)
|
| 515 |
+
except:
|
| 516 |
+
response_payload = None
|
| 517 |
+
http_response = {
|
| 518 |
+
"payload": response_payload,
|
| 519 |
+
"headers": dict(response.headers),
|
| 520 |
+
"status": response.status_code,
|
| 521 |
+
}
|
| 522 |
+
_LOGGER.debug(
|
| 523 |
+
"Received response for google.ai.generativelanguage_v1beta.CacheServiceClient.create_cached_content",
|
| 524 |
+
extra={
|
| 525 |
+
"serviceName": "google.ai.generativelanguage.v1beta.CacheService",
|
| 526 |
+
"rpcName": "CreateCachedContent",
|
| 527 |
+
"metadata": http_response["headers"],
|
| 528 |
+
"httpResponse": http_response,
|
| 529 |
+
},
|
| 530 |
+
)
|
| 531 |
+
return resp
|
| 532 |
+
|
| 533 |
+
class _DeleteCachedContent(
|
| 534 |
+
_BaseCacheServiceRestTransport._BaseDeleteCachedContent, CacheServiceRestStub
|
| 535 |
+
):
|
| 536 |
+
def __hash__(self):
|
| 537 |
+
return hash("CacheServiceRestTransport.DeleteCachedContent")
|
| 538 |
+
|
| 539 |
+
@staticmethod
|
| 540 |
+
def _get_response(
|
| 541 |
+
host,
|
| 542 |
+
metadata,
|
| 543 |
+
query_params,
|
| 544 |
+
session,
|
| 545 |
+
timeout,
|
| 546 |
+
transcoded_request,
|
| 547 |
+
body=None,
|
| 548 |
+
):
|
| 549 |
+
uri = transcoded_request["uri"]
|
| 550 |
+
method = transcoded_request["method"]
|
| 551 |
+
headers = dict(metadata)
|
| 552 |
+
headers["Content-Type"] = "application/json"
|
| 553 |
+
response = getattr(session, method)(
|
| 554 |
+
"{host}{uri}".format(host=host, uri=uri),
|
| 555 |
+
timeout=timeout,
|
| 556 |
+
headers=headers,
|
| 557 |
+
params=rest_helpers.flatten_query_params(query_params, strict=True),
|
| 558 |
+
)
|
| 559 |
+
return response
|
| 560 |
+
|
| 561 |
+
def __call__(
|
| 562 |
+
self,
|
| 563 |
+
request: cache_service.DeleteCachedContentRequest,
|
| 564 |
+
*,
|
| 565 |
+
retry: OptionalRetry = gapic_v1.method.DEFAULT,
|
| 566 |
+
timeout: Optional[float] = None,
|
| 567 |
+
metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
|
| 568 |
+
):
|
| 569 |
+
r"""Call the delete cached content method over HTTP.
|
| 570 |
+
|
| 571 |
+
Args:
|
| 572 |
+
request (~.cache_service.DeleteCachedContentRequest):
|
| 573 |
+
The request object. Request to delete CachedContent.
|
| 574 |
+
retry (google.api_core.retry.Retry): Designation of what errors, if any,
|
| 575 |
+
should be retried.
|
| 576 |
+
timeout (float): The timeout for this request.
|
| 577 |
+
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
|
| 578 |
+
sent along with the request as metadata. Normally, each value must be of type `str`,
|
| 579 |
+
but for metadata keys ending with the suffix `-bin`, the corresponding values must
|
| 580 |
+
be of type `bytes`.
|
| 581 |
+
"""
|
| 582 |
+
|
| 583 |
+
http_options = (
|
| 584 |
+
_BaseCacheServiceRestTransport._BaseDeleteCachedContent._get_http_options()
|
| 585 |
+
)
|
| 586 |
+
|
| 587 |
+
request, metadata = self._interceptor.pre_delete_cached_content(
|
| 588 |
+
request, metadata
|
| 589 |
+
)
|
| 590 |
+
transcoded_request = _BaseCacheServiceRestTransport._BaseDeleteCachedContent._get_transcoded_request(
|
| 591 |
+
http_options, request
|
| 592 |
+
)
|
| 593 |
+
|
| 594 |
+
# Jsonify the query params
|
| 595 |
+
query_params = _BaseCacheServiceRestTransport._BaseDeleteCachedContent._get_query_params_json(
|
| 596 |
+
transcoded_request
|
| 597 |
+
)
|
| 598 |
+
|
| 599 |
+
if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
|
| 600 |
+
logging.DEBUG
|
| 601 |
+
): # pragma: NO COVER
|
| 602 |
+
request_url = "{host}{uri}".format(
|
| 603 |
+
host=self._host, uri=transcoded_request["uri"]
|
| 604 |
+
)
|
| 605 |
+
method = transcoded_request["method"]
|
| 606 |
+
try:
|
| 607 |
+
request_payload = json_format.MessageToJson(request)
|
| 608 |
+
except:
|
| 609 |
+
request_payload = None
|
| 610 |
+
http_request = {
|
| 611 |
+
"payload": request_payload,
|
| 612 |
+
"requestMethod": method,
|
| 613 |
+
"requestUrl": request_url,
|
| 614 |
+
"headers": dict(metadata),
|
| 615 |
+
}
|
| 616 |
+
_LOGGER.debug(
|
| 617 |
+
f"Sending request for google.ai.generativelanguage_v1beta.CacheServiceClient.DeleteCachedContent",
|
| 618 |
+
extra={
|
| 619 |
+
"serviceName": "google.ai.generativelanguage.v1beta.CacheService",
|
| 620 |
+
"rpcName": "DeleteCachedContent",
|
| 621 |
+
"httpRequest": http_request,
|
| 622 |
+
"metadata": http_request["headers"],
|
| 623 |
+
},
|
| 624 |
+
)
|
| 625 |
+
|
| 626 |
+
# Send the request
|
| 627 |
+
response = CacheServiceRestTransport._DeleteCachedContent._get_response(
|
| 628 |
+
self._host,
|
| 629 |
+
metadata,
|
| 630 |
+
query_params,
|
| 631 |
+
self._session,
|
| 632 |
+
timeout,
|
| 633 |
+
transcoded_request,
|
| 634 |
+
)
|
| 635 |
+
|
| 636 |
+
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
|
| 637 |
+
# subclass.
|
| 638 |
+
if response.status_code >= 400:
|
| 639 |
+
raise core_exceptions.from_http_response(response)
|
| 640 |
+
|
| 641 |
+
class _GetCachedContent(
|
| 642 |
+
_BaseCacheServiceRestTransport._BaseGetCachedContent, CacheServiceRestStub
|
| 643 |
+
):
|
| 644 |
+
def __hash__(self):
|
| 645 |
+
return hash("CacheServiceRestTransport.GetCachedContent")
|
| 646 |
+
|
| 647 |
+
@staticmethod
|
| 648 |
+
def _get_response(
|
| 649 |
+
host,
|
| 650 |
+
metadata,
|
| 651 |
+
query_params,
|
| 652 |
+
session,
|
| 653 |
+
timeout,
|
| 654 |
+
transcoded_request,
|
| 655 |
+
body=None,
|
| 656 |
+
):
|
| 657 |
+
uri = transcoded_request["uri"]
|
| 658 |
+
method = transcoded_request["method"]
|
| 659 |
+
headers = dict(metadata)
|
| 660 |
+
headers["Content-Type"] = "application/json"
|
| 661 |
+
response = getattr(session, method)(
|
| 662 |
+
"{host}{uri}".format(host=host, uri=uri),
|
| 663 |
+
timeout=timeout,
|
| 664 |
+
headers=headers,
|
| 665 |
+
params=rest_helpers.flatten_query_params(query_params, strict=True),
|
| 666 |
+
)
|
| 667 |
+
return response
|
| 668 |
+
|
| 669 |
+
def __call__(
|
| 670 |
+
self,
|
| 671 |
+
request: cache_service.GetCachedContentRequest,
|
| 672 |
+
*,
|
| 673 |
+
retry: OptionalRetry = gapic_v1.method.DEFAULT,
|
| 674 |
+
timeout: Optional[float] = None,
|
| 675 |
+
metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
|
| 676 |
+
) -> cached_content.CachedContent:
|
| 677 |
+
r"""Call the get cached content method over HTTP.
|
| 678 |
+
|
| 679 |
+
Args:
|
| 680 |
+
request (~.cache_service.GetCachedContentRequest):
|
| 681 |
+
The request object. Request to read CachedContent.
|
| 682 |
+
retry (google.api_core.retry.Retry): Designation of what errors, if any,
|
| 683 |
+
should be retried.
|
| 684 |
+
timeout (float): The timeout for this request.
|
| 685 |
+
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
|
| 686 |
+
sent along with the request as metadata. Normally, each value must be of type `str`,
|
| 687 |
+
but for metadata keys ending with the suffix `-bin`, the corresponding values must
|
| 688 |
+
be of type `bytes`.
|
| 689 |
+
|
| 690 |
+
Returns:
|
| 691 |
+
~.cached_content.CachedContent:
|
| 692 |
+
Content that has been preprocessed
|
| 693 |
+
and can be used in subsequent request to
|
| 694 |
+
GenerativeService.
|
| 695 |
+
|
| 696 |
+
Cached content can be only used with
|
| 697 |
+
model it was created for.
|
| 698 |
+
|
| 699 |
+
"""
|
| 700 |
+
|
| 701 |
+
http_options = (
|
| 702 |
+
_BaseCacheServiceRestTransport._BaseGetCachedContent._get_http_options()
|
| 703 |
+
)
|
| 704 |
+
|
| 705 |
+
request, metadata = self._interceptor.pre_get_cached_content(
|
| 706 |
+
request, metadata
|
| 707 |
+
)
|
| 708 |
+
transcoded_request = _BaseCacheServiceRestTransport._BaseGetCachedContent._get_transcoded_request(
|
| 709 |
+
http_options, request
|
| 710 |
+
)
|
| 711 |
+
|
| 712 |
+
# Jsonify the query params
|
| 713 |
+
query_params = _BaseCacheServiceRestTransport._BaseGetCachedContent._get_query_params_json(
|
| 714 |
+
transcoded_request
|
| 715 |
+
)
|
| 716 |
+
|
| 717 |
+
if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
|
| 718 |
+
logging.DEBUG
|
| 719 |
+
): # pragma: NO COVER
|
| 720 |
+
request_url = "{host}{uri}".format(
|
| 721 |
+
host=self._host, uri=transcoded_request["uri"]
|
| 722 |
+
)
|
| 723 |
+
method = transcoded_request["method"]
|
| 724 |
+
try:
|
| 725 |
+
request_payload = type(request).to_json(request)
|
| 726 |
+
except:
|
| 727 |
+
request_payload = None
|
| 728 |
+
http_request = {
|
| 729 |
+
"payload": request_payload,
|
| 730 |
+
"requestMethod": method,
|
| 731 |
+
"requestUrl": request_url,
|
| 732 |
+
"headers": dict(metadata),
|
| 733 |
+
}
|
| 734 |
+
_LOGGER.debug(
|
| 735 |
+
f"Sending request for google.ai.generativelanguage_v1beta.CacheServiceClient.GetCachedContent",
|
| 736 |
+
extra={
|
| 737 |
+
"serviceName": "google.ai.generativelanguage.v1beta.CacheService",
|
| 738 |
+
"rpcName": "GetCachedContent",
|
| 739 |
+
"httpRequest": http_request,
|
| 740 |
+
"metadata": http_request["headers"],
|
| 741 |
+
},
|
| 742 |
+
)
|
| 743 |
+
|
| 744 |
+
# Send the request
|
| 745 |
+
response = CacheServiceRestTransport._GetCachedContent._get_response(
|
| 746 |
+
self._host,
|
| 747 |
+
metadata,
|
| 748 |
+
query_params,
|
| 749 |
+
self._session,
|
| 750 |
+
timeout,
|
| 751 |
+
transcoded_request,
|
| 752 |
+
)
|
| 753 |
+
|
| 754 |
+
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
|
| 755 |
+
# subclass.
|
| 756 |
+
if response.status_code >= 400:
|
| 757 |
+
raise core_exceptions.from_http_response(response)
|
| 758 |
+
|
| 759 |
+
# Return the response
|
| 760 |
+
resp = cached_content.CachedContent()
|
| 761 |
+
pb_resp = cached_content.CachedContent.pb(resp)
|
| 762 |
+
|
| 763 |
+
json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
|
| 764 |
+
|
| 765 |
+
resp = self._interceptor.post_get_cached_content(resp)
|
| 766 |
+
if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
|
| 767 |
+
logging.DEBUG
|
| 768 |
+
): # pragma: NO COVER
|
| 769 |
+
try:
|
| 770 |
+
response_payload = cached_content.CachedContent.to_json(response)
|
| 771 |
+
except:
|
| 772 |
+
response_payload = None
|
| 773 |
+
http_response = {
|
| 774 |
+
"payload": response_payload,
|
| 775 |
+
"headers": dict(response.headers),
|
| 776 |
+
"status": response.status_code,
|
| 777 |
+
}
|
| 778 |
+
_LOGGER.debug(
|
| 779 |
+
"Received response for google.ai.generativelanguage_v1beta.CacheServiceClient.get_cached_content",
|
| 780 |
+
extra={
|
| 781 |
+
"serviceName": "google.ai.generativelanguage.v1beta.CacheService",
|
| 782 |
+
"rpcName": "GetCachedContent",
|
| 783 |
+
"metadata": http_response["headers"],
|
| 784 |
+
"httpResponse": http_response,
|
| 785 |
+
},
|
| 786 |
+
)
|
| 787 |
+
return resp
|
| 788 |
+
|
| 789 |
+
class _ListCachedContents(
|
| 790 |
+
_BaseCacheServiceRestTransport._BaseListCachedContents, CacheServiceRestStub
|
| 791 |
+
):
|
| 792 |
+
def __hash__(self):
|
| 793 |
+
return hash("CacheServiceRestTransport.ListCachedContents")
|
| 794 |
+
|
| 795 |
+
@staticmethod
|
| 796 |
+
def _get_response(
|
| 797 |
+
host,
|
| 798 |
+
metadata,
|
| 799 |
+
query_params,
|
| 800 |
+
session,
|
| 801 |
+
timeout,
|
| 802 |
+
transcoded_request,
|
| 803 |
+
body=None,
|
| 804 |
+
):
|
| 805 |
+
uri = transcoded_request["uri"]
|
| 806 |
+
method = transcoded_request["method"]
|
| 807 |
+
headers = dict(metadata)
|
| 808 |
+
headers["Content-Type"] = "application/json"
|
| 809 |
+
response = getattr(session, method)(
|
| 810 |
+
"{host}{uri}".format(host=host, uri=uri),
|
| 811 |
+
timeout=timeout,
|
| 812 |
+
headers=headers,
|
| 813 |
+
params=rest_helpers.flatten_query_params(query_params, strict=True),
|
| 814 |
+
)
|
| 815 |
+
return response
|
| 816 |
+
|
| 817 |
+
def __call__(
|
| 818 |
+
self,
|
| 819 |
+
request: cache_service.ListCachedContentsRequest,
|
| 820 |
+
*,
|
| 821 |
+
retry: OptionalRetry = gapic_v1.method.DEFAULT,
|
| 822 |
+
timeout: Optional[float] = None,
|
| 823 |
+
metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
|
| 824 |
+
) -> cache_service.ListCachedContentsResponse:
|
| 825 |
+
r"""Call the list cached contents method over HTTP.
|
| 826 |
+
|
| 827 |
+
Args:
|
| 828 |
+
request (~.cache_service.ListCachedContentsRequest):
|
| 829 |
+
The request object. Request to list CachedContents.
|
| 830 |
+
retry (google.api_core.retry.Retry): Designation of what errors, if any,
|
| 831 |
+
should be retried.
|
| 832 |
+
timeout (float): The timeout for this request.
|
| 833 |
+
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
|
| 834 |
+
sent along with the request as metadata. Normally, each value must be of type `str`,
|
| 835 |
+
but for metadata keys ending with the suffix `-bin`, the corresponding values must
|
| 836 |
+
be of type `bytes`.
|
| 837 |
+
|
| 838 |
+
Returns:
|
| 839 |
+
~.cache_service.ListCachedContentsResponse:
|
| 840 |
+
Response with CachedContents list.
|
| 841 |
+
"""
|
| 842 |
+
|
| 843 |
+
http_options = (
|
| 844 |
+
_BaseCacheServiceRestTransport._BaseListCachedContents._get_http_options()
|
| 845 |
+
)
|
| 846 |
+
|
| 847 |
+
request, metadata = self._interceptor.pre_list_cached_contents(
|
| 848 |
+
request, metadata
|
| 849 |
+
)
|
| 850 |
+
transcoded_request = _BaseCacheServiceRestTransport._BaseListCachedContents._get_transcoded_request(
|
| 851 |
+
http_options, request
|
| 852 |
+
)
|
| 853 |
+
|
| 854 |
+
# Jsonify the query params
|
| 855 |
+
query_params = _BaseCacheServiceRestTransport._BaseListCachedContents._get_query_params_json(
|
| 856 |
+
transcoded_request
|
| 857 |
+
)
|
| 858 |
+
|
| 859 |
+
if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
|
| 860 |
+
logging.DEBUG
|
| 861 |
+
): # pragma: NO COVER
|
| 862 |
+
request_url = "{host}{uri}".format(
|
| 863 |
+
host=self._host, uri=transcoded_request["uri"]
|
| 864 |
+
)
|
| 865 |
+
method = transcoded_request["method"]
|
| 866 |
+
try:
|
| 867 |
+
request_payload = type(request).to_json(request)
|
| 868 |
+
except:
|
| 869 |
+
request_payload = None
|
| 870 |
+
http_request = {
|
| 871 |
+
"payload": request_payload,
|
| 872 |
+
"requestMethod": method,
|
| 873 |
+
"requestUrl": request_url,
|
| 874 |
+
"headers": dict(metadata),
|
| 875 |
+
}
|
| 876 |
+
_LOGGER.debug(
|
| 877 |
+
f"Sending request for google.ai.generativelanguage_v1beta.CacheServiceClient.ListCachedContents",
|
| 878 |
+
extra={
|
| 879 |
+
"serviceName": "google.ai.generativelanguage.v1beta.CacheService",
|
| 880 |
+
"rpcName": "ListCachedContents",
|
| 881 |
+
"httpRequest": http_request,
|
| 882 |
+
"metadata": http_request["headers"],
|
| 883 |
+
},
|
| 884 |
+
)
|
| 885 |
+
|
| 886 |
+
# Send the request
|
| 887 |
+
response = CacheServiceRestTransport._ListCachedContents._get_response(
|
| 888 |
+
self._host,
|
| 889 |
+
metadata,
|
| 890 |
+
query_params,
|
| 891 |
+
self._session,
|
| 892 |
+
timeout,
|
| 893 |
+
transcoded_request,
|
| 894 |
+
)
|
| 895 |
+
|
| 896 |
+
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
|
| 897 |
+
# subclass.
|
| 898 |
+
if response.status_code >= 400:
|
| 899 |
+
raise core_exceptions.from_http_response(response)
|
| 900 |
+
|
| 901 |
+
# Return the response
|
| 902 |
+
resp = cache_service.ListCachedContentsResponse()
|
| 903 |
+
pb_resp = cache_service.ListCachedContentsResponse.pb(resp)
|
| 904 |
+
|
| 905 |
+
json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
|
| 906 |
+
|
| 907 |
+
resp = self._interceptor.post_list_cached_contents(resp)
|
| 908 |
+
if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
|
| 909 |
+
logging.DEBUG
|
| 910 |
+
): # pragma: NO COVER
|
| 911 |
+
try:
|
| 912 |
+
response_payload = cache_service.ListCachedContentsResponse.to_json(
|
| 913 |
+
response
|
| 914 |
+
)
|
| 915 |
+
except:
|
| 916 |
+
response_payload = None
|
| 917 |
+
http_response = {
|
| 918 |
+
"payload": response_payload,
|
| 919 |
+
"headers": dict(response.headers),
|
| 920 |
+
"status": response.status_code,
|
| 921 |
+
}
|
| 922 |
+
_LOGGER.debug(
|
| 923 |
+
"Received response for google.ai.generativelanguage_v1beta.CacheServiceClient.list_cached_contents",
|
| 924 |
+
extra={
|
| 925 |
+
"serviceName": "google.ai.generativelanguage.v1beta.CacheService",
|
| 926 |
+
"rpcName": "ListCachedContents",
|
| 927 |
+
"metadata": http_response["headers"],
|
| 928 |
+
"httpResponse": http_response,
|
| 929 |
+
},
|
| 930 |
+
)
|
| 931 |
+
return resp
|
| 932 |
+
|
| 933 |
+
class _UpdateCachedContent(
|
| 934 |
+
_BaseCacheServiceRestTransport._BaseUpdateCachedContent, CacheServiceRestStub
|
| 935 |
+
):
|
| 936 |
+
def __hash__(self):
|
| 937 |
+
return hash("CacheServiceRestTransport.UpdateCachedContent")
|
| 938 |
+
|
| 939 |
+
@staticmethod
|
| 940 |
+
def _get_response(
|
| 941 |
+
host,
|
| 942 |
+
metadata,
|
| 943 |
+
query_params,
|
| 944 |
+
session,
|
| 945 |
+
timeout,
|
| 946 |
+
transcoded_request,
|
| 947 |
+
body=None,
|
| 948 |
+
):
|
| 949 |
+
uri = transcoded_request["uri"]
|
| 950 |
+
method = transcoded_request["method"]
|
| 951 |
+
headers = dict(metadata)
|
| 952 |
+
headers["Content-Type"] = "application/json"
|
| 953 |
+
response = getattr(session, method)(
|
| 954 |
+
"{host}{uri}".format(host=host, uri=uri),
|
| 955 |
+
timeout=timeout,
|
| 956 |
+
headers=headers,
|
| 957 |
+
params=rest_helpers.flatten_query_params(query_params, strict=True),
|
| 958 |
+
data=body,
|
| 959 |
+
)
|
| 960 |
+
return response
|
| 961 |
+
|
| 962 |
+
def __call__(
|
| 963 |
+
self,
|
| 964 |
+
request: cache_service.UpdateCachedContentRequest,
|
| 965 |
+
*,
|
| 966 |
+
retry: OptionalRetry = gapic_v1.method.DEFAULT,
|
| 967 |
+
timeout: Optional[float] = None,
|
| 968 |
+
metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
|
| 969 |
+
) -> gag_cached_content.CachedContent:
|
| 970 |
+
r"""Call the update cached content method over HTTP.
|
| 971 |
+
|
| 972 |
+
Args:
|
| 973 |
+
request (~.cache_service.UpdateCachedContentRequest):
|
| 974 |
+
The request object. Request to update CachedContent.
|
| 975 |
+
retry (google.api_core.retry.Retry): Designation of what errors, if any,
|
| 976 |
+
should be retried.
|
| 977 |
+
timeout (float): The timeout for this request.
|
| 978 |
+
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
|
| 979 |
+
sent along with the request as metadata. Normally, each value must be of type `str`,
|
| 980 |
+
but for metadata keys ending with the suffix `-bin`, the corresponding values must
|
| 981 |
+
be of type `bytes`.
|
| 982 |
+
|
| 983 |
+
Returns:
|
| 984 |
+
~.gag_cached_content.CachedContent:
|
| 985 |
+
Content that has been preprocessed
|
| 986 |
+
and can be used in subsequent request to
|
| 987 |
+
GenerativeService.
|
| 988 |
+
|
| 989 |
+
Cached content can be only used with
|
| 990 |
+
model it was created for.
|
| 991 |
+
|
| 992 |
+
"""
|
| 993 |
+
|
| 994 |
+
http_options = (
|
| 995 |
+
_BaseCacheServiceRestTransport._BaseUpdateCachedContent._get_http_options()
|
| 996 |
+
)
|
| 997 |
+
|
| 998 |
+
request, metadata = self._interceptor.pre_update_cached_content(
|
| 999 |
+
request, metadata
|
| 1000 |
+
)
|
| 1001 |
+
transcoded_request = _BaseCacheServiceRestTransport._BaseUpdateCachedContent._get_transcoded_request(
|
| 1002 |
+
http_options, request
|
| 1003 |
+
)
|
| 1004 |
+
|
| 1005 |
+
body = _BaseCacheServiceRestTransport._BaseUpdateCachedContent._get_request_body_json(
|
| 1006 |
+
transcoded_request
|
| 1007 |
+
)
|
| 1008 |
+
|
| 1009 |
+
# Jsonify the query params
|
| 1010 |
+
query_params = _BaseCacheServiceRestTransport._BaseUpdateCachedContent._get_query_params_json(
|
| 1011 |
+
transcoded_request
|
| 1012 |
+
)
|
| 1013 |
+
|
| 1014 |
+
if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
|
| 1015 |
+
logging.DEBUG
|
| 1016 |
+
): # pragma: NO COVER
|
| 1017 |
+
request_url = "{host}{uri}".format(
|
| 1018 |
+
host=self._host, uri=transcoded_request["uri"]
|
| 1019 |
+
)
|
| 1020 |
+
method = transcoded_request["method"]
|
| 1021 |
+
try:
|
| 1022 |
+
request_payload = type(request).to_json(request)
|
| 1023 |
+
except:
|
| 1024 |
+
request_payload = None
|
| 1025 |
+
http_request = {
|
| 1026 |
+
"payload": request_payload,
|
| 1027 |
+
"requestMethod": method,
|
| 1028 |
+
"requestUrl": request_url,
|
| 1029 |
+
"headers": dict(metadata),
|
| 1030 |
+
}
|
| 1031 |
+
_LOGGER.debug(
|
| 1032 |
+
f"Sending request for google.ai.generativelanguage_v1beta.CacheServiceClient.UpdateCachedContent",
|
| 1033 |
+
extra={
|
| 1034 |
+
"serviceName": "google.ai.generativelanguage.v1beta.CacheService",
|
| 1035 |
+
"rpcName": "UpdateCachedContent",
|
| 1036 |
+
"httpRequest": http_request,
|
| 1037 |
+
"metadata": http_request["headers"],
|
| 1038 |
+
},
|
| 1039 |
+
)
|
| 1040 |
+
|
| 1041 |
+
# Send the request
|
| 1042 |
+
response = CacheServiceRestTransport._UpdateCachedContent._get_response(
|
| 1043 |
+
self._host,
|
| 1044 |
+
metadata,
|
| 1045 |
+
query_params,
|
| 1046 |
+
self._session,
|
| 1047 |
+
timeout,
|
| 1048 |
+
transcoded_request,
|
| 1049 |
+
body,
|
| 1050 |
+
)
|
| 1051 |
+
|
| 1052 |
+
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
|
| 1053 |
+
# subclass.
|
| 1054 |
+
if response.status_code >= 400:
|
| 1055 |
+
raise core_exceptions.from_http_response(response)
|
| 1056 |
+
|
| 1057 |
+
# Return the response
|
| 1058 |
+
resp = gag_cached_content.CachedContent()
|
| 1059 |
+
pb_resp = gag_cached_content.CachedContent.pb(resp)
|
| 1060 |
+
|
| 1061 |
+
json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
|
| 1062 |
+
|
| 1063 |
+
resp = self._interceptor.post_update_cached_content(resp)
|
| 1064 |
+
if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
|
| 1065 |
+
logging.DEBUG
|
| 1066 |
+
): # pragma: NO COVER
|
| 1067 |
+
try:
|
| 1068 |
+
response_payload = gag_cached_content.CachedContent.to_json(
|
| 1069 |
+
response
|
| 1070 |
+
)
|
| 1071 |
+
except:
|
| 1072 |
+
response_payload = None
|
| 1073 |
+
http_response = {
|
| 1074 |
+
"payload": response_payload,
|
| 1075 |
+
"headers": dict(response.headers),
|
| 1076 |
+
"status": response.status_code,
|
| 1077 |
+
}
|
| 1078 |
+
_LOGGER.debug(
|
| 1079 |
+
"Received response for google.ai.generativelanguage_v1beta.CacheServiceClient.update_cached_content",
|
| 1080 |
+
extra={
|
| 1081 |
+
"serviceName": "google.ai.generativelanguage.v1beta.CacheService",
|
| 1082 |
+
"rpcName": "UpdateCachedContent",
|
| 1083 |
+
"metadata": http_response["headers"],
|
| 1084 |
+
"httpResponse": http_response,
|
| 1085 |
+
},
|
| 1086 |
+
)
|
| 1087 |
+
return resp
|
| 1088 |
+
|
| 1089 |
+
@property
|
| 1090 |
+
def create_cached_content(
|
| 1091 |
+
self,
|
| 1092 |
+
) -> Callable[
|
| 1093 |
+
[cache_service.CreateCachedContentRequest], gag_cached_content.CachedContent
|
| 1094 |
+
]:
|
| 1095 |
+
# The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
|
| 1096 |
+
# In C++ this would require a dynamic_cast
|
| 1097 |
+
return self._CreateCachedContent(self._session, self._host, self._interceptor) # type: ignore
|
| 1098 |
+
|
| 1099 |
+
@property
|
| 1100 |
+
def delete_cached_content(
|
| 1101 |
+
self,
|
| 1102 |
+
) -> Callable[[cache_service.DeleteCachedContentRequest], empty_pb2.Empty]:
|
| 1103 |
+
# The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
|
| 1104 |
+
# In C++ this would require a dynamic_cast
|
| 1105 |
+
return self._DeleteCachedContent(self._session, self._host, self._interceptor) # type: ignore
|
| 1106 |
+
|
| 1107 |
+
@property
|
| 1108 |
+
def get_cached_content(
|
| 1109 |
+
self,
|
| 1110 |
+
) -> Callable[
|
| 1111 |
+
[cache_service.GetCachedContentRequest], cached_content.CachedContent
|
| 1112 |
+
]:
|
| 1113 |
+
# The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
|
| 1114 |
+
# In C++ this would require a dynamic_cast
|
| 1115 |
+
return self._GetCachedContent(self._session, self._host, self._interceptor) # type: ignore
|
| 1116 |
+
|
| 1117 |
+
@property
|
| 1118 |
+
def list_cached_contents(
|
| 1119 |
+
self,
|
| 1120 |
+
) -> Callable[
|
| 1121 |
+
[cache_service.ListCachedContentsRequest],
|
| 1122 |
+
cache_service.ListCachedContentsResponse,
|
| 1123 |
+
]:
|
| 1124 |
+
# The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
|
| 1125 |
+
# In C++ this would require a dynamic_cast
|
| 1126 |
+
return self._ListCachedContents(self._session, self._host, self._interceptor) # type: ignore
|
| 1127 |
+
|
| 1128 |
+
@property
|
| 1129 |
+
def update_cached_content(
|
| 1130 |
+
self,
|
| 1131 |
+
) -> Callable[
|
| 1132 |
+
[cache_service.UpdateCachedContentRequest], gag_cached_content.CachedContent
|
| 1133 |
+
]:
|
| 1134 |
+
# The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
|
| 1135 |
+
# In C++ this would require a dynamic_cast
|
| 1136 |
+
return self._UpdateCachedContent(self._session, self._host, self._interceptor) # type: ignore
|
| 1137 |
+
|
| 1138 |
+
@property
|
| 1139 |
+
def get_operation(self):
|
| 1140 |
+
return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore
|
| 1141 |
+
|
| 1142 |
+
class _GetOperation(
|
| 1143 |
+
_BaseCacheServiceRestTransport._BaseGetOperation, CacheServiceRestStub
|
| 1144 |
+
):
|
| 1145 |
+
def __hash__(self):
|
| 1146 |
+
return hash("CacheServiceRestTransport.GetOperation")
|
| 1147 |
+
|
| 1148 |
+
@staticmethod
|
| 1149 |
+
def _get_response(
|
| 1150 |
+
host,
|
| 1151 |
+
metadata,
|
| 1152 |
+
query_params,
|
| 1153 |
+
session,
|
| 1154 |
+
timeout,
|
| 1155 |
+
transcoded_request,
|
| 1156 |
+
body=None,
|
| 1157 |
+
):
|
| 1158 |
+
uri = transcoded_request["uri"]
|
| 1159 |
+
method = transcoded_request["method"]
|
| 1160 |
+
headers = dict(metadata)
|
| 1161 |
+
headers["Content-Type"] = "application/json"
|
| 1162 |
+
response = getattr(session, method)(
|
| 1163 |
+
"{host}{uri}".format(host=host, uri=uri),
|
| 1164 |
+
timeout=timeout,
|
| 1165 |
+
headers=headers,
|
| 1166 |
+
params=rest_helpers.flatten_query_params(query_params, strict=True),
|
| 1167 |
+
)
|
| 1168 |
+
return response
|
| 1169 |
+
|
| 1170 |
+
def __call__(
|
| 1171 |
+
self,
|
| 1172 |
+
request: operations_pb2.GetOperationRequest,
|
| 1173 |
+
*,
|
| 1174 |
+
retry: OptionalRetry = gapic_v1.method.DEFAULT,
|
| 1175 |
+
timeout: Optional[float] = None,
|
| 1176 |
+
metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
|
| 1177 |
+
) -> operations_pb2.Operation:
|
| 1178 |
+
r"""Call the get operation method over HTTP.
|
| 1179 |
+
|
| 1180 |
+
Args:
|
| 1181 |
+
request (operations_pb2.GetOperationRequest):
|
| 1182 |
+
The request object for GetOperation method.
|
| 1183 |
+
retry (google.api_core.retry.Retry): Designation of what errors, if any,
|
| 1184 |
+
should be retried.
|
| 1185 |
+
timeout (float): The timeout for this request.
|
| 1186 |
+
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
|
| 1187 |
+
sent along with the request as metadata. Normally, each value must be of type `str`,
|
| 1188 |
+
but for metadata keys ending with the suffix `-bin`, the corresponding values must
|
| 1189 |
+
be of type `bytes`.
|
| 1190 |
+
|
| 1191 |
+
Returns:
|
| 1192 |
+
operations_pb2.Operation: Response from GetOperation method.
|
| 1193 |
+
"""
|
| 1194 |
+
|
| 1195 |
+
http_options = (
|
| 1196 |
+
_BaseCacheServiceRestTransport._BaseGetOperation._get_http_options()
|
| 1197 |
+
)
|
| 1198 |
+
|
| 1199 |
+
request, metadata = self._interceptor.pre_get_operation(request, metadata)
|
| 1200 |
+
transcoded_request = _BaseCacheServiceRestTransport._BaseGetOperation._get_transcoded_request(
|
| 1201 |
+
http_options, request
|
| 1202 |
+
)
|
| 1203 |
+
|
| 1204 |
+
# Jsonify the query params
|
| 1205 |
+
query_params = (
|
| 1206 |
+
_BaseCacheServiceRestTransport._BaseGetOperation._get_query_params_json(
|
| 1207 |
+
transcoded_request
|
| 1208 |
+
)
|
| 1209 |
+
)
|
| 1210 |
+
|
| 1211 |
+
if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
|
| 1212 |
+
logging.DEBUG
|
| 1213 |
+
): # pragma: NO COVER
|
| 1214 |
+
request_url = "{host}{uri}".format(
|
| 1215 |
+
host=self._host, uri=transcoded_request["uri"]
|
| 1216 |
+
)
|
| 1217 |
+
method = transcoded_request["method"]
|
| 1218 |
+
try:
|
| 1219 |
+
request_payload = json_format.MessageToJson(request)
|
| 1220 |
+
except:
|
| 1221 |
+
request_payload = None
|
| 1222 |
+
http_request = {
|
| 1223 |
+
"payload": request_payload,
|
| 1224 |
+
"requestMethod": method,
|
| 1225 |
+
"requestUrl": request_url,
|
| 1226 |
+
"headers": dict(metadata),
|
| 1227 |
+
}
|
| 1228 |
+
_LOGGER.debug(
|
| 1229 |
+
f"Sending request for google.ai.generativelanguage_v1beta.CacheServiceClient.GetOperation",
|
| 1230 |
+
extra={
|
| 1231 |
+
"serviceName": "google.ai.generativelanguage.v1beta.CacheService",
|
| 1232 |
+
"rpcName": "GetOperation",
|
| 1233 |
+
"httpRequest": http_request,
|
| 1234 |
+
"metadata": http_request["headers"],
|
| 1235 |
+
},
|
| 1236 |
+
)
|
| 1237 |
+
|
| 1238 |
+
# Send the request
|
| 1239 |
+
response = CacheServiceRestTransport._GetOperation._get_response(
|
| 1240 |
+
self._host,
|
| 1241 |
+
metadata,
|
| 1242 |
+
query_params,
|
| 1243 |
+
self._session,
|
| 1244 |
+
timeout,
|
| 1245 |
+
transcoded_request,
|
| 1246 |
+
)
|
| 1247 |
+
|
| 1248 |
+
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
|
| 1249 |
+
# subclass.
|
| 1250 |
+
if response.status_code >= 400:
|
| 1251 |
+
raise core_exceptions.from_http_response(response)
|
| 1252 |
+
|
| 1253 |
+
content = response.content.decode("utf-8")
|
| 1254 |
+
resp = operations_pb2.Operation()
|
| 1255 |
+
resp = json_format.Parse(content, resp)
|
| 1256 |
+
resp = self._interceptor.post_get_operation(resp)
|
| 1257 |
+
if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
|
| 1258 |
+
logging.DEBUG
|
| 1259 |
+
): # pragma: NO COVER
|
| 1260 |
+
try:
|
| 1261 |
+
response_payload = json_format.MessageToJson(resp)
|
| 1262 |
+
except:
|
| 1263 |
+
response_payload = None
|
| 1264 |
+
http_response = {
|
| 1265 |
+
"payload": response_payload,
|
| 1266 |
+
"headers": dict(response.headers),
|
| 1267 |
+
"status": response.status_code,
|
| 1268 |
+
}
|
| 1269 |
+
_LOGGER.debug(
|
| 1270 |
+
"Received response for google.ai.generativelanguage_v1beta.CacheServiceAsyncClient.GetOperation",
|
| 1271 |
+
extra={
|
| 1272 |
+
"serviceName": "google.ai.generativelanguage.v1beta.CacheService",
|
| 1273 |
+
"rpcName": "GetOperation",
|
| 1274 |
+
"httpResponse": http_response,
|
| 1275 |
+
"metadata": http_response["headers"],
|
| 1276 |
+
},
|
| 1277 |
+
)
|
| 1278 |
+
return resp
|
| 1279 |
+
|
| 1280 |
+
@property
|
| 1281 |
+
def list_operations(self):
|
| 1282 |
+
return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore
|
| 1283 |
+
|
| 1284 |
+
class _ListOperations(
|
| 1285 |
+
_BaseCacheServiceRestTransport._BaseListOperations, CacheServiceRestStub
|
| 1286 |
+
):
|
| 1287 |
+
def __hash__(self):
|
| 1288 |
+
return hash("CacheServiceRestTransport.ListOperations")
|
| 1289 |
+
|
| 1290 |
+
@staticmethod
|
| 1291 |
+
def _get_response(
|
| 1292 |
+
host,
|
| 1293 |
+
metadata,
|
| 1294 |
+
query_params,
|
| 1295 |
+
session,
|
| 1296 |
+
timeout,
|
| 1297 |
+
transcoded_request,
|
| 1298 |
+
body=None,
|
| 1299 |
+
):
|
| 1300 |
+
uri = transcoded_request["uri"]
|
| 1301 |
+
method = transcoded_request["method"]
|
| 1302 |
+
headers = dict(metadata)
|
| 1303 |
+
headers["Content-Type"] = "application/json"
|
| 1304 |
+
response = getattr(session, method)(
|
| 1305 |
+
"{host}{uri}".format(host=host, uri=uri),
|
| 1306 |
+
timeout=timeout,
|
| 1307 |
+
headers=headers,
|
| 1308 |
+
params=rest_helpers.flatten_query_params(query_params, strict=True),
|
| 1309 |
+
)
|
| 1310 |
+
return response
|
| 1311 |
+
|
| 1312 |
+
def __call__(
|
| 1313 |
+
self,
|
| 1314 |
+
request: operations_pb2.ListOperationsRequest,
|
| 1315 |
+
*,
|
| 1316 |
+
retry: OptionalRetry = gapic_v1.method.DEFAULT,
|
| 1317 |
+
timeout: Optional[float] = None,
|
| 1318 |
+
metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
|
| 1319 |
+
) -> operations_pb2.ListOperationsResponse:
|
| 1320 |
+
r"""Call the list operations method over HTTP.
|
| 1321 |
+
|
| 1322 |
+
Args:
|
| 1323 |
+
request (operations_pb2.ListOperationsRequest):
|
| 1324 |
+
The request object for ListOperations method.
|
| 1325 |
+
retry (google.api_core.retry.Retry): Designation of what errors, if any,
|
| 1326 |
+
should be retried.
|
| 1327 |
+
timeout (float): The timeout for this request.
|
| 1328 |
+
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
|
| 1329 |
+
sent along with the request as metadata. Normally, each value must be of type `str`,
|
| 1330 |
+
but for metadata keys ending with the suffix `-bin`, the corresponding values must
|
| 1331 |
+
be of type `bytes`.
|
| 1332 |
+
|
| 1333 |
+
Returns:
|
| 1334 |
+
operations_pb2.ListOperationsResponse: Response from ListOperations method.
|
| 1335 |
+
"""
|
| 1336 |
+
|
| 1337 |
+
http_options = (
|
| 1338 |
+
_BaseCacheServiceRestTransport._BaseListOperations._get_http_options()
|
| 1339 |
+
)
|
| 1340 |
+
|
| 1341 |
+
request, metadata = self._interceptor.pre_list_operations(request, metadata)
|
| 1342 |
+
transcoded_request = _BaseCacheServiceRestTransport._BaseListOperations._get_transcoded_request(
|
| 1343 |
+
http_options, request
|
| 1344 |
+
)
|
| 1345 |
+
|
| 1346 |
+
# Jsonify the query params
|
| 1347 |
+
query_params = _BaseCacheServiceRestTransport._BaseListOperations._get_query_params_json(
|
| 1348 |
+
transcoded_request
|
| 1349 |
+
)
|
| 1350 |
+
|
| 1351 |
+
if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
|
| 1352 |
+
logging.DEBUG
|
| 1353 |
+
): # pragma: NO COVER
|
| 1354 |
+
request_url = "{host}{uri}".format(
|
| 1355 |
+
host=self._host, uri=transcoded_request["uri"]
|
| 1356 |
+
)
|
| 1357 |
+
method = transcoded_request["method"]
|
| 1358 |
+
try:
|
| 1359 |
+
request_payload = json_format.MessageToJson(request)
|
| 1360 |
+
except:
|
| 1361 |
+
request_payload = None
|
| 1362 |
+
http_request = {
|
| 1363 |
+
"payload": request_payload,
|
| 1364 |
+
"requestMethod": method,
|
| 1365 |
+
"requestUrl": request_url,
|
| 1366 |
+
"headers": dict(metadata),
|
| 1367 |
+
}
|
| 1368 |
+
_LOGGER.debug(
|
| 1369 |
+
f"Sending request for google.ai.generativelanguage_v1beta.CacheServiceClient.ListOperations",
|
| 1370 |
+
extra={
|
| 1371 |
+
"serviceName": "google.ai.generativelanguage.v1beta.CacheService",
|
| 1372 |
+
"rpcName": "ListOperations",
|
| 1373 |
+
"httpRequest": http_request,
|
| 1374 |
+
"metadata": http_request["headers"],
|
| 1375 |
+
},
|
| 1376 |
+
)
|
| 1377 |
+
|
| 1378 |
+
# Send the request
|
| 1379 |
+
response = CacheServiceRestTransport._ListOperations._get_response(
|
| 1380 |
+
self._host,
|
| 1381 |
+
metadata,
|
| 1382 |
+
query_params,
|
| 1383 |
+
self._session,
|
| 1384 |
+
timeout,
|
| 1385 |
+
transcoded_request,
|
| 1386 |
+
)
|
| 1387 |
+
|
| 1388 |
+
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
|
| 1389 |
+
# subclass.
|
| 1390 |
+
if response.status_code >= 400:
|
| 1391 |
+
raise core_exceptions.from_http_response(response)
|
| 1392 |
+
|
| 1393 |
+
content = response.content.decode("utf-8")
|
| 1394 |
+
resp = operations_pb2.ListOperationsResponse()
|
| 1395 |
+
resp = json_format.Parse(content, resp)
|
| 1396 |
+
resp = self._interceptor.post_list_operations(resp)
|
| 1397 |
+
if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
|
| 1398 |
+
logging.DEBUG
|
| 1399 |
+
): # pragma: NO COVER
|
| 1400 |
+
try:
|
| 1401 |
+
response_payload = json_format.MessageToJson(resp)
|
| 1402 |
+
except:
|
| 1403 |
+
response_payload = None
|
| 1404 |
+
http_response = {
|
| 1405 |
+
"payload": response_payload,
|
| 1406 |
+
"headers": dict(response.headers),
|
| 1407 |
+
"status": response.status_code,
|
| 1408 |
+
}
|
| 1409 |
+
_LOGGER.debug(
|
| 1410 |
+
"Received response for google.ai.generativelanguage_v1beta.CacheServiceAsyncClient.ListOperations",
|
| 1411 |
+
extra={
|
| 1412 |
+
"serviceName": "google.ai.generativelanguage.v1beta.CacheService",
|
| 1413 |
+
"rpcName": "ListOperations",
|
| 1414 |
+
"httpResponse": http_response,
|
| 1415 |
+
"metadata": http_response["headers"],
|
| 1416 |
+
},
|
| 1417 |
+
)
|
| 1418 |
+
return resp
|
| 1419 |
+
|
| 1420 |
+
@property
|
| 1421 |
+
def kind(self) -> str:
|
| 1422 |
+
return "rest"
|
| 1423 |
+
|
| 1424 |
+
def close(self):
|
| 1425 |
+
self._session.close()
|
| 1426 |
+
|
| 1427 |
+
|
| 1428 |
+
__all__ = ("CacheServiceRestTransport",)
|
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/cache_service/transports/rest_base.py
ADDED
|
@@ -0,0 +1,399 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Copyright 2024 Google LLC
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
#
|
| 16 |
+
import json # type: ignore
|
| 17 |
+
import re
|
| 18 |
+
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union
|
| 19 |
+
|
| 20 |
+
from google.api_core import gapic_v1, path_template
|
| 21 |
+
from google.longrunning import operations_pb2 # type: ignore
|
| 22 |
+
from google.protobuf import empty_pb2 # type: ignore
|
| 23 |
+
from google.protobuf import json_format
|
| 24 |
+
|
| 25 |
+
from google.ai.generativelanguage_v1beta.types import (
|
| 26 |
+
cached_content as gag_cached_content,
|
| 27 |
+
)
|
| 28 |
+
from google.ai.generativelanguage_v1beta.types import cache_service
|
| 29 |
+
from google.ai.generativelanguage_v1beta.types import cached_content
|
| 30 |
+
|
| 31 |
+
from .base import DEFAULT_CLIENT_INFO, CacheServiceTransport
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class _BaseCacheServiceRestTransport(CacheServiceTransport):
|
| 35 |
+
"""Base REST backend transport for CacheService.
|
| 36 |
+
|
| 37 |
+
Note: This class is not meant to be used directly. Use its sync and
|
| 38 |
+
async sub-classes instead.
|
| 39 |
+
|
| 40 |
+
This class defines the same methods as the primary client, so the
|
| 41 |
+
primary client can load the underlying transport implementation
|
| 42 |
+
and call it.
|
| 43 |
+
|
| 44 |
+
It sends JSON representations of protocol buffers over HTTP/1.1
|
| 45 |
+
"""
|
| 46 |
+
|
| 47 |
+
def __init__(
|
| 48 |
+
self,
|
| 49 |
+
*,
|
| 50 |
+
host: str = "generativelanguage.googleapis.com",
|
| 51 |
+
credentials: Optional[Any] = None,
|
| 52 |
+
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
|
| 53 |
+
always_use_jwt_access: Optional[bool] = False,
|
| 54 |
+
url_scheme: str = "https",
|
| 55 |
+
api_audience: Optional[str] = None,
|
| 56 |
+
) -> None:
|
| 57 |
+
"""Instantiate the transport.
|
| 58 |
+
Args:
|
| 59 |
+
host (Optional[str]):
|
| 60 |
+
The hostname to connect to (default: 'generativelanguage.googleapis.com').
|
| 61 |
+
credentials (Optional[Any]): The
|
| 62 |
+
authorization credentials to attach to requests. These
|
| 63 |
+
credentials identify the application to the service; if none
|
| 64 |
+
are specified, the client will attempt to ascertain the
|
| 65 |
+
credentials from the environment.
|
| 66 |
+
client_info (google.api_core.gapic_v1.client_info.ClientInfo):
|
| 67 |
+
The client info used to send a user-agent string along with
|
| 68 |
+
API requests. If ``None``, then default info will be used.
|
| 69 |
+
Generally, you only need to set this if you are developing
|
| 70 |
+
your own client library.
|
| 71 |
+
always_use_jwt_access (Optional[bool]): Whether self signed JWT should
|
| 72 |
+
be used for service account credentials.
|
| 73 |
+
url_scheme: the protocol scheme for the API endpoint. Normally
|
| 74 |
+
"https", but for testing or local servers,
|
| 75 |
+
"http" can be specified.
|
| 76 |
+
"""
|
| 77 |
+
# Run the base constructor
|
| 78 |
+
maybe_url_match = re.match("^(?P<scheme>http(?:s)?://)?(?P<host>.*)$", host)
|
| 79 |
+
if maybe_url_match is None:
|
| 80 |
+
raise ValueError(
|
| 81 |
+
f"Unexpected hostname structure: {host}"
|
| 82 |
+
) # pragma: NO COVER
|
| 83 |
+
|
| 84 |
+
url_match_items = maybe_url_match.groupdict()
|
| 85 |
+
|
| 86 |
+
host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host
|
| 87 |
+
|
| 88 |
+
super().__init__(
|
| 89 |
+
host=host,
|
| 90 |
+
credentials=credentials,
|
| 91 |
+
client_info=client_info,
|
| 92 |
+
always_use_jwt_access=always_use_jwt_access,
|
| 93 |
+
api_audience=api_audience,
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
class _BaseCreateCachedContent:
|
| 97 |
+
def __hash__(self): # pragma: NO COVER
|
| 98 |
+
return NotImplementedError("__hash__ must be implemented.")
|
| 99 |
+
|
| 100 |
+
__REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
|
| 101 |
+
|
| 102 |
+
@classmethod
|
| 103 |
+
def _get_unset_required_fields(cls, message_dict):
|
| 104 |
+
return {
|
| 105 |
+
k: v
|
| 106 |
+
for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
|
| 107 |
+
if k not in message_dict
|
| 108 |
+
}
|
| 109 |
+
|
| 110 |
+
@staticmethod
|
| 111 |
+
def _get_http_options():
|
| 112 |
+
http_options: List[Dict[str, str]] = [
|
| 113 |
+
{
|
| 114 |
+
"method": "post",
|
| 115 |
+
"uri": "/v1beta/cachedContents",
|
| 116 |
+
"body": "cached_content",
|
| 117 |
+
},
|
| 118 |
+
]
|
| 119 |
+
return http_options
|
| 120 |
+
|
| 121 |
+
@staticmethod
|
| 122 |
+
def _get_transcoded_request(http_options, request):
|
| 123 |
+
pb_request = cache_service.CreateCachedContentRequest.pb(request)
|
| 124 |
+
transcoded_request = path_template.transcode(http_options, pb_request)
|
| 125 |
+
return transcoded_request
|
| 126 |
+
|
| 127 |
+
@staticmethod
|
| 128 |
+
def _get_request_body_json(transcoded_request):
|
| 129 |
+
# Jsonify the request body
|
| 130 |
+
|
| 131 |
+
body = json_format.MessageToJson(
|
| 132 |
+
transcoded_request["body"], use_integers_for_enums=True
|
| 133 |
+
)
|
| 134 |
+
return body
|
| 135 |
+
|
| 136 |
+
@staticmethod
|
| 137 |
+
def _get_query_params_json(transcoded_request):
|
| 138 |
+
query_params = json.loads(
|
| 139 |
+
json_format.MessageToJson(
|
| 140 |
+
transcoded_request["query_params"],
|
| 141 |
+
use_integers_for_enums=True,
|
| 142 |
+
)
|
| 143 |
+
)
|
| 144 |
+
query_params.update(
|
| 145 |
+
_BaseCacheServiceRestTransport._BaseCreateCachedContent._get_unset_required_fields(
|
| 146 |
+
query_params
|
| 147 |
+
)
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
query_params["$alt"] = "json;enum-encoding=int"
|
| 151 |
+
return query_params
|
| 152 |
+
|
| 153 |
+
class _BaseDeleteCachedContent:
|
| 154 |
+
def __hash__(self): # pragma: NO COVER
|
| 155 |
+
return NotImplementedError("__hash__ must be implemented.")
|
| 156 |
+
|
| 157 |
+
__REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
|
| 158 |
+
|
| 159 |
+
@classmethod
|
| 160 |
+
def _get_unset_required_fields(cls, message_dict):
|
| 161 |
+
return {
|
| 162 |
+
k: v
|
| 163 |
+
for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
|
| 164 |
+
if k not in message_dict
|
| 165 |
+
}
|
| 166 |
+
|
| 167 |
+
@staticmethod
|
| 168 |
+
def _get_http_options():
|
| 169 |
+
http_options: List[Dict[str, str]] = [
|
| 170 |
+
{
|
| 171 |
+
"method": "delete",
|
| 172 |
+
"uri": "/v1beta/{name=cachedContents/*}",
|
| 173 |
+
},
|
| 174 |
+
]
|
| 175 |
+
return http_options
|
| 176 |
+
|
| 177 |
+
@staticmethod
|
| 178 |
+
def _get_transcoded_request(http_options, request):
|
| 179 |
+
pb_request = cache_service.DeleteCachedContentRequest.pb(request)
|
| 180 |
+
transcoded_request = path_template.transcode(http_options, pb_request)
|
| 181 |
+
return transcoded_request
|
| 182 |
+
|
| 183 |
+
@staticmethod
|
| 184 |
+
def _get_query_params_json(transcoded_request):
|
| 185 |
+
query_params = json.loads(
|
| 186 |
+
json_format.MessageToJson(
|
| 187 |
+
transcoded_request["query_params"],
|
| 188 |
+
use_integers_for_enums=True,
|
| 189 |
+
)
|
| 190 |
+
)
|
| 191 |
+
query_params.update(
|
| 192 |
+
_BaseCacheServiceRestTransport._BaseDeleteCachedContent._get_unset_required_fields(
|
| 193 |
+
query_params
|
| 194 |
+
)
|
| 195 |
+
)
|
| 196 |
+
|
| 197 |
+
query_params["$alt"] = "json;enum-encoding=int"
|
| 198 |
+
return query_params
|
| 199 |
+
|
| 200 |
+
class _BaseGetCachedContent:
|
| 201 |
+
def __hash__(self): # pragma: NO COVER
|
| 202 |
+
return NotImplementedError("__hash__ must be implemented.")
|
| 203 |
+
|
| 204 |
+
__REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
|
| 205 |
+
|
| 206 |
+
@classmethod
|
| 207 |
+
def _get_unset_required_fields(cls, message_dict):
|
| 208 |
+
return {
|
| 209 |
+
k: v
|
| 210 |
+
for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
|
| 211 |
+
if k not in message_dict
|
| 212 |
+
}
|
| 213 |
+
|
| 214 |
+
@staticmethod
|
| 215 |
+
def _get_http_options():
|
| 216 |
+
http_options: List[Dict[str, str]] = [
|
| 217 |
+
{
|
| 218 |
+
"method": "get",
|
| 219 |
+
"uri": "/v1beta/{name=cachedContents/*}",
|
| 220 |
+
},
|
| 221 |
+
]
|
| 222 |
+
return http_options
|
| 223 |
+
|
| 224 |
+
@staticmethod
|
| 225 |
+
def _get_transcoded_request(http_options, request):
|
| 226 |
+
pb_request = cache_service.GetCachedContentRequest.pb(request)
|
| 227 |
+
transcoded_request = path_template.transcode(http_options, pb_request)
|
| 228 |
+
return transcoded_request
|
| 229 |
+
|
| 230 |
+
@staticmethod
|
| 231 |
+
def _get_query_params_json(transcoded_request):
|
| 232 |
+
query_params = json.loads(
|
| 233 |
+
json_format.MessageToJson(
|
| 234 |
+
transcoded_request["query_params"],
|
| 235 |
+
use_integers_for_enums=True,
|
| 236 |
+
)
|
| 237 |
+
)
|
| 238 |
+
query_params.update(
|
| 239 |
+
_BaseCacheServiceRestTransport._BaseGetCachedContent._get_unset_required_fields(
|
| 240 |
+
query_params
|
| 241 |
+
)
|
| 242 |
+
)
|
| 243 |
+
|
| 244 |
+
query_params["$alt"] = "json;enum-encoding=int"
|
| 245 |
+
return query_params
|
| 246 |
+
|
| 247 |
+
class _BaseListCachedContents:
|
| 248 |
+
def __hash__(self): # pragma: NO COVER
|
| 249 |
+
return NotImplementedError("__hash__ must be implemented.")
|
| 250 |
+
|
| 251 |
+
@staticmethod
|
| 252 |
+
def _get_http_options():
|
| 253 |
+
http_options: List[Dict[str, str]] = [
|
| 254 |
+
{
|
| 255 |
+
"method": "get",
|
| 256 |
+
"uri": "/v1beta/cachedContents",
|
| 257 |
+
},
|
| 258 |
+
]
|
| 259 |
+
return http_options
|
| 260 |
+
|
| 261 |
+
@staticmethod
|
| 262 |
+
def _get_transcoded_request(http_options, request):
|
| 263 |
+
pb_request = cache_service.ListCachedContentsRequest.pb(request)
|
| 264 |
+
transcoded_request = path_template.transcode(http_options, pb_request)
|
| 265 |
+
return transcoded_request
|
| 266 |
+
|
| 267 |
+
@staticmethod
|
| 268 |
+
def _get_query_params_json(transcoded_request):
|
| 269 |
+
query_params = json.loads(
|
| 270 |
+
json_format.MessageToJson(
|
| 271 |
+
transcoded_request["query_params"],
|
| 272 |
+
use_integers_for_enums=True,
|
| 273 |
+
)
|
| 274 |
+
)
|
| 275 |
+
|
| 276 |
+
query_params["$alt"] = "json;enum-encoding=int"
|
| 277 |
+
return query_params
|
| 278 |
+
|
| 279 |
+
class _BaseUpdateCachedContent:
|
| 280 |
+
def __hash__(self): # pragma: NO COVER
|
| 281 |
+
return NotImplementedError("__hash__ must be implemented.")
|
| 282 |
+
|
| 283 |
+
__REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
|
| 284 |
+
|
| 285 |
+
@classmethod
|
| 286 |
+
def _get_unset_required_fields(cls, message_dict):
|
| 287 |
+
return {
|
| 288 |
+
k: v
|
| 289 |
+
for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
|
| 290 |
+
if k not in message_dict
|
| 291 |
+
}
|
| 292 |
+
|
| 293 |
+
@staticmethod
|
| 294 |
+
def _get_http_options():
|
| 295 |
+
http_options: List[Dict[str, str]] = [
|
| 296 |
+
{
|
| 297 |
+
"method": "patch",
|
| 298 |
+
"uri": "/v1beta/{cached_content.name=cachedContents/*}",
|
| 299 |
+
"body": "cached_content",
|
| 300 |
+
},
|
| 301 |
+
]
|
| 302 |
+
return http_options
|
| 303 |
+
|
| 304 |
+
@staticmethod
|
| 305 |
+
def _get_transcoded_request(http_options, request):
|
| 306 |
+
pb_request = cache_service.UpdateCachedContentRequest.pb(request)
|
| 307 |
+
transcoded_request = path_template.transcode(http_options, pb_request)
|
| 308 |
+
return transcoded_request
|
| 309 |
+
|
| 310 |
+
@staticmethod
|
| 311 |
+
def _get_request_body_json(transcoded_request):
|
| 312 |
+
# Jsonify the request body
|
| 313 |
+
|
| 314 |
+
body = json_format.MessageToJson(
|
| 315 |
+
transcoded_request["body"], use_integers_for_enums=True
|
| 316 |
+
)
|
| 317 |
+
return body
|
| 318 |
+
|
| 319 |
+
@staticmethod
|
| 320 |
+
def _get_query_params_json(transcoded_request):
|
| 321 |
+
query_params = json.loads(
|
| 322 |
+
json_format.MessageToJson(
|
| 323 |
+
transcoded_request["query_params"],
|
| 324 |
+
use_integers_for_enums=True,
|
| 325 |
+
)
|
| 326 |
+
)
|
| 327 |
+
query_params.update(
|
| 328 |
+
_BaseCacheServiceRestTransport._BaseUpdateCachedContent._get_unset_required_fields(
|
| 329 |
+
query_params
|
| 330 |
+
)
|
| 331 |
+
)
|
| 332 |
+
|
| 333 |
+
query_params["$alt"] = "json;enum-encoding=int"
|
| 334 |
+
return query_params
|
| 335 |
+
|
| 336 |
+
class _BaseGetOperation:
|
| 337 |
+
def __hash__(self): # pragma: NO COVER
|
| 338 |
+
return NotImplementedError("__hash__ must be implemented.")
|
| 339 |
+
|
| 340 |
+
@staticmethod
|
| 341 |
+
def _get_http_options():
|
| 342 |
+
http_options: List[Dict[str, str]] = [
|
| 343 |
+
{
|
| 344 |
+
"method": "get",
|
| 345 |
+
"uri": "/v1beta/{name=tunedModels/*/operations/*}",
|
| 346 |
+
},
|
| 347 |
+
{
|
| 348 |
+
"method": "get",
|
| 349 |
+
"uri": "/v1beta/{name=generatedFiles/*/operations/*}",
|
| 350 |
+
},
|
| 351 |
+
{
|
| 352 |
+
"method": "get",
|
| 353 |
+
"uri": "/v1beta/{name=models/*/operations/*}",
|
| 354 |
+
},
|
| 355 |
+
]
|
| 356 |
+
return http_options
|
| 357 |
+
|
| 358 |
+
@staticmethod
|
| 359 |
+
def _get_transcoded_request(http_options, request):
|
| 360 |
+
request_kwargs = json_format.MessageToDict(request)
|
| 361 |
+
transcoded_request = path_template.transcode(http_options, **request_kwargs)
|
| 362 |
+
return transcoded_request
|
| 363 |
+
|
| 364 |
+
@staticmethod
|
| 365 |
+
def _get_query_params_json(transcoded_request):
|
| 366 |
+
query_params = json.loads(json.dumps(transcoded_request["query_params"]))
|
| 367 |
+
return query_params
|
| 368 |
+
|
| 369 |
+
class _BaseListOperations:
|
| 370 |
+
def __hash__(self): # pragma: NO COVER
|
| 371 |
+
return NotImplementedError("__hash__ must be implemented.")
|
| 372 |
+
|
| 373 |
+
@staticmethod
|
| 374 |
+
def _get_http_options():
|
| 375 |
+
http_options: List[Dict[str, str]] = [
|
| 376 |
+
{
|
| 377 |
+
"method": "get",
|
| 378 |
+
"uri": "/v1beta/{name=tunedModels/*}/operations",
|
| 379 |
+
},
|
| 380 |
+
{
|
| 381 |
+
"method": "get",
|
| 382 |
+
"uri": "/v1beta/{name=models/*}/operations",
|
| 383 |
+
},
|
| 384 |
+
]
|
| 385 |
+
return http_options
|
| 386 |
+
|
| 387 |
+
@staticmethod
|
| 388 |
+
def _get_transcoded_request(http_options, request):
|
| 389 |
+
request_kwargs = json_format.MessageToDict(request)
|
| 390 |
+
transcoded_request = path_template.transcode(http_options, **request_kwargs)
|
| 391 |
+
return transcoded_request
|
| 392 |
+
|
| 393 |
+
@staticmethod
|
| 394 |
+
def _get_query_params_json(transcoded_request):
|
| 395 |
+
query_params = json.loads(json.dumps(transcoded_request["query_params"]))
|
| 396 |
+
return query_params
|
| 397 |
+
|
| 398 |
+
|
| 399 |
+
__all__ = ("_BaseCacheServiceRestTransport",)
|
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/generative_service/__init__.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Copyright 2024 Google LLC
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
#
|
| 16 |
+
from .async_client import GenerativeServiceAsyncClient
|
| 17 |
+
from .client import GenerativeServiceClient
|
| 18 |
+
|
| 19 |
+
__all__ = (
|
| 20 |
+
"GenerativeServiceClient",
|
| 21 |
+
"GenerativeServiceAsyncClient",
|
| 22 |
+
)
|
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/generative_service/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (417 Bytes). View file
|
|
|
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/generative_service/__pycache__/async_client.cpython-311.pyc
ADDED
|
Binary file (52.6 kB). View file
|
|
|
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/generative_service/__pycache__/client.cpython-311.pyc
ADDED
|
Binary file (68.7 kB). View file
|
|
|
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/generative_service/async_client.py
ADDED
|
@@ -0,0 +1,1272 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Copyright 2024 Google LLC
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
#
|
| 16 |
+
from collections import OrderedDict
|
| 17 |
+
import logging as std_logging
|
| 18 |
+
import re
|
| 19 |
+
from typing import (
|
| 20 |
+
AsyncIterable,
|
| 21 |
+
Awaitable,
|
| 22 |
+
Callable,
|
| 23 |
+
Dict,
|
| 24 |
+
Mapping,
|
| 25 |
+
MutableMapping,
|
| 26 |
+
MutableSequence,
|
| 27 |
+
Optional,
|
| 28 |
+
Sequence,
|
| 29 |
+
Tuple,
|
| 30 |
+
Type,
|
| 31 |
+
Union,
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
from google.api_core import exceptions as core_exceptions
|
| 35 |
+
from google.api_core import gapic_v1
|
| 36 |
+
from google.api_core import retry_async as retries
|
| 37 |
+
from google.api_core.client_options import ClientOptions
|
| 38 |
+
from google.auth import credentials as ga_credentials # type: ignore
|
| 39 |
+
from google.oauth2 import service_account # type: ignore
|
| 40 |
+
|
| 41 |
+
from google.ai.generativelanguage_v1beta import gapic_version as package_version
|
| 42 |
+
|
| 43 |
+
try:
|
| 44 |
+
OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None]
|
| 45 |
+
except AttributeError: # pragma: NO COVER
|
| 46 |
+
OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore
|
| 47 |
+
|
| 48 |
+
from google.longrunning import operations_pb2 # type: ignore
|
| 49 |
+
|
| 50 |
+
from google.ai.generativelanguage_v1beta.types import generative_service, safety
|
| 51 |
+
from google.ai.generativelanguage_v1beta.types import content
|
| 52 |
+
from google.ai.generativelanguage_v1beta.types import content as gag_content
|
| 53 |
+
|
| 54 |
+
from .client import GenerativeServiceClient
|
| 55 |
+
from .transports.base import DEFAULT_CLIENT_INFO, GenerativeServiceTransport
|
| 56 |
+
from .transports.grpc_asyncio import GenerativeServiceGrpcAsyncIOTransport
|
| 57 |
+
|
| 58 |
+
try:
|
| 59 |
+
from google.api_core import client_logging # type: ignore
|
| 60 |
+
|
| 61 |
+
CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER
|
| 62 |
+
except ImportError: # pragma: NO COVER
|
| 63 |
+
CLIENT_LOGGING_SUPPORTED = False
|
| 64 |
+
|
| 65 |
+
_LOGGER = std_logging.getLogger(__name__)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
class GenerativeServiceAsyncClient:
|
| 69 |
+
"""API for using Large Models that generate multimodal content
|
| 70 |
+
and have additional capabilities beyond text generation.
|
| 71 |
+
"""
|
| 72 |
+
|
| 73 |
+
_client: GenerativeServiceClient
|
| 74 |
+
|
| 75 |
+
# Copy defaults from the synchronous client for use here.
|
| 76 |
+
# Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead.
|
| 77 |
+
DEFAULT_ENDPOINT = GenerativeServiceClient.DEFAULT_ENDPOINT
|
| 78 |
+
DEFAULT_MTLS_ENDPOINT = GenerativeServiceClient.DEFAULT_MTLS_ENDPOINT
|
| 79 |
+
_DEFAULT_ENDPOINT_TEMPLATE = GenerativeServiceClient._DEFAULT_ENDPOINT_TEMPLATE
|
| 80 |
+
_DEFAULT_UNIVERSE = GenerativeServiceClient._DEFAULT_UNIVERSE
|
| 81 |
+
|
| 82 |
+
cached_content_path = staticmethod(GenerativeServiceClient.cached_content_path)
|
| 83 |
+
parse_cached_content_path = staticmethod(
|
| 84 |
+
GenerativeServiceClient.parse_cached_content_path
|
| 85 |
+
)
|
| 86 |
+
model_path = staticmethod(GenerativeServiceClient.model_path)
|
| 87 |
+
parse_model_path = staticmethod(GenerativeServiceClient.parse_model_path)
|
| 88 |
+
common_billing_account_path = staticmethod(
|
| 89 |
+
GenerativeServiceClient.common_billing_account_path
|
| 90 |
+
)
|
| 91 |
+
parse_common_billing_account_path = staticmethod(
|
| 92 |
+
GenerativeServiceClient.parse_common_billing_account_path
|
| 93 |
+
)
|
| 94 |
+
common_folder_path = staticmethod(GenerativeServiceClient.common_folder_path)
|
| 95 |
+
parse_common_folder_path = staticmethod(
|
| 96 |
+
GenerativeServiceClient.parse_common_folder_path
|
| 97 |
+
)
|
| 98 |
+
common_organization_path = staticmethod(
|
| 99 |
+
GenerativeServiceClient.common_organization_path
|
| 100 |
+
)
|
| 101 |
+
parse_common_organization_path = staticmethod(
|
| 102 |
+
GenerativeServiceClient.parse_common_organization_path
|
| 103 |
+
)
|
| 104 |
+
common_project_path = staticmethod(GenerativeServiceClient.common_project_path)
|
| 105 |
+
parse_common_project_path = staticmethod(
|
| 106 |
+
GenerativeServiceClient.parse_common_project_path
|
| 107 |
+
)
|
| 108 |
+
common_location_path = staticmethod(GenerativeServiceClient.common_location_path)
|
| 109 |
+
parse_common_location_path = staticmethod(
|
| 110 |
+
GenerativeServiceClient.parse_common_location_path
|
| 111 |
+
)
|
| 112 |
+
|
| 113 |
+
@classmethod
|
| 114 |
+
def from_service_account_info(cls, info: dict, *args, **kwargs):
|
| 115 |
+
"""Creates an instance of this client using the provided credentials
|
| 116 |
+
info.
|
| 117 |
+
|
| 118 |
+
Args:
|
| 119 |
+
info (dict): The service account private key info.
|
| 120 |
+
args: Additional arguments to pass to the constructor.
|
| 121 |
+
kwargs: Additional arguments to pass to the constructor.
|
| 122 |
+
|
| 123 |
+
Returns:
|
| 124 |
+
GenerativeServiceAsyncClient: The constructed client.
|
| 125 |
+
"""
|
| 126 |
+
return GenerativeServiceClient.from_service_account_info.__func__(GenerativeServiceAsyncClient, info, *args, **kwargs) # type: ignore
|
| 127 |
+
|
| 128 |
+
@classmethod
|
| 129 |
+
def from_service_account_file(cls, filename: str, *args, **kwargs):
|
| 130 |
+
"""Creates an instance of this client using the provided credentials
|
| 131 |
+
file.
|
| 132 |
+
|
| 133 |
+
Args:
|
| 134 |
+
filename (str): The path to the service account private key json
|
| 135 |
+
file.
|
| 136 |
+
args: Additional arguments to pass to the constructor.
|
| 137 |
+
kwargs: Additional arguments to pass to the constructor.
|
| 138 |
+
|
| 139 |
+
Returns:
|
| 140 |
+
GenerativeServiceAsyncClient: The constructed client.
|
| 141 |
+
"""
|
| 142 |
+
return GenerativeServiceClient.from_service_account_file.__func__(GenerativeServiceAsyncClient, filename, *args, **kwargs) # type: ignore
|
| 143 |
+
|
| 144 |
+
from_service_account_json = from_service_account_file
|
| 145 |
+
|
| 146 |
+
@classmethod
|
| 147 |
+
def get_mtls_endpoint_and_cert_source(
|
| 148 |
+
cls, client_options: Optional[ClientOptions] = None
|
| 149 |
+
):
|
| 150 |
+
"""Return the API endpoint and client cert source for mutual TLS.
|
| 151 |
+
|
| 152 |
+
The client cert source is determined in the following order:
|
| 153 |
+
(1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the
|
| 154 |
+
client cert source is None.
|
| 155 |
+
(2) if `client_options.client_cert_source` is provided, use the provided one; if the
|
| 156 |
+
default client cert source exists, use the default one; otherwise the client cert
|
| 157 |
+
source is None.
|
| 158 |
+
|
| 159 |
+
The API endpoint is determined in the following order:
|
| 160 |
+
(1) if `client_options.api_endpoint` if provided, use the provided one.
|
| 161 |
+
(2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the
|
| 162 |
+
default mTLS endpoint; if the environment variable is "never", use the default API
|
| 163 |
+
endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise
|
| 164 |
+
use the default API endpoint.
|
| 165 |
+
|
| 166 |
+
More details can be found at https://google.aip.dev/auth/4114.
|
| 167 |
+
|
| 168 |
+
Args:
|
| 169 |
+
client_options (google.api_core.client_options.ClientOptions): Custom options for the
|
| 170 |
+
client. Only the `api_endpoint` and `client_cert_source` properties may be used
|
| 171 |
+
in this method.
|
| 172 |
+
|
| 173 |
+
Returns:
|
| 174 |
+
Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the
|
| 175 |
+
client cert source to use.
|
| 176 |
+
|
| 177 |
+
Raises:
|
| 178 |
+
google.auth.exceptions.MutualTLSChannelError: If any errors happen.
|
| 179 |
+
"""
|
| 180 |
+
return GenerativeServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore
|
| 181 |
+
|
| 182 |
+
@property
|
| 183 |
+
def transport(self) -> GenerativeServiceTransport:
|
| 184 |
+
"""Returns the transport used by the client instance.
|
| 185 |
+
|
| 186 |
+
Returns:
|
| 187 |
+
GenerativeServiceTransport: The transport used by the client instance.
|
| 188 |
+
"""
|
| 189 |
+
return self._client.transport
|
| 190 |
+
|
| 191 |
+
@property
|
| 192 |
+
def api_endpoint(self):
|
| 193 |
+
"""Return the API endpoint used by the client instance.
|
| 194 |
+
|
| 195 |
+
Returns:
|
| 196 |
+
str: The API endpoint used by the client instance.
|
| 197 |
+
"""
|
| 198 |
+
return self._client._api_endpoint
|
| 199 |
+
|
| 200 |
+
@property
|
| 201 |
+
def universe_domain(self) -> str:
|
| 202 |
+
"""Return the universe domain used by the client instance.
|
| 203 |
+
|
| 204 |
+
Returns:
|
| 205 |
+
str: The universe domain used
|
| 206 |
+
by the client instance.
|
| 207 |
+
"""
|
| 208 |
+
return self._client._universe_domain
|
| 209 |
+
|
| 210 |
+
get_transport_class = GenerativeServiceClient.get_transport_class
|
| 211 |
+
|
| 212 |
+
def __init__(
|
| 213 |
+
self,
|
| 214 |
+
*,
|
| 215 |
+
credentials: Optional[ga_credentials.Credentials] = None,
|
| 216 |
+
transport: Optional[
|
| 217 |
+
Union[
|
| 218 |
+
str,
|
| 219 |
+
GenerativeServiceTransport,
|
| 220 |
+
Callable[..., GenerativeServiceTransport],
|
| 221 |
+
]
|
| 222 |
+
] = "grpc_asyncio",
|
| 223 |
+
client_options: Optional[ClientOptions] = None,
|
| 224 |
+
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
|
| 225 |
+
) -> None:
|
| 226 |
+
"""Instantiates the generative service async client.
|
| 227 |
+
|
| 228 |
+
Args:
|
| 229 |
+
credentials (Optional[google.auth.credentials.Credentials]): The
|
| 230 |
+
authorization credentials to attach to requests. These
|
| 231 |
+
credentials identify the application to the service; if none
|
| 232 |
+
are specified, the client will attempt to ascertain the
|
| 233 |
+
credentials from the environment.
|
| 234 |
+
transport (Optional[Union[str,GenerativeServiceTransport,Callable[..., GenerativeServiceTransport]]]):
|
| 235 |
+
The transport to use, or a Callable that constructs and returns a new transport to use.
|
| 236 |
+
If a Callable is given, it will be called with the same set of initialization
|
| 237 |
+
arguments as used in the GenerativeServiceTransport constructor.
|
| 238 |
+
If set to None, a transport is chosen automatically.
|
| 239 |
+
client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]):
|
| 240 |
+
Custom options for the client.
|
| 241 |
+
|
| 242 |
+
1. The ``api_endpoint`` property can be used to override the
|
| 243 |
+
default endpoint provided by the client when ``transport`` is
|
| 244 |
+
not explicitly provided. Only if this property is not set and
|
| 245 |
+
``transport`` was not explicitly provided, the endpoint is
|
| 246 |
+
determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment
|
| 247 |
+
variable, which have one of the following values:
|
| 248 |
+
"always" (always use the default mTLS endpoint), "never" (always
|
| 249 |
+
use the default regular endpoint) and "auto" (auto-switch to the
|
| 250 |
+
default mTLS endpoint if client certificate is present; this is
|
| 251 |
+
the default value).
|
| 252 |
+
|
| 253 |
+
2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable
|
| 254 |
+
is "true", then the ``client_cert_source`` property can be used
|
| 255 |
+
to provide a client certificate for mTLS transport. If
|
| 256 |
+
not provided, the default SSL client certificate will be used if
|
| 257 |
+
present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not
|
| 258 |
+
set, no client certificate will be used.
|
| 259 |
+
|
| 260 |
+
3. The ``universe_domain`` property can be used to override the
|
| 261 |
+
default "googleapis.com" universe. Note that ``api_endpoint``
|
| 262 |
+
property still takes precedence; and ``universe_domain`` is
|
| 263 |
+
currently not supported for mTLS.
|
| 264 |
+
|
| 265 |
+
client_info (google.api_core.gapic_v1.client_info.ClientInfo):
|
| 266 |
+
The client info used to send a user-agent string along with
|
| 267 |
+
API requests. If ``None``, then default info will be used.
|
| 268 |
+
Generally, you only need to set this if you're developing
|
| 269 |
+
your own client library.
|
| 270 |
+
|
| 271 |
+
Raises:
|
| 272 |
+
google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
|
| 273 |
+
creation failed for any reason.
|
| 274 |
+
"""
|
| 275 |
+
self._client = GenerativeServiceClient(
|
| 276 |
+
credentials=credentials,
|
| 277 |
+
transport=transport,
|
| 278 |
+
client_options=client_options,
|
| 279 |
+
client_info=client_info,
|
| 280 |
+
)
|
| 281 |
+
|
| 282 |
+
if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
|
| 283 |
+
std_logging.DEBUG
|
| 284 |
+
): # pragma: NO COVER
|
| 285 |
+
_LOGGER.debug(
|
| 286 |
+
"Created client `google.ai.generativelanguage_v1beta.GenerativeServiceAsyncClient`.",
|
| 287 |
+
extra={
|
| 288 |
+
"serviceName": "google.ai.generativelanguage.v1beta.GenerativeService",
|
| 289 |
+
"universeDomain": getattr(
|
| 290 |
+
self._client._transport._credentials, "universe_domain", ""
|
| 291 |
+
),
|
| 292 |
+
"credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}",
|
| 293 |
+
"credentialsInfo": getattr(
|
| 294 |
+
self.transport._credentials, "get_cred_info", lambda: None
|
| 295 |
+
)(),
|
| 296 |
+
}
|
| 297 |
+
if hasattr(self._client._transport, "_credentials")
|
| 298 |
+
else {
|
| 299 |
+
"serviceName": "google.ai.generativelanguage.v1beta.GenerativeService",
|
| 300 |
+
"credentialsType": None,
|
| 301 |
+
},
|
| 302 |
+
)
|
| 303 |
+
|
| 304 |
+
async def generate_content(
|
| 305 |
+
self,
|
| 306 |
+
request: Optional[
|
| 307 |
+
Union[generative_service.GenerateContentRequest, dict]
|
| 308 |
+
] = None,
|
| 309 |
+
*,
|
| 310 |
+
model: Optional[str] = None,
|
| 311 |
+
contents: Optional[MutableSequence[content.Content]] = None,
|
| 312 |
+
retry: OptionalRetry = gapic_v1.method.DEFAULT,
|
| 313 |
+
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
|
| 314 |
+
metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
|
| 315 |
+
) -> generative_service.GenerateContentResponse:
|
| 316 |
+
r"""Generates a model response given an input
|
| 317 |
+
``GenerateContentRequest``. Refer to the `text generation
|
| 318 |
+
guide <https://ai.google.dev/gemini-api/docs/text-generation>`__
|
| 319 |
+
for detailed usage information. Input capabilities differ
|
| 320 |
+
between models, including tuned models. Refer to the `model
|
| 321 |
+
guide <https://ai.google.dev/gemini-api/docs/models/gemini>`__
|
| 322 |
+
and `tuning
|
| 323 |
+
guide <https://ai.google.dev/gemini-api/docs/model-tuning>`__
|
| 324 |
+
for details.
|
| 325 |
+
|
| 326 |
+
.. code-block:: python
|
| 327 |
+
|
| 328 |
+
# This snippet has been automatically generated and should be regarded as a
|
| 329 |
+
# code template only.
|
| 330 |
+
# It will require modifications to work:
|
| 331 |
+
# - It may require correct/in-range values for request initialization.
|
| 332 |
+
# - It may require specifying regional endpoints when creating the service
|
| 333 |
+
# client as shown in:
|
| 334 |
+
# https://googleapis.dev/python/google-api-core/latest/client_options.html
|
| 335 |
+
from google.ai import generativelanguage_v1beta
|
| 336 |
+
|
| 337 |
+
async def sample_generate_content():
|
| 338 |
+
# Create a client
|
| 339 |
+
client = generativelanguage_v1beta.GenerativeServiceAsyncClient()
|
| 340 |
+
|
| 341 |
+
# Initialize request argument(s)
|
| 342 |
+
request = generativelanguage_v1beta.GenerateContentRequest(
|
| 343 |
+
model="model_value",
|
| 344 |
+
)
|
| 345 |
+
|
| 346 |
+
# Make the request
|
| 347 |
+
response = await client.generate_content(request=request)
|
| 348 |
+
|
| 349 |
+
# Handle the response
|
| 350 |
+
print(response)
|
| 351 |
+
|
| 352 |
+
Args:
|
| 353 |
+
request (Optional[Union[google.ai.generativelanguage_v1beta.types.GenerateContentRequest, dict]]):
|
| 354 |
+
The request object. Request to generate a completion from
|
| 355 |
+
the model.
|
| 356 |
+
model (:class:`str`):
|
| 357 |
+
Required. The name of the ``Model`` to use for
|
| 358 |
+
generating the completion.
|
| 359 |
+
|
| 360 |
+
Format: ``models/{model}``.
|
| 361 |
+
|
| 362 |
+
This corresponds to the ``model`` field
|
| 363 |
+
on the ``request`` instance; if ``request`` is provided, this
|
| 364 |
+
should not be set.
|
| 365 |
+
contents (:class:`MutableSequence[google.ai.generativelanguage_v1beta.types.Content]`):
|
| 366 |
+
Required. The content of the current conversation with
|
| 367 |
+
the model.
|
| 368 |
+
|
| 369 |
+
For single-turn queries, this is a single instance. For
|
| 370 |
+
multi-turn queries like
|
| 371 |
+
`chat <https://ai.google.dev/gemini-api/docs/text-generation#chat>`__,
|
| 372 |
+
this is a repeated field that contains the conversation
|
| 373 |
+
history and the latest request.
|
| 374 |
+
|
| 375 |
+
This corresponds to the ``contents`` field
|
| 376 |
+
on the ``request`` instance; if ``request`` is provided, this
|
| 377 |
+
should not be set.
|
| 378 |
+
retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any,
|
| 379 |
+
should be retried.
|
| 380 |
+
timeout (float): The timeout for this request.
|
| 381 |
+
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
|
| 382 |
+
sent along with the request as metadata. Normally, each value must be of type `str`,
|
| 383 |
+
but for metadata keys ending with the suffix `-bin`, the corresponding values must
|
| 384 |
+
be of type `bytes`.
|
| 385 |
+
|
| 386 |
+
Returns:
|
| 387 |
+
google.ai.generativelanguage_v1beta.types.GenerateContentResponse:
|
| 388 |
+
Response from the model supporting multiple candidate
|
| 389 |
+
responses.
|
| 390 |
+
|
| 391 |
+
Safety ratings and content filtering are reported for
|
| 392 |
+
both prompt in
|
| 393 |
+
GenerateContentResponse.prompt_feedback and for each
|
| 394 |
+
candidate in finish_reason and in safety_ratings. The
|
| 395 |
+
API: - Returns either all requested candidates or
|
| 396 |
+
none of them - Returns no candidates at all only if
|
| 397 |
+
there was something wrong with the prompt (check
|
| 398 |
+
prompt_feedback) - Reports feedback on each candidate
|
| 399 |
+
in finish_reason and safety_ratings.
|
| 400 |
+
|
| 401 |
+
"""
|
| 402 |
+
# Create or coerce a protobuf request object.
|
| 403 |
+
# - Quick check: If we got a request object, we should *not* have
|
| 404 |
+
# gotten any keyword arguments that map to the request.
|
| 405 |
+
has_flattened_params = any([model, contents])
|
| 406 |
+
if request is not None and has_flattened_params:
|
| 407 |
+
raise ValueError(
|
| 408 |
+
"If the `request` argument is set, then none of "
|
| 409 |
+
"the individual field arguments should be set."
|
| 410 |
+
)
|
| 411 |
+
|
| 412 |
+
# - Use the request object if provided (there's no risk of modifying the input as
|
| 413 |
+
# there are no flattened fields), or create one.
|
| 414 |
+
if not isinstance(request, generative_service.GenerateContentRequest):
|
| 415 |
+
request = generative_service.GenerateContentRequest(request)
|
| 416 |
+
|
| 417 |
+
# If we have keyword arguments corresponding to fields on the
|
| 418 |
+
# request, apply these.
|
| 419 |
+
if model is not None:
|
| 420 |
+
request.model = model
|
| 421 |
+
if contents:
|
| 422 |
+
request.contents.extend(contents)
|
| 423 |
+
|
| 424 |
+
# Wrap the RPC method; this adds retry and timeout information,
|
| 425 |
+
# and friendly error handling.
|
| 426 |
+
rpc = self._client._transport._wrapped_methods[
|
| 427 |
+
self._client._transport.generate_content
|
| 428 |
+
]
|
| 429 |
+
|
| 430 |
+
# Certain fields should be provided within the metadata header;
|
| 431 |
+
# add these here.
|
| 432 |
+
metadata = tuple(metadata) + (
|
| 433 |
+
gapic_v1.routing_header.to_grpc_metadata((("model", request.model),)),
|
| 434 |
+
)
|
| 435 |
+
|
| 436 |
+
# Validate the universe domain.
|
| 437 |
+
self._client._validate_universe_domain()
|
| 438 |
+
|
| 439 |
+
# Send the request.
|
| 440 |
+
response = await rpc(
|
| 441 |
+
request,
|
| 442 |
+
retry=retry,
|
| 443 |
+
timeout=timeout,
|
| 444 |
+
metadata=metadata,
|
| 445 |
+
)
|
| 446 |
+
|
| 447 |
+
# Done; return the response.
|
| 448 |
+
return response
|
| 449 |
+
|
| 450 |
+
async def generate_answer(
|
| 451 |
+
self,
|
| 452 |
+
request: Optional[Union[generative_service.GenerateAnswerRequest, dict]] = None,
|
| 453 |
+
*,
|
| 454 |
+
model: Optional[str] = None,
|
| 455 |
+
contents: Optional[MutableSequence[content.Content]] = None,
|
| 456 |
+
safety_settings: Optional[MutableSequence[safety.SafetySetting]] = None,
|
| 457 |
+
answer_style: Optional[
|
| 458 |
+
generative_service.GenerateAnswerRequest.AnswerStyle
|
| 459 |
+
] = None,
|
| 460 |
+
retry: OptionalRetry = gapic_v1.method.DEFAULT,
|
| 461 |
+
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
|
| 462 |
+
metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
|
| 463 |
+
) -> generative_service.GenerateAnswerResponse:
|
| 464 |
+
r"""Generates a grounded answer from the model given an input
|
| 465 |
+
``GenerateAnswerRequest``.
|
| 466 |
+
|
| 467 |
+
.. code-block:: python
|
| 468 |
+
|
| 469 |
+
# This snippet has been automatically generated and should be regarded as a
|
| 470 |
+
# code template only.
|
| 471 |
+
# It will require modifications to work:
|
| 472 |
+
# - It may require correct/in-range values for request initialization.
|
| 473 |
+
# - It may require specifying regional endpoints when creating the service
|
| 474 |
+
# client as shown in:
|
| 475 |
+
# https://googleapis.dev/python/google-api-core/latest/client_options.html
|
| 476 |
+
from google.ai import generativelanguage_v1beta
|
| 477 |
+
|
| 478 |
+
async def sample_generate_answer():
|
| 479 |
+
# Create a client
|
| 480 |
+
client = generativelanguage_v1beta.GenerativeServiceAsyncClient()
|
| 481 |
+
|
| 482 |
+
# Initialize request argument(s)
|
| 483 |
+
request = generativelanguage_v1beta.GenerateAnswerRequest(
|
| 484 |
+
model="model_value",
|
| 485 |
+
answer_style="VERBOSE",
|
| 486 |
+
)
|
| 487 |
+
|
| 488 |
+
# Make the request
|
| 489 |
+
response = await client.generate_answer(request=request)
|
| 490 |
+
|
| 491 |
+
# Handle the response
|
| 492 |
+
print(response)
|
| 493 |
+
|
| 494 |
+
Args:
|
| 495 |
+
request (Optional[Union[google.ai.generativelanguage_v1beta.types.GenerateAnswerRequest, dict]]):
|
| 496 |
+
The request object. Request to generate a grounded answer from the
|
| 497 |
+
``Model``.
|
| 498 |
+
model (:class:`str`):
|
| 499 |
+
Required. The name of the ``Model`` to use for
|
| 500 |
+
generating the grounded response.
|
| 501 |
+
|
| 502 |
+
Format: ``model=models/{model}``.
|
| 503 |
+
|
| 504 |
+
This corresponds to the ``model`` field
|
| 505 |
+
on the ``request`` instance; if ``request`` is provided, this
|
| 506 |
+
should not be set.
|
| 507 |
+
contents (:class:`MutableSequence[google.ai.generativelanguage_v1beta.types.Content]`):
|
| 508 |
+
Required. The content of the current conversation with
|
| 509 |
+
the ``Model``. For single-turn queries, this is a single
|
| 510 |
+
question to answer. For multi-turn queries, this is a
|
| 511 |
+
repeated field that contains conversation history and
|
| 512 |
+
the last ``Content`` in the list containing the
|
| 513 |
+
question.
|
| 514 |
+
|
| 515 |
+
Note: ``GenerateAnswer`` only supports queries in
|
| 516 |
+
English.
|
| 517 |
+
|
| 518 |
+
This corresponds to the ``contents`` field
|
| 519 |
+
on the ``request`` instance; if ``request`` is provided, this
|
| 520 |
+
should not be set.
|
| 521 |
+
safety_settings (:class:`MutableSequence[google.ai.generativelanguage_v1beta.types.SafetySetting]`):
|
| 522 |
+
Optional. A list of unique ``SafetySetting`` instances
|
| 523 |
+
for blocking unsafe content.
|
| 524 |
+
|
| 525 |
+
This will be enforced on the
|
| 526 |
+
``GenerateAnswerRequest.contents`` and
|
| 527 |
+
``GenerateAnswerResponse.candidate``. There should not
|
| 528 |
+
be more than one setting for each ``SafetyCategory``
|
| 529 |
+
type. The API will block any contents and responses that
|
| 530 |
+
fail to meet the thresholds set by these settings. This
|
| 531 |
+
list overrides the default settings for each
|
| 532 |
+
``SafetyCategory`` specified in the safety_settings. If
|
| 533 |
+
there is no ``SafetySetting`` for a given
|
| 534 |
+
``SafetyCategory`` provided in the list, the API will
|
| 535 |
+
use the default safety setting for that category. Harm
|
| 536 |
+
categories HARM_CATEGORY_HATE_SPEECH,
|
| 537 |
+
HARM_CATEGORY_SEXUALLY_EXPLICIT,
|
| 538 |
+
HARM_CATEGORY_DANGEROUS_CONTENT,
|
| 539 |
+
HARM_CATEGORY_HARASSMENT are supported. Refer to the
|
| 540 |
+
`guide <https://ai.google.dev/gemini-api/docs/safety-settings>`__
|
| 541 |
+
for detailed information on available safety settings.
|
| 542 |
+
Also refer to the `Safety
|
| 543 |
+
guidance <https://ai.google.dev/gemini-api/docs/safety-guidance>`__
|
| 544 |
+
to learn how to incorporate safety considerations in
|
| 545 |
+
your AI applications.
|
| 546 |
+
|
| 547 |
+
This corresponds to the ``safety_settings`` field
|
| 548 |
+
on the ``request`` instance; if ``request`` is provided, this
|
| 549 |
+
should not be set.
|
| 550 |
+
answer_style (:class:`google.ai.generativelanguage_v1beta.types.GenerateAnswerRequest.AnswerStyle`):
|
| 551 |
+
Required. Style in which answers
|
| 552 |
+
should be returned.
|
| 553 |
+
|
| 554 |
+
This corresponds to the ``answer_style`` field
|
| 555 |
+
on the ``request`` instance; if ``request`` is provided, this
|
| 556 |
+
should not be set.
|
| 557 |
+
retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any,
|
| 558 |
+
should be retried.
|
| 559 |
+
timeout (float): The timeout for this request.
|
| 560 |
+
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
|
| 561 |
+
sent along with the request as metadata. Normally, each value must be of type `str`,
|
| 562 |
+
but for metadata keys ending with the suffix `-bin`, the corresponding values must
|
| 563 |
+
be of type `bytes`.
|
| 564 |
+
|
| 565 |
+
Returns:
|
| 566 |
+
google.ai.generativelanguage_v1beta.types.GenerateAnswerResponse:
|
| 567 |
+
Response from the model for a
|
| 568 |
+
grounded answer.
|
| 569 |
+
|
| 570 |
+
"""
|
| 571 |
+
# Create or coerce a protobuf request object.
|
| 572 |
+
# - Quick check: If we got a request object, we should *not* have
|
| 573 |
+
# gotten any keyword arguments that map to the request.
|
| 574 |
+
has_flattened_params = any([model, contents, safety_settings, answer_style])
|
| 575 |
+
if request is not None and has_flattened_params:
|
| 576 |
+
raise ValueError(
|
| 577 |
+
"If the `request` argument is set, then none of "
|
| 578 |
+
"the individual field arguments should be set."
|
| 579 |
+
)
|
| 580 |
+
|
| 581 |
+
# - Use the request object if provided (there's no risk of modifying the input as
|
| 582 |
+
# there are no flattened fields), or create one.
|
| 583 |
+
if not isinstance(request, generative_service.GenerateAnswerRequest):
|
| 584 |
+
request = generative_service.GenerateAnswerRequest(request)
|
| 585 |
+
|
| 586 |
+
# If we have keyword arguments corresponding to fields on the
|
| 587 |
+
# request, apply these.
|
| 588 |
+
if model is not None:
|
| 589 |
+
request.model = model
|
| 590 |
+
if answer_style is not None:
|
| 591 |
+
request.answer_style = answer_style
|
| 592 |
+
if contents:
|
| 593 |
+
request.contents.extend(contents)
|
| 594 |
+
if safety_settings:
|
| 595 |
+
request.safety_settings.extend(safety_settings)
|
| 596 |
+
|
| 597 |
+
# Wrap the RPC method; this adds retry and timeout information,
|
| 598 |
+
# and friendly error handling.
|
| 599 |
+
rpc = self._client._transport._wrapped_methods[
|
| 600 |
+
self._client._transport.generate_answer
|
| 601 |
+
]
|
| 602 |
+
|
| 603 |
+
# Certain fields should be provided within the metadata header;
|
| 604 |
+
# add these here.
|
| 605 |
+
metadata = tuple(metadata) + (
|
| 606 |
+
gapic_v1.routing_header.to_grpc_metadata((("model", request.model),)),
|
| 607 |
+
)
|
| 608 |
+
|
| 609 |
+
# Validate the universe domain.
|
| 610 |
+
self._client._validate_universe_domain()
|
| 611 |
+
|
| 612 |
+
# Send the request.
|
| 613 |
+
response = await rpc(
|
| 614 |
+
request,
|
| 615 |
+
retry=retry,
|
| 616 |
+
timeout=timeout,
|
| 617 |
+
metadata=metadata,
|
| 618 |
+
)
|
| 619 |
+
|
| 620 |
+
# Done; return the response.
|
| 621 |
+
return response
|
| 622 |
+
|
| 623 |
+
def stream_generate_content(
|
| 624 |
+
self,
|
| 625 |
+
request: Optional[
|
| 626 |
+
Union[generative_service.GenerateContentRequest, dict]
|
| 627 |
+
] = None,
|
| 628 |
+
*,
|
| 629 |
+
model: Optional[str] = None,
|
| 630 |
+
contents: Optional[MutableSequence[content.Content]] = None,
|
| 631 |
+
retry: OptionalRetry = gapic_v1.method.DEFAULT,
|
| 632 |
+
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
|
| 633 |
+
metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
|
| 634 |
+
) -> Awaitable[AsyncIterable[generative_service.GenerateContentResponse]]:
|
| 635 |
+
r"""Generates a `streamed
|
| 636 |
+
response <https://ai.google.dev/gemini-api/docs/text-generation?lang=python#generate-a-text-stream>`__
|
| 637 |
+
from the model given an input ``GenerateContentRequest``.
|
| 638 |
+
|
| 639 |
+
.. code-block:: python
|
| 640 |
+
|
| 641 |
+
# This snippet has been automatically generated and should be regarded as a
|
| 642 |
+
# code template only.
|
| 643 |
+
# It will require modifications to work:
|
| 644 |
+
# - It may require correct/in-range values for request initialization.
|
| 645 |
+
# - It may require specifying regional endpoints when creating the service
|
| 646 |
+
# client as shown in:
|
| 647 |
+
# https://googleapis.dev/python/google-api-core/latest/client_options.html
|
| 648 |
+
from google.ai import generativelanguage_v1beta
|
| 649 |
+
|
| 650 |
+
async def sample_stream_generate_content():
|
| 651 |
+
# Create a client
|
| 652 |
+
client = generativelanguage_v1beta.GenerativeServiceAsyncClient()
|
| 653 |
+
|
| 654 |
+
# Initialize request argument(s)
|
| 655 |
+
request = generativelanguage_v1beta.GenerateContentRequest(
|
| 656 |
+
model="model_value",
|
| 657 |
+
)
|
| 658 |
+
|
| 659 |
+
# Make the request
|
| 660 |
+
stream = await client.stream_generate_content(request=request)
|
| 661 |
+
|
| 662 |
+
# Handle the response
|
| 663 |
+
async for response in stream:
|
| 664 |
+
print(response)
|
| 665 |
+
|
| 666 |
+
Args:
|
| 667 |
+
request (Optional[Union[google.ai.generativelanguage_v1beta.types.GenerateContentRequest, dict]]):
|
| 668 |
+
The request object. Request to generate a completion from
|
| 669 |
+
the model.
|
| 670 |
+
model (:class:`str`):
|
| 671 |
+
Required. The name of the ``Model`` to use for
|
| 672 |
+
generating the completion.
|
| 673 |
+
|
| 674 |
+
Format: ``models/{model}``.
|
| 675 |
+
|
| 676 |
+
This corresponds to the ``model`` field
|
| 677 |
+
on the ``request`` instance; if ``request`` is provided, this
|
| 678 |
+
should not be set.
|
| 679 |
+
contents (:class:`MutableSequence[google.ai.generativelanguage_v1beta.types.Content]`):
|
| 680 |
+
Required. The content of the current conversation with
|
| 681 |
+
the model.
|
| 682 |
+
|
| 683 |
+
For single-turn queries, this is a single instance. For
|
| 684 |
+
multi-turn queries like
|
| 685 |
+
`chat <https://ai.google.dev/gemini-api/docs/text-generation#chat>`__,
|
| 686 |
+
this is a repeated field that contains the conversation
|
| 687 |
+
history and the latest request.
|
| 688 |
+
|
| 689 |
+
This corresponds to the ``contents`` field
|
| 690 |
+
on the ``request`` instance; if ``request`` is provided, this
|
| 691 |
+
should not be set.
|
| 692 |
+
retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any,
|
| 693 |
+
should be retried.
|
| 694 |
+
timeout (float): The timeout for this request.
|
| 695 |
+
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
|
| 696 |
+
sent along with the request as metadata. Normally, each value must be of type `str`,
|
| 697 |
+
but for metadata keys ending with the suffix `-bin`, the corresponding values must
|
| 698 |
+
be of type `bytes`.
|
| 699 |
+
|
| 700 |
+
Returns:
|
| 701 |
+
AsyncIterable[google.ai.generativelanguage_v1beta.types.GenerateContentResponse]:
|
| 702 |
+
Response from the model supporting multiple candidate
|
| 703 |
+
responses.
|
| 704 |
+
|
| 705 |
+
Safety ratings and content filtering are reported for
|
| 706 |
+
both prompt in
|
| 707 |
+
GenerateContentResponse.prompt_feedback and for each
|
| 708 |
+
candidate in finish_reason and in safety_ratings. The
|
| 709 |
+
API: - Returns either all requested candidates or
|
| 710 |
+
none of them - Returns no candidates at all only if
|
| 711 |
+
there was something wrong with the prompt (check
|
| 712 |
+
prompt_feedback) - Reports feedback on each candidate
|
| 713 |
+
in finish_reason and safety_ratings.
|
| 714 |
+
|
| 715 |
+
"""
|
| 716 |
+
# Create or coerce a protobuf request object.
|
| 717 |
+
# - Quick check: If we got a request object, we should *not* have
|
| 718 |
+
# gotten any keyword arguments that map to the request.
|
| 719 |
+
has_flattened_params = any([model, contents])
|
| 720 |
+
if request is not None and has_flattened_params:
|
| 721 |
+
raise ValueError(
|
| 722 |
+
"If the `request` argument is set, then none of "
|
| 723 |
+
"the individual field arguments should be set."
|
| 724 |
+
)
|
| 725 |
+
|
| 726 |
+
# - Use the request object if provided (there's no risk of modifying the input as
|
| 727 |
+
# there are no flattened fields), or create one.
|
| 728 |
+
if not isinstance(request, generative_service.GenerateContentRequest):
|
| 729 |
+
request = generative_service.GenerateContentRequest(request)
|
| 730 |
+
|
| 731 |
+
# If we have keyword arguments corresponding to fields on the
|
| 732 |
+
# request, apply these.
|
| 733 |
+
if model is not None:
|
| 734 |
+
request.model = model
|
| 735 |
+
if contents:
|
| 736 |
+
request.contents.extend(contents)
|
| 737 |
+
|
| 738 |
+
# Wrap the RPC method; this adds retry and timeout information,
|
| 739 |
+
# and friendly error handling.
|
| 740 |
+
rpc = self._client._transport._wrapped_methods[
|
| 741 |
+
self._client._transport.stream_generate_content
|
| 742 |
+
]
|
| 743 |
+
|
| 744 |
+
# Certain fields should be provided within the metadata header;
|
| 745 |
+
# add these here.
|
| 746 |
+
metadata = tuple(metadata) + (
|
| 747 |
+
gapic_v1.routing_header.to_grpc_metadata((("model", request.model),)),
|
| 748 |
+
)
|
| 749 |
+
|
| 750 |
+
# Validate the universe domain.
|
| 751 |
+
self._client._validate_universe_domain()
|
| 752 |
+
|
| 753 |
+
# Send the request.
|
| 754 |
+
response = rpc(
|
| 755 |
+
request,
|
| 756 |
+
retry=retry,
|
| 757 |
+
timeout=timeout,
|
| 758 |
+
metadata=metadata,
|
| 759 |
+
)
|
| 760 |
+
|
| 761 |
+
# Done; return the response.
|
| 762 |
+
return response
|
| 763 |
+
|
| 764 |
+
async def embed_content(
|
| 765 |
+
self,
|
| 766 |
+
request: Optional[Union[generative_service.EmbedContentRequest, dict]] = None,
|
| 767 |
+
*,
|
| 768 |
+
model: Optional[str] = None,
|
| 769 |
+
content: Optional[gag_content.Content] = None,
|
| 770 |
+
retry: OptionalRetry = gapic_v1.method.DEFAULT,
|
| 771 |
+
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
|
| 772 |
+
metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
|
| 773 |
+
) -> generative_service.EmbedContentResponse:
|
| 774 |
+
r"""Generates a text embedding vector from the input ``Content``
|
| 775 |
+
using the specified `Gemini Embedding
|
| 776 |
+
model <https://ai.google.dev/gemini-api/docs/models/gemini#text-embedding>`__.
|
| 777 |
+
|
| 778 |
+
.. code-block:: python
|
| 779 |
+
|
| 780 |
+
# This snippet has been automatically generated and should be regarded as a
|
| 781 |
+
# code template only.
|
| 782 |
+
# It will require modifications to work:
|
| 783 |
+
# - It may require correct/in-range values for request initialization.
|
| 784 |
+
# - It may require specifying regional endpoints when creating the service
|
| 785 |
+
# client as shown in:
|
| 786 |
+
# https://googleapis.dev/python/google-api-core/latest/client_options.html
|
| 787 |
+
from google.ai import generativelanguage_v1beta
|
| 788 |
+
|
| 789 |
+
async def sample_embed_content():
|
| 790 |
+
# Create a client
|
| 791 |
+
client = generativelanguage_v1beta.GenerativeServiceAsyncClient()
|
| 792 |
+
|
| 793 |
+
# Initialize request argument(s)
|
| 794 |
+
request = generativelanguage_v1beta.EmbedContentRequest(
|
| 795 |
+
model="model_value",
|
| 796 |
+
)
|
| 797 |
+
|
| 798 |
+
# Make the request
|
| 799 |
+
response = await client.embed_content(request=request)
|
| 800 |
+
|
| 801 |
+
# Handle the response
|
| 802 |
+
print(response)
|
| 803 |
+
|
| 804 |
+
Args:
|
| 805 |
+
request (Optional[Union[google.ai.generativelanguage_v1beta.types.EmbedContentRequest, dict]]):
|
| 806 |
+
The request object. Request containing the ``Content`` for the model to
|
| 807 |
+
embed.
|
| 808 |
+
model (:class:`str`):
|
| 809 |
+
Required. The model's resource name. This serves as an
|
| 810 |
+
ID for the Model to use.
|
| 811 |
+
|
| 812 |
+
This name should match a model name returned by the
|
| 813 |
+
``ListModels`` method.
|
| 814 |
+
|
| 815 |
+
Format: ``models/{model}``
|
| 816 |
+
|
| 817 |
+
This corresponds to the ``model`` field
|
| 818 |
+
on the ``request`` instance; if ``request`` is provided, this
|
| 819 |
+
should not be set.
|
| 820 |
+
content (:class:`google.ai.generativelanguage_v1beta.types.Content`):
|
| 821 |
+
Required. The content to embed. Only the ``parts.text``
|
| 822 |
+
fields will be counted.
|
| 823 |
+
|
| 824 |
+
This corresponds to the ``content`` field
|
| 825 |
+
on the ``request`` instance; if ``request`` is provided, this
|
| 826 |
+
should not be set.
|
| 827 |
+
retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any,
|
| 828 |
+
should be retried.
|
| 829 |
+
timeout (float): The timeout for this request.
|
| 830 |
+
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
|
| 831 |
+
sent along with the request as metadata. Normally, each value must be of type `str`,
|
| 832 |
+
but for metadata keys ending with the suffix `-bin`, the corresponding values must
|
| 833 |
+
be of type `bytes`.
|
| 834 |
+
|
| 835 |
+
Returns:
|
| 836 |
+
google.ai.generativelanguage_v1beta.types.EmbedContentResponse:
|
| 837 |
+
The response to an EmbedContentRequest.
|
| 838 |
+
"""
|
| 839 |
+
# Create or coerce a protobuf request object.
|
| 840 |
+
# - Quick check: If we got a request object, we should *not* have
|
| 841 |
+
# gotten any keyword arguments that map to the request.
|
| 842 |
+
has_flattened_params = any([model, content])
|
| 843 |
+
if request is not None and has_flattened_params:
|
| 844 |
+
raise ValueError(
|
| 845 |
+
"If the `request` argument is set, then none of "
|
| 846 |
+
"the individual field arguments should be set."
|
| 847 |
+
)
|
| 848 |
+
|
| 849 |
+
# - Use the request object if provided (there's no risk of modifying the input as
|
| 850 |
+
# there are no flattened fields), or create one.
|
| 851 |
+
if not isinstance(request, generative_service.EmbedContentRequest):
|
| 852 |
+
request = generative_service.EmbedContentRequest(request)
|
| 853 |
+
|
| 854 |
+
# If we have keyword arguments corresponding to fields on the
|
| 855 |
+
# request, apply these.
|
| 856 |
+
if model is not None:
|
| 857 |
+
request.model = model
|
| 858 |
+
if content is not None:
|
| 859 |
+
request.content = content
|
| 860 |
+
|
| 861 |
+
# Wrap the RPC method; this adds retry and timeout information,
|
| 862 |
+
# and friendly error handling.
|
| 863 |
+
rpc = self._client._transport._wrapped_methods[
|
| 864 |
+
self._client._transport.embed_content
|
| 865 |
+
]
|
| 866 |
+
|
| 867 |
+
# Certain fields should be provided within the metadata header;
|
| 868 |
+
# add these here.
|
| 869 |
+
metadata = tuple(metadata) + (
|
| 870 |
+
gapic_v1.routing_header.to_grpc_metadata((("model", request.model),)),
|
| 871 |
+
)
|
| 872 |
+
|
| 873 |
+
# Validate the universe domain.
|
| 874 |
+
self._client._validate_universe_domain()
|
| 875 |
+
|
| 876 |
+
# Send the request.
|
| 877 |
+
response = await rpc(
|
| 878 |
+
request,
|
| 879 |
+
retry=retry,
|
| 880 |
+
timeout=timeout,
|
| 881 |
+
metadata=metadata,
|
| 882 |
+
)
|
| 883 |
+
|
| 884 |
+
# Done; return the response.
|
| 885 |
+
return response
|
| 886 |
+
|
| 887 |
+
async def batch_embed_contents(
|
| 888 |
+
self,
|
| 889 |
+
request: Optional[
|
| 890 |
+
Union[generative_service.BatchEmbedContentsRequest, dict]
|
| 891 |
+
] = None,
|
| 892 |
+
*,
|
| 893 |
+
model: Optional[str] = None,
|
| 894 |
+
requests: Optional[
|
| 895 |
+
MutableSequence[generative_service.EmbedContentRequest]
|
| 896 |
+
] = None,
|
| 897 |
+
retry: OptionalRetry = gapic_v1.method.DEFAULT,
|
| 898 |
+
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
|
| 899 |
+
metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
|
| 900 |
+
) -> generative_service.BatchEmbedContentsResponse:
|
| 901 |
+
r"""Generates multiple embedding vectors from the input ``Content``
|
| 902 |
+
which consists of a batch of strings represented as
|
| 903 |
+
``EmbedContentRequest`` objects.
|
| 904 |
+
|
| 905 |
+
.. code-block:: python
|
| 906 |
+
|
| 907 |
+
# This snippet has been automatically generated and should be regarded as a
|
| 908 |
+
# code template only.
|
| 909 |
+
# It will require modifications to work:
|
| 910 |
+
# - It may require correct/in-range values for request initialization.
|
| 911 |
+
# - It may require specifying regional endpoints when creating the service
|
| 912 |
+
# client as shown in:
|
| 913 |
+
# https://googleapis.dev/python/google-api-core/latest/client_options.html
|
| 914 |
+
from google.ai import generativelanguage_v1beta
|
| 915 |
+
|
| 916 |
+
async def sample_batch_embed_contents():
|
| 917 |
+
# Create a client
|
| 918 |
+
client = generativelanguage_v1beta.GenerativeServiceAsyncClient()
|
| 919 |
+
|
| 920 |
+
# Initialize request argument(s)
|
| 921 |
+
requests = generativelanguage_v1beta.EmbedContentRequest()
|
| 922 |
+
requests.model = "model_value"
|
| 923 |
+
|
| 924 |
+
request = generativelanguage_v1beta.BatchEmbedContentsRequest(
|
| 925 |
+
model="model_value",
|
| 926 |
+
requests=requests,
|
| 927 |
+
)
|
| 928 |
+
|
| 929 |
+
# Make the request
|
| 930 |
+
response = await client.batch_embed_contents(request=request)
|
| 931 |
+
|
| 932 |
+
# Handle the response
|
| 933 |
+
print(response)
|
| 934 |
+
|
| 935 |
+
Args:
|
| 936 |
+
request (Optional[Union[google.ai.generativelanguage_v1beta.types.BatchEmbedContentsRequest, dict]]):
|
| 937 |
+
The request object. Batch request to get embeddings from
|
| 938 |
+
the model for a list of prompts.
|
| 939 |
+
model (:class:`str`):
|
| 940 |
+
Required. The model's resource name. This serves as an
|
| 941 |
+
ID for the Model to use.
|
| 942 |
+
|
| 943 |
+
This name should match a model name returned by the
|
| 944 |
+
``ListModels`` method.
|
| 945 |
+
|
| 946 |
+
Format: ``models/{model}``
|
| 947 |
+
|
| 948 |
+
This corresponds to the ``model`` field
|
| 949 |
+
on the ``request`` instance; if ``request`` is provided, this
|
| 950 |
+
should not be set.
|
| 951 |
+
requests (:class:`MutableSequence[google.ai.generativelanguage_v1beta.types.EmbedContentRequest]`):
|
| 952 |
+
Required. Embed requests for the batch. The model in
|
| 953 |
+
each of these requests must match the model specified
|
| 954 |
+
``BatchEmbedContentsRequest.model``.
|
| 955 |
+
|
| 956 |
+
This corresponds to the ``requests`` field
|
| 957 |
+
on the ``request`` instance; if ``request`` is provided, this
|
| 958 |
+
should not be set.
|
| 959 |
+
retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any,
|
| 960 |
+
should be retried.
|
| 961 |
+
timeout (float): The timeout for this request.
|
| 962 |
+
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
|
| 963 |
+
sent along with the request as metadata. Normally, each value must be of type `str`,
|
| 964 |
+
but for metadata keys ending with the suffix `-bin`, the corresponding values must
|
| 965 |
+
be of type `bytes`.
|
| 966 |
+
|
| 967 |
+
Returns:
|
| 968 |
+
google.ai.generativelanguage_v1beta.types.BatchEmbedContentsResponse:
|
| 969 |
+
The response to a BatchEmbedContentsRequest.
|
| 970 |
+
"""
|
| 971 |
+
# Create or coerce a protobuf request object.
|
| 972 |
+
# - Quick check: If we got a request object, we should *not* have
|
| 973 |
+
# gotten any keyword arguments that map to the request.
|
| 974 |
+
has_flattened_params = any([model, requests])
|
| 975 |
+
if request is not None and has_flattened_params:
|
| 976 |
+
raise ValueError(
|
| 977 |
+
"If the `request` argument is set, then none of "
|
| 978 |
+
"the individual field arguments should be set."
|
| 979 |
+
)
|
| 980 |
+
|
| 981 |
+
# - Use the request object if provided (there's no risk of modifying the input as
|
| 982 |
+
# there are no flattened fields), or create one.
|
| 983 |
+
if not isinstance(request, generative_service.BatchEmbedContentsRequest):
|
| 984 |
+
request = generative_service.BatchEmbedContentsRequest(request)
|
| 985 |
+
|
| 986 |
+
# If we have keyword arguments corresponding to fields on the
|
| 987 |
+
# request, apply these.
|
| 988 |
+
if model is not None:
|
| 989 |
+
request.model = model
|
| 990 |
+
if requests:
|
| 991 |
+
request.requests.extend(requests)
|
| 992 |
+
|
| 993 |
+
# Wrap the RPC method; this adds retry and timeout information,
|
| 994 |
+
# and friendly error handling.
|
| 995 |
+
rpc = self._client._transport._wrapped_methods[
|
| 996 |
+
self._client._transport.batch_embed_contents
|
| 997 |
+
]
|
| 998 |
+
|
| 999 |
+
# Certain fields should be provided within the metadata header;
|
| 1000 |
+
# add these here.
|
| 1001 |
+
metadata = tuple(metadata) + (
|
| 1002 |
+
gapic_v1.routing_header.to_grpc_metadata((("model", request.model),)),
|
| 1003 |
+
)
|
| 1004 |
+
|
| 1005 |
+
# Validate the universe domain.
|
| 1006 |
+
self._client._validate_universe_domain()
|
| 1007 |
+
|
| 1008 |
+
# Send the request.
|
| 1009 |
+
response = await rpc(
|
| 1010 |
+
request,
|
| 1011 |
+
retry=retry,
|
| 1012 |
+
timeout=timeout,
|
| 1013 |
+
metadata=metadata,
|
| 1014 |
+
)
|
| 1015 |
+
|
| 1016 |
+
# Done; return the response.
|
| 1017 |
+
return response
|
| 1018 |
+
|
| 1019 |
+
async def count_tokens(
|
| 1020 |
+
self,
|
| 1021 |
+
request: Optional[Union[generative_service.CountTokensRequest, dict]] = None,
|
| 1022 |
+
*,
|
| 1023 |
+
model: Optional[str] = None,
|
| 1024 |
+
contents: Optional[MutableSequence[content.Content]] = None,
|
| 1025 |
+
retry: OptionalRetry = gapic_v1.method.DEFAULT,
|
| 1026 |
+
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
|
| 1027 |
+
metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
|
| 1028 |
+
) -> generative_service.CountTokensResponse:
|
| 1029 |
+
r"""Runs a model's tokenizer on input ``Content`` and returns the
|
| 1030 |
+
token count. Refer to the `tokens
|
| 1031 |
+
guide <https://ai.google.dev/gemini-api/docs/tokens>`__ to learn
|
| 1032 |
+
more about tokens.
|
| 1033 |
+
|
| 1034 |
+
.. code-block:: python
|
| 1035 |
+
|
| 1036 |
+
# This snippet has been automatically generated and should be regarded as a
|
| 1037 |
+
# code template only.
|
| 1038 |
+
# It will require modifications to work:
|
| 1039 |
+
# - It may require correct/in-range values for request initialization.
|
| 1040 |
+
# - It may require specifying regional endpoints when creating the service
|
| 1041 |
+
# client as shown in:
|
| 1042 |
+
# https://googleapis.dev/python/google-api-core/latest/client_options.html
|
| 1043 |
+
from google.ai import generativelanguage_v1beta
|
| 1044 |
+
|
| 1045 |
+
async def sample_count_tokens():
|
| 1046 |
+
# Create a client
|
| 1047 |
+
client = generativelanguage_v1beta.GenerativeServiceAsyncClient()
|
| 1048 |
+
|
| 1049 |
+
# Initialize request argument(s)
|
| 1050 |
+
request = generativelanguage_v1beta.CountTokensRequest(
|
| 1051 |
+
model="model_value",
|
| 1052 |
+
)
|
| 1053 |
+
|
| 1054 |
+
# Make the request
|
| 1055 |
+
response = await client.count_tokens(request=request)
|
| 1056 |
+
|
| 1057 |
+
# Handle the response
|
| 1058 |
+
print(response)
|
| 1059 |
+
|
| 1060 |
+
Args:
|
| 1061 |
+
request (Optional[Union[google.ai.generativelanguage_v1beta.types.CountTokensRequest, dict]]):
|
| 1062 |
+
The request object. Counts the number of tokens in the ``prompt`` sent to a
|
| 1063 |
+
model.
|
| 1064 |
+
|
| 1065 |
+
Models may tokenize text differently, so each model may
|
| 1066 |
+
return a different ``token_count``.
|
| 1067 |
+
model (:class:`str`):
|
| 1068 |
+
Required. The model's resource name. This serves as an
|
| 1069 |
+
ID for the Model to use.
|
| 1070 |
+
|
| 1071 |
+
This name should match a model name returned by the
|
| 1072 |
+
``ListModels`` method.
|
| 1073 |
+
|
| 1074 |
+
Format: ``models/{model}``
|
| 1075 |
+
|
| 1076 |
+
This corresponds to the ``model`` field
|
| 1077 |
+
on the ``request`` instance; if ``request`` is provided, this
|
| 1078 |
+
should not be set.
|
| 1079 |
+
contents (:class:`MutableSequence[google.ai.generativelanguage_v1beta.types.Content]`):
|
| 1080 |
+
Optional. The input given to the model as a prompt. This
|
| 1081 |
+
field is ignored when ``generate_content_request`` is
|
| 1082 |
+
set.
|
| 1083 |
+
|
| 1084 |
+
This corresponds to the ``contents`` field
|
| 1085 |
+
on the ``request`` instance; if ``request`` is provided, this
|
| 1086 |
+
should not be set.
|
| 1087 |
+
retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any,
|
| 1088 |
+
should be retried.
|
| 1089 |
+
timeout (float): The timeout for this request.
|
| 1090 |
+
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
|
| 1091 |
+
sent along with the request as metadata. Normally, each value must be of type `str`,
|
| 1092 |
+
but for metadata keys ending with the suffix `-bin`, the corresponding values must
|
| 1093 |
+
be of type `bytes`.
|
| 1094 |
+
|
| 1095 |
+
Returns:
|
| 1096 |
+
google.ai.generativelanguage_v1beta.types.CountTokensResponse:
|
| 1097 |
+
A response from CountTokens.
|
| 1098 |
+
|
| 1099 |
+
It returns the model's token_count for the prompt.
|
| 1100 |
+
|
| 1101 |
+
"""
|
| 1102 |
+
# Create or coerce a protobuf request object.
|
| 1103 |
+
# - Quick check: If we got a request object, we should *not* have
|
| 1104 |
+
# gotten any keyword arguments that map to the request.
|
| 1105 |
+
has_flattened_params = any([model, contents])
|
| 1106 |
+
if request is not None and has_flattened_params:
|
| 1107 |
+
raise ValueError(
|
| 1108 |
+
"If the `request` argument is set, then none of "
|
| 1109 |
+
"the individual field arguments should be set."
|
| 1110 |
+
)
|
| 1111 |
+
|
| 1112 |
+
# - Use the request object if provided (there's no risk of modifying the input as
|
| 1113 |
+
# there are no flattened fields), or create one.
|
| 1114 |
+
if not isinstance(request, generative_service.CountTokensRequest):
|
| 1115 |
+
request = generative_service.CountTokensRequest(request)
|
| 1116 |
+
|
| 1117 |
+
# If we have keyword arguments corresponding to fields on the
|
| 1118 |
+
# request, apply these.
|
| 1119 |
+
if model is not None:
|
| 1120 |
+
request.model = model
|
| 1121 |
+
if contents:
|
| 1122 |
+
request.contents.extend(contents)
|
| 1123 |
+
|
| 1124 |
+
# Wrap the RPC method; this adds retry and timeout information,
|
| 1125 |
+
# and friendly error handling.
|
| 1126 |
+
rpc = self._client._transport._wrapped_methods[
|
| 1127 |
+
self._client._transport.count_tokens
|
| 1128 |
+
]
|
| 1129 |
+
|
| 1130 |
+
# Certain fields should be provided within the metadata header;
|
| 1131 |
+
# add these here.
|
| 1132 |
+
metadata = tuple(metadata) + (
|
| 1133 |
+
gapic_v1.routing_header.to_grpc_metadata((("model", request.model),)),
|
| 1134 |
+
)
|
| 1135 |
+
|
| 1136 |
+
# Validate the universe domain.
|
| 1137 |
+
self._client._validate_universe_domain()
|
| 1138 |
+
|
| 1139 |
+
# Send the request.
|
| 1140 |
+
response = await rpc(
|
| 1141 |
+
request,
|
| 1142 |
+
retry=retry,
|
| 1143 |
+
timeout=timeout,
|
| 1144 |
+
metadata=metadata,
|
| 1145 |
+
)
|
| 1146 |
+
|
| 1147 |
+
# Done; return the response.
|
| 1148 |
+
return response
|
| 1149 |
+
|
| 1150 |
+
async def list_operations(
|
| 1151 |
+
self,
|
| 1152 |
+
request: Optional[operations_pb2.ListOperationsRequest] = None,
|
| 1153 |
+
*,
|
| 1154 |
+
retry: OptionalRetry = gapic_v1.method.DEFAULT,
|
| 1155 |
+
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
|
| 1156 |
+
metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
|
| 1157 |
+
) -> operations_pb2.ListOperationsResponse:
|
| 1158 |
+
r"""Lists operations that match the specified filter in the request.
|
| 1159 |
+
|
| 1160 |
+
Args:
|
| 1161 |
+
request (:class:`~.operations_pb2.ListOperationsRequest`):
|
| 1162 |
+
The request object. Request message for
|
| 1163 |
+
`ListOperations` method.
|
| 1164 |
+
retry (google.api_core.retry_async.AsyncRetry): Designation of what errors,
|
| 1165 |
+
if any, should be retried.
|
| 1166 |
+
timeout (float): The timeout for this request.
|
| 1167 |
+
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
|
| 1168 |
+
sent along with the request as metadata. Normally, each value must be of type `str`,
|
| 1169 |
+
but for metadata keys ending with the suffix `-bin`, the corresponding values must
|
| 1170 |
+
be of type `bytes`.
|
| 1171 |
+
Returns:
|
| 1172 |
+
~.operations_pb2.ListOperationsResponse:
|
| 1173 |
+
Response message for ``ListOperations`` method.
|
| 1174 |
+
"""
|
| 1175 |
+
# Create or coerce a protobuf request object.
|
| 1176 |
+
# The request isn't a proto-plus wrapped type,
|
| 1177 |
+
# so it must be constructed via keyword expansion.
|
| 1178 |
+
if isinstance(request, dict):
|
| 1179 |
+
request = operations_pb2.ListOperationsRequest(**request)
|
| 1180 |
+
|
| 1181 |
+
# Wrap the RPC method; this adds retry and timeout information,
|
| 1182 |
+
# and friendly error handling.
|
| 1183 |
+
rpc = self.transport._wrapped_methods[self._client._transport.list_operations]
|
| 1184 |
+
|
| 1185 |
+
# Certain fields should be provided within the metadata header;
|
| 1186 |
+
# add these here.
|
| 1187 |
+
metadata = tuple(metadata) + (
|
| 1188 |
+
gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
|
| 1189 |
+
)
|
| 1190 |
+
|
| 1191 |
+
# Validate the universe domain.
|
| 1192 |
+
self._client._validate_universe_domain()
|
| 1193 |
+
|
| 1194 |
+
# Send the request.
|
| 1195 |
+
response = await rpc(
|
| 1196 |
+
request,
|
| 1197 |
+
retry=retry,
|
| 1198 |
+
timeout=timeout,
|
| 1199 |
+
metadata=metadata,
|
| 1200 |
+
)
|
| 1201 |
+
|
| 1202 |
+
# Done; return the response.
|
| 1203 |
+
return response
|
| 1204 |
+
|
| 1205 |
+
async def get_operation(
|
| 1206 |
+
self,
|
| 1207 |
+
request: Optional[operations_pb2.GetOperationRequest] = None,
|
| 1208 |
+
*,
|
| 1209 |
+
retry: OptionalRetry = gapic_v1.method.DEFAULT,
|
| 1210 |
+
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
|
| 1211 |
+
metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
|
| 1212 |
+
) -> operations_pb2.Operation:
|
| 1213 |
+
r"""Gets the latest state of a long-running operation.
|
| 1214 |
+
|
| 1215 |
+
Args:
|
| 1216 |
+
request (:class:`~.operations_pb2.GetOperationRequest`):
|
| 1217 |
+
The request object. Request message for
|
| 1218 |
+
`GetOperation` method.
|
| 1219 |
+
retry (google.api_core.retry_async.AsyncRetry): Designation of what errors,
|
| 1220 |
+
if any, should be retried.
|
| 1221 |
+
timeout (float): The timeout for this request.
|
| 1222 |
+
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
|
| 1223 |
+
sent along with the request as metadata. Normally, each value must be of type `str`,
|
| 1224 |
+
but for metadata keys ending with the suffix `-bin`, the corresponding values must
|
| 1225 |
+
be of type `bytes`.
|
| 1226 |
+
Returns:
|
| 1227 |
+
~.operations_pb2.Operation:
|
| 1228 |
+
An ``Operation`` object.
|
| 1229 |
+
"""
|
| 1230 |
+
# Create or coerce a protobuf request object.
|
| 1231 |
+
# The request isn't a proto-plus wrapped type,
|
| 1232 |
+
# so it must be constructed via keyword expansion.
|
| 1233 |
+
if isinstance(request, dict):
|
| 1234 |
+
request = operations_pb2.GetOperationRequest(**request)
|
| 1235 |
+
|
| 1236 |
+
# Wrap the RPC method; this adds retry and timeout information,
|
| 1237 |
+
# and friendly error handling.
|
| 1238 |
+
rpc = self.transport._wrapped_methods[self._client._transport.get_operation]
|
| 1239 |
+
|
| 1240 |
+
# Certain fields should be provided within the metadata header;
|
| 1241 |
+
# add these here.
|
| 1242 |
+
metadata = tuple(metadata) + (
|
| 1243 |
+
gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
|
| 1244 |
+
)
|
| 1245 |
+
|
| 1246 |
+
# Validate the universe domain.
|
| 1247 |
+
self._client._validate_universe_domain()
|
| 1248 |
+
|
| 1249 |
+
# Send the request.
|
| 1250 |
+
response = await rpc(
|
| 1251 |
+
request,
|
| 1252 |
+
retry=retry,
|
| 1253 |
+
timeout=timeout,
|
| 1254 |
+
metadata=metadata,
|
| 1255 |
+
)
|
| 1256 |
+
|
| 1257 |
+
# Done; return the response.
|
| 1258 |
+
return response
|
| 1259 |
+
|
| 1260 |
+
async def __aenter__(self) -> "GenerativeServiceAsyncClient":
|
| 1261 |
+
return self
|
| 1262 |
+
|
| 1263 |
+
async def __aexit__(self, exc_type, exc, tb):
|
| 1264 |
+
await self.transport.close()
|
| 1265 |
+
|
| 1266 |
+
|
| 1267 |
+
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
|
| 1268 |
+
gapic_version=package_version.__version__
|
| 1269 |
+
)
|
| 1270 |
+
|
| 1271 |
+
|
| 1272 |
+
__all__ = ("GenerativeServiceAsyncClient",)
|
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/generative_service/client.py
ADDED
|
@@ -0,0 +1,1659 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Copyright 2024 Google LLC
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
#
|
| 16 |
+
from collections import OrderedDict
|
| 17 |
+
import logging as std_logging
|
| 18 |
+
import os
|
| 19 |
+
import re
|
| 20 |
+
from typing import (
|
| 21 |
+
Callable,
|
| 22 |
+
Dict,
|
| 23 |
+
Iterable,
|
| 24 |
+
Mapping,
|
| 25 |
+
MutableMapping,
|
| 26 |
+
MutableSequence,
|
| 27 |
+
Optional,
|
| 28 |
+
Sequence,
|
| 29 |
+
Tuple,
|
| 30 |
+
Type,
|
| 31 |
+
Union,
|
| 32 |
+
cast,
|
| 33 |
+
)
|
| 34 |
+
import warnings
|
| 35 |
+
|
| 36 |
+
from google.api_core import client_options as client_options_lib
|
| 37 |
+
from google.api_core import exceptions as core_exceptions
|
| 38 |
+
from google.api_core import gapic_v1
|
| 39 |
+
from google.api_core import retry as retries
|
| 40 |
+
from google.auth import credentials as ga_credentials # type: ignore
|
| 41 |
+
from google.auth.exceptions import MutualTLSChannelError # type: ignore
|
| 42 |
+
from google.auth.transport import mtls # type: ignore
|
| 43 |
+
from google.auth.transport.grpc import SslCredentials # type: ignore
|
| 44 |
+
from google.oauth2 import service_account # type: ignore
|
| 45 |
+
|
| 46 |
+
from google.ai.generativelanguage_v1beta import gapic_version as package_version
|
| 47 |
+
|
| 48 |
+
try:
|
| 49 |
+
OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None]
|
| 50 |
+
except AttributeError: # pragma: NO COVER
|
| 51 |
+
OptionalRetry = Union[retries.Retry, object, None] # type: ignore
|
| 52 |
+
|
| 53 |
+
try:
|
| 54 |
+
from google.api_core import client_logging # type: ignore
|
| 55 |
+
|
| 56 |
+
CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER
|
| 57 |
+
except ImportError: # pragma: NO COVER
|
| 58 |
+
CLIENT_LOGGING_SUPPORTED = False
|
| 59 |
+
|
| 60 |
+
_LOGGER = std_logging.getLogger(__name__)
|
| 61 |
+
|
| 62 |
+
from google.longrunning import operations_pb2 # type: ignore
|
| 63 |
+
|
| 64 |
+
from google.ai.generativelanguage_v1beta.types import generative_service, safety
|
| 65 |
+
from google.ai.generativelanguage_v1beta.types import content
|
| 66 |
+
from google.ai.generativelanguage_v1beta.types import content as gag_content
|
| 67 |
+
|
| 68 |
+
from .transports.base import DEFAULT_CLIENT_INFO, GenerativeServiceTransport
|
| 69 |
+
from .transports.grpc import GenerativeServiceGrpcTransport
|
| 70 |
+
from .transports.grpc_asyncio import GenerativeServiceGrpcAsyncIOTransport
|
| 71 |
+
from .transports.rest import GenerativeServiceRestTransport
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
class GenerativeServiceClientMeta(type):
|
| 75 |
+
"""Metaclass for the GenerativeService client.
|
| 76 |
+
|
| 77 |
+
This provides class-level methods for building and retrieving
|
| 78 |
+
support objects (e.g. transport) without polluting the client instance
|
| 79 |
+
objects.
|
| 80 |
+
"""
|
| 81 |
+
|
| 82 |
+
_transport_registry = (
|
| 83 |
+
OrderedDict()
|
| 84 |
+
) # type: Dict[str, Type[GenerativeServiceTransport]]
|
| 85 |
+
_transport_registry["grpc"] = GenerativeServiceGrpcTransport
|
| 86 |
+
_transport_registry["grpc_asyncio"] = GenerativeServiceGrpcAsyncIOTransport
|
| 87 |
+
_transport_registry["rest"] = GenerativeServiceRestTransport
|
| 88 |
+
|
| 89 |
+
def get_transport_class(
|
| 90 |
+
cls,
|
| 91 |
+
label: Optional[str] = None,
|
| 92 |
+
) -> Type[GenerativeServiceTransport]:
|
| 93 |
+
"""Returns an appropriate transport class.
|
| 94 |
+
|
| 95 |
+
Args:
|
| 96 |
+
label: The name of the desired transport. If none is
|
| 97 |
+
provided, then the first transport in the registry is used.
|
| 98 |
+
|
| 99 |
+
Returns:
|
| 100 |
+
The transport class to use.
|
| 101 |
+
"""
|
| 102 |
+
# If a specific transport is requested, return that one.
|
| 103 |
+
if label:
|
| 104 |
+
return cls._transport_registry[label]
|
| 105 |
+
|
| 106 |
+
# No transport is requested; return the default (that is, the first one
|
| 107 |
+
# in the dictionary).
|
| 108 |
+
return next(iter(cls._transport_registry.values()))
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
class GenerativeServiceClient(metaclass=GenerativeServiceClientMeta):
|
| 112 |
+
"""API for using Large Models that generate multimodal content
|
| 113 |
+
and have additional capabilities beyond text generation.
|
| 114 |
+
"""
|
| 115 |
+
|
| 116 |
+
@staticmethod
|
| 117 |
+
def _get_default_mtls_endpoint(api_endpoint):
|
| 118 |
+
"""Converts api endpoint to mTLS endpoint.
|
| 119 |
+
|
| 120 |
+
Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to
|
| 121 |
+
"*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively.
|
| 122 |
+
Args:
|
| 123 |
+
api_endpoint (Optional[str]): the api endpoint to convert.
|
| 124 |
+
Returns:
|
| 125 |
+
str: converted mTLS api endpoint.
|
| 126 |
+
"""
|
| 127 |
+
if not api_endpoint:
|
| 128 |
+
return api_endpoint
|
| 129 |
+
|
| 130 |
+
mtls_endpoint_re = re.compile(
|
| 131 |
+
r"(?P<name>[^.]+)(?P<mtls>\.mtls)?(?P<sandbox>\.sandbox)?(?P<googledomain>\.googleapis\.com)?"
|
| 132 |
+
)
|
| 133 |
+
|
| 134 |
+
m = mtls_endpoint_re.match(api_endpoint)
|
| 135 |
+
name, mtls, sandbox, googledomain = m.groups()
|
| 136 |
+
if mtls or not googledomain:
|
| 137 |
+
return api_endpoint
|
| 138 |
+
|
| 139 |
+
if sandbox:
|
| 140 |
+
return api_endpoint.replace(
|
| 141 |
+
"sandbox.googleapis.com", "mtls.sandbox.googleapis.com"
|
| 142 |
+
)
|
| 143 |
+
|
| 144 |
+
return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com")
|
| 145 |
+
|
| 146 |
+
# Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead.
|
| 147 |
+
DEFAULT_ENDPOINT = "generativelanguage.googleapis.com"
|
| 148 |
+
DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore
|
| 149 |
+
DEFAULT_ENDPOINT
|
| 150 |
+
)
|
| 151 |
+
|
| 152 |
+
_DEFAULT_ENDPOINT_TEMPLATE = "generativelanguage.{UNIVERSE_DOMAIN}"
|
| 153 |
+
_DEFAULT_UNIVERSE = "googleapis.com"
|
| 154 |
+
|
| 155 |
+
@classmethod
|
| 156 |
+
def from_service_account_info(cls, info: dict, *args, **kwargs):
|
| 157 |
+
"""Creates an instance of this client using the provided credentials
|
| 158 |
+
info.
|
| 159 |
+
|
| 160 |
+
Args:
|
| 161 |
+
info (dict): The service account private key info.
|
| 162 |
+
args: Additional arguments to pass to the constructor.
|
| 163 |
+
kwargs: Additional arguments to pass to the constructor.
|
| 164 |
+
|
| 165 |
+
Returns:
|
| 166 |
+
GenerativeServiceClient: The constructed client.
|
| 167 |
+
"""
|
| 168 |
+
credentials = service_account.Credentials.from_service_account_info(info)
|
| 169 |
+
kwargs["credentials"] = credentials
|
| 170 |
+
return cls(*args, **kwargs)
|
| 171 |
+
|
| 172 |
+
@classmethod
|
| 173 |
+
def from_service_account_file(cls, filename: str, *args, **kwargs):
|
| 174 |
+
"""Creates an instance of this client using the provided credentials
|
| 175 |
+
file.
|
| 176 |
+
|
| 177 |
+
Args:
|
| 178 |
+
filename (str): The path to the service account private key json
|
| 179 |
+
file.
|
| 180 |
+
args: Additional arguments to pass to the constructor.
|
| 181 |
+
kwargs: Additional arguments to pass to the constructor.
|
| 182 |
+
|
| 183 |
+
Returns:
|
| 184 |
+
GenerativeServiceClient: The constructed client.
|
| 185 |
+
"""
|
| 186 |
+
credentials = service_account.Credentials.from_service_account_file(filename)
|
| 187 |
+
kwargs["credentials"] = credentials
|
| 188 |
+
return cls(*args, **kwargs)
|
| 189 |
+
|
| 190 |
+
from_service_account_json = from_service_account_file
|
| 191 |
+
|
| 192 |
+
@property
|
| 193 |
+
def transport(self) -> GenerativeServiceTransport:
|
| 194 |
+
"""Returns the transport used by the client instance.
|
| 195 |
+
|
| 196 |
+
Returns:
|
| 197 |
+
GenerativeServiceTransport: The transport used by the client
|
| 198 |
+
instance.
|
| 199 |
+
"""
|
| 200 |
+
return self._transport
|
| 201 |
+
|
| 202 |
+
@staticmethod
|
| 203 |
+
def cached_content_path(
|
| 204 |
+
id: str,
|
| 205 |
+
) -> str:
|
| 206 |
+
"""Returns a fully-qualified cached_content string."""
|
| 207 |
+
return "cachedContents/{id}".format(
|
| 208 |
+
id=id,
|
| 209 |
+
)
|
| 210 |
+
|
| 211 |
+
@staticmethod
|
| 212 |
+
def parse_cached_content_path(path: str) -> Dict[str, str]:
|
| 213 |
+
"""Parses a cached_content path into its component segments."""
|
| 214 |
+
m = re.match(r"^cachedContents/(?P<id>.+?)$", path)
|
| 215 |
+
return m.groupdict() if m else {}
|
| 216 |
+
|
| 217 |
+
@staticmethod
|
| 218 |
+
def model_path(
|
| 219 |
+
model: str,
|
| 220 |
+
) -> str:
|
| 221 |
+
"""Returns a fully-qualified model string."""
|
| 222 |
+
return "models/{model}".format(
|
| 223 |
+
model=model,
|
| 224 |
+
)
|
| 225 |
+
|
| 226 |
+
@staticmethod
|
| 227 |
+
def parse_model_path(path: str) -> Dict[str, str]:
|
| 228 |
+
"""Parses a model path into its component segments."""
|
| 229 |
+
m = re.match(r"^models/(?P<model>.+?)$", path)
|
| 230 |
+
return m.groupdict() if m else {}
|
| 231 |
+
|
| 232 |
+
@staticmethod
|
| 233 |
+
def common_billing_account_path(
|
| 234 |
+
billing_account: str,
|
| 235 |
+
) -> str:
|
| 236 |
+
"""Returns a fully-qualified billing_account string."""
|
| 237 |
+
return "billingAccounts/{billing_account}".format(
|
| 238 |
+
billing_account=billing_account,
|
| 239 |
+
)
|
| 240 |
+
|
| 241 |
+
@staticmethod
|
| 242 |
+
def parse_common_billing_account_path(path: str) -> Dict[str, str]:
|
| 243 |
+
"""Parse a billing_account path into its component segments."""
|
| 244 |
+
m = re.match(r"^billingAccounts/(?P<billing_account>.+?)$", path)
|
| 245 |
+
return m.groupdict() if m else {}
|
| 246 |
+
|
| 247 |
+
@staticmethod
|
| 248 |
+
def common_folder_path(
|
| 249 |
+
folder: str,
|
| 250 |
+
) -> str:
|
| 251 |
+
"""Returns a fully-qualified folder string."""
|
| 252 |
+
return "folders/{folder}".format(
|
| 253 |
+
folder=folder,
|
| 254 |
+
)
|
| 255 |
+
|
| 256 |
+
@staticmethod
|
| 257 |
+
def parse_common_folder_path(path: str) -> Dict[str, str]:
|
| 258 |
+
"""Parse a folder path into its component segments."""
|
| 259 |
+
m = re.match(r"^folders/(?P<folder>.+?)$", path)
|
| 260 |
+
return m.groupdict() if m else {}
|
| 261 |
+
|
| 262 |
+
@staticmethod
|
| 263 |
+
def common_organization_path(
|
| 264 |
+
organization: str,
|
| 265 |
+
) -> str:
|
| 266 |
+
"""Returns a fully-qualified organization string."""
|
| 267 |
+
return "organizations/{organization}".format(
|
| 268 |
+
organization=organization,
|
| 269 |
+
)
|
| 270 |
+
|
| 271 |
+
@staticmethod
|
| 272 |
+
def parse_common_organization_path(path: str) -> Dict[str, str]:
|
| 273 |
+
"""Parse a organization path into its component segments."""
|
| 274 |
+
m = re.match(r"^organizations/(?P<organization>.+?)$", path)
|
| 275 |
+
return m.groupdict() if m else {}
|
| 276 |
+
|
| 277 |
+
@staticmethod
|
| 278 |
+
def common_project_path(
|
| 279 |
+
project: str,
|
| 280 |
+
) -> str:
|
| 281 |
+
"""Returns a fully-qualified project string."""
|
| 282 |
+
return "projects/{project}".format(
|
| 283 |
+
project=project,
|
| 284 |
+
)
|
| 285 |
+
|
| 286 |
+
@staticmethod
|
| 287 |
+
def parse_common_project_path(path: str) -> Dict[str, str]:
|
| 288 |
+
"""Parse a project path into its component segments."""
|
| 289 |
+
m = re.match(r"^projects/(?P<project>.+?)$", path)
|
| 290 |
+
return m.groupdict() if m else {}
|
| 291 |
+
|
| 292 |
+
@staticmethod
|
| 293 |
+
def common_location_path(
|
| 294 |
+
project: str,
|
| 295 |
+
location: str,
|
| 296 |
+
) -> str:
|
| 297 |
+
"""Returns a fully-qualified location string."""
|
| 298 |
+
return "projects/{project}/locations/{location}".format(
|
| 299 |
+
project=project,
|
| 300 |
+
location=location,
|
| 301 |
+
)
|
| 302 |
+
|
| 303 |
+
@staticmethod
|
| 304 |
+
def parse_common_location_path(path: str) -> Dict[str, str]:
|
| 305 |
+
"""Parse a location path into its component segments."""
|
| 306 |
+
m = re.match(r"^projects/(?P<project>.+?)/locations/(?P<location>.+?)$", path)
|
| 307 |
+
return m.groupdict() if m else {}
|
| 308 |
+
|
| 309 |
+
@classmethod
|
| 310 |
+
def get_mtls_endpoint_and_cert_source(
|
| 311 |
+
cls, client_options: Optional[client_options_lib.ClientOptions] = None
|
| 312 |
+
):
|
| 313 |
+
"""Deprecated. Return the API endpoint and client cert source for mutual TLS.
|
| 314 |
+
|
| 315 |
+
The client cert source is determined in the following order:
|
| 316 |
+
(1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the
|
| 317 |
+
client cert source is None.
|
| 318 |
+
(2) if `client_options.client_cert_source` is provided, use the provided one; if the
|
| 319 |
+
default client cert source exists, use the default one; otherwise the client cert
|
| 320 |
+
source is None.
|
| 321 |
+
|
| 322 |
+
The API endpoint is determined in the following order:
|
| 323 |
+
(1) if `client_options.api_endpoint` if provided, use the provided one.
|
| 324 |
+
(2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the
|
| 325 |
+
default mTLS endpoint; if the environment variable is "never", use the default API
|
| 326 |
+
endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise
|
| 327 |
+
use the default API endpoint.
|
| 328 |
+
|
| 329 |
+
More details can be found at https://google.aip.dev/auth/4114.
|
| 330 |
+
|
| 331 |
+
Args:
|
| 332 |
+
client_options (google.api_core.client_options.ClientOptions): Custom options for the
|
| 333 |
+
client. Only the `api_endpoint` and `client_cert_source` properties may be used
|
| 334 |
+
in this method.
|
| 335 |
+
|
| 336 |
+
Returns:
|
| 337 |
+
Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the
|
| 338 |
+
client cert source to use.
|
| 339 |
+
|
| 340 |
+
Raises:
|
| 341 |
+
google.auth.exceptions.MutualTLSChannelError: If any errors happen.
|
| 342 |
+
"""
|
| 343 |
+
|
| 344 |
+
warnings.warn(
|
| 345 |
+
"get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.",
|
| 346 |
+
DeprecationWarning,
|
| 347 |
+
)
|
| 348 |
+
if client_options is None:
|
| 349 |
+
client_options = client_options_lib.ClientOptions()
|
| 350 |
+
use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false")
|
| 351 |
+
use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto")
|
| 352 |
+
if use_client_cert not in ("true", "false"):
|
| 353 |
+
raise ValueError(
|
| 354 |
+
"Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`"
|
| 355 |
+
)
|
| 356 |
+
if use_mtls_endpoint not in ("auto", "never", "always"):
|
| 357 |
+
raise MutualTLSChannelError(
|
| 358 |
+
"Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`"
|
| 359 |
+
)
|
| 360 |
+
|
| 361 |
+
# Figure out the client cert source to use.
|
| 362 |
+
client_cert_source = None
|
| 363 |
+
if use_client_cert == "true":
|
| 364 |
+
if client_options.client_cert_source:
|
| 365 |
+
client_cert_source = client_options.client_cert_source
|
| 366 |
+
elif mtls.has_default_client_cert_source():
|
| 367 |
+
client_cert_source = mtls.default_client_cert_source()
|
| 368 |
+
|
| 369 |
+
# Figure out which api endpoint to use.
|
| 370 |
+
if client_options.api_endpoint is not None:
|
| 371 |
+
api_endpoint = client_options.api_endpoint
|
| 372 |
+
elif use_mtls_endpoint == "always" or (
|
| 373 |
+
use_mtls_endpoint == "auto" and client_cert_source
|
| 374 |
+
):
|
| 375 |
+
api_endpoint = cls.DEFAULT_MTLS_ENDPOINT
|
| 376 |
+
else:
|
| 377 |
+
api_endpoint = cls.DEFAULT_ENDPOINT
|
| 378 |
+
|
| 379 |
+
return api_endpoint, client_cert_source
|
| 380 |
+
|
| 381 |
+
@staticmethod
|
| 382 |
+
def _read_environment_variables():
|
| 383 |
+
"""Returns the environment variables used by the client.
|
| 384 |
+
|
| 385 |
+
Returns:
|
| 386 |
+
Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE,
|
| 387 |
+
GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables.
|
| 388 |
+
|
| 389 |
+
Raises:
|
| 390 |
+
ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not
|
| 391 |
+
any of ["true", "false"].
|
| 392 |
+
google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT
|
| 393 |
+
is not any of ["auto", "never", "always"].
|
| 394 |
+
"""
|
| 395 |
+
use_client_cert = os.getenv(
|
| 396 |
+
"GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"
|
| 397 |
+
).lower()
|
| 398 |
+
use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower()
|
| 399 |
+
universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN")
|
| 400 |
+
if use_client_cert not in ("true", "false"):
|
| 401 |
+
raise ValueError(
|
| 402 |
+
"Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`"
|
| 403 |
+
)
|
| 404 |
+
if use_mtls_endpoint not in ("auto", "never", "always"):
|
| 405 |
+
raise MutualTLSChannelError(
|
| 406 |
+
"Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`"
|
| 407 |
+
)
|
| 408 |
+
return use_client_cert == "true", use_mtls_endpoint, universe_domain_env
|
| 409 |
+
|
| 410 |
+
@staticmethod
|
| 411 |
+
def _get_client_cert_source(provided_cert_source, use_cert_flag):
|
| 412 |
+
"""Return the client cert source to be used by the client.
|
| 413 |
+
|
| 414 |
+
Args:
|
| 415 |
+
provided_cert_source (bytes): The client certificate source provided.
|
| 416 |
+
use_cert_flag (bool): A flag indicating whether to use the client certificate.
|
| 417 |
+
|
| 418 |
+
Returns:
|
| 419 |
+
bytes or None: The client cert source to be used by the client.
|
| 420 |
+
"""
|
| 421 |
+
client_cert_source = None
|
| 422 |
+
if use_cert_flag:
|
| 423 |
+
if provided_cert_source:
|
| 424 |
+
client_cert_source = provided_cert_source
|
| 425 |
+
elif mtls.has_default_client_cert_source():
|
| 426 |
+
client_cert_source = mtls.default_client_cert_source()
|
| 427 |
+
return client_cert_source
|
| 428 |
+
|
| 429 |
+
@staticmethod
|
| 430 |
+
def _get_api_endpoint(
|
| 431 |
+
api_override, client_cert_source, universe_domain, use_mtls_endpoint
|
| 432 |
+
):
|
| 433 |
+
"""Return the API endpoint used by the client.
|
| 434 |
+
|
| 435 |
+
Args:
|
| 436 |
+
api_override (str): The API endpoint override. If specified, this is always
|
| 437 |
+
the return value of this function and the other arguments are not used.
|
| 438 |
+
client_cert_source (bytes): The client certificate source used by the client.
|
| 439 |
+
universe_domain (str): The universe domain used by the client.
|
| 440 |
+
use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters.
|
| 441 |
+
Possible values are "always", "auto", or "never".
|
| 442 |
+
|
| 443 |
+
Returns:
|
| 444 |
+
str: The API endpoint to be used by the client.
|
| 445 |
+
"""
|
| 446 |
+
if api_override is not None:
|
| 447 |
+
api_endpoint = api_override
|
| 448 |
+
elif use_mtls_endpoint == "always" or (
|
| 449 |
+
use_mtls_endpoint == "auto" and client_cert_source
|
| 450 |
+
):
|
| 451 |
+
_default_universe = GenerativeServiceClient._DEFAULT_UNIVERSE
|
| 452 |
+
if universe_domain != _default_universe:
|
| 453 |
+
raise MutualTLSChannelError(
|
| 454 |
+
f"mTLS is not supported in any universe other than {_default_universe}."
|
| 455 |
+
)
|
| 456 |
+
api_endpoint = GenerativeServiceClient.DEFAULT_MTLS_ENDPOINT
|
| 457 |
+
else:
|
| 458 |
+
api_endpoint = GenerativeServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(
|
| 459 |
+
UNIVERSE_DOMAIN=universe_domain
|
| 460 |
+
)
|
| 461 |
+
return api_endpoint
|
| 462 |
+
|
| 463 |
+
@staticmethod
|
| 464 |
+
def _get_universe_domain(
|
| 465 |
+
client_universe_domain: Optional[str], universe_domain_env: Optional[str]
|
| 466 |
+
) -> str:
|
| 467 |
+
"""Return the universe domain used by the client.
|
| 468 |
+
|
| 469 |
+
Args:
|
| 470 |
+
client_universe_domain (Optional[str]): The universe domain configured via the client options.
|
| 471 |
+
universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable.
|
| 472 |
+
|
| 473 |
+
Returns:
|
| 474 |
+
str: The universe domain to be used by the client.
|
| 475 |
+
|
| 476 |
+
Raises:
|
| 477 |
+
ValueError: If the universe domain is an empty string.
|
| 478 |
+
"""
|
| 479 |
+
universe_domain = GenerativeServiceClient._DEFAULT_UNIVERSE
|
| 480 |
+
if client_universe_domain is not None:
|
| 481 |
+
universe_domain = client_universe_domain
|
| 482 |
+
elif universe_domain_env is not None:
|
| 483 |
+
universe_domain = universe_domain_env
|
| 484 |
+
if len(universe_domain.strip()) == 0:
|
| 485 |
+
raise ValueError("Universe Domain cannot be an empty string.")
|
| 486 |
+
return universe_domain
|
| 487 |
+
|
| 488 |
+
def _validate_universe_domain(self):
|
| 489 |
+
"""Validates client's and credentials' universe domains are consistent.
|
| 490 |
+
|
| 491 |
+
Returns:
|
| 492 |
+
bool: True iff the configured universe domain is valid.
|
| 493 |
+
|
| 494 |
+
Raises:
|
| 495 |
+
ValueError: If the configured universe domain is not valid.
|
| 496 |
+
"""
|
| 497 |
+
|
| 498 |
+
# NOTE (b/349488459): universe validation is disabled until further notice.
|
| 499 |
+
return True
|
| 500 |
+
|
| 501 |
+
@property
|
| 502 |
+
def api_endpoint(self):
|
| 503 |
+
"""Return the API endpoint used by the client instance.
|
| 504 |
+
|
| 505 |
+
Returns:
|
| 506 |
+
str: The API endpoint used by the client instance.
|
| 507 |
+
"""
|
| 508 |
+
return self._api_endpoint
|
| 509 |
+
|
| 510 |
+
@property
|
| 511 |
+
def universe_domain(self) -> str:
|
| 512 |
+
"""Return the universe domain used by the client instance.
|
| 513 |
+
|
| 514 |
+
Returns:
|
| 515 |
+
str: The universe domain used by the client instance.
|
| 516 |
+
"""
|
| 517 |
+
return self._universe_domain
|
| 518 |
+
|
| 519 |
+
def __init__(
|
| 520 |
+
self,
|
| 521 |
+
*,
|
| 522 |
+
credentials: Optional[ga_credentials.Credentials] = None,
|
| 523 |
+
transport: Optional[
|
| 524 |
+
Union[
|
| 525 |
+
str,
|
| 526 |
+
GenerativeServiceTransport,
|
| 527 |
+
Callable[..., GenerativeServiceTransport],
|
| 528 |
+
]
|
| 529 |
+
] = None,
|
| 530 |
+
client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None,
|
| 531 |
+
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
|
| 532 |
+
) -> None:
|
| 533 |
+
"""Instantiates the generative service client.
|
| 534 |
+
|
| 535 |
+
Args:
|
| 536 |
+
credentials (Optional[google.auth.credentials.Credentials]): The
|
| 537 |
+
authorization credentials to attach to requests. These
|
| 538 |
+
credentials identify the application to the service; if none
|
| 539 |
+
are specified, the client will attempt to ascertain the
|
| 540 |
+
credentials from the environment.
|
| 541 |
+
transport (Optional[Union[str,GenerativeServiceTransport,Callable[..., GenerativeServiceTransport]]]):
|
| 542 |
+
The transport to use, or a Callable that constructs and returns a new transport.
|
| 543 |
+
If a Callable is given, it will be called with the same set of initialization
|
| 544 |
+
arguments as used in the GenerativeServiceTransport constructor.
|
| 545 |
+
If set to None, a transport is chosen automatically.
|
| 546 |
+
client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]):
|
| 547 |
+
Custom options for the client.
|
| 548 |
+
|
| 549 |
+
1. The ``api_endpoint`` property can be used to override the
|
| 550 |
+
default endpoint provided by the client when ``transport`` is
|
| 551 |
+
not explicitly provided. Only if this property is not set and
|
| 552 |
+
``transport`` was not explicitly provided, the endpoint is
|
| 553 |
+
determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment
|
| 554 |
+
variable, which have one of the following values:
|
| 555 |
+
"always" (always use the default mTLS endpoint), "never" (always
|
| 556 |
+
use the default regular endpoint) and "auto" (auto-switch to the
|
| 557 |
+
default mTLS endpoint if client certificate is present; this is
|
| 558 |
+
the default value).
|
| 559 |
+
|
| 560 |
+
2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable
|
| 561 |
+
is "true", then the ``client_cert_source`` property can be used
|
| 562 |
+
to provide a client certificate for mTLS transport. If
|
| 563 |
+
not provided, the default SSL client certificate will be used if
|
| 564 |
+
present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not
|
| 565 |
+
set, no client certificate will be used.
|
| 566 |
+
|
| 567 |
+
3. The ``universe_domain`` property can be used to override the
|
| 568 |
+
default "googleapis.com" universe. Note that the ``api_endpoint``
|
| 569 |
+
property still takes precedence; and ``universe_domain`` is
|
| 570 |
+
currently not supported for mTLS.
|
| 571 |
+
|
| 572 |
+
client_info (google.api_core.gapic_v1.client_info.ClientInfo):
|
| 573 |
+
The client info used to send a user-agent string along with
|
| 574 |
+
API requests. If ``None``, then default info will be used.
|
| 575 |
+
Generally, you only need to set this if you're developing
|
| 576 |
+
your own client library.
|
| 577 |
+
|
| 578 |
+
Raises:
|
| 579 |
+
google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
|
| 580 |
+
creation failed for any reason.
|
| 581 |
+
"""
|
| 582 |
+
self._client_options = client_options
|
| 583 |
+
if isinstance(self._client_options, dict):
|
| 584 |
+
self._client_options = client_options_lib.from_dict(self._client_options)
|
| 585 |
+
if self._client_options is None:
|
| 586 |
+
self._client_options = client_options_lib.ClientOptions()
|
| 587 |
+
self._client_options = cast(
|
| 588 |
+
client_options_lib.ClientOptions, self._client_options
|
| 589 |
+
)
|
| 590 |
+
|
| 591 |
+
universe_domain_opt = getattr(self._client_options, "universe_domain", None)
|
| 592 |
+
|
| 593 |
+
(
|
| 594 |
+
self._use_client_cert,
|
| 595 |
+
self._use_mtls_endpoint,
|
| 596 |
+
self._universe_domain_env,
|
| 597 |
+
) = GenerativeServiceClient._read_environment_variables()
|
| 598 |
+
self._client_cert_source = GenerativeServiceClient._get_client_cert_source(
|
| 599 |
+
self._client_options.client_cert_source, self._use_client_cert
|
| 600 |
+
)
|
| 601 |
+
self._universe_domain = GenerativeServiceClient._get_universe_domain(
|
| 602 |
+
universe_domain_opt, self._universe_domain_env
|
| 603 |
+
)
|
| 604 |
+
self._api_endpoint = None # updated below, depending on `transport`
|
| 605 |
+
|
| 606 |
+
# Initialize the universe domain validation.
|
| 607 |
+
self._is_universe_domain_valid = False
|
| 608 |
+
|
| 609 |
+
if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER
|
| 610 |
+
# Setup logging.
|
| 611 |
+
client_logging.initialize_logging()
|
| 612 |
+
|
| 613 |
+
api_key_value = getattr(self._client_options, "api_key", None)
|
| 614 |
+
if api_key_value and credentials:
|
| 615 |
+
raise ValueError(
|
| 616 |
+
"client_options.api_key and credentials are mutually exclusive"
|
| 617 |
+
)
|
| 618 |
+
|
| 619 |
+
# Save or instantiate the transport.
|
| 620 |
+
# Ordinarily, we provide the transport, but allowing a custom transport
|
| 621 |
+
# instance provides an extensibility point for unusual situations.
|
| 622 |
+
transport_provided = isinstance(transport, GenerativeServiceTransport)
|
| 623 |
+
if transport_provided:
|
| 624 |
+
# transport is a GenerativeServiceTransport instance.
|
| 625 |
+
if credentials or self._client_options.credentials_file or api_key_value:
|
| 626 |
+
raise ValueError(
|
| 627 |
+
"When providing a transport instance, "
|
| 628 |
+
"provide its credentials directly."
|
| 629 |
+
)
|
| 630 |
+
if self._client_options.scopes:
|
| 631 |
+
raise ValueError(
|
| 632 |
+
"When providing a transport instance, provide its scopes "
|
| 633 |
+
"directly."
|
| 634 |
+
)
|
| 635 |
+
self._transport = cast(GenerativeServiceTransport, transport)
|
| 636 |
+
self._api_endpoint = self._transport.host
|
| 637 |
+
|
| 638 |
+
self._api_endpoint = (
|
| 639 |
+
self._api_endpoint
|
| 640 |
+
or GenerativeServiceClient._get_api_endpoint(
|
| 641 |
+
self._client_options.api_endpoint,
|
| 642 |
+
self._client_cert_source,
|
| 643 |
+
self._universe_domain,
|
| 644 |
+
self._use_mtls_endpoint,
|
| 645 |
+
)
|
| 646 |
+
)
|
| 647 |
+
|
| 648 |
+
if not transport_provided:
|
| 649 |
+
import google.auth._default # type: ignore
|
| 650 |
+
|
| 651 |
+
if api_key_value and hasattr(
|
| 652 |
+
google.auth._default, "get_api_key_credentials"
|
| 653 |
+
):
|
| 654 |
+
credentials = google.auth._default.get_api_key_credentials(
|
| 655 |
+
api_key_value
|
| 656 |
+
)
|
| 657 |
+
|
| 658 |
+
transport_init: Union[
|
| 659 |
+
Type[GenerativeServiceTransport],
|
| 660 |
+
Callable[..., GenerativeServiceTransport],
|
| 661 |
+
] = (
|
| 662 |
+
GenerativeServiceClient.get_transport_class(transport)
|
| 663 |
+
if isinstance(transport, str) or transport is None
|
| 664 |
+
else cast(Callable[..., GenerativeServiceTransport], transport)
|
| 665 |
+
)
|
| 666 |
+
# initialize with the provided callable or the passed in class
|
| 667 |
+
self._transport = transport_init(
|
| 668 |
+
credentials=credentials,
|
| 669 |
+
credentials_file=self._client_options.credentials_file,
|
| 670 |
+
host=self._api_endpoint,
|
| 671 |
+
scopes=self._client_options.scopes,
|
| 672 |
+
client_cert_source_for_mtls=self._client_cert_source,
|
| 673 |
+
quota_project_id=self._client_options.quota_project_id,
|
| 674 |
+
client_info=client_info,
|
| 675 |
+
always_use_jwt_access=True,
|
| 676 |
+
api_audience=self._client_options.api_audience,
|
| 677 |
+
)
|
| 678 |
+
|
| 679 |
+
if "async" not in str(self._transport):
|
| 680 |
+
if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
|
| 681 |
+
std_logging.DEBUG
|
| 682 |
+
): # pragma: NO COVER
|
| 683 |
+
_LOGGER.debug(
|
| 684 |
+
"Created client `google.ai.generativelanguage_v1beta.GenerativeServiceClient`.",
|
| 685 |
+
extra={
|
| 686 |
+
"serviceName": "google.ai.generativelanguage.v1beta.GenerativeService",
|
| 687 |
+
"universeDomain": getattr(
|
| 688 |
+
self._transport._credentials, "universe_domain", ""
|
| 689 |
+
),
|
| 690 |
+
"credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}",
|
| 691 |
+
"credentialsInfo": getattr(
|
| 692 |
+
self.transport._credentials, "get_cred_info", lambda: None
|
| 693 |
+
)(),
|
| 694 |
+
}
|
| 695 |
+
if hasattr(self._transport, "_credentials")
|
| 696 |
+
else {
|
| 697 |
+
"serviceName": "google.ai.generativelanguage.v1beta.GenerativeService",
|
| 698 |
+
"credentialsType": None,
|
| 699 |
+
},
|
| 700 |
+
)
|
| 701 |
+
|
| 702 |
+
def generate_content(
|
| 703 |
+
self,
|
| 704 |
+
request: Optional[
|
| 705 |
+
Union[generative_service.GenerateContentRequest, dict]
|
| 706 |
+
] = None,
|
| 707 |
+
*,
|
| 708 |
+
model: Optional[str] = None,
|
| 709 |
+
contents: Optional[MutableSequence[content.Content]] = None,
|
| 710 |
+
retry: OptionalRetry = gapic_v1.method.DEFAULT,
|
| 711 |
+
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
|
| 712 |
+
metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
|
| 713 |
+
) -> generative_service.GenerateContentResponse:
|
| 714 |
+
r"""Generates a model response given an input
|
| 715 |
+
``GenerateContentRequest``. Refer to the `text generation
|
| 716 |
+
guide <https://ai.google.dev/gemini-api/docs/text-generation>`__
|
| 717 |
+
for detailed usage information. Input capabilities differ
|
| 718 |
+
between models, including tuned models. Refer to the `model
|
| 719 |
+
guide <https://ai.google.dev/gemini-api/docs/models/gemini>`__
|
| 720 |
+
and `tuning
|
| 721 |
+
guide <https://ai.google.dev/gemini-api/docs/model-tuning>`__
|
| 722 |
+
for details.
|
| 723 |
+
|
| 724 |
+
.. code-block:: python
|
| 725 |
+
|
| 726 |
+
# This snippet has been automatically generated and should be regarded as a
|
| 727 |
+
# code template only.
|
| 728 |
+
# It will require modifications to work:
|
| 729 |
+
# - It may require correct/in-range values for request initialization.
|
| 730 |
+
# - It may require specifying regional endpoints when creating the service
|
| 731 |
+
# client as shown in:
|
| 732 |
+
# https://googleapis.dev/python/google-api-core/latest/client_options.html
|
| 733 |
+
from google.ai import generativelanguage_v1beta
|
| 734 |
+
|
| 735 |
+
def sample_generate_content():
|
| 736 |
+
# Create a client
|
| 737 |
+
client = generativelanguage_v1beta.GenerativeServiceClient()
|
| 738 |
+
|
| 739 |
+
# Initialize request argument(s)
|
| 740 |
+
request = generativelanguage_v1beta.GenerateContentRequest(
|
| 741 |
+
model="model_value",
|
| 742 |
+
)
|
| 743 |
+
|
| 744 |
+
# Make the request
|
| 745 |
+
response = client.generate_content(request=request)
|
| 746 |
+
|
| 747 |
+
# Handle the response
|
| 748 |
+
print(response)
|
| 749 |
+
|
| 750 |
+
Args:
|
| 751 |
+
request (Union[google.ai.generativelanguage_v1beta.types.GenerateContentRequest, dict]):
|
| 752 |
+
The request object. Request to generate a completion from
|
| 753 |
+
the model.
|
| 754 |
+
model (str):
|
| 755 |
+
Required. The name of the ``Model`` to use for
|
| 756 |
+
generating the completion.
|
| 757 |
+
|
| 758 |
+
Format: ``models/{model}``.
|
| 759 |
+
|
| 760 |
+
This corresponds to the ``model`` field
|
| 761 |
+
on the ``request`` instance; if ``request`` is provided, this
|
| 762 |
+
should not be set.
|
| 763 |
+
contents (MutableSequence[google.ai.generativelanguage_v1beta.types.Content]):
|
| 764 |
+
Required. The content of the current conversation with
|
| 765 |
+
the model.
|
| 766 |
+
|
| 767 |
+
For single-turn queries, this is a single instance. For
|
| 768 |
+
multi-turn queries like
|
| 769 |
+
`chat <https://ai.google.dev/gemini-api/docs/text-generation#chat>`__,
|
| 770 |
+
this is a repeated field that contains the conversation
|
| 771 |
+
history and the latest request.
|
| 772 |
+
|
| 773 |
+
This corresponds to the ``contents`` field
|
| 774 |
+
on the ``request`` instance; if ``request`` is provided, this
|
| 775 |
+
should not be set.
|
| 776 |
+
retry (google.api_core.retry.Retry): Designation of what errors, if any,
|
| 777 |
+
should be retried.
|
| 778 |
+
timeout (float): The timeout for this request.
|
| 779 |
+
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
|
| 780 |
+
sent along with the request as metadata. Normally, each value must be of type `str`,
|
| 781 |
+
but for metadata keys ending with the suffix `-bin`, the corresponding values must
|
| 782 |
+
be of type `bytes`.
|
| 783 |
+
|
| 784 |
+
Returns:
|
| 785 |
+
google.ai.generativelanguage_v1beta.types.GenerateContentResponse:
|
| 786 |
+
Response from the model supporting multiple candidate
|
| 787 |
+
responses.
|
| 788 |
+
|
| 789 |
+
Safety ratings and content filtering are reported for
|
| 790 |
+
both prompt in
|
| 791 |
+
GenerateContentResponse.prompt_feedback and for each
|
| 792 |
+
candidate in finish_reason and in safety_ratings. The
|
| 793 |
+
API: - Returns either all requested candidates or
|
| 794 |
+
none of them - Returns no candidates at all only if
|
| 795 |
+
there was something wrong with the prompt (check
|
| 796 |
+
prompt_feedback) - Reports feedback on each candidate
|
| 797 |
+
in finish_reason and safety_ratings.
|
| 798 |
+
|
| 799 |
+
"""
|
| 800 |
+
# Create or coerce a protobuf request object.
|
| 801 |
+
# - Quick check: If we got a request object, we should *not* have
|
| 802 |
+
# gotten any keyword arguments that map to the request.
|
| 803 |
+
has_flattened_params = any([model, contents])
|
| 804 |
+
if request is not None and has_flattened_params:
|
| 805 |
+
raise ValueError(
|
| 806 |
+
"If the `request` argument is set, then none of "
|
| 807 |
+
"the individual field arguments should be set."
|
| 808 |
+
)
|
| 809 |
+
|
| 810 |
+
# - Use the request object if provided (there's no risk of modifying the input as
|
| 811 |
+
# there are no flattened fields), or create one.
|
| 812 |
+
if not isinstance(request, generative_service.GenerateContentRequest):
|
| 813 |
+
request = generative_service.GenerateContentRequest(request)
|
| 814 |
+
# If we have keyword arguments corresponding to fields on the
|
| 815 |
+
# request, apply these.
|
| 816 |
+
if model is not None:
|
| 817 |
+
request.model = model
|
| 818 |
+
if contents is not None:
|
| 819 |
+
request.contents = contents
|
| 820 |
+
|
| 821 |
+
# Wrap the RPC method; this adds retry and timeout information,
|
| 822 |
+
# and friendly error handling.
|
| 823 |
+
rpc = self._transport._wrapped_methods[self._transport.generate_content]
|
| 824 |
+
|
| 825 |
+
# Certain fields should be provided within the metadata header;
|
| 826 |
+
# add these here.
|
| 827 |
+
metadata = tuple(metadata) + (
|
| 828 |
+
gapic_v1.routing_header.to_grpc_metadata((("model", request.model),)),
|
| 829 |
+
)
|
| 830 |
+
|
| 831 |
+
# Validate the universe domain.
|
| 832 |
+
self._validate_universe_domain()
|
| 833 |
+
|
| 834 |
+
# Send the request.
|
| 835 |
+
response = rpc(
|
| 836 |
+
request,
|
| 837 |
+
retry=retry,
|
| 838 |
+
timeout=timeout,
|
| 839 |
+
metadata=metadata,
|
| 840 |
+
)
|
| 841 |
+
|
| 842 |
+
# Done; return the response.
|
| 843 |
+
return response
|
| 844 |
+
|
| 845 |
+
def generate_answer(
|
| 846 |
+
self,
|
| 847 |
+
request: Optional[Union[generative_service.GenerateAnswerRequest, dict]] = None,
|
| 848 |
+
*,
|
| 849 |
+
model: Optional[str] = None,
|
| 850 |
+
contents: Optional[MutableSequence[content.Content]] = None,
|
| 851 |
+
safety_settings: Optional[MutableSequence[safety.SafetySetting]] = None,
|
| 852 |
+
answer_style: Optional[
|
| 853 |
+
generative_service.GenerateAnswerRequest.AnswerStyle
|
| 854 |
+
] = None,
|
| 855 |
+
retry: OptionalRetry = gapic_v1.method.DEFAULT,
|
| 856 |
+
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
|
| 857 |
+
metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
|
| 858 |
+
) -> generative_service.GenerateAnswerResponse:
|
| 859 |
+
r"""Generates a grounded answer from the model given an input
|
| 860 |
+
``GenerateAnswerRequest``.
|
| 861 |
+
|
| 862 |
+
.. code-block:: python
|
| 863 |
+
|
| 864 |
+
# This snippet has been automatically generated and should be regarded as a
|
| 865 |
+
# code template only.
|
| 866 |
+
# It will require modifications to work:
|
| 867 |
+
# - It may require correct/in-range values for request initialization.
|
| 868 |
+
# - It may require specifying regional endpoints when creating the service
|
| 869 |
+
# client as shown in:
|
| 870 |
+
# https://googleapis.dev/python/google-api-core/latest/client_options.html
|
| 871 |
+
from google.ai import generativelanguage_v1beta
|
| 872 |
+
|
| 873 |
+
def sample_generate_answer():
|
| 874 |
+
# Create a client
|
| 875 |
+
client = generativelanguage_v1beta.GenerativeServiceClient()
|
| 876 |
+
|
| 877 |
+
# Initialize request argument(s)
|
| 878 |
+
request = generativelanguage_v1beta.GenerateAnswerRequest(
|
| 879 |
+
model="model_value",
|
| 880 |
+
answer_style="VERBOSE",
|
| 881 |
+
)
|
| 882 |
+
|
| 883 |
+
# Make the request
|
| 884 |
+
response = client.generate_answer(request=request)
|
| 885 |
+
|
| 886 |
+
# Handle the response
|
| 887 |
+
print(response)
|
| 888 |
+
|
| 889 |
+
Args:
|
| 890 |
+
request (Union[google.ai.generativelanguage_v1beta.types.GenerateAnswerRequest, dict]):
|
| 891 |
+
The request object. Request to generate a grounded answer from the
|
| 892 |
+
``Model``.
|
| 893 |
+
model (str):
|
| 894 |
+
Required. The name of the ``Model`` to use for
|
| 895 |
+
generating the grounded response.
|
| 896 |
+
|
| 897 |
+
Format: ``model=models/{model}``.
|
| 898 |
+
|
| 899 |
+
This corresponds to the ``model`` field
|
| 900 |
+
on the ``request`` instance; if ``request`` is provided, this
|
| 901 |
+
should not be set.
|
| 902 |
+
contents (MutableSequence[google.ai.generativelanguage_v1beta.types.Content]):
|
| 903 |
+
Required. The content of the current conversation with
|
| 904 |
+
the ``Model``. For single-turn queries, this is a single
|
| 905 |
+
question to answer. For multi-turn queries, this is a
|
| 906 |
+
repeated field that contains conversation history and
|
| 907 |
+
the last ``Content`` in the list containing the
|
| 908 |
+
question.
|
| 909 |
+
|
| 910 |
+
Note: ``GenerateAnswer`` only supports queries in
|
| 911 |
+
English.
|
| 912 |
+
|
| 913 |
+
This corresponds to the ``contents`` field
|
| 914 |
+
on the ``request`` instance; if ``request`` is provided, this
|
| 915 |
+
should not be set.
|
| 916 |
+
safety_settings (MutableSequence[google.ai.generativelanguage_v1beta.types.SafetySetting]):
|
| 917 |
+
Optional. A list of unique ``SafetySetting`` instances
|
| 918 |
+
for blocking unsafe content.
|
| 919 |
+
|
| 920 |
+
This will be enforced on the
|
| 921 |
+
``GenerateAnswerRequest.contents`` and
|
| 922 |
+
``GenerateAnswerResponse.candidate``. There should not
|
| 923 |
+
be more than one setting for each ``SafetyCategory``
|
| 924 |
+
type. The API will block any contents and responses that
|
| 925 |
+
fail to meet the thresholds set by these settings. This
|
| 926 |
+
list overrides the default settings for each
|
| 927 |
+
``SafetyCategory`` specified in the safety_settings. If
|
| 928 |
+
there is no ``SafetySetting`` for a given
|
| 929 |
+
``SafetyCategory`` provided in the list, the API will
|
| 930 |
+
use the default safety setting for that category. Harm
|
| 931 |
+
categories HARM_CATEGORY_HATE_SPEECH,
|
| 932 |
+
HARM_CATEGORY_SEXUALLY_EXPLICIT,
|
| 933 |
+
HARM_CATEGORY_DANGEROUS_CONTENT,
|
| 934 |
+
HARM_CATEGORY_HARASSMENT are supported. Refer to the
|
| 935 |
+
`guide <https://ai.google.dev/gemini-api/docs/safety-settings>`__
|
| 936 |
+
for detailed information on available safety settings.
|
| 937 |
+
Also refer to the `Safety
|
| 938 |
+
guidance <https://ai.google.dev/gemini-api/docs/safety-guidance>`__
|
| 939 |
+
to learn how to incorporate safety considerations in
|
| 940 |
+
your AI applications.
|
| 941 |
+
|
| 942 |
+
This corresponds to the ``safety_settings`` field
|
| 943 |
+
on the ``request`` instance; if ``request`` is provided, this
|
| 944 |
+
should not be set.
|
| 945 |
+
answer_style (google.ai.generativelanguage_v1beta.types.GenerateAnswerRequest.AnswerStyle):
|
| 946 |
+
Required. Style in which answers
|
| 947 |
+
should be returned.
|
| 948 |
+
|
| 949 |
+
This corresponds to the ``answer_style`` field
|
| 950 |
+
on the ``request`` instance; if ``request`` is provided, this
|
| 951 |
+
should not be set.
|
| 952 |
+
retry (google.api_core.retry.Retry): Designation of what errors, if any,
|
| 953 |
+
should be retried.
|
| 954 |
+
timeout (float): The timeout for this request.
|
| 955 |
+
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
|
| 956 |
+
sent along with the request as metadata. Normally, each value must be of type `str`,
|
| 957 |
+
but for metadata keys ending with the suffix `-bin`, the corresponding values must
|
| 958 |
+
be of type `bytes`.
|
| 959 |
+
|
| 960 |
+
Returns:
|
| 961 |
+
google.ai.generativelanguage_v1beta.types.GenerateAnswerResponse:
|
| 962 |
+
Response from the model for a
|
| 963 |
+
grounded answer.
|
| 964 |
+
|
| 965 |
+
"""
|
| 966 |
+
# Create or coerce a protobuf request object.
|
| 967 |
+
# - Quick check: If we got a request object, we should *not* have
|
| 968 |
+
# gotten any keyword arguments that map to the request.
|
| 969 |
+
has_flattened_params = any([model, contents, safety_settings, answer_style])
|
| 970 |
+
if request is not None and has_flattened_params:
|
| 971 |
+
raise ValueError(
|
| 972 |
+
"If the `request` argument is set, then none of "
|
| 973 |
+
"the individual field arguments should be set."
|
| 974 |
+
)
|
| 975 |
+
|
| 976 |
+
# - Use the request object if provided (there's no risk of modifying the input as
|
| 977 |
+
# there are no flattened fields), or create one.
|
| 978 |
+
if not isinstance(request, generative_service.GenerateAnswerRequest):
|
| 979 |
+
request = generative_service.GenerateAnswerRequest(request)
|
| 980 |
+
# If we have keyword arguments corresponding to fields on the
|
| 981 |
+
# request, apply these.
|
| 982 |
+
if model is not None:
|
| 983 |
+
request.model = model
|
| 984 |
+
if contents is not None:
|
| 985 |
+
request.contents = contents
|
| 986 |
+
if safety_settings is not None:
|
| 987 |
+
request.safety_settings = safety_settings
|
| 988 |
+
if answer_style is not None:
|
| 989 |
+
request.answer_style = answer_style
|
| 990 |
+
|
| 991 |
+
# Wrap the RPC method; this adds retry and timeout information,
|
| 992 |
+
# and friendly error handling.
|
| 993 |
+
rpc = self._transport._wrapped_methods[self._transport.generate_answer]
|
| 994 |
+
|
| 995 |
+
# Certain fields should be provided within the metadata header;
|
| 996 |
+
# add these here.
|
| 997 |
+
metadata = tuple(metadata) + (
|
| 998 |
+
gapic_v1.routing_header.to_grpc_metadata((("model", request.model),)),
|
| 999 |
+
)
|
| 1000 |
+
|
| 1001 |
+
# Validate the universe domain.
|
| 1002 |
+
self._validate_universe_domain()
|
| 1003 |
+
|
| 1004 |
+
# Send the request.
|
| 1005 |
+
response = rpc(
|
| 1006 |
+
request,
|
| 1007 |
+
retry=retry,
|
| 1008 |
+
timeout=timeout,
|
| 1009 |
+
metadata=metadata,
|
| 1010 |
+
)
|
| 1011 |
+
|
| 1012 |
+
# Done; return the response.
|
| 1013 |
+
return response
|
| 1014 |
+
|
| 1015 |
+
def stream_generate_content(
|
| 1016 |
+
self,
|
| 1017 |
+
request: Optional[
|
| 1018 |
+
Union[generative_service.GenerateContentRequest, dict]
|
| 1019 |
+
] = None,
|
| 1020 |
+
*,
|
| 1021 |
+
model: Optional[str] = None,
|
| 1022 |
+
contents: Optional[MutableSequence[content.Content]] = None,
|
| 1023 |
+
retry: OptionalRetry = gapic_v1.method.DEFAULT,
|
| 1024 |
+
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
|
| 1025 |
+
metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
|
| 1026 |
+
) -> Iterable[generative_service.GenerateContentResponse]:
|
| 1027 |
+
r"""Generates a `streamed
|
| 1028 |
+
response <https://ai.google.dev/gemini-api/docs/text-generation?lang=python#generate-a-text-stream>`__
|
| 1029 |
+
from the model given an input ``GenerateContentRequest``.
|
| 1030 |
+
|
| 1031 |
+
.. code-block:: python
|
| 1032 |
+
|
| 1033 |
+
# This snippet has been automatically generated and should be regarded as a
|
| 1034 |
+
# code template only.
|
| 1035 |
+
# It will require modifications to work:
|
| 1036 |
+
# - It may require correct/in-range values for request initialization.
|
| 1037 |
+
# - It may require specifying regional endpoints when creating the service
|
| 1038 |
+
# client as shown in:
|
| 1039 |
+
# https://googleapis.dev/python/google-api-core/latest/client_options.html
|
| 1040 |
+
from google.ai import generativelanguage_v1beta
|
| 1041 |
+
|
| 1042 |
+
def sample_stream_generate_content():
|
| 1043 |
+
# Create a client
|
| 1044 |
+
client = generativelanguage_v1beta.GenerativeServiceClient()
|
| 1045 |
+
|
| 1046 |
+
# Initialize request argument(s)
|
| 1047 |
+
request = generativelanguage_v1beta.GenerateContentRequest(
|
| 1048 |
+
model="model_value",
|
| 1049 |
+
)
|
| 1050 |
+
|
| 1051 |
+
# Make the request
|
| 1052 |
+
stream = client.stream_generate_content(request=request)
|
| 1053 |
+
|
| 1054 |
+
# Handle the response
|
| 1055 |
+
for response in stream:
|
| 1056 |
+
print(response)
|
| 1057 |
+
|
| 1058 |
+
Args:
|
| 1059 |
+
request (Union[google.ai.generativelanguage_v1beta.types.GenerateContentRequest, dict]):
|
| 1060 |
+
The request object. Request to generate a completion from
|
| 1061 |
+
the model.
|
| 1062 |
+
model (str):
|
| 1063 |
+
Required. The name of the ``Model`` to use for
|
| 1064 |
+
generating the completion.
|
| 1065 |
+
|
| 1066 |
+
Format: ``models/{model}``.
|
| 1067 |
+
|
| 1068 |
+
This corresponds to the ``model`` field
|
| 1069 |
+
on the ``request`` instance; if ``request`` is provided, this
|
| 1070 |
+
should not be set.
|
| 1071 |
+
contents (MutableSequence[google.ai.generativelanguage_v1beta.types.Content]):
|
| 1072 |
+
Required. The content of the current conversation with
|
| 1073 |
+
the model.
|
| 1074 |
+
|
| 1075 |
+
For single-turn queries, this is a single instance. For
|
| 1076 |
+
multi-turn queries like
|
| 1077 |
+
`chat <https://ai.google.dev/gemini-api/docs/text-generation#chat>`__,
|
| 1078 |
+
this is a repeated field that contains the conversation
|
| 1079 |
+
history and the latest request.
|
| 1080 |
+
|
| 1081 |
+
This corresponds to the ``contents`` field
|
| 1082 |
+
on the ``request`` instance; if ``request`` is provided, this
|
| 1083 |
+
should not be set.
|
| 1084 |
+
retry (google.api_core.retry.Retry): Designation of what errors, if any,
|
| 1085 |
+
should be retried.
|
| 1086 |
+
timeout (float): The timeout for this request.
|
| 1087 |
+
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
|
| 1088 |
+
sent along with the request as metadata. Normally, each value must be of type `str`,
|
| 1089 |
+
but for metadata keys ending with the suffix `-bin`, the corresponding values must
|
| 1090 |
+
be of type `bytes`.
|
| 1091 |
+
|
| 1092 |
+
Returns:
|
| 1093 |
+
Iterable[google.ai.generativelanguage_v1beta.types.GenerateContentResponse]:
|
| 1094 |
+
Response from the model supporting multiple candidate
|
| 1095 |
+
responses.
|
| 1096 |
+
|
| 1097 |
+
Safety ratings and content filtering are reported for
|
| 1098 |
+
both prompt in
|
| 1099 |
+
GenerateContentResponse.prompt_feedback and for each
|
| 1100 |
+
candidate in finish_reason and in safety_ratings. The
|
| 1101 |
+
API: - Returns either all requested candidates or
|
| 1102 |
+
none of them - Returns no candidates at all only if
|
| 1103 |
+
there was something wrong with the prompt (check
|
| 1104 |
+
prompt_feedback) - Reports feedback on each candidate
|
| 1105 |
+
in finish_reason and safety_ratings.
|
| 1106 |
+
|
| 1107 |
+
"""
|
| 1108 |
+
# Create or coerce a protobuf request object.
|
| 1109 |
+
# - Quick check: If we got a request object, we should *not* have
|
| 1110 |
+
# gotten any keyword arguments that map to the request.
|
| 1111 |
+
has_flattened_params = any([model, contents])
|
| 1112 |
+
if request is not None and has_flattened_params:
|
| 1113 |
+
raise ValueError(
|
| 1114 |
+
"If the `request` argument is set, then none of "
|
| 1115 |
+
"the individual field arguments should be set."
|
| 1116 |
+
)
|
| 1117 |
+
|
| 1118 |
+
# - Use the request object if provided (there's no risk of modifying the input as
|
| 1119 |
+
# there are no flattened fields), or create one.
|
| 1120 |
+
if not isinstance(request, generative_service.GenerateContentRequest):
|
| 1121 |
+
request = generative_service.GenerateContentRequest(request)
|
| 1122 |
+
# If we have keyword arguments corresponding to fields on the
|
| 1123 |
+
# request, apply these.
|
| 1124 |
+
if model is not None:
|
| 1125 |
+
request.model = model
|
| 1126 |
+
if contents is not None:
|
| 1127 |
+
request.contents = contents
|
| 1128 |
+
|
| 1129 |
+
# Wrap the RPC method; this adds retry and timeout information,
|
| 1130 |
+
# and friendly error handling.
|
| 1131 |
+
rpc = self._transport._wrapped_methods[self._transport.stream_generate_content]
|
| 1132 |
+
|
| 1133 |
+
# Certain fields should be provided within the metadata header;
|
| 1134 |
+
# add these here.
|
| 1135 |
+
metadata = tuple(metadata) + (
|
| 1136 |
+
gapic_v1.routing_header.to_grpc_metadata((("model", request.model),)),
|
| 1137 |
+
)
|
| 1138 |
+
|
| 1139 |
+
# Validate the universe domain.
|
| 1140 |
+
self._validate_universe_domain()
|
| 1141 |
+
|
| 1142 |
+
# Send the request.
|
| 1143 |
+
response = rpc(
|
| 1144 |
+
request,
|
| 1145 |
+
retry=retry,
|
| 1146 |
+
timeout=timeout,
|
| 1147 |
+
metadata=metadata,
|
| 1148 |
+
)
|
| 1149 |
+
|
| 1150 |
+
# Done; return the response.
|
| 1151 |
+
return response
|
| 1152 |
+
|
| 1153 |
+
def embed_content(
|
| 1154 |
+
self,
|
| 1155 |
+
request: Optional[Union[generative_service.EmbedContentRequest, dict]] = None,
|
| 1156 |
+
*,
|
| 1157 |
+
model: Optional[str] = None,
|
| 1158 |
+
content: Optional[gag_content.Content] = None,
|
| 1159 |
+
retry: OptionalRetry = gapic_v1.method.DEFAULT,
|
| 1160 |
+
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
|
| 1161 |
+
metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
|
| 1162 |
+
) -> generative_service.EmbedContentResponse:
|
| 1163 |
+
r"""Generates a text embedding vector from the input ``Content``
|
| 1164 |
+
using the specified `Gemini Embedding
|
| 1165 |
+
model <https://ai.google.dev/gemini-api/docs/models/gemini#text-embedding>`__.
|
| 1166 |
+
|
| 1167 |
+
.. code-block:: python
|
| 1168 |
+
|
| 1169 |
+
# This snippet has been automatically generated and should be regarded as a
|
| 1170 |
+
# code template only.
|
| 1171 |
+
# It will require modifications to work:
|
| 1172 |
+
# - It may require correct/in-range values for request initialization.
|
| 1173 |
+
# - It may require specifying regional endpoints when creating the service
|
| 1174 |
+
# client as shown in:
|
| 1175 |
+
# https://googleapis.dev/python/google-api-core/latest/client_options.html
|
| 1176 |
+
from google.ai import generativelanguage_v1beta
|
| 1177 |
+
|
| 1178 |
+
def sample_embed_content():
|
| 1179 |
+
# Create a client
|
| 1180 |
+
client = generativelanguage_v1beta.GenerativeServiceClient()
|
| 1181 |
+
|
| 1182 |
+
# Initialize request argument(s)
|
| 1183 |
+
request = generativelanguage_v1beta.EmbedContentRequest(
|
| 1184 |
+
model="model_value",
|
| 1185 |
+
)
|
| 1186 |
+
|
| 1187 |
+
# Make the request
|
| 1188 |
+
response = client.embed_content(request=request)
|
| 1189 |
+
|
| 1190 |
+
# Handle the response
|
| 1191 |
+
print(response)
|
| 1192 |
+
|
| 1193 |
+
Args:
|
| 1194 |
+
request (Union[google.ai.generativelanguage_v1beta.types.EmbedContentRequest, dict]):
|
| 1195 |
+
The request object. Request containing the ``Content`` for the model to
|
| 1196 |
+
embed.
|
| 1197 |
+
model (str):
|
| 1198 |
+
Required. The model's resource name. This serves as an
|
| 1199 |
+
ID for the Model to use.
|
| 1200 |
+
|
| 1201 |
+
This name should match a model name returned by the
|
| 1202 |
+
``ListModels`` method.
|
| 1203 |
+
|
| 1204 |
+
Format: ``models/{model}``
|
| 1205 |
+
|
| 1206 |
+
This corresponds to the ``model`` field
|
| 1207 |
+
on the ``request`` instance; if ``request`` is provided, this
|
| 1208 |
+
should not be set.
|
| 1209 |
+
content (google.ai.generativelanguage_v1beta.types.Content):
|
| 1210 |
+
Required. The content to embed. Only the ``parts.text``
|
| 1211 |
+
fields will be counted.
|
| 1212 |
+
|
| 1213 |
+
This corresponds to the ``content`` field
|
| 1214 |
+
on the ``request`` instance; if ``request`` is provided, this
|
| 1215 |
+
should not be set.
|
| 1216 |
+
retry (google.api_core.retry.Retry): Designation of what errors, if any,
|
| 1217 |
+
should be retried.
|
| 1218 |
+
timeout (float): The timeout for this request.
|
| 1219 |
+
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
|
| 1220 |
+
sent along with the request as metadata. Normally, each value must be of type `str`,
|
| 1221 |
+
but for metadata keys ending with the suffix `-bin`, the corresponding values must
|
| 1222 |
+
be of type `bytes`.
|
| 1223 |
+
|
| 1224 |
+
Returns:
|
| 1225 |
+
google.ai.generativelanguage_v1beta.types.EmbedContentResponse:
|
| 1226 |
+
The response to an EmbedContentRequest.
|
| 1227 |
+
"""
|
| 1228 |
+
# Create or coerce a protobuf request object.
|
| 1229 |
+
# - Quick check: If we got a request object, we should *not* have
|
| 1230 |
+
# gotten any keyword arguments that map to the request.
|
| 1231 |
+
has_flattened_params = any([model, content])
|
| 1232 |
+
if request is not None and has_flattened_params:
|
| 1233 |
+
raise ValueError(
|
| 1234 |
+
"If the `request` argument is set, then none of "
|
| 1235 |
+
"the individual field arguments should be set."
|
| 1236 |
+
)
|
| 1237 |
+
|
| 1238 |
+
# - Use the request object if provided (there's no risk of modifying the input as
|
| 1239 |
+
# there are no flattened fields), or create one.
|
| 1240 |
+
if not isinstance(request, generative_service.EmbedContentRequest):
|
| 1241 |
+
request = generative_service.EmbedContentRequest(request)
|
| 1242 |
+
# If we have keyword arguments corresponding to fields on the
|
| 1243 |
+
# request, apply these.
|
| 1244 |
+
if model is not None:
|
| 1245 |
+
request.model = model
|
| 1246 |
+
if content is not None:
|
| 1247 |
+
request.content = content
|
| 1248 |
+
|
| 1249 |
+
# Wrap the RPC method; this adds retry and timeout information,
|
| 1250 |
+
# and friendly error handling.
|
| 1251 |
+
rpc = self._transport._wrapped_methods[self._transport.embed_content]
|
| 1252 |
+
|
| 1253 |
+
# Certain fields should be provided within the metadata header;
|
| 1254 |
+
# add these here.
|
| 1255 |
+
metadata = tuple(metadata) + (
|
| 1256 |
+
gapic_v1.routing_header.to_grpc_metadata((("model", request.model),)),
|
| 1257 |
+
)
|
| 1258 |
+
|
| 1259 |
+
# Validate the universe domain.
|
| 1260 |
+
self._validate_universe_domain()
|
| 1261 |
+
|
| 1262 |
+
# Send the request.
|
| 1263 |
+
response = rpc(
|
| 1264 |
+
request,
|
| 1265 |
+
retry=retry,
|
| 1266 |
+
timeout=timeout,
|
| 1267 |
+
metadata=metadata,
|
| 1268 |
+
)
|
| 1269 |
+
|
| 1270 |
+
# Done; return the response.
|
| 1271 |
+
return response
|
| 1272 |
+
|
| 1273 |
+
def batch_embed_contents(
|
| 1274 |
+
self,
|
| 1275 |
+
request: Optional[
|
| 1276 |
+
Union[generative_service.BatchEmbedContentsRequest, dict]
|
| 1277 |
+
] = None,
|
| 1278 |
+
*,
|
| 1279 |
+
model: Optional[str] = None,
|
| 1280 |
+
requests: Optional[
|
| 1281 |
+
MutableSequence[generative_service.EmbedContentRequest]
|
| 1282 |
+
] = None,
|
| 1283 |
+
retry: OptionalRetry = gapic_v1.method.DEFAULT,
|
| 1284 |
+
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
|
| 1285 |
+
metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
|
| 1286 |
+
) -> generative_service.BatchEmbedContentsResponse:
|
| 1287 |
+
r"""Generates multiple embedding vectors from the input ``Content``
|
| 1288 |
+
which consists of a batch of strings represented as
|
| 1289 |
+
``EmbedContentRequest`` objects.
|
| 1290 |
+
|
| 1291 |
+
.. code-block:: python
|
| 1292 |
+
|
| 1293 |
+
# This snippet has been automatically generated and should be regarded as a
|
| 1294 |
+
# code template only.
|
| 1295 |
+
# It will require modifications to work:
|
| 1296 |
+
# - It may require correct/in-range values for request initialization.
|
| 1297 |
+
# - It may require specifying regional endpoints when creating the service
|
| 1298 |
+
# client as shown in:
|
| 1299 |
+
# https://googleapis.dev/python/google-api-core/latest/client_options.html
|
| 1300 |
+
from google.ai import generativelanguage_v1beta
|
| 1301 |
+
|
| 1302 |
+
def sample_batch_embed_contents():
|
| 1303 |
+
# Create a client
|
| 1304 |
+
client = generativelanguage_v1beta.GenerativeServiceClient()
|
| 1305 |
+
|
| 1306 |
+
# Initialize request argument(s)
|
| 1307 |
+
requests = generativelanguage_v1beta.EmbedContentRequest()
|
| 1308 |
+
requests.model = "model_value"
|
| 1309 |
+
|
| 1310 |
+
request = generativelanguage_v1beta.BatchEmbedContentsRequest(
|
| 1311 |
+
model="model_value",
|
| 1312 |
+
requests=requests,
|
| 1313 |
+
)
|
| 1314 |
+
|
| 1315 |
+
# Make the request
|
| 1316 |
+
response = client.batch_embed_contents(request=request)
|
| 1317 |
+
|
| 1318 |
+
# Handle the response
|
| 1319 |
+
print(response)
|
| 1320 |
+
|
| 1321 |
+
Args:
|
| 1322 |
+
request (Union[google.ai.generativelanguage_v1beta.types.BatchEmbedContentsRequest, dict]):
|
| 1323 |
+
The request object. Batch request to get embeddings from
|
| 1324 |
+
the model for a list of prompts.
|
| 1325 |
+
model (str):
|
| 1326 |
+
Required. The model's resource name. This serves as an
|
| 1327 |
+
ID for the Model to use.
|
| 1328 |
+
|
| 1329 |
+
This name should match a model name returned by the
|
| 1330 |
+
``ListModels`` method.
|
| 1331 |
+
|
| 1332 |
+
Format: ``models/{model}``
|
| 1333 |
+
|
| 1334 |
+
This corresponds to the ``model`` field
|
| 1335 |
+
on the ``request`` instance; if ``request`` is provided, this
|
| 1336 |
+
should not be set.
|
| 1337 |
+
requests (MutableSequence[google.ai.generativelanguage_v1beta.types.EmbedContentRequest]):
|
| 1338 |
+
Required. Embed requests for the batch. The model in
|
| 1339 |
+
each of these requests must match the model specified
|
| 1340 |
+
``BatchEmbedContentsRequest.model``.
|
| 1341 |
+
|
| 1342 |
+
This corresponds to the ``requests`` field
|
| 1343 |
+
on the ``request`` instance; if ``request`` is provided, this
|
| 1344 |
+
should not be set.
|
| 1345 |
+
retry (google.api_core.retry.Retry): Designation of what errors, if any,
|
| 1346 |
+
should be retried.
|
| 1347 |
+
timeout (float): The timeout for this request.
|
| 1348 |
+
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
|
| 1349 |
+
sent along with the request as metadata. Normally, each value must be of type `str`,
|
| 1350 |
+
but for metadata keys ending with the suffix `-bin`, the corresponding values must
|
| 1351 |
+
be of type `bytes`.
|
| 1352 |
+
|
| 1353 |
+
Returns:
|
| 1354 |
+
google.ai.generativelanguage_v1beta.types.BatchEmbedContentsResponse:
|
| 1355 |
+
The response to a BatchEmbedContentsRequest.
|
| 1356 |
+
"""
|
| 1357 |
+
# Create or coerce a protobuf request object.
|
| 1358 |
+
# - Quick check: If we got a request object, we should *not* have
|
| 1359 |
+
# gotten any keyword arguments that map to the request.
|
| 1360 |
+
has_flattened_params = any([model, requests])
|
| 1361 |
+
if request is not None and has_flattened_params:
|
| 1362 |
+
raise ValueError(
|
| 1363 |
+
"If the `request` argument is set, then none of "
|
| 1364 |
+
"the individual field arguments should be set."
|
| 1365 |
+
)
|
| 1366 |
+
|
| 1367 |
+
# - Use the request object if provided (there's no risk of modifying the input as
|
| 1368 |
+
# there are no flattened fields), or create one.
|
| 1369 |
+
if not isinstance(request, generative_service.BatchEmbedContentsRequest):
|
| 1370 |
+
request = generative_service.BatchEmbedContentsRequest(request)
|
| 1371 |
+
# If we have keyword arguments corresponding to fields on the
|
| 1372 |
+
# request, apply these.
|
| 1373 |
+
if model is not None:
|
| 1374 |
+
request.model = model
|
| 1375 |
+
if requests is not None:
|
| 1376 |
+
request.requests = requests
|
| 1377 |
+
|
| 1378 |
+
# Wrap the RPC method; this adds retry and timeout information,
|
| 1379 |
+
# and friendly error handling.
|
| 1380 |
+
rpc = self._transport._wrapped_methods[self._transport.batch_embed_contents]
|
| 1381 |
+
|
| 1382 |
+
# Certain fields should be provided within the metadata header;
|
| 1383 |
+
# add these here.
|
| 1384 |
+
metadata = tuple(metadata) + (
|
| 1385 |
+
gapic_v1.routing_header.to_grpc_metadata((("model", request.model),)),
|
| 1386 |
+
)
|
| 1387 |
+
|
| 1388 |
+
# Validate the universe domain.
|
| 1389 |
+
self._validate_universe_domain()
|
| 1390 |
+
|
| 1391 |
+
# Send the request.
|
| 1392 |
+
response = rpc(
|
| 1393 |
+
request,
|
| 1394 |
+
retry=retry,
|
| 1395 |
+
timeout=timeout,
|
| 1396 |
+
metadata=metadata,
|
| 1397 |
+
)
|
| 1398 |
+
|
| 1399 |
+
# Done; return the response.
|
| 1400 |
+
return response
|
| 1401 |
+
|
| 1402 |
+
def count_tokens(
|
| 1403 |
+
self,
|
| 1404 |
+
request: Optional[Union[generative_service.CountTokensRequest, dict]] = None,
|
| 1405 |
+
*,
|
| 1406 |
+
model: Optional[str] = None,
|
| 1407 |
+
contents: Optional[MutableSequence[content.Content]] = None,
|
| 1408 |
+
retry: OptionalRetry = gapic_v1.method.DEFAULT,
|
| 1409 |
+
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
|
| 1410 |
+
metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
|
| 1411 |
+
) -> generative_service.CountTokensResponse:
|
| 1412 |
+
r"""Runs a model's tokenizer on input ``Content`` and returns the
|
| 1413 |
+
token count. Refer to the `tokens
|
| 1414 |
+
guide <https://ai.google.dev/gemini-api/docs/tokens>`__ to learn
|
| 1415 |
+
more about tokens.
|
| 1416 |
+
|
| 1417 |
+
.. code-block:: python
|
| 1418 |
+
|
| 1419 |
+
# This snippet has been automatically generated and should be regarded as a
|
| 1420 |
+
# code template only.
|
| 1421 |
+
# It will require modifications to work:
|
| 1422 |
+
# - It may require correct/in-range values for request initialization.
|
| 1423 |
+
# - It may require specifying regional endpoints when creating the service
|
| 1424 |
+
# client as shown in:
|
| 1425 |
+
# https://googleapis.dev/python/google-api-core/latest/client_options.html
|
| 1426 |
+
from google.ai import generativelanguage_v1beta
|
| 1427 |
+
|
| 1428 |
+
def sample_count_tokens():
|
| 1429 |
+
# Create a client
|
| 1430 |
+
client = generativelanguage_v1beta.GenerativeServiceClient()
|
| 1431 |
+
|
| 1432 |
+
# Initialize request argument(s)
|
| 1433 |
+
request = generativelanguage_v1beta.CountTokensRequest(
|
| 1434 |
+
model="model_value",
|
| 1435 |
+
)
|
| 1436 |
+
|
| 1437 |
+
# Make the request
|
| 1438 |
+
response = client.count_tokens(request=request)
|
| 1439 |
+
|
| 1440 |
+
# Handle the response
|
| 1441 |
+
print(response)
|
| 1442 |
+
|
| 1443 |
+
Args:
|
| 1444 |
+
request (Union[google.ai.generativelanguage_v1beta.types.CountTokensRequest, dict]):
|
| 1445 |
+
The request object. Counts the number of tokens in the ``prompt`` sent to a
|
| 1446 |
+
model.
|
| 1447 |
+
|
| 1448 |
+
Models may tokenize text differently, so each model may
|
| 1449 |
+
return a different ``token_count``.
|
| 1450 |
+
model (str):
|
| 1451 |
+
Required. The model's resource name. This serves as an
|
| 1452 |
+
ID for the Model to use.
|
| 1453 |
+
|
| 1454 |
+
This name should match a model name returned by the
|
| 1455 |
+
``ListModels`` method.
|
| 1456 |
+
|
| 1457 |
+
Format: ``models/{model}``
|
| 1458 |
+
|
| 1459 |
+
This corresponds to the ``model`` field
|
| 1460 |
+
on the ``request`` instance; if ``request`` is provided, this
|
| 1461 |
+
should not be set.
|
| 1462 |
+
contents (MutableSequence[google.ai.generativelanguage_v1beta.types.Content]):
|
| 1463 |
+
Optional. The input given to the model as a prompt. This
|
| 1464 |
+
field is ignored when ``generate_content_request`` is
|
| 1465 |
+
set.
|
| 1466 |
+
|
| 1467 |
+
This corresponds to the ``contents`` field
|
| 1468 |
+
on the ``request`` instance; if ``request`` is provided, this
|
| 1469 |
+
should not be set.
|
| 1470 |
+
retry (google.api_core.retry.Retry): Designation of what errors, if any,
|
| 1471 |
+
should be retried.
|
| 1472 |
+
timeout (float): The timeout for this request.
|
| 1473 |
+
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
|
| 1474 |
+
sent along with the request as metadata. Normally, each value must be of type `str`,
|
| 1475 |
+
but for metadata keys ending with the suffix `-bin`, the corresponding values must
|
| 1476 |
+
be of type `bytes`.
|
| 1477 |
+
|
| 1478 |
+
Returns:
|
| 1479 |
+
google.ai.generativelanguage_v1beta.types.CountTokensResponse:
|
| 1480 |
+
A response from CountTokens.
|
| 1481 |
+
|
| 1482 |
+
It returns the model's token_count for the prompt.
|
| 1483 |
+
|
| 1484 |
+
"""
|
| 1485 |
+
# Create or coerce a protobuf request object.
|
| 1486 |
+
# - Quick check: If we got a request object, we should *not* have
|
| 1487 |
+
# gotten any keyword arguments that map to the request.
|
| 1488 |
+
has_flattened_params = any([model, contents])
|
| 1489 |
+
if request is not None and has_flattened_params:
|
| 1490 |
+
raise ValueError(
|
| 1491 |
+
"If the `request` argument is set, then none of "
|
| 1492 |
+
"the individual field arguments should be set."
|
| 1493 |
+
)
|
| 1494 |
+
|
| 1495 |
+
# - Use the request object if provided (there's no risk of modifying the input as
|
| 1496 |
+
# there are no flattened fields), or create one.
|
| 1497 |
+
if not isinstance(request, generative_service.CountTokensRequest):
|
| 1498 |
+
request = generative_service.CountTokensRequest(request)
|
| 1499 |
+
# If we have keyword arguments corresponding to fields on the
|
| 1500 |
+
# request, apply these.
|
| 1501 |
+
if model is not None:
|
| 1502 |
+
request.model = model
|
| 1503 |
+
if contents is not None:
|
| 1504 |
+
request.contents = contents
|
| 1505 |
+
|
| 1506 |
+
# Wrap the RPC method; this adds retry and timeout information,
|
| 1507 |
+
# and friendly error handling.
|
| 1508 |
+
rpc = self._transport._wrapped_methods[self._transport.count_tokens]
|
| 1509 |
+
|
| 1510 |
+
# Certain fields should be provided within the metadata header;
|
| 1511 |
+
# add these here.
|
| 1512 |
+
metadata = tuple(metadata) + (
|
| 1513 |
+
gapic_v1.routing_header.to_grpc_metadata((("model", request.model),)),
|
| 1514 |
+
)
|
| 1515 |
+
|
| 1516 |
+
# Validate the universe domain.
|
| 1517 |
+
self._validate_universe_domain()
|
| 1518 |
+
|
| 1519 |
+
# Send the request.
|
| 1520 |
+
response = rpc(
|
| 1521 |
+
request,
|
| 1522 |
+
retry=retry,
|
| 1523 |
+
timeout=timeout,
|
| 1524 |
+
metadata=metadata,
|
| 1525 |
+
)
|
| 1526 |
+
|
| 1527 |
+
# Done; return the response.
|
| 1528 |
+
return response
|
| 1529 |
+
|
| 1530 |
+
def __enter__(self) -> "GenerativeServiceClient":
|
| 1531 |
+
return self
|
| 1532 |
+
|
| 1533 |
+
def __exit__(self, type, value, traceback):
|
| 1534 |
+
"""Releases underlying transport's resources.
|
| 1535 |
+
|
| 1536 |
+
.. warning::
|
| 1537 |
+
ONLY use as a context manager if the transport is NOT shared
|
| 1538 |
+
with other clients! Exiting the with block will CLOSE the transport
|
| 1539 |
+
and may cause errors in other clients!
|
| 1540 |
+
"""
|
| 1541 |
+
self.transport.close()
|
| 1542 |
+
|
| 1543 |
+
def list_operations(
|
| 1544 |
+
self,
|
| 1545 |
+
request: Optional[operations_pb2.ListOperationsRequest] = None,
|
| 1546 |
+
*,
|
| 1547 |
+
retry: OptionalRetry = gapic_v1.method.DEFAULT,
|
| 1548 |
+
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
|
| 1549 |
+
metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
|
| 1550 |
+
) -> operations_pb2.ListOperationsResponse:
|
| 1551 |
+
r"""Lists operations that match the specified filter in the request.
|
| 1552 |
+
|
| 1553 |
+
Args:
|
| 1554 |
+
request (:class:`~.operations_pb2.ListOperationsRequest`):
|
| 1555 |
+
The request object. Request message for
|
| 1556 |
+
`ListOperations` method.
|
| 1557 |
+
retry (google.api_core.retry.Retry): Designation of what errors,
|
| 1558 |
+
if any, should be retried.
|
| 1559 |
+
timeout (float): The timeout for this request.
|
| 1560 |
+
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
|
| 1561 |
+
sent along with the request as metadata. Normally, each value must be of type `str`,
|
| 1562 |
+
but for metadata keys ending with the suffix `-bin`, the corresponding values must
|
| 1563 |
+
be of type `bytes`.
|
| 1564 |
+
Returns:
|
| 1565 |
+
~.operations_pb2.ListOperationsResponse:
|
| 1566 |
+
Response message for ``ListOperations`` method.
|
| 1567 |
+
"""
|
| 1568 |
+
# Create or coerce a protobuf request object.
|
| 1569 |
+
# The request isn't a proto-plus wrapped type,
|
| 1570 |
+
# so it must be constructed via keyword expansion.
|
| 1571 |
+
if isinstance(request, dict):
|
| 1572 |
+
request = operations_pb2.ListOperationsRequest(**request)
|
| 1573 |
+
|
| 1574 |
+
# Wrap the RPC method; this adds retry and timeout information,
|
| 1575 |
+
# and friendly error handling.
|
| 1576 |
+
rpc = self._transport._wrapped_methods[self._transport.list_operations]
|
| 1577 |
+
|
| 1578 |
+
# Certain fields should be provided within the metadata header;
|
| 1579 |
+
# add these here.
|
| 1580 |
+
metadata = tuple(metadata) + (
|
| 1581 |
+
gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
|
| 1582 |
+
)
|
| 1583 |
+
|
| 1584 |
+
# Validate the universe domain.
|
| 1585 |
+
self._validate_universe_domain()
|
| 1586 |
+
|
| 1587 |
+
# Send the request.
|
| 1588 |
+
response = rpc(
|
| 1589 |
+
request,
|
| 1590 |
+
retry=retry,
|
| 1591 |
+
timeout=timeout,
|
| 1592 |
+
metadata=metadata,
|
| 1593 |
+
)
|
| 1594 |
+
|
| 1595 |
+
# Done; return the response.
|
| 1596 |
+
return response
|
| 1597 |
+
|
| 1598 |
+
def get_operation(
|
| 1599 |
+
self,
|
| 1600 |
+
request: Optional[operations_pb2.GetOperationRequest] = None,
|
| 1601 |
+
*,
|
| 1602 |
+
retry: OptionalRetry = gapic_v1.method.DEFAULT,
|
| 1603 |
+
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
|
| 1604 |
+
metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
|
| 1605 |
+
) -> operations_pb2.Operation:
|
| 1606 |
+
r"""Gets the latest state of a long-running operation.
|
| 1607 |
+
|
| 1608 |
+
Args:
|
| 1609 |
+
request (:class:`~.operations_pb2.GetOperationRequest`):
|
| 1610 |
+
The request object. Request message for
|
| 1611 |
+
`GetOperation` method.
|
| 1612 |
+
retry (google.api_core.retry.Retry): Designation of what errors,
|
| 1613 |
+
if any, should be retried.
|
| 1614 |
+
timeout (float): The timeout for this request.
|
| 1615 |
+
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
|
| 1616 |
+
sent along with the request as metadata. Normally, each value must be of type `str`,
|
| 1617 |
+
but for metadata keys ending with the suffix `-bin`, the corresponding values must
|
| 1618 |
+
be of type `bytes`.
|
| 1619 |
+
Returns:
|
| 1620 |
+
~.operations_pb2.Operation:
|
| 1621 |
+
An ``Operation`` object.
|
| 1622 |
+
"""
|
| 1623 |
+
# Create or coerce a protobuf request object.
|
| 1624 |
+
# The request isn't a proto-plus wrapped type,
|
| 1625 |
+
# so it must be constructed via keyword expansion.
|
| 1626 |
+
if isinstance(request, dict):
|
| 1627 |
+
request = operations_pb2.GetOperationRequest(**request)
|
| 1628 |
+
|
| 1629 |
+
# Wrap the RPC method; this adds retry and timeout information,
|
| 1630 |
+
# and friendly error handling.
|
| 1631 |
+
rpc = self._transport._wrapped_methods[self._transport.get_operation]
|
| 1632 |
+
|
| 1633 |
+
# Certain fields should be provided within the metadata header;
|
| 1634 |
+
# add these here.
|
| 1635 |
+
metadata = tuple(metadata) + (
|
| 1636 |
+
gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
|
| 1637 |
+
)
|
| 1638 |
+
|
| 1639 |
+
# Validate the universe domain.
|
| 1640 |
+
self._validate_universe_domain()
|
| 1641 |
+
|
| 1642 |
+
# Send the request.
|
| 1643 |
+
response = rpc(
|
| 1644 |
+
request,
|
| 1645 |
+
retry=retry,
|
| 1646 |
+
timeout=timeout,
|
| 1647 |
+
metadata=metadata,
|
| 1648 |
+
)
|
| 1649 |
+
|
| 1650 |
+
# Done; return the response.
|
| 1651 |
+
return response
|
| 1652 |
+
|
| 1653 |
+
|
| 1654 |
+
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
|
| 1655 |
+
gapic_version=package_version.__version__
|
| 1656 |
+
)
|
| 1657 |
+
|
| 1658 |
+
|
| 1659 |
+
__all__ = ("GenerativeServiceClient",)
|
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/generative_service/transports/__init__.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Copyright 2024 Google LLC
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
#
|
| 16 |
+
from collections import OrderedDict
|
| 17 |
+
from typing import Dict, Type
|
| 18 |
+
|
| 19 |
+
from .base import GenerativeServiceTransport
|
| 20 |
+
from .grpc import GenerativeServiceGrpcTransport
|
| 21 |
+
from .grpc_asyncio import GenerativeServiceGrpcAsyncIOTransport
|
| 22 |
+
from .rest import GenerativeServiceRestInterceptor, GenerativeServiceRestTransport
|
| 23 |
+
|
| 24 |
+
# Compile a registry of transports.
|
| 25 |
+
_transport_registry = OrderedDict() # type: Dict[str, Type[GenerativeServiceTransport]]
|
| 26 |
+
_transport_registry["grpc"] = GenerativeServiceGrpcTransport
|
| 27 |
+
_transport_registry["grpc_asyncio"] = GenerativeServiceGrpcAsyncIOTransport
|
| 28 |
+
_transport_registry["rest"] = GenerativeServiceRestTransport
|
| 29 |
+
|
| 30 |
+
__all__ = (
|
| 31 |
+
"GenerativeServiceTransport",
|
| 32 |
+
"GenerativeServiceGrpcTransport",
|
| 33 |
+
"GenerativeServiceGrpcAsyncIOTransport",
|
| 34 |
+
"GenerativeServiceRestTransport",
|
| 35 |
+
"GenerativeServiceRestInterceptor",
|
| 36 |
+
)
|
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/generative_service/transports/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (925 Bytes). View file
|
|
|
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/generative_service/transports/__pycache__/base.cpython-311.pyc
ADDED
|
Binary file (11.8 kB). View file
|
|
|
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/generative_service/transports/__pycache__/grpc.cpython-311.pyc
ADDED
|
Binary file (24.5 kB). View file
|
|
|
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/generative_service/transports/__pycache__/grpc_asyncio.cpython-311.pyc
ADDED
|
Binary file (28.3 kB). View file
|
|
|
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/generative_service/transports/__pycache__/rest.cpython-311.pyc
ADDED
|
Binary file (64.3 kB). View file
|
|
|
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/generative_service/transports/__pycache__/rest_base.cpython-311.pyc
ADDED
|
Binary file (23.1 kB). View file
|
|
|
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/generative_service/transports/base.py
ADDED
|
@@ -0,0 +1,335 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
#
|
| 16 |
+
import abc
|
| 17 |
+
from typing import Awaitable, Callable, Dict, Optional, Sequence, Union
|
| 18 |
+
|
| 19 |
+
import google.api_core
|
| 20 |
+
from google.api_core import exceptions as core_exceptions
|
| 21 |
+
from google.api_core import gapic_v1
|
| 22 |
+
from google.api_core import retry as retries
|
| 23 |
+
import google.auth # type: ignore
|
| 24 |
+
from google.auth import credentials as ga_credentials # type: ignore
|
| 25 |
+
from google.longrunning import operations_pb2 # type: ignore
|
| 26 |
+
from google.oauth2 import service_account # type: ignore
|
| 27 |
+
|
| 28 |
+
from google.ai.generativelanguage_v1beta import gapic_version as package_version
|
| 29 |
+
from google.ai.generativelanguage_v1beta.types import generative_service
|
| 30 |
+
|
| 31 |
+
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
|
| 32 |
+
gapic_version=package_version.__version__
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class GenerativeServiceTransport(abc.ABC):
|
| 37 |
+
"""Abstract transport class for GenerativeService."""
|
| 38 |
+
|
| 39 |
+
AUTH_SCOPES = ()
|
| 40 |
+
|
| 41 |
+
DEFAULT_HOST: str = "generativelanguage.googleapis.com"
|
| 42 |
+
|
| 43 |
+
def __init__(
|
| 44 |
+
self,
|
| 45 |
+
*,
|
| 46 |
+
host: str = DEFAULT_HOST,
|
| 47 |
+
credentials: Optional[ga_credentials.Credentials] = None,
|
| 48 |
+
credentials_file: Optional[str] = None,
|
| 49 |
+
scopes: Optional[Sequence[str]] = None,
|
| 50 |
+
quota_project_id: Optional[str] = None,
|
| 51 |
+
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
|
| 52 |
+
always_use_jwt_access: Optional[bool] = False,
|
| 53 |
+
api_audience: Optional[str] = None,
|
| 54 |
+
**kwargs,
|
| 55 |
+
) -> None:
|
| 56 |
+
"""Instantiate the transport.
|
| 57 |
+
|
| 58 |
+
Args:
|
| 59 |
+
host (Optional[str]):
|
| 60 |
+
The hostname to connect to (default: 'generativelanguage.googleapis.com').
|
| 61 |
+
credentials (Optional[google.auth.credentials.Credentials]): The
|
| 62 |
+
authorization credentials to attach to requests. These
|
| 63 |
+
credentials identify the application to the service; if none
|
| 64 |
+
are specified, the client will attempt to ascertain the
|
| 65 |
+
credentials from the environment.
|
| 66 |
+
credentials_file (Optional[str]): A file with credentials that can
|
| 67 |
+
be loaded with :func:`google.auth.load_credentials_from_file`.
|
| 68 |
+
This argument is mutually exclusive with credentials.
|
| 69 |
+
scopes (Optional[Sequence[str]]): A list of scopes.
|
| 70 |
+
quota_project_id (Optional[str]): An optional project to use for billing
|
| 71 |
+
and quota.
|
| 72 |
+
client_info (google.api_core.gapic_v1.client_info.ClientInfo):
|
| 73 |
+
The client info used to send a user-agent string along with
|
| 74 |
+
API requests. If ``None``, then default info will be used.
|
| 75 |
+
Generally, you only need to set this if you're developing
|
| 76 |
+
your own client library.
|
| 77 |
+
always_use_jwt_access (Optional[bool]): Whether self signed JWT should
|
| 78 |
+
be used for service account credentials.
|
| 79 |
+
"""
|
| 80 |
+
|
| 81 |
+
scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES}
|
| 82 |
+
|
| 83 |
+
# Save the scopes.
|
| 84 |
+
self._scopes = scopes
|
| 85 |
+
if not hasattr(self, "_ignore_credentials"):
|
| 86 |
+
self._ignore_credentials: bool = False
|
| 87 |
+
|
| 88 |
+
# If no credentials are provided, then determine the appropriate
|
| 89 |
+
# defaults.
|
| 90 |
+
if credentials and credentials_file:
|
| 91 |
+
raise core_exceptions.DuplicateCredentialArgs(
|
| 92 |
+
"'credentials_file' and 'credentials' are mutually exclusive"
|
| 93 |
+
)
|
| 94 |
+
|
| 95 |
+
if credentials_file is not None:
|
| 96 |
+
credentials, _ = google.auth.load_credentials_from_file(
|
| 97 |
+
credentials_file, **scopes_kwargs, quota_project_id=quota_project_id
|
| 98 |
+
)
|
| 99 |
+
elif credentials is None and not self._ignore_credentials:
|
| 100 |
+
credentials, _ = google.auth.default(
|
| 101 |
+
**scopes_kwargs, quota_project_id=quota_project_id
|
| 102 |
+
)
|
| 103 |
+
# Don't apply audience if the credentials file passed from user.
|
| 104 |
+
if hasattr(credentials, "with_gdch_audience"):
|
| 105 |
+
credentials = credentials.with_gdch_audience(
|
| 106 |
+
api_audience if api_audience else host
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
# If the credentials are service account credentials, then always try to use self signed JWT.
|
| 110 |
+
if (
|
| 111 |
+
always_use_jwt_access
|
| 112 |
+
and isinstance(credentials, service_account.Credentials)
|
| 113 |
+
and hasattr(service_account.Credentials, "with_always_use_jwt_access")
|
| 114 |
+
):
|
| 115 |
+
credentials = credentials.with_always_use_jwt_access(True)
|
| 116 |
+
|
| 117 |
+
# Save the credentials.
|
| 118 |
+
self._credentials = credentials
|
| 119 |
+
|
| 120 |
+
# Save the hostname. Default to port 443 (HTTPS) if none is specified.
|
| 121 |
+
if ":" not in host:
|
| 122 |
+
host += ":443"
|
| 123 |
+
self._host = host
|
| 124 |
+
|
| 125 |
+
@property
|
| 126 |
+
def host(self):
|
| 127 |
+
return self._host
|
| 128 |
+
|
| 129 |
+
def _prep_wrapped_messages(self, client_info):
|
| 130 |
+
# Precompute the wrapped methods.
|
| 131 |
+
self._wrapped_methods = {
|
| 132 |
+
self.generate_content: gapic_v1.method.wrap_method(
|
| 133 |
+
self.generate_content,
|
| 134 |
+
default_retry=retries.Retry(
|
| 135 |
+
initial=1.0,
|
| 136 |
+
maximum=10.0,
|
| 137 |
+
multiplier=1.3,
|
| 138 |
+
predicate=retries.if_exception_type(
|
| 139 |
+
core_exceptions.ServiceUnavailable,
|
| 140 |
+
),
|
| 141 |
+
deadline=600.0,
|
| 142 |
+
),
|
| 143 |
+
default_timeout=600.0,
|
| 144 |
+
client_info=client_info,
|
| 145 |
+
),
|
| 146 |
+
self.generate_answer: gapic_v1.method.wrap_method(
|
| 147 |
+
self.generate_answer,
|
| 148 |
+
default_retry=retries.Retry(
|
| 149 |
+
initial=1.0,
|
| 150 |
+
maximum=10.0,
|
| 151 |
+
multiplier=1.3,
|
| 152 |
+
predicate=retries.if_exception_type(
|
| 153 |
+
core_exceptions.ServiceUnavailable,
|
| 154 |
+
),
|
| 155 |
+
deadline=60.0,
|
| 156 |
+
),
|
| 157 |
+
default_timeout=60.0,
|
| 158 |
+
client_info=client_info,
|
| 159 |
+
),
|
| 160 |
+
self.stream_generate_content: gapic_v1.method.wrap_method(
|
| 161 |
+
self.stream_generate_content,
|
| 162 |
+
default_retry=retries.Retry(
|
| 163 |
+
initial=1.0,
|
| 164 |
+
maximum=10.0,
|
| 165 |
+
multiplier=1.3,
|
| 166 |
+
predicate=retries.if_exception_type(
|
| 167 |
+
core_exceptions.ServiceUnavailable,
|
| 168 |
+
),
|
| 169 |
+
deadline=600.0,
|
| 170 |
+
),
|
| 171 |
+
default_timeout=600.0,
|
| 172 |
+
client_info=client_info,
|
| 173 |
+
),
|
| 174 |
+
self.embed_content: gapic_v1.method.wrap_method(
|
| 175 |
+
self.embed_content,
|
| 176 |
+
default_retry=retries.Retry(
|
| 177 |
+
initial=1.0,
|
| 178 |
+
maximum=10.0,
|
| 179 |
+
multiplier=1.3,
|
| 180 |
+
predicate=retries.if_exception_type(
|
| 181 |
+
core_exceptions.ServiceUnavailable,
|
| 182 |
+
),
|
| 183 |
+
deadline=60.0,
|
| 184 |
+
),
|
| 185 |
+
default_timeout=60.0,
|
| 186 |
+
client_info=client_info,
|
| 187 |
+
),
|
| 188 |
+
self.batch_embed_contents: gapic_v1.method.wrap_method(
|
| 189 |
+
self.batch_embed_contents,
|
| 190 |
+
default_retry=retries.Retry(
|
| 191 |
+
initial=1.0,
|
| 192 |
+
maximum=10.0,
|
| 193 |
+
multiplier=1.3,
|
| 194 |
+
predicate=retries.if_exception_type(
|
| 195 |
+
core_exceptions.ServiceUnavailable,
|
| 196 |
+
),
|
| 197 |
+
deadline=60.0,
|
| 198 |
+
),
|
| 199 |
+
default_timeout=60.0,
|
| 200 |
+
client_info=client_info,
|
| 201 |
+
),
|
| 202 |
+
self.count_tokens: gapic_v1.method.wrap_method(
|
| 203 |
+
self.count_tokens,
|
| 204 |
+
default_retry=retries.Retry(
|
| 205 |
+
initial=1.0,
|
| 206 |
+
maximum=10.0,
|
| 207 |
+
multiplier=1.3,
|
| 208 |
+
predicate=retries.if_exception_type(
|
| 209 |
+
core_exceptions.ServiceUnavailable,
|
| 210 |
+
),
|
| 211 |
+
deadline=60.0,
|
| 212 |
+
),
|
| 213 |
+
default_timeout=60.0,
|
| 214 |
+
client_info=client_info,
|
| 215 |
+
),
|
| 216 |
+
self.get_operation: gapic_v1.method.wrap_method(
|
| 217 |
+
self.get_operation,
|
| 218 |
+
default_timeout=None,
|
| 219 |
+
client_info=client_info,
|
| 220 |
+
),
|
| 221 |
+
self.list_operations: gapic_v1.method.wrap_method(
|
| 222 |
+
self.list_operations,
|
| 223 |
+
default_timeout=None,
|
| 224 |
+
client_info=client_info,
|
| 225 |
+
),
|
| 226 |
+
}
|
| 227 |
+
|
| 228 |
+
def close(self):
|
| 229 |
+
"""Closes resources associated with the transport.
|
| 230 |
+
|
| 231 |
+
.. warning::
|
| 232 |
+
Only call this method if the transport is NOT shared
|
| 233 |
+
with other clients - this may cause errors in other clients!
|
| 234 |
+
"""
|
| 235 |
+
raise NotImplementedError()
|
| 236 |
+
|
| 237 |
+
@property
|
| 238 |
+
def generate_content(
|
| 239 |
+
self,
|
| 240 |
+
) -> Callable[
|
| 241 |
+
[generative_service.GenerateContentRequest],
|
| 242 |
+
Union[
|
| 243 |
+
generative_service.GenerateContentResponse,
|
| 244 |
+
Awaitable[generative_service.GenerateContentResponse],
|
| 245 |
+
],
|
| 246 |
+
]:
|
| 247 |
+
raise NotImplementedError()
|
| 248 |
+
|
| 249 |
+
@property
|
| 250 |
+
def generate_answer(
|
| 251 |
+
self,
|
| 252 |
+
) -> Callable[
|
| 253 |
+
[generative_service.GenerateAnswerRequest],
|
| 254 |
+
Union[
|
| 255 |
+
generative_service.GenerateAnswerResponse,
|
| 256 |
+
Awaitable[generative_service.GenerateAnswerResponse],
|
| 257 |
+
],
|
| 258 |
+
]:
|
| 259 |
+
raise NotImplementedError()
|
| 260 |
+
|
| 261 |
+
@property
|
| 262 |
+
def stream_generate_content(
|
| 263 |
+
self,
|
| 264 |
+
) -> Callable[
|
| 265 |
+
[generative_service.GenerateContentRequest],
|
| 266 |
+
Union[
|
| 267 |
+
generative_service.GenerateContentResponse,
|
| 268 |
+
Awaitable[generative_service.GenerateContentResponse],
|
| 269 |
+
],
|
| 270 |
+
]:
|
| 271 |
+
raise NotImplementedError()
|
| 272 |
+
|
| 273 |
+
@property
|
| 274 |
+
def embed_content(
|
| 275 |
+
self,
|
| 276 |
+
) -> Callable[
|
| 277 |
+
[generative_service.EmbedContentRequest],
|
| 278 |
+
Union[
|
| 279 |
+
generative_service.EmbedContentResponse,
|
| 280 |
+
Awaitable[generative_service.EmbedContentResponse],
|
| 281 |
+
],
|
| 282 |
+
]:
|
| 283 |
+
raise NotImplementedError()
|
| 284 |
+
|
| 285 |
+
@property
|
| 286 |
+
def batch_embed_contents(
|
| 287 |
+
self,
|
| 288 |
+
) -> Callable[
|
| 289 |
+
[generative_service.BatchEmbedContentsRequest],
|
| 290 |
+
Union[
|
| 291 |
+
generative_service.BatchEmbedContentsResponse,
|
| 292 |
+
Awaitable[generative_service.BatchEmbedContentsResponse],
|
| 293 |
+
],
|
| 294 |
+
]:
|
| 295 |
+
raise NotImplementedError()
|
| 296 |
+
|
| 297 |
+
@property
|
| 298 |
+
def count_tokens(
|
| 299 |
+
self,
|
| 300 |
+
) -> Callable[
|
| 301 |
+
[generative_service.CountTokensRequest],
|
| 302 |
+
Union[
|
| 303 |
+
generative_service.CountTokensResponse,
|
| 304 |
+
Awaitable[generative_service.CountTokensResponse],
|
| 305 |
+
],
|
| 306 |
+
]:
|
| 307 |
+
raise NotImplementedError()
|
| 308 |
+
|
| 309 |
+
@property
|
| 310 |
+
def list_operations(
|
| 311 |
+
self,
|
| 312 |
+
) -> Callable[
|
| 313 |
+
[operations_pb2.ListOperationsRequest],
|
| 314 |
+
Union[
|
| 315 |
+
operations_pb2.ListOperationsResponse,
|
| 316 |
+
Awaitable[operations_pb2.ListOperationsResponse],
|
| 317 |
+
],
|
| 318 |
+
]:
|
| 319 |
+
raise NotImplementedError()
|
| 320 |
+
|
| 321 |
+
@property
|
| 322 |
+
def get_operation(
|
| 323 |
+
self,
|
| 324 |
+
) -> Callable[
|
| 325 |
+
[operations_pb2.GetOperationRequest],
|
| 326 |
+
Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]],
|
| 327 |
+
]:
|
| 328 |
+
raise NotImplementedError()
|
| 329 |
+
|
| 330 |
+
@property
|
| 331 |
+
def kind(self) -> str:
|
| 332 |
+
raise NotImplementedError()
|
| 333 |
+
|
| 334 |
+
|
| 335 |
+
__all__ = ("GenerativeServiceTransport",)
|
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/generative_service/transports/grpc.py
ADDED
|
@@ -0,0 +1,560 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Copyright 2024 Google LLC
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
#
|
| 16 |
+
import json
|
| 17 |
+
import logging as std_logging
|
| 18 |
+
import pickle
|
| 19 |
+
from typing import Callable, Dict, Optional, Sequence, Tuple, Union
|
| 20 |
+
import warnings
|
| 21 |
+
|
| 22 |
+
from google.api_core import gapic_v1, grpc_helpers
|
| 23 |
+
import google.auth # type: ignore
|
| 24 |
+
from google.auth import credentials as ga_credentials # type: ignore
|
| 25 |
+
from google.auth.transport.grpc import SslCredentials # type: ignore
|
| 26 |
+
from google.longrunning import operations_pb2 # type: ignore
|
| 27 |
+
from google.protobuf.json_format import MessageToJson
|
| 28 |
+
import google.protobuf.message
|
| 29 |
+
import grpc # type: ignore
|
| 30 |
+
import proto # type: ignore
|
| 31 |
+
|
| 32 |
+
from google.ai.generativelanguage_v1beta.types import generative_service
|
| 33 |
+
|
| 34 |
+
from .base import DEFAULT_CLIENT_INFO, GenerativeServiceTransport
|
| 35 |
+
|
| 36 |
+
try:
|
| 37 |
+
from google.api_core import client_logging # type: ignore
|
| 38 |
+
|
| 39 |
+
CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER
|
| 40 |
+
except ImportError: # pragma: NO COVER
|
| 41 |
+
CLIENT_LOGGING_SUPPORTED = False
|
| 42 |
+
|
| 43 |
+
_LOGGER = std_logging.getLogger(__name__)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER
|
| 47 |
+
def intercept_unary_unary(self, continuation, client_call_details, request):
|
| 48 |
+
logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
|
| 49 |
+
std_logging.DEBUG
|
| 50 |
+
)
|
| 51 |
+
if logging_enabled: # pragma: NO COVER
|
| 52 |
+
request_metadata = client_call_details.metadata
|
| 53 |
+
if isinstance(request, proto.Message):
|
| 54 |
+
request_payload = type(request).to_json(request)
|
| 55 |
+
elif isinstance(request, google.protobuf.message.Message):
|
| 56 |
+
request_payload = MessageToJson(request)
|
| 57 |
+
else:
|
| 58 |
+
request_payload = f"{type(request).__name__}: {pickle.dumps(request)}"
|
| 59 |
+
|
| 60 |
+
request_metadata = {
|
| 61 |
+
key: value.decode("utf-8") if isinstance(value, bytes) else value
|
| 62 |
+
for key, value in request_metadata
|
| 63 |
+
}
|
| 64 |
+
grpc_request = {
|
| 65 |
+
"payload": request_payload,
|
| 66 |
+
"requestMethod": "grpc",
|
| 67 |
+
"metadata": dict(request_metadata),
|
| 68 |
+
}
|
| 69 |
+
_LOGGER.debug(
|
| 70 |
+
f"Sending request for {client_call_details.method}",
|
| 71 |
+
extra={
|
| 72 |
+
"serviceName": "google.ai.generativelanguage.v1beta.GenerativeService",
|
| 73 |
+
"rpcName": client_call_details.method,
|
| 74 |
+
"request": grpc_request,
|
| 75 |
+
"metadata": grpc_request["metadata"],
|
| 76 |
+
},
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
response = continuation(client_call_details, request)
|
| 80 |
+
if logging_enabled: # pragma: NO COVER
|
| 81 |
+
response_metadata = response.trailing_metadata()
|
| 82 |
+
# Convert gRPC metadata `<class 'grpc.aio._metadata.Metadata'>` to list of tuples
|
| 83 |
+
metadata = (
|
| 84 |
+
dict([(k, str(v)) for k, v in response_metadata])
|
| 85 |
+
if response_metadata
|
| 86 |
+
else None
|
| 87 |
+
)
|
| 88 |
+
result = response.result()
|
| 89 |
+
if isinstance(result, proto.Message):
|
| 90 |
+
response_payload = type(result).to_json(result)
|
| 91 |
+
elif isinstance(result, google.protobuf.message.Message):
|
| 92 |
+
response_payload = MessageToJson(result)
|
| 93 |
+
else:
|
| 94 |
+
response_payload = f"{type(result).__name__}: {pickle.dumps(result)}"
|
| 95 |
+
grpc_response = {
|
| 96 |
+
"payload": response_payload,
|
| 97 |
+
"metadata": metadata,
|
| 98 |
+
"status": "OK",
|
| 99 |
+
}
|
| 100 |
+
_LOGGER.debug(
|
| 101 |
+
f"Received response for {client_call_details.method}.",
|
| 102 |
+
extra={
|
| 103 |
+
"serviceName": "google.ai.generativelanguage.v1beta.GenerativeService",
|
| 104 |
+
"rpcName": client_call_details.method,
|
| 105 |
+
"response": grpc_response,
|
| 106 |
+
"metadata": grpc_response["metadata"],
|
| 107 |
+
},
|
| 108 |
+
)
|
| 109 |
+
return response
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
class GenerativeServiceGrpcTransport(GenerativeServiceTransport):
|
| 113 |
+
"""gRPC backend transport for GenerativeService.
|
| 114 |
+
|
| 115 |
+
API for using Large Models that generate multimodal content
|
| 116 |
+
and have additional capabilities beyond text generation.
|
| 117 |
+
|
| 118 |
+
This class defines the same methods as the primary client, so the
|
| 119 |
+
primary client can load the underlying transport implementation
|
| 120 |
+
and call it.
|
| 121 |
+
|
| 122 |
+
It sends protocol buffers over the wire using gRPC (which is built on
|
| 123 |
+
top of HTTP/2); the ``grpcio`` package must be installed.
|
| 124 |
+
"""
|
| 125 |
+
|
| 126 |
+
_stubs: Dict[str, Callable]
|
| 127 |
+
|
| 128 |
+
def __init__(
|
| 129 |
+
self,
|
| 130 |
+
*,
|
| 131 |
+
host: str = "generativelanguage.googleapis.com",
|
| 132 |
+
credentials: Optional[ga_credentials.Credentials] = None,
|
| 133 |
+
credentials_file: Optional[str] = None,
|
| 134 |
+
scopes: Optional[Sequence[str]] = None,
|
| 135 |
+
channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None,
|
| 136 |
+
api_mtls_endpoint: Optional[str] = None,
|
| 137 |
+
client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None,
|
| 138 |
+
ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None,
|
| 139 |
+
client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None,
|
| 140 |
+
quota_project_id: Optional[str] = None,
|
| 141 |
+
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
|
| 142 |
+
always_use_jwt_access: Optional[bool] = False,
|
| 143 |
+
api_audience: Optional[str] = None,
|
| 144 |
+
) -> None:
|
| 145 |
+
"""Instantiate the transport.
|
| 146 |
+
|
| 147 |
+
Args:
|
| 148 |
+
host (Optional[str]):
|
| 149 |
+
The hostname to connect to (default: 'generativelanguage.googleapis.com').
|
| 150 |
+
credentials (Optional[google.auth.credentials.Credentials]): The
|
| 151 |
+
authorization credentials to attach to requests. These
|
| 152 |
+
credentials identify the application to the service; if none
|
| 153 |
+
are specified, the client will attempt to ascertain the
|
| 154 |
+
credentials from the environment.
|
| 155 |
+
This argument is ignored if a ``channel`` instance is provided.
|
| 156 |
+
credentials_file (Optional[str]): A file with credentials that can
|
| 157 |
+
be loaded with :func:`google.auth.load_credentials_from_file`.
|
| 158 |
+
This argument is ignored if a ``channel`` instance is provided.
|
| 159 |
+
scopes (Optional(Sequence[str])): A list of scopes. This argument is
|
| 160 |
+
ignored if a ``channel`` instance is provided.
|
| 161 |
+
channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]):
|
| 162 |
+
A ``Channel`` instance through which to make calls, or a Callable
|
| 163 |
+
that constructs and returns one. If set to None, ``self.create_channel``
|
| 164 |
+
is used to create the channel. If a Callable is given, it will be called
|
| 165 |
+
with the same arguments as used in ``self.create_channel``.
|
| 166 |
+
api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint.
|
| 167 |
+
If provided, it overrides the ``host`` argument and tries to create
|
| 168 |
+
a mutual TLS channel with client SSL credentials from
|
| 169 |
+
``client_cert_source`` or application default SSL credentials.
|
| 170 |
+
client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]):
|
| 171 |
+
Deprecated. A callback to provide client SSL certificate bytes and
|
| 172 |
+
private key bytes, both in PEM format. It is ignored if
|
| 173 |
+
``api_mtls_endpoint`` is None.
|
| 174 |
+
ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials
|
| 175 |
+
for the grpc channel. It is ignored if a ``channel`` instance is provided.
|
| 176 |
+
client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]):
|
| 177 |
+
A callback to provide client certificate bytes and private key bytes,
|
| 178 |
+
both in PEM format. It is used to configure a mutual TLS channel. It is
|
| 179 |
+
ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided.
|
| 180 |
+
quota_project_id (Optional[str]): An optional project to use for billing
|
| 181 |
+
and quota.
|
| 182 |
+
client_info (google.api_core.gapic_v1.client_info.ClientInfo):
|
| 183 |
+
The client info used to send a user-agent string along with
|
| 184 |
+
API requests. If ``None``, then default info will be used.
|
| 185 |
+
Generally, you only need to set this if you're developing
|
| 186 |
+
your own client library.
|
| 187 |
+
always_use_jwt_access (Optional[bool]): Whether self signed JWT should
|
| 188 |
+
be used for service account credentials.
|
| 189 |
+
|
| 190 |
+
Raises:
|
| 191 |
+
google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
|
| 192 |
+
creation failed for any reason.
|
| 193 |
+
google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
|
| 194 |
+
and ``credentials_file`` are passed.
|
| 195 |
+
"""
|
| 196 |
+
self._grpc_channel = None
|
| 197 |
+
self._ssl_channel_credentials = ssl_channel_credentials
|
| 198 |
+
self._stubs: Dict[str, Callable] = {}
|
| 199 |
+
|
| 200 |
+
if api_mtls_endpoint:
|
| 201 |
+
warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning)
|
| 202 |
+
if client_cert_source:
|
| 203 |
+
warnings.warn("client_cert_source is deprecated", DeprecationWarning)
|
| 204 |
+
|
| 205 |
+
if isinstance(channel, grpc.Channel):
|
| 206 |
+
# Ignore credentials if a channel was passed.
|
| 207 |
+
credentials = None
|
| 208 |
+
self._ignore_credentials = True
|
| 209 |
+
# If a channel was explicitly provided, set it.
|
| 210 |
+
self._grpc_channel = channel
|
| 211 |
+
self._ssl_channel_credentials = None
|
| 212 |
+
|
| 213 |
+
else:
|
| 214 |
+
if api_mtls_endpoint:
|
| 215 |
+
host = api_mtls_endpoint
|
| 216 |
+
|
| 217 |
+
# Create SSL credentials with client_cert_source or application
|
| 218 |
+
# default SSL credentials.
|
| 219 |
+
if client_cert_source:
|
| 220 |
+
cert, key = client_cert_source()
|
| 221 |
+
self._ssl_channel_credentials = grpc.ssl_channel_credentials(
|
| 222 |
+
certificate_chain=cert, private_key=key
|
| 223 |
+
)
|
| 224 |
+
else:
|
| 225 |
+
self._ssl_channel_credentials = SslCredentials().ssl_credentials
|
| 226 |
+
|
| 227 |
+
else:
|
| 228 |
+
if client_cert_source_for_mtls and not ssl_channel_credentials:
|
| 229 |
+
cert, key = client_cert_source_for_mtls()
|
| 230 |
+
self._ssl_channel_credentials = grpc.ssl_channel_credentials(
|
| 231 |
+
certificate_chain=cert, private_key=key
|
| 232 |
+
)
|
| 233 |
+
|
| 234 |
+
# The base transport sets the host, credentials and scopes
|
| 235 |
+
super().__init__(
|
| 236 |
+
host=host,
|
| 237 |
+
credentials=credentials,
|
| 238 |
+
credentials_file=credentials_file,
|
| 239 |
+
scopes=scopes,
|
| 240 |
+
quota_project_id=quota_project_id,
|
| 241 |
+
client_info=client_info,
|
| 242 |
+
always_use_jwt_access=always_use_jwt_access,
|
| 243 |
+
api_audience=api_audience,
|
| 244 |
+
)
|
| 245 |
+
|
| 246 |
+
if not self._grpc_channel:
|
| 247 |
+
# initialize with the provided callable or the default channel
|
| 248 |
+
channel_init = channel or type(self).create_channel
|
| 249 |
+
self._grpc_channel = channel_init(
|
| 250 |
+
self._host,
|
| 251 |
+
# use the credentials which are saved
|
| 252 |
+
credentials=self._credentials,
|
| 253 |
+
# Set ``credentials_file`` to ``None`` here as
|
| 254 |
+
# the credentials that we saved earlier should be used.
|
| 255 |
+
credentials_file=None,
|
| 256 |
+
scopes=self._scopes,
|
| 257 |
+
ssl_credentials=self._ssl_channel_credentials,
|
| 258 |
+
quota_project_id=quota_project_id,
|
| 259 |
+
options=[
|
| 260 |
+
("grpc.max_send_message_length", -1),
|
| 261 |
+
("grpc.max_receive_message_length", -1),
|
| 262 |
+
],
|
| 263 |
+
)
|
| 264 |
+
|
| 265 |
+
self._interceptor = _LoggingClientInterceptor()
|
| 266 |
+
self._logged_channel = grpc.intercept_channel(
|
| 267 |
+
self._grpc_channel, self._interceptor
|
| 268 |
+
)
|
| 269 |
+
|
| 270 |
+
# Wrap messages. This must be done after self._logged_channel exists
|
| 271 |
+
self._prep_wrapped_messages(client_info)
|
| 272 |
+
|
| 273 |
+
@classmethod
|
| 274 |
+
def create_channel(
|
| 275 |
+
cls,
|
| 276 |
+
host: str = "generativelanguage.googleapis.com",
|
| 277 |
+
credentials: Optional[ga_credentials.Credentials] = None,
|
| 278 |
+
credentials_file: Optional[str] = None,
|
| 279 |
+
scopes: Optional[Sequence[str]] = None,
|
| 280 |
+
quota_project_id: Optional[str] = None,
|
| 281 |
+
**kwargs,
|
| 282 |
+
) -> grpc.Channel:
|
| 283 |
+
"""Create and return a gRPC channel object.
|
| 284 |
+
Args:
|
| 285 |
+
host (Optional[str]): The host for the channel to use.
|
| 286 |
+
credentials (Optional[~.Credentials]): The
|
| 287 |
+
authorization credentials to attach to requests. These
|
| 288 |
+
credentials identify this application to the service. If
|
| 289 |
+
none are specified, the client will attempt to ascertain
|
| 290 |
+
the credentials from the environment.
|
| 291 |
+
credentials_file (Optional[str]): A file with credentials that can
|
| 292 |
+
be loaded with :func:`google.auth.load_credentials_from_file`.
|
| 293 |
+
This argument is mutually exclusive with credentials.
|
| 294 |
+
scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
|
| 295 |
+
service. These are only used when credentials are not specified and
|
| 296 |
+
are passed to :func:`google.auth.default`.
|
| 297 |
+
quota_project_id (Optional[str]): An optional project to use for billing
|
| 298 |
+
and quota.
|
| 299 |
+
kwargs (Optional[dict]): Keyword arguments, which are passed to the
|
| 300 |
+
channel creation.
|
| 301 |
+
Returns:
|
| 302 |
+
grpc.Channel: A gRPC channel object.
|
| 303 |
+
|
| 304 |
+
Raises:
|
| 305 |
+
google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
|
| 306 |
+
and ``credentials_file`` are passed.
|
| 307 |
+
"""
|
| 308 |
+
|
| 309 |
+
return grpc_helpers.create_channel(
|
| 310 |
+
host,
|
| 311 |
+
credentials=credentials,
|
| 312 |
+
credentials_file=credentials_file,
|
| 313 |
+
quota_project_id=quota_project_id,
|
| 314 |
+
default_scopes=cls.AUTH_SCOPES,
|
| 315 |
+
scopes=scopes,
|
| 316 |
+
default_host=cls.DEFAULT_HOST,
|
| 317 |
+
**kwargs,
|
| 318 |
+
)
|
| 319 |
+
|
| 320 |
+
@property
|
| 321 |
+
def grpc_channel(self) -> grpc.Channel:
|
| 322 |
+
"""Return the channel designed to connect to this service."""
|
| 323 |
+
return self._grpc_channel
|
| 324 |
+
|
| 325 |
+
@property
|
| 326 |
+
def generate_content(
|
| 327 |
+
self,
|
| 328 |
+
) -> Callable[
|
| 329 |
+
[generative_service.GenerateContentRequest],
|
| 330 |
+
generative_service.GenerateContentResponse,
|
| 331 |
+
]:
|
| 332 |
+
r"""Return a callable for the generate content method over gRPC.
|
| 333 |
+
|
| 334 |
+
Generates a model response given an input
|
| 335 |
+
``GenerateContentRequest``. Refer to the `text generation
|
| 336 |
+
guide <https://ai.google.dev/gemini-api/docs/text-generation>`__
|
| 337 |
+
for detailed usage information. Input capabilities differ
|
| 338 |
+
between models, including tuned models. Refer to the `model
|
| 339 |
+
guide <https://ai.google.dev/gemini-api/docs/models/gemini>`__
|
| 340 |
+
and `tuning
|
| 341 |
+
guide <https://ai.google.dev/gemini-api/docs/model-tuning>`__
|
| 342 |
+
for details.
|
| 343 |
+
|
| 344 |
+
Returns:
|
| 345 |
+
Callable[[~.GenerateContentRequest],
|
| 346 |
+
~.GenerateContentResponse]:
|
| 347 |
+
A function that, when called, will call the underlying RPC
|
| 348 |
+
on the server.
|
| 349 |
+
"""
|
| 350 |
+
# Generate a "stub function" on-the-fly which will actually make
|
| 351 |
+
# the request.
|
| 352 |
+
# gRPC handles serialization and deserialization, so we just need
|
| 353 |
+
# to pass in the functions for each.
|
| 354 |
+
if "generate_content" not in self._stubs:
|
| 355 |
+
self._stubs["generate_content"] = self._logged_channel.unary_unary(
|
| 356 |
+
"/google.ai.generativelanguage.v1beta.GenerativeService/GenerateContent",
|
| 357 |
+
request_serializer=generative_service.GenerateContentRequest.serialize,
|
| 358 |
+
response_deserializer=generative_service.GenerateContentResponse.deserialize,
|
| 359 |
+
)
|
| 360 |
+
return self._stubs["generate_content"]
|
| 361 |
+
|
| 362 |
+
@property
|
| 363 |
+
def generate_answer(
|
| 364 |
+
self,
|
| 365 |
+
) -> Callable[
|
| 366 |
+
[generative_service.GenerateAnswerRequest],
|
| 367 |
+
generative_service.GenerateAnswerResponse,
|
| 368 |
+
]:
|
| 369 |
+
r"""Return a callable for the generate answer method over gRPC.
|
| 370 |
+
|
| 371 |
+
Generates a grounded answer from the model given an input
|
| 372 |
+
``GenerateAnswerRequest``.
|
| 373 |
+
|
| 374 |
+
Returns:
|
| 375 |
+
Callable[[~.GenerateAnswerRequest],
|
| 376 |
+
~.GenerateAnswerResponse]:
|
| 377 |
+
A function that, when called, will call the underlying RPC
|
| 378 |
+
on the server.
|
| 379 |
+
"""
|
| 380 |
+
# Generate a "stub function" on-the-fly which will actually make
|
| 381 |
+
# the request.
|
| 382 |
+
# gRPC handles serialization and deserialization, so we just need
|
| 383 |
+
# to pass in the functions for each.
|
| 384 |
+
if "generate_answer" not in self._stubs:
|
| 385 |
+
self._stubs["generate_answer"] = self._logged_channel.unary_unary(
|
| 386 |
+
"/google.ai.generativelanguage.v1beta.GenerativeService/GenerateAnswer",
|
| 387 |
+
request_serializer=generative_service.GenerateAnswerRequest.serialize,
|
| 388 |
+
response_deserializer=generative_service.GenerateAnswerResponse.deserialize,
|
| 389 |
+
)
|
| 390 |
+
return self._stubs["generate_answer"]
|
| 391 |
+
|
| 392 |
+
@property
|
| 393 |
+
def stream_generate_content(
|
| 394 |
+
self,
|
| 395 |
+
) -> Callable[
|
| 396 |
+
[generative_service.GenerateContentRequest],
|
| 397 |
+
generative_service.GenerateContentResponse,
|
| 398 |
+
]:
|
| 399 |
+
r"""Return a callable for the stream generate content method over gRPC.
|
| 400 |
+
|
| 401 |
+
Generates a `streamed
|
| 402 |
+
response <https://ai.google.dev/gemini-api/docs/text-generation?lang=python#generate-a-text-stream>`__
|
| 403 |
+
from the model given an input ``GenerateContentRequest``.
|
| 404 |
+
|
| 405 |
+
Returns:
|
| 406 |
+
Callable[[~.GenerateContentRequest],
|
| 407 |
+
~.GenerateContentResponse]:
|
| 408 |
+
A function that, when called, will call the underlying RPC
|
| 409 |
+
on the server.
|
| 410 |
+
"""
|
| 411 |
+
# Generate a "stub function" on-the-fly which will actually make
|
| 412 |
+
# the request.
|
| 413 |
+
# gRPC handles serialization and deserialization, so we just need
|
| 414 |
+
# to pass in the functions for each.
|
| 415 |
+
if "stream_generate_content" not in self._stubs:
|
| 416 |
+
self._stubs["stream_generate_content"] = self._logged_channel.unary_stream(
|
| 417 |
+
"/google.ai.generativelanguage.v1beta.GenerativeService/StreamGenerateContent",
|
| 418 |
+
request_serializer=generative_service.GenerateContentRequest.serialize,
|
| 419 |
+
response_deserializer=generative_service.GenerateContentResponse.deserialize,
|
| 420 |
+
)
|
| 421 |
+
return self._stubs["stream_generate_content"]
|
| 422 |
+
|
| 423 |
+
@property
|
| 424 |
+
def embed_content(
|
| 425 |
+
self,
|
| 426 |
+
) -> Callable[
|
| 427 |
+
[generative_service.EmbedContentRequest],
|
| 428 |
+
generative_service.EmbedContentResponse,
|
| 429 |
+
]:
|
| 430 |
+
r"""Return a callable for the embed content method over gRPC.
|
| 431 |
+
|
| 432 |
+
Generates a text embedding vector from the input ``Content``
|
| 433 |
+
using the specified `Gemini Embedding
|
| 434 |
+
model <https://ai.google.dev/gemini-api/docs/models/gemini#text-embedding>`__.
|
| 435 |
+
|
| 436 |
+
Returns:
|
| 437 |
+
Callable[[~.EmbedContentRequest],
|
| 438 |
+
~.EmbedContentResponse]:
|
| 439 |
+
A function that, when called, will call the underlying RPC
|
| 440 |
+
on the server.
|
| 441 |
+
"""
|
| 442 |
+
# Generate a "stub function" on-the-fly which will actually make
|
| 443 |
+
# the request.
|
| 444 |
+
# gRPC handles serialization and deserialization, so we just need
|
| 445 |
+
# to pass in the functions for each.
|
| 446 |
+
if "embed_content" not in self._stubs:
|
| 447 |
+
self._stubs["embed_content"] = self._logged_channel.unary_unary(
|
| 448 |
+
"/google.ai.generativelanguage.v1beta.GenerativeService/EmbedContent",
|
| 449 |
+
request_serializer=generative_service.EmbedContentRequest.serialize,
|
| 450 |
+
response_deserializer=generative_service.EmbedContentResponse.deserialize,
|
| 451 |
+
)
|
| 452 |
+
return self._stubs["embed_content"]
|
| 453 |
+
|
| 454 |
+
@property
|
| 455 |
+
def batch_embed_contents(
|
| 456 |
+
self,
|
| 457 |
+
) -> Callable[
|
| 458 |
+
[generative_service.BatchEmbedContentsRequest],
|
| 459 |
+
generative_service.BatchEmbedContentsResponse,
|
| 460 |
+
]:
|
| 461 |
+
r"""Return a callable for the batch embed contents method over gRPC.
|
| 462 |
+
|
| 463 |
+
Generates multiple embedding vectors from the input ``Content``
|
| 464 |
+
which consists of a batch of strings represented as
|
| 465 |
+
``EmbedContentRequest`` objects.
|
| 466 |
+
|
| 467 |
+
Returns:
|
| 468 |
+
Callable[[~.BatchEmbedContentsRequest],
|
| 469 |
+
~.BatchEmbedContentsResponse]:
|
| 470 |
+
A function that, when called, will call the underlying RPC
|
| 471 |
+
on the server.
|
| 472 |
+
"""
|
| 473 |
+
# Generate a "stub function" on-the-fly which will actually make
|
| 474 |
+
# the request.
|
| 475 |
+
# gRPC handles serialization and deserialization, so we just need
|
| 476 |
+
# to pass in the functions for each.
|
| 477 |
+
if "batch_embed_contents" not in self._stubs:
|
| 478 |
+
self._stubs["batch_embed_contents"] = self._logged_channel.unary_unary(
|
| 479 |
+
"/google.ai.generativelanguage.v1beta.GenerativeService/BatchEmbedContents",
|
| 480 |
+
request_serializer=generative_service.BatchEmbedContentsRequest.serialize,
|
| 481 |
+
response_deserializer=generative_service.BatchEmbedContentsResponse.deserialize,
|
| 482 |
+
)
|
| 483 |
+
return self._stubs["batch_embed_contents"]
|
| 484 |
+
|
| 485 |
+
@property
|
| 486 |
+
def count_tokens(
|
| 487 |
+
self,
|
| 488 |
+
) -> Callable[
|
| 489 |
+
[generative_service.CountTokensRequest], generative_service.CountTokensResponse
|
| 490 |
+
]:
|
| 491 |
+
r"""Return a callable for the count tokens method over gRPC.
|
| 492 |
+
|
| 493 |
+
Runs a model's tokenizer on input ``Content`` and returns the
|
| 494 |
+
token count. Refer to the `tokens
|
| 495 |
+
guide <https://ai.google.dev/gemini-api/docs/tokens>`__ to learn
|
| 496 |
+
more about tokens.
|
| 497 |
+
|
| 498 |
+
Returns:
|
| 499 |
+
Callable[[~.CountTokensRequest],
|
| 500 |
+
~.CountTokensResponse]:
|
| 501 |
+
A function that, when called, will call the underlying RPC
|
| 502 |
+
on the server.
|
| 503 |
+
"""
|
| 504 |
+
# Generate a "stub function" on-the-fly which will actually make
|
| 505 |
+
# the request.
|
| 506 |
+
# gRPC handles serialization and deserialization, so we just need
|
| 507 |
+
# to pass in the functions for each.
|
| 508 |
+
if "count_tokens" not in self._stubs:
|
| 509 |
+
self._stubs["count_tokens"] = self._logged_channel.unary_unary(
|
| 510 |
+
"/google.ai.generativelanguage.v1beta.GenerativeService/CountTokens",
|
| 511 |
+
request_serializer=generative_service.CountTokensRequest.serialize,
|
| 512 |
+
response_deserializer=generative_service.CountTokensResponse.deserialize,
|
| 513 |
+
)
|
| 514 |
+
return self._stubs["count_tokens"]
|
| 515 |
+
|
| 516 |
+
def close(self):
|
| 517 |
+
self._logged_channel.close()
|
| 518 |
+
|
| 519 |
+
@property
|
| 520 |
+
def get_operation(
|
| 521 |
+
self,
|
| 522 |
+
) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]:
|
| 523 |
+
r"""Return a callable for the get_operation method over gRPC."""
|
| 524 |
+
# Generate a "stub function" on-the-fly which will actually make
|
| 525 |
+
# the request.
|
| 526 |
+
# gRPC handles serialization and deserialization, so we just need
|
| 527 |
+
# to pass in the functions for each.
|
| 528 |
+
if "get_operation" not in self._stubs:
|
| 529 |
+
self._stubs["get_operation"] = self._logged_channel.unary_unary(
|
| 530 |
+
"/google.longrunning.Operations/GetOperation",
|
| 531 |
+
request_serializer=operations_pb2.GetOperationRequest.SerializeToString,
|
| 532 |
+
response_deserializer=operations_pb2.Operation.FromString,
|
| 533 |
+
)
|
| 534 |
+
return self._stubs["get_operation"]
|
| 535 |
+
|
| 536 |
+
@property
|
| 537 |
+
def list_operations(
|
| 538 |
+
self,
|
| 539 |
+
) -> Callable[
|
| 540 |
+
[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse
|
| 541 |
+
]:
|
| 542 |
+
r"""Return a callable for the list_operations method over gRPC."""
|
| 543 |
+
# Generate a "stub function" on-the-fly which will actually make
|
| 544 |
+
# the request.
|
| 545 |
+
# gRPC handles serialization and deserialization, so we just need
|
| 546 |
+
# to pass in the functions for each.
|
| 547 |
+
if "list_operations" not in self._stubs:
|
| 548 |
+
self._stubs["list_operations"] = self._logged_channel.unary_unary(
|
| 549 |
+
"/google.longrunning.Operations/ListOperations",
|
| 550 |
+
request_serializer=operations_pb2.ListOperationsRequest.SerializeToString,
|
| 551 |
+
response_deserializer=operations_pb2.ListOperationsResponse.FromString,
|
| 552 |
+
)
|
| 553 |
+
return self._stubs["list_operations"]
|
| 554 |
+
|
| 555 |
+
@property
|
| 556 |
+
def kind(self) -> str:
|
| 557 |
+
return "grpc"
|
| 558 |
+
|
| 559 |
+
|
| 560 |
+
__all__ = ("GenerativeServiceGrpcTransport",)
|
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/generative_service/transports/grpc_asyncio.py
ADDED
|
@@ -0,0 +1,672 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Copyright 2024 Google LLC
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
#
|
| 16 |
+
import inspect
|
| 17 |
+
import json
|
| 18 |
+
import logging as std_logging
|
| 19 |
+
import pickle
|
| 20 |
+
from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union
|
| 21 |
+
import warnings
|
| 22 |
+
|
| 23 |
+
from google.api_core import exceptions as core_exceptions
|
| 24 |
+
from google.api_core import gapic_v1, grpc_helpers_async
|
| 25 |
+
from google.api_core import retry_async as retries
|
| 26 |
+
from google.auth import credentials as ga_credentials # type: ignore
|
| 27 |
+
from google.auth.transport.grpc import SslCredentials # type: ignore
|
| 28 |
+
from google.longrunning import operations_pb2 # type: ignore
|
| 29 |
+
from google.protobuf.json_format import MessageToJson
|
| 30 |
+
import google.protobuf.message
|
| 31 |
+
import grpc # type: ignore
|
| 32 |
+
from grpc.experimental import aio # type: ignore
|
| 33 |
+
import proto # type: ignore
|
| 34 |
+
|
| 35 |
+
from google.ai.generativelanguage_v1beta.types import generative_service
|
| 36 |
+
|
| 37 |
+
from .base import DEFAULT_CLIENT_INFO, GenerativeServiceTransport
|
| 38 |
+
from .grpc import GenerativeServiceGrpcTransport
|
| 39 |
+
|
| 40 |
+
try:
|
| 41 |
+
from google.api_core import client_logging # type: ignore
|
| 42 |
+
|
| 43 |
+
CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER
|
| 44 |
+
except ImportError: # pragma: NO COVER
|
| 45 |
+
CLIENT_LOGGING_SUPPORTED = False
|
| 46 |
+
|
| 47 |
+
_LOGGER = std_logging.getLogger(__name__)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
class _LoggingClientAIOInterceptor(
|
| 51 |
+
grpc.aio.UnaryUnaryClientInterceptor
|
| 52 |
+
): # pragma: NO COVER
|
| 53 |
+
async def intercept_unary_unary(self, continuation, client_call_details, request):
|
| 54 |
+
logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
|
| 55 |
+
std_logging.DEBUG
|
| 56 |
+
)
|
| 57 |
+
if logging_enabled: # pragma: NO COVER
|
| 58 |
+
request_metadata = client_call_details.metadata
|
| 59 |
+
if isinstance(request, proto.Message):
|
| 60 |
+
request_payload = type(request).to_json(request)
|
| 61 |
+
elif isinstance(request, google.protobuf.message.Message):
|
| 62 |
+
request_payload = MessageToJson(request)
|
| 63 |
+
else:
|
| 64 |
+
request_payload = f"{type(request).__name__}: {pickle.dumps(request)}"
|
| 65 |
+
|
| 66 |
+
request_metadata = {
|
| 67 |
+
key: value.decode("utf-8") if isinstance(value, bytes) else value
|
| 68 |
+
for key, value in request_metadata
|
| 69 |
+
}
|
| 70 |
+
grpc_request = {
|
| 71 |
+
"payload": request_payload,
|
| 72 |
+
"requestMethod": "grpc",
|
| 73 |
+
"metadata": dict(request_metadata),
|
| 74 |
+
}
|
| 75 |
+
_LOGGER.debug(
|
| 76 |
+
f"Sending request for {client_call_details.method}",
|
| 77 |
+
extra={
|
| 78 |
+
"serviceName": "google.ai.generativelanguage.v1beta.GenerativeService",
|
| 79 |
+
"rpcName": str(client_call_details.method),
|
| 80 |
+
"request": grpc_request,
|
| 81 |
+
"metadata": grpc_request["metadata"],
|
| 82 |
+
},
|
| 83 |
+
)
|
| 84 |
+
response = await continuation(client_call_details, request)
|
| 85 |
+
if logging_enabled: # pragma: NO COVER
|
| 86 |
+
response_metadata = await response.trailing_metadata()
|
| 87 |
+
# Convert gRPC metadata `<class 'grpc.aio._metadata.Metadata'>` to list of tuples
|
| 88 |
+
metadata = (
|
| 89 |
+
dict([(k, str(v)) for k, v in response_metadata])
|
| 90 |
+
if response_metadata
|
| 91 |
+
else None
|
| 92 |
+
)
|
| 93 |
+
result = await response
|
| 94 |
+
if isinstance(result, proto.Message):
|
| 95 |
+
response_payload = type(result).to_json(result)
|
| 96 |
+
elif isinstance(result, google.protobuf.message.Message):
|
| 97 |
+
response_payload = MessageToJson(result)
|
| 98 |
+
else:
|
| 99 |
+
response_payload = f"{type(result).__name__}: {pickle.dumps(result)}"
|
| 100 |
+
grpc_response = {
|
| 101 |
+
"payload": response_payload,
|
| 102 |
+
"metadata": metadata,
|
| 103 |
+
"status": "OK",
|
| 104 |
+
}
|
| 105 |
+
_LOGGER.debug(
|
| 106 |
+
f"Received response to rpc {client_call_details.method}.",
|
| 107 |
+
extra={
|
| 108 |
+
"serviceName": "google.ai.generativelanguage.v1beta.GenerativeService",
|
| 109 |
+
"rpcName": str(client_call_details.method),
|
| 110 |
+
"response": grpc_response,
|
| 111 |
+
"metadata": grpc_response["metadata"],
|
| 112 |
+
},
|
| 113 |
+
)
|
| 114 |
+
return response
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
class GenerativeServiceGrpcAsyncIOTransport(GenerativeServiceTransport):
|
| 118 |
+
"""gRPC AsyncIO backend transport for GenerativeService.
|
| 119 |
+
|
| 120 |
+
API for using Large Models that generate multimodal content
|
| 121 |
+
and have additional capabilities beyond text generation.
|
| 122 |
+
|
| 123 |
+
This class defines the same methods as the primary client, so the
|
| 124 |
+
primary client can load the underlying transport implementation
|
| 125 |
+
and call it.
|
| 126 |
+
|
| 127 |
+
It sends protocol buffers over the wire using gRPC (which is built on
|
| 128 |
+
top of HTTP/2); the ``grpcio`` package must be installed.
|
| 129 |
+
"""
|
| 130 |
+
|
| 131 |
+
_grpc_channel: aio.Channel
|
| 132 |
+
_stubs: Dict[str, Callable] = {}
|
| 133 |
+
|
| 134 |
+
@classmethod
|
| 135 |
+
def create_channel(
|
| 136 |
+
cls,
|
| 137 |
+
host: str = "generativelanguage.googleapis.com",
|
| 138 |
+
credentials: Optional[ga_credentials.Credentials] = None,
|
| 139 |
+
credentials_file: Optional[str] = None,
|
| 140 |
+
scopes: Optional[Sequence[str]] = None,
|
| 141 |
+
quota_project_id: Optional[str] = None,
|
| 142 |
+
**kwargs,
|
| 143 |
+
) -> aio.Channel:
|
| 144 |
+
"""Create and return a gRPC AsyncIO channel object.
|
| 145 |
+
Args:
|
| 146 |
+
host (Optional[str]): The host for the channel to use.
|
| 147 |
+
credentials (Optional[~.Credentials]): The
|
| 148 |
+
authorization credentials to attach to requests. These
|
| 149 |
+
credentials identify this application to the service. If
|
| 150 |
+
none are specified, the client will attempt to ascertain
|
| 151 |
+
the credentials from the environment.
|
| 152 |
+
credentials_file (Optional[str]): A file with credentials that can
|
| 153 |
+
be loaded with :func:`google.auth.load_credentials_from_file`.
|
| 154 |
+
scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
|
| 155 |
+
service. These are only used when credentials are not specified and
|
| 156 |
+
are passed to :func:`google.auth.default`.
|
| 157 |
+
quota_project_id (Optional[str]): An optional project to use for billing
|
| 158 |
+
and quota.
|
| 159 |
+
kwargs (Optional[dict]): Keyword arguments, which are passed to the
|
| 160 |
+
channel creation.
|
| 161 |
+
Returns:
|
| 162 |
+
aio.Channel: A gRPC AsyncIO channel object.
|
| 163 |
+
"""
|
| 164 |
+
|
| 165 |
+
return grpc_helpers_async.create_channel(
|
| 166 |
+
host,
|
| 167 |
+
credentials=credentials,
|
| 168 |
+
credentials_file=credentials_file,
|
| 169 |
+
quota_project_id=quota_project_id,
|
| 170 |
+
default_scopes=cls.AUTH_SCOPES,
|
| 171 |
+
scopes=scopes,
|
| 172 |
+
default_host=cls.DEFAULT_HOST,
|
| 173 |
+
**kwargs,
|
| 174 |
+
)
|
| 175 |
+
|
| 176 |
+
def __init__(
|
| 177 |
+
self,
|
| 178 |
+
*,
|
| 179 |
+
host: str = "generativelanguage.googleapis.com",
|
| 180 |
+
credentials: Optional[ga_credentials.Credentials] = None,
|
| 181 |
+
credentials_file: Optional[str] = None,
|
| 182 |
+
scopes: Optional[Sequence[str]] = None,
|
| 183 |
+
channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None,
|
| 184 |
+
api_mtls_endpoint: Optional[str] = None,
|
| 185 |
+
client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None,
|
| 186 |
+
ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None,
|
| 187 |
+
client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None,
|
| 188 |
+
quota_project_id: Optional[str] = None,
|
| 189 |
+
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
|
| 190 |
+
always_use_jwt_access: Optional[bool] = False,
|
| 191 |
+
api_audience: Optional[str] = None,
|
| 192 |
+
) -> None:
|
| 193 |
+
"""Instantiate the transport.
|
| 194 |
+
|
| 195 |
+
Args:
|
| 196 |
+
host (Optional[str]):
|
| 197 |
+
The hostname to connect to (default: 'generativelanguage.googleapis.com').
|
| 198 |
+
credentials (Optional[google.auth.credentials.Credentials]): The
|
| 199 |
+
authorization credentials to attach to requests. These
|
| 200 |
+
credentials identify the application to the service; if none
|
| 201 |
+
are specified, the client will attempt to ascertain the
|
| 202 |
+
credentials from the environment.
|
| 203 |
+
This argument is ignored if a ``channel`` instance is provided.
|
| 204 |
+
credentials_file (Optional[str]): A file with credentials that can
|
| 205 |
+
be loaded with :func:`google.auth.load_credentials_from_file`.
|
| 206 |
+
This argument is ignored if a ``channel`` instance is provided.
|
| 207 |
+
scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
|
| 208 |
+
service. These are only used when credentials are not specified and
|
| 209 |
+
are passed to :func:`google.auth.default`.
|
| 210 |
+
channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]):
|
| 211 |
+
A ``Channel`` instance through which to make calls, or a Callable
|
| 212 |
+
that constructs and returns one. If set to None, ``self.create_channel``
|
| 213 |
+
is used to create the channel. If a Callable is given, it will be called
|
| 214 |
+
with the same arguments as used in ``self.create_channel``.
|
| 215 |
+
api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint.
|
| 216 |
+
If provided, it overrides the ``host`` argument and tries to create
|
| 217 |
+
a mutual TLS channel with client SSL credentials from
|
| 218 |
+
``client_cert_source`` or application default SSL credentials.
|
| 219 |
+
client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]):
|
| 220 |
+
Deprecated. A callback to provide client SSL certificate bytes and
|
| 221 |
+
private key bytes, both in PEM format. It is ignored if
|
| 222 |
+
``api_mtls_endpoint`` is None.
|
| 223 |
+
ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials
|
| 224 |
+
for the grpc channel. It is ignored if a ``channel`` instance is provided.
|
| 225 |
+
client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]):
|
| 226 |
+
A callback to provide client certificate bytes and private key bytes,
|
| 227 |
+
both in PEM format. It is used to configure a mutual TLS channel. It is
|
| 228 |
+
ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided.
|
| 229 |
+
quota_project_id (Optional[str]): An optional project to use for billing
|
| 230 |
+
and quota.
|
| 231 |
+
client_info (google.api_core.gapic_v1.client_info.ClientInfo):
|
| 232 |
+
The client info used to send a user-agent string along with
|
| 233 |
+
API requests. If ``None``, then default info will be used.
|
| 234 |
+
Generally, you only need to set this if you're developing
|
| 235 |
+
your own client library.
|
| 236 |
+
always_use_jwt_access (Optional[bool]): Whether self signed JWT should
|
| 237 |
+
be used for service account credentials.
|
| 238 |
+
|
| 239 |
+
Raises:
|
| 240 |
+
google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
|
| 241 |
+
creation failed for any reason.
|
| 242 |
+
google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
|
| 243 |
+
and ``credentials_file`` are passed.
|
| 244 |
+
"""
|
| 245 |
+
self._grpc_channel = None
|
| 246 |
+
self._ssl_channel_credentials = ssl_channel_credentials
|
| 247 |
+
self._stubs: Dict[str, Callable] = {}
|
| 248 |
+
|
| 249 |
+
if api_mtls_endpoint:
|
| 250 |
+
warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning)
|
| 251 |
+
if client_cert_source:
|
| 252 |
+
warnings.warn("client_cert_source is deprecated", DeprecationWarning)
|
| 253 |
+
|
| 254 |
+
if isinstance(channel, aio.Channel):
|
| 255 |
+
# Ignore credentials if a channel was passed.
|
| 256 |
+
credentials = None
|
| 257 |
+
self._ignore_credentials = True
|
| 258 |
+
# If a channel was explicitly provided, set it.
|
| 259 |
+
self._grpc_channel = channel
|
| 260 |
+
self._ssl_channel_credentials = None
|
| 261 |
+
else:
|
| 262 |
+
if api_mtls_endpoint:
|
| 263 |
+
host = api_mtls_endpoint
|
| 264 |
+
|
| 265 |
+
# Create SSL credentials with client_cert_source or application
|
| 266 |
+
# default SSL credentials.
|
| 267 |
+
if client_cert_source:
|
| 268 |
+
cert, key = client_cert_source()
|
| 269 |
+
self._ssl_channel_credentials = grpc.ssl_channel_credentials(
|
| 270 |
+
certificate_chain=cert, private_key=key
|
| 271 |
+
)
|
| 272 |
+
else:
|
| 273 |
+
self._ssl_channel_credentials = SslCredentials().ssl_credentials
|
| 274 |
+
|
| 275 |
+
else:
|
| 276 |
+
if client_cert_source_for_mtls and not ssl_channel_credentials:
|
| 277 |
+
cert, key = client_cert_source_for_mtls()
|
| 278 |
+
self._ssl_channel_credentials = grpc.ssl_channel_credentials(
|
| 279 |
+
certificate_chain=cert, private_key=key
|
| 280 |
+
)
|
| 281 |
+
|
| 282 |
+
# The base transport sets the host, credentials and scopes
|
| 283 |
+
super().__init__(
|
| 284 |
+
host=host,
|
| 285 |
+
credentials=credentials,
|
| 286 |
+
credentials_file=credentials_file,
|
| 287 |
+
scopes=scopes,
|
| 288 |
+
quota_project_id=quota_project_id,
|
| 289 |
+
client_info=client_info,
|
| 290 |
+
always_use_jwt_access=always_use_jwt_access,
|
| 291 |
+
api_audience=api_audience,
|
| 292 |
+
)
|
| 293 |
+
|
| 294 |
+
if not self._grpc_channel:
|
| 295 |
+
# initialize with the provided callable or the default channel
|
| 296 |
+
channel_init = channel or type(self).create_channel
|
| 297 |
+
self._grpc_channel = channel_init(
|
| 298 |
+
self._host,
|
| 299 |
+
# use the credentials which are saved
|
| 300 |
+
credentials=self._credentials,
|
| 301 |
+
# Set ``credentials_file`` to ``None`` here as
|
| 302 |
+
# the credentials that we saved earlier should be used.
|
| 303 |
+
credentials_file=None,
|
| 304 |
+
scopes=self._scopes,
|
| 305 |
+
ssl_credentials=self._ssl_channel_credentials,
|
| 306 |
+
quota_project_id=quota_project_id,
|
| 307 |
+
options=[
|
| 308 |
+
("grpc.max_send_message_length", -1),
|
| 309 |
+
("grpc.max_receive_message_length", -1),
|
| 310 |
+
],
|
| 311 |
+
)
|
| 312 |
+
|
| 313 |
+
self._interceptor = _LoggingClientAIOInterceptor()
|
| 314 |
+
self._grpc_channel._unary_unary_interceptors.append(self._interceptor)
|
| 315 |
+
self._logged_channel = self._grpc_channel
|
| 316 |
+
self._wrap_with_kind = (
|
| 317 |
+
"kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters
|
| 318 |
+
)
|
| 319 |
+
# Wrap messages. This must be done after self._logged_channel exists
|
| 320 |
+
self._prep_wrapped_messages(client_info)
|
| 321 |
+
|
| 322 |
+
@property
|
| 323 |
+
def grpc_channel(self) -> aio.Channel:
|
| 324 |
+
"""Create the channel designed to connect to this service.
|
| 325 |
+
|
| 326 |
+
This property caches on the instance; repeated calls return
|
| 327 |
+
the same channel.
|
| 328 |
+
"""
|
| 329 |
+
# Return the channel from cache.
|
| 330 |
+
return self._grpc_channel
|
| 331 |
+
|
| 332 |
+
@property
|
| 333 |
+
def generate_content(
|
| 334 |
+
self,
|
| 335 |
+
) -> Callable[
|
| 336 |
+
[generative_service.GenerateContentRequest],
|
| 337 |
+
Awaitable[generative_service.GenerateContentResponse],
|
| 338 |
+
]:
|
| 339 |
+
r"""Return a callable for the generate content method over gRPC.
|
| 340 |
+
|
| 341 |
+
Generates a model response given an input
|
| 342 |
+
``GenerateContentRequest``. Refer to the `text generation
|
| 343 |
+
guide <https://ai.google.dev/gemini-api/docs/text-generation>`__
|
| 344 |
+
for detailed usage information. Input capabilities differ
|
| 345 |
+
between models, including tuned models. Refer to the `model
|
| 346 |
+
guide <https://ai.google.dev/gemini-api/docs/models/gemini>`__
|
| 347 |
+
and `tuning
|
| 348 |
+
guide <https://ai.google.dev/gemini-api/docs/model-tuning>`__
|
| 349 |
+
for details.
|
| 350 |
+
|
| 351 |
+
Returns:
|
| 352 |
+
Callable[[~.GenerateContentRequest],
|
| 353 |
+
Awaitable[~.GenerateContentResponse]]:
|
| 354 |
+
A function that, when called, will call the underlying RPC
|
| 355 |
+
on the server.
|
| 356 |
+
"""
|
| 357 |
+
# Generate a "stub function" on-the-fly which will actually make
|
| 358 |
+
# the request.
|
| 359 |
+
# gRPC handles serialization and deserialization, so we just need
|
| 360 |
+
# to pass in the functions for each.
|
| 361 |
+
if "generate_content" not in self._stubs:
|
| 362 |
+
self._stubs["generate_content"] = self._logged_channel.unary_unary(
|
| 363 |
+
"/google.ai.generativelanguage.v1beta.GenerativeService/GenerateContent",
|
| 364 |
+
request_serializer=generative_service.GenerateContentRequest.serialize,
|
| 365 |
+
response_deserializer=generative_service.GenerateContentResponse.deserialize,
|
| 366 |
+
)
|
| 367 |
+
return self._stubs["generate_content"]
|
| 368 |
+
|
| 369 |
+
@property
|
| 370 |
+
def generate_answer(
|
| 371 |
+
self,
|
| 372 |
+
) -> Callable[
|
| 373 |
+
[generative_service.GenerateAnswerRequest],
|
| 374 |
+
Awaitable[generative_service.GenerateAnswerResponse],
|
| 375 |
+
]:
|
| 376 |
+
r"""Return a callable for the generate answer method over gRPC.
|
| 377 |
+
|
| 378 |
+
Generates a grounded answer from the model given an input
|
| 379 |
+
``GenerateAnswerRequest``.
|
| 380 |
+
|
| 381 |
+
Returns:
|
| 382 |
+
Callable[[~.GenerateAnswerRequest],
|
| 383 |
+
Awaitable[~.GenerateAnswerResponse]]:
|
| 384 |
+
A function that, when called, will call the underlying RPC
|
| 385 |
+
on the server.
|
| 386 |
+
"""
|
| 387 |
+
# Generate a "stub function" on-the-fly which will actually make
|
| 388 |
+
# the request.
|
| 389 |
+
# gRPC handles serialization and deserialization, so we just need
|
| 390 |
+
# to pass in the functions for each.
|
| 391 |
+
if "generate_answer" not in self._stubs:
|
| 392 |
+
self._stubs["generate_answer"] = self._logged_channel.unary_unary(
|
| 393 |
+
"/google.ai.generativelanguage.v1beta.GenerativeService/GenerateAnswer",
|
| 394 |
+
request_serializer=generative_service.GenerateAnswerRequest.serialize,
|
| 395 |
+
response_deserializer=generative_service.GenerateAnswerResponse.deserialize,
|
| 396 |
+
)
|
| 397 |
+
return self._stubs["generate_answer"]
|
| 398 |
+
|
| 399 |
+
@property
|
| 400 |
+
def stream_generate_content(
|
| 401 |
+
self,
|
| 402 |
+
) -> Callable[
|
| 403 |
+
[generative_service.GenerateContentRequest],
|
| 404 |
+
Awaitable[generative_service.GenerateContentResponse],
|
| 405 |
+
]:
|
| 406 |
+
r"""Return a callable for the stream generate content method over gRPC.
|
| 407 |
+
|
| 408 |
+
Generates a `streamed
|
| 409 |
+
response <https://ai.google.dev/gemini-api/docs/text-generation?lang=python#generate-a-text-stream>`__
|
| 410 |
+
from the model given an input ``GenerateContentRequest``.
|
| 411 |
+
|
| 412 |
+
Returns:
|
| 413 |
+
Callable[[~.GenerateContentRequest],
|
| 414 |
+
Awaitable[~.GenerateContentResponse]]:
|
| 415 |
+
A function that, when called, will call the underlying RPC
|
| 416 |
+
on the server.
|
| 417 |
+
"""
|
| 418 |
+
# Generate a "stub function" on-the-fly which will actually make
|
| 419 |
+
# the request.
|
| 420 |
+
# gRPC handles serialization and deserialization, so we just need
|
| 421 |
+
# to pass in the functions for each.
|
| 422 |
+
if "stream_generate_content" not in self._stubs:
|
| 423 |
+
self._stubs["stream_generate_content"] = self._logged_channel.unary_stream(
|
| 424 |
+
"/google.ai.generativelanguage.v1beta.GenerativeService/StreamGenerateContent",
|
| 425 |
+
request_serializer=generative_service.GenerateContentRequest.serialize,
|
| 426 |
+
response_deserializer=generative_service.GenerateContentResponse.deserialize,
|
| 427 |
+
)
|
| 428 |
+
return self._stubs["stream_generate_content"]
|
| 429 |
+
|
| 430 |
+
@property
|
| 431 |
+
def embed_content(
|
| 432 |
+
self,
|
| 433 |
+
) -> Callable[
|
| 434 |
+
[generative_service.EmbedContentRequest],
|
| 435 |
+
Awaitable[generative_service.EmbedContentResponse],
|
| 436 |
+
]:
|
| 437 |
+
r"""Return a callable for the embed content method over gRPC.
|
| 438 |
+
|
| 439 |
+
Generates a text embedding vector from the input ``Content``
|
| 440 |
+
using the specified `Gemini Embedding
|
| 441 |
+
model <https://ai.google.dev/gemini-api/docs/models/gemini#text-embedding>`__.
|
| 442 |
+
|
| 443 |
+
Returns:
|
| 444 |
+
Callable[[~.EmbedContentRequest],
|
| 445 |
+
Awaitable[~.EmbedContentResponse]]:
|
| 446 |
+
A function that, when called, will call the underlying RPC
|
| 447 |
+
on the server.
|
| 448 |
+
"""
|
| 449 |
+
# Generate a "stub function" on-the-fly which will actually make
|
| 450 |
+
# the request.
|
| 451 |
+
# gRPC handles serialization and deserialization, so we just need
|
| 452 |
+
# to pass in the functions for each.
|
| 453 |
+
if "embed_content" not in self._stubs:
|
| 454 |
+
self._stubs["embed_content"] = self._logged_channel.unary_unary(
|
| 455 |
+
"/google.ai.generativelanguage.v1beta.GenerativeService/EmbedContent",
|
| 456 |
+
request_serializer=generative_service.EmbedContentRequest.serialize,
|
| 457 |
+
response_deserializer=generative_service.EmbedContentResponse.deserialize,
|
| 458 |
+
)
|
| 459 |
+
return self._stubs["embed_content"]
|
| 460 |
+
|
| 461 |
+
@property
|
| 462 |
+
def batch_embed_contents(
|
| 463 |
+
self,
|
| 464 |
+
) -> Callable[
|
| 465 |
+
[generative_service.BatchEmbedContentsRequest],
|
| 466 |
+
Awaitable[generative_service.BatchEmbedContentsResponse],
|
| 467 |
+
]:
|
| 468 |
+
r"""Return a callable for the batch embed contents method over gRPC.
|
| 469 |
+
|
| 470 |
+
Generates multiple embedding vectors from the input ``Content``
|
| 471 |
+
which consists of a batch of strings represented as
|
| 472 |
+
``EmbedContentRequest`` objects.
|
| 473 |
+
|
| 474 |
+
Returns:
|
| 475 |
+
Callable[[~.BatchEmbedContentsRequest],
|
| 476 |
+
Awaitable[~.BatchEmbedContentsResponse]]:
|
| 477 |
+
A function that, when called, will call the underlying RPC
|
| 478 |
+
on the server.
|
| 479 |
+
"""
|
| 480 |
+
# Generate a "stub function" on-the-fly which will actually make
|
| 481 |
+
# the request.
|
| 482 |
+
# gRPC handles serialization and deserialization, so we just need
|
| 483 |
+
# to pass in the functions for each.
|
| 484 |
+
if "batch_embed_contents" not in self._stubs:
|
| 485 |
+
self._stubs["batch_embed_contents"] = self._logged_channel.unary_unary(
|
| 486 |
+
"/google.ai.generativelanguage.v1beta.GenerativeService/BatchEmbedContents",
|
| 487 |
+
request_serializer=generative_service.BatchEmbedContentsRequest.serialize,
|
| 488 |
+
response_deserializer=generative_service.BatchEmbedContentsResponse.deserialize,
|
| 489 |
+
)
|
| 490 |
+
return self._stubs["batch_embed_contents"]
|
| 491 |
+
|
| 492 |
+
@property
|
| 493 |
+
def count_tokens(
|
| 494 |
+
self,
|
| 495 |
+
) -> Callable[
|
| 496 |
+
[generative_service.CountTokensRequest],
|
| 497 |
+
Awaitable[generative_service.CountTokensResponse],
|
| 498 |
+
]:
|
| 499 |
+
r"""Return a callable for the count tokens method over gRPC.
|
| 500 |
+
|
| 501 |
+
Runs a model's tokenizer on input ``Content`` and returns the
|
| 502 |
+
token count. Refer to the `tokens
|
| 503 |
+
guide <https://ai.google.dev/gemini-api/docs/tokens>`__ to learn
|
| 504 |
+
more about tokens.
|
| 505 |
+
|
| 506 |
+
Returns:
|
| 507 |
+
Callable[[~.CountTokensRequest],
|
| 508 |
+
Awaitable[~.CountTokensResponse]]:
|
| 509 |
+
A function that, when called, will call the underlying RPC
|
| 510 |
+
on the server.
|
| 511 |
+
"""
|
| 512 |
+
# Generate a "stub function" on-the-fly which will actually make
|
| 513 |
+
# the request.
|
| 514 |
+
# gRPC handles serialization and deserialization, so we just need
|
| 515 |
+
# to pass in the functions for each.
|
| 516 |
+
if "count_tokens" not in self._stubs:
|
| 517 |
+
self._stubs["count_tokens"] = self._logged_channel.unary_unary(
|
| 518 |
+
"/google.ai.generativelanguage.v1beta.GenerativeService/CountTokens",
|
| 519 |
+
request_serializer=generative_service.CountTokensRequest.serialize,
|
| 520 |
+
response_deserializer=generative_service.CountTokensResponse.deserialize,
|
| 521 |
+
)
|
| 522 |
+
return self._stubs["count_tokens"]
|
| 523 |
+
|
| 524 |
+
def _prep_wrapped_messages(self, client_info):
|
| 525 |
+
"""Precompute the wrapped methods, overriding the base class method to use async wrappers."""
|
| 526 |
+
self._wrapped_methods = {
|
| 527 |
+
self.generate_content: self._wrap_method(
|
| 528 |
+
self.generate_content,
|
| 529 |
+
default_retry=retries.AsyncRetry(
|
| 530 |
+
initial=1.0,
|
| 531 |
+
maximum=10.0,
|
| 532 |
+
multiplier=1.3,
|
| 533 |
+
predicate=retries.if_exception_type(
|
| 534 |
+
core_exceptions.ServiceUnavailable,
|
| 535 |
+
),
|
| 536 |
+
deadline=600.0,
|
| 537 |
+
),
|
| 538 |
+
default_timeout=600.0,
|
| 539 |
+
client_info=client_info,
|
| 540 |
+
),
|
| 541 |
+
self.generate_answer: self._wrap_method(
|
| 542 |
+
self.generate_answer,
|
| 543 |
+
default_retry=retries.AsyncRetry(
|
| 544 |
+
initial=1.0,
|
| 545 |
+
maximum=10.0,
|
| 546 |
+
multiplier=1.3,
|
| 547 |
+
predicate=retries.if_exception_type(
|
| 548 |
+
core_exceptions.ServiceUnavailable,
|
| 549 |
+
),
|
| 550 |
+
deadline=60.0,
|
| 551 |
+
),
|
| 552 |
+
default_timeout=60.0,
|
| 553 |
+
client_info=client_info,
|
| 554 |
+
),
|
| 555 |
+
self.stream_generate_content: self._wrap_method(
|
| 556 |
+
self.stream_generate_content,
|
| 557 |
+
default_retry=retries.AsyncRetry(
|
| 558 |
+
initial=1.0,
|
| 559 |
+
maximum=10.0,
|
| 560 |
+
multiplier=1.3,
|
| 561 |
+
predicate=retries.if_exception_type(
|
| 562 |
+
core_exceptions.ServiceUnavailable,
|
| 563 |
+
),
|
| 564 |
+
deadline=600.0,
|
| 565 |
+
),
|
| 566 |
+
default_timeout=600.0,
|
| 567 |
+
client_info=client_info,
|
| 568 |
+
),
|
| 569 |
+
self.embed_content: self._wrap_method(
|
| 570 |
+
self.embed_content,
|
| 571 |
+
default_retry=retries.AsyncRetry(
|
| 572 |
+
initial=1.0,
|
| 573 |
+
maximum=10.0,
|
| 574 |
+
multiplier=1.3,
|
| 575 |
+
predicate=retries.if_exception_type(
|
| 576 |
+
core_exceptions.ServiceUnavailable,
|
| 577 |
+
),
|
| 578 |
+
deadline=60.0,
|
| 579 |
+
),
|
| 580 |
+
default_timeout=60.0,
|
| 581 |
+
client_info=client_info,
|
| 582 |
+
),
|
| 583 |
+
self.batch_embed_contents: self._wrap_method(
|
| 584 |
+
self.batch_embed_contents,
|
| 585 |
+
default_retry=retries.AsyncRetry(
|
| 586 |
+
initial=1.0,
|
| 587 |
+
maximum=10.0,
|
| 588 |
+
multiplier=1.3,
|
| 589 |
+
predicate=retries.if_exception_type(
|
| 590 |
+
core_exceptions.ServiceUnavailable,
|
| 591 |
+
),
|
| 592 |
+
deadline=60.0,
|
| 593 |
+
),
|
| 594 |
+
default_timeout=60.0,
|
| 595 |
+
client_info=client_info,
|
| 596 |
+
),
|
| 597 |
+
self.count_tokens: self._wrap_method(
|
| 598 |
+
self.count_tokens,
|
| 599 |
+
default_retry=retries.AsyncRetry(
|
| 600 |
+
initial=1.0,
|
| 601 |
+
maximum=10.0,
|
| 602 |
+
multiplier=1.3,
|
| 603 |
+
predicate=retries.if_exception_type(
|
| 604 |
+
core_exceptions.ServiceUnavailable,
|
| 605 |
+
),
|
| 606 |
+
deadline=60.0,
|
| 607 |
+
),
|
| 608 |
+
default_timeout=60.0,
|
| 609 |
+
client_info=client_info,
|
| 610 |
+
),
|
| 611 |
+
self.get_operation: self._wrap_method(
|
| 612 |
+
self.get_operation,
|
| 613 |
+
default_timeout=None,
|
| 614 |
+
client_info=client_info,
|
| 615 |
+
),
|
| 616 |
+
self.list_operations: self._wrap_method(
|
| 617 |
+
self.list_operations,
|
| 618 |
+
default_timeout=None,
|
| 619 |
+
client_info=client_info,
|
| 620 |
+
),
|
| 621 |
+
}
|
| 622 |
+
|
| 623 |
+
def _wrap_method(self, func, *args, **kwargs):
|
| 624 |
+
if self._wrap_with_kind: # pragma: NO COVER
|
| 625 |
+
kwargs["kind"] = self.kind
|
| 626 |
+
return gapic_v1.method_async.wrap_method(func, *args, **kwargs)
|
| 627 |
+
|
| 628 |
+
def close(self):
|
| 629 |
+
return self._logged_channel.close()
|
| 630 |
+
|
| 631 |
+
@property
|
| 632 |
+
def kind(self) -> str:
|
| 633 |
+
return "grpc_asyncio"
|
| 634 |
+
|
| 635 |
+
@property
|
| 636 |
+
def get_operation(
|
| 637 |
+
self,
|
| 638 |
+
) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]:
|
| 639 |
+
r"""Return a callable for the get_operation method over gRPC."""
|
| 640 |
+
# Generate a "stub function" on-the-fly which will actually make
|
| 641 |
+
# the request.
|
| 642 |
+
# gRPC handles serialization and deserialization, so we just need
|
| 643 |
+
# to pass in the functions for each.
|
| 644 |
+
if "get_operation" not in self._stubs:
|
| 645 |
+
self._stubs["get_operation"] = self._logged_channel.unary_unary(
|
| 646 |
+
"/google.longrunning.Operations/GetOperation",
|
| 647 |
+
request_serializer=operations_pb2.GetOperationRequest.SerializeToString,
|
| 648 |
+
response_deserializer=operations_pb2.Operation.FromString,
|
| 649 |
+
)
|
| 650 |
+
return self._stubs["get_operation"]
|
| 651 |
+
|
| 652 |
+
@property
|
| 653 |
+
def list_operations(
|
| 654 |
+
self,
|
| 655 |
+
) -> Callable[
|
| 656 |
+
[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse
|
| 657 |
+
]:
|
| 658 |
+
r"""Return a callable for the list_operations method over gRPC."""
|
| 659 |
+
# Generate a "stub function" on-the-fly which will actually make
|
| 660 |
+
# the request.
|
| 661 |
+
# gRPC handles serialization and deserialization, so we just need
|
| 662 |
+
# to pass in the functions for each.
|
| 663 |
+
if "list_operations" not in self._stubs:
|
| 664 |
+
self._stubs["list_operations"] = self._logged_channel.unary_unary(
|
| 665 |
+
"/google.longrunning.Operations/ListOperations",
|
| 666 |
+
request_serializer=operations_pb2.ListOperationsRequest.SerializeToString,
|
| 667 |
+
response_deserializer=operations_pb2.ListOperationsResponse.FromString,
|
| 668 |
+
)
|
| 669 |
+
return self._stubs["list_operations"]
|
| 670 |
+
|
| 671 |
+
|
| 672 |
+
__all__ = ("GenerativeServiceGrpcAsyncIOTransport",)
|
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/generative_service/transports/rest.py
ADDED
|
@@ -0,0 +1,1696 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
#
|
| 16 |
+
import dataclasses
|
| 17 |
+
import json # type: ignore
|
| 18 |
+
import logging
|
| 19 |
+
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union
|
| 20 |
+
import warnings
|
| 21 |
+
|
| 22 |
+
from google.api_core import exceptions as core_exceptions
|
| 23 |
+
from google.api_core import gapic_v1, rest_helpers, rest_streaming
|
| 24 |
+
from google.api_core import retry as retries
|
| 25 |
+
from google.auth import credentials as ga_credentials # type: ignore
|
| 26 |
+
from google.auth.transport.requests import AuthorizedSession # type: ignore
|
| 27 |
+
from google.longrunning import operations_pb2 # type: ignore
|
| 28 |
+
from google.protobuf import json_format
|
| 29 |
+
from requests import __version__ as requests_version
|
| 30 |
+
|
| 31 |
+
from google.ai.generativelanguage_v1beta.types import generative_service
|
| 32 |
+
|
| 33 |
+
from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO
|
| 34 |
+
from .rest_base import _BaseGenerativeServiceRestTransport
|
| 35 |
+
|
| 36 |
+
try:
|
| 37 |
+
OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None]
|
| 38 |
+
except AttributeError: # pragma: NO COVER
|
| 39 |
+
OptionalRetry = Union[retries.Retry, object, None] # type: ignore
|
| 40 |
+
|
| 41 |
+
try:
|
| 42 |
+
from google.api_core import client_logging # type: ignore
|
| 43 |
+
|
| 44 |
+
CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER
|
| 45 |
+
except ImportError: # pragma: NO COVER
|
| 46 |
+
CLIENT_LOGGING_SUPPORTED = False
|
| 47 |
+
|
| 48 |
+
_LOGGER = logging.getLogger(__name__)
|
| 49 |
+
|
| 50 |
+
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
|
| 51 |
+
gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
|
| 52 |
+
grpc_version=None,
|
| 53 |
+
rest_version=f"requests@{requests_version}",
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
class GenerativeServiceRestInterceptor:
|
| 58 |
+
"""Interceptor for GenerativeService.
|
| 59 |
+
|
| 60 |
+
Interceptors are used to manipulate requests, request metadata, and responses
|
| 61 |
+
in arbitrary ways.
|
| 62 |
+
Example use cases include:
|
| 63 |
+
* Logging
|
| 64 |
+
* Verifying requests according to service or custom semantics
|
| 65 |
+
* Stripping extraneous information from responses
|
| 66 |
+
|
| 67 |
+
These use cases and more can be enabled by injecting an
|
| 68 |
+
instance of a custom subclass when constructing the GenerativeServiceRestTransport.
|
| 69 |
+
|
| 70 |
+
.. code-block:: python
|
| 71 |
+
class MyCustomGenerativeServiceInterceptor(GenerativeServiceRestInterceptor):
|
| 72 |
+
def pre_batch_embed_contents(self, request, metadata):
|
| 73 |
+
logging.log(f"Received request: {request}")
|
| 74 |
+
return request, metadata
|
| 75 |
+
|
| 76 |
+
def post_batch_embed_contents(self, response):
|
| 77 |
+
logging.log(f"Received response: {response}")
|
| 78 |
+
return response
|
| 79 |
+
|
| 80 |
+
def pre_count_tokens(self, request, metadata):
|
| 81 |
+
logging.log(f"Received request: {request}")
|
| 82 |
+
return request, metadata
|
| 83 |
+
|
| 84 |
+
def post_count_tokens(self, response):
|
| 85 |
+
logging.log(f"Received response: {response}")
|
| 86 |
+
return response
|
| 87 |
+
|
| 88 |
+
def pre_embed_content(self, request, metadata):
|
| 89 |
+
logging.log(f"Received request: {request}")
|
| 90 |
+
return request, metadata
|
| 91 |
+
|
| 92 |
+
def post_embed_content(self, response):
|
| 93 |
+
logging.log(f"Received response: {response}")
|
| 94 |
+
return response
|
| 95 |
+
|
| 96 |
+
def pre_generate_answer(self, request, metadata):
|
| 97 |
+
logging.log(f"Received request: {request}")
|
| 98 |
+
return request, metadata
|
| 99 |
+
|
| 100 |
+
def post_generate_answer(self, response):
|
| 101 |
+
logging.log(f"Received response: {response}")
|
| 102 |
+
return response
|
| 103 |
+
|
| 104 |
+
def pre_generate_content(self, request, metadata):
|
| 105 |
+
logging.log(f"Received request: {request}")
|
| 106 |
+
return request, metadata
|
| 107 |
+
|
| 108 |
+
def post_generate_content(self, response):
|
| 109 |
+
logging.log(f"Received response: {response}")
|
| 110 |
+
return response
|
| 111 |
+
|
| 112 |
+
def pre_stream_generate_content(self, request, metadata):
|
| 113 |
+
logging.log(f"Received request: {request}")
|
| 114 |
+
return request, metadata
|
| 115 |
+
|
| 116 |
+
def post_stream_generate_content(self, response):
|
| 117 |
+
logging.log(f"Received response: {response}")
|
| 118 |
+
return response
|
| 119 |
+
|
| 120 |
+
transport = GenerativeServiceRestTransport(interceptor=MyCustomGenerativeServiceInterceptor())
|
| 121 |
+
client = GenerativeServiceClient(transport=transport)
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
"""
|
| 125 |
+
|
| 126 |
+
def pre_batch_embed_contents(
|
| 127 |
+
self,
|
| 128 |
+
request: generative_service.BatchEmbedContentsRequest,
|
| 129 |
+
metadata: Sequence[Tuple[str, Union[str, bytes]]],
|
| 130 |
+
) -> Tuple[
|
| 131 |
+
generative_service.BatchEmbedContentsRequest,
|
| 132 |
+
Sequence[Tuple[str, Union[str, bytes]]],
|
| 133 |
+
]:
|
| 134 |
+
"""Pre-rpc interceptor for batch_embed_contents
|
| 135 |
+
|
| 136 |
+
Override in a subclass to manipulate the request or metadata
|
| 137 |
+
before they are sent to the GenerativeService server.
|
| 138 |
+
"""
|
| 139 |
+
return request, metadata
|
| 140 |
+
|
| 141 |
+
def post_batch_embed_contents(
|
| 142 |
+
self, response: generative_service.BatchEmbedContentsResponse
|
| 143 |
+
) -> generative_service.BatchEmbedContentsResponse:
|
| 144 |
+
"""Post-rpc interceptor for batch_embed_contents
|
| 145 |
+
|
| 146 |
+
Override in a subclass to manipulate the response
|
| 147 |
+
after it is returned by the GenerativeService server but before
|
| 148 |
+
it is returned to user code.
|
| 149 |
+
"""
|
| 150 |
+
return response
|
| 151 |
+
|
| 152 |
+
def pre_count_tokens(
|
| 153 |
+
self,
|
| 154 |
+
request: generative_service.CountTokensRequest,
|
| 155 |
+
metadata: Sequence[Tuple[str, Union[str, bytes]]],
|
| 156 |
+
) -> Tuple[
|
| 157 |
+
generative_service.CountTokensRequest, Sequence[Tuple[str, Union[str, bytes]]]
|
| 158 |
+
]:
|
| 159 |
+
"""Pre-rpc interceptor for count_tokens
|
| 160 |
+
|
| 161 |
+
Override in a subclass to manipulate the request or metadata
|
| 162 |
+
before they are sent to the GenerativeService server.
|
| 163 |
+
"""
|
| 164 |
+
return request, metadata
|
| 165 |
+
|
| 166 |
+
def post_count_tokens(
|
| 167 |
+
self, response: generative_service.CountTokensResponse
|
| 168 |
+
) -> generative_service.CountTokensResponse:
|
| 169 |
+
"""Post-rpc interceptor for count_tokens
|
| 170 |
+
|
| 171 |
+
Override in a subclass to manipulate the response
|
| 172 |
+
after it is returned by the GenerativeService server but before
|
| 173 |
+
it is returned to user code.
|
| 174 |
+
"""
|
| 175 |
+
return response
|
| 176 |
+
|
| 177 |
+
def pre_embed_content(
|
| 178 |
+
self,
|
| 179 |
+
request: generative_service.EmbedContentRequest,
|
| 180 |
+
metadata: Sequence[Tuple[str, Union[str, bytes]]],
|
| 181 |
+
) -> Tuple[
|
| 182 |
+
generative_service.EmbedContentRequest, Sequence[Tuple[str, Union[str, bytes]]]
|
| 183 |
+
]:
|
| 184 |
+
"""Pre-rpc interceptor for embed_content
|
| 185 |
+
|
| 186 |
+
Override in a subclass to manipulate the request or metadata
|
| 187 |
+
before they are sent to the GenerativeService server.
|
| 188 |
+
"""
|
| 189 |
+
return request, metadata
|
| 190 |
+
|
| 191 |
+
def post_embed_content(
|
| 192 |
+
self, response: generative_service.EmbedContentResponse
|
| 193 |
+
) -> generative_service.EmbedContentResponse:
|
| 194 |
+
"""Post-rpc interceptor for embed_content
|
| 195 |
+
|
| 196 |
+
Override in a subclass to manipulate the response
|
| 197 |
+
after it is returned by the GenerativeService server but before
|
| 198 |
+
it is returned to user code.
|
| 199 |
+
"""
|
| 200 |
+
return response
|
| 201 |
+
|
| 202 |
+
def pre_generate_answer(
|
| 203 |
+
self,
|
| 204 |
+
request: generative_service.GenerateAnswerRequest,
|
| 205 |
+
metadata: Sequence[Tuple[str, Union[str, bytes]]],
|
| 206 |
+
) -> Tuple[
|
| 207 |
+
generative_service.GenerateAnswerRequest,
|
| 208 |
+
Sequence[Tuple[str, Union[str, bytes]]],
|
| 209 |
+
]:
|
| 210 |
+
"""Pre-rpc interceptor for generate_answer
|
| 211 |
+
|
| 212 |
+
Override in a subclass to manipulate the request or metadata
|
| 213 |
+
before they are sent to the GenerativeService server.
|
| 214 |
+
"""
|
| 215 |
+
return request, metadata
|
| 216 |
+
|
| 217 |
+
def post_generate_answer(
|
| 218 |
+
self, response: generative_service.GenerateAnswerResponse
|
| 219 |
+
) -> generative_service.GenerateAnswerResponse:
|
| 220 |
+
"""Post-rpc interceptor for generate_answer
|
| 221 |
+
|
| 222 |
+
Override in a subclass to manipulate the response
|
| 223 |
+
after it is returned by the GenerativeService server but before
|
| 224 |
+
it is returned to user code.
|
| 225 |
+
"""
|
| 226 |
+
return response
|
| 227 |
+
|
| 228 |
+
def pre_generate_content(
|
| 229 |
+
self,
|
| 230 |
+
request: generative_service.GenerateContentRequest,
|
| 231 |
+
metadata: Sequence[Tuple[str, Union[str, bytes]]],
|
| 232 |
+
) -> Tuple[
|
| 233 |
+
generative_service.GenerateContentRequest,
|
| 234 |
+
Sequence[Tuple[str, Union[str, bytes]]],
|
| 235 |
+
]:
|
| 236 |
+
"""Pre-rpc interceptor for generate_content
|
| 237 |
+
|
| 238 |
+
Override in a subclass to manipulate the request or metadata
|
| 239 |
+
before they are sent to the GenerativeService server.
|
| 240 |
+
"""
|
| 241 |
+
return request, metadata
|
| 242 |
+
|
| 243 |
+
def post_generate_content(
|
| 244 |
+
self, response: generative_service.GenerateContentResponse
|
| 245 |
+
) -> generative_service.GenerateContentResponse:
|
| 246 |
+
"""Post-rpc interceptor for generate_content
|
| 247 |
+
|
| 248 |
+
Override in a subclass to manipulate the response
|
| 249 |
+
after it is returned by the GenerativeService server but before
|
| 250 |
+
it is returned to user code.
|
| 251 |
+
"""
|
| 252 |
+
return response
|
| 253 |
+
|
| 254 |
+
def pre_stream_generate_content(
|
| 255 |
+
self,
|
| 256 |
+
request: generative_service.GenerateContentRequest,
|
| 257 |
+
metadata: Sequence[Tuple[str, Union[str, bytes]]],
|
| 258 |
+
) -> Tuple[
|
| 259 |
+
generative_service.GenerateContentRequest,
|
| 260 |
+
Sequence[Tuple[str, Union[str, bytes]]],
|
| 261 |
+
]:
|
| 262 |
+
"""Pre-rpc interceptor for stream_generate_content
|
| 263 |
+
|
| 264 |
+
Override in a subclass to manipulate the request or metadata
|
| 265 |
+
before they are sent to the GenerativeService server.
|
| 266 |
+
"""
|
| 267 |
+
return request, metadata
|
| 268 |
+
|
| 269 |
+
def post_stream_generate_content(
|
| 270 |
+
self, response: rest_streaming.ResponseIterator
|
| 271 |
+
) -> rest_streaming.ResponseIterator:
|
| 272 |
+
"""Post-rpc interceptor for stream_generate_content
|
| 273 |
+
|
| 274 |
+
Override in a subclass to manipulate the response
|
| 275 |
+
after it is returned by the GenerativeService server but before
|
| 276 |
+
it is returned to user code.
|
| 277 |
+
"""
|
| 278 |
+
return response
|
| 279 |
+
|
| 280 |
+
def pre_get_operation(
|
| 281 |
+
self,
|
| 282 |
+
request: operations_pb2.GetOperationRequest,
|
| 283 |
+
metadata: Sequence[Tuple[str, Union[str, bytes]]],
|
| 284 |
+
) -> Tuple[
|
| 285 |
+
operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]
|
| 286 |
+
]:
|
| 287 |
+
"""Pre-rpc interceptor for get_operation
|
| 288 |
+
|
| 289 |
+
Override in a subclass to manipulate the request or metadata
|
| 290 |
+
before they are sent to the GenerativeService server.
|
| 291 |
+
"""
|
| 292 |
+
return request, metadata
|
| 293 |
+
|
| 294 |
+
def post_get_operation(
|
| 295 |
+
self, response: operations_pb2.Operation
|
| 296 |
+
) -> operations_pb2.Operation:
|
| 297 |
+
"""Post-rpc interceptor for get_operation
|
| 298 |
+
|
| 299 |
+
Override in a subclass to manipulate the response
|
| 300 |
+
after it is returned by the GenerativeService server but before
|
| 301 |
+
it is returned to user code.
|
| 302 |
+
"""
|
| 303 |
+
return response
|
| 304 |
+
|
| 305 |
+
def pre_list_operations(
|
| 306 |
+
self,
|
| 307 |
+
request: operations_pb2.ListOperationsRequest,
|
| 308 |
+
metadata: Sequence[Tuple[str, Union[str, bytes]]],
|
| 309 |
+
) -> Tuple[
|
| 310 |
+
operations_pb2.ListOperationsRequest, Sequence[Tuple[str, Union[str, bytes]]]
|
| 311 |
+
]:
|
| 312 |
+
"""Pre-rpc interceptor for list_operations
|
| 313 |
+
|
| 314 |
+
Override in a subclass to manipulate the request or metadata
|
| 315 |
+
before they are sent to the GenerativeService server.
|
| 316 |
+
"""
|
| 317 |
+
return request, metadata
|
| 318 |
+
|
| 319 |
+
def post_list_operations(
|
| 320 |
+
self, response: operations_pb2.ListOperationsResponse
|
| 321 |
+
) -> operations_pb2.ListOperationsResponse:
|
| 322 |
+
"""Post-rpc interceptor for list_operations
|
| 323 |
+
|
| 324 |
+
Override in a subclass to manipulate the response
|
| 325 |
+
after it is returned by the GenerativeService server but before
|
| 326 |
+
it is returned to user code.
|
| 327 |
+
"""
|
| 328 |
+
return response
|
| 329 |
+
|
| 330 |
+
|
| 331 |
+
@dataclasses.dataclass
|
| 332 |
+
class GenerativeServiceRestStub:
|
| 333 |
+
_session: AuthorizedSession
|
| 334 |
+
_host: str
|
| 335 |
+
_interceptor: GenerativeServiceRestInterceptor
|
| 336 |
+
|
| 337 |
+
|
| 338 |
+
class GenerativeServiceRestTransport(_BaseGenerativeServiceRestTransport):
|
| 339 |
+
"""REST backend synchronous transport for GenerativeService.
|
| 340 |
+
|
| 341 |
+
API for using Large Models that generate multimodal content
|
| 342 |
+
and have additional capabilities beyond text generation.
|
| 343 |
+
|
| 344 |
+
This class defines the same methods as the primary client, so the
|
| 345 |
+
primary client can load the underlying transport implementation
|
| 346 |
+
and call it.
|
| 347 |
+
|
| 348 |
+
It sends JSON representations of protocol buffers over HTTP/1.1
|
| 349 |
+
"""
|
| 350 |
+
|
| 351 |
+
def __init__(
|
| 352 |
+
self,
|
| 353 |
+
*,
|
| 354 |
+
host: str = "generativelanguage.googleapis.com",
|
| 355 |
+
credentials: Optional[ga_credentials.Credentials] = None,
|
| 356 |
+
credentials_file: Optional[str] = None,
|
| 357 |
+
scopes: Optional[Sequence[str]] = None,
|
| 358 |
+
client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None,
|
| 359 |
+
quota_project_id: Optional[str] = None,
|
| 360 |
+
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
|
| 361 |
+
always_use_jwt_access: Optional[bool] = False,
|
| 362 |
+
url_scheme: str = "https",
|
| 363 |
+
interceptor: Optional[GenerativeServiceRestInterceptor] = None,
|
| 364 |
+
api_audience: Optional[str] = None,
|
| 365 |
+
) -> None:
|
| 366 |
+
"""Instantiate the transport.
|
| 367 |
+
|
| 368 |
+
Args:
|
| 369 |
+
host (Optional[str]):
|
| 370 |
+
The hostname to connect to (default: 'generativelanguage.googleapis.com').
|
| 371 |
+
credentials (Optional[google.auth.credentials.Credentials]): The
|
| 372 |
+
authorization credentials to attach to requests. These
|
| 373 |
+
credentials identify the application to the service; if none
|
| 374 |
+
are specified, the client will attempt to ascertain the
|
| 375 |
+
credentials from the environment.
|
| 376 |
+
|
| 377 |
+
credentials_file (Optional[str]): A file with credentials that can
|
| 378 |
+
be loaded with :func:`google.auth.load_credentials_from_file`.
|
| 379 |
+
This argument is ignored if ``channel`` is provided.
|
| 380 |
+
scopes (Optional(Sequence[str])): A list of scopes. This argument is
|
| 381 |
+
ignored if ``channel`` is provided.
|
| 382 |
+
client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client
|
| 383 |
+
certificate to configure mutual TLS HTTP channel. It is ignored
|
| 384 |
+
if ``channel`` is provided.
|
| 385 |
+
quota_project_id (Optional[str]): An optional project to use for billing
|
| 386 |
+
and quota.
|
| 387 |
+
client_info (google.api_core.gapic_v1.client_info.ClientInfo):
|
| 388 |
+
The client info used to send a user-agent string along with
|
| 389 |
+
API requests. If ``None``, then default info will be used.
|
| 390 |
+
Generally, you only need to set this if you are developing
|
| 391 |
+
your own client library.
|
| 392 |
+
always_use_jwt_access (Optional[bool]): Whether self signed JWT should
|
| 393 |
+
be used for service account credentials.
|
| 394 |
+
url_scheme: the protocol scheme for the API endpoint. Normally
|
| 395 |
+
"https", but for testing or local servers,
|
| 396 |
+
"http" can be specified.
|
| 397 |
+
"""
|
| 398 |
+
# Run the base constructor
|
| 399 |
+
# TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc.
|
| 400 |
+
# TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the
|
| 401 |
+
# credentials object
|
| 402 |
+
super().__init__(
|
| 403 |
+
host=host,
|
| 404 |
+
credentials=credentials,
|
| 405 |
+
client_info=client_info,
|
| 406 |
+
always_use_jwt_access=always_use_jwt_access,
|
| 407 |
+
url_scheme=url_scheme,
|
| 408 |
+
api_audience=api_audience,
|
| 409 |
+
)
|
| 410 |
+
self._session = AuthorizedSession(
|
| 411 |
+
self._credentials, default_host=self.DEFAULT_HOST
|
| 412 |
+
)
|
| 413 |
+
if client_cert_source_for_mtls:
|
| 414 |
+
self._session.configure_mtls_channel(client_cert_source_for_mtls)
|
| 415 |
+
self._interceptor = interceptor or GenerativeServiceRestInterceptor()
|
| 416 |
+
self._prep_wrapped_messages(client_info)
|
| 417 |
+
|
| 418 |
+
class _BatchEmbedContents(
|
| 419 |
+
_BaseGenerativeServiceRestTransport._BaseBatchEmbedContents,
|
| 420 |
+
GenerativeServiceRestStub,
|
| 421 |
+
):
|
| 422 |
+
def __hash__(self):
|
| 423 |
+
return hash("GenerativeServiceRestTransport.BatchEmbedContents")
|
| 424 |
+
|
| 425 |
+
@staticmethod
|
| 426 |
+
def _get_response(
|
| 427 |
+
host,
|
| 428 |
+
metadata,
|
| 429 |
+
query_params,
|
| 430 |
+
session,
|
| 431 |
+
timeout,
|
| 432 |
+
transcoded_request,
|
| 433 |
+
body=None,
|
| 434 |
+
):
|
| 435 |
+
uri = transcoded_request["uri"]
|
| 436 |
+
method = transcoded_request["method"]
|
| 437 |
+
headers = dict(metadata)
|
| 438 |
+
headers["Content-Type"] = "application/json"
|
| 439 |
+
response = getattr(session, method)(
|
| 440 |
+
"{host}{uri}".format(host=host, uri=uri),
|
| 441 |
+
timeout=timeout,
|
| 442 |
+
headers=headers,
|
| 443 |
+
params=rest_helpers.flatten_query_params(query_params, strict=True),
|
| 444 |
+
data=body,
|
| 445 |
+
)
|
| 446 |
+
return response
|
| 447 |
+
|
| 448 |
+
def __call__(
|
| 449 |
+
self,
|
| 450 |
+
request: generative_service.BatchEmbedContentsRequest,
|
| 451 |
+
*,
|
| 452 |
+
retry: OptionalRetry = gapic_v1.method.DEFAULT,
|
| 453 |
+
timeout: Optional[float] = None,
|
| 454 |
+
metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
|
| 455 |
+
) -> generative_service.BatchEmbedContentsResponse:
|
| 456 |
+
r"""Call the batch embed contents method over HTTP.
|
| 457 |
+
|
| 458 |
+
Args:
|
| 459 |
+
request (~.generative_service.BatchEmbedContentsRequest):
|
| 460 |
+
The request object. Batch request to get embeddings from
|
| 461 |
+
the model for a list of prompts.
|
| 462 |
+
retry (google.api_core.retry.Retry): Designation of what errors, if any,
|
| 463 |
+
should be retried.
|
| 464 |
+
timeout (float): The timeout for this request.
|
| 465 |
+
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
|
| 466 |
+
sent along with the request as metadata. Normally, each value must be of type `str`,
|
| 467 |
+
but for metadata keys ending with the suffix `-bin`, the corresponding values must
|
| 468 |
+
be of type `bytes`.
|
| 469 |
+
|
| 470 |
+
Returns:
|
| 471 |
+
~.generative_service.BatchEmbedContentsResponse:
|
| 472 |
+
The response to a ``BatchEmbedContentsRequest``.
|
| 473 |
+
"""
|
| 474 |
+
|
| 475 |
+
http_options = (
|
| 476 |
+
_BaseGenerativeServiceRestTransport._BaseBatchEmbedContents._get_http_options()
|
| 477 |
+
)
|
| 478 |
+
|
| 479 |
+
request, metadata = self._interceptor.pre_batch_embed_contents(
|
| 480 |
+
request, metadata
|
| 481 |
+
)
|
| 482 |
+
transcoded_request = _BaseGenerativeServiceRestTransport._BaseBatchEmbedContents._get_transcoded_request(
|
| 483 |
+
http_options, request
|
| 484 |
+
)
|
| 485 |
+
|
| 486 |
+
body = _BaseGenerativeServiceRestTransport._BaseBatchEmbedContents._get_request_body_json(
|
| 487 |
+
transcoded_request
|
| 488 |
+
)
|
| 489 |
+
|
| 490 |
+
# Jsonify the query params
|
| 491 |
+
query_params = _BaseGenerativeServiceRestTransport._BaseBatchEmbedContents._get_query_params_json(
|
| 492 |
+
transcoded_request
|
| 493 |
+
)
|
| 494 |
+
|
| 495 |
+
if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
|
| 496 |
+
logging.DEBUG
|
| 497 |
+
): # pragma: NO COVER
|
| 498 |
+
request_url = "{host}{uri}".format(
|
| 499 |
+
host=self._host, uri=transcoded_request["uri"]
|
| 500 |
+
)
|
| 501 |
+
method = transcoded_request["method"]
|
| 502 |
+
try:
|
| 503 |
+
request_payload = type(request).to_json(request)
|
| 504 |
+
except:
|
| 505 |
+
request_payload = None
|
| 506 |
+
http_request = {
|
| 507 |
+
"payload": request_payload,
|
| 508 |
+
"requestMethod": method,
|
| 509 |
+
"requestUrl": request_url,
|
| 510 |
+
"headers": dict(metadata),
|
| 511 |
+
}
|
| 512 |
+
_LOGGER.debug(
|
| 513 |
+
f"Sending request for google.ai.generativelanguage_v1beta.GenerativeServiceClient.BatchEmbedContents",
|
| 514 |
+
extra={
|
| 515 |
+
"serviceName": "google.ai.generativelanguage.v1beta.GenerativeService",
|
| 516 |
+
"rpcName": "BatchEmbedContents",
|
| 517 |
+
"httpRequest": http_request,
|
| 518 |
+
"metadata": http_request["headers"],
|
| 519 |
+
},
|
| 520 |
+
)
|
| 521 |
+
|
| 522 |
+
# Send the request
|
| 523 |
+
response = GenerativeServiceRestTransport._BatchEmbedContents._get_response(
|
| 524 |
+
self._host,
|
| 525 |
+
metadata,
|
| 526 |
+
query_params,
|
| 527 |
+
self._session,
|
| 528 |
+
timeout,
|
| 529 |
+
transcoded_request,
|
| 530 |
+
body,
|
| 531 |
+
)
|
| 532 |
+
|
| 533 |
+
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
|
| 534 |
+
# subclass.
|
| 535 |
+
if response.status_code >= 400:
|
| 536 |
+
raise core_exceptions.from_http_response(response)
|
| 537 |
+
|
| 538 |
+
# Return the response
|
| 539 |
+
resp = generative_service.BatchEmbedContentsResponse()
|
| 540 |
+
pb_resp = generative_service.BatchEmbedContentsResponse.pb(resp)
|
| 541 |
+
|
| 542 |
+
json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
|
| 543 |
+
|
| 544 |
+
resp = self._interceptor.post_batch_embed_contents(resp)
|
| 545 |
+
if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
|
| 546 |
+
logging.DEBUG
|
| 547 |
+
): # pragma: NO COVER
|
| 548 |
+
try:
|
| 549 |
+
response_payload = (
|
| 550 |
+
generative_service.BatchEmbedContentsResponse.to_json(response)
|
| 551 |
+
)
|
| 552 |
+
except:
|
| 553 |
+
response_payload = None
|
| 554 |
+
http_response = {
|
| 555 |
+
"payload": response_payload,
|
| 556 |
+
"headers": dict(response.headers),
|
| 557 |
+
"status": response.status_code,
|
| 558 |
+
}
|
| 559 |
+
_LOGGER.debug(
|
| 560 |
+
"Received response for google.ai.generativelanguage_v1beta.GenerativeServiceClient.batch_embed_contents",
|
| 561 |
+
extra={
|
| 562 |
+
"serviceName": "google.ai.generativelanguage.v1beta.GenerativeService",
|
| 563 |
+
"rpcName": "BatchEmbedContents",
|
| 564 |
+
"metadata": http_response["headers"],
|
| 565 |
+
"httpResponse": http_response,
|
| 566 |
+
},
|
| 567 |
+
)
|
| 568 |
+
return resp
|
| 569 |
+
|
| 570 |
+
class _CountTokens(
|
| 571 |
+
_BaseGenerativeServiceRestTransport._BaseCountTokens, GenerativeServiceRestStub
|
| 572 |
+
):
|
| 573 |
+
def __hash__(self):
|
| 574 |
+
return hash("GenerativeServiceRestTransport.CountTokens")
|
| 575 |
+
|
| 576 |
+
@staticmethod
|
| 577 |
+
def _get_response(
|
| 578 |
+
host,
|
| 579 |
+
metadata,
|
| 580 |
+
query_params,
|
| 581 |
+
session,
|
| 582 |
+
timeout,
|
| 583 |
+
transcoded_request,
|
| 584 |
+
body=None,
|
| 585 |
+
):
|
| 586 |
+
uri = transcoded_request["uri"]
|
| 587 |
+
method = transcoded_request["method"]
|
| 588 |
+
headers = dict(metadata)
|
| 589 |
+
headers["Content-Type"] = "application/json"
|
| 590 |
+
response = getattr(session, method)(
|
| 591 |
+
"{host}{uri}".format(host=host, uri=uri),
|
| 592 |
+
timeout=timeout,
|
| 593 |
+
headers=headers,
|
| 594 |
+
params=rest_helpers.flatten_query_params(query_params, strict=True),
|
| 595 |
+
data=body,
|
| 596 |
+
)
|
| 597 |
+
return response
|
| 598 |
+
|
| 599 |
+
def __call__(
|
| 600 |
+
self,
|
| 601 |
+
request: generative_service.CountTokensRequest,
|
| 602 |
+
*,
|
| 603 |
+
retry: OptionalRetry = gapic_v1.method.DEFAULT,
|
| 604 |
+
timeout: Optional[float] = None,
|
| 605 |
+
metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
|
| 606 |
+
) -> generative_service.CountTokensResponse:
|
| 607 |
+
r"""Call the count tokens method over HTTP.
|
| 608 |
+
|
| 609 |
+
Args:
|
| 610 |
+
request (~.generative_service.CountTokensRequest):
|
| 611 |
+
The request object. Counts the number of tokens in the ``prompt`` sent to a
|
| 612 |
+
model.
|
| 613 |
+
|
| 614 |
+
Models may tokenize text differently, so each model may
|
| 615 |
+
return a different ``token_count``.
|
| 616 |
+
retry (google.api_core.retry.Retry): Designation of what errors, if any,
|
| 617 |
+
should be retried.
|
| 618 |
+
timeout (float): The timeout for this request.
|
| 619 |
+
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
|
| 620 |
+
sent along with the request as metadata. Normally, each value must be of type `str`,
|
| 621 |
+
but for metadata keys ending with the suffix `-bin`, the corresponding values must
|
| 622 |
+
be of type `bytes`.
|
| 623 |
+
|
| 624 |
+
Returns:
|
| 625 |
+
~.generative_service.CountTokensResponse:
|
| 626 |
+
A response from ``CountTokens``.
|
| 627 |
+
|
| 628 |
+
It returns the model's ``token_count`` for the
|
| 629 |
+
``prompt``.
|
| 630 |
+
|
| 631 |
+
"""
|
| 632 |
+
|
| 633 |
+
http_options = (
|
| 634 |
+
_BaseGenerativeServiceRestTransport._BaseCountTokens._get_http_options()
|
| 635 |
+
)
|
| 636 |
+
|
| 637 |
+
request, metadata = self._interceptor.pre_count_tokens(request, metadata)
|
| 638 |
+
transcoded_request = _BaseGenerativeServiceRestTransport._BaseCountTokens._get_transcoded_request(
|
| 639 |
+
http_options, request
|
| 640 |
+
)
|
| 641 |
+
|
| 642 |
+
body = _BaseGenerativeServiceRestTransport._BaseCountTokens._get_request_body_json(
|
| 643 |
+
transcoded_request
|
| 644 |
+
)
|
| 645 |
+
|
| 646 |
+
# Jsonify the query params
|
| 647 |
+
query_params = _BaseGenerativeServiceRestTransport._BaseCountTokens._get_query_params_json(
|
| 648 |
+
transcoded_request
|
| 649 |
+
)
|
| 650 |
+
|
| 651 |
+
if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
|
| 652 |
+
logging.DEBUG
|
| 653 |
+
): # pragma: NO COVER
|
| 654 |
+
request_url = "{host}{uri}".format(
|
| 655 |
+
host=self._host, uri=transcoded_request["uri"]
|
| 656 |
+
)
|
| 657 |
+
method = transcoded_request["method"]
|
| 658 |
+
try:
|
| 659 |
+
request_payload = type(request).to_json(request)
|
| 660 |
+
except:
|
| 661 |
+
request_payload = None
|
| 662 |
+
http_request = {
|
| 663 |
+
"payload": request_payload,
|
| 664 |
+
"requestMethod": method,
|
| 665 |
+
"requestUrl": request_url,
|
| 666 |
+
"headers": dict(metadata),
|
| 667 |
+
}
|
| 668 |
+
_LOGGER.debug(
|
| 669 |
+
f"Sending request for google.ai.generativelanguage_v1beta.GenerativeServiceClient.CountTokens",
|
| 670 |
+
extra={
|
| 671 |
+
"serviceName": "google.ai.generativelanguage.v1beta.GenerativeService",
|
| 672 |
+
"rpcName": "CountTokens",
|
| 673 |
+
"httpRequest": http_request,
|
| 674 |
+
"metadata": http_request["headers"],
|
| 675 |
+
},
|
| 676 |
+
)
|
| 677 |
+
|
| 678 |
+
# Send the request
|
| 679 |
+
response = GenerativeServiceRestTransport._CountTokens._get_response(
|
| 680 |
+
self._host,
|
| 681 |
+
metadata,
|
| 682 |
+
query_params,
|
| 683 |
+
self._session,
|
| 684 |
+
timeout,
|
| 685 |
+
transcoded_request,
|
| 686 |
+
body,
|
| 687 |
+
)
|
| 688 |
+
|
| 689 |
+
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
|
| 690 |
+
# subclass.
|
| 691 |
+
if response.status_code >= 400:
|
| 692 |
+
raise core_exceptions.from_http_response(response)
|
| 693 |
+
|
| 694 |
+
# Return the response
|
| 695 |
+
resp = generative_service.CountTokensResponse()
|
| 696 |
+
pb_resp = generative_service.CountTokensResponse.pb(resp)
|
| 697 |
+
|
| 698 |
+
json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
|
| 699 |
+
|
| 700 |
+
resp = self._interceptor.post_count_tokens(resp)
|
| 701 |
+
if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
|
| 702 |
+
logging.DEBUG
|
| 703 |
+
): # pragma: NO COVER
|
| 704 |
+
try:
|
| 705 |
+
response_payload = generative_service.CountTokensResponse.to_json(
|
| 706 |
+
response
|
| 707 |
+
)
|
| 708 |
+
except:
|
| 709 |
+
response_payload = None
|
| 710 |
+
http_response = {
|
| 711 |
+
"payload": response_payload,
|
| 712 |
+
"headers": dict(response.headers),
|
| 713 |
+
"status": response.status_code,
|
| 714 |
+
}
|
| 715 |
+
_LOGGER.debug(
|
| 716 |
+
"Received response for google.ai.generativelanguage_v1beta.GenerativeServiceClient.count_tokens",
|
| 717 |
+
extra={
|
| 718 |
+
"serviceName": "google.ai.generativelanguage.v1beta.GenerativeService",
|
| 719 |
+
"rpcName": "CountTokens",
|
| 720 |
+
"metadata": http_response["headers"],
|
| 721 |
+
"httpResponse": http_response,
|
| 722 |
+
},
|
| 723 |
+
)
|
| 724 |
+
return resp
|
| 725 |
+
|
| 726 |
+
class _EmbedContent(
|
| 727 |
+
_BaseGenerativeServiceRestTransport._BaseEmbedContent, GenerativeServiceRestStub
|
| 728 |
+
):
|
| 729 |
+
def __hash__(self):
|
| 730 |
+
return hash("GenerativeServiceRestTransport.EmbedContent")
|
| 731 |
+
|
| 732 |
+
@staticmethod
|
| 733 |
+
def _get_response(
|
| 734 |
+
host,
|
| 735 |
+
metadata,
|
| 736 |
+
query_params,
|
| 737 |
+
session,
|
| 738 |
+
timeout,
|
| 739 |
+
transcoded_request,
|
| 740 |
+
body=None,
|
| 741 |
+
):
|
| 742 |
+
uri = transcoded_request["uri"]
|
| 743 |
+
method = transcoded_request["method"]
|
| 744 |
+
headers = dict(metadata)
|
| 745 |
+
headers["Content-Type"] = "application/json"
|
| 746 |
+
response = getattr(session, method)(
|
| 747 |
+
"{host}{uri}".format(host=host, uri=uri),
|
| 748 |
+
timeout=timeout,
|
| 749 |
+
headers=headers,
|
| 750 |
+
params=rest_helpers.flatten_query_params(query_params, strict=True),
|
| 751 |
+
data=body,
|
| 752 |
+
)
|
| 753 |
+
return response
|
| 754 |
+
|
| 755 |
+
def __call__(
|
| 756 |
+
self,
|
| 757 |
+
request: generative_service.EmbedContentRequest,
|
| 758 |
+
*,
|
| 759 |
+
retry: OptionalRetry = gapic_v1.method.DEFAULT,
|
| 760 |
+
timeout: Optional[float] = None,
|
| 761 |
+
metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
|
| 762 |
+
) -> generative_service.EmbedContentResponse:
|
| 763 |
+
r"""Call the embed content method over HTTP.
|
| 764 |
+
|
| 765 |
+
Args:
|
| 766 |
+
request (~.generative_service.EmbedContentRequest):
|
| 767 |
+
The request object. Request containing the ``Content`` for the model to
|
| 768 |
+
embed.
|
| 769 |
+
retry (google.api_core.retry.Retry): Designation of what errors, if any,
|
| 770 |
+
should be retried.
|
| 771 |
+
timeout (float): The timeout for this request.
|
| 772 |
+
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
|
| 773 |
+
sent along with the request as metadata. Normally, each value must be of type `str`,
|
| 774 |
+
but for metadata keys ending with the suffix `-bin`, the corresponding values must
|
| 775 |
+
be of type `bytes`.
|
| 776 |
+
|
| 777 |
+
Returns:
|
| 778 |
+
~.generative_service.EmbedContentResponse:
|
| 779 |
+
The response to an ``EmbedContentRequest``.
|
| 780 |
+
"""
|
| 781 |
+
|
| 782 |
+
http_options = (
|
| 783 |
+
_BaseGenerativeServiceRestTransport._BaseEmbedContent._get_http_options()
|
| 784 |
+
)
|
| 785 |
+
|
| 786 |
+
request, metadata = self._interceptor.pre_embed_content(request, metadata)
|
| 787 |
+
transcoded_request = _BaseGenerativeServiceRestTransport._BaseEmbedContent._get_transcoded_request(
|
| 788 |
+
http_options, request
|
| 789 |
+
)
|
| 790 |
+
|
| 791 |
+
body = _BaseGenerativeServiceRestTransport._BaseEmbedContent._get_request_body_json(
|
| 792 |
+
transcoded_request
|
| 793 |
+
)
|
| 794 |
+
|
| 795 |
+
# Jsonify the query params
|
| 796 |
+
query_params = _BaseGenerativeServiceRestTransport._BaseEmbedContent._get_query_params_json(
|
| 797 |
+
transcoded_request
|
| 798 |
+
)
|
| 799 |
+
|
| 800 |
+
if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
|
| 801 |
+
logging.DEBUG
|
| 802 |
+
): # pragma: NO COVER
|
| 803 |
+
request_url = "{host}{uri}".format(
|
| 804 |
+
host=self._host, uri=transcoded_request["uri"]
|
| 805 |
+
)
|
| 806 |
+
method = transcoded_request["method"]
|
| 807 |
+
try:
|
| 808 |
+
request_payload = type(request).to_json(request)
|
| 809 |
+
except:
|
| 810 |
+
request_payload = None
|
| 811 |
+
http_request = {
|
| 812 |
+
"payload": request_payload,
|
| 813 |
+
"requestMethod": method,
|
| 814 |
+
"requestUrl": request_url,
|
| 815 |
+
"headers": dict(metadata),
|
| 816 |
+
}
|
| 817 |
+
_LOGGER.debug(
|
| 818 |
+
f"Sending request for google.ai.generativelanguage_v1beta.GenerativeServiceClient.EmbedContent",
|
| 819 |
+
extra={
|
| 820 |
+
"serviceName": "google.ai.generativelanguage.v1beta.GenerativeService",
|
| 821 |
+
"rpcName": "EmbedContent",
|
| 822 |
+
"httpRequest": http_request,
|
| 823 |
+
"metadata": http_request["headers"],
|
| 824 |
+
},
|
| 825 |
+
)
|
| 826 |
+
|
| 827 |
+
# Send the request
|
| 828 |
+
response = GenerativeServiceRestTransport._EmbedContent._get_response(
|
| 829 |
+
self._host,
|
| 830 |
+
metadata,
|
| 831 |
+
query_params,
|
| 832 |
+
self._session,
|
| 833 |
+
timeout,
|
| 834 |
+
transcoded_request,
|
| 835 |
+
body,
|
| 836 |
+
)
|
| 837 |
+
|
| 838 |
+
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
|
| 839 |
+
# subclass.
|
| 840 |
+
if response.status_code >= 400:
|
| 841 |
+
raise core_exceptions.from_http_response(response)
|
| 842 |
+
|
| 843 |
+
# Return the response
|
| 844 |
+
resp = generative_service.EmbedContentResponse()
|
| 845 |
+
pb_resp = generative_service.EmbedContentResponse.pb(resp)
|
| 846 |
+
|
| 847 |
+
json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
|
| 848 |
+
|
| 849 |
+
resp = self._interceptor.post_embed_content(resp)
|
| 850 |
+
if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
|
| 851 |
+
logging.DEBUG
|
| 852 |
+
): # pragma: NO COVER
|
| 853 |
+
try:
|
| 854 |
+
response_payload = generative_service.EmbedContentResponse.to_json(
|
| 855 |
+
response
|
| 856 |
+
)
|
| 857 |
+
except:
|
| 858 |
+
response_payload = None
|
| 859 |
+
http_response = {
|
| 860 |
+
"payload": response_payload,
|
| 861 |
+
"headers": dict(response.headers),
|
| 862 |
+
"status": response.status_code,
|
| 863 |
+
}
|
| 864 |
+
_LOGGER.debug(
|
| 865 |
+
"Received response for google.ai.generativelanguage_v1beta.GenerativeServiceClient.embed_content",
|
| 866 |
+
extra={
|
| 867 |
+
"serviceName": "google.ai.generativelanguage.v1beta.GenerativeService",
|
| 868 |
+
"rpcName": "EmbedContent",
|
| 869 |
+
"metadata": http_response["headers"],
|
| 870 |
+
"httpResponse": http_response,
|
| 871 |
+
},
|
| 872 |
+
)
|
| 873 |
+
return resp
|
| 874 |
+
|
| 875 |
+
class _GenerateAnswer(
|
| 876 |
+
_BaseGenerativeServiceRestTransport._BaseGenerateAnswer,
|
| 877 |
+
GenerativeServiceRestStub,
|
| 878 |
+
):
|
| 879 |
+
def __hash__(self):
|
| 880 |
+
return hash("GenerativeServiceRestTransport.GenerateAnswer")
|
| 881 |
+
|
| 882 |
+
@staticmethod
|
| 883 |
+
def _get_response(
|
| 884 |
+
host,
|
| 885 |
+
metadata,
|
| 886 |
+
query_params,
|
| 887 |
+
session,
|
| 888 |
+
timeout,
|
| 889 |
+
transcoded_request,
|
| 890 |
+
body=None,
|
| 891 |
+
):
|
| 892 |
+
uri = transcoded_request["uri"]
|
| 893 |
+
method = transcoded_request["method"]
|
| 894 |
+
headers = dict(metadata)
|
| 895 |
+
headers["Content-Type"] = "application/json"
|
| 896 |
+
response = getattr(session, method)(
|
| 897 |
+
"{host}{uri}".format(host=host, uri=uri),
|
| 898 |
+
timeout=timeout,
|
| 899 |
+
headers=headers,
|
| 900 |
+
params=rest_helpers.flatten_query_params(query_params, strict=True),
|
| 901 |
+
data=body,
|
| 902 |
+
)
|
| 903 |
+
return response
|
| 904 |
+
|
| 905 |
+
def __call__(
|
| 906 |
+
self,
|
| 907 |
+
request: generative_service.GenerateAnswerRequest,
|
| 908 |
+
*,
|
| 909 |
+
retry: OptionalRetry = gapic_v1.method.DEFAULT,
|
| 910 |
+
timeout: Optional[float] = None,
|
| 911 |
+
metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
|
| 912 |
+
) -> generative_service.GenerateAnswerResponse:
|
| 913 |
+
r"""Call the generate answer method over HTTP.
|
| 914 |
+
|
| 915 |
+
Args:
|
| 916 |
+
request (~.generative_service.GenerateAnswerRequest):
|
| 917 |
+
The request object. Request to generate a grounded answer from the
|
| 918 |
+
``Model``.
|
| 919 |
+
retry (google.api_core.retry.Retry): Designation of what errors, if any,
|
| 920 |
+
should be retried.
|
| 921 |
+
timeout (float): The timeout for this request.
|
| 922 |
+
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
|
| 923 |
+
sent along with the request as metadata. Normally, each value must be of type `str`,
|
| 924 |
+
but for metadata keys ending with the suffix `-bin`, the corresponding values must
|
| 925 |
+
be of type `bytes`.
|
| 926 |
+
|
| 927 |
+
Returns:
|
| 928 |
+
~.generative_service.GenerateAnswerResponse:
|
| 929 |
+
Response from the model for a
|
| 930 |
+
grounded answer.
|
| 931 |
+
|
| 932 |
+
"""
|
| 933 |
+
|
| 934 |
+
http_options = (
|
| 935 |
+
_BaseGenerativeServiceRestTransport._BaseGenerateAnswer._get_http_options()
|
| 936 |
+
)
|
| 937 |
+
|
| 938 |
+
request, metadata = self._interceptor.pre_generate_answer(request, metadata)
|
| 939 |
+
transcoded_request = _BaseGenerativeServiceRestTransport._BaseGenerateAnswer._get_transcoded_request(
|
| 940 |
+
http_options, request
|
| 941 |
+
)
|
| 942 |
+
|
| 943 |
+
body = _BaseGenerativeServiceRestTransport._BaseGenerateAnswer._get_request_body_json(
|
| 944 |
+
transcoded_request
|
| 945 |
+
)
|
| 946 |
+
|
| 947 |
+
# Jsonify the query params
|
| 948 |
+
query_params = _BaseGenerativeServiceRestTransport._BaseGenerateAnswer._get_query_params_json(
|
| 949 |
+
transcoded_request
|
| 950 |
+
)
|
| 951 |
+
|
| 952 |
+
if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
|
| 953 |
+
logging.DEBUG
|
| 954 |
+
): # pragma: NO COVER
|
| 955 |
+
request_url = "{host}{uri}".format(
|
| 956 |
+
host=self._host, uri=transcoded_request["uri"]
|
| 957 |
+
)
|
| 958 |
+
method = transcoded_request["method"]
|
| 959 |
+
try:
|
| 960 |
+
request_payload = type(request).to_json(request)
|
| 961 |
+
except:
|
| 962 |
+
request_payload = None
|
| 963 |
+
http_request = {
|
| 964 |
+
"payload": request_payload,
|
| 965 |
+
"requestMethod": method,
|
| 966 |
+
"requestUrl": request_url,
|
| 967 |
+
"headers": dict(metadata),
|
| 968 |
+
}
|
| 969 |
+
_LOGGER.debug(
|
| 970 |
+
f"Sending request for google.ai.generativelanguage_v1beta.GenerativeServiceClient.GenerateAnswer",
|
| 971 |
+
extra={
|
| 972 |
+
"serviceName": "google.ai.generativelanguage.v1beta.GenerativeService",
|
| 973 |
+
"rpcName": "GenerateAnswer",
|
| 974 |
+
"httpRequest": http_request,
|
| 975 |
+
"metadata": http_request["headers"],
|
| 976 |
+
},
|
| 977 |
+
)
|
| 978 |
+
|
| 979 |
+
# Send the request
|
| 980 |
+
response = GenerativeServiceRestTransport._GenerateAnswer._get_response(
|
| 981 |
+
self._host,
|
| 982 |
+
metadata,
|
| 983 |
+
query_params,
|
| 984 |
+
self._session,
|
| 985 |
+
timeout,
|
| 986 |
+
transcoded_request,
|
| 987 |
+
body,
|
| 988 |
+
)
|
| 989 |
+
|
| 990 |
+
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
|
| 991 |
+
# subclass.
|
| 992 |
+
if response.status_code >= 400:
|
| 993 |
+
raise core_exceptions.from_http_response(response)
|
| 994 |
+
|
| 995 |
+
# Return the response
|
| 996 |
+
resp = generative_service.GenerateAnswerResponse()
|
| 997 |
+
pb_resp = generative_service.GenerateAnswerResponse.pb(resp)
|
| 998 |
+
|
| 999 |
+
json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
|
| 1000 |
+
|
| 1001 |
+
resp = self._interceptor.post_generate_answer(resp)
|
| 1002 |
+
if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
|
| 1003 |
+
logging.DEBUG
|
| 1004 |
+
): # pragma: NO COVER
|
| 1005 |
+
try:
|
| 1006 |
+
response_payload = (
|
| 1007 |
+
generative_service.GenerateAnswerResponse.to_json(response)
|
| 1008 |
+
)
|
| 1009 |
+
except:
|
| 1010 |
+
response_payload = None
|
| 1011 |
+
http_response = {
|
| 1012 |
+
"payload": response_payload,
|
| 1013 |
+
"headers": dict(response.headers),
|
| 1014 |
+
"status": response.status_code,
|
| 1015 |
+
}
|
| 1016 |
+
_LOGGER.debug(
|
| 1017 |
+
"Received response for google.ai.generativelanguage_v1beta.GenerativeServiceClient.generate_answer",
|
| 1018 |
+
extra={
|
| 1019 |
+
"serviceName": "google.ai.generativelanguage.v1beta.GenerativeService",
|
| 1020 |
+
"rpcName": "GenerateAnswer",
|
| 1021 |
+
"metadata": http_response["headers"],
|
| 1022 |
+
"httpResponse": http_response,
|
| 1023 |
+
},
|
| 1024 |
+
)
|
| 1025 |
+
return resp
|
| 1026 |
+
|
| 1027 |
+
class _GenerateContent(
|
| 1028 |
+
_BaseGenerativeServiceRestTransport._BaseGenerateContent,
|
| 1029 |
+
GenerativeServiceRestStub,
|
| 1030 |
+
):
|
| 1031 |
+
def __hash__(self):
|
| 1032 |
+
return hash("GenerativeServiceRestTransport.GenerateContent")
|
| 1033 |
+
|
| 1034 |
+
@staticmethod
|
| 1035 |
+
def _get_response(
|
| 1036 |
+
host,
|
| 1037 |
+
metadata,
|
| 1038 |
+
query_params,
|
| 1039 |
+
session,
|
| 1040 |
+
timeout,
|
| 1041 |
+
transcoded_request,
|
| 1042 |
+
body=None,
|
| 1043 |
+
):
|
| 1044 |
+
uri = transcoded_request["uri"]
|
| 1045 |
+
method = transcoded_request["method"]
|
| 1046 |
+
headers = dict(metadata)
|
| 1047 |
+
headers["Content-Type"] = "application/json"
|
| 1048 |
+
response = getattr(session, method)(
|
| 1049 |
+
"{host}{uri}".format(host=host, uri=uri),
|
| 1050 |
+
timeout=timeout,
|
| 1051 |
+
headers=headers,
|
| 1052 |
+
params=rest_helpers.flatten_query_params(query_params, strict=True),
|
| 1053 |
+
data=body,
|
| 1054 |
+
)
|
| 1055 |
+
return response
|
| 1056 |
+
|
| 1057 |
+
def __call__(
|
| 1058 |
+
self,
|
| 1059 |
+
request: generative_service.GenerateContentRequest,
|
| 1060 |
+
*,
|
| 1061 |
+
retry: OptionalRetry = gapic_v1.method.DEFAULT,
|
| 1062 |
+
timeout: Optional[float] = None,
|
| 1063 |
+
metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
|
| 1064 |
+
) -> generative_service.GenerateContentResponse:
|
| 1065 |
+
r"""Call the generate content method over HTTP.
|
| 1066 |
+
|
| 1067 |
+
Args:
|
| 1068 |
+
request (~.generative_service.GenerateContentRequest):
|
| 1069 |
+
The request object. Request to generate a completion from
|
| 1070 |
+
the model.
|
| 1071 |
+
retry (google.api_core.retry.Retry): Designation of what errors, if any,
|
| 1072 |
+
should be retried.
|
| 1073 |
+
timeout (float): The timeout for this request.
|
| 1074 |
+
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
|
| 1075 |
+
sent along with the request as metadata. Normally, each value must be of type `str`,
|
| 1076 |
+
but for metadata keys ending with the suffix `-bin`, the corresponding values must
|
| 1077 |
+
be of type `bytes`.
|
| 1078 |
+
|
| 1079 |
+
Returns:
|
| 1080 |
+
~.generative_service.GenerateContentResponse:
|
| 1081 |
+
Response from the model supporting multiple candidate
|
| 1082 |
+
responses.
|
| 1083 |
+
|
| 1084 |
+
Safety ratings and content filtering are reported for
|
| 1085 |
+
both prompt in
|
| 1086 |
+
``GenerateContentResponse.prompt_feedback`` and for each
|
| 1087 |
+
candidate in ``finish_reason`` and in
|
| 1088 |
+
``safety_ratings``. The API:
|
| 1089 |
+
|
| 1090 |
+
- Returns either all requested candidates or none of
|
| 1091 |
+
them
|
| 1092 |
+
- Returns no candidates at all only if there was
|
| 1093 |
+
something wrong with the prompt (check
|
| 1094 |
+
``prompt_feedback``)
|
| 1095 |
+
- Reports feedback on each candidate in
|
| 1096 |
+
``finish_reason`` and ``safety_ratings``.
|
| 1097 |
+
|
| 1098 |
+
"""
|
| 1099 |
+
|
| 1100 |
+
http_options = (
|
| 1101 |
+
_BaseGenerativeServiceRestTransport._BaseGenerateContent._get_http_options()
|
| 1102 |
+
)
|
| 1103 |
+
|
| 1104 |
+
request, metadata = self._interceptor.pre_generate_content(
|
| 1105 |
+
request, metadata
|
| 1106 |
+
)
|
| 1107 |
+
transcoded_request = _BaseGenerativeServiceRestTransport._BaseGenerateContent._get_transcoded_request(
|
| 1108 |
+
http_options, request
|
| 1109 |
+
)
|
| 1110 |
+
|
| 1111 |
+
body = _BaseGenerativeServiceRestTransport._BaseGenerateContent._get_request_body_json(
|
| 1112 |
+
transcoded_request
|
| 1113 |
+
)
|
| 1114 |
+
|
| 1115 |
+
# Jsonify the query params
|
| 1116 |
+
query_params = _BaseGenerativeServiceRestTransport._BaseGenerateContent._get_query_params_json(
|
| 1117 |
+
transcoded_request
|
| 1118 |
+
)
|
| 1119 |
+
|
| 1120 |
+
if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
|
| 1121 |
+
logging.DEBUG
|
| 1122 |
+
): # pragma: NO COVER
|
| 1123 |
+
request_url = "{host}{uri}".format(
|
| 1124 |
+
host=self._host, uri=transcoded_request["uri"]
|
| 1125 |
+
)
|
| 1126 |
+
method = transcoded_request["method"]
|
| 1127 |
+
try:
|
| 1128 |
+
request_payload = type(request).to_json(request)
|
| 1129 |
+
except:
|
| 1130 |
+
request_payload = None
|
| 1131 |
+
http_request = {
|
| 1132 |
+
"payload": request_payload,
|
| 1133 |
+
"requestMethod": method,
|
| 1134 |
+
"requestUrl": request_url,
|
| 1135 |
+
"headers": dict(metadata),
|
| 1136 |
+
}
|
| 1137 |
+
_LOGGER.debug(
|
| 1138 |
+
f"Sending request for google.ai.generativelanguage_v1beta.GenerativeServiceClient.GenerateContent",
|
| 1139 |
+
extra={
|
| 1140 |
+
"serviceName": "google.ai.generativelanguage.v1beta.GenerativeService",
|
| 1141 |
+
"rpcName": "GenerateContent",
|
| 1142 |
+
"httpRequest": http_request,
|
| 1143 |
+
"metadata": http_request["headers"],
|
| 1144 |
+
},
|
| 1145 |
+
)
|
| 1146 |
+
|
| 1147 |
+
# Send the request
|
| 1148 |
+
response = GenerativeServiceRestTransport._GenerateContent._get_response(
|
| 1149 |
+
self._host,
|
| 1150 |
+
metadata,
|
| 1151 |
+
query_params,
|
| 1152 |
+
self._session,
|
| 1153 |
+
timeout,
|
| 1154 |
+
transcoded_request,
|
| 1155 |
+
body,
|
| 1156 |
+
)
|
| 1157 |
+
|
| 1158 |
+
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
|
| 1159 |
+
# subclass.
|
| 1160 |
+
if response.status_code >= 400:
|
| 1161 |
+
raise core_exceptions.from_http_response(response)
|
| 1162 |
+
|
| 1163 |
+
# Return the response
|
| 1164 |
+
resp = generative_service.GenerateContentResponse()
|
| 1165 |
+
pb_resp = generative_service.GenerateContentResponse.pb(resp)
|
| 1166 |
+
|
| 1167 |
+
json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
|
| 1168 |
+
|
| 1169 |
+
resp = self._interceptor.post_generate_content(resp)
|
| 1170 |
+
if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
|
| 1171 |
+
logging.DEBUG
|
| 1172 |
+
): # pragma: NO COVER
|
| 1173 |
+
try:
|
| 1174 |
+
response_payload = (
|
| 1175 |
+
generative_service.GenerateContentResponse.to_json(response)
|
| 1176 |
+
)
|
| 1177 |
+
except:
|
| 1178 |
+
response_payload = None
|
| 1179 |
+
http_response = {
|
| 1180 |
+
"payload": response_payload,
|
| 1181 |
+
"headers": dict(response.headers),
|
| 1182 |
+
"status": response.status_code,
|
| 1183 |
+
}
|
| 1184 |
+
_LOGGER.debug(
|
| 1185 |
+
"Received response for google.ai.generativelanguage_v1beta.GenerativeServiceClient.generate_content",
|
| 1186 |
+
extra={
|
| 1187 |
+
"serviceName": "google.ai.generativelanguage.v1beta.GenerativeService",
|
| 1188 |
+
"rpcName": "GenerateContent",
|
| 1189 |
+
"metadata": http_response["headers"],
|
| 1190 |
+
"httpResponse": http_response,
|
| 1191 |
+
},
|
| 1192 |
+
)
|
| 1193 |
+
return resp
|
| 1194 |
+
|
| 1195 |
+
class _StreamGenerateContent(
|
| 1196 |
+
_BaseGenerativeServiceRestTransport._BaseStreamGenerateContent,
|
| 1197 |
+
GenerativeServiceRestStub,
|
| 1198 |
+
):
|
| 1199 |
+
def __hash__(self):
|
| 1200 |
+
return hash("GenerativeServiceRestTransport.StreamGenerateContent")
|
| 1201 |
+
|
| 1202 |
+
@staticmethod
|
| 1203 |
+
def _get_response(
|
| 1204 |
+
host,
|
| 1205 |
+
metadata,
|
| 1206 |
+
query_params,
|
| 1207 |
+
session,
|
| 1208 |
+
timeout,
|
| 1209 |
+
transcoded_request,
|
| 1210 |
+
body=None,
|
| 1211 |
+
):
|
| 1212 |
+
uri = transcoded_request["uri"]
|
| 1213 |
+
method = transcoded_request["method"]
|
| 1214 |
+
headers = dict(metadata)
|
| 1215 |
+
headers["Content-Type"] = "application/json"
|
| 1216 |
+
response = getattr(session, method)(
|
| 1217 |
+
"{host}{uri}".format(host=host, uri=uri),
|
| 1218 |
+
timeout=timeout,
|
| 1219 |
+
headers=headers,
|
| 1220 |
+
params=rest_helpers.flatten_query_params(query_params, strict=True),
|
| 1221 |
+
data=body,
|
| 1222 |
+
stream=True,
|
| 1223 |
+
)
|
| 1224 |
+
return response
|
| 1225 |
+
|
| 1226 |
+
def __call__(
|
| 1227 |
+
self,
|
| 1228 |
+
request: generative_service.GenerateContentRequest,
|
| 1229 |
+
*,
|
| 1230 |
+
retry: OptionalRetry = gapic_v1.method.DEFAULT,
|
| 1231 |
+
timeout: Optional[float] = None,
|
| 1232 |
+
metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
|
| 1233 |
+
) -> rest_streaming.ResponseIterator:
|
| 1234 |
+
r"""Call the stream generate content method over HTTP.
|
| 1235 |
+
|
| 1236 |
+
Args:
|
| 1237 |
+
request (~.generative_service.GenerateContentRequest):
|
| 1238 |
+
The request object. Request to generate a completion from
|
| 1239 |
+
the model.
|
| 1240 |
+
retry (google.api_core.retry.Retry): Designation of what errors, if any,
|
| 1241 |
+
should be retried.
|
| 1242 |
+
timeout (float): The timeout for this request.
|
| 1243 |
+
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
|
| 1244 |
+
sent along with the request as metadata. Normally, each value must be of type `str`,
|
| 1245 |
+
but for metadata keys ending with the suffix `-bin`, the corresponding values must
|
| 1246 |
+
be of type `bytes`.
|
| 1247 |
+
|
| 1248 |
+
Returns:
|
| 1249 |
+
~.generative_service.GenerateContentResponse:
|
| 1250 |
+
Response from the model supporting multiple candidate
|
| 1251 |
+
responses.
|
| 1252 |
+
|
| 1253 |
+
Safety ratings and content filtering are reported for
|
| 1254 |
+
both prompt in
|
| 1255 |
+
``GenerateContentResponse.prompt_feedback`` and for each
|
| 1256 |
+
candidate in ``finish_reason`` and in
|
| 1257 |
+
``safety_ratings``. The API:
|
| 1258 |
+
|
| 1259 |
+
- Returns either all requested candidates or none of
|
| 1260 |
+
them
|
| 1261 |
+
- Returns no candidates at all only if there was
|
| 1262 |
+
something wrong with the prompt (check
|
| 1263 |
+
``prompt_feedback``)
|
| 1264 |
+
- Reports feedback on each candidate in
|
| 1265 |
+
``finish_reason`` and ``safety_ratings``.
|
| 1266 |
+
|
| 1267 |
+
"""
|
| 1268 |
+
|
| 1269 |
+
http_options = (
|
| 1270 |
+
_BaseGenerativeServiceRestTransport._BaseStreamGenerateContent._get_http_options()
|
| 1271 |
+
)
|
| 1272 |
+
|
| 1273 |
+
request, metadata = self._interceptor.pre_stream_generate_content(
|
| 1274 |
+
request, metadata
|
| 1275 |
+
)
|
| 1276 |
+
transcoded_request = _BaseGenerativeServiceRestTransport._BaseStreamGenerateContent._get_transcoded_request(
|
| 1277 |
+
http_options, request
|
| 1278 |
+
)
|
| 1279 |
+
|
| 1280 |
+
body = _BaseGenerativeServiceRestTransport._BaseStreamGenerateContent._get_request_body_json(
|
| 1281 |
+
transcoded_request
|
| 1282 |
+
)
|
| 1283 |
+
|
| 1284 |
+
# Jsonify the query params
|
| 1285 |
+
query_params = _BaseGenerativeServiceRestTransport._BaseStreamGenerateContent._get_query_params_json(
|
| 1286 |
+
transcoded_request
|
| 1287 |
+
)
|
| 1288 |
+
|
| 1289 |
+
if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
|
| 1290 |
+
logging.DEBUG
|
| 1291 |
+
): # pragma: NO COVER
|
| 1292 |
+
request_url = "{host}{uri}".format(
|
| 1293 |
+
host=self._host, uri=transcoded_request["uri"]
|
| 1294 |
+
)
|
| 1295 |
+
method = transcoded_request["method"]
|
| 1296 |
+
try:
|
| 1297 |
+
request_payload = type(request).to_json(request)
|
| 1298 |
+
except:
|
| 1299 |
+
request_payload = None
|
| 1300 |
+
http_request = {
|
| 1301 |
+
"payload": request_payload,
|
| 1302 |
+
"requestMethod": method,
|
| 1303 |
+
"requestUrl": request_url,
|
| 1304 |
+
"headers": dict(metadata),
|
| 1305 |
+
}
|
| 1306 |
+
_LOGGER.debug(
|
| 1307 |
+
f"Sending request for google.ai.generativelanguage_v1beta.GenerativeServiceClient.StreamGenerateContent",
|
| 1308 |
+
extra={
|
| 1309 |
+
"serviceName": "google.ai.generativelanguage.v1beta.GenerativeService",
|
| 1310 |
+
"rpcName": "StreamGenerateContent",
|
| 1311 |
+
"httpRequest": http_request,
|
| 1312 |
+
"metadata": http_request["headers"],
|
| 1313 |
+
},
|
| 1314 |
+
)
|
| 1315 |
+
|
| 1316 |
+
# Send the request
|
| 1317 |
+
response = (
|
| 1318 |
+
GenerativeServiceRestTransport._StreamGenerateContent._get_response(
|
| 1319 |
+
self._host,
|
| 1320 |
+
metadata,
|
| 1321 |
+
query_params,
|
| 1322 |
+
self._session,
|
| 1323 |
+
timeout,
|
| 1324 |
+
transcoded_request,
|
| 1325 |
+
body,
|
| 1326 |
+
)
|
| 1327 |
+
)
|
| 1328 |
+
|
| 1329 |
+
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
|
| 1330 |
+
# subclass.
|
| 1331 |
+
if response.status_code >= 400:
|
| 1332 |
+
raise core_exceptions.from_http_response(response)
|
| 1333 |
+
|
| 1334 |
+
# Return the response
|
| 1335 |
+
resp = rest_streaming.ResponseIterator(
|
| 1336 |
+
response, generative_service.GenerateContentResponse
|
| 1337 |
+
)
|
| 1338 |
+
|
| 1339 |
+
resp = self._interceptor.post_stream_generate_content(resp)
|
| 1340 |
+
return resp
|
| 1341 |
+
|
| 1342 |
+
@property
|
| 1343 |
+
def batch_embed_contents(
|
| 1344 |
+
self,
|
| 1345 |
+
) -> Callable[
|
| 1346 |
+
[generative_service.BatchEmbedContentsRequest],
|
| 1347 |
+
generative_service.BatchEmbedContentsResponse,
|
| 1348 |
+
]:
|
| 1349 |
+
# The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
|
| 1350 |
+
# In C++ this would require a dynamic_cast
|
| 1351 |
+
return self._BatchEmbedContents(self._session, self._host, self._interceptor) # type: ignore
|
| 1352 |
+
|
| 1353 |
+
@property
|
| 1354 |
+
def count_tokens(
|
| 1355 |
+
self,
|
| 1356 |
+
) -> Callable[
|
| 1357 |
+
[generative_service.CountTokensRequest], generative_service.CountTokensResponse
|
| 1358 |
+
]:
|
| 1359 |
+
# The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
|
| 1360 |
+
# In C++ this would require a dynamic_cast
|
| 1361 |
+
return self._CountTokens(self._session, self._host, self._interceptor) # type: ignore
|
| 1362 |
+
|
| 1363 |
+
@property
|
| 1364 |
+
def embed_content(
|
| 1365 |
+
self,
|
| 1366 |
+
) -> Callable[
|
| 1367 |
+
[generative_service.EmbedContentRequest],
|
| 1368 |
+
generative_service.EmbedContentResponse,
|
| 1369 |
+
]:
|
| 1370 |
+
# The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
|
| 1371 |
+
# In C++ this would require a dynamic_cast
|
| 1372 |
+
return self._EmbedContent(self._session, self._host, self._interceptor) # type: ignore
|
| 1373 |
+
|
| 1374 |
+
@property
|
| 1375 |
+
def generate_answer(
|
| 1376 |
+
self,
|
| 1377 |
+
) -> Callable[
|
| 1378 |
+
[generative_service.GenerateAnswerRequest],
|
| 1379 |
+
generative_service.GenerateAnswerResponse,
|
| 1380 |
+
]:
|
| 1381 |
+
# The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
|
| 1382 |
+
# In C++ this would require a dynamic_cast
|
| 1383 |
+
return self._GenerateAnswer(self._session, self._host, self._interceptor) # type: ignore
|
| 1384 |
+
|
| 1385 |
+
@property
|
| 1386 |
+
def generate_content(
|
| 1387 |
+
self,
|
| 1388 |
+
) -> Callable[
|
| 1389 |
+
[generative_service.GenerateContentRequest],
|
| 1390 |
+
generative_service.GenerateContentResponse,
|
| 1391 |
+
]:
|
| 1392 |
+
# The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
|
| 1393 |
+
# In C++ this would require a dynamic_cast
|
| 1394 |
+
return self._GenerateContent(self._session, self._host, self._interceptor) # type: ignore
|
| 1395 |
+
|
| 1396 |
+
@property
|
| 1397 |
+
def stream_generate_content(
|
| 1398 |
+
self,
|
| 1399 |
+
) -> Callable[
|
| 1400 |
+
[generative_service.GenerateContentRequest],
|
| 1401 |
+
generative_service.GenerateContentResponse,
|
| 1402 |
+
]:
|
| 1403 |
+
# The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
|
| 1404 |
+
# In C++ this would require a dynamic_cast
|
| 1405 |
+
return self._StreamGenerateContent(self._session, self._host, self._interceptor) # type: ignore
|
| 1406 |
+
|
| 1407 |
+
@property
|
| 1408 |
+
def get_operation(self):
|
| 1409 |
+
return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore
|
| 1410 |
+
|
| 1411 |
+
class _GetOperation(
|
| 1412 |
+
_BaseGenerativeServiceRestTransport._BaseGetOperation, GenerativeServiceRestStub
|
| 1413 |
+
):
|
| 1414 |
+
def __hash__(self):
|
| 1415 |
+
return hash("GenerativeServiceRestTransport.GetOperation")
|
| 1416 |
+
|
| 1417 |
+
@staticmethod
|
| 1418 |
+
def _get_response(
|
| 1419 |
+
host,
|
| 1420 |
+
metadata,
|
| 1421 |
+
query_params,
|
| 1422 |
+
session,
|
| 1423 |
+
timeout,
|
| 1424 |
+
transcoded_request,
|
| 1425 |
+
body=None,
|
| 1426 |
+
):
|
| 1427 |
+
uri = transcoded_request["uri"]
|
| 1428 |
+
method = transcoded_request["method"]
|
| 1429 |
+
headers = dict(metadata)
|
| 1430 |
+
headers["Content-Type"] = "application/json"
|
| 1431 |
+
response = getattr(session, method)(
|
| 1432 |
+
"{host}{uri}".format(host=host, uri=uri),
|
| 1433 |
+
timeout=timeout,
|
| 1434 |
+
headers=headers,
|
| 1435 |
+
params=rest_helpers.flatten_query_params(query_params, strict=True),
|
| 1436 |
+
)
|
| 1437 |
+
return response
|
| 1438 |
+
|
| 1439 |
+
def __call__(
|
| 1440 |
+
self,
|
| 1441 |
+
request: operations_pb2.GetOperationRequest,
|
| 1442 |
+
*,
|
| 1443 |
+
retry: OptionalRetry = gapic_v1.method.DEFAULT,
|
| 1444 |
+
timeout: Optional[float] = None,
|
| 1445 |
+
metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
|
| 1446 |
+
) -> operations_pb2.Operation:
|
| 1447 |
+
r"""Call the get operation method over HTTP.
|
| 1448 |
+
|
| 1449 |
+
Args:
|
| 1450 |
+
request (operations_pb2.GetOperationRequest):
|
| 1451 |
+
The request object for GetOperation method.
|
| 1452 |
+
retry (google.api_core.retry.Retry): Designation of what errors, if any,
|
| 1453 |
+
should be retried.
|
| 1454 |
+
timeout (float): The timeout for this request.
|
| 1455 |
+
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
|
| 1456 |
+
sent along with the request as metadata. Normally, each value must be of type `str`,
|
| 1457 |
+
but for metadata keys ending with the suffix `-bin`, the corresponding values must
|
| 1458 |
+
be of type `bytes`.
|
| 1459 |
+
|
| 1460 |
+
Returns:
|
| 1461 |
+
operations_pb2.Operation: Response from GetOperation method.
|
| 1462 |
+
"""
|
| 1463 |
+
|
| 1464 |
+
http_options = (
|
| 1465 |
+
_BaseGenerativeServiceRestTransport._BaseGetOperation._get_http_options()
|
| 1466 |
+
)
|
| 1467 |
+
|
| 1468 |
+
request, metadata = self._interceptor.pre_get_operation(request, metadata)
|
| 1469 |
+
transcoded_request = _BaseGenerativeServiceRestTransport._BaseGetOperation._get_transcoded_request(
|
| 1470 |
+
http_options, request
|
| 1471 |
+
)
|
| 1472 |
+
|
| 1473 |
+
# Jsonify the query params
|
| 1474 |
+
query_params = _BaseGenerativeServiceRestTransport._BaseGetOperation._get_query_params_json(
|
| 1475 |
+
transcoded_request
|
| 1476 |
+
)
|
| 1477 |
+
|
| 1478 |
+
if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
|
| 1479 |
+
logging.DEBUG
|
| 1480 |
+
): # pragma: NO COVER
|
| 1481 |
+
request_url = "{host}{uri}".format(
|
| 1482 |
+
host=self._host, uri=transcoded_request["uri"]
|
| 1483 |
+
)
|
| 1484 |
+
method = transcoded_request["method"]
|
| 1485 |
+
try:
|
| 1486 |
+
request_payload = json_format.MessageToJson(request)
|
| 1487 |
+
except:
|
| 1488 |
+
request_payload = None
|
| 1489 |
+
http_request = {
|
| 1490 |
+
"payload": request_payload,
|
| 1491 |
+
"requestMethod": method,
|
| 1492 |
+
"requestUrl": request_url,
|
| 1493 |
+
"headers": dict(metadata),
|
| 1494 |
+
}
|
| 1495 |
+
_LOGGER.debug(
|
| 1496 |
+
f"Sending request for google.ai.generativelanguage_v1beta.GenerativeServiceClient.GetOperation",
|
| 1497 |
+
extra={
|
| 1498 |
+
"serviceName": "google.ai.generativelanguage.v1beta.GenerativeService",
|
| 1499 |
+
"rpcName": "GetOperation",
|
| 1500 |
+
"httpRequest": http_request,
|
| 1501 |
+
"metadata": http_request["headers"],
|
| 1502 |
+
},
|
| 1503 |
+
)
|
| 1504 |
+
|
| 1505 |
+
# Send the request
|
| 1506 |
+
response = GenerativeServiceRestTransport._GetOperation._get_response(
|
| 1507 |
+
self._host,
|
| 1508 |
+
metadata,
|
| 1509 |
+
query_params,
|
| 1510 |
+
self._session,
|
| 1511 |
+
timeout,
|
| 1512 |
+
transcoded_request,
|
| 1513 |
+
)
|
| 1514 |
+
|
| 1515 |
+
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
|
| 1516 |
+
# subclass.
|
| 1517 |
+
if response.status_code >= 400:
|
| 1518 |
+
raise core_exceptions.from_http_response(response)
|
| 1519 |
+
|
| 1520 |
+
content = response.content.decode("utf-8")
|
| 1521 |
+
resp = operations_pb2.Operation()
|
| 1522 |
+
resp = json_format.Parse(content, resp)
|
| 1523 |
+
resp = self._interceptor.post_get_operation(resp)
|
| 1524 |
+
if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
|
| 1525 |
+
logging.DEBUG
|
| 1526 |
+
): # pragma: NO COVER
|
| 1527 |
+
try:
|
| 1528 |
+
response_payload = json_format.MessageToJson(resp)
|
| 1529 |
+
except:
|
| 1530 |
+
response_payload = None
|
| 1531 |
+
http_response = {
|
| 1532 |
+
"payload": response_payload,
|
| 1533 |
+
"headers": dict(response.headers),
|
| 1534 |
+
"status": response.status_code,
|
| 1535 |
+
}
|
| 1536 |
+
_LOGGER.debug(
|
| 1537 |
+
"Received response for google.ai.generativelanguage_v1beta.GenerativeServiceAsyncClient.GetOperation",
|
| 1538 |
+
extra={
|
| 1539 |
+
"serviceName": "google.ai.generativelanguage.v1beta.GenerativeService",
|
| 1540 |
+
"rpcName": "GetOperation",
|
| 1541 |
+
"httpResponse": http_response,
|
| 1542 |
+
"metadata": http_response["headers"],
|
| 1543 |
+
},
|
| 1544 |
+
)
|
| 1545 |
+
return resp
|
| 1546 |
+
|
| 1547 |
+
@property
|
| 1548 |
+
def list_operations(self):
|
| 1549 |
+
return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore
|
| 1550 |
+
|
| 1551 |
+
class _ListOperations(
|
| 1552 |
+
_BaseGenerativeServiceRestTransport._BaseListOperations,
|
| 1553 |
+
GenerativeServiceRestStub,
|
| 1554 |
+
):
|
| 1555 |
+
def __hash__(self):
|
| 1556 |
+
return hash("GenerativeServiceRestTransport.ListOperations")
|
| 1557 |
+
|
| 1558 |
+
@staticmethod
|
| 1559 |
+
def _get_response(
|
| 1560 |
+
host,
|
| 1561 |
+
metadata,
|
| 1562 |
+
query_params,
|
| 1563 |
+
session,
|
| 1564 |
+
timeout,
|
| 1565 |
+
transcoded_request,
|
| 1566 |
+
body=None,
|
| 1567 |
+
):
|
| 1568 |
+
uri = transcoded_request["uri"]
|
| 1569 |
+
method = transcoded_request["method"]
|
| 1570 |
+
headers = dict(metadata)
|
| 1571 |
+
headers["Content-Type"] = "application/json"
|
| 1572 |
+
response = getattr(session, method)(
|
| 1573 |
+
"{host}{uri}".format(host=host, uri=uri),
|
| 1574 |
+
timeout=timeout,
|
| 1575 |
+
headers=headers,
|
| 1576 |
+
params=rest_helpers.flatten_query_params(query_params, strict=True),
|
| 1577 |
+
)
|
| 1578 |
+
return response
|
| 1579 |
+
|
| 1580 |
+
def __call__(
|
| 1581 |
+
self,
|
| 1582 |
+
request: operations_pb2.ListOperationsRequest,
|
| 1583 |
+
*,
|
| 1584 |
+
retry: OptionalRetry = gapic_v1.method.DEFAULT,
|
| 1585 |
+
timeout: Optional[float] = None,
|
| 1586 |
+
metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
|
| 1587 |
+
) -> operations_pb2.ListOperationsResponse:
|
| 1588 |
+
r"""Call the list operations method over HTTP.
|
| 1589 |
+
|
| 1590 |
+
Args:
|
| 1591 |
+
request (operations_pb2.ListOperationsRequest):
|
| 1592 |
+
The request object for ListOperations method.
|
| 1593 |
+
retry (google.api_core.retry.Retry): Designation of what errors, if any,
|
| 1594 |
+
should be retried.
|
| 1595 |
+
timeout (float): The timeout for this request.
|
| 1596 |
+
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
|
| 1597 |
+
sent along with the request as metadata. Normally, each value must be of type `str`,
|
| 1598 |
+
but for metadata keys ending with the suffix `-bin`, the corresponding values must
|
| 1599 |
+
be of type `bytes`.
|
| 1600 |
+
|
| 1601 |
+
Returns:
|
| 1602 |
+
operations_pb2.ListOperationsResponse: Response from ListOperations method.
|
| 1603 |
+
"""
|
| 1604 |
+
|
| 1605 |
+
http_options = (
|
| 1606 |
+
_BaseGenerativeServiceRestTransport._BaseListOperations._get_http_options()
|
| 1607 |
+
)
|
| 1608 |
+
|
| 1609 |
+
request, metadata = self._interceptor.pre_list_operations(request, metadata)
|
| 1610 |
+
transcoded_request = _BaseGenerativeServiceRestTransport._BaseListOperations._get_transcoded_request(
|
| 1611 |
+
http_options, request
|
| 1612 |
+
)
|
| 1613 |
+
|
| 1614 |
+
# Jsonify the query params
|
| 1615 |
+
query_params = _BaseGenerativeServiceRestTransport._BaseListOperations._get_query_params_json(
|
| 1616 |
+
transcoded_request
|
| 1617 |
+
)
|
| 1618 |
+
|
| 1619 |
+
if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
|
| 1620 |
+
logging.DEBUG
|
| 1621 |
+
): # pragma: NO COVER
|
| 1622 |
+
request_url = "{host}{uri}".format(
|
| 1623 |
+
host=self._host, uri=transcoded_request["uri"]
|
| 1624 |
+
)
|
| 1625 |
+
method = transcoded_request["method"]
|
| 1626 |
+
try:
|
| 1627 |
+
request_payload = json_format.MessageToJson(request)
|
| 1628 |
+
except:
|
| 1629 |
+
request_payload = None
|
| 1630 |
+
http_request = {
|
| 1631 |
+
"payload": request_payload,
|
| 1632 |
+
"requestMethod": method,
|
| 1633 |
+
"requestUrl": request_url,
|
| 1634 |
+
"headers": dict(metadata),
|
| 1635 |
+
}
|
| 1636 |
+
_LOGGER.debug(
|
| 1637 |
+
f"Sending request for google.ai.generativelanguage_v1beta.GenerativeServiceClient.ListOperations",
|
| 1638 |
+
extra={
|
| 1639 |
+
"serviceName": "google.ai.generativelanguage.v1beta.GenerativeService",
|
| 1640 |
+
"rpcName": "ListOperations",
|
| 1641 |
+
"httpRequest": http_request,
|
| 1642 |
+
"metadata": http_request["headers"],
|
| 1643 |
+
},
|
| 1644 |
+
)
|
| 1645 |
+
|
| 1646 |
+
# Send the request
|
| 1647 |
+
response = GenerativeServiceRestTransport._ListOperations._get_response(
|
| 1648 |
+
self._host,
|
| 1649 |
+
metadata,
|
| 1650 |
+
query_params,
|
| 1651 |
+
self._session,
|
| 1652 |
+
timeout,
|
| 1653 |
+
transcoded_request,
|
| 1654 |
+
)
|
| 1655 |
+
|
| 1656 |
+
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
|
| 1657 |
+
# subclass.
|
| 1658 |
+
if response.status_code >= 400:
|
| 1659 |
+
raise core_exceptions.from_http_response(response)
|
| 1660 |
+
|
| 1661 |
+
content = response.content.decode("utf-8")
|
| 1662 |
+
resp = operations_pb2.ListOperationsResponse()
|
| 1663 |
+
resp = json_format.Parse(content, resp)
|
| 1664 |
+
resp = self._interceptor.post_list_operations(resp)
|
| 1665 |
+
if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
|
| 1666 |
+
logging.DEBUG
|
| 1667 |
+
): # pragma: NO COVER
|
| 1668 |
+
try:
|
| 1669 |
+
response_payload = json_format.MessageToJson(resp)
|
| 1670 |
+
except:
|
| 1671 |
+
response_payload = None
|
| 1672 |
+
http_response = {
|
| 1673 |
+
"payload": response_payload,
|
| 1674 |
+
"headers": dict(response.headers),
|
| 1675 |
+
"status": response.status_code,
|
| 1676 |
+
}
|
| 1677 |
+
_LOGGER.debug(
|
| 1678 |
+
"Received response for google.ai.generativelanguage_v1beta.GenerativeServiceAsyncClient.ListOperations",
|
| 1679 |
+
extra={
|
| 1680 |
+
"serviceName": "google.ai.generativelanguage.v1beta.GenerativeService",
|
| 1681 |
+
"rpcName": "ListOperations",
|
| 1682 |
+
"httpResponse": http_response,
|
| 1683 |
+
"metadata": http_response["headers"],
|
| 1684 |
+
},
|
| 1685 |
+
)
|
| 1686 |
+
return resp
|
| 1687 |
+
|
| 1688 |
+
@property
|
| 1689 |
+
def kind(self) -> str:
|
| 1690 |
+
return "rest"
|
| 1691 |
+
|
| 1692 |
+
def close(self):
|
| 1693 |
+
self._session.close()
|
| 1694 |
+
|
| 1695 |
+
|
| 1696 |
+
__all__ = ("GenerativeServiceRestTransport",)
|
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/generative_service/transports/rest_base.py
ADDED
|
@@ -0,0 +1,506 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Copyright 2024 Google LLC
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
#
|
| 16 |
+
import json # type: ignore
|
| 17 |
+
import re
|
| 18 |
+
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union
|
| 19 |
+
|
| 20 |
+
from google.api_core import gapic_v1, path_template
|
| 21 |
+
from google.longrunning import operations_pb2 # type: ignore
|
| 22 |
+
from google.protobuf import json_format
|
| 23 |
+
|
| 24 |
+
from google.ai.generativelanguage_v1beta.types import generative_service
|
| 25 |
+
|
| 26 |
+
from .base import DEFAULT_CLIENT_INFO, GenerativeServiceTransport
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class _BaseGenerativeServiceRestTransport(GenerativeServiceTransport):
|
| 30 |
+
"""Base REST backend transport for GenerativeService.
|
| 31 |
+
|
| 32 |
+
Note: This class is not meant to be used directly. Use its sync and
|
| 33 |
+
async sub-classes instead.
|
| 34 |
+
|
| 35 |
+
This class defines the same methods as the primary client, so the
|
| 36 |
+
primary client can load the underlying transport implementation
|
| 37 |
+
and call it.
|
| 38 |
+
|
| 39 |
+
It sends JSON representations of protocol buffers over HTTP/1.1
|
| 40 |
+
"""
|
| 41 |
+
|
| 42 |
+
def __init__(
|
| 43 |
+
self,
|
| 44 |
+
*,
|
| 45 |
+
host: str = "generativelanguage.googleapis.com",
|
| 46 |
+
credentials: Optional[Any] = None,
|
| 47 |
+
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
|
| 48 |
+
always_use_jwt_access: Optional[bool] = False,
|
| 49 |
+
url_scheme: str = "https",
|
| 50 |
+
api_audience: Optional[str] = None,
|
| 51 |
+
) -> None:
|
| 52 |
+
"""Instantiate the transport.
|
| 53 |
+
Args:
|
| 54 |
+
host (Optional[str]):
|
| 55 |
+
The hostname to connect to (default: 'generativelanguage.googleapis.com').
|
| 56 |
+
credentials (Optional[Any]): The
|
| 57 |
+
authorization credentials to attach to requests. These
|
| 58 |
+
credentials identify the application to the service; if none
|
| 59 |
+
are specified, the client will attempt to ascertain the
|
| 60 |
+
credentials from the environment.
|
| 61 |
+
client_info (google.api_core.gapic_v1.client_info.ClientInfo):
|
| 62 |
+
The client info used to send a user-agent string along with
|
| 63 |
+
API requests. If ``None``, then default info will be used.
|
| 64 |
+
Generally, you only need to set this if you are developing
|
| 65 |
+
your own client library.
|
| 66 |
+
always_use_jwt_access (Optional[bool]): Whether self signed JWT should
|
| 67 |
+
be used for service account credentials.
|
| 68 |
+
url_scheme: the protocol scheme for the API endpoint. Normally
|
| 69 |
+
"https", but for testing or local servers,
|
| 70 |
+
"http" can be specified.
|
| 71 |
+
"""
|
| 72 |
+
# Run the base constructor
|
| 73 |
+
maybe_url_match = re.match("^(?P<scheme>http(?:s)?://)?(?P<host>.*)$", host)
|
| 74 |
+
if maybe_url_match is None:
|
| 75 |
+
raise ValueError(
|
| 76 |
+
f"Unexpected hostname structure: {host}"
|
| 77 |
+
) # pragma: NO COVER
|
| 78 |
+
|
| 79 |
+
url_match_items = maybe_url_match.groupdict()
|
| 80 |
+
|
| 81 |
+
host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host
|
| 82 |
+
|
| 83 |
+
super().__init__(
|
| 84 |
+
host=host,
|
| 85 |
+
credentials=credentials,
|
| 86 |
+
client_info=client_info,
|
| 87 |
+
always_use_jwt_access=always_use_jwt_access,
|
| 88 |
+
api_audience=api_audience,
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
class _BaseBatchEmbedContents:
|
| 92 |
+
def __hash__(self): # pragma: NO COVER
|
| 93 |
+
return NotImplementedError("__hash__ must be implemented.")
|
| 94 |
+
|
| 95 |
+
__REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
|
| 96 |
+
|
| 97 |
+
@classmethod
|
| 98 |
+
def _get_unset_required_fields(cls, message_dict):
|
| 99 |
+
return {
|
| 100 |
+
k: v
|
| 101 |
+
for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
|
| 102 |
+
if k not in message_dict
|
| 103 |
+
}
|
| 104 |
+
|
| 105 |
+
@staticmethod
|
| 106 |
+
def _get_http_options():
|
| 107 |
+
http_options: List[Dict[str, str]] = [
|
| 108 |
+
{
|
| 109 |
+
"method": "post",
|
| 110 |
+
"uri": "/v1beta/{model=models/*}:batchEmbedContents",
|
| 111 |
+
"body": "*",
|
| 112 |
+
},
|
| 113 |
+
]
|
| 114 |
+
return http_options
|
| 115 |
+
|
| 116 |
+
@staticmethod
|
| 117 |
+
def _get_transcoded_request(http_options, request):
|
| 118 |
+
pb_request = generative_service.BatchEmbedContentsRequest.pb(request)
|
| 119 |
+
transcoded_request = path_template.transcode(http_options, pb_request)
|
| 120 |
+
return transcoded_request
|
| 121 |
+
|
| 122 |
+
@staticmethod
|
| 123 |
+
def _get_request_body_json(transcoded_request):
|
| 124 |
+
# Jsonify the request body
|
| 125 |
+
|
| 126 |
+
body = json_format.MessageToJson(
|
| 127 |
+
transcoded_request["body"], use_integers_for_enums=True
|
| 128 |
+
)
|
| 129 |
+
return body
|
| 130 |
+
|
| 131 |
+
@staticmethod
|
| 132 |
+
def _get_query_params_json(transcoded_request):
|
| 133 |
+
query_params = json.loads(
|
| 134 |
+
json_format.MessageToJson(
|
| 135 |
+
transcoded_request["query_params"],
|
| 136 |
+
use_integers_for_enums=True,
|
| 137 |
+
)
|
| 138 |
+
)
|
| 139 |
+
query_params.update(
|
| 140 |
+
_BaseGenerativeServiceRestTransport._BaseBatchEmbedContents._get_unset_required_fields(
|
| 141 |
+
query_params
|
| 142 |
+
)
|
| 143 |
+
)
|
| 144 |
+
|
| 145 |
+
query_params["$alt"] = "json;enum-encoding=int"
|
| 146 |
+
return query_params
|
| 147 |
+
|
| 148 |
+
class _BaseCountTokens:
|
| 149 |
+
def __hash__(self): # pragma: NO COVER
|
| 150 |
+
return NotImplementedError("__hash__ must be implemented.")
|
| 151 |
+
|
| 152 |
+
__REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
|
| 153 |
+
|
| 154 |
+
@classmethod
|
| 155 |
+
def _get_unset_required_fields(cls, message_dict):
|
| 156 |
+
return {
|
| 157 |
+
k: v
|
| 158 |
+
for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
|
| 159 |
+
if k not in message_dict
|
| 160 |
+
}
|
| 161 |
+
|
| 162 |
+
@staticmethod
|
| 163 |
+
def _get_http_options():
|
| 164 |
+
http_options: List[Dict[str, str]] = [
|
| 165 |
+
{
|
| 166 |
+
"method": "post",
|
| 167 |
+
"uri": "/v1beta/{model=models/*}:countTokens",
|
| 168 |
+
"body": "*",
|
| 169 |
+
},
|
| 170 |
+
]
|
| 171 |
+
return http_options
|
| 172 |
+
|
| 173 |
+
@staticmethod
|
| 174 |
+
def _get_transcoded_request(http_options, request):
|
| 175 |
+
pb_request = generative_service.CountTokensRequest.pb(request)
|
| 176 |
+
transcoded_request = path_template.transcode(http_options, pb_request)
|
| 177 |
+
return transcoded_request
|
| 178 |
+
|
| 179 |
+
@staticmethod
|
| 180 |
+
def _get_request_body_json(transcoded_request):
|
| 181 |
+
# Jsonify the request body
|
| 182 |
+
|
| 183 |
+
body = json_format.MessageToJson(
|
| 184 |
+
transcoded_request["body"], use_integers_for_enums=True
|
| 185 |
+
)
|
| 186 |
+
return body
|
| 187 |
+
|
| 188 |
+
@staticmethod
|
| 189 |
+
def _get_query_params_json(transcoded_request):
|
| 190 |
+
query_params = json.loads(
|
| 191 |
+
json_format.MessageToJson(
|
| 192 |
+
transcoded_request["query_params"],
|
| 193 |
+
use_integers_for_enums=True,
|
| 194 |
+
)
|
| 195 |
+
)
|
| 196 |
+
query_params.update(
|
| 197 |
+
_BaseGenerativeServiceRestTransport._BaseCountTokens._get_unset_required_fields(
|
| 198 |
+
query_params
|
| 199 |
+
)
|
| 200 |
+
)
|
| 201 |
+
|
| 202 |
+
query_params["$alt"] = "json;enum-encoding=int"
|
| 203 |
+
return query_params
|
| 204 |
+
|
| 205 |
+
class _BaseEmbedContent:
|
| 206 |
+
def __hash__(self): # pragma: NO COVER
|
| 207 |
+
return NotImplementedError("__hash__ must be implemented.")
|
| 208 |
+
|
| 209 |
+
__REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
|
| 210 |
+
|
| 211 |
+
@classmethod
|
| 212 |
+
def _get_unset_required_fields(cls, message_dict):
|
| 213 |
+
return {
|
| 214 |
+
k: v
|
| 215 |
+
for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
|
| 216 |
+
if k not in message_dict
|
| 217 |
+
}
|
| 218 |
+
|
| 219 |
+
@staticmethod
|
| 220 |
+
def _get_http_options():
|
| 221 |
+
http_options: List[Dict[str, str]] = [
|
| 222 |
+
{
|
| 223 |
+
"method": "post",
|
| 224 |
+
"uri": "/v1beta/{model=models/*}:embedContent",
|
| 225 |
+
"body": "*",
|
| 226 |
+
},
|
| 227 |
+
]
|
| 228 |
+
return http_options
|
| 229 |
+
|
| 230 |
+
@staticmethod
|
| 231 |
+
def _get_transcoded_request(http_options, request):
|
| 232 |
+
pb_request = generative_service.EmbedContentRequest.pb(request)
|
| 233 |
+
transcoded_request = path_template.transcode(http_options, pb_request)
|
| 234 |
+
return transcoded_request
|
| 235 |
+
|
| 236 |
+
@staticmethod
|
| 237 |
+
def _get_request_body_json(transcoded_request):
|
| 238 |
+
# Jsonify the request body
|
| 239 |
+
|
| 240 |
+
body = json_format.MessageToJson(
|
| 241 |
+
transcoded_request["body"], use_integers_for_enums=True
|
| 242 |
+
)
|
| 243 |
+
return body
|
| 244 |
+
|
| 245 |
+
@staticmethod
|
| 246 |
+
def _get_query_params_json(transcoded_request):
|
| 247 |
+
query_params = json.loads(
|
| 248 |
+
json_format.MessageToJson(
|
| 249 |
+
transcoded_request["query_params"],
|
| 250 |
+
use_integers_for_enums=True,
|
| 251 |
+
)
|
| 252 |
+
)
|
| 253 |
+
query_params.update(
|
| 254 |
+
_BaseGenerativeServiceRestTransport._BaseEmbedContent._get_unset_required_fields(
|
| 255 |
+
query_params
|
| 256 |
+
)
|
| 257 |
+
)
|
| 258 |
+
|
| 259 |
+
query_params["$alt"] = "json;enum-encoding=int"
|
| 260 |
+
return query_params
|
| 261 |
+
|
| 262 |
+
class _BaseGenerateAnswer:
|
| 263 |
+
def __hash__(self): # pragma: NO COVER
|
| 264 |
+
return NotImplementedError("__hash__ must be implemented.")
|
| 265 |
+
|
| 266 |
+
__REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
|
| 267 |
+
|
| 268 |
+
@classmethod
|
| 269 |
+
def _get_unset_required_fields(cls, message_dict):
|
| 270 |
+
return {
|
| 271 |
+
k: v
|
| 272 |
+
for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
|
| 273 |
+
if k not in message_dict
|
| 274 |
+
}
|
| 275 |
+
|
| 276 |
+
@staticmethod
|
| 277 |
+
def _get_http_options():
|
| 278 |
+
http_options: List[Dict[str, str]] = [
|
| 279 |
+
{
|
| 280 |
+
"method": "post",
|
| 281 |
+
"uri": "/v1beta/{model=models/*}:generateAnswer",
|
| 282 |
+
"body": "*",
|
| 283 |
+
},
|
| 284 |
+
]
|
| 285 |
+
return http_options
|
| 286 |
+
|
| 287 |
+
@staticmethod
|
| 288 |
+
def _get_transcoded_request(http_options, request):
|
| 289 |
+
pb_request = generative_service.GenerateAnswerRequest.pb(request)
|
| 290 |
+
transcoded_request = path_template.transcode(http_options, pb_request)
|
| 291 |
+
return transcoded_request
|
| 292 |
+
|
| 293 |
+
@staticmethod
|
| 294 |
+
def _get_request_body_json(transcoded_request):
|
| 295 |
+
# Jsonify the request body
|
| 296 |
+
|
| 297 |
+
body = json_format.MessageToJson(
|
| 298 |
+
transcoded_request["body"], use_integers_for_enums=True
|
| 299 |
+
)
|
| 300 |
+
return body
|
| 301 |
+
|
| 302 |
+
@staticmethod
|
| 303 |
+
def _get_query_params_json(transcoded_request):
|
| 304 |
+
query_params = json.loads(
|
| 305 |
+
json_format.MessageToJson(
|
| 306 |
+
transcoded_request["query_params"],
|
| 307 |
+
use_integers_for_enums=True,
|
| 308 |
+
)
|
| 309 |
+
)
|
| 310 |
+
query_params.update(
|
| 311 |
+
_BaseGenerativeServiceRestTransport._BaseGenerateAnswer._get_unset_required_fields(
|
| 312 |
+
query_params
|
| 313 |
+
)
|
| 314 |
+
)
|
| 315 |
+
|
| 316 |
+
query_params["$alt"] = "json;enum-encoding=int"
|
| 317 |
+
return query_params
|
| 318 |
+
|
| 319 |
+
class _BaseGenerateContent:
|
| 320 |
+
def __hash__(self): # pragma: NO COVER
|
| 321 |
+
return NotImplementedError("__hash__ must be implemented.")
|
| 322 |
+
|
| 323 |
+
__REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
|
| 324 |
+
|
| 325 |
+
@classmethod
|
| 326 |
+
def _get_unset_required_fields(cls, message_dict):
|
| 327 |
+
return {
|
| 328 |
+
k: v
|
| 329 |
+
for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
|
| 330 |
+
if k not in message_dict
|
| 331 |
+
}
|
| 332 |
+
|
| 333 |
+
@staticmethod
|
| 334 |
+
def _get_http_options():
|
| 335 |
+
http_options: List[Dict[str, str]] = [
|
| 336 |
+
{
|
| 337 |
+
"method": "post",
|
| 338 |
+
"uri": "/v1beta/{model=models/*}:generateContent",
|
| 339 |
+
"body": "*",
|
| 340 |
+
},
|
| 341 |
+
{
|
| 342 |
+
"method": "post",
|
| 343 |
+
"uri": "/v1beta/{model=tunedModels/*}:generateContent",
|
| 344 |
+
"body": "*",
|
| 345 |
+
},
|
| 346 |
+
]
|
| 347 |
+
return http_options
|
| 348 |
+
|
| 349 |
+
@staticmethod
|
| 350 |
+
def _get_transcoded_request(http_options, request):
|
| 351 |
+
pb_request = generative_service.GenerateContentRequest.pb(request)
|
| 352 |
+
transcoded_request = path_template.transcode(http_options, pb_request)
|
| 353 |
+
return transcoded_request
|
| 354 |
+
|
| 355 |
+
@staticmethod
|
| 356 |
+
def _get_request_body_json(transcoded_request):
|
| 357 |
+
# Jsonify the request body
|
| 358 |
+
|
| 359 |
+
body = json_format.MessageToJson(
|
| 360 |
+
transcoded_request["body"], use_integers_for_enums=True
|
| 361 |
+
)
|
| 362 |
+
return body
|
| 363 |
+
|
| 364 |
+
@staticmethod
|
| 365 |
+
def _get_query_params_json(transcoded_request):
|
| 366 |
+
query_params = json.loads(
|
| 367 |
+
json_format.MessageToJson(
|
| 368 |
+
transcoded_request["query_params"],
|
| 369 |
+
use_integers_for_enums=True,
|
| 370 |
+
)
|
| 371 |
+
)
|
| 372 |
+
query_params.update(
|
| 373 |
+
_BaseGenerativeServiceRestTransport._BaseGenerateContent._get_unset_required_fields(
|
| 374 |
+
query_params
|
| 375 |
+
)
|
| 376 |
+
)
|
| 377 |
+
|
| 378 |
+
query_params["$alt"] = "json;enum-encoding=int"
|
| 379 |
+
return query_params
|
| 380 |
+
|
| 381 |
+
class _BaseStreamGenerateContent:
|
| 382 |
+
def __hash__(self): # pragma: NO COVER
|
| 383 |
+
return NotImplementedError("__hash__ must be implemented.")
|
| 384 |
+
|
| 385 |
+
__REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
|
| 386 |
+
|
| 387 |
+
@classmethod
|
| 388 |
+
def _get_unset_required_fields(cls, message_dict):
|
| 389 |
+
return {
|
| 390 |
+
k: v
|
| 391 |
+
for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
|
| 392 |
+
if k not in message_dict
|
| 393 |
+
}
|
| 394 |
+
|
| 395 |
+
@staticmethod
|
| 396 |
+
def _get_http_options():
|
| 397 |
+
http_options: List[Dict[str, str]] = [
|
| 398 |
+
{
|
| 399 |
+
"method": "post",
|
| 400 |
+
"uri": "/v1beta/{model=models/*}:streamGenerateContent",
|
| 401 |
+
"body": "*",
|
| 402 |
+
},
|
| 403 |
+
{
|
| 404 |
+
"method": "post",
|
| 405 |
+
"uri": "/v1beta/{model=tunedModels/*}:streamGenerateContent",
|
| 406 |
+
"body": "*",
|
| 407 |
+
},
|
| 408 |
+
]
|
| 409 |
+
return http_options
|
| 410 |
+
|
| 411 |
+
@staticmethod
|
| 412 |
+
def _get_transcoded_request(http_options, request):
|
| 413 |
+
pb_request = generative_service.GenerateContentRequest.pb(request)
|
| 414 |
+
transcoded_request = path_template.transcode(http_options, pb_request)
|
| 415 |
+
return transcoded_request
|
| 416 |
+
|
| 417 |
+
@staticmethod
|
| 418 |
+
def _get_request_body_json(transcoded_request):
|
| 419 |
+
# Jsonify the request body
|
| 420 |
+
|
| 421 |
+
body = json_format.MessageToJson(
|
| 422 |
+
transcoded_request["body"], use_integers_for_enums=True
|
| 423 |
+
)
|
| 424 |
+
return body
|
| 425 |
+
|
| 426 |
+
@staticmethod
|
| 427 |
+
def _get_query_params_json(transcoded_request):
|
| 428 |
+
query_params = json.loads(
|
| 429 |
+
json_format.MessageToJson(
|
| 430 |
+
transcoded_request["query_params"],
|
| 431 |
+
use_integers_for_enums=True,
|
| 432 |
+
)
|
| 433 |
+
)
|
| 434 |
+
query_params.update(
|
| 435 |
+
_BaseGenerativeServiceRestTransport._BaseStreamGenerateContent._get_unset_required_fields(
|
| 436 |
+
query_params
|
| 437 |
+
)
|
| 438 |
+
)
|
| 439 |
+
|
| 440 |
+
query_params["$alt"] = "json;enum-encoding=int"
|
| 441 |
+
return query_params
|
| 442 |
+
|
| 443 |
+
class _BaseGetOperation:
|
| 444 |
+
def __hash__(self): # pragma: NO COVER
|
| 445 |
+
return NotImplementedError("__hash__ must be implemented.")
|
| 446 |
+
|
| 447 |
+
@staticmethod
|
| 448 |
+
def _get_http_options():
|
| 449 |
+
http_options: List[Dict[str, str]] = [
|
| 450 |
+
{
|
| 451 |
+
"method": "get",
|
| 452 |
+
"uri": "/v1beta/{name=tunedModels/*/operations/*}",
|
| 453 |
+
},
|
| 454 |
+
{
|
| 455 |
+
"method": "get",
|
| 456 |
+
"uri": "/v1beta/{name=generatedFiles/*/operations/*}",
|
| 457 |
+
},
|
| 458 |
+
{
|
| 459 |
+
"method": "get",
|
| 460 |
+
"uri": "/v1beta/{name=models/*/operations/*}",
|
| 461 |
+
},
|
| 462 |
+
]
|
| 463 |
+
return http_options
|
| 464 |
+
|
| 465 |
+
@staticmethod
|
| 466 |
+
def _get_transcoded_request(http_options, request):
|
| 467 |
+
request_kwargs = json_format.MessageToDict(request)
|
| 468 |
+
transcoded_request = path_template.transcode(http_options, **request_kwargs)
|
| 469 |
+
return transcoded_request
|
| 470 |
+
|
| 471 |
+
@staticmethod
|
| 472 |
+
def _get_query_params_json(transcoded_request):
|
| 473 |
+
query_params = json.loads(json.dumps(transcoded_request["query_params"]))
|
| 474 |
+
return query_params
|
| 475 |
+
|
| 476 |
+
class _BaseListOperations:
|
| 477 |
+
def __hash__(self): # pragma: NO COVER
|
| 478 |
+
return NotImplementedError("__hash__ must be implemented.")
|
| 479 |
+
|
| 480 |
+
@staticmethod
|
| 481 |
+
def _get_http_options():
|
| 482 |
+
http_options: List[Dict[str, str]] = [
|
| 483 |
+
{
|
| 484 |
+
"method": "get",
|
| 485 |
+
"uri": "/v1beta/{name=tunedModels/*}/operations",
|
| 486 |
+
},
|
| 487 |
+
{
|
| 488 |
+
"method": "get",
|
| 489 |
+
"uri": "/v1beta/{name=models/*}/operations",
|
| 490 |
+
},
|
| 491 |
+
]
|
| 492 |
+
return http_options
|
| 493 |
+
|
| 494 |
+
@staticmethod
|
| 495 |
+
def _get_transcoded_request(http_options, request):
|
| 496 |
+
request_kwargs = json_format.MessageToDict(request)
|
| 497 |
+
transcoded_request = path_template.transcode(http_options, **request_kwargs)
|
| 498 |
+
return transcoded_request
|
| 499 |
+
|
| 500 |
+
@staticmethod
|
| 501 |
+
def _get_query_params_json(transcoded_request):
|
| 502 |
+
query_params = json.loads(json.dumps(transcoded_request["query_params"]))
|
| 503 |
+
return query_params
|
| 504 |
+
|
| 505 |
+
|
| 506 |
+
__all__ = ("_BaseGenerativeServiceRestTransport",)
|
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/retriever_service/__init__.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Copyright 2024 Google LLC
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
#
|
| 16 |
+
from .async_client import RetrieverServiceAsyncClient
|
| 17 |
+
from .client import RetrieverServiceClient
|
| 18 |
+
|
| 19 |
+
__all__ = (
|
| 20 |
+
"RetrieverServiceClient",
|
| 21 |
+
"RetrieverServiceAsyncClient",
|
| 22 |
+
)
|
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/retriever_service/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (414 Bytes). View file
|
|
|
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/retriever_service/__pycache__/async_client.cpython-311.pyc
ADDED
|
Binary file (96.1 kB). View file
|
|
|
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/retriever_service/__pycache__/pagers.cpython-311.pyc
ADDED
|
Binary file (26.2 kB). View file
|
|
|
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/retriever_service/async_client.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/retriever_service/client.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/retriever_service/pagers.py
ADDED
|
@@ -0,0 +1,509 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Copyright 2024 Google LLC
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
#
|
| 16 |
+
from typing import (
|
| 17 |
+
Any,
|
| 18 |
+
AsyncIterator,
|
| 19 |
+
Awaitable,
|
| 20 |
+
Callable,
|
| 21 |
+
Iterator,
|
| 22 |
+
Optional,
|
| 23 |
+
Sequence,
|
| 24 |
+
Tuple,
|
| 25 |
+
Union,
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
from google.api_core import gapic_v1
|
| 29 |
+
from google.api_core import retry as retries
|
| 30 |
+
from google.api_core import retry_async as retries_async
|
| 31 |
+
|
| 32 |
+
try:
|
| 33 |
+
OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None]
|
| 34 |
+
OptionalAsyncRetry = Union[
|
| 35 |
+
retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None
|
| 36 |
+
]
|
| 37 |
+
except AttributeError: # pragma: NO COVER
|
| 38 |
+
OptionalRetry = Union[retries.Retry, object, None] # type: ignore
|
| 39 |
+
OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore
|
| 40 |
+
|
| 41 |
+
from google.ai.generativelanguage_v1beta.types import retriever, retriever_service
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class ListCorporaPager:
|
| 45 |
+
"""A pager for iterating through ``list_corpora`` requests.
|
| 46 |
+
|
| 47 |
+
This class thinly wraps an initial
|
| 48 |
+
:class:`google.ai.generativelanguage_v1beta.types.ListCorporaResponse` object, and
|
| 49 |
+
provides an ``__iter__`` method to iterate through its
|
| 50 |
+
``corpora`` field.
|
| 51 |
+
|
| 52 |
+
If there are more pages, the ``__iter__`` method will make additional
|
| 53 |
+
``ListCorpora`` requests and continue to iterate
|
| 54 |
+
through the ``corpora`` field on the
|
| 55 |
+
corresponding responses.
|
| 56 |
+
|
| 57 |
+
All the usual :class:`google.ai.generativelanguage_v1beta.types.ListCorporaResponse`
|
| 58 |
+
attributes are available on the pager. If multiple requests are made, only
|
| 59 |
+
the most recent response is retained, and thus used for attribute lookup.
|
| 60 |
+
"""
|
| 61 |
+
|
| 62 |
+
def __init__(
|
| 63 |
+
self,
|
| 64 |
+
method: Callable[..., retriever_service.ListCorporaResponse],
|
| 65 |
+
request: retriever_service.ListCorporaRequest,
|
| 66 |
+
response: retriever_service.ListCorporaResponse,
|
| 67 |
+
*,
|
| 68 |
+
retry: OptionalRetry = gapic_v1.method.DEFAULT,
|
| 69 |
+
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
|
| 70 |
+
metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()
|
| 71 |
+
):
|
| 72 |
+
"""Instantiate the pager.
|
| 73 |
+
|
| 74 |
+
Args:
|
| 75 |
+
method (Callable): The method that was originally called, and
|
| 76 |
+
which instantiated this pager.
|
| 77 |
+
request (google.ai.generativelanguage_v1beta.types.ListCorporaRequest):
|
| 78 |
+
The initial request object.
|
| 79 |
+
response (google.ai.generativelanguage_v1beta.types.ListCorporaResponse):
|
| 80 |
+
The initial response object.
|
| 81 |
+
retry (google.api_core.retry.Retry): Designation of what errors,
|
| 82 |
+
if any, should be retried.
|
| 83 |
+
timeout (float): The timeout for this request.
|
| 84 |
+
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
|
| 85 |
+
sent along with the request as metadata. Normally, each value must be of type `str`,
|
| 86 |
+
but for metadata keys ending with the suffix `-bin`, the corresponding values must
|
| 87 |
+
be of type `bytes`.
|
| 88 |
+
"""
|
| 89 |
+
self._method = method
|
| 90 |
+
self._request = retriever_service.ListCorporaRequest(request)
|
| 91 |
+
self._response = response
|
| 92 |
+
self._retry = retry
|
| 93 |
+
self._timeout = timeout
|
| 94 |
+
self._metadata = metadata
|
| 95 |
+
|
| 96 |
+
def __getattr__(self, name: str) -> Any:
|
| 97 |
+
return getattr(self._response, name)
|
| 98 |
+
|
| 99 |
+
@property
|
| 100 |
+
def pages(self) -> Iterator[retriever_service.ListCorporaResponse]:
|
| 101 |
+
yield self._response
|
| 102 |
+
while self._response.next_page_token:
|
| 103 |
+
self._request.page_token = self._response.next_page_token
|
| 104 |
+
self._response = self._method(
|
| 105 |
+
self._request,
|
| 106 |
+
retry=self._retry,
|
| 107 |
+
timeout=self._timeout,
|
| 108 |
+
metadata=self._metadata,
|
| 109 |
+
)
|
| 110 |
+
yield self._response
|
| 111 |
+
|
| 112 |
+
def __iter__(self) -> Iterator[retriever.Corpus]:
|
| 113 |
+
for page in self.pages:
|
| 114 |
+
yield from page.corpora
|
| 115 |
+
|
| 116 |
+
def __repr__(self) -> str:
|
| 117 |
+
return "{0}<{1!r}>".format(self.__class__.__name__, self._response)
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
class ListCorporaAsyncPager:
|
| 121 |
+
"""A pager for iterating through ``list_corpora`` requests.
|
| 122 |
+
|
| 123 |
+
This class thinly wraps an initial
|
| 124 |
+
:class:`google.ai.generativelanguage_v1beta.types.ListCorporaResponse` object, and
|
| 125 |
+
provides an ``__aiter__`` method to iterate through its
|
| 126 |
+
``corpora`` field.
|
| 127 |
+
|
| 128 |
+
If there are more pages, the ``__aiter__`` method will make additional
|
| 129 |
+
``ListCorpora`` requests and continue to iterate
|
| 130 |
+
through the ``corpora`` field on the
|
| 131 |
+
corresponding responses.
|
| 132 |
+
|
| 133 |
+
All the usual :class:`google.ai.generativelanguage_v1beta.types.ListCorporaResponse`
|
| 134 |
+
attributes are available on the pager. If multiple requests are made, only
|
| 135 |
+
the most recent response is retained, and thus used for attribute lookup.
|
| 136 |
+
"""
|
| 137 |
+
|
| 138 |
+
def __init__(
|
| 139 |
+
self,
|
| 140 |
+
method: Callable[..., Awaitable[retriever_service.ListCorporaResponse]],
|
| 141 |
+
request: retriever_service.ListCorporaRequest,
|
| 142 |
+
response: retriever_service.ListCorporaResponse,
|
| 143 |
+
*,
|
| 144 |
+
retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT,
|
| 145 |
+
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
|
| 146 |
+
metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()
|
| 147 |
+
):
|
| 148 |
+
"""Instantiates the pager.
|
| 149 |
+
|
| 150 |
+
Args:
|
| 151 |
+
method (Callable): The method that was originally called, and
|
| 152 |
+
which instantiated this pager.
|
| 153 |
+
request (google.ai.generativelanguage_v1beta.types.ListCorporaRequest):
|
| 154 |
+
The initial request object.
|
| 155 |
+
response (google.ai.generativelanguage_v1beta.types.ListCorporaResponse):
|
| 156 |
+
The initial response object.
|
| 157 |
+
retry (google.api_core.retry.AsyncRetry): Designation of what errors,
|
| 158 |
+
if any, should be retried.
|
| 159 |
+
timeout (float): The timeout for this request.
|
| 160 |
+
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
|
| 161 |
+
sent along with the request as metadata. Normally, each value must be of type `str`,
|
| 162 |
+
but for metadata keys ending with the suffix `-bin`, the corresponding values must
|
| 163 |
+
be of type `bytes`.
|
| 164 |
+
"""
|
| 165 |
+
self._method = method
|
| 166 |
+
self._request = retriever_service.ListCorporaRequest(request)
|
| 167 |
+
self._response = response
|
| 168 |
+
self._retry = retry
|
| 169 |
+
self._timeout = timeout
|
| 170 |
+
self._metadata = metadata
|
| 171 |
+
|
| 172 |
+
def __getattr__(self, name: str) -> Any:
|
| 173 |
+
return getattr(self._response, name)
|
| 174 |
+
|
| 175 |
+
@property
|
| 176 |
+
async def pages(self) -> AsyncIterator[retriever_service.ListCorporaResponse]:
|
| 177 |
+
yield self._response
|
| 178 |
+
while self._response.next_page_token:
|
| 179 |
+
self._request.page_token = self._response.next_page_token
|
| 180 |
+
self._response = await self._method(
|
| 181 |
+
self._request,
|
| 182 |
+
retry=self._retry,
|
| 183 |
+
timeout=self._timeout,
|
| 184 |
+
metadata=self._metadata,
|
| 185 |
+
)
|
| 186 |
+
yield self._response
|
| 187 |
+
|
| 188 |
+
def __aiter__(self) -> AsyncIterator[retriever.Corpus]:
|
| 189 |
+
async def async_generator():
|
| 190 |
+
async for page in self.pages:
|
| 191 |
+
for response in page.corpora:
|
| 192 |
+
yield response
|
| 193 |
+
|
| 194 |
+
return async_generator()
|
| 195 |
+
|
| 196 |
+
def __repr__(self) -> str:
|
| 197 |
+
return "{0}<{1!r}>".format(self.__class__.__name__, self._response)
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
class ListDocumentsPager:
|
| 201 |
+
"""A pager for iterating through ``list_documents`` requests.
|
| 202 |
+
|
| 203 |
+
This class thinly wraps an initial
|
| 204 |
+
:class:`google.ai.generativelanguage_v1beta.types.ListDocumentsResponse` object, and
|
| 205 |
+
provides an ``__iter__`` method to iterate through its
|
| 206 |
+
``documents`` field.
|
| 207 |
+
|
| 208 |
+
If there are more pages, the ``__iter__`` method will make additional
|
| 209 |
+
``ListDocuments`` requests and continue to iterate
|
| 210 |
+
through the ``documents`` field on the
|
| 211 |
+
corresponding responses.
|
| 212 |
+
|
| 213 |
+
All the usual :class:`google.ai.generativelanguage_v1beta.types.ListDocumentsResponse`
|
| 214 |
+
attributes are available on the pager. If multiple requests are made, only
|
| 215 |
+
the most recent response is retained, and thus used for attribute lookup.
|
| 216 |
+
"""
|
| 217 |
+
|
| 218 |
+
def __init__(
|
| 219 |
+
self,
|
| 220 |
+
method: Callable[..., retriever_service.ListDocumentsResponse],
|
| 221 |
+
request: retriever_service.ListDocumentsRequest,
|
| 222 |
+
response: retriever_service.ListDocumentsResponse,
|
| 223 |
+
*,
|
| 224 |
+
retry: OptionalRetry = gapic_v1.method.DEFAULT,
|
| 225 |
+
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
|
| 226 |
+
metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()
|
| 227 |
+
):
|
| 228 |
+
"""Instantiate the pager.
|
| 229 |
+
|
| 230 |
+
Args:
|
| 231 |
+
method (Callable): The method that was originally called, and
|
| 232 |
+
which instantiated this pager.
|
| 233 |
+
request (google.ai.generativelanguage_v1beta.types.ListDocumentsRequest):
|
| 234 |
+
The initial request object.
|
| 235 |
+
response (google.ai.generativelanguage_v1beta.types.ListDocumentsResponse):
|
| 236 |
+
The initial response object.
|
| 237 |
+
retry (google.api_core.retry.Retry): Designation of what errors,
|
| 238 |
+
if any, should be retried.
|
| 239 |
+
timeout (float): The timeout for this request.
|
| 240 |
+
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
|
| 241 |
+
sent along with the request as metadata. Normally, each value must be of type `str`,
|
| 242 |
+
but for metadata keys ending with the suffix `-bin`, the corresponding values must
|
| 243 |
+
be of type `bytes`.
|
| 244 |
+
"""
|
| 245 |
+
self._method = method
|
| 246 |
+
self._request = retriever_service.ListDocumentsRequest(request)
|
| 247 |
+
self._response = response
|
| 248 |
+
self._retry = retry
|
| 249 |
+
self._timeout = timeout
|
| 250 |
+
self._metadata = metadata
|
| 251 |
+
|
| 252 |
+
def __getattr__(self, name: str) -> Any:
|
| 253 |
+
return getattr(self._response, name)
|
| 254 |
+
|
| 255 |
+
@property
|
| 256 |
+
def pages(self) -> Iterator[retriever_service.ListDocumentsResponse]:
|
| 257 |
+
yield self._response
|
| 258 |
+
while self._response.next_page_token:
|
| 259 |
+
self._request.page_token = self._response.next_page_token
|
| 260 |
+
self._response = self._method(
|
| 261 |
+
self._request,
|
| 262 |
+
retry=self._retry,
|
| 263 |
+
timeout=self._timeout,
|
| 264 |
+
metadata=self._metadata,
|
| 265 |
+
)
|
| 266 |
+
yield self._response
|
| 267 |
+
|
| 268 |
+
def __iter__(self) -> Iterator[retriever.Document]:
|
| 269 |
+
for page in self.pages:
|
| 270 |
+
yield from page.documents
|
| 271 |
+
|
| 272 |
+
def __repr__(self) -> str:
|
| 273 |
+
return "{0}<{1!r}>".format(self.__class__.__name__, self._response)
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
class ListDocumentsAsyncPager:
|
| 277 |
+
"""A pager for iterating through ``list_documents`` requests.
|
| 278 |
+
|
| 279 |
+
This class thinly wraps an initial
|
| 280 |
+
:class:`google.ai.generativelanguage_v1beta.types.ListDocumentsResponse` object, and
|
| 281 |
+
provides an ``__aiter__`` method to iterate through its
|
| 282 |
+
``documents`` field.
|
| 283 |
+
|
| 284 |
+
If there are more pages, the ``__aiter__`` method will make additional
|
| 285 |
+
``ListDocuments`` requests and continue to iterate
|
| 286 |
+
through the ``documents`` field on the
|
| 287 |
+
corresponding responses.
|
| 288 |
+
|
| 289 |
+
All the usual :class:`google.ai.generativelanguage_v1beta.types.ListDocumentsResponse`
|
| 290 |
+
attributes are available on the pager. If multiple requests are made, only
|
| 291 |
+
the most recent response is retained, and thus used for attribute lookup.
|
| 292 |
+
"""
|
| 293 |
+
|
| 294 |
+
def __init__(
|
| 295 |
+
self,
|
| 296 |
+
method: Callable[..., Awaitable[retriever_service.ListDocumentsResponse]],
|
| 297 |
+
request: retriever_service.ListDocumentsRequest,
|
| 298 |
+
response: retriever_service.ListDocumentsResponse,
|
| 299 |
+
*,
|
| 300 |
+
retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT,
|
| 301 |
+
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
|
| 302 |
+
metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()
|
| 303 |
+
):
|
| 304 |
+
"""Instantiates the pager.
|
| 305 |
+
|
| 306 |
+
Args:
|
| 307 |
+
method (Callable): The method that was originally called, and
|
| 308 |
+
which instantiated this pager.
|
| 309 |
+
request (google.ai.generativelanguage_v1beta.types.ListDocumentsRequest):
|
| 310 |
+
The initial request object.
|
| 311 |
+
response (google.ai.generativelanguage_v1beta.types.ListDocumentsResponse):
|
| 312 |
+
The initial response object.
|
| 313 |
+
retry (google.api_core.retry.AsyncRetry): Designation of what errors,
|
| 314 |
+
if any, should be retried.
|
| 315 |
+
timeout (float): The timeout for this request.
|
| 316 |
+
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
|
| 317 |
+
sent along with the request as metadata. Normally, each value must be of type `str`,
|
| 318 |
+
but for metadata keys ending with the suffix `-bin`, the corresponding values must
|
| 319 |
+
be of type `bytes`.
|
| 320 |
+
"""
|
| 321 |
+
self._method = method
|
| 322 |
+
self._request = retriever_service.ListDocumentsRequest(request)
|
| 323 |
+
self._response = response
|
| 324 |
+
self._retry = retry
|
| 325 |
+
self._timeout = timeout
|
| 326 |
+
self._metadata = metadata
|
| 327 |
+
|
| 328 |
+
def __getattr__(self, name: str) -> Any:
|
| 329 |
+
return getattr(self._response, name)
|
| 330 |
+
|
| 331 |
+
@property
|
| 332 |
+
async def pages(self) -> AsyncIterator[retriever_service.ListDocumentsResponse]:
|
| 333 |
+
yield self._response
|
| 334 |
+
while self._response.next_page_token:
|
| 335 |
+
self._request.page_token = self._response.next_page_token
|
| 336 |
+
self._response = await self._method(
|
| 337 |
+
self._request,
|
| 338 |
+
retry=self._retry,
|
| 339 |
+
timeout=self._timeout,
|
| 340 |
+
metadata=self._metadata,
|
| 341 |
+
)
|
| 342 |
+
yield self._response
|
| 343 |
+
|
| 344 |
+
def __aiter__(self) -> AsyncIterator[retriever.Document]:
|
| 345 |
+
async def async_generator():
|
| 346 |
+
async for page in self.pages:
|
| 347 |
+
for response in page.documents:
|
| 348 |
+
yield response
|
| 349 |
+
|
| 350 |
+
return async_generator()
|
| 351 |
+
|
| 352 |
+
def __repr__(self) -> str:
|
| 353 |
+
return "{0}<{1!r}>".format(self.__class__.__name__, self._response)
|
| 354 |
+
|
| 355 |
+
|
| 356 |
+
class ListChunksPager:
|
| 357 |
+
"""A pager for iterating through ``list_chunks`` requests.
|
| 358 |
+
|
| 359 |
+
This class thinly wraps an initial
|
| 360 |
+
:class:`google.ai.generativelanguage_v1beta.types.ListChunksResponse` object, and
|
| 361 |
+
provides an ``__iter__`` method to iterate through its
|
| 362 |
+
``chunks`` field.
|
| 363 |
+
|
| 364 |
+
If there are more pages, the ``__iter__`` method will make additional
|
| 365 |
+
``ListChunks`` requests and continue to iterate
|
| 366 |
+
through the ``chunks`` field on the
|
| 367 |
+
corresponding responses.
|
| 368 |
+
|
| 369 |
+
All the usual :class:`google.ai.generativelanguage_v1beta.types.ListChunksResponse`
|
| 370 |
+
attributes are available on the pager. If multiple requests are made, only
|
| 371 |
+
the most recent response is retained, and thus used for attribute lookup.
|
| 372 |
+
"""
|
| 373 |
+
|
| 374 |
+
def __init__(
|
| 375 |
+
self,
|
| 376 |
+
method: Callable[..., retriever_service.ListChunksResponse],
|
| 377 |
+
request: retriever_service.ListChunksRequest,
|
| 378 |
+
response: retriever_service.ListChunksResponse,
|
| 379 |
+
*,
|
| 380 |
+
retry: OptionalRetry = gapic_v1.method.DEFAULT,
|
| 381 |
+
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
|
| 382 |
+
metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()
|
| 383 |
+
):
|
| 384 |
+
"""Instantiate the pager.
|
| 385 |
+
|
| 386 |
+
Args:
|
| 387 |
+
method (Callable): The method that was originally called, and
|
| 388 |
+
which instantiated this pager.
|
| 389 |
+
request (google.ai.generativelanguage_v1beta.types.ListChunksRequest):
|
| 390 |
+
The initial request object.
|
| 391 |
+
response (google.ai.generativelanguage_v1beta.types.ListChunksResponse):
|
| 392 |
+
The initial response object.
|
| 393 |
+
retry (google.api_core.retry.Retry): Designation of what errors,
|
| 394 |
+
if any, should be retried.
|
| 395 |
+
timeout (float): The timeout for this request.
|
| 396 |
+
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
|
| 397 |
+
sent along with the request as metadata. Normally, each value must be of type `str`,
|
| 398 |
+
but for metadata keys ending with the suffix `-bin`, the corresponding values must
|
| 399 |
+
be of type `bytes`.
|
| 400 |
+
"""
|
| 401 |
+
self._method = method
|
| 402 |
+
self._request = retriever_service.ListChunksRequest(request)
|
| 403 |
+
self._response = response
|
| 404 |
+
self._retry = retry
|
| 405 |
+
self._timeout = timeout
|
| 406 |
+
self._metadata = metadata
|
| 407 |
+
|
| 408 |
+
def __getattr__(self, name: str) -> Any:
|
| 409 |
+
return getattr(self._response, name)
|
| 410 |
+
|
| 411 |
+
@property
|
| 412 |
+
def pages(self) -> Iterator[retriever_service.ListChunksResponse]:
|
| 413 |
+
yield self._response
|
| 414 |
+
while self._response.next_page_token:
|
| 415 |
+
self._request.page_token = self._response.next_page_token
|
| 416 |
+
self._response = self._method(
|
| 417 |
+
self._request,
|
| 418 |
+
retry=self._retry,
|
| 419 |
+
timeout=self._timeout,
|
| 420 |
+
metadata=self._metadata,
|
| 421 |
+
)
|
| 422 |
+
yield self._response
|
| 423 |
+
|
| 424 |
+
def __iter__(self) -> Iterator[retriever.Chunk]:
|
| 425 |
+
for page in self.pages:
|
| 426 |
+
yield from page.chunks
|
| 427 |
+
|
| 428 |
+
def __repr__(self) -> str:
|
| 429 |
+
return "{0}<{1!r}>".format(self.__class__.__name__, self._response)
|
| 430 |
+
|
| 431 |
+
|
| 432 |
+
class ListChunksAsyncPager:
|
| 433 |
+
"""A pager for iterating through ``list_chunks`` requests.
|
| 434 |
+
|
| 435 |
+
This class thinly wraps an initial
|
| 436 |
+
:class:`google.ai.generativelanguage_v1beta.types.ListChunksResponse` object, and
|
| 437 |
+
provides an ``__aiter__`` method to iterate through its
|
| 438 |
+
``chunks`` field.
|
| 439 |
+
|
| 440 |
+
If there are more pages, the ``__aiter__`` method will make additional
|
| 441 |
+
``ListChunks`` requests and continue to iterate
|
| 442 |
+
through the ``chunks`` field on the
|
| 443 |
+
corresponding responses.
|
| 444 |
+
|
| 445 |
+
All the usual :class:`google.ai.generativelanguage_v1beta.types.ListChunksResponse`
|
| 446 |
+
attributes are available on the pager. If multiple requests are made, only
|
| 447 |
+
the most recent response is retained, and thus used for attribute lookup.
|
| 448 |
+
"""
|
| 449 |
+
|
| 450 |
+
def __init__(
|
| 451 |
+
self,
|
| 452 |
+
method: Callable[..., Awaitable[retriever_service.ListChunksResponse]],
|
| 453 |
+
request: retriever_service.ListChunksRequest,
|
| 454 |
+
response: retriever_service.ListChunksResponse,
|
| 455 |
+
*,
|
| 456 |
+
retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT,
|
| 457 |
+
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
|
| 458 |
+
metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()
|
| 459 |
+
):
|
| 460 |
+
"""Instantiates the pager.
|
| 461 |
+
|
| 462 |
+
Args:
|
| 463 |
+
method (Callable): The method that was originally called, and
|
| 464 |
+
which instantiated this pager.
|
| 465 |
+
request (google.ai.generativelanguage_v1beta.types.ListChunksRequest):
|
| 466 |
+
The initial request object.
|
| 467 |
+
response (google.ai.generativelanguage_v1beta.types.ListChunksResponse):
|
| 468 |
+
The initial response object.
|
| 469 |
+
retry (google.api_core.retry.AsyncRetry): Designation of what errors,
|
| 470 |
+
if any, should be retried.
|
| 471 |
+
timeout (float): The timeout for this request.
|
| 472 |
+
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
|
| 473 |
+
sent along with the request as metadata. Normally, each value must be of type `str`,
|
| 474 |
+
but for metadata keys ending with the suffix `-bin`, the corresponding values must
|
| 475 |
+
be of type `bytes`.
|
| 476 |
+
"""
|
| 477 |
+
self._method = method
|
| 478 |
+
self._request = retriever_service.ListChunksRequest(request)
|
| 479 |
+
self._response = response
|
| 480 |
+
self._retry = retry
|
| 481 |
+
self._timeout = timeout
|
| 482 |
+
self._metadata = metadata
|
| 483 |
+
|
| 484 |
+
def __getattr__(self, name: str) -> Any:
|
| 485 |
+
return getattr(self._response, name)
|
| 486 |
+
|
| 487 |
+
@property
|
| 488 |
+
async def pages(self) -> AsyncIterator[retriever_service.ListChunksResponse]:
|
| 489 |
+
yield self._response
|
| 490 |
+
while self._response.next_page_token:
|
| 491 |
+
self._request.page_token = self._response.next_page_token
|
| 492 |
+
self._response = await self._method(
|
| 493 |
+
self._request,
|
| 494 |
+
retry=self._retry,
|
| 495 |
+
timeout=self._timeout,
|
| 496 |
+
metadata=self._metadata,
|
| 497 |
+
)
|
| 498 |
+
yield self._response
|
| 499 |
+
|
| 500 |
+
def __aiter__(self) -> AsyncIterator[retriever.Chunk]:
|
| 501 |
+
async def async_generator():
|
| 502 |
+
async for page in self.pages:
|
| 503 |
+
for response in page.chunks:
|
| 504 |
+
yield response
|
| 505 |
+
|
| 506 |
+
return async_generator()
|
| 507 |
+
|
| 508 |
+
def __repr__(self) -> str:
|
| 509 |
+
return "{0}<{1!r}>".format(self.__class__.__name__, self._response)
|
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/retriever_service/transports/__init__.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Copyright 2024 Google LLC
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
#
|
| 16 |
+
from collections import OrderedDict
|
| 17 |
+
from typing import Dict, Type
|
| 18 |
+
|
| 19 |
+
from .base import RetrieverServiceTransport
|
| 20 |
+
from .grpc import RetrieverServiceGrpcTransport
|
| 21 |
+
from .grpc_asyncio import RetrieverServiceGrpcAsyncIOTransport
|
| 22 |
+
from .rest import RetrieverServiceRestInterceptor, RetrieverServiceRestTransport
|
| 23 |
+
|
| 24 |
+
# Compile a registry of transports.
|
| 25 |
+
_transport_registry = OrderedDict() # type: Dict[str, Type[RetrieverServiceTransport]]
|
| 26 |
+
_transport_registry["grpc"] = RetrieverServiceGrpcTransport
|
| 27 |
+
_transport_registry["grpc_asyncio"] = RetrieverServiceGrpcAsyncIOTransport
|
| 28 |
+
_transport_registry["rest"] = RetrieverServiceRestTransport
|
| 29 |
+
|
| 30 |
+
__all__ = (
|
| 31 |
+
"RetrieverServiceTransport",
|
| 32 |
+
"RetrieverServiceGrpcTransport",
|
| 33 |
+
"RetrieverServiceGrpcAsyncIOTransport",
|
| 34 |
+
"RetrieverServiceRestTransport",
|
| 35 |
+
"RetrieverServiceRestInterceptor",
|
| 36 |
+
)
|
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/retriever_service/transports/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (919 Bytes). View file
|
|
|
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta/services/retriever_service/transports/__pycache__/base.cpython-311.pyc
ADDED
|
Binary file (20.8 kB). View file
|
|
|