koichi12 commited on
Commit
b292475
·
verified ·
1 Parent(s): dae2552

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/gapic_version.py +16 -0
  2. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/__init__.py +15 -0
  3. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/cache_service/__init__.py +22 -0
  4. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/cache_service/__pycache__/pagers.cpython-311.pyc +0 -0
  5. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/cache_service/async_client.py +950 -0
  6. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/cache_service/client.py +1340 -0
  7. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/cache_service/pagers.py +197 -0
  8. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/cache_service/transports/grpc.py +517 -0
  9. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/cache_service/transports/grpc_asyncio.py +573 -0
  10. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/cache_service/transports/rest.py +1428 -0
  11. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/cache_service/transports/rest_base.py +399 -0
  12. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/__init__.py +22 -0
  13. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/__pycache__/__init__.cpython-311.pyc +0 -0
  14. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/__pycache__/async_client.cpython-311.pyc +0 -0
  15. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/__pycache__/client.cpython-311.pyc +0 -0
  16. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/async_client.py +1366 -0
  17. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/client.py +1751 -0
  18. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/transports/__init__.py +36 -0
  19. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/transports/__pycache__/__init__.cpython-311.pyc +0 -0
  20. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/transports/__pycache__/base.cpython-311.pyc +0 -0
  21. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/transports/__pycache__/grpc.cpython-311.pyc +0 -0
  22. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/transports/__pycache__/grpc_asyncio.cpython-311.pyc +0 -0
  23. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/transports/__pycache__/rest.cpython-311.pyc +0 -0
  24. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/transports/__pycache__/rest_base.cpython-311.pyc +0 -0
  25. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/transports/base.py +298 -0
  26. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/transports/grpc.py +591 -0
  27. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/transports/grpc_asyncio.py +654 -0
  28. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/transports/rest.py +1726 -0
  29. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/transports/rest_base.py +510 -0
  30. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/permission_service/__init__.py +22 -0
  31. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/permission_service/transports/__init__.py +36 -0
  32. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/permission_service/transports/__pycache__/base.cpython-311.pyc +0 -0
  33. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/permission_service/transports/__pycache__/grpc_asyncio.cpython-311.pyc +0 -0
  34. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/permission_service/transports/base.py +272 -0
  35. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/permission_service/transports/grpc.py +541 -0
  36. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/permission_service/transports/grpc_asyncio.py +604 -0
  37. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/permission_service/transports/rest.py +1671 -0
  38. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/permission_service/transports/rest_base.py +493 -0
  39. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/retriever_service/__init__.py +22 -0
  40. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/retriever_service/__pycache__/__init__.cpython-311.pyc +0 -0
  41. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/retriever_service/__pycache__/async_client.cpython-311.pyc +0 -0
  42. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/retriever_service/__pycache__/pagers.cpython-311.pyc +0 -0
  43. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/retriever_service/async_client.py +0 -0
  44. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/retriever_service/client.py +0 -0
  45. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/retriever_service/pagers.py +509 -0
  46. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/retriever_service/transports/__init__.py +36 -0
  47. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/retriever_service/transports/__pycache__/__init__.cpython-311.pyc +0 -0
  48. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/retriever_service/transports/__pycache__/base.cpython-311.pyc +0 -0
  49. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/retriever_service/transports/__pycache__/grpc.cpython-311.pyc +0 -0
  50. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/retriever_service/transports/__pycache__/grpc_asyncio.cpython-311.pyc +0 -0
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/gapic_version.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ __version__ = "0.6.15" # {x-release-please-version}
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/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_v1alpha/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_v1alpha/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_v1alpha/services/cache_service/async_client.py ADDED
@@ -0,0 +1,950 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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_v1alpha 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_v1alpha.services.cache_service import pagers
52
+ from google.ai.generativelanguage_v1alpha.types import (
53
+ cached_content as gag_cached_content,
54
+ )
55
+ from google.ai.generativelanguage_v1alpha.types import cache_service
56
+ from google.ai.generativelanguage_v1alpha.types import cached_content
57
+ from google.ai.generativelanguage_v1alpha.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_v1alpha.CacheServiceAsyncClient`.",
287
+ extra={
288
+ "serviceName": "google.ai.generativelanguage.v1alpha.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.v1alpha.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_v1alpha
324
+
325
+ async def sample_list_cached_contents():
326
+ # Create a client
327
+ client = generativelanguage_v1alpha.CacheServiceAsyncClient()
328
+
329
+ # Initialize request argument(s)
330
+ request = generativelanguage_v1alpha.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_v1alpha.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_v1alpha.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_v1alpha
418
+
419
+ async def sample_create_cached_content():
420
+ # Create a client
421
+ client = generativelanguage_v1alpha.CacheServiceAsyncClient()
422
+
423
+ # Initialize request argument(s)
424
+ request = generativelanguage_v1alpha.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_v1alpha.types.CreateCachedContentRequest, dict]]):
435
+ The request object. Request to create CachedContent.
436
+ cached_content (:class:`google.ai.generativelanguage_v1alpha.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_v1alpha.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_v1alpha
522
+
523
+ async def sample_get_cached_content():
524
+ # Create a client
525
+ client = generativelanguage_v1alpha.CacheServiceAsyncClient()
526
+
527
+ # Initialize request argument(s)
528
+ request = generativelanguage_v1alpha.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_v1alpha.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_v1alpha.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_v1alpha
635
+
636
+ async def sample_update_cached_content():
637
+ # Create a client
638
+ client = generativelanguage_v1alpha.CacheServiceAsyncClient()
639
+
640
+ # Initialize request argument(s)
641
+ request = generativelanguage_v1alpha.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_v1alpha.types.UpdateCachedContentRequest, dict]]):
652
+ The request object. Request to update CachedContent.
653
+ cached_content (:class:`google.ai.generativelanguage_v1alpha.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_v1alpha.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_v1alpha
754
+
755
+ async def sample_delete_cached_content():
756
+ # Create a client
757
+ client = generativelanguage_v1alpha.CacheServiceAsyncClient()
758
+
759
+ # Initialize request argument(s)
760
+ request = generativelanguage_v1alpha.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_v1alpha.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_v1alpha/services/cache_service/client.py ADDED
@@ -0,0 +1,1340 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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_v1alpha 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_v1alpha.services.cache_service import pagers
67
+ from google.ai.generativelanguage_v1alpha.types import (
68
+ cached_content as gag_cached_content,
69
+ )
70
+ from google.ai.generativelanguage_v1alpha.types import cache_service
71
+ from google.ai.generativelanguage_v1alpha.types import cached_content
72
+ from google.ai.generativelanguage_v1alpha.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_v1alpha.CacheServiceClient`.",
684
+ extra={
685
+ "serviceName": "google.ai.generativelanguage.v1alpha.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.v1alpha.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_v1alpha
721
+
722
+ def sample_list_cached_contents():
723
+ # Create a client
724
+ client = generativelanguage_v1alpha.CacheServiceClient()
725
+
726
+ # Initialize request argument(s)
727
+ request = generativelanguage_v1alpha.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_v1alpha.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_v1alpha.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_v1alpha
813
+
814
+ def sample_create_cached_content():
815
+ # Create a client
816
+ client = generativelanguage_v1alpha.CacheServiceClient()
817
+
818
+ # Initialize request argument(s)
819
+ request = generativelanguage_v1alpha.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_v1alpha.types.CreateCachedContentRequest, dict]):
830
+ The request object. Request to create CachedContent.
831
+ cached_content (google.ai.generativelanguage_v1alpha.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_v1alpha.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_v1alpha
914
+
915
+ def sample_get_cached_content():
916
+ # Create a client
917
+ client = generativelanguage_v1alpha.CacheServiceClient()
918
+
919
+ # Initialize request argument(s)
920
+ request = generativelanguage_v1alpha.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_v1alpha.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_v1alpha.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_v1alpha
1024
+
1025
+ def sample_update_cached_content():
1026
+ # Create a client
1027
+ client = generativelanguage_v1alpha.CacheServiceClient()
1028
+
1029
+ # Initialize request argument(s)
1030
+ request = generativelanguage_v1alpha.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_v1alpha.types.UpdateCachedContentRequest, dict]):
1041
+ The request object. Request to update CachedContent.
1042
+ cached_content (google.ai.generativelanguage_v1alpha.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_v1alpha.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_v1alpha
1140
+
1141
+ def sample_delete_cached_content():
1142
+ # Create a client
1143
+ client = generativelanguage_v1alpha.CacheServiceClient()
1144
+
1145
+ # Initialize request argument(s)
1146
+ request = generativelanguage_v1alpha.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_v1alpha.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_v1alpha/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_v1alpha.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_v1alpha.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_v1alpha.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_v1alpha.types.ListCachedContentsRequest):
78
+ The initial request object.
79
+ response (google.ai.generativelanguage_v1alpha.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_v1alpha.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_v1alpha.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_v1alpha.types.ListCachedContentsRequest):
154
+ The initial request object.
155
+ response (google.ai.generativelanguage_v1alpha.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_v1alpha/services/cache_service/transports/grpc.py ADDED
@@ -0,0 +1,517 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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_v1alpha.types import (
34
+ cached_content as gag_cached_content,
35
+ )
36
+ from google.ai.generativelanguage_v1alpha.types import cache_service
37
+ from google.ai.generativelanguage_v1alpha.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.v1alpha.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.v1alpha.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.v1alpha.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.v1alpha.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.v1alpha.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.v1alpha.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.v1alpha.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_v1alpha/services/cache_service/transports/grpc_asyncio.py ADDED
@@ -0,0 +1,573 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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_v1alpha.types import (
37
+ cached_content as gag_cached_content,
38
+ )
39
+ from google.ai.generativelanguage_v1alpha.types import cache_service
40
+ from google.ai.generativelanguage_v1alpha.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.v1alpha.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.v1alpha.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.v1alpha.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.v1alpha.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.v1alpha.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.v1alpha.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.v1alpha.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_v1alpha/services/cache_service/transports/rest.py ADDED
@@ -0,0 +1,1428 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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_v1alpha.types import (
33
+ cached_content as gag_cached_content,
34
+ )
35
+ from google.ai.generativelanguage_v1alpha.types import cache_service
36
+ from google.ai.generativelanguage_v1alpha.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_v1alpha.CacheServiceClient.CreateCachedContent",
477
+ extra={
478
+ "serviceName": "google.ai.generativelanguage.v1alpha.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_v1alpha.CacheServiceClient.create_cached_content",
524
+ extra={
525
+ "serviceName": "google.ai.generativelanguage.v1alpha.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_v1alpha.CacheServiceClient.DeleteCachedContent",
618
+ extra={
619
+ "serviceName": "google.ai.generativelanguage.v1alpha.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_v1alpha.CacheServiceClient.GetCachedContent",
736
+ extra={
737
+ "serviceName": "google.ai.generativelanguage.v1alpha.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_v1alpha.CacheServiceClient.get_cached_content",
780
+ extra={
781
+ "serviceName": "google.ai.generativelanguage.v1alpha.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_v1alpha.CacheServiceClient.ListCachedContents",
878
+ extra={
879
+ "serviceName": "google.ai.generativelanguage.v1alpha.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_v1alpha.CacheServiceClient.list_cached_contents",
924
+ extra={
925
+ "serviceName": "google.ai.generativelanguage.v1alpha.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_v1alpha.CacheServiceClient.UpdateCachedContent",
1033
+ extra={
1034
+ "serviceName": "google.ai.generativelanguage.v1alpha.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_v1alpha.CacheServiceClient.update_cached_content",
1080
+ extra={
1081
+ "serviceName": "google.ai.generativelanguage.v1alpha.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_v1alpha.CacheServiceClient.GetOperation",
1230
+ extra={
1231
+ "serviceName": "google.ai.generativelanguage.v1alpha.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_v1alpha.CacheServiceAsyncClient.GetOperation",
1271
+ extra={
1272
+ "serviceName": "google.ai.generativelanguage.v1alpha.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_v1alpha.CacheServiceClient.ListOperations",
1370
+ extra={
1371
+ "serviceName": "google.ai.generativelanguage.v1alpha.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_v1alpha.CacheServiceAsyncClient.ListOperations",
1411
+ extra={
1412
+ "serviceName": "google.ai.generativelanguage.v1alpha.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_v1alpha/services/cache_service/transports/rest_base.py ADDED
@@ -0,0 +1,399 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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_v1alpha.types import (
26
+ cached_content as gag_cached_content,
27
+ )
28
+ from google.ai.generativelanguage_v1alpha.types import cache_service
29
+ from google.ai.generativelanguage_v1alpha.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": "/v1alpha/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": "/v1alpha/{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": "/v1alpha/{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": "/v1alpha/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": "/v1alpha/{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": "/v1alpha/{name=tunedModels/*/operations/*}",
346
+ },
347
+ {
348
+ "method": "get",
349
+ "uri": "/v1alpha/{name=generatedFiles/*/operations/*}",
350
+ },
351
+ {
352
+ "method": "get",
353
+ "uri": "/v1alpha/{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": "/v1alpha/{name=tunedModels/*}/operations",
379
+ },
380
+ {
381
+ "method": "get",
382
+ "uri": "/v1alpha/{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_v1alpha/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_v1alpha/services/generative_service/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (418 Bytes). View file
 
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/__pycache__/async_client.cpython-311.pyc ADDED
Binary file (56.5 kB). View file
 
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/__pycache__/client.cpython-311.pyc ADDED
Binary file (72.5 kB). View file
 
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/async_client.py ADDED
@@ -0,0 +1,1366 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ AsyncIterator,
22
+ Awaitable,
23
+ Callable,
24
+ Dict,
25
+ Mapping,
26
+ MutableMapping,
27
+ MutableSequence,
28
+ Optional,
29
+ Sequence,
30
+ Tuple,
31
+ Type,
32
+ Union,
33
+ )
34
+
35
+ from google.api_core import exceptions as core_exceptions
36
+ from google.api_core import gapic_v1
37
+ from google.api_core import retry_async as retries
38
+ from google.api_core.client_options import ClientOptions
39
+ from google.auth import credentials as ga_credentials # type: ignore
40
+ from google.oauth2 import service_account # type: ignore
41
+
42
+ from google.ai.generativelanguage_v1alpha import gapic_version as package_version
43
+
44
+ try:
45
+ OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None]
46
+ except AttributeError: # pragma: NO COVER
47
+ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore
48
+
49
+ from google.longrunning import operations_pb2 # type: ignore
50
+
51
+ from google.ai.generativelanguage_v1alpha.types import generative_service, safety
52
+ from google.ai.generativelanguage_v1alpha.types import content
53
+ from google.ai.generativelanguage_v1alpha.types import content as gag_content
54
+
55
+ from .client import GenerativeServiceClient
56
+ from .transports.base import DEFAULT_CLIENT_INFO, GenerativeServiceTransport
57
+ from .transports.grpc_asyncio import GenerativeServiceGrpcAsyncIOTransport
58
+
59
+ try:
60
+ from google.api_core import client_logging # type: ignore
61
+
62
+ CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER
63
+ except ImportError: # pragma: NO COVER
64
+ CLIENT_LOGGING_SUPPORTED = False
65
+
66
+ _LOGGER = std_logging.getLogger(__name__)
67
+
68
+
69
+ class GenerativeServiceAsyncClient:
70
+ """API for using Large Models that generate multimodal content
71
+ and have additional capabilities beyond text generation.
72
+ """
73
+
74
+ _client: GenerativeServiceClient
75
+
76
+ # Copy defaults from the synchronous client for use here.
77
+ # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead.
78
+ DEFAULT_ENDPOINT = GenerativeServiceClient.DEFAULT_ENDPOINT
79
+ DEFAULT_MTLS_ENDPOINT = GenerativeServiceClient.DEFAULT_MTLS_ENDPOINT
80
+ _DEFAULT_ENDPOINT_TEMPLATE = GenerativeServiceClient._DEFAULT_ENDPOINT_TEMPLATE
81
+ _DEFAULT_UNIVERSE = GenerativeServiceClient._DEFAULT_UNIVERSE
82
+
83
+ cached_content_path = staticmethod(GenerativeServiceClient.cached_content_path)
84
+ parse_cached_content_path = staticmethod(
85
+ GenerativeServiceClient.parse_cached_content_path
86
+ )
87
+ model_path = staticmethod(GenerativeServiceClient.model_path)
88
+ parse_model_path = staticmethod(GenerativeServiceClient.parse_model_path)
89
+ common_billing_account_path = staticmethod(
90
+ GenerativeServiceClient.common_billing_account_path
91
+ )
92
+ parse_common_billing_account_path = staticmethod(
93
+ GenerativeServiceClient.parse_common_billing_account_path
94
+ )
95
+ common_folder_path = staticmethod(GenerativeServiceClient.common_folder_path)
96
+ parse_common_folder_path = staticmethod(
97
+ GenerativeServiceClient.parse_common_folder_path
98
+ )
99
+ common_organization_path = staticmethod(
100
+ GenerativeServiceClient.common_organization_path
101
+ )
102
+ parse_common_organization_path = staticmethod(
103
+ GenerativeServiceClient.parse_common_organization_path
104
+ )
105
+ common_project_path = staticmethod(GenerativeServiceClient.common_project_path)
106
+ parse_common_project_path = staticmethod(
107
+ GenerativeServiceClient.parse_common_project_path
108
+ )
109
+ common_location_path = staticmethod(GenerativeServiceClient.common_location_path)
110
+ parse_common_location_path = staticmethod(
111
+ GenerativeServiceClient.parse_common_location_path
112
+ )
113
+
114
+ @classmethod
115
+ def from_service_account_info(cls, info: dict, *args, **kwargs):
116
+ """Creates an instance of this client using the provided credentials
117
+ info.
118
+
119
+ Args:
120
+ info (dict): The service account private key info.
121
+ args: Additional arguments to pass to the constructor.
122
+ kwargs: Additional arguments to pass to the constructor.
123
+
124
+ Returns:
125
+ GenerativeServiceAsyncClient: The constructed client.
126
+ """
127
+ return GenerativeServiceClient.from_service_account_info.__func__(GenerativeServiceAsyncClient, info, *args, **kwargs) # type: ignore
128
+
129
+ @classmethod
130
+ def from_service_account_file(cls, filename: str, *args, **kwargs):
131
+ """Creates an instance of this client using the provided credentials
132
+ file.
133
+
134
+ Args:
135
+ filename (str): The path to the service account private key json
136
+ file.
137
+ args: Additional arguments to pass to the constructor.
138
+ kwargs: Additional arguments to pass to the constructor.
139
+
140
+ Returns:
141
+ GenerativeServiceAsyncClient: The constructed client.
142
+ """
143
+ return GenerativeServiceClient.from_service_account_file.__func__(GenerativeServiceAsyncClient, filename, *args, **kwargs) # type: ignore
144
+
145
+ from_service_account_json = from_service_account_file
146
+
147
+ @classmethod
148
+ def get_mtls_endpoint_and_cert_source(
149
+ cls, client_options: Optional[ClientOptions] = None
150
+ ):
151
+ """Return the API endpoint and client cert source for mutual TLS.
152
+
153
+ The client cert source is determined in the following order:
154
+ (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the
155
+ client cert source is None.
156
+ (2) if `client_options.client_cert_source` is provided, use the provided one; if the
157
+ default client cert source exists, use the default one; otherwise the client cert
158
+ source is None.
159
+
160
+ The API endpoint is determined in the following order:
161
+ (1) if `client_options.api_endpoint` if provided, use the provided one.
162
+ (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the
163
+ default mTLS endpoint; if the environment variable is "never", use the default API
164
+ endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise
165
+ use the default API endpoint.
166
+
167
+ More details can be found at https://google.aip.dev/auth/4114.
168
+
169
+ Args:
170
+ client_options (google.api_core.client_options.ClientOptions): Custom options for the
171
+ client. Only the `api_endpoint` and `client_cert_source` properties may be used
172
+ in this method.
173
+
174
+ Returns:
175
+ Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the
176
+ client cert source to use.
177
+
178
+ Raises:
179
+ google.auth.exceptions.MutualTLSChannelError: If any errors happen.
180
+ """
181
+ return GenerativeServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore
182
+
183
+ @property
184
+ def transport(self) -> GenerativeServiceTransport:
185
+ """Returns the transport used by the client instance.
186
+
187
+ Returns:
188
+ GenerativeServiceTransport: The transport used by the client instance.
189
+ """
190
+ return self._client.transport
191
+
192
+ @property
193
+ def api_endpoint(self):
194
+ """Return the API endpoint used by the client instance.
195
+
196
+ Returns:
197
+ str: The API endpoint used by the client instance.
198
+ """
199
+ return self._client._api_endpoint
200
+
201
+ @property
202
+ def universe_domain(self) -> str:
203
+ """Return the universe domain used by the client instance.
204
+
205
+ Returns:
206
+ str: The universe domain used
207
+ by the client instance.
208
+ """
209
+ return self._client._universe_domain
210
+
211
+ get_transport_class = GenerativeServiceClient.get_transport_class
212
+
213
+ def __init__(
214
+ self,
215
+ *,
216
+ credentials: Optional[ga_credentials.Credentials] = None,
217
+ transport: Optional[
218
+ Union[
219
+ str,
220
+ GenerativeServiceTransport,
221
+ Callable[..., GenerativeServiceTransport],
222
+ ]
223
+ ] = "grpc_asyncio",
224
+ client_options: Optional[ClientOptions] = None,
225
+ client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
226
+ ) -> None:
227
+ """Instantiates the generative service async client.
228
+
229
+ Args:
230
+ credentials (Optional[google.auth.credentials.Credentials]): The
231
+ authorization credentials to attach to requests. These
232
+ credentials identify the application to the service; if none
233
+ are specified, the client will attempt to ascertain the
234
+ credentials from the environment.
235
+ transport (Optional[Union[str,GenerativeServiceTransport,Callable[..., GenerativeServiceTransport]]]):
236
+ The transport to use, or a Callable that constructs and returns a new transport to use.
237
+ If a Callable is given, it will be called with the same set of initialization
238
+ arguments as used in the GenerativeServiceTransport constructor.
239
+ If set to None, a transport is chosen automatically.
240
+ client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]):
241
+ Custom options for the client.
242
+
243
+ 1. The ``api_endpoint`` property can be used to override the
244
+ default endpoint provided by the client when ``transport`` is
245
+ not explicitly provided. Only if this property is not set and
246
+ ``transport`` was not explicitly provided, the endpoint is
247
+ determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment
248
+ variable, which have one of the following values:
249
+ "always" (always use the default mTLS endpoint), "never" (always
250
+ use the default regular endpoint) and "auto" (auto-switch to the
251
+ default mTLS endpoint if client certificate is present; this is
252
+ the default value).
253
+
254
+ 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable
255
+ is "true", then the ``client_cert_source`` property can be used
256
+ to provide a client certificate for mTLS transport. If
257
+ not provided, the default SSL client certificate will be used if
258
+ present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not
259
+ set, no client certificate will be used.
260
+
261
+ 3. The ``universe_domain`` property can be used to override the
262
+ default "googleapis.com" universe. Note that ``api_endpoint``
263
+ property still takes precedence; and ``universe_domain`` is
264
+ currently not supported for mTLS.
265
+
266
+ client_info (google.api_core.gapic_v1.client_info.ClientInfo):
267
+ The client info used to send a user-agent string along with
268
+ API requests. If ``None``, then default info will be used.
269
+ Generally, you only need to set this if you're developing
270
+ your own client library.
271
+
272
+ Raises:
273
+ google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
274
+ creation failed for any reason.
275
+ """
276
+ self._client = GenerativeServiceClient(
277
+ credentials=credentials,
278
+ transport=transport,
279
+ client_options=client_options,
280
+ client_info=client_info,
281
+ )
282
+
283
+ if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
284
+ std_logging.DEBUG
285
+ ): # pragma: NO COVER
286
+ _LOGGER.debug(
287
+ "Created client `google.ai.generativelanguage_v1alpha.GenerativeServiceAsyncClient`.",
288
+ extra={
289
+ "serviceName": "google.ai.generativelanguage.v1alpha.GenerativeService",
290
+ "universeDomain": getattr(
291
+ self._client._transport._credentials, "universe_domain", ""
292
+ ),
293
+ "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}",
294
+ "credentialsInfo": getattr(
295
+ self.transport._credentials, "get_cred_info", lambda: None
296
+ )(),
297
+ }
298
+ if hasattr(self._client._transport, "_credentials")
299
+ else {
300
+ "serviceName": "google.ai.generativelanguage.v1alpha.GenerativeService",
301
+ "credentialsType": None,
302
+ },
303
+ )
304
+
305
+ async def generate_content(
306
+ self,
307
+ request: Optional[
308
+ Union[generative_service.GenerateContentRequest, dict]
309
+ ] = None,
310
+ *,
311
+ model: Optional[str] = None,
312
+ contents: Optional[MutableSequence[content.Content]] = None,
313
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
314
+ timeout: Union[float, object] = gapic_v1.method.DEFAULT,
315
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
316
+ ) -> generative_service.GenerateContentResponse:
317
+ r"""Generates a model response given an input
318
+ ``GenerateContentRequest``. Refer to the `text generation
319
+ guide <https://ai.google.dev/gemini-api/docs/text-generation>`__
320
+ for detailed usage information. Input capabilities differ
321
+ between models, including tuned models. Refer to the `model
322
+ guide <https://ai.google.dev/gemini-api/docs/models/gemini>`__
323
+ and `tuning
324
+ guide <https://ai.google.dev/gemini-api/docs/model-tuning>`__
325
+ for details.
326
+
327
+ .. code-block:: python
328
+
329
+ # This snippet has been automatically generated and should be regarded as a
330
+ # code template only.
331
+ # It will require modifications to work:
332
+ # - It may require correct/in-range values for request initialization.
333
+ # - It may require specifying regional endpoints when creating the service
334
+ # client as shown in:
335
+ # https://googleapis.dev/python/google-api-core/latest/client_options.html
336
+ from google.ai import generativelanguage_v1alpha
337
+
338
+ async def sample_generate_content():
339
+ # Create a client
340
+ client = generativelanguage_v1alpha.GenerativeServiceAsyncClient()
341
+
342
+ # Initialize request argument(s)
343
+ request = generativelanguage_v1alpha.GenerateContentRequest(
344
+ model="model_value",
345
+ )
346
+
347
+ # Make the request
348
+ response = await client.generate_content(request=request)
349
+
350
+ # Handle the response
351
+ print(response)
352
+
353
+ Args:
354
+ request (Optional[Union[google.ai.generativelanguage_v1alpha.types.GenerateContentRequest, dict]]):
355
+ The request object. Request to generate a completion from
356
+ the model.
357
+ model (:class:`str`):
358
+ Required. The name of the ``Model`` to use for
359
+ generating the completion.
360
+
361
+ Format: ``models/{model}``.
362
+
363
+ This corresponds to the ``model`` field
364
+ on the ``request`` instance; if ``request`` is provided, this
365
+ should not be set.
366
+ contents (:class:`MutableSequence[google.ai.generativelanguage_v1alpha.types.Content]`):
367
+ Required. The content of the current conversation with
368
+ the model.
369
+
370
+ For single-turn queries, this is a single instance. For
371
+ multi-turn queries like
372
+ `chat <https://ai.google.dev/gemini-api/docs/text-generation#chat>`__,
373
+ this is a repeated field that contains the conversation
374
+ history and the latest request.
375
+
376
+ This corresponds to the ``contents`` field
377
+ on the ``request`` instance; if ``request`` is provided, this
378
+ should not be set.
379
+ retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any,
380
+ should be retried.
381
+ timeout (float): The timeout for this request.
382
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
383
+ sent along with the request as metadata. Normally, each value must be of type `str`,
384
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
385
+ be of type `bytes`.
386
+
387
+ Returns:
388
+ google.ai.generativelanguage_v1alpha.types.GenerateContentResponse:
389
+ Response from the model supporting multiple candidate
390
+ responses.
391
+
392
+ Safety ratings and content filtering are reported for
393
+ both prompt in
394
+ GenerateContentResponse.prompt_feedback and for each
395
+ candidate in finish_reason and in safety_ratings. The
396
+ API: - Returns either all requested candidates or
397
+ none of them - Returns no candidates at all only if
398
+ there was something wrong with the prompt (check
399
+ prompt_feedback) - Reports feedback on each candidate
400
+ in finish_reason and safety_ratings.
401
+
402
+ """
403
+ # Create or coerce a protobuf request object.
404
+ # - Quick check: If we got a request object, we should *not* have
405
+ # gotten any keyword arguments that map to the request.
406
+ has_flattened_params = any([model, contents])
407
+ if request is not None and has_flattened_params:
408
+ raise ValueError(
409
+ "If the `request` argument is set, then none of "
410
+ "the individual field arguments should be set."
411
+ )
412
+
413
+ # - Use the request object if provided (there's no risk of modifying the input as
414
+ # there are no flattened fields), or create one.
415
+ if not isinstance(request, generative_service.GenerateContentRequest):
416
+ request = generative_service.GenerateContentRequest(request)
417
+
418
+ # If we have keyword arguments corresponding to fields on the
419
+ # request, apply these.
420
+ if model is not None:
421
+ request.model = model
422
+ if contents:
423
+ request.contents.extend(contents)
424
+
425
+ # Wrap the RPC method; this adds retry and timeout information,
426
+ # and friendly error handling.
427
+ rpc = self._client._transport._wrapped_methods[
428
+ self._client._transport.generate_content
429
+ ]
430
+
431
+ # Certain fields should be provided within the metadata header;
432
+ # add these here.
433
+ metadata = tuple(metadata) + (
434
+ gapic_v1.routing_header.to_grpc_metadata((("model", request.model),)),
435
+ )
436
+
437
+ # Validate the universe domain.
438
+ self._client._validate_universe_domain()
439
+
440
+ # Send the request.
441
+ response = await rpc(
442
+ request,
443
+ retry=retry,
444
+ timeout=timeout,
445
+ metadata=metadata,
446
+ )
447
+
448
+ # Done; return the response.
449
+ return response
450
+
451
+ async def generate_answer(
452
+ self,
453
+ request: Optional[Union[generative_service.GenerateAnswerRequest, dict]] = None,
454
+ *,
455
+ model: Optional[str] = None,
456
+ contents: Optional[MutableSequence[content.Content]] = None,
457
+ safety_settings: Optional[MutableSequence[safety.SafetySetting]] = None,
458
+ answer_style: Optional[
459
+ generative_service.GenerateAnswerRequest.AnswerStyle
460
+ ] = None,
461
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
462
+ timeout: Union[float, object] = gapic_v1.method.DEFAULT,
463
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
464
+ ) -> generative_service.GenerateAnswerResponse:
465
+ r"""Generates a grounded answer from the model given an input
466
+ ``GenerateAnswerRequest``.
467
+
468
+ .. code-block:: python
469
+
470
+ # This snippet has been automatically generated and should be regarded as a
471
+ # code template only.
472
+ # It will require modifications to work:
473
+ # - It may require correct/in-range values for request initialization.
474
+ # - It may require specifying regional endpoints when creating the service
475
+ # client as shown in:
476
+ # https://googleapis.dev/python/google-api-core/latest/client_options.html
477
+ from google.ai import generativelanguage_v1alpha
478
+
479
+ async def sample_generate_answer():
480
+ # Create a client
481
+ client = generativelanguage_v1alpha.GenerativeServiceAsyncClient()
482
+
483
+ # Initialize request argument(s)
484
+ request = generativelanguage_v1alpha.GenerateAnswerRequest(
485
+ model="model_value",
486
+ answer_style="VERBOSE",
487
+ )
488
+
489
+ # Make the request
490
+ response = await client.generate_answer(request=request)
491
+
492
+ # Handle the response
493
+ print(response)
494
+
495
+ Args:
496
+ request (Optional[Union[google.ai.generativelanguage_v1alpha.types.GenerateAnswerRequest, dict]]):
497
+ The request object. Request to generate a grounded answer from the
498
+ ``Model``.
499
+ model (:class:`str`):
500
+ Required. The name of the ``Model`` to use for
501
+ generating the grounded response.
502
+
503
+ Format: ``model=models/{model}``.
504
+
505
+ This corresponds to the ``model`` field
506
+ on the ``request`` instance; if ``request`` is provided, this
507
+ should not be set.
508
+ contents (:class:`MutableSequence[google.ai.generativelanguage_v1alpha.types.Content]`):
509
+ Required. The content of the current conversation with
510
+ the ``Model``. For single-turn queries, this is a single
511
+ question to answer. For multi-turn queries, this is a
512
+ repeated field that contains conversation history and
513
+ the last ``Content`` in the list containing the
514
+ question.
515
+
516
+ Note: ``GenerateAnswer`` only supports queries in
517
+ English.
518
+
519
+ This corresponds to the ``contents`` field
520
+ on the ``request`` instance; if ``request`` is provided, this
521
+ should not be set.
522
+ safety_settings (:class:`MutableSequence[google.ai.generativelanguage_v1alpha.types.SafetySetting]`):
523
+ Optional. A list of unique ``SafetySetting`` instances
524
+ for blocking unsafe content.
525
+
526
+ This will be enforced on the
527
+ ``GenerateAnswerRequest.contents`` and
528
+ ``GenerateAnswerResponse.candidate``. There should not
529
+ be more than one setting for each ``SafetyCategory``
530
+ type. The API will block any contents and responses that
531
+ fail to meet the thresholds set by these settings. This
532
+ list overrides the default settings for each
533
+ ``SafetyCategory`` specified in the safety_settings. If
534
+ there is no ``SafetySetting`` for a given
535
+ ``SafetyCategory`` provided in the list, the API will
536
+ use the default safety setting for that category. Harm
537
+ categories HARM_CATEGORY_HATE_SPEECH,
538
+ HARM_CATEGORY_SEXUALLY_EXPLICIT,
539
+ HARM_CATEGORY_DANGEROUS_CONTENT,
540
+ HARM_CATEGORY_HARASSMENT are supported. Refer to the
541
+ `guide <https://ai.google.dev/gemini-api/docs/safety-settings>`__
542
+ for detailed information on available safety settings.
543
+ Also refer to the `Safety
544
+ guidance <https://ai.google.dev/gemini-api/docs/safety-guidance>`__
545
+ to learn how to incorporate safety considerations in
546
+ your AI applications.
547
+
548
+ This corresponds to the ``safety_settings`` field
549
+ on the ``request`` instance; if ``request`` is provided, this
550
+ should not be set.
551
+ answer_style (:class:`google.ai.generativelanguage_v1alpha.types.GenerateAnswerRequest.AnswerStyle`):
552
+ Required. Style in which answers
553
+ should be returned.
554
+
555
+ This corresponds to the ``answer_style`` field
556
+ on the ``request`` instance; if ``request`` is provided, this
557
+ should not be set.
558
+ retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any,
559
+ should be retried.
560
+ timeout (float): The timeout for this request.
561
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
562
+ sent along with the request as metadata. Normally, each value must be of type `str`,
563
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
564
+ be of type `bytes`.
565
+
566
+ Returns:
567
+ google.ai.generativelanguage_v1alpha.types.GenerateAnswerResponse:
568
+ Response from the model for a
569
+ grounded answer.
570
+
571
+ """
572
+ # Create or coerce a protobuf request object.
573
+ # - Quick check: If we got a request object, we should *not* have
574
+ # gotten any keyword arguments that map to the request.
575
+ has_flattened_params = any([model, contents, safety_settings, answer_style])
576
+ if request is not None and has_flattened_params:
577
+ raise ValueError(
578
+ "If the `request` argument is set, then none of "
579
+ "the individual field arguments should be set."
580
+ )
581
+
582
+ # - Use the request object if provided (there's no risk of modifying the input as
583
+ # there are no flattened fields), or create one.
584
+ if not isinstance(request, generative_service.GenerateAnswerRequest):
585
+ request = generative_service.GenerateAnswerRequest(request)
586
+
587
+ # If we have keyword arguments corresponding to fields on the
588
+ # request, apply these.
589
+ if model is not None:
590
+ request.model = model
591
+ if answer_style is not None:
592
+ request.answer_style = answer_style
593
+ if contents:
594
+ request.contents.extend(contents)
595
+ if safety_settings:
596
+ request.safety_settings.extend(safety_settings)
597
+
598
+ # Wrap the RPC method; this adds retry and timeout information,
599
+ # and friendly error handling.
600
+ rpc = self._client._transport._wrapped_methods[
601
+ self._client._transport.generate_answer
602
+ ]
603
+
604
+ # Certain fields should be provided within the metadata header;
605
+ # add these here.
606
+ metadata = tuple(metadata) + (
607
+ gapic_v1.routing_header.to_grpc_metadata((("model", request.model),)),
608
+ )
609
+
610
+ # Validate the universe domain.
611
+ self._client._validate_universe_domain()
612
+
613
+ # Send the request.
614
+ response = await rpc(
615
+ request,
616
+ retry=retry,
617
+ timeout=timeout,
618
+ metadata=metadata,
619
+ )
620
+
621
+ # Done; return the response.
622
+ return response
623
+
624
+ def stream_generate_content(
625
+ self,
626
+ request: Optional[
627
+ Union[generative_service.GenerateContentRequest, dict]
628
+ ] = None,
629
+ *,
630
+ model: Optional[str] = None,
631
+ contents: Optional[MutableSequence[content.Content]] = None,
632
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
633
+ timeout: Union[float, object] = gapic_v1.method.DEFAULT,
634
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
635
+ ) -> Awaitable[AsyncIterable[generative_service.GenerateContentResponse]]:
636
+ r"""Generates a `streamed
637
+ response <https://ai.google.dev/gemini-api/docs/text-generation?lang=python#generate-a-text-stream>`__
638
+ from the model given an input ``GenerateContentRequest``.
639
+
640
+ .. code-block:: python
641
+
642
+ # This snippet has been automatically generated and should be regarded as a
643
+ # code template only.
644
+ # It will require modifications to work:
645
+ # - It may require correct/in-range values for request initialization.
646
+ # - It may require specifying regional endpoints when creating the service
647
+ # client as shown in:
648
+ # https://googleapis.dev/python/google-api-core/latest/client_options.html
649
+ from google.ai import generativelanguage_v1alpha
650
+
651
+ async def sample_stream_generate_content():
652
+ # Create a client
653
+ client = generativelanguage_v1alpha.GenerativeServiceAsyncClient()
654
+
655
+ # Initialize request argument(s)
656
+ request = generativelanguage_v1alpha.GenerateContentRequest(
657
+ model="model_value",
658
+ )
659
+
660
+ # Make the request
661
+ stream = await client.stream_generate_content(request=request)
662
+
663
+ # Handle the response
664
+ async for response in stream:
665
+ print(response)
666
+
667
+ Args:
668
+ request (Optional[Union[google.ai.generativelanguage_v1alpha.types.GenerateContentRequest, dict]]):
669
+ The request object. Request to generate a completion from
670
+ the model.
671
+ model (:class:`str`):
672
+ Required. The name of the ``Model`` to use for
673
+ generating the completion.
674
+
675
+ Format: ``models/{model}``.
676
+
677
+ This corresponds to the ``model`` field
678
+ on the ``request`` instance; if ``request`` is provided, this
679
+ should not be set.
680
+ contents (:class:`MutableSequence[google.ai.generativelanguage_v1alpha.types.Content]`):
681
+ Required. The content of the current conversation with
682
+ the model.
683
+
684
+ For single-turn queries, this is a single instance. For
685
+ multi-turn queries like
686
+ `chat <https://ai.google.dev/gemini-api/docs/text-generation#chat>`__,
687
+ this is a repeated field that contains the conversation
688
+ history and the latest request.
689
+
690
+ This corresponds to the ``contents`` field
691
+ on the ``request`` instance; if ``request`` is provided, this
692
+ should not be set.
693
+ retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any,
694
+ should be retried.
695
+ timeout (float): The timeout for this request.
696
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
697
+ sent along with the request as metadata. Normally, each value must be of type `str`,
698
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
699
+ be of type `bytes`.
700
+
701
+ Returns:
702
+ AsyncIterable[google.ai.generativelanguage_v1alpha.types.GenerateContentResponse]:
703
+ Response from the model supporting multiple candidate
704
+ responses.
705
+
706
+ Safety ratings and content filtering are reported for
707
+ both prompt in
708
+ GenerateContentResponse.prompt_feedback and for each
709
+ candidate in finish_reason and in safety_ratings. The
710
+ API: - Returns either all requested candidates or
711
+ none of them - Returns no candidates at all only if
712
+ there was something wrong with the prompt (check
713
+ prompt_feedback) - Reports feedback on each candidate
714
+ in finish_reason and safety_ratings.
715
+
716
+ """
717
+ # Create or coerce a protobuf request object.
718
+ # - Quick check: If we got a request object, we should *not* have
719
+ # gotten any keyword arguments that map to the request.
720
+ has_flattened_params = any([model, contents])
721
+ if request is not None and has_flattened_params:
722
+ raise ValueError(
723
+ "If the `request` argument is set, then none of "
724
+ "the individual field arguments should be set."
725
+ )
726
+
727
+ # - Use the request object if provided (there's no risk of modifying the input as
728
+ # there are no flattened fields), or create one.
729
+ if not isinstance(request, generative_service.GenerateContentRequest):
730
+ request = generative_service.GenerateContentRequest(request)
731
+
732
+ # If we have keyword arguments corresponding to fields on the
733
+ # request, apply these.
734
+ if model is not None:
735
+ request.model = model
736
+ if contents:
737
+ request.contents.extend(contents)
738
+
739
+ # Wrap the RPC method; this adds retry and timeout information,
740
+ # and friendly error handling.
741
+ rpc = self._client._transport._wrapped_methods[
742
+ self._client._transport.stream_generate_content
743
+ ]
744
+
745
+ # Certain fields should be provided within the metadata header;
746
+ # add these here.
747
+ metadata = tuple(metadata) + (
748
+ gapic_v1.routing_header.to_grpc_metadata((("model", request.model),)),
749
+ )
750
+
751
+ # Validate the universe domain.
752
+ self._client._validate_universe_domain()
753
+
754
+ # Send the request.
755
+ response = rpc(
756
+ request,
757
+ retry=retry,
758
+ timeout=timeout,
759
+ metadata=metadata,
760
+ )
761
+
762
+ # Done; return the response.
763
+ return response
764
+
765
+ async def embed_content(
766
+ self,
767
+ request: Optional[Union[generative_service.EmbedContentRequest, dict]] = None,
768
+ *,
769
+ model: Optional[str] = None,
770
+ content: Optional[gag_content.Content] = None,
771
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
772
+ timeout: Union[float, object] = gapic_v1.method.DEFAULT,
773
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
774
+ ) -> generative_service.EmbedContentResponse:
775
+ r"""Generates a text embedding vector from the input ``Content``
776
+ using the specified `Gemini Embedding
777
+ model <https://ai.google.dev/gemini-api/docs/models/gemini#text-embedding>`__.
778
+
779
+ .. code-block:: python
780
+
781
+ # This snippet has been automatically generated and should be regarded as a
782
+ # code template only.
783
+ # It will require modifications to work:
784
+ # - It may require correct/in-range values for request initialization.
785
+ # - It may require specifying regional endpoints when creating the service
786
+ # client as shown in:
787
+ # https://googleapis.dev/python/google-api-core/latest/client_options.html
788
+ from google.ai import generativelanguage_v1alpha
789
+
790
+ async def sample_embed_content():
791
+ # Create a client
792
+ client = generativelanguage_v1alpha.GenerativeServiceAsyncClient()
793
+
794
+ # Initialize request argument(s)
795
+ request = generativelanguage_v1alpha.EmbedContentRequest(
796
+ model="model_value",
797
+ )
798
+
799
+ # Make the request
800
+ response = await client.embed_content(request=request)
801
+
802
+ # Handle the response
803
+ print(response)
804
+
805
+ Args:
806
+ request (Optional[Union[google.ai.generativelanguage_v1alpha.types.EmbedContentRequest, dict]]):
807
+ The request object. Request containing the ``Content`` for the model to
808
+ embed.
809
+ model (:class:`str`):
810
+ Required. The model's resource name. This serves as an
811
+ ID for the Model to use.
812
+
813
+ This name should match a model name returned by the
814
+ ``ListModels`` method.
815
+
816
+ Format: ``models/{model}``
817
+
818
+ This corresponds to the ``model`` field
819
+ on the ``request`` instance; if ``request`` is provided, this
820
+ should not be set.
821
+ content (:class:`google.ai.generativelanguage_v1alpha.types.Content`):
822
+ Required. The content to embed. Only the ``parts.text``
823
+ fields will be counted.
824
+
825
+ This corresponds to the ``content`` field
826
+ on the ``request`` instance; if ``request`` is provided, this
827
+ should not be set.
828
+ retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any,
829
+ should be retried.
830
+ timeout (float): The timeout for this request.
831
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
832
+ sent along with the request as metadata. Normally, each value must be of type `str`,
833
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
834
+ be of type `bytes`.
835
+
836
+ Returns:
837
+ google.ai.generativelanguage_v1alpha.types.EmbedContentResponse:
838
+ The response to an EmbedContentRequest.
839
+ """
840
+ # Create or coerce a protobuf request object.
841
+ # - Quick check: If we got a request object, we should *not* have
842
+ # gotten any keyword arguments that map to the request.
843
+ has_flattened_params = any([model, content])
844
+ if request is not None and has_flattened_params:
845
+ raise ValueError(
846
+ "If the `request` argument is set, then none of "
847
+ "the individual field arguments should be set."
848
+ )
849
+
850
+ # - Use the request object if provided (there's no risk of modifying the input as
851
+ # there are no flattened fields), or create one.
852
+ if not isinstance(request, generative_service.EmbedContentRequest):
853
+ request = generative_service.EmbedContentRequest(request)
854
+
855
+ # If we have keyword arguments corresponding to fields on the
856
+ # request, apply these.
857
+ if model is not None:
858
+ request.model = model
859
+ if content is not None:
860
+ request.content = content
861
+
862
+ # Wrap the RPC method; this adds retry and timeout information,
863
+ # and friendly error handling.
864
+ rpc = self._client._transport._wrapped_methods[
865
+ self._client._transport.embed_content
866
+ ]
867
+
868
+ # Certain fields should be provided within the metadata header;
869
+ # add these here.
870
+ metadata = tuple(metadata) + (
871
+ gapic_v1.routing_header.to_grpc_metadata((("model", request.model),)),
872
+ )
873
+
874
+ # Validate the universe domain.
875
+ self._client._validate_universe_domain()
876
+
877
+ # Send the request.
878
+ response = await rpc(
879
+ request,
880
+ retry=retry,
881
+ timeout=timeout,
882
+ metadata=metadata,
883
+ )
884
+
885
+ # Done; return the response.
886
+ return response
887
+
888
+ async def batch_embed_contents(
889
+ self,
890
+ request: Optional[
891
+ Union[generative_service.BatchEmbedContentsRequest, dict]
892
+ ] = None,
893
+ *,
894
+ model: Optional[str] = None,
895
+ requests: Optional[
896
+ MutableSequence[generative_service.EmbedContentRequest]
897
+ ] = 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
+ ) -> generative_service.BatchEmbedContentsResponse:
902
+ r"""Generates multiple embedding vectors from the input ``Content``
903
+ which consists of a batch of strings represented as
904
+ ``EmbedContentRequest`` objects.
905
+
906
+ .. code-block:: python
907
+
908
+ # This snippet has been automatically generated and should be regarded as a
909
+ # code template only.
910
+ # It will require modifications to work:
911
+ # - It may require correct/in-range values for request initialization.
912
+ # - It may require specifying regional endpoints when creating the service
913
+ # client as shown in:
914
+ # https://googleapis.dev/python/google-api-core/latest/client_options.html
915
+ from google.ai import generativelanguage_v1alpha
916
+
917
+ async def sample_batch_embed_contents():
918
+ # Create a client
919
+ client = generativelanguage_v1alpha.GenerativeServiceAsyncClient()
920
+
921
+ # Initialize request argument(s)
922
+ requests = generativelanguage_v1alpha.EmbedContentRequest()
923
+ requests.model = "model_value"
924
+
925
+ request = generativelanguage_v1alpha.BatchEmbedContentsRequest(
926
+ model="model_value",
927
+ requests=requests,
928
+ )
929
+
930
+ # Make the request
931
+ response = await client.batch_embed_contents(request=request)
932
+
933
+ # Handle the response
934
+ print(response)
935
+
936
+ Args:
937
+ request (Optional[Union[google.ai.generativelanguage_v1alpha.types.BatchEmbedContentsRequest, dict]]):
938
+ The request object. Batch request to get embeddings from
939
+ the model for a list of prompts.
940
+ model (:class:`str`):
941
+ Required. The model's resource name. This serves as an
942
+ ID for the Model to use.
943
+
944
+ This name should match a model name returned by the
945
+ ``ListModels`` method.
946
+
947
+ Format: ``models/{model}``
948
+
949
+ This corresponds to the ``model`` field
950
+ on the ``request`` instance; if ``request`` is provided, this
951
+ should not be set.
952
+ requests (:class:`MutableSequence[google.ai.generativelanguage_v1alpha.types.EmbedContentRequest]`):
953
+ Required. Embed requests for the batch. The model in
954
+ each of these requests must match the model specified
955
+ ``BatchEmbedContentsRequest.model``.
956
+
957
+ This corresponds to the ``requests`` field
958
+ on the ``request`` instance; if ``request`` is provided, this
959
+ should not be set.
960
+ retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any,
961
+ should be retried.
962
+ timeout (float): The timeout for this request.
963
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
964
+ sent along with the request as metadata. Normally, each value must be of type `str`,
965
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
966
+ be of type `bytes`.
967
+
968
+ Returns:
969
+ google.ai.generativelanguage_v1alpha.types.BatchEmbedContentsResponse:
970
+ The response to a BatchEmbedContentsRequest.
971
+ """
972
+ # Create or coerce a protobuf request object.
973
+ # - Quick check: If we got a request object, we should *not* have
974
+ # gotten any keyword arguments that map to the request.
975
+ has_flattened_params = any([model, requests])
976
+ if request is not None and has_flattened_params:
977
+ raise ValueError(
978
+ "If the `request` argument is set, then none of "
979
+ "the individual field arguments should be set."
980
+ )
981
+
982
+ # - Use the request object if provided (there's no risk of modifying the input as
983
+ # there are no flattened fields), or create one.
984
+ if not isinstance(request, generative_service.BatchEmbedContentsRequest):
985
+ request = generative_service.BatchEmbedContentsRequest(request)
986
+
987
+ # If we have keyword arguments corresponding to fields on the
988
+ # request, apply these.
989
+ if model is not None:
990
+ request.model = model
991
+ if requests:
992
+ request.requests.extend(requests)
993
+
994
+ # Wrap the RPC method; this adds retry and timeout information,
995
+ # and friendly error handling.
996
+ rpc = self._client._transport._wrapped_methods[
997
+ self._client._transport.batch_embed_contents
998
+ ]
999
+
1000
+ # Certain fields should be provided within the metadata header;
1001
+ # add these here.
1002
+ metadata = tuple(metadata) + (
1003
+ gapic_v1.routing_header.to_grpc_metadata((("model", request.model),)),
1004
+ )
1005
+
1006
+ # Validate the universe domain.
1007
+ self._client._validate_universe_domain()
1008
+
1009
+ # Send the request.
1010
+ response = await rpc(
1011
+ request,
1012
+ retry=retry,
1013
+ timeout=timeout,
1014
+ metadata=metadata,
1015
+ )
1016
+
1017
+ # Done; return the response.
1018
+ return response
1019
+
1020
+ async def count_tokens(
1021
+ self,
1022
+ request: Optional[Union[generative_service.CountTokensRequest, dict]] = None,
1023
+ *,
1024
+ model: Optional[str] = None,
1025
+ contents: Optional[MutableSequence[content.Content]] = None,
1026
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
1027
+ timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1028
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1029
+ ) -> generative_service.CountTokensResponse:
1030
+ r"""Runs a model's tokenizer on input ``Content`` and returns the
1031
+ token count. Refer to the `tokens
1032
+ guide <https://ai.google.dev/gemini-api/docs/tokens>`__ to learn
1033
+ more about tokens.
1034
+
1035
+ .. code-block:: python
1036
+
1037
+ # This snippet has been automatically generated and should be regarded as a
1038
+ # code template only.
1039
+ # It will require modifications to work:
1040
+ # - It may require correct/in-range values for request initialization.
1041
+ # - It may require specifying regional endpoints when creating the service
1042
+ # client as shown in:
1043
+ # https://googleapis.dev/python/google-api-core/latest/client_options.html
1044
+ from google.ai import generativelanguage_v1alpha
1045
+
1046
+ async def sample_count_tokens():
1047
+ # Create a client
1048
+ client = generativelanguage_v1alpha.GenerativeServiceAsyncClient()
1049
+
1050
+ # Initialize request argument(s)
1051
+ request = generativelanguage_v1alpha.CountTokensRequest(
1052
+ model="model_value",
1053
+ )
1054
+
1055
+ # Make the request
1056
+ response = await client.count_tokens(request=request)
1057
+
1058
+ # Handle the response
1059
+ print(response)
1060
+
1061
+ Args:
1062
+ request (Optional[Union[google.ai.generativelanguage_v1alpha.types.CountTokensRequest, dict]]):
1063
+ The request object. Counts the number of tokens in the ``prompt`` sent to a
1064
+ model.
1065
+
1066
+ Models may tokenize text differently, so each model may
1067
+ return a different ``token_count``.
1068
+ model (:class:`str`):
1069
+ Required. The model's resource name. This serves as an
1070
+ ID for the Model to use.
1071
+
1072
+ This name should match a model name returned by the
1073
+ ``ListModels`` method.
1074
+
1075
+ Format: ``models/{model}``
1076
+
1077
+ This corresponds to the ``model`` field
1078
+ on the ``request`` instance; if ``request`` is provided, this
1079
+ should not be set.
1080
+ contents (:class:`MutableSequence[google.ai.generativelanguage_v1alpha.types.Content]`):
1081
+ Optional. The input given to the model as a prompt. This
1082
+ field is ignored when ``generate_content_request`` is
1083
+ set.
1084
+
1085
+ This corresponds to the ``contents`` field
1086
+ on the ``request`` instance; if ``request`` is provided, this
1087
+ should not be set.
1088
+ retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any,
1089
+ should be retried.
1090
+ timeout (float): The timeout for this request.
1091
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1092
+ sent along with the request as metadata. Normally, each value must be of type `str`,
1093
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
1094
+ be of type `bytes`.
1095
+
1096
+ Returns:
1097
+ google.ai.generativelanguage_v1alpha.types.CountTokensResponse:
1098
+ A response from CountTokens.
1099
+
1100
+ It returns the model's token_count for the prompt.
1101
+
1102
+ """
1103
+ # Create or coerce a protobuf request object.
1104
+ # - Quick check: If we got a request object, we should *not* have
1105
+ # gotten any keyword arguments that map to the request.
1106
+ has_flattened_params = any([model, contents])
1107
+ if request is not None and has_flattened_params:
1108
+ raise ValueError(
1109
+ "If the `request` argument is set, then none of "
1110
+ "the individual field arguments should be set."
1111
+ )
1112
+
1113
+ # - Use the request object if provided (there's no risk of modifying the input as
1114
+ # there are no flattened fields), or create one.
1115
+ if not isinstance(request, generative_service.CountTokensRequest):
1116
+ request = generative_service.CountTokensRequest(request)
1117
+
1118
+ # If we have keyword arguments corresponding to fields on the
1119
+ # request, apply these.
1120
+ if model is not None:
1121
+ request.model = model
1122
+ if contents:
1123
+ request.contents.extend(contents)
1124
+
1125
+ # Wrap the RPC method; this adds retry and timeout information,
1126
+ # and friendly error handling.
1127
+ rpc = self._client._transport._wrapped_methods[
1128
+ self._client._transport.count_tokens
1129
+ ]
1130
+
1131
+ # Certain fields should be provided within the metadata header;
1132
+ # add these here.
1133
+ metadata = tuple(metadata) + (
1134
+ gapic_v1.routing_header.to_grpc_metadata((("model", request.model),)),
1135
+ )
1136
+
1137
+ # Validate the universe domain.
1138
+ self._client._validate_universe_domain()
1139
+
1140
+ # Send the request.
1141
+ response = await rpc(
1142
+ request,
1143
+ retry=retry,
1144
+ timeout=timeout,
1145
+ metadata=metadata,
1146
+ )
1147
+
1148
+ # Done; return the response.
1149
+ return response
1150
+
1151
+ def bidi_generate_content(
1152
+ self,
1153
+ requests: Optional[
1154
+ AsyncIterator[generative_service.BidiGenerateContentClientMessage]
1155
+ ] = None,
1156
+ *,
1157
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
1158
+ timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1159
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1160
+ ) -> Awaitable[AsyncIterable[generative_service.BidiGenerateContentServerMessage]]:
1161
+ r"""Low-Latency bidirectional streaming API that supports
1162
+ audio and video streaming inputs can produce multimodal
1163
+ output streams (audio and text).
1164
+
1165
+ .. code-block:: python
1166
+
1167
+ # This snippet has been automatically generated and should be regarded as a
1168
+ # code template only.
1169
+ # It will require modifications to work:
1170
+ # - It may require correct/in-range values for request initialization.
1171
+ # - It may require specifying regional endpoints when creating the service
1172
+ # client as shown in:
1173
+ # https://googleapis.dev/python/google-api-core/latest/client_options.html
1174
+ from google.ai import generativelanguage_v1alpha
1175
+
1176
+ async def sample_bidi_generate_content():
1177
+ # Create a client
1178
+ client = generativelanguage_v1alpha.GenerativeServiceAsyncClient()
1179
+
1180
+ # Initialize request argument(s)
1181
+ setup = generativelanguage_v1alpha.BidiGenerateContentSetup()
1182
+ setup.model = "model_value"
1183
+
1184
+ request = generativelanguage_v1alpha.BidiGenerateContentClientMessage(
1185
+ setup=setup,
1186
+ )
1187
+
1188
+ # This method expects an iterator which contains
1189
+ # 'generativelanguage_v1alpha.BidiGenerateContentClientMessage' objects
1190
+ # Here we create a generator that yields a single `request` for
1191
+ # demonstrative purposes.
1192
+ requests = [request]
1193
+
1194
+ def request_generator():
1195
+ for request in requests:
1196
+ yield request
1197
+
1198
+ # Make the request
1199
+ stream = await client.bidi_generate_content(requests=request_generator())
1200
+
1201
+ # Handle the response
1202
+ async for response in stream:
1203
+ print(response)
1204
+
1205
+ Args:
1206
+ requests (AsyncIterator[`google.ai.generativelanguage_v1alpha.types.BidiGenerateContentClientMessage`]):
1207
+ The request object AsyncIterator. Messages sent by the client in the
1208
+ BidiGenerateContent call.
1209
+ retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any,
1210
+ should be retried.
1211
+ timeout (float): The timeout for this request.
1212
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1213
+ sent along with the request as metadata. Normally, each value must be of type `str`,
1214
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
1215
+ be of type `bytes`.
1216
+
1217
+ Returns:
1218
+ AsyncIterable[google.ai.generativelanguage_v1alpha.types.BidiGenerateContentServerMessage]:
1219
+ Response message for the
1220
+ BidiGenerateContent call.
1221
+
1222
+ """
1223
+
1224
+ # Wrap the RPC method; this adds retry and timeout information,
1225
+ # and friendly error handling.
1226
+ rpc = self._client._transport._wrapped_methods[
1227
+ self._client._transport.bidi_generate_content
1228
+ ]
1229
+
1230
+ # Validate the universe domain.
1231
+ self._client._validate_universe_domain()
1232
+
1233
+ # Send the request.
1234
+ response = rpc(
1235
+ requests,
1236
+ retry=retry,
1237
+ timeout=timeout,
1238
+ metadata=metadata,
1239
+ )
1240
+
1241
+ # Done; return the response.
1242
+ return response
1243
+
1244
+ async def list_operations(
1245
+ self,
1246
+ request: Optional[operations_pb2.ListOperationsRequest] = None,
1247
+ *,
1248
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
1249
+ timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1250
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1251
+ ) -> operations_pb2.ListOperationsResponse:
1252
+ r"""Lists operations that match the specified filter in the request.
1253
+
1254
+ Args:
1255
+ request (:class:`~.operations_pb2.ListOperationsRequest`):
1256
+ The request object. Request message for
1257
+ `ListOperations` method.
1258
+ retry (google.api_core.retry_async.AsyncRetry): Designation of what errors,
1259
+ if any, should be retried.
1260
+ timeout (float): The timeout for this request.
1261
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1262
+ sent along with the request as metadata. Normally, each value must be of type `str`,
1263
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
1264
+ be of type `bytes`.
1265
+ Returns:
1266
+ ~.operations_pb2.ListOperationsResponse:
1267
+ Response message for ``ListOperations`` method.
1268
+ """
1269
+ # Create or coerce a protobuf request object.
1270
+ # The request isn't a proto-plus wrapped type,
1271
+ # so it must be constructed via keyword expansion.
1272
+ if isinstance(request, dict):
1273
+ request = operations_pb2.ListOperationsRequest(**request)
1274
+
1275
+ # Wrap the RPC method; this adds retry and timeout information,
1276
+ # and friendly error handling.
1277
+ rpc = self.transport._wrapped_methods[self._client._transport.list_operations]
1278
+
1279
+ # Certain fields should be provided within the metadata header;
1280
+ # add these here.
1281
+ metadata = tuple(metadata) + (
1282
+ gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
1283
+ )
1284
+
1285
+ # Validate the universe domain.
1286
+ self._client._validate_universe_domain()
1287
+
1288
+ # Send the request.
1289
+ response = await rpc(
1290
+ request,
1291
+ retry=retry,
1292
+ timeout=timeout,
1293
+ metadata=metadata,
1294
+ )
1295
+
1296
+ # Done; return the response.
1297
+ return response
1298
+
1299
+ async def get_operation(
1300
+ self,
1301
+ request: Optional[operations_pb2.GetOperationRequest] = None,
1302
+ *,
1303
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
1304
+ timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1305
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1306
+ ) -> operations_pb2.Operation:
1307
+ r"""Gets the latest state of a long-running operation.
1308
+
1309
+ Args:
1310
+ request (:class:`~.operations_pb2.GetOperationRequest`):
1311
+ The request object. Request message for
1312
+ `GetOperation` method.
1313
+ retry (google.api_core.retry_async.AsyncRetry): Designation of what errors,
1314
+ if any, should be retried.
1315
+ timeout (float): The timeout for this request.
1316
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1317
+ sent along with the request as metadata. Normally, each value must be of type `str`,
1318
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
1319
+ be of type `bytes`.
1320
+ Returns:
1321
+ ~.operations_pb2.Operation:
1322
+ An ``Operation`` object.
1323
+ """
1324
+ # Create or coerce a protobuf request object.
1325
+ # The request isn't a proto-plus wrapped type,
1326
+ # so it must be constructed via keyword expansion.
1327
+ if isinstance(request, dict):
1328
+ request = operations_pb2.GetOperationRequest(**request)
1329
+
1330
+ # Wrap the RPC method; this adds retry and timeout information,
1331
+ # and friendly error handling.
1332
+ rpc = self.transport._wrapped_methods[self._client._transport.get_operation]
1333
+
1334
+ # Certain fields should be provided within the metadata header;
1335
+ # add these here.
1336
+ metadata = tuple(metadata) + (
1337
+ gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
1338
+ )
1339
+
1340
+ # Validate the universe domain.
1341
+ self._client._validate_universe_domain()
1342
+
1343
+ # Send the request.
1344
+ response = await rpc(
1345
+ request,
1346
+ retry=retry,
1347
+ timeout=timeout,
1348
+ metadata=metadata,
1349
+ )
1350
+
1351
+ # Done; return the response.
1352
+ return response
1353
+
1354
+ async def __aenter__(self) -> "GenerativeServiceAsyncClient":
1355
+ return self
1356
+
1357
+ async def __aexit__(self, exc_type, exc, tb):
1358
+ await self.transport.close()
1359
+
1360
+
1361
+ DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
1362
+ gapic_version=package_version.__version__
1363
+ )
1364
+
1365
+
1366
+ __all__ = ("GenerativeServiceAsyncClient",)
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/client.py ADDED
@@ -0,0 +1,1751 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ Iterator,
25
+ Mapping,
26
+ MutableMapping,
27
+ MutableSequence,
28
+ Optional,
29
+ Sequence,
30
+ Tuple,
31
+ Type,
32
+ Union,
33
+ cast,
34
+ )
35
+ import warnings
36
+
37
+ from google.api_core import client_options as client_options_lib
38
+ from google.api_core import exceptions as core_exceptions
39
+ from google.api_core import gapic_v1
40
+ from google.api_core import retry as retries
41
+ from google.auth import credentials as ga_credentials # type: ignore
42
+ from google.auth.exceptions import MutualTLSChannelError # type: ignore
43
+ from google.auth.transport import mtls # type: ignore
44
+ from google.auth.transport.grpc import SslCredentials # type: ignore
45
+ from google.oauth2 import service_account # type: ignore
46
+
47
+ from google.ai.generativelanguage_v1alpha import gapic_version as package_version
48
+
49
+ try:
50
+ OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None]
51
+ except AttributeError: # pragma: NO COVER
52
+ OptionalRetry = Union[retries.Retry, object, None] # type: ignore
53
+
54
+ try:
55
+ from google.api_core import client_logging # type: ignore
56
+
57
+ CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER
58
+ except ImportError: # pragma: NO COVER
59
+ CLIENT_LOGGING_SUPPORTED = False
60
+
61
+ _LOGGER = std_logging.getLogger(__name__)
62
+
63
+ from google.longrunning import operations_pb2 # type: ignore
64
+
65
+ from google.ai.generativelanguage_v1alpha.types import generative_service, safety
66
+ from google.ai.generativelanguage_v1alpha.types import content
67
+ from google.ai.generativelanguage_v1alpha.types import content as gag_content
68
+
69
+ from .transports.base import DEFAULT_CLIENT_INFO, GenerativeServiceTransport
70
+ from .transports.grpc import GenerativeServiceGrpcTransport
71
+ from .transports.grpc_asyncio import GenerativeServiceGrpcAsyncIOTransport
72
+ from .transports.rest import GenerativeServiceRestTransport
73
+
74
+
75
+ class GenerativeServiceClientMeta(type):
76
+ """Metaclass for the GenerativeService client.
77
+
78
+ This provides class-level methods for building and retrieving
79
+ support objects (e.g. transport) without polluting the client instance
80
+ objects.
81
+ """
82
+
83
+ _transport_registry = (
84
+ OrderedDict()
85
+ ) # type: Dict[str, Type[GenerativeServiceTransport]]
86
+ _transport_registry["grpc"] = GenerativeServiceGrpcTransport
87
+ _transport_registry["grpc_asyncio"] = GenerativeServiceGrpcAsyncIOTransport
88
+ _transport_registry["rest"] = GenerativeServiceRestTransport
89
+
90
+ def get_transport_class(
91
+ cls,
92
+ label: Optional[str] = None,
93
+ ) -> Type[GenerativeServiceTransport]:
94
+ """Returns an appropriate transport class.
95
+
96
+ Args:
97
+ label: The name of the desired transport. If none is
98
+ provided, then the first transport in the registry is used.
99
+
100
+ Returns:
101
+ The transport class to use.
102
+ """
103
+ # If a specific transport is requested, return that one.
104
+ if label:
105
+ return cls._transport_registry[label]
106
+
107
+ # No transport is requested; return the default (that is, the first one
108
+ # in the dictionary).
109
+ return next(iter(cls._transport_registry.values()))
110
+
111
+
112
+ class GenerativeServiceClient(metaclass=GenerativeServiceClientMeta):
113
+ """API for using Large Models that generate multimodal content
114
+ and have additional capabilities beyond text generation.
115
+ """
116
+
117
+ @staticmethod
118
+ def _get_default_mtls_endpoint(api_endpoint):
119
+ """Converts api endpoint to mTLS endpoint.
120
+
121
+ Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to
122
+ "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively.
123
+ Args:
124
+ api_endpoint (Optional[str]): the api endpoint to convert.
125
+ Returns:
126
+ str: converted mTLS api endpoint.
127
+ """
128
+ if not api_endpoint:
129
+ return api_endpoint
130
+
131
+ mtls_endpoint_re = re.compile(
132
+ r"(?P<name>[^.]+)(?P<mtls>\.mtls)?(?P<sandbox>\.sandbox)?(?P<googledomain>\.googleapis\.com)?"
133
+ )
134
+
135
+ m = mtls_endpoint_re.match(api_endpoint)
136
+ name, mtls, sandbox, googledomain = m.groups()
137
+ if mtls or not googledomain:
138
+ return api_endpoint
139
+
140
+ if sandbox:
141
+ return api_endpoint.replace(
142
+ "sandbox.googleapis.com", "mtls.sandbox.googleapis.com"
143
+ )
144
+
145
+ return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com")
146
+
147
+ # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead.
148
+ DEFAULT_ENDPOINT = "generativelanguage.googleapis.com"
149
+ DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore
150
+ DEFAULT_ENDPOINT
151
+ )
152
+
153
+ _DEFAULT_ENDPOINT_TEMPLATE = "generativelanguage.{UNIVERSE_DOMAIN}"
154
+ _DEFAULT_UNIVERSE = "googleapis.com"
155
+
156
+ @classmethod
157
+ def from_service_account_info(cls, info: dict, *args, **kwargs):
158
+ """Creates an instance of this client using the provided credentials
159
+ info.
160
+
161
+ Args:
162
+ info (dict): The service account private key info.
163
+ args: Additional arguments to pass to the constructor.
164
+ kwargs: Additional arguments to pass to the constructor.
165
+
166
+ Returns:
167
+ GenerativeServiceClient: The constructed client.
168
+ """
169
+ credentials = service_account.Credentials.from_service_account_info(info)
170
+ kwargs["credentials"] = credentials
171
+ return cls(*args, **kwargs)
172
+
173
+ @classmethod
174
+ def from_service_account_file(cls, filename: str, *args, **kwargs):
175
+ """Creates an instance of this client using the provided credentials
176
+ file.
177
+
178
+ Args:
179
+ filename (str): The path to the service account private key json
180
+ file.
181
+ args: Additional arguments to pass to the constructor.
182
+ kwargs: Additional arguments to pass to the constructor.
183
+
184
+ Returns:
185
+ GenerativeServiceClient: The constructed client.
186
+ """
187
+ credentials = service_account.Credentials.from_service_account_file(filename)
188
+ kwargs["credentials"] = credentials
189
+ return cls(*args, **kwargs)
190
+
191
+ from_service_account_json = from_service_account_file
192
+
193
+ @property
194
+ def transport(self) -> GenerativeServiceTransport:
195
+ """Returns the transport used by the client instance.
196
+
197
+ Returns:
198
+ GenerativeServiceTransport: The transport used by the client
199
+ instance.
200
+ """
201
+ return self._transport
202
+
203
+ @staticmethod
204
+ def cached_content_path(
205
+ id: str,
206
+ ) -> str:
207
+ """Returns a fully-qualified cached_content string."""
208
+ return "cachedContents/{id}".format(
209
+ id=id,
210
+ )
211
+
212
+ @staticmethod
213
+ def parse_cached_content_path(path: str) -> Dict[str, str]:
214
+ """Parses a cached_content path into its component segments."""
215
+ m = re.match(r"^cachedContents/(?P<id>.+?)$", path)
216
+ return m.groupdict() if m else {}
217
+
218
+ @staticmethod
219
+ def model_path(
220
+ model: str,
221
+ ) -> str:
222
+ """Returns a fully-qualified model string."""
223
+ return "models/{model}".format(
224
+ model=model,
225
+ )
226
+
227
+ @staticmethod
228
+ def parse_model_path(path: str) -> Dict[str, str]:
229
+ """Parses a model path into its component segments."""
230
+ m = re.match(r"^models/(?P<model>.+?)$", path)
231
+ return m.groupdict() if m else {}
232
+
233
+ @staticmethod
234
+ def common_billing_account_path(
235
+ billing_account: str,
236
+ ) -> str:
237
+ """Returns a fully-qualified billing_account string."""
238
+ return "billingAccounts/{billing_account}".format(
239
+ billing_account=billing_account,
240
+ )
241
+
242
+ @staticmethod
243
+ def parse_common_billing_account_path(path: str) -> Dict[str, str]:
244
+ """Parse a billing_account path into its component segments."""
245
+ m = re.match(r"^billingAccounts/(?P<billing_account>.+?)$", path)
246
+ return m.groupdict() if m else {}
247
+
248
+ @staticmethod
249
+ def common_folder_path(
250
+ folder: str,
251
+ ) -> str:
252
+ """Returns a fully-qualified folder string."""
253
+ return "folders/{folder}".format(
254
+ folder=folder,
255
+ )
256
+
257
+ @staticmethod
258
+ def parse_common_folder_path(path: str) -> Dict[str, str]:
259
+ """Parse a folder path into its component segments."""
260
+ m = re.match(r"^folders/(?P<folder>.+?)$", path)
261
+ return m.groupdict() if m else {}
262
+
263
+ @staticmethod
264
+ def common_organization_path(
265
+ organization: str,
266
+ ) -> str:
267
+ """Returns a fully-qualified organization string."""
268
+ return "organizations/{organization}".format(
269
+ organization=organization,
270
+ )
271
+
272
+ @staticmethod
273
+ def parse_common_organization_path(path: str) -> Dict[str, str]:
274
+ """Parse a organization path into its component segments."""
275
+ m = re.match(r"^organizations/(?P<organization>.+?)$", path)
276
+ return m.groupdict() if m else {}
277
+
278
+ @staticmethod
279
+ def common_project_path(
280
+ project: str,
281
+ ) -> str:
282
+ """Returns a fully-qualified project string."""
283
+ return "projects/{project}".format(
284
+ project=project,
285
+ )
286
+
287
+ @staticmethod
288
+ def parse_common_project_path(path: str) -> Dict[str, str]:
289
+ """Parse a project path into its component segments."""
290
+ m = re.match(r"^projects/(?P<project>.+?)$", path)
291
+ return m.groupdict() if m else {}
292
+
293
+ @staticmethod
294
+ def common_location_path(
295
+ project: str,
296
+ location: str,
297
+ ) -> str:
298
+ """Returns a fully-qualified location string."""
299
+ return "projects/{project}/locations/{location}".format(
300
+ project=project,
301
+ location=location,
302
+ )
303
+
304
+ @staticmethod
305
+ def parse_common_location_path(path: str) -> Dict[str, str]:
306
+ """Parse a location path into its component segments."""
307
+ m = re.match(r"^projects/(?P<project>.+?)/locations/(?P<location>.+?)$", path)
308
+ return m.groupdict() if m else {}
309
+
310
+ @classmethod
311
+ def get_mtls_endpoint_and_cert_source(
312
+ cls, client_options: Optional[client_options_lib.ClientOptions] = None
313
+ ):
314
+ """Deprecated. Return the API endpoint and client cert source for mutual TLS.
315
+
316
+ The client cert source is determined in the following order:
317
+ (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the
318
+ client cert source is None.
319
+ (2) if `client_options.client_cert_source` is provided, use the provided one; if the
320
+ default client cert source exists, use the default one; otherwise the client cert
321
+ source is None.
322
+
323
+ The API endpoint is determined in the following order:
324
+ (1) if `client_options.api_endpoint` if provided, use the provided one.
325
+ (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the
326
+ default mTLS endpoint; if the environment variable is "never", use the default API
327
+ endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise
328
+ use the default API endpoint.
329
+
330
+ More details can be found at https://google.aip.dev/auth/4114.
331
+
332
+ Args:
333
+ client_options (google.api_core.client_options.ClientOptions): Custom options for the
334
+ client. Only the `api_endpoint` and `client_cert_source` properties may be used
335
+ in this method.
336
+
337
+ Returns:
338
+ Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the
339
+ client cert source to use.
340
+
341
+ Raises:
342
+ google.auth.exceptions.MutualTLSChannelError: If any errors happen.
343
+ """
344
+
345
+ warnings.warn(
346
+ "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.",
347
+ DeprecationWarning,
348
+ )
349
+ if client_options is None:
350
+ client_options = client_options_lib.ClientOptions()
351
+ use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false")
352
+ use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto")
353
+ if use_client_cert not in ("true", "false"):
354
+ raise ValueError(
355
+ "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`"
356
+ )
357
+ if use_mtls_endpoint not in ("auto", "never", "always"):
358
+ raise MutualTLSChannelError(
359
+ "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`"
360
+ )
361
+
362
+ # Figure out the client cert source to use.
363
+ client_cert_source = None
364
+ if use_client_cert == "true":
365
+ if client_options.client_cert_source:
366
+ client_cert_source = client_options.client_cert_source
367
+ elif mtls.has_default_client_cert_source():
368
+ client_cert_source = mtls.default_client_cert_source()
369
+
370
+ # Figure out which api endpoint to use.
371
+ if client_options.api_endpoint is not None:
372
+ api_endpoint = client_options.api_endpoint
373
+ elif use_mtls_endpoint == "always" or (
374
+ use_mtls_endpoint == "auto" and client_cert_source
375
+ ):
376
+ api_endpoint = cls.DEFAULT_MTLS_ENDPOINT
377
+ else:
378
+ api_endpoint = cls.DEFAULT_ENDPOINT
379
+
380
+ return api_endpoint, client_cert_source
381
+
382
+ @staticmethod
383
+ def _read_environment_variables():
384
+ """Returns the environment variables used by the client.
385
+
386
+ Returns:
387
+ Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE,
388
+ GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables.
389
+
390
+ Raises:
391
+ ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not
392
+ any of ["true", "false"].
393
+ google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT
394
+ is not any of ["auto", "never", "always"].
395
+ """
396
+ use_client_cert = os.getenv(
397
+ "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"
398
+ ).lower()
399
+ use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower()
400
+ universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN")
401
+ if use_client_cert not in ("true", "false"):
402
+ raise ValueError(
403
+ "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`"
404
+ )
405
+ if use_mtls_endpoint not in ("auto", "never", "always"):
406
+ raise MutualTLSChannelError(
407
+ "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`"
408
+ )
409
+ return use_client_cert == "true", use_mtls_endpoint, universe_domain_env
410
+
411
+ @staticmethod
412
+ def _get_client_cert_source(provided_cert_source, use_cert_flag):
413
+ """Return the client cert source to be used by the client.
414
+
415
+ Args:
416
+ provided_cert_source (bytes): The client certificate source provided.
417
+ use_cert_flag (bool): A flag indicating whether to use the client certificate.
418
+
419
+ Returns:
420
+ bytes or None: The client cert source to be used by the client.
421
+ """
422
+ client_cert_source = None
423
+ if use_cert_flag:
424
+ if provided_cert_source:
425
+ client_cert_source = provided_cert_source
426
+ elif mtls.has_default_client_cert_source():
427
+ client_cert_source = mtls.default_client_cert_source()
428
+ return client_cert_source
429
+
430
+ @staticmethod
431
+ def _get_api_endpoint(
432
+ api_override, client_cert_source, universe_domain, use_mtls_endpoint
433
+ ):
434
+ """Return the API endpoint used by the client.
435
+
436
+ Args:
437
+ api_override (str): The API endpoint override. If specified, this is always
438
+ the return value of this function and the other arguments are not used.
439
+ client_cert_source (bytes): The client certificate source used by the client.
440
+ universe_domain (str): The universe domain used by the client.
441
+ use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters.
442
+ Possible values are "always", "auto", or "never".
443
+
444
+ Returns:
445
+ str: The API endpoint to be used by the client.
446
+ """
447
+ if api_override is not None:
448
+ api_endpoint = api_override
449
+ elif use_mtls_endpoint == "always" or (
450
+ use_mtls_endpoint == "auto" and client_cert_source
451
+ ):
452
+ _default_universe = GenerativeServiceClient._DEFAULT_UNIVERSE
453
+ if universe_domain != _default_universe:
454
+ raise MutualTLSChannelError(
455
+ f"mTLS is not supported in any universe other than {_default_universe}."
456
+ )
457
+ api_endpoint = GenerativeServiceClient.DEFAULT_MTLS_ENDPOINT
458
+ else:
459
+ api_endpoint = GenerativeServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(
460
+ UNIVERSE_DOMAIN=universe_domain
461
+ )
462
+ return api_endpoint
463
+
464
+ @staticmethod
465
+ def _get_universe_domain(
466
+ client_universe_domain: Optional[str], universe_domain_env: Optional[str]
467
+ ) -> str:
468
+ """Return the universe domain used by the client.
469
+
470
+ Args:
471
+ client_universe_domain (Optional[str]): The universe domain configured via the client options.
472
+ universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable.
473
+
474
+ Returns:
475
+ str: The universe domain to be used by the client.
476
+
477
+ Raises:
478
+ ValueError: If the universe domain is an empty string.
479
+ """
480
+ universe_domain = GenerativeServiceClient._DEFAULT_UNIVERSE
481
+ if client_universe_domain is not None:
482
+ universe_domain = client_universe_domain
483
+ elif universe_domain_env is not None:
484
+ universe_domain = universe_domain_env
485
+ if len(universe_domain.strip()) == 0:
486
+ raise ValueError("Universe Domain cannot be an empty string.")
487
+ return universe_domain
488
+
489
+ def _validate_universe_domain(self):
490
+ """Validates client's and credentials' universe domains are consistent.
491
+
492
+ Returns:
493
+ bool: True iff the configured universe domain is valid.
494
+
495
+ Raises:
496
+ ValueError: If the configured universe domain is not valid.
497
+ """
498
+
499
+ # NOTE (b/349488459): universe validation is disabled until further notice.
500
+ return True
501
+
502
+ @property
503
+ def api_endpoint(self):
504
+ """Return the API endpoint used by the client instance.
505
+
506
+ Returns:
507
+ str: The API endpoint used by the client instance.
508
+ """
509
+ return self._api_endpoint
510
+
511
+ @property
512
+ def universe_domain(self) -> str:
513
+ """Return the universe domain used by the client instance.
514
+
515
+ Returns:
516
+ str: The universe domain used by the client instance.
517
+ """
518
+ return self._universe_domain
519
+
520
+ def __init__(
521
+ self,
522
+ *,
523
+ credentials: Optional[ga_credentials.Credentials] = None,
524
+ transport: Optional[
525
+ Union[
526
+ str,
527
+ GenerativeServiceTransport,
528
+ Callable[..., GenerativeServiceTransport],
529
+ ]
530
+ ] = None,
531
+ client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None,
532
+ client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
533
+ ) -> None:
534
+ """Instantiates the generative service client.
535
+
536
+ Args:
537
+ credentials (Optional[google.auth.credentials.Credentials]): The
538
+ authorization credentials to attach to requests. These
539
+ credentials identify the application to the service; if none
540
+ are specified, the client will attempt to ascertain the
541
+ credentials from the environment.
542
+ transport (Optional[Union[str,GenerativeServiceTransport,Callable[..., GenerativeServiceTransport]]]):
543
+ The transport to use, or a Callable that constructs and returns a new transport.
544
+ If a Callable is given, it will be called with the same set of initialization
545
+ arguments as used in the GenerativeServiceTransport constructor.
546
+ If set to None, a transport is chosen automatically.
547
+ client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]):
548
+ Custom options for the client.
549
+
550
+ 1. The ``api_endpoint`` property can be used to override the
551
+ default endpoint provided by the client when ``transport`` is
552
+ not explicitly provided. Only if this property is not set and
553
+ ``transport`` was not explicitly provided, the endpoint is
554
+ determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment
555
+ variable, which have one of the following values:
556
+ "always" (always use the default mTLS endpoint), "never" (always
557
+ use the default regular endpoint) and "auto" (auto-switch to the
558
+ default mTLS endpoint if client certificate is present; this is
559
+ the default value).
560
+
561
+ 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable
562
+ is "true", then the ``client_cert_source`` property can be used
563
+ to provide a client certificate for mTLS transport. If
564
+ not provided, the default SSL client certificate will be used if
565
+ present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not
566
+ set, no client certificate will be used.
567
+
568
+ 3. The ``universe_domain`` property can be used to override the
569
+ default "googleapis.com" universe. Note that the ``api_endpoint``
570
+ property still takes precedence; and ``universe_domain`` is
571
+ currently not supported for mTLS.
572
+
573
+ client_info (google.api_core.gapic_v1.client_info.ClientInfo):
574
+ The client info used to send a user-agent string along with
575
+ API requests. If ``None``, then default info will be used.
576
+ Generally, you only need to set this if you're developing
577
+ your own client library.
578
+
579
+ Raises:
580
+ google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
581
+ creation failed for any reason.
582
+ """
583
+ self._client_options = client_options
584
+ if isinstance(self._client_options, dict):
585
+ self._client_options = client_options_lib.from_dict(self._client_options)
586
+ if self._client_options is None:
587
+ self._client_options = client_options_lib.ClientOptions()
588
+ self._client_options = cast(
589
+ client_options_lib.ClientOptions, self._client_options
590
+ )
591
+
592
+ universe_domain_opt = getattr(self._client_options, "universe_domain", None)
593
+
594
+ (
595
+ self._use_client_cert,
596
+ self._use_mtls_endpoint,
597
+ self._universe_domain_env,
598
+ ) = GenerativeServiceClient._read_environment_variables()
599
+ self._client_cert_source = GenerativeServiceClient._get_client_cert_source(
600
+ self._client_options.client_cert_source, self._use_client_cert
601
+ )
602
+ self._universe_domain = GenerativeServiceClient._get_universe_domain(
603
+ universe_domain_opt, self._universe_domain_env
604
+ )
605
+ self._api_endpoint = None # updated below, depending on `transport`
606
+
607
+ # Initialize the universe domain validation.
608
+ self._is_universe_domain_valid = False
609
+
610
+ if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER
611
+ # Setup logging.
612
+ client_logging.initialize_logging()
613
+
614
+ api_key_value = getattr(self._client_options, "api_key", None)
615
+ if api_key_value and credentials:
616
+ raise ValueError(
617
+ "client_options.api_key and credentials are mutually exclusive"
618
+ )
619
+
620
+ # Save or instantiate the transport.
621
+ # Ordinarily, we provide the transport, but allowing a custom transport
622
+ # instance provides an extensibility point for unusual situations.
623
+ transport_provided = isinstance(transport, GenerativeServiceTransport)
624
+ if transport_provided:
625
+ # transport is a GenerativeServiceTransport instance.
626
+ if credentials or self._client_options.credentials_file or api_key_value:
627
+ raise ValueError(
628
+ "When providing a transport instance, "
629
+ "provide its credentials directly."
630
+ )
631
+ if self._client_options.scopes:
632
+ raise ValueError(
633
+ "When providing a transport instance, provide its scopes "
634
+ "directly."
635
+ )
636
+ self._transport = cast(GenerativeServiceTransport, transport)
637
+ self._api_endpoint = self._transport.host
638
+
639
+ self._api_endpoint = (
640
+ self._api_endpoint
641
+ or GenerativeServiceClient._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
+
649
+ if not transport_provided:
650
+ import google.auth._default # type: ignore
651
+
652
+ if api_key_value and hasattr(
653
+ google.auth._default, "get_api_key_credentials"
654
+ ):
655
+ credentials = google.auth._default.get_api_key_credentials(
656
+ api_key_value
657
+ )
658
+
659
+ transport_init: Union[
660
+ Type[GenerativeServiceTransport],
661
+ Callable[..., GenerativeServiceTransport],
662
+ ] = (
663
+ GenerativeServiceClient.get_transport_class(transport)
664
+ if isinstance(transport, str) or transport is None
665
+ else cast(Callable[..., GenerativeServiceTransport], transport)
666
+ )
667
+ # initialize with the provided callable or the passed in class
668
+ self._transport = transport_init(
669
+ credentials=credentials,
670
+ credentials_file=self._client_options.credentials_file,
671
+ host=self._api_endpoint,
672
+ scopes=self._client_options.scopes,
673
+ client_cert_source_for_mtls=self._client_cert_source,
674
+ quota_project_id=self._client_options.quota_project_id,
675
+ client_info=client_info,
676
+ always_use_jwt_access=True,
677
+ api_audience=self._client_options.api_audience,
678
+ )
679
+
680
+ if "async" not in str(self._transport):
681
+ if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
682
+ std_logging.DEBUG
683
+ ): # pragma: NO COVER
684
+ _LOGGER.debug(
685
+ "Created client `google.ai.generativelanguage_v1alpha.GenerativeServiceClient`.",
686
+ extra={
687
+ "serviceName": "google.ai.generativelanguage.v1alpha.GenerativeService",
688
+ "universeDomain": getattr(
689
+ self._transport._credentials, "universe_domain", ""
690
+ ),
691
+ "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}",
692
+ "credentialsInfo": getattr(
693
+ self.transport._credentials, "get_cred_info", lambda: None
694
+ )(),
695
+ }
696
+ if hasattr(self._transport, "_credentials")
697
+ else {
698
+ "serviceName": "google.ai.generativelanguage.v1alpha.GenerativeService",
699
+ "credentialsType": None,
700
+ },
701
+ )
702
+
703
+ def generate_content(
704
+ self,
705
+ request: Optional[
706
+ Union[generative_service.GenerateContentRequest, dict]
707
+ ] = None,
708
+ *,
709
+ model: Optional[str] = None,
710
+ contents: Optional[MutableSequence[content.Content]] = None,
711
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
712
+ timeout: Union[float, object] = gapic_v1.method.DEFAULT,
713
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
714
+ ) -> generative_service.GenerateContentResponse:
715
+ r"""Generates a model response given an input
716
+ ``GenerateContentRequest``. Refer to the `text generation
717
+ guide <https://ai.google.dev/gemini-api/docs/text-generation>`__
718
+ for detailed usage information. Input capabilities differ
719
+ between models, including tuned models. Refer to the `model
720
+ guide <https://ai.google.dev/gemini-api/docs/models/gemini>`__
721
+ and `tuning
722
+ guide <https://ai.google.dev/gemini-api/docs/model-tuning>`__
723
+ for details.
724
+
725
+ .. code-block:: python
726
+
727
+ # This snippet has been automatically generated and should be regarded as a
728
+ # code template only.
729
+ # It will require modifications to work:
730
+ # - It may require correct/in-range values for request initialization.
731
+ # - It may require specifying regional endpoints when creating the service
732
+ # client as shown in:
733
+ # https://googleapis.dev/python/google-api-core/latest/client_options.html
734
+ from google.ai import generativelanguage_v1alpha
735
+
736
+ def sample_generate_content():
737
+ # Create a client
738
+ client = generativelanguage_v1alpha.GenerativeServiceClient()
739
+
740
+ # Initialize request argument(s)
741
+ request = generativelanguage_v1alpha.GenerateContentRequest(
742
+ model="model_value",
743
+ )
744
+
745
+ # Make the request
746
+ response = client.generate_content(request=request)
747
+
748
+ # Handle the response
749
+ print(response)
750
+
751
+ Args:
752
+ request (Union[google.ai.generativelanguage_v1alpha.types.GenerateContentRequest, dict]):
753
+ The request object. Request to generate a completion from
754
+ the model.
755
+ model (str):
756
+ Required. The name of the ``Model`` to use for
757
+ generating the completion.
758
+
759
+ Format: ``models/{model}``.
760
+
761
+ This corresponds to the ``model`` field
762
+ on the ``request`` instance; if ``request`` is provided, this
763
+ should not be set.
764
+ contents (MutableSequence[google.ai.generativelanguage_v1alpha.types.Content]):
765
+ Required. The content of the current conversation with
766
+ the model.
767
+
768
+ For single-turn queries, this is a single instance. For
769
+ multi-turn queries like
770
+ `chat <https://ai.google.dev/gemini-api/docs/text-generation#chat>`__,
771
+ this is a repeated field that contains the conversation
772
+ history and the latest request.
773
+
774
+ This corresponds to the ``contents`` field
775
+ on the ``request`` instance; if ``request`` is provided, this
776
+ should not be set.
777
+ retry (google.api_core.retry.Retry): 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
+ Returns:
786
+ google.ai.generativelanguage_v1alpha.types.GenerateContentResponse:
787
+ Response from the model supporting multiple candidate
788
+ responses.
789
+
790
+ Safety ratings and content filtering are reported for
791
+ both prompt in
792
+ GenerateContentResponse.prompt_feedback and for each
793
+ candidate in finish_reason and in safety_ratings. The
794
+ API: - Returns either all requested candidates or
795
+ none of them - Returns no candidates at all only if
796
+ there was something wrong with the prompt (check
797
+ prompt_feedback) - Reports feedback on each candidate
798
+ in finish_reason and safety_ratings.
799
+
800
+ """
801
+ # Create or coerce a protobuf request object.
802
+ # - Quick check: If we got a request object, we should *not* have
803
+ # gotten any keyword arguments that map to the request.
804
+ has_flattened_params = any([model, contents])
805
+ if request is not None and has_flattened_params:
806
+ raise ValueError(
807
+ "If the `request` argument is set, then none of "
808
+ "the individual field arguments should be set."
809
+ )
810
+
811
+ # - Use the request object if provided (there's no risk of modifying the input as
812
+ # there are no flattened fields), or create one.
813
+ if not isinstance(request, generative_service.GenerateContentRequest):
814
+ request = generative_service.GenerateContentRequest(request)
815
+ # If we have keyword arguments corresponding to fields on the
816
+ # request, apply these.
817
+ if model is not None:
818
+ request.model = model
819
+ if contents is not None:
820
+ request.contents = contents
821
+
822
+ # Wrap the RPC method; this adds retry and timeout information,
823
+ # and friendly error handling.
824
+ rpc = self._transport._wrapped_methods[self._transport.generate_content]
825
+
826
+ # Certain fields should be provided within the metadata header;
827
+ # add these here.
828
+ metadata = tuple(metadata) + (
829
+ gapic_v1.routing_header.to_grpc_metadata((("model", request.model),)),
830
+ )
831
+
832
+ # Validate the universe domain.
833
+ self._validate_universe_domain()
834
+
835
+ # Send the request.
836
+ response = rpc(
837
+ request,
838
+ retry=retry,
839
+ timeout=timeout,
840
+ metadata=metadata,
841
+ )
842
+
843
+ # Done; return the response.
844
+ return response
845
+
846
+ def generate_answer(
847
+ self,
848
+ request: Optional[Union[generative_service.GenerateAnswerRequest, dict]] = None,
849
+ *,
850
+ model: Optional[str] = None,
851
+ contents: Optional[MutableSequence[content.Content]] = None,
852
+ safety_settings: Optional[MutableSequence[safety.SafetySetting]] = None,
853
+ answer_style: Optional[
854
+ generative_service.GenerateAnswerRequest.AnswerStyle
855
+ ] = None,
856
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
857
+ timeout: Union[float, object] = gapic_v1.method.DEFAULT,
858
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
859
+ ) -> generative_service.GenerateAnswerResponse:
860
+ r"""Generates a grounded answer from the model given an input
861
+ ``GenerateAnswerRequest``.
862
+
863
+ .. code-block:: python
864
+
865
+ # This snippet has been automatically generated and should be regarded as a
866
+ # code template only.
867
+ # It will require modifications to work:
868
+ # - It may require correct/in-range values for request initialization.
869
+ # - It may require specifying regional endpoints when creating the service
870
+ # client as shown in:
871
+ # https://googleapis.dev/python/google-api-core/latest/client_options.html
872
+ from google.ai import generativelanguage_v1alpha
873
+
874
+ def sample_generate_answer():
875
+ # Create a client
876
+ client = generativelanguage_v1alpha.GenerativeServiceClient()
877
+
878
+ # Initialize request argument(s)
879
+ request = generativelanguage_v1alpha.GenerateAnswerRequest(
880
+ model="model_value",
881
+ answer_style="VERBOSE",
882
+ )
883
+
884
+ # Make the request
885
+ response = client.generate_answer(request=request)
886
+
887
+ # Handle the response
888
+ print(response)
889
+
890
+ Args:
891
+ request (Union[google.ai.generativelanguage_v1alpha.types.GenerateAnswerRequest, dict]):
892
+ The request object. Request to generate a grounded answer from the
893
+ ``Model``.
894
+ model (str):
895
+ Required. The name of the ``Model`` to use for
896
+ generating the grounded response.
897
+
898
+ Format: ``model=models/{model}``.
899
+
900
+ This corresponds to the ``model`` field
901
+ on the ``request`` instance; if ``request`` is provided, this
902
+ should not be set.
903
+ contents (MutableSequence[google.ai.generativelanguage_v1alpha.types.Content]):
904
+ Required. The content of the current conversation with
905
+ the ``Model``. For single-turn queries, this is a single
906
+ question to answer. For multi-turn queries, this is a
907
+ repeated field that contains conversation history and
908
+ the last ``Content`` in the list containing the
909
+ question.
910
+
911
+ Note: ``GenerateAnswer`` only supports queries in
912
+ English.
913
+
914
+ This corresponds to the ``contents`` field
915
+ on the ``request`` instance; if ``request`` is provided, this
916
+ should not be set.
917
+ safety_settings (MutableSequence[google.ai.generativelanguage_v1alpha.types.SafetySetting]):
918
+ Optional. A list of unique ``SafetySetting`` instances
919
+ for blocking unsafe content.
920
+
921
+ This will be enforced on the
922
+ ``GenerateAnswerRequest.contents`` and
923
+ ``GenerateAnswerResponse.candidate``. There should not
924
+ be more than one setting for each ``SafetyCategory``
925
+ type. The API will block any contents and responses that
926
+ fail to meet the thresholds set by these settings. This
927
+ list overrides the default settings for each
928
+ ``SafetyCategory`` specified in the safety_settings. If
929
+ there is no ``SafetySetting`` for a given
930
+ ``SafetyCategory`` provided in the list, the API will
931
+ use the default safety setting for that category. Harm
932
+ categories HARM_CATEGORY_HATE_SPEECH,
933
+ HARM_CATEGORY_SEXUALLY_EXPLICIT,
934
+ HARM_CATEGORY_DANGEROUS_CONTENT,
935
+ HARM_CATEGORY_HARASSMENT are supported. Refer to the
936
+ `guide <https://ai.google.dev/gemini-api/docs/safety-settings>`__
937
+ for detailed information on available safety settings.
938
+ Also refer to the `Safety
939
+ guidance <https://ai.google.dev/gemini-api/docs/safety-guidance>`__
940
+ to learn how to incorporate safety considerations in
941
+ your AI applications.
942
+
943
+ This corresponds to the ``safety_settings`` field
944
+ on the ``request`` instance; if ``request`` is provided, this
945
+ should not be set.
946
+ answer_style (google.ai.generativelanguage_v1alpha.types.GenerateAnswerRequest.AnswerStyle):
947
+ Required. Style in which answers
948
+ should be returned.
949
+
950
+ This corresponds to the ``answer_style`` field
951
+ on the ``request`` instance; if ``request`` is provided, this
952
+ should not be set.
953
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
954
+ should be retried.
955
+ timeout (float): The timeout for this request.
956
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
957
+ sent along with the request as metadata. Normally, each value must be of type `str`,
958
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
959
+ be of type `bytes`.
960
+
961
+ Returns:
962
+ google.ai.generativelanguage_v1alpha.types.GenerateAnswerResponse:
963
+ Response from the model for a
964
+ grounded answer.
965
+
966
+ """
967
+ # Create or coerce a protobuf request object.
968
+ # - Quick check: If we got a request object, we should *not* have
969
+ # gotten any keyword arguments that map to the request.
970
+ has_flattened_params = any([model, contents, safety_settings, answer_style])
971
+ if request is not None and has_flattened_params:
972
+ raise ValueError(
973
+ "If the `request` argument is set, then none of "
974
+ "the individual field arguments should be set."
975
+ )
976
+
977
+ # - Use the request object if provided (there's no risk of modifying the input as
978
+ # there are no flattened fields), or create one.
979
+ if not isinstance(request, generative_service.GenerateAnswerRequest):
980
+ request = generative_service.GenerateAnswerRequest(request)
981
+ # If we have keyword arguments corresponding to fields on the
982
+ # request, apply these.
983
+ if model is not None:
984
+ request.model = model
985
+ if contents is not None:
986
+ request.contents = contents
987
+ if safety_settings is not None:
988
+ request.safety_settings = safety_settings
989
+ if answer_style is not None:
990
+ request.answer_style = answer_style
991
+
992
+ # Wrap the RPC method; this adds retry and timeout information,
993
+ # and friendly error handling.
994
+ rpc = self._transport._wrapped_methods[self._transport.generate_answer]
995
+
996
+ # Certain fields should be provided within the metadata header;
997
+ # add these here.
998
+ metadata = tuple(metadata) + (
999
+ gapic_v1.routing_header.to_grpc_metadata((("model", request.model),)),
1000
+ )
1001
+
1002
+ # Validate the universe domain.
1003
+ self._validate_universe_domain()
1004
+
1005
+ # Send the request.
1006
+ response = rpc(
1007
+ request,
1008
+ retry=retry,
1009
+ timeout=timeout,
1010
+ metadata=metadata,
1011
+ )
1012
+
1013
+ # Done; return the response.
1014
+ return response
1015
+
1016
+ def stream_generate_content(
1017
+ self,
1018
+ request: Optional[
1019
+ Union[generative_service.GenerateContentRequest, dict]
1020
+ ] = None,
1021
+ *,
1022
+ model: Optional[str] = None,
1023
+ contents: Optional[MutableSequence[content.Content]] = None,
1024
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
1025
+ timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1026
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1027
+ ) -> Iterable[generative_service.GenerateContentResponse]:
1028
+ r"""Generates a `streamed
1029
+ response <https://ai.google.dev/gemini-api/docs/text-generation?lang=python#generate-a-text-stream>`__
1030
+ from the model given an input ``GenerateContentRequest``.
1031
+
1032
+ .. code-block:: python
1033
+
1034
+ # This snippet has been automatically generated and should be regarded as a
1035
+ # code template only.
1036
+ # It will require modifications to work:
1037
+ # - It may require correct/in-range values for request initialization.
1038
+ # - It may require specifying regional endpoints when creating the service
1039
+ # client as shown in:
1040
+ # https://googleapis.dev/python/google-api-core/latest/client_options.html
1041
+ from google.ai import generativelanguage_v1alpha
1042
+
1043
+ def sample_stream_generate_content():
1044
+ # Create a client
1045
+ client = generativelanguage_v1alpha.GenerativeServiceClient()
1046
+
1047
+ # Initialize request argument(s)
1048
+ request = generativelanguage_v1alpha.GenerateContentRequest(
1049
+ model="model_value",
1050
+ )
1051
+
1052
+ # Make the request
1053
+ stream = client.stream_generate_content(request=request)
1054
+
1055
+ # Handle the response
1056
+ for response in stream:
1057
+ print(response)
1058
+
1059
+ Args:
1060
+ request (Union[google.ai.generativelanguage_v1alpha.types.GenerateContentRequest, dict]):
1061
+ The request object. Request to generate a completion from
1062
+ the model.
1063
+ model (str):
1064
+ Required. The name of the ``Model`` to use for
1065
+ generating the completion.
1066
+
1067
+ Format: ``models/{model}``.
1068
+
1069
+ This corresponds to the ``model`` field
1070
+ on the ``request`` instance; if ``request`` is provided, this
1071
+ should not be set.
1072
+ contents (MutableSequence[google.ai.generativelanguage_v1alpha.types.Content]):
1073
+ Required. The content of the current conversation with
1074
+ the model.
1075
+
1076
+ For single-turn queries, this is a single instance. For
1077
+ multi-turn queries like
1078
+ `chat <https://ai.google.dev/gemini-api/docs/text-generation#chat>`__,
1079
+ this is a repeated field that contains the conversation
1080
+ history and the latest request.
1081
+
1082
+ This corresponds to the ``contents`` field
1083
+ on the ``request`` instance; if ``request`` is provided, this
1084
+ should not be set.
1085
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
1086
+ should be retried.
1087
+ timeout (float): The timeout for this request.
1088
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1089
+ sent along with the request as metadata. Normally, each value must be of type `str`,
1090
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
1091
+ be of type `bytes`.
1092
+
1093
+ Returns:
1094
+ Iterable[google.ai.generativelanguage_v1alpha.types.GenerateContentResponse]:
1095
+ Response from the model supporting multiple candidate
1096
+ responses.
1097
+
1098
+ Safety ratings and content filtering are reported for
1099
+ both prompt in
1100
+ GenerateContentResponse.prompt_feedback and for each
1101
+ candidate in finish_reason and in safety_ratings. The
1102
+ API: - Returns either all requested candidates or
1103
+ none of them - Returns no candidates at all only if
1104
+ there was something wrong with the prompt (check
1105
+ prompt_feedback) - Reports feedback on each candidate
1106
+ in finish_reason and safety_ratings.
1107
+
1108
+ """
1109
+ # Create or coerce a protobuf request object.
1110
+ # - Quick check: If we got a request object, we should *not* have
1111
+ # gotten any keyword arguments that map to the request.
1112
+ has_flattened_params = any([model, contents])
1113
+ if request is not None and has_flattened_params:
1114
+ raise ValueError(
1115
+ "If the `request` argument is set, then none of "
1116
+ "the individual field arguments should be set."
1117
+ )
1118
+
1119
+ # - Use the request object if provided (there's no risk of modifying the input as
1120
+ # there are no flattened fields), or create one.
1121
+ if not isinstance(request, generative_service.GenerateContentRequest):
1122
+ request = generative_service.GenerateContentRequest(request)
1123
+ # If we have keyword arguments corresponding to fields on the
1124
+ # request, apply these.
1125
+ if model is not None:
1126
+ request.model = model
1127
+ if contents is not None:
1128
+ request.contents = contents
1129
+
1130
+ # Wrap the RPC method; this adds retry and timeout information,
1131
+ # and friendly error handling.
1132
+ rpc = self._transport._wrapped_methods[self._transport.stream_generate_content]
1133
+
1134
+ # Certain fields should be provided within the metadata header;
1135
+ # add these here.
1136
+ metadata = tuple(metadata) + (
1137
+ gapic_v1.routing_header.to_grpc_metadata((("model", request.model),)),
1138
+ )
1139
+
1140
+ # Validate the universe domain.
1141
+ self._validate_universe_domain()
1142
+
1143
+ # Send the request.
1144
+ response = rpc(
1145
+ request,
1146
+ retry=retry,
1147
+ timeout=timeout,
1148
+ metadata=metadata,
1149
+ )
1150
+
1151
+ # Done; return the response.
1152
+ return response
1153
+
1154
+ def embed_content(
1155
+ self,
1156
+ request: Optional[Union[generative_service.EmbedContentRequest, dict]] = None,
1157
+ *,
1158
+ model: Optional[str] = None,
1159
+ content: Optional[gag_content.Content] = None,
1160
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
1161
+ timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1162
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1163
+ ) -> generative_service.EmbedContentResponse:
1164
+ r"""Generates a text embedding vector from the input ``Content``
1165
+ using the specified `Gemini Embedding
1166
+ model <https://ai.google.dev/gemini-api/docs/models/gemini#text-embedding>`__.
1167
+
1168
+ .. code-block:: python
1169
+
1170
+ # This snippet has been automatically generated and should be regarded as a
1171
+ # code template only.
1172
+ # It will require modifications to work:
1173
+ # - It may require correct/in-range values for request initialization.
1174
+ # - It may require specifying regional endpoints when creating the service
1175
+ # client as shown in:
1176
+ # https://googleapis.dev/python/google-api-core/latest/client_options.html
1177
+ from google.ai import generativelanguage_v1alpha
1178
+
1179
+ def sample_embed_content():
1180
+ # Create a client
1181
+ client = generativelanguage_v1alpha.GenerativeServiceClient()
1182
+
1183
+ # Initialize request argument(s)
1184
+ request = generativelanguage_v1alpha.EmbedContentRequest(
1185
+ model="model_value",
1186
+ )
1187
+
1188
+ # Make the request
1189
+ response = client.embed_content(request=request)
1190
+
1191
+ # Handle the response
1192
+ print(response)
1193
+
1194
+ Args:
1195
+ request (Union[google.ai.generativelanguage_v1alpha.types.EmbedContentRequest, dict]):
1196
+ The request object. Request containing the ``Content`` for the model to
1197
+ embed.
1198
+ model (str):
1199
+ Required. The model's resource name. This serves as an
1200
+ ID for the Model to use.
1201
+
1202
+ This name should match a model name returned by the
1203
+ ``ListModels`` method.
1204
+
1205
+ Format: ``models/{model}``
1206
+
1207
+ This corresponds to the ``model`` field
1208
+ on the ``request`` instance; if ``request`` is provided, this
1209
+ should not be set.
1210
+ content (google.ai.generativelanguage_v1alpha.types.Content):
1211
+ Required. The content to embed. Only the ``parts.text``
1212
+ fields will be counted.
1213
+
1214
+ This corresponds to the ``content`` field
1215
+ on the ``request`` instance; if ``request`` is provided, this
1216
+ should not be set.
1217
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
1218
+ should be retried.
1219
+ timeout (float): The timeout for this request.
1220
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1221
+ sent along with the request as metadata. Normally, each value must be of type `str`,
1222
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
1223
+ be of type `bytes`.
1224
+
1225
+ Returns:
1226
+ google.ai.generativelanguage_v1alpha.types.EmbedContentResponse:
1227
+ The response to an EmbedContentRequest.
1228
+ """
1229
+ # Create or coerce a protobuf request object.
1230
+ # - Quick check: If we got a request object, we should *not* have
1231
+ # gotten any keyword arguments that map to the request.
1232
+ has_flattened_params = any([model, content])
1233
+ if request is not None and has_flattened_params:
1234
+ raise ValueError(
1235
+ "If the `request` argument is set, then none of "
1236
+ "the individual field arguments should be set."
1237
+ )
1238
+
1239
+ # - Use the request object if provided (there's no risk of modifying the input as
1240
+ # there are no flattened fields), or create one.
1241
+ if not isinstance(request, generative_service.EmbedContentRequest):
1242
+ request = generative_service.EmbedContentRequest(request)
1243
+ # If we have keyword arguments corresponding to fields on the
1244
+ # request, apply these.
1245
+ if model is not None:
1246
+ request.model = model
1247
+ if content is not None:
1248
+ request.content = content
1249
+
1250
+ # Wrap the RPC method; this adds retry and timeout information,
1251
+ # and friendly error handling.
1252
+ rpc = self._transport._wrapped_methods[self._transport.embed_content]
1253
+
1254
+ # Certain fields should be provided within the metadata header;
1255
+ # add these here.
1256
+ metadata = tuple(metadata) + (
1257
+ gapic_v1.routing_header.to_grpc_metadata((("model", request.model),)),
1258
+ )
1259
+
1260
+ # Validate the universe domain.
1261
+ self._validate_universe_domain()
1262
+
1263
+ # Send the request.
1264
+ response = rpc(
1265
+ request,
1266
+ retry=retry,
1267
+ timeout=timeout,
1268
+ metadata=metadata,
1269
+ )
1270
+
1271
+ # Done; return the response.
1272
+ return response
1273
+
1274
+ def batch_embed_contents(
1275
+ self,
1276
+ request: Optional[
1277
+ Union[generative_service.BatchEmbedContentsRequest, dict]
1278
+ ] = None,
1279
+ *,
1280
+ model: Optional[str] = None,
1281
+ requests: Optional[
1282
+ MutableSequence[generative_service.EmbedContentRequest]
1283
+ ] = None,
1284
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
1285
+ timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1286
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1287
+ ) -> generative_service.BatchEmbedContentsResponse:
1288
+ r"""Generates multiple embedding vectors from the input ``Content``
1289
+ which consists of a batch of strings represented as
1290
+ ``EmbedContentRequest`` objects.
1291
+
1292
+ .. code-block:: python
1293
+
1294
+ # This snippet has been automatically generated and should be regarded as a
1295
+ # code template only.
1296
+ # It will require modifications to work:
1297
+ # - It may require correct/in-range values for request initialization.
1298
+ # - It may require specifying regional endpoints when creating the service
1299
+ # client as shown in:
1300
+ # https://googleapis.dev/python/google-api-core/latest/client_options.html
1301
+ from google.ai import generativelanguage_v1alpha
1302
+
1303
+ def sample_batch_embed_contents():
1304
+ # Create a client
1305
+ client = generativelanguage_v1alpha.GenerativeServiceClient()
1306
+
1307
+ # Initialize request argument(s)
1308
+ requests = generativelanguage_v1alpha.EmbedContentRequest()
1309
+ requests.model = "model_value"
1310
+
1311
+ request = generativelanguage_v1alpha.BatchEmbedContentsRequest(
1312
+ model="model_value",
1313
+ requests=requests,
1314
+ )
1315
+
1316
+ # Make the request
1317
+ response = client.batch_embed_contents(request=request)
1318
+
1319
+ # Handle the response
1320
+ print(response)
1321
+
1322
+ Args:
1323
+ request (Union[google.ai.generativelanguage_v1alpha.types.BatchEmbedContentsRequest, dict]):
1324
+ The request object. Batch request to get embeddings from
1325
+ the model for a list of prompts.
1326
+ model (str):
1327
+ Required. The model's resource name. This serves as an
1328
+ ID for the Model to use.
1329
+
1330
+ This name should match a model name returned by the
1331
+ ``ListModels`` method.
1332
+
1333
+ Format: ``models/{model}``
1334
+
1335
+ This corresponds to the ``model`` field
1336
+ on the ``request`` instance; if ``request`` is provided, this
1337
+ should not be set.
1338
+ requests (MutableSequence[google.ai.generativelanguage_v1alpha.types.EmbedContentRequest]):
1339
+ Required. Embed requests for the batch. The model in
1340
+ each of these requests must match the model specified
1341
+ ``BatchEmbedContentsRequest.model``.
1342
+
1343
+ This corresponds to the ``requests`` field
1344
+ on the ``request`` instance; if ``request`` is provided, this
1345
+ should not be set.
1346
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
1347
+ should be retried.
1348
+ timeout (float): The timeout for this request.
1349
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1350
+ sent along with the request as metadata. Normally, each value must be of type `str`,
1351
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
1352
+ be of type `bytes`.
1353
+
1354
+ Returns:
1355
+ google.ai.generativelanguage_v1alpha.types.BatchEmbedContentsResponse:
1356
+ The response to a BatchEmbedContentsRequest.
1357
+ """
1358
+ # Create or coerce a protobuf request object.
1359
+ # - Quick check: If we got a request object, we should *not* have
1360
+ # gotten any keyword arguments that map to the request.
1361
+ has_flattened_params = any([model, requests])
1362
+ if request is not None and has_flattened_params:
1363
+ raise ValueError(
1364
+ "If the `request` argument is set, then none of "
1365
+ "the individual field arguments should be set."
1366
+ )
1367
+
1368
+ # - Use the request object if provided (there's no risk of modifying the input as
1369
+ # there are no flattened fields), or create one.
1370
+ if not isinstance(request, generative_service.BatchEmbedContentsRequest):
1371
+ request = generative_service.BatchEmbedContentsRequest(request)
1372
+ # If we have keyword arguments corresponding to fields on the
1373
+ # request, apply these.
1374
+ if model is not None:
1375
+ request.model = model
1376
+ if requests is not None:
1377
+ request.requests = requests
1378
+
1379
+ # Wrap the RPC method; this adds retry and timeout information,
1380
+ # and friendly error handling.
1381
+ rpc = self._transport._wrapped_methods[self._transport.batch_embed_contents]
1382
+
1383
+ # Certain fields should be provided within the metadata header;
1384
+ # add these here.
1385
+ metadata = tuple(metadata) + (
1386
+ gapic_v1.routing_header.to_grpc_metadata((("model", request.model),)),
1387
+ )
1388
+
1389
+ # Validate the universe domain.
1390
+ self._validate_universe_domain()
1391
+
1392
+ # Send the request.
1393
+ response = rpc(
1394
+ request,
1395
+ retry=retry,
1396
+ timeout=timeout,
1397
+ metadata=metadata,
1398
+ )
1399
+
1400
+ # Done; return the response.
1401
+ return response
1402
+
1403
+ def count_tokens(
1404
+ self,
1405
+ request: Optional[Union[generative_service.CountTokensRequest, dict]] = None,
1406
+ *,
1407
+ model: Optional[str] = None,
1408
+ contents: Optional[MutableSequence[content.Content]] = None,
1409
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
1410
+ timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1411
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1412
+ ) -> generative_service.CountTokensResponse:
1413
+ r"""Runs a model's tokenizer on input ``Content`` and returns the
1414
+ token count. Refer to the `tokens
1415
+ guide <https://ai.google.dev/gemini-api/docs/tokens>`__ to learn
1416
+ more about tokens.
1417
+
1418
+ .. code-block:: python
1419
+
1420
+ # This snippet has been automatically generated and should be regarded as a
1421
+ # code template only.
1422
+ # It will require modifications to work:
1423
+ # - It may require correct/in-range values for request initialization.
1424
+ # - It may require specifying regional endpoints when creating the service
1425
+ # client as shown in:
1426
+ # https://googleapis.dev/python/google-api-core/latest/client_options.html
1427
+ from google.ai import generativelanguage_v1alpha
1428
+
1429
+ def sample_count_tokens():
1430
+ # Create a client
1431
+ client = generativelanguage_v1alpha.GenerativeServiceClient()
1432
+
1433
+ # Initialize request argument(s)
1434
+ request = generativelanguage_v1alpha.CountTokensRequest(
1435
+ model="model_value",
1436
+ )
1437
+
1438
+ # Make the request
1439
+ response = client.count_tokens(request=request)
1440
+
1441
+ # Handle the response
1442
+ print(response)
1443
+
1444
+ Args:
1445
+ request (Union[google.ai.generativelanguage_v1alpha.types.CountTokensRequest, dict]):
1446
+ The request object. Counts the number of tokens in the ``prompt`` sent to a
1447
+ model.
1448
+
1449
+ Models may tokenize text differently, so each model may
1450
+ return a different ``token_count``.
1451
+ model (str):
1452
+ Required. The model's resource name. This serves as an
1453
+ ID for the Model to use.
1454
+
1455
+ This name should match a model name returned by the
1456
+ ``ListModels`` method.
1457
+
1458
+ Format: ``models/{model}``
1459
+
1460
+ This corresponds to the ``model`` field
1461
+ on the ``request`` instance; if ``request`` is provided, this
1462
+ should not be set.
1463
+ contents (MutableSequence[google.ai.generativelanguage_v1alpha.types.Content]):
1464
+ Optional. The input given to the model as a prompt. This
1465
+ field is ignored when ``generate_content_request`` is
1466
+ set.
1467
+
1468
+ This corresponds to the ``contents`` field
1469
+ on the ``request`` instance; if ``request`` is provided, this
1470
+ should not be set.
1471
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
1472
+ should be retried.
1473
+ timeout (float): The timeout for this request.
1474
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1475
+ sent along with the request as metadata. Normally, each value must be of type `str`,
1476
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
1477
+ be of type `bytes`.
1478
+
1479
+ Returns:
1480
+ google.ai.generativelanguage_v1alpha.types.CountTokensResponse:
1481
+ A response from CountTokens.
1482
+
1483
+ It returns the model's token_count for the prompt.
1484
+
1485
+ """
1486
+ # Create or coerce a protobuf request object.
1487
+ # - Quick check: If we got a request object, we should *not* have
1488
+ # gotten any keyword arguments that map to the request.
1489
+ has_flattened_params = any([model, contents])
1490
+ if request is not None and has_flattened_params:
1491
+ raise ValueError(
1492
+ "If the `request` argument is set, then none of "
1493
+ "the individual field arguments should be set."
1494
+ )
1495
+
1496
+ # - Use the request object if provided (there's no risk of modifying the input as
1497
+ # there are no flattened fields), or create one.
1498
+ if not isinstance(request, generative_service.CountTokensRequest):
1499
+ request = generative_service.CountTokensRequest(request)
1500
+ # If we have keyword arguments corresponding to fields on the
1501
+ # request, apply these.
1502
+ if model is not None:
1503
+ request.model = model
1504
+ if contents is not None:
1505
+ request.contents = contents
1506
+
1507
+ # Wrap the RPC method; this adds retry and timeout information,
1508
+ # and friendly error handling.
1509
+ rpc = self._transport._wrapped_methods[self._transport.count_tokens]
1510
+
1511
+ # Certain fields should be provided within the metadata header;
1512
+ # add these here.
1513
+ metadata = tuple(metadata) + (
1514
+ gapic_v1.routing_header.to_grpc_metadata((("model", request.model),)),
1515
+ )
1516
+
1517
+ # Validate the universe domain.
1518
+ self._validate_universe_domain()
1519
+
1520
+ # Send the request.
1521
+ response = rpc(
1522
+ request,
1523
+ retry=retry,
1524
+ timeout=timeout,
1525
+ metadata=metadata,
1526
+ )
1527
+
1528
+ # Done; return the response.
1529
+ return response
1530
+
1531
+ def bidi_generate_content(
1532
+ self,
1533
+ requests: Optional[
1534
+ Iterator[generative_service.BidiGenerateContentClientMessage]
1535
+ ] = None,
1536
+ *,
1537
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
1538
+ timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1539
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1540
+ ) -> Iterable[generative_service.BidiGenerateContentServerMessage]:
1541
+ r"""Low-Latency bidirectional streaming API that supports
1542
+ audio and video streaming inputs can produce multimodal
1543
+ output streams (audio and text).
1544
+
1545
+ .. code-block:: python
1546
+
1547
+ # This snippet has been automatically generated and should be regarded as a
1548
+ # code template only.
1549
+ # It will require modifications to work:
1550
+ # - It may require correct/in-range values for request initialization.
1551
+ # - It may require specifying regional endpoints when creating the service
1552
+ # client as shown in:
1553
+ # https://googleapis.dev/python/google-api-core/latest/client_options.html
1554
+ from google.ai import generativelanguage_v1alpha
1555
+
1556
+ def sample_bidi_generate_content():
1557
+ # Create a client
1558
+ client = generativelanguage_v1alpha.GenerativeServiceClient()
1559
+
1560
+ # Initialize request argument(s)
1561
+ setup = generativelanguage_v1alpha.BidiGenerateContentSetup()
1562
+ setup.model = "model_value"
1563
+
1564
+ request = generativelanguage_v1alpha.BidiGenerateContentClientMessage(
1565
+ setup=setup,
1566
+ )
1567
+
1568
+ # This method expects an iterator which contains
1569
+ # 'generativelanguage_v1alpha.BidiGenerateContentClientMessage' objects
1570
+ # Here we create a generator that yields a single `request` for
1571
+ # demonstrative purposes.
1572
+ requests = [request]
1573
+
1574
+ def request_generator():
1575
+ for request in requests:
1576
+ yield request
1577
+
1578
+ # Make the request
1579
+ stream = client.bidi_generate_content(requests=request_generator())
1580
+
1581
+ # Handle the response
1582
+ for response in stream:
1583
+ print(response)
1584
+
1585
+ Args:
1586
+ requests (Iterator[google.ai.generativelanguage_v1alpha.types.BidiGenerateContentClientMessage]):
1587
+ The request object iterator. Messages sent by the client in the
1588
+ BidiGenerateContent call.
1589
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
1590
+ should be retried.
1591
+ timeout (float): The timeout for this request.
1592
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1593
+ sent along with the request as metadata. Normally, each value must be of type `str`,
1594
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
1595
+ be of type `bytes`.
1596
+
1597
+ Returns:
1598
+ Iterable[google.ai.generativelanguage_v1alpha.types.BidiGenerateContentServerMessage]:
1599
+ Response message for the
1600
+ BidiGenerateContent call.
1601
+
1602
+ """
1603
+
1604
+ # Wrap the RPC method; this adds retry and timeout information,
1605
+ # and friendly error handling.
1606
+ rpc = self._transport._wrapped_methods[self._transport.bidi_generate_content]
1607
+
1608
+ # Validate the universe domain.
1609
+ self._validate_universe_domain()
1610
+
1611
+ # Send the request.
1612
+ response = rpc(
1613
+ requests,
1614
+ retry=retry,
1615
+ timeout=timeout,
1616
+ metadata=metadata,
1617
+ )
1618
+
1619
+ # Done; return the response.
1620
+ return response
1621
+
1622
+ def __enter__(self) -> "GenerativeServiceClient":
1623
+ return self
1624
+
1625
+ def __exit__(self, type, value, traceback):
1626
+ """Releases underlying transport's resources.
1627
+
1628
+ .. warning::
1629
+ ONLY use as a context manager if the transport is NOT shared
1630
+ with other clients! Exiting the with block will CLOSE the transport
1631
+ and may cause errors in other clients!
1632
+ """
1633
+ self.transport.close()
1634
+
1635
+ def list_operations(
1636
+ self,
1637
+ request: Optional[operations_pb2.ListOperationsRequest] = None,
1638
+ *,
1639
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
1640
+ timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1641
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1642
+ ) -> operations_pb2.ListOperationsResponse:
1643
+ r"""Lists operations that match the specified filter in the request.
1644
+
1645
+ Args:
1646
+ request (:class:`~.operations_pb2.ListOperationsRequest`):
1647
+ The request object. Request message for
1648
+ `ListOperations` method.
1649
+ retry (google.api_core.retry.Retry): Designation of what errors,
1650
+ if any, should be retried.
1651
+ timeout (float): The timeout for this request.
1652
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1653
+ sent along with the request as metadata. Normally, each value must be of type `str`,
1654
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
1655
+ be of type `bytes`.
1656
+ Returns:
1657
+ ~.operations_pb2.ListOperationsResponse:
1658
+ Response message for ``ListOperations`` method.
1659
+ """
1660
+ # Create or coerce a protobuf request object.
1661
+ # The request isn't a proto-plus wrapped type,
1662
+ # so it must be constructed via keyword expansion.
1663
+ if isinstance(request, dict):
1664
+ request = operations_pb2.ListOperationsRequest(**request)
1665
+
1666
+ # Wrap the RPC method; this adds retry and timeout information,
1667
+ # and friendly error handling.
1668
+ rpc = self._transport._wrapped_methods[self._transport.list_operations]
1669
+
1670
+ # Certain fields should be provided within the metadata header;
1671
+ # add these here.
1672
+ metadata = tuple(metadata) + (
1673
+ gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
1674
+ )
1675
+
1676
+ # Validate the universe domain.
1677
+ self._validate_universe_domain()
1678
+
1679
+ # Send the request.
1680
+ response = rpc(
1681
+ request,
1682
+ retry=retry,
1683
+ timeout=timeout,
1684
+ metadata=metadata,
1685
+ )
1686
+
1687
+ # Done; return the response.
1688
+ return response
1689
+
1690
+ def get_operation(
1691
+ self,
1692
+ request: Optional[operations_pb2.GetOperationRequest] = None,
1693
+ *,
1694
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
1695
+ timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1696
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1697
+ ) -> operations_pb2.Operation:
1698
+ r"""Gets the latest state of a long-running operation.
1699
+
1700
+ Args:
1701
+ request (:class:`~.operations_pb2.GetOperationRequest`):
1702
+ The request object. Request message for
1703
+ `GetOperation` method.
1704
+ retry (google.api_core.retry.Retry): Designation of what errors,
1705
+ if any, should be retried.
1706
+ timeout (float): The timeout for this request.
1707
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1708
+ sent along with the request as metadata. Normally, each value must be of type `str`,
1709
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
1710
+ be of type `bytes`.
1711
+ Returns:
1712
+ ~.operations_pb2.Operation:
1713
+ An ``Operation`` object.
1714
+ """
1715
+ # Create or coerce a protobuf request object.
1716
+ # The request isn't a proto-plus wrapped type,
1717
+ # so it must be constructed via keyword expansion.
1718
+ if isinstance(request, dict):
1719
+ request = operations_pb2.GetOperationRequest(**request)
1720
+
1721
+ # Wrap the RPC method; this adds retry and timeout information,
1722
+ # and friendly error handling.
1723
+ rpc = self._transport._wrapped_methods[self._transport.get_operation]
1724
+
1725
+ # Certain fields should be provided within the metadata header;
1726
+ # add these here.
1727
+ metadata = tuple(metadata) + (
1728
+ gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
1729
+ )
1730
+
1731
+ # Validate the universe domain.
1732
+ self._validate_universe_domain()
1733
+
1734
+ # Send the request.
1735
+ response = rpc(
1736
+ request,
1737
+ retry=retry,
1738
+ timeout=timeout,
1739
+ metadata=metadata,
1740
+ )
1741
+
1742
+ # Done; return the response.
1743
+ return response
1744
+
1745
+
1746
+ DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
1747
+ gapic_version=package_version.__version__
1748
+ )
1749
+
1750
+
1751
+ __all__ = ("GenerativeServiceClient",)
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/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_v1alpha/services/generative_service/transports/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (926 Bytes). View file
 
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/transports/__pycache__/base.cpython-311.pyc ADDED
Binary file (11.3 kB). View file
 
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/transports/__pycache__/grpc.cpython-311.pyc ADDED
Binary file (25.7 kB). View file
 
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/transports/__pycache__/grpc_asyncio.cpython-311.pyc ADDED
Binary file (28.5 kB). View file
 
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/transports/__pycache__/rest.cpython-311.pyc ADDED
Binary file (66 kB). View file
 
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/transports/__pycache__/rest_base.cpython-311.pyc ADDED
Binary file (23.7 kB). View file
 
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/transports/base.py ADDED
@@ -0,0 +1,298 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
28
+ from google.ai.generativelanguage_v1alpha import gapic_version as package_version
29
+ from google.ai.generativelanguage_v1alpha.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_timeout=None,
135
+ client_info=client_info,
136
+ ),
137
+ self.generate_answer: gapic_v1.method.wrap_method(
138
+ self.generate_answer,
139
+ default_timeout=None,
140
+ client_info=client_info,
141
+ ),
142
+ self.stream_generate_content: gapic_v1.method.wrap_method(
143
+ self.stream_generate_content,
144
+ default_timeout=None,
145
+ client_info=client_info,
146
+ ),
147
+ self.embed_content: gapic_v1.method.wrap_method(
148
+ self.embed_content,
149
+ default_timeout=None,
150
+ client_info=client_info,
151
+ ),
152
+ self.batch_embed_contents: gapic_v1.method.wrap_method(
153
+ self.batch_embed_contents,
154
+ default_timeout=None,
155
+ client_info=client_info,
156
+ ),
157
+ self.count_tokens: gapic_v1.method.wrap_method(
158
+ self.count_tokens,
159
+ default_timeout=None,
160
+ client_info=client_info,
161
+ ),
162
+ self.bidi_generate_content: gapic_v1.method.wrap_method(
163
+ self.bidi_generate_content,
164
+ default_timeout=None,
165
+ client_info=client_info,
166
+ ),
167
+ self.get_operation: gapic_v1.method.wrap_method(
168
+ self.get_operation,
169
+ default_timeout=None,
170
+ client_info=client_info,
171
+ ),
172
+ self.list_operations: gapic_v1.method.wrap_method(
173
+ self.list_operations,
174
+ default_timeout=None,
175
+ client_info=client_info,
176
+ ),
177
+ }
178
+
179
+ def close(self):
180
+ """Closes resources associated with the transport.
181
+
182
+ .. warning::
183
+ Only call this method if the transport is NOT shared
184
+ with other clients - this may cause errors in other clients!
185
+ """
186
+ raise NotImplementedError()
187
+
188
+ @property
189
+ def generate_content(
190
+ self,
191
+ ) -> Callable[
192
+ [generative_service.GenerateContentRequest],
193
+ Union[
194
+ generative_service.GenerateContentResponse,
195
+ Awaitable[generative_service.GenerateContentResponse],
196
+ ],
197
+ ]:
198
+ raise NotImplementedError()
199
+
200
+ @property
201
+ def generate_answer(
202
+ self,
203
+ ) -> Callable[
204
+ [generative_service.GenerateAnswerRequest],
205
+ Union[
206
+ generative_service.GenerateAnswerResponse,
207
+ Awaitable[generative_service.GenerateAnswerResponse],
208
+ ],
209
+ ]:
210
+ raise NotImplementedError()
211
+
212
+ @property
213
+ def stream_generate_content(
214
+ self,
215
+ ) -> Callable[
216
+ [generative_service.GenerateContentRequest],
217
+ Union[
218
+ generative_service.GenerateContentResponse,
219
+ Awaitable[generative_service.GenerateContentResponse],
220
+ ],
221
+ ]:
222
+ raise NotImplementedError()
223
+
224
+ @property
225
+ def embed_content(
226
+ self,
227
+ ) -> Callable[
228
+ [generative_service.EmbedContentRequest],
229
+ Union[
230
+ generative_service.EmbedContentResponse,
231
+ Awaitable[generative_service.EmbedContentResponse],
232
+ ],
233
+ ]:
234
+ raise NotImplementedError()
235
+
236
+ @property
237
+ def batch_embed_contents(
238
+ self,
239
+ ) -> Callable[
240
+ [generative_service.BatchEmbedContentsRequest],
241
+ Union[
242
+ generative_service.BatchEmbedContentsResponse,
243
+ Awaitable[generative_service.BatchEmbedContentsResponse],
244
+ ],
245
+ ]:
246
+ raise NotImplementedError()
247
+
248
+ @property
249
+ def count_tokens(
250
+ self,
251
+ ) -> Callable[
252
+ [generative_service.CountTokensRequest],
253
+ Union[
254
+ generative_service.CountTokensResponse,
255
+ Awaitable[generative_service.CountTokensResponse],
256
+ ],
257
+ ]:
258
+ raise NotImplementedError()
259
+
260
+ @property
261
+ def bidi_generate_content(
262
+ self,
263
+ ) -> Callable[
264
+ [generative_service.BidiGenerateContentClientMessage],
265
+ Union[
266
+ generative_service.BidiGenerateContentServerMessage,
267
+ Awaitable[generative_service.BidiGenerateContentServerMessage],
268
+ ],
269
+ ]:
270
+ raise NotImplementedError()
271
+
272
+ @property
273
+ def list_operations(
274
+ self,
275
+ ) -> Callable[
276
+ [operations_pb2.ListOperationsRequest],
277
+ Union[
278
+ operations_pb2.ListOperationsResponse,
279
+ Awaitable[operations_pb2.ListOperationsResponse],
280
+ ],
281
+ ]:
282
+ raise NotImplementedError()
283
+
284
+ @property
285
+ def get_operation(
286
+ self,
287
+ ) -> Callable[
288
+ [operations_pb2.GetOperationRequest],
289
+ Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]],
290
+ ]:
291
+ raise NotImplementedError()
292
+
293
+ @property
294
+ def kind(self) -> str:
295
+ raise NotImplementedError()
296
+
297
+
298
+ __all__ = ("GenerativeServiceTransport",)
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/transports/grpc.py ADDED
@@ -0,0 +1,591 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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_v1alpha.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.v1alpha.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.v1alpha.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.v1alpha.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.v1alpha.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.v1alpha.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.v1alpha.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.v1alpha.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.v1alpha.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
+ @property
517
+ def bidi_generate_content(
518
+ self,
519
+ ) -> Callable[
520
+ [generative_service.BidiGenerateContentClientMessage],
521
+ generative_service.BidiGenerateContentServerMessage,
522
+ ]:
523
+ r"""Return a callable for the bidi generate content method over gRPC.
524
+
525
+ Low-Latency bidirectional streaming API that supports
526
+ audio and video streaming inputs can produce multimodal
527
+ output streams (audio and text).
528
+
529
+ Returns:
530
+ Callable[[~.BidiGenerateContentClientMessage],
531
+ ~.BidiGenerateContentServerMessage]:
532
+ A function that, when called, will call the underlying RPC
533
+ on the server.
534
+ """
535
+ # Generate a "stub function" on-the-fly which will actually make
536
+ # the request.
537
+ # gRPC handles serialization and deserialization, so we just need
538
+ # to pass in the functions for each.
539
+ if "bidi_generate_content" not in self._stubs:
540
+ self._stubs["bidi_generate_content"] = self._logged_channel.stream_stream(
541
+ "/google.ai.generativelanguage.v1alpha.GenerativeService/BidiGenerateContent",
542
+ request_serializer=generative_service.BidiGenerateContentClientMessage.serialize,
543
+ response_deserializer=generative_service.BidiGenerateContentServerMessage.deserialize,
544
+ )
545
+ return self._stubs["bidi_generate_content"]
546
+
547
+ def close(self):
548
+ self._logged_channel.close()
549
+
550
+ @property
551
+ def get_operation(
552
+ self,
553
+ ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]:
554
+ r"""Return a callable for the get_operation method over gRPC."""
555
+ # Generate a "stub function" on-the-fly which will actually make
556
+ # the request.
557
+ # gRPC handles serialization and deserialization, so we just need
558
+ # to pass in the functions for each.
559
+ if "get_operation" not in self._stubs:
560
+ self._stubs["get_operation"] = self._logged_channel.unary_unary(
561
+ "/google.longrunning.Operations/GetOperation",
562
+ request_serializer=operations_pb2.GetOperationRequest.SerializeToString,
563
+ response_deserializer=operations_pb2.Operation.FromString,
564
+ )
565
+ return self._stubs["get_operation"]
566
+
567
+ @property
568
+ def list_operations(
569
+ self,
570
+ ) -> Callable[
571
+ [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse
572
+ ]:
573
+ r"""Return a callable for the list_operations method over gRPC."""
574
+ # Generate a "stub function" on-the-fly which will actually make
575
+ # the request.
576
+ # gRPC handles serialization and deserialization, so we just need
577
+ # to pass in the functions for each.
578
+ if "list_operations" not in self._stubs:
579
+ self._stubs["list_operations"] = self._logged_channel.unary_unary(
580
+ "/google.longrunning.Operations/ListOperations",
581
+ request_serializer=operations_pb2.ListOperationsRequest.SerializeToString,
582
+ response_deserializer=operations_pb2.ListOperationsResponse.FromString,
583
+ )
584
+ return self._stubs["list_operations"]
585
+
586
+ @property
587
+ def kind(self) -> str:
588
+ return "grpc"
589
+
590
+
591
+ __all__ = ("GenerativeServiceGrpcTransport",)
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/transports/grpc_asyncio.py ADDED
@@ -0,0 +1,654 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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_v1alpha.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.v1alpha.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.v1alpha.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.v1alpha.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.v1alpha.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.v1alpha.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.v1alpha.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.v1alpha.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.v1alpha.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
+ @property
525
+ def bidi_generate_content(
526
+ self,
527
+ ) -> Callable[
528
+ [generative_service.BidiGenerateContentClientMessage],
529
+ Awaitable[generative_service.BidiGenerateContentServerMessage],
530
+ ]:
531
+ r"""Return a callable for the bidi generate content method over gRPC.
532
+
533
+ Low-Latency bidirectional streaming API that supports
534
+ audio and video streaming inputs can produce multimodal
535
+ output streams (audio and text).
536
+
537
+ Returns:
538
+ Callable[[~.BidiGenerateContentClientMessage],
539
+ Awaitable[~.BidiGenerateContentServerMessage]]:
540
+ A function that, when called, will call the underlying RPC
541
+ on the server.
542
+ """
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 "bidi_generate_content" not in self._stubs:
548
+ self._stubs["bidi_generate_content"] = self._logged_channel.stream_stream(
549
+ "/google.ai.generativelanguage.v1alpha.GenerativeService/BidiGenerateContent",
550
+ request_serializer=generative_service.BidiGenerateContentClientMessage.serialize,
551
+ response_deserializer=generative_service.BidiGenerateContentServerMessage.deserialize,
552
+ )
553
+ return self._stubs["bidi_generate_content"]
554
+
555
+ def _prep_wrapped_messages(self, client_info):
556
+ """Precompute the wrapped methods, overriding the base class method to use async wrappers."""
557
+ self._wrapped_methods = {
558
+ self.generate_content: self._wrap_method(
559
+ self.generate_content,
560
+ default_timeout=None,
561
+ client_info=client_info,
562
+ ),
563
+ self.generate_answer: self._wrap_method(
564
+ self.generate_answer,
565
+ default_timeout=None,
566
+ client_info=client_info,
567
+ ),
568
+ self.stream_generate_content: self._wrap_method(
569
+ self.stream_generate_content,
570
+ default_timeout=None,
571
+ client_info=client_info,
572
+ ),
573
+ self.embed_content: self._wrap_method(
574
+ self.embed_content,
575
+ default_timeout=None,
576
+ client_info=client_info,
577
+ ),
578
+ self.batch_embed_contents: self._wrap_method(
579
+ self.batch_embed_contents,
580
+ default_timeout=None,
581
+ client_info=client_info,
582
+ ),
583
+ self.count_tokens: self._wrap_method(
584
+ self.count_tokens,
585
+ default_timeout=None,
586
+ client_info=client_info,
587
+ ),
588
+ self.bidi_generate_content: self._wrap_method(
589
+ self.bidi_generate_content,
590
+ default_timeout=None,
591
+ client_info=client_info,
592
+ ),
593
+ self.get_operation: self._wrap_method(
594
+ self.get_operation,
595
+ default_timeout=None,
596
+ client_info=client_info,
597
+ ),
598
+ self.list_operations: self._wrap_method(
599
+ self.list_operations,
600
+ default_timeout=None,
601
+ client_info=client_info,
602
+ ),
603
+ }
604
+
605
+ def _wrap_method(self, func, *args, **kwargs):
606
+ if self._wrap_with_kind: # pragma: NO COVER
607
+ kwargs["kind"] = self.kind
608
+ return gapic_v1.method_async.wrap_method(func, *args, **kwargs)
609
+
610
+ def close(self):
611
+ return self._logged_channel.close()
612
+
613
+ @property
614
+ def kind(self) -> str:
615
+ return "grpc_asyncio"
616
+
617
+ @property
618
+ def get_operation(
619
+ self,
620
+ ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]:
621
+ r"""Return a callable for the get_operation method over gRPC."""
622
+ # Generate a "stub function" on-the-fly which will actually make
623
+ # the request.
624
+ # gRPC handles serialization and deserialization, so we just need
625
+ # to pass in the functions for each.
626
+ if "get_operation" not in self._stubs:
627
+ self._stubs["get_operation"] = self._logged_channel.unary_unary(
628
+ "/google.longrunning.Operations/GetOperation",
629
+ request_serializer=operations_pb2.GetOperationRequest.SerializeToString,
630
+ response_deserializer=operations_pb2.Operation.FromString,
631
+ )
632
+ return self._stubs["get_operation"]
633
+
634
+ @property
635
+ def list_operations(
636
+ self,
637
+ ) -> Callable[
638
+ [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse
639
+ ]:
640
+ r"""Return a callable for the list_operations method over gRPC."""
641
+ # Generate a "stub function" on-the-fly which will actually make
642
+ # the request.
643
+ # gRPC handles serialization and deserialization, so we just need
644
+ # to pass in the functions for each.
645
+ if "list_operations" not in self._stubs:
646
+ self._stubs["list_operations"] = self._logged_channel.unary_unary(
647
+ "/google.longrunning.Operations/ListOperations",
648
+ request_serializer=operations_pb2.ListOperationsRequest.SerializeToString,
649
+ response_deserializer=operations_pb2.ListOperationsResponse.FromString,
650
+ )
651
+ return self._stubs["list_operations"]
652
+
653
+
654
+ __all__ = ("GenerativeServiceGrpcAsyncIOTransport",)
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/transports/rest.py ADDED
@@ -0,0 +1,1726 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 json_format
29
+ from requests import __version__ as requests_version
30
+
31
+ from google.ai.generativelanguage_v1alpha.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_v1alpha.GenerativeServiceClient.BatchEmbedContents",
514
+ extra={
515
+ "serviceName": "google.ai.generativelanguage.v1alpha.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_v1alpha.GenerativeServiceClient.batch_embed_contents",
561
+ extra={
562
+ "serviceName": "google.ai.generativelanguage.v1alpha.GenerativeService",
563
+ "rpcName": "BatchEmbedContents",
564
+ "metadata": http_response["headers"],
565
+ "httpResponse": http_response,
566
+ },
567
+ )
568
+ return resp
569
+
570
+ class _BidiGenerateContent(
571
+ _BaseGenerativeServiceRestTransport._BaseBidiGenerateContent,
572
+ GenerativeServiceRestStub,
573
+ ):
574
+ def __hash__(self):
575
+ return hash("GenerativeServiceRestTransport.BidiGenerateContent")
576
+
577
+ def __call__(
578
+ self,
579
+ request: generative_service.BidiGenerateContentClientMessage,
580
+ *,
581
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
582
+ timeout: Optional[float] = None,
583
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
584
+ ) -> rest_streaming.ResponseIterator:
585
+ raise NotImplementedError(
586
+ "Method BidiGenerateContent is not available over REST transport"
587
+ )
588
+
589
+ class _CountTokens(
590
+ _BaseGenerativeServiceRestTransport._BaseCountTokens, GenerativeServiceRestStub
591
+ ):
592
+ def __hash__(self):
593
+ return hash("GenerativeServiceRestTransport.CountTokens")
594
+
595
+ @staticmethod
596
+ def _get_response(
597
+ host,
598
+ metadata,
599
+ query_params,
600
+ session,
601
+ timeout,
602
+ transcoded_request,
603
+ body=None,
604
+ ):
605
+ uri = transcoded_request["uri"]
606
+ method = transcoded_request["method"]
607
+ headers = dict(metadata)
608
+ headers["Content-Type"] = "application/json"
609
+ response = getattr(session, method)(
610
+ "{host}{uri}".format(host=host, uri=uri),
611
+ timeout=timeout,
612
+ headers=headers,
613
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
614
+ data=body,
615
+ )
616
+ return response
617
+
618
+ def __call__(
619
+ self,
620
+ request: generative_service.CountTokensRequest,
621
+ *,
622
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
623
+ timeout: Optional[float] = None,
624
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
625
+ ) -> generative_service.CountTokensResponse:
626
+ r"""Call the count tokens method over HTTP.
627
+
628
+ Args:
629
+ request (~.generative_service.CountTokensRequest):
630
+ The request object. Counts the number of tokens in the ``prompt`` sent to a
631
+ model.
632
+
633
+ Models may tokenize text differently, so each model may
634
+ return a different ``token_count``.
635
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
636
+ should be retried.
637
+ timeout (float): The timeout for this request.
638
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
639
+ sent along with the request as metadata. Normally, each value must be of type `str`,
640
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
641
+ be of type `bytes`.
642
+
643
+ Returns:
644
+ ~.generative_service.CountTokensResponse:
645
+ A response from ``CountTokens``.
646
+
647
+ It returns the model's ``token_count`` for the
648
+ ``prompt``.
649
+
650
+ """
651
+
652
+ http_options = (
653
+ _BaseGenerativeServiceRestTransport._BaseCountTokens._get_http_options()
654
+ )
655
+
656
+ request, metadata = self._interceptor.pre_count_tokens(request, metadata)
657
+ transcoded_request = _BaseGenerativeServiceRestTransport._BaseCountTokens._get_transcoded_request(
658
+ http_options, request
659
+ )
660
+
661
+ body = _BaseGenerativeServiceRestTransport._BaseCountTokens._get_request_body_json(
662
+ transcoded_request
663
+ )
664
+
665
+ # Jsonify the query params
666
+ query_params = _BaseGenerativeServiceRestTransport._BaseCountTokens._get_query_params_json(
667
+ transcoded_request
668
+ )
669
+
670
+ if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
671
+ logging.DEBUG
672
+ ): # pragma: NO COVER
673
+ request_url = "{host}{uri}".format(
674
+ host=self._host, uri=transcoded_request["uri"]
675
+ )
676
+ method = transcoded_request["method"]
677
+ try:
678
+ request_payload = type(request).to_json(request)
679
+ except:
680
+ request_payload = None
681
+ http_request = {
682
+ "payload": request_payload,
683
+ "requestMethod": method,
684
+ "requestUrl": request_url,
685
+ "headers": dict(metadata),
686
+ }
687
+ _LOGGER.debug(
688
+ f"Sending request for google.ai.generativelanguage_v1alpha.GenerativeServiceClient.CountTokens",
689
+ extra={
690
+ "serviceName": "google.ai.generativelanguage.v1alpha.GenerativeService",
691
+ "rpcName": "CountTokens",
692
+ "httpRequest": http_request,
693
+ "metadata": http_request["headers"],
694
+ },
695
+ )
696
+
697
+ # Send the request
698
+ response = GenerativeServiceRestTransport._CountTokens._get_response(
699
+ self._host,
700
+ metadata,
701
+ query_params,
702
+ self._session,
703
+ timeout,
704
+ transcoded_request,
705
+ body,
706
+ )
707
+
708
+ # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
709
+ # subclass.
710
+ if response.status_code >= 400:
711
+ raise core_exceptions.from_http_response(response)
712
+
713
+ # Return the response
714
+ resp = generative_service.CountTokensResponse()
715
+ pb_resp = generative_service.CountTokensResponse.pb(resp)
716
+
717
+ json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
718
+
719
+ resp = self._interceptor.post_count_tokens(resp)
720
+ if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
721
+ logging.DEBUG
722
+ ): # pragma: NO COVER
723
+ try:
724
+ response_payload = generative_service.CountTokensResponse.to_json(
725
+ response
726
+ )
727
+ except:
728
+ response_payload = None
729
+ http_response = {
730
+ "payload": response_payload,
731
+ "headers": dict(response.headers),
732
+ "status": response.status_code,
733
+ }
734
+ _LOGGER.debug(
735
+ "Received response for google.ai.generativelanguage_v1alpha.GenerativeServiceClient.count_tokens",
736
+ extra={
737
+ "serviceName": "google.ai.generativelanguage.v1alpha.GenerativeService",
738
+ "rpcName": "CountTokens",
739
+ "metadata": http_response["headers"],
740
+ "httpResponse": http_response,
741
+ },
742
+ )
743
+ return resp
744
+
745
+ class _EmbedContent(
746
+ _BaseGenerativeServiceRestTransport._BaseEmbedContent, GenerativeServiceRestStub
747
+ ):
748
+ def __hash__(self):
749
+ return hash("GenerativeServiceRestTransport.EmbedContent")
750
+
751
+ @staticmethod
752
+ def _get_response(
753
+ host,
754
+ metadata,
755
+ query_params,
756
+ session,
757
+ timeout,
758
+ transcoded_request,
759
+ body=None,
760
+ ):
761
+ uri = transcoded_request["uri"]
762
+ method = transcoded_request["method"]
763
+ headers = dict(metadata)
764
+ headers["Content-Type"] = "application/json"
765
+ response = getattr(session, method)(
766
+ "{host}{uri}".format(host=host, uri=uri),
767
+ timeout=timeout,
768
+ headers=headers,
769
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
770
+ data=body,
771
+ )
772
+ return response
773
+
774
+ def __call__(
775
+ self,
776
+ request: generative_service.EmbedContentRequest,
777
+ *,
778
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
779
+ timeout: Optional[float] = None,
780
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
781
+ ) -> generative_service.EmbedContentResponse:
782
+ r"""Call the embed content method over HTTP.
783
+
784
+ Args:
785
+ request (~.generative_service.EmbedContentRequest):
786
+ The request object. Request containing the ``Content`` for the model to
787
+ embed.
788
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
789
+ should be retried.
790
+ timeout (float): The timeout for this request.
791
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
792
+ sent along with the request as metadata. Normally, each value must be of type `str`,
793
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
794
+ be of type `bytes`.
795
+
796
+ Returns:
797
+ ~.generative_service.EmbedContentResponse:
798
+ The response to an ``EmbedContentRequest``.
799
+ """
800
+
801
+ http_options = (
802
+ _BaseGenerativeServiceRestTransport._BaseEmbedContent._get_http_options()
803
+ )
804
+
805
+ request, metadata = self._interceptor.pre_embed_content(request, metadata)
806
+ transcoded_request = _BaseGenerativeServiceRestTransport._BaseEmbedContent._get_transcoded_request(
807
+ http_options, request
808
+ )
809
+
810
+ body = _BaseGenerativeServiceRestTransport._BaseEmbedContent._get_request_body_json(
811
+ transcoded_request
812
+ )
813
+
814
+ # Jsonify the query params
815
+ query_params = _BaseGenerativeServiceRestTransport._BaseEmbedContent._get_query_params_json(
816
+ transcoded_request
817
+ )
818
+
819
+ if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
820
+ logging.DEBUG
821
+ ): # pragma: NO COVER
822
+ request_url = "{host}{uri}".format(
823
+ host=self._host, uri=transcoded_request["uri"]
824
+ )
825
+ method = transcoded_request["method"]
826
+ try:
827
+ request_payload = type(request).to_json(request)
828
+ except:
829
+ request_payload = None
830
+ http_request = {
831
+ "payload": request_payload,
832
+ "requestMethod": method,
833
+ "requestUrl": request_url,
834
+ "headers": dict(metadata),
835
+ }
836
+ _LOGGER.debug(
837
+ f"Sending request for google.ai.generativelanguage_v1alpha.GenerativeServiceClient.EmbedContent",
838
+ extra={
839
+ "serviceName": "google.ai.generativelanguage.v1alpha.GenerativeService",
840
+ "rpcName": "EmbedContent",
841
+ "httpRequest": http_request,
842
+ "metadata": http_request["headers"],
843
+ },
844
+ )
845
+
846
+ # Send the request
847
+ response = GenerativeServiceRestTransport._EmbedContent._get_response(
848
+ self._host,
849
+ metadata,
850
+ query_params,
851
+ self._session,
852
+ timeout,
853
+ transcoded_request,
854
+ body,
855
+ )
856
+
857
+ # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
858
+ # subclass.
859
+ if response.status_code >= 400:
860
+ raise core_exceptions.from_http_response(response)
861
+
862
+ # Return the response
863
+ resp = generative_service.EmbedContentResponse()
864
+ pb_resp = generative_service.EmbedContentResponse.pb(resp)
865
+
866
+ json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
867
+
868
+ resp = self._interceptor.post_embed_content(resp)
869
+ if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
870
+ logging.DEBUG
871
+ ): # pragma: NO COVER
872
+ try:
873
+ response_payload = generative_service.EmbedContentResponse.to_json(
874
+ response
875
+ )
876
+ except:
877
+ response_payload = None
878
+ http_response = {
879
+ "payload": response_payload,
880
+ "headers": dict(response.headers),
881
+ "status": response.status_code,
882
+ }
883
+ _LOGGER.debug(
884
+ "Received response for google.ai.generativelanguage_v1alpha.GenerativeServiceClient.embed_content",
885
+ extra={
886
+ "serviceName": "google.ai.generativelanguage.v1alpha.GenerativeService",
887
+ "rpcName": "EmbedContent",
888
+ "metadata": http_response["headers"],
889
+ "httpResponse": http_response,
890
+ },
891
+ )
892
+ return resp
893
+
894
+ class _GenerateAnswer(
895
+ _BaseGenerativeServiceRestTransport._BaseGenerateAnswer,
896
+ GenerativeServiceRestStub,
897
+ ):
898
+ def __hash__(self):
899
+ return hash("GenerativeServiceRestTransport.GenerateAnswer")
900
+
901
+ @staticmethod
902
+ def _get_response(
903
+ host,
904
+ metadata,
905
+ query_params,
906
+ session,
907
+ timeout,
908
+ transcoded_request,
909
+ body=None,
910
+ ):
911
+ uri = transcoded_request["uri"]
912
+ method = transcoded_request["method"]
913
+ headers = dict(metadata)
914
+ headers["Content-Type"] = "application/json"
915
+ response = getattr(session, method)(
916
+ "{host}{uri}".format(host=host, uri=uri),
917
+ timeout=timeout,
918
+ headers=headers,
919
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
920
+ data=body,
921
+ )
922
+ return response
923
+
924
+ def __call__(
925
+ self,
926
+ request: generative_service.GenerateAnswerRequest,
927
+ *,
928
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
929
+ timeout: Optional[float] = None,
930
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
931
+ ) -> generative_service.GenerateAnswerResponse:
932
+ r"""Call the generate answer method over HTTP.
933
+
934
+ Args:
935
+ request (~.generative_service.GenerateAnswerRequest):
936
+ The request object. Request to generate a grounded answer from the
937
+ ``Model``.
938
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
939
+ should be retried.
940
+ timeout (float): The timeout for this request.
941
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
942
+ sent along with the request as metadata. Normally, each value must be of type `str`,
943
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
944
+ be of type `bytes`.
945
+
946
+ Returns:
947
+ ~.generative_service.GenerateAnswerResponse:
948
+ Response from the model for a
949
+ grounded answer.
950
+
951
+ """
952
+
953
+ http_options = (
954
+ _BaseGenerativeServiceRestTransport._BaseGenerateAnswer._get_http_options()
955
+ )
956
+
957
+ request, metadata = self._interceptor.pre_generate_answer(request, metadata)
958
+ transcoded_request = _BaseGenerativeServiceRestTransport._BaseGenerateAnswer._get_transcoded_request(
959
+ http_options, request
960
+ )
961
+
962
+ body = _BaseGenerativeServiceRestTransport._BaseGenerateAnswer._get_request_body_json(
963
+ transcoded_request
964
+ )
965
+
966
+ # Jsonify the query params
967
+ query_params = _BaseGenerativeServiceRestTransport._BaseGenerateAnswer._get_query_params_json(
968
+ transcoded_request
969
+ )
970
+
971
+ if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
972
+ logging.DEBUG
973
+ ): # pragma: NO COVER
974
+ request_url = "{host}{uri}".format(
975
+ host=self._host, uri=transcoded_request["uri"]
976
+ )
977
+ method = transcoded_request["method"]
978
+ try:
979
+ request_payload = type(request).to_json(request)
980
+ except:
981
+ request_payload = None
982
+ http_request = {
983
+ "payload": request_payload,
984
+ "requestMethod": method,
985
+ "requestUrl": request_url,
986
+ "headers": dict(metadata),
987
+ }
988
+ _LOGGER.debug(
989
+ f"Sending request for google.ai.generativelanguage_v1alpha.GenerativeServiceClient.GenerateAnswer",
990
+ extra={
991
+ "serviceName": "google.ai.generativelanguage.v1alpha.GenerativeService",
992
+ "rpcName": "GenerateAnswer",
993
+ "httpRequest": http_request,
994
+ "metadata": http_request["headers"],
995
+ },
996
+ )
997
+
998
+ # Send the request
999
+ response = GenerativeServiceRestTransport._GenerateAnswer._get_response(
1000
+ self._host,
1001
+ metadata,
1002
+ query_params,
1003
+ self._session,
1004
+ timeout,
1005
+ transcoded_request,
1006
+ body,
1007
+ )
1008
+
1009
+ # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
1010
+ # subclass.
1011
+ if response.status_code >= 400:
1012
+ raise core_exceptions.from_http_response(response)
1013
+
1014
+ # Return the response
1015
+ resp = generative_service.GenerateAnswerResponse()
1016
+ pb_resp = generative_service.GenerateAnswerResponse.pb(resp)
1017
+
1018
+ json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
1019
+
1020
+ resp = self._interceptor.post_generate_answer(resp)
1021
+ if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
1022
+ logging.DEBUG
1023
+ ): # pragma: NO COVER
1024
+ try:
1025
+ response_payload = (
1026
+ generative_service.GenerateAnswerResponse.to_json(response)
1027
+ )
1028
+ except:
1029
+ response_payload = None
1030
+ http_response = {
1031
+ "payload": response_payload,
1032
+ "headers": dict(response.headers),
1033
+ "status": response.status_code,
1034
+ }
1035
+ _LOGGER.debug(
1036
+ "Received response for google.ai.generativelanguage_v1alpha.GenerativeServiceClient.generate_answer",
1037
+ extra={
1038
+ "serviceName": "google.ai.generativelanguage.v1alpha.GenerativeService",
1039
+ "rpcName": "GenerateAnswer",
1040
+ "metadata": http_response["headers"],
1041
+ "httpResponse": http_response,
1042
+ },
1043
+ )
1044
+ return resp
1045
+
1046
+ class _GenerateContent(
1047
+ _BaseGenerativeServiceRestTransport._BaseGenerateContent,
1048
+ GenerativeServiceRestStub,
1049
+ ):
1050
+ def __hash__(self):
1051
+ return hash("GenerativeServiceRestTransport.GenerateContent")
1052
+
1053
+ @staticmethod
1054
+ def _get_response(
1055
+ host,
1056
+ metadata,
1057
+ query_params,
1058
+ session,
1059
+ timeout,
1060
+ transcoded_request,
1061
+ body=None,
1062
+ ):
1063
+ uri = transcoded_request["uri"]
1064
+ method = transcoded_request["method"]
1065
+ headers = dict(metadata)
1066
+ headers["Content-Type"] = "application/json"
1067
+ response = getattr(session, method)(
1068
+ "{host}{uri}".format(host=host, uri=uri),
1069
+ timeout=timeout,
1070
+ headers=headers,
1071
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
1072
+ data=body,
1073
+ )
1074
+ return response
1075
+
1076
+ def __call__(
1077
+ self,
1078
+ request: generative_service.GenerateContentRequest,
1079
+ *,
1080
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
1081
+ timeout: Optional[float] = None,
1082
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1083
+ ) -> generative_service.GenerateContentResponse:
1084
+ r"""Call the generate content method over HTTP.
1085
+
1086
+ Args:
1087
+ request (~.generative_service.GenerateContentRequest):
1088
+ The request object. Request to generate a completion from
1089
+ the model.
1090
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
1091
+ should be retried.
1092
+ timeout (float): The timeout for this request.
1093
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1094
+ sent along with the request as metadata. Normally, each value must be of type `str`,
1095
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
1096
+ be of type `bytes`.
1097
+
1098
+ Returns:
1099
+ ~.generative_service.GenerateContentResponse:
1100
+ Response from the model supporting multiple candidate
1101
+ responses.
1102
+
1103
+ Safety ratings and content filtering are reported for
1104
+ both prompt in
1105
+ ``GenerateContentResponse.prompt_feedback`` and for each
1106
+ candidate in ``finish_reason`` and in
1107
+ ``safety_ratings``. The API:
1108
+
1109
+ - Returns either all requested candidates or none of
1110
+ them
1111
+ - Returns no candidates at all only if there was
1112
+ something wrong with the prompt (check
1113
+ ``prompt_feedback``)
1114
+ - Reports feedback on each candidate in
1115
+ ``finish_reason`` and ``safety_ratings``.
1116
+
1117
+ """
1118
+
1119
+ http_options = (
1120
+ _BaseGenerativeServiceRestTransport._BaseGenerateContent._get_http_options()
1121
+ )
1122
+
1123
+ request, metadata = self._interceptor.pre_generate_content(
1124
+ request, metadata
1125
+ )
1126
+ transcoded_request = _BaseGenerativeServiceRestTransport._BaseGenerateContent._get_transcoded_request(
1127
+ http_options, request
1128
+ )
1129
+
1130
+ body = _BaseGenerativeServiceRestTransport._BaseGenerateContent._get_request_body_json(
1131
+ transcoded_request
1132
+ )
1133
+
1134
+ # Jsonify the query params
1135
+ query_params = _BaseGenerativeServiceRestTransport._BaseGenerateContent._get_query_params_json(
1136
+ transcoded_request
1137
+ )
1138
+
1139
+ if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
1140
+ logging.DEBUG
1141
+ ): # pragma: NO COVER
1142
+ request_url = "{host}{uri}".format(
1143
+ host=self._host, uri=transcoded_request["uri"]
1144
+ )
1145
+ method = transcoded_request["method"]
1146
+ try:
1147
+ request_payload = type(request).to_json(request)
1148
+ except:
1149
+ request_payload = None
1150
+ http_request = {
1151
+ "payload": request_payload,
1152
+ "requestMethod": method,
1153
+ "requestUrl": request_url,
1154
+ "headers": dict(metadata),
1155
+ }
1156
+ _LOGGER.debug(
1157
+ f"Sending request for google.ai.generativelanguage_v1alpha.GenerativeServiceClient.GenerateContent",
1158
+ extra={
1159
+ "serviceName": "google.ai.generativelanguage.v1alpha.GenerativeService",
1160
+ "rpcName": "GenerateContent",
1161
+ "httpRequest": http_request,
1162
+ "metadata": http_request["headers"],
1163
+ },
1164
+ )
1165
+
1166
+ # Send the request
1167
+ response = GenerativeServiceRestTransport._GenerateContent._get_response(
1168
+ self._host,
1169
+ metadata,
1170
+ query_params,
1171
+ self._session,
1172
+ timeout,
1173
+ transcoded_request,
1174
+ body,
1175
+ )
1176
+
1177
+ # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
1178
+ # subclass.
1179
+ if response.status_code >= 400:
1180
+ raise core_exceptions.from_http_response(response)
1181
+
1182
+ # Return the response
1183
+ resp = generative_service.GenerateContentResponse()
1184
+ pb_resp = generative_service.GenerateContentResponse.pb(resp)
1185
+
1186
+ json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
1187
+
1188
+ resp = self._interceptor.post_generate_content(resp)
1189
+ if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
1190
+ logging.DEBUG
1191
+ ): # pragma: NO COVER
1192
+ try:
1193
+ response_payload = (
1194
+ generative_service.GenerateContentResponse.to_json(response)
1195
+ )
1196
+ except:
1197
+ response_payload = None
1198
+ http_response = {
1199
+ "payload": response_payload,
1200
+ "headers": dict(response.headers),
1201
+ "status": response.status_code,
1202
+ }
1203
+ _LOGGER.debug(
1204
+ "Received response for google.ai.generativelanguage_v1alpha.GenerativeServiceClient.generate_content",
1205
+ extra={
1206
+ "serviceName": "google.ai.generativelanguage.v1alpha.GenerativeService",
1207
+ "rpcName": "GenerateContent",
1208
+ "metadata": http_response["headers"],
1209
+ "httpResponse": http_response,
1210
+ },
1211
+ )
1212
+ return resp
1213
+
1214
+ class _StreamGenerateContent(
1215
+ _BaseGenerativeServiceRestTransport._BaseStreamGenerateContent,
1216
+ GenerativeServiceRestStub,
1217
+ ):
1218
+ def __hash__(self):
1219
+ return hash("GenerativeServiceRestTransport.StreamGenerateContent")
1220
+
1221
+ @staticmethod
1222
+ def _get_response(
1223
+ host,
1224
+ metadata,
1225
+ query_params,
1226
+ session,
1227
+ timeout,
1228
+ transcoded_request,
1229
+ body=None,
1230
+ ):
1231
+ uri = transcoded_request["uri"]
1232
+ method = transcoded_request["method"]
1233
+ headers = dict(metadata)
1234
+ headers["Content-Type"] = "application/json"
1235
+ response = getattr(session, method)(
1236
+ "{host}{uri}".format(host=host, uri=uri),
1237
+ timeout=timeout,
1238
+ headers=headers,
1239
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
1240
+ data=body,
1241
+ stream=True,
1242
+ )
1243
+ return response
1244
+
1245
+ def __call__(
1246
+ self,
1247
+ request: generative_service.GenerateContentRequest,
1248
+ *,
1249
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
1250
+ timeout: Optional[float] = None,
1251
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1252
+ ) -> rest_streaming.ResponseIterator:
1253
+ r"""Call the stream generate content method over HTTP.
1254
+
1255
+ Args:
1256
+ request (~.generative_service.GenerateContentRequest):
1257
+ The request object. Request to generate a completion from
1258
+ the model.
1259
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
1260
+ should be retried.
1261
+ timeout (float): The timeout for this request.
1262
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1263
+ sent along with the request as metadata. Normally, each value must be of type `str`,
1264
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
1265
+ be of type `bytes`.
1266
+
1267
+ Returns:
1268
+ ~.generative_service.GenerateContentResponse:
1269
+ Response from the model supporting multiple candidate
1270
+ responses.
1271
+
1272
+ Safety ratings and content filtering are reported for
1273
+ both prompt in
1274
+ ``GenerateContentResponse.prompt_feedback`` and for each
1275
+ candidate in ``finish_reason`` and in
1276
+ ``safety_ratings``. The API:
1277
+
1278
+ - Returns either all requested candidates or none of
1279
+ them
1280
+ - Returns no candidates at all only if there was
1281
+ something wrong with the prompt (check
1282
+ ``prompt_feedback``)
1283
+ - Reports feedback on each candidate in
1284
+ ``finish_reason`` and ``safety_ratings``.
1285
+
1286
+ """
1287
+
1288
+ http_options = (
1289
+ _BaseGenerativeServiceRestTransport._BaseStreamGenerateContent._get_http_options()
1290
+ )
1291
+
1292
+ request, metadata = self._interceptor.pre_stream_generate_content(
1293
+ request, metadata
1294
+ )
1295
+ transcoded_request = _BaseGenerativeServiceRestTransport._BaseStreamGenerateContent._get_transcoded_request(
1296
+ http_options, request
1297
+ )
1298
+
1299
+ body = _BaseGenerativeServiceRestTransport._BaseStreamGenerateContent._get_request_body_json(
1300
+ transcoded_request
1301
+ )
1302
+
1303
+ # Jsonify the query params
1304
+ query_params = _BaseGenerativeServiceRestTransport._BaseStreamGenerateContent._get_query_params_json(
1305
+ transcoded_request
1306
+ )
1307
+
1308
+ if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
1309
+ logging.DEBUG
1310
+ ): # pragma: NO COVER
1311
+ request_url = "{host}{uri}".format(
1312
+ host=self._host, uri=transcoded_request["uri"]
1313
+ )
1314
+ method = transcoded_request["method"]
1315
+ try:
1316
+ request_payload = type(request).to_json(request)
1317
+ except:
1318
+ request_payload = None
1319
+ http_request = {
1320
+ "payload": request_payload,
1321
+ "requestMethod": method,
1322
+ "requestUrl": request_url,
1323
+ "headers": dict(metadata),
1324
+ }
1325
+ _LOGGER.debug(
1326
+ f"Sending request for google.ai.generativelanguage_v1alpha.GenerativeServiceClient.StreamGenerateContent",
1327
+ extra={
1328
+ "serviceName": "google.ai.generativelanguage.v1alpha.GenerativeService",
1329
+ "rpcName": "StreamGenerateContent",
1330
+ "httpRequest": http_request,
1331
+ "metadata": http_request["headers"],
1332
+ },
1333
+ )
1334
+
1335
+ # Send the request
1336
+ response = (
1337
+ GenerativeServiceRestTransport._StreamGenerateContent._get_response(
1338
+ self._host,
1339
+ metadata,
1340
+ query_params,
1341
+ self._session,
1342
+ timeout,
1343
+ transcoded_request,
1344
+ body,
1345
+ )
1346
+ )
1347
+
1348
+ # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
1349
+ # subclass.
1350
+ if response.status_code >= 400:
1351
+ raise core_exceptions.from_http_response(response)
1352
+
1353
+ # Return the response
1354
+ resp = rest_streaming.ResponseIterator(
1355
+ response, generative_service.GenerateContentResponse
1356
+ )
1357
+
1358
+ resp = self._interceptor.post_stream_generate_content(resp)
1359
+ return resp
1360
+
1361
+ @property
1362
+ def batch_embed_contents(
1363
+ self,
1364
+ ) -> Callable[
1365
+ [generative_service.BatchEmbedContentsRequest],
1366
+ generative_service.BatchEmbedContentsResponse,
1367
+ ]:
1368
+ # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
1369
+ # In C++ this would require a dynamic_cast
1370
+ return self._BatchEmbedContents(self._session, self._host, self._interceptor) # type: ignore
1371
+
1372
+ @property
1373
+ def bidi_generate_content(
1374
+ self,
1375
+ ) -> Callable[
1376
+ [generative_service.BidiGenerateContentClientMessage],
1377
+ generative_service.BidiGenerateContentServerMessage,
1378
+ ]:
1379
+ # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
1380
+ # In C++ this would require a dynamic_cast
1381
+ return self._BidiGenerateContent(self._session, self._host, self._interceptor) # type: ignore
1382
+
1383
+ @property
1384
+ def count_tokens(
1385
+ self,
1386
+ ) -> Callable[
1387
+ [generative_service.CountTokensRequest], generative_service.CountTokensResponse
1388
+ ]:
1389
+ # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
1390
+ # In C++ this would require a dynamic_cast
1391
+ return self._CountTokens(self._session, self._host, self._interceptor) # type: ignore
1392
+
1393
+ @property
1394
+ def embed_content(
1395
+ self,
1396
+ ) -> Callable[
1397
+ [generative_service.EmbedContentRequest],
1398
+ generative_service.EmbedContentResponse,
1399
+ ]:
1400
+ # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
1401
+ # In C++ this would require a dynamic_cast
1402
+ return self._EmbedContent(self._session, self._host, self._interceptor) # type: ignore
1403
+
1404
+ @property
1405
+ def generate_answer(
1406
+ self,
1407
+ ) -> Callable[
1408
+ [generative_service.GenerateAnswerRequest],
1409
+ generative_service.GenerateAnswerResponse,
1410
+ ]:
1411
+ # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
1412
+ # In C++ this would require a dynamic_cast
1413
+ return self._GenerateAnswer(self._session, self._host, self._interceptor) # type: ignore
1414
+
1415
+ @property
1416
+ def generate_content(
1417
+ self,
1418
+ ) -> Callable[
1419
+ [generative_service.GenerateContentRequest],
1420
+ generative_service.GenerateContentResponse,
1421
+ ]:
1422
+ # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
1423
+ # In C++ this would require a dynamic_cast
1424
+ return self._GenerateContent(self._session, self._host, self._interceptor) # type: ignore
1425
+
1426
+ @property
1427
+ def stream_generate_content(
1428
+ self,
1429
+ ) -> Callable[
1430
+ [generative_service.GenerateContentRequest],
1431
+ generative_service.GenerateContentResponse,
1432
+ ]:
1433
+ # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
1434
+ # In C++ this would require a dynamic_cast
1435
+ return self._StreamGenerateContent(self._session, self._host, self._interceptor) # type: ignore
1436
+
1437
+ @property
1438
+ def get_operation(self):
1439
+ return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore
1440
+
1441
+ class _GetOperation(
1442
+ _BaseGenerativeServiceRestTransport._BaseGetOperation, GenerativeServiceRestStub
1443
+ ):
1444
+ def __hash__(self):
1445
+ return hash("GenerativeServiceRestTransport.GetOperation")
1446
+
1447
+ @staticmethod
1448
+ def _get_response(
1449
+ host,
1450
+ metadata,
1451
+ query_params,
1452
+ session,
1453
+ timeout,
1454
+ transcoded_request,
1455
+ body=None,
1456
+ ):
1457
+ uri = transcoded_request["uri"]
1458
+ method = transcoded_request["method"]
1459
+ headers = dict(metadata)
1460
+ headers["Content-Type"] = "application/json"
1461
+ response = getattr(session, method)(
1462
+ "{host}{uri}".format(host=host, uri=uri),
1463
+ timeout=timeout,
1464
+ headers=headers,
1465
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
1466
+ )
1467
+ return response
1468
+
1469
+ def __call__(
1470
+ self,
1471
+ request: operations_pb2.GetOperationRequest,
1472
+ *,
1473
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
1474
+ timeout: Optional[float] = None,
1475
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1476
+ ) -> operations_pb2.Operation:
1477
+ r"""Call the get operation method over HTTP.
1478
+
1479
+ Args:
1480
+ request (operations_pb2.GetOperationRequest):
1481
+ The request object for GetOperation method.
1482
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
1483
+ should be retried.
1484
+ timeout (float): The timeout for this request.
1485
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1486
+ sent along with the request as metadata. Normally, each value must be of type `str`,
1487
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
1488
+ be of type `bytes`.
1489
+
1490
+ Returns:
1491
+ operations_pb2.Operation: Response from GetOperation method.
1492
+ """
1493
+
1494
+ http_options = (
1495
+ _BaseGenerativeServiceRestTransport._BaseGetOperation._get_http_options()
1496
+ )
1497
+
1498
+ request, metadata = self._interceptor.pre_get_operation(request, metadata)
1499
+ transcoded_request = _BaseGenerativeServiceRestTransport._BaseGetOperation._get_transcoded_request(
1500
+ http_options, request
1501
+ )
1502
+
1503
+ # Jsonify the query params
1504
+ query_params = _BaseGenerativeServiceRestTransport._BaseGetOperation._get_query_params_json(
1505
+ transcoded_request
1506
+ )
1507
+
1508
+ if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
1509
+ logging.DEBUG
1510
+ ): # pragma: NO COVER
1511
+ request_url = "{host}{uri}".format(
1512
+ host=self._host, uri=transcoded_request["uri"]
1513
+ )
1514
+ method = transcoded_request["method"]
1515
+ try:
1516
+ request_payload = json_format.MessageToJson(request)
1517
+ except:
1518
+ request_payload = None
1519
+ http_request = {
1520
+ "payload": request_payload,
1521
+ "requestMethod": method,
1522
+ "requestUrl": request_url,
1523
+ "headers": dict(metadata),
1524
+ }
1525
+ _LOGGER.debug(
1526
+ f"Sending request for google.ai.generativelanguage_v1alpha.GenerativeServiceClient.GetOperation",
1527
+ extra={
1528
+ "serviceName": "google.ai.generativelanguage.v1alpha.GenerativeService",
1529
+ "rpcName": "GetOperation",
1530
+ "httpRequest": http_request,
1531
+ "metadata": http_request["headers"],
1532
+ },
1533
+ )
1534
+
1535
+ # Send the request
1536
+ response = GenerativeServiceRestTransport._GetOperation._get_response(
1537
+ self._host,
1538
+ metadata,
1539
+ query_params,
1540
+ self._session,
1541
+ timeout,
1542
+ transcoded_request,
1543
+ )
1544
+
1545
+ # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
1546
+ # subclass.
1547
+ if response.status_code >= 400:
1548
+ raise core_exceptions.from_http_response(response)
1549
+
1550
+ content = response.content.decode("utf-8")
1551
+ resp = operations_pb2.Operation()
1552
+ resp = json_format.Parse(content, resp)
1553
+ resp = self._interceptor.post_get_operation(resp)
1554
+ if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
1555
+ logging.DEBUG
1556
+ ): # pragma: NO COVER
1557
+ try:
1558
+ response_payload = json_format.MessageToJson(resp)
1559
+ except:
1560
+ response_payload = None
1561
+ http_response = {
1562
+ "payload": response_payload,
1563
+ "headers": dict(response.headers),
1564
+ "status": response.status_code,
1565
+ }
1566
+ _LOGGER.debug(
1567
+ "Received response for google.ai.generativelanguage_v1alpha.GenerativeServiceAsyncClient.GetOperation",
1568
+ extra={
1569
+ "serviceName": "google.ai.generativelanguage.v1alpha.GenerativeService",
1570
+ "rpcName": "GetOperation",
1571
+ "httpResponse": http_response,
1572
+ "metadata": http_response["headers"],
1573
+ },
1574
+ )
1575
+ return resp
1576
+
1577
+ @property
1578
+ def list_operations(self):
1579
+ return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore
1580
+
1581
+ class _ListOperations(
1582
+ _BaseGenerativeServiceRestTransport._BaseListOperations,
1583
+ GenerativeServiceRestStub,
1584
+ ):
1585
+ def __hash__(self):
1586
+ return hash("GenerativeServiceRestTransport.ListOperations")
1587
+
1588
+ @staticmethod
1589
+ def _get_response(
1590
+ host,
1591
+ metadata,
1592
+ query_params,
1593
+ session,
1594
+ timeout,
1595
+ transcoded_request,
1596
+ body=None,
1597
+ ):
1598
+ uri = transcoded_request["uri"]
1599
+ method = transcoded_request["method"]
1600
+ headers = dict(metadata)
1601
+ headers["Content-Type"] = "application/json"
1602
+ response = getattr(session, method)(
1603
+ "{host}{uri}".format(host=host, uri=uri),
1604
+ timeout=timeout,
1605
+ headers=headers,
1606
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
1607
+ )
1608
+ return response
1609
+
1610
+ def __call__(
1611
+ self,
1612
+ request: operations_pb2.ListOperationsRequest,
1613
+ *,
1614
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
1615
+ timeout: Optional[float] = None,
1616
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1617
+ ) -> operations_pb2.ListOperationsResponse:
1618
+ r"""Call the list operations method over HTTP.
1619
+
1620
+ Args:
1621
+ request (operations_pb2.ListOperationsRequest):
1622
+ The request object for ListOperations method.
1623
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
1624
+ should be retried.
1625
+ timeout (float): The timeout for this request.
1626
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1627
+ sent along with the request as metadata. Normally, each value must be of type `str`,
1628
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
1629
+ be of type `bytes`.
1630
+
1631
+ Returns:
1632
+ operations_pb2.ListOperationsResponse: Response from ListOperations method.
1633
+ """
1634
+
1635
+ http_options = (
1636
+ _BaseGenerativeServiceRestTransport._BaseListOperations._get_http_options()
1637
+ )
1638
+
1639
+ request, metadata = self._interceptor.pre_list_operations(request, metadata)
1640
+ transcoded_request = _BaseGenerativeServiceRestTransport._BaseListOperations._get_transcoded_request(
1641
+ http_options, request
1642
+ )
1643
+
1644
+ # Jsonify the query params
1645
+ query_params = _BaseGenerativeServiceRestTransport._BaseListOperations._get_query_params_json(
1646
+ transcoded_request
1647
+ )
1648
+
1649
+ if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
1650
+ logging.DEBUG
1651
+ ): # pragma: NO COVER
1652
+ request_url = "{host}{uri}".format(
1653
+ host=self._host, uri=transcoded_request["uri"]
1654
+ )
1655
+ method = transcoded_request["method"]
1656
+ try:
1657
+ request_payload = json_format.MessageToJson(request)
1658
+ except:
1659
+ request_payload = None
1660
+ http_request = {
1661
+ "payload": request_payload,
1662
+ "requestMethod": method,
1663
+ "requestUrl": request_url,
1664
+ "headers": dict(metadata),
1665
+ }
1666
+ _LOGGER.debug(
1667
+ f"Sending request for google.ai.generativelanguage_v1alpha.GenerativeServiceClient.ListOperations",
1668
+ extra={
1669
+ "serviceName": "google.ai.generativelanguage.v1alpha.GenerativeService",
1670
+ "rpcName": "ListOperations",
1671
+ "httpRequest": http_request,
1672
+ "metadata": http_request["headers"],
1673
+ },
1674
+ )
1675
+
1676
+ # Send the request
1677
+ response = GenerativeServiceRestTransport._ListOperations._get_response(
1678
+ self._host,
1679
+ metadata,
1680
+ query_params,
1681
+ self._session,
1682
+ timeout,
1683
+ transcoded_request,
1684
+ )
1685
+
1686
+ # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
1687
+ # subclass.
1688
+ if response.status_code >= 400:
1689
+ raise core_exceptions.from_http_response(response)
1690
+
1691
+ content = response.content.decode("utf-8")
1692
+ resp = operations_pb2.ListOperationsResponse()
1693
+ resp = json_format.Parse(content, resp)
1694
+ resp = self._interceptor.post_list_operations(resp)
1695
+ if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
1696
+ logging.DEBUG
1697
+ ): # pragma: NO COVER
1698
+ try:
1699
+ response_payload = json_format.MessageToJson(resp)
1700
+ except:
1701
+ response_payload = None
1702
+ http_response = {
1703
+ "payload": response_payload,
1704
+ "headers": dict(response.headers),
1705
+ "status": response.status_code,
1706
+ }
1707
+ _LOGGER.debug(
1708
+ "Received response for google.ai.generativelanguage_v1alpha.GenerativeServiceAsyncClient.ListOperations",
1709
+ extra={
1710
+ "serviceName": "google.ai.generativelanguage.v1alpha.GenerativeService",
1711
+ "rpcName": "ListOperations",
1712
+ "httpResponse": http_response,
1713
+ "metadata": http_response["headers"],
1714
+ },
1715
+ )
1716
+ return resp
1717
+
1718
+ @property
1719
+ def kind(self) -> str:
1720
+ return "rest"
1721
+
1722
+ def close(self):
1723
+ self._session.close()
1724
+
1725
+
1726
+ __all__ = ("GenerativeServiceRestTransport",)
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/generative_service/transports/rest_base.py ADDED
@@ -0,0 +1,510 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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_v1alpha.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": "/v1alpha/{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 _BaseBidiGenerateContent:
149
+ def __hash__(self): # pragma: NO COVER
150
+ return NotImplementedError("__hash__ must be implemented.")
151
+
152
+ class _BaseCountTokens:
153
+ def __hash__(self): # pragma: NO COVER
154
+ return NotImplementedError("__hash__ must be implemented.")
155
+
156
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
157
+
158
+ @classmethod
159
+ def _get_unset_required_fields(cls, message_dict):
160
+ return {
161
+ k: v
162
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
163
+ if k not in message_dict
164
+ }
165
+
166
+ @staticmethod
167
+ def _get_http_options():
168
+ http_options: List[Dict[str, str]] = [
169
+ {
170
+ "method": "post",
171
+ "uri": "/v1alpha/{model=models/*}:countTokens",
172
+ "body": "*",
173
+ },
174
+ ]
175
+ return http_options
176
+
177
+ @staticmethod
178
+ def _get_transcoded_request(http_options, request):
179
+ pb_request = generative_service.CountTokensRequest.pb(request)
180
+ transcoded_request = path_template.transcode(http_options, pb_request)
181
+ return transcoded_request
182
+
183
+ @staticmethod
184
+ def _get_request_body_json(transcoded_request):
185
+ # Jsonify the request body
186
+
187
+ body = json_format.MessageToJson(
188
+ transcoded_request["body"], use_integers_for_enums=True
189
+ )
190
+ return body
191
+
192
+ @staticmethod
193
+ def _get_query_params_json(transcoded_request):
194
+ query_params = json.loads(
195
+ json_format.MessageToJson(
196
+ transcoded_request["query_params"],
197
+ use_integers_for_enums=True,
198
+ )
199
+ )
200
+ query_params.update(
201
+ _BaseGenerativeServiceRestTransport._BaseCountTokens._get_unset_required_fields(
202
+ query_params
203
+ )
204
+ )
205
+
206
+ query_params["$alt"] = "json;enum-encoding=int"
207
+ return query_params
208
+
209
+ class _BaseEmbedContent:
210
+ def __hash__(self): # pragma: NO COVER
211
+ return NotImplementedError("__hash__ must be implemented.")
212
+
213
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
214
+
215
+ @classmethod
216
+ def _get_unset_required_fields(cls, message_dict):
217
+ return {
218
+ k: v
219
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
220
+ if k not in message_dict
221
+ }
222
+
223
+ @staticmethod
224
+ def _get_http_options():
225
+ http_options: List[Dict[str, str]] = [
226
+ {
227
+ "method": "post",
228
+ "uri": "/v1alpha/{model=models/*}:embedContent",
229
+ "body": "*",
230
+ },
231
+ ]
232
+ return http_options
233
+
234
+ @staticmethod
235
+ def _get_transcoded_request(http_options, request):
236
+ pb_request = generative_service.EmbedContentRequest.pb(request)
237
+ transcoded_request = path_template.transcode(http_options, pb_request)
238
+ return transcoded_request
239
+
240
+ @staticmethod
241
+ def _get_request_body_json(transcoded_request):
242
+ # Jsonify the request body
243
+
244
+ body = json_format.MessageToJson(
245
+ transcoded_request["body"], use_integers_for_enums=True
246
+ )
247
+ return body
248
+
249
+ @staticmethod
250
+ def _get_query_params_json(transcoded_request):
251
+ query_params = json.loads(
252
+ json_format.MessageToJson(
253
+ transcoded_request["query_params"],
254
+ use_integers_for_enums=True,
255
+ )
256
+ )
257
+ query_params.update(
258
+ _BaseGenerativeServiceRestTransport._BaseEmbedContent._get_unset_required_fields(
259
+ query_params
260
+ )
261
+ )
262
+
263
+ query_params["$alt"] = "json;enum-encoding=int"
264
+ return query_params
265
+
266
+ class _BaseGenerateAnswer:
267
+ def __hash__(self): # pragma: NO COVER
268
+ return NotImplementedError("__hash__ must be implemented.")
269
+
270
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
271
+
272
+ @classmethod
273
+ def _get_unset_required_fields(cls, message_dict):
274
+ return {
275
+ k: v
276
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
277
+ if k not in message_dict
278
+ }
279
+
280
+ @staticmethod
281
+ def _get_http_options():
282
+ http_options: List[Dict[str, str]] = [
283
+ {
284
+ "method": "post",
285
+ "uri": "/v1alpha/{model=models/*}:generateAnswer",
286
+ "body": "*",
287
+ },
288
+ ]
289
+ return http_options
290
+
291
+ @staticmethod
292
+ def _get_transcoded_request(http_options, request):
293
+ pb_request = generative_service.GenerateAnswerRequest.pb(request)
294
+ transcoded_request = path_template.transcode(http_options, pb_request)
295
+ return transcoded_request
296
+
297
+ @staticmethod
298
+ def _get_request_body_json(transcoded_request):
299
+ # Jsonify the request body
300
+
301
+ body = json_format.MessageToJson(
302
+ transcoded_request["body"], use_integers_for_enums=True
303
+ )
304
+ return body
305
+
306
+ @staticmethod
307
+ def _get_query_params_json(transcoded_request):
308
+ query_params = json.loads(
309
+ json_format.MessageToJson(
310
+ transcoded_request["query_params"],
311
+ use_integers_for_enums=True,
312
+ )
313
+ )
314
+ query_params.update(
315
+ _BaseGenerativeServiceRestTransport._BaseGenerateAnswer._get_unset_required_fields(
316
+ query_params
317
+ )
318
+ )
319
+
320
+ query_params["$alt"] = "json;enum-encoding=int"
321
+ return query_params
322
+
323
+ class _BaseGenerateContent:
324
+ def __hash__(self): # pragma: NO COVER
325
+ return NotImplementedError("__hash__ must be implemented.")
326
+
327
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
328
+
329
+ @classmethod
330
+ def _get_unset_required_fields(cls, message_dict):
331
+ return {
332
+ k: v
333
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
334
+ if k not in message_dict
335
+ }
336
+
337
+ @staticmethod
338
+ def _get_http_options():
339
+ http_options: List[Dict[str, str]] = [
340
+ {
341
+ "method": "post",
342
+ "uri": "/v1alpha/{model=models/*}:generateContent",
343
+ "body": "*",
344
+ },
345
+ {
346
+ "method": "post",
347
+ "uri": "/v1alpha/{model=tunedModels/*}:generateContent",
348
+ "body": "*",
349
+ },
350
+ ]
351
+ return http_options
352
+
353
+ @staticmethod
354
+ def _get_transcoded_request(http_options, request):
355
+ pb_request = generative_service.GenerateContentRequest.pb(request)
356
+ transcoded_request = path_template.transcode(http_options, pb_request)
357
+ return transcoded_request
358
+
359
+ @staticmethod
360
+ def _get_request_body_json(transcoded_request):
361
+ # Jsonify the request body
362
+
363
+ body = json_format.MessageToJson(
364
+ transcoded_request["body"], use_integers_for_enums=True
365
+ )
366
+ return body
367
+
368
+ @staticmethod
369
+ def _get_query_params_json(transcoded_request):
370
+ query_params = json.loads(
371
+ json_format.MessageToJson(
372
+ transcoded_request["query_params"],
373
+ use_integers_for_enums=True,
374
+ )
375
+ )
376
+ query_params.update(
377
+ _BaseGenerativeServiceRestTransport._BaseGenerateContent._get_unset_required_fields(
378
+ query_params
379
+ )
380
+ )
381
+
382
+ query_params["$alt"] = "json;enum-encoding=int"
383
+ return query_params
384
+
385
+ class _BaseStreamGenerateContent:
386
+ def __hash__(self): # pragma: NO COVER
387
+ return NotImplementedError("__hash__ must be implemented.")
388
+
389
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
390
+
391
+ @classmethod
392
+ def _get_unset_required_fields(cls, message_dict):
393
+ return {
394
+ k: v
395
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
396
+ if k not in message_dict
397
+ }
398
+
399
+ @staticmethod
400
+ def _get_http_options():
401
+ http_options: List[Dict[str, str]] = [
402
+ {
403
+ "method": "post",
404
+ "uri": "/v1alpha/{model=models/*}:streamGenerateContent",
405
+ "body": "*",
406
+ },
407
+ {
408
+ "method": "post",
409
+ "uri": "/v1alpha/{model=tunedModels/*}:streamGenerateContent",
410
+ "body": "*",
411
+ },
412
+ ]
413
+ return http_options
414
+
415
+ @staticmethod
416
+ def _get_transcoded_request(http_options, request):
417
+ pb_request = generative_service.GenerateContentRequest.pb(request)
418
+ transcoded_request = path_template.transcode(http_options, pb_request)
419
+ return transcoded_request
420
+
421
+ @staticmethod
422
+ def _get_request_body_json(transcoded_request):
423
+ # Jsonify the request body
424
+
425
+ body = json_format.MessageToJson(
426
+ transcoded_request["body"], use_integers_for_enums=True
427
+ )
428
+ return body
429
+
430
+ @staticmethod
431
+ def _get_query_params_json(transcoded_request):
432
+ query_params = json.loads(
433
+ json_format.MessageToJson(
434
+ transcoded_request["query_params"],
435
+ use_integers_for_enums=True,
436
+ )
437
+ )
438
+ query_params.update(
439
+ _BaseGenerativeServiceRestTransport._BaseStreamGenerateContent._get_unset_required_fields(
440
+ query_params
441
+ )
442
+ )
443
+
444
+ query_params["$alt"] = "json;enum-encoding=int"
445
+ return query_params
446
+
447
+ class _BaseGetOperation:
448
+ def __hash__(self): # pragma: NO COVER
449
+ return NotImplementedError("__hash__ must be implemented.")
450
+
451
+ @staticmethod
452
+ def _get_http_options():
453
+ http_options: List[Dict[str, str]] = [
454
+ {
455
+ "method": "get",
456
+ "uri": "/v1alpha/{name=tunedModels/*/operations/*}",
457
+ },
458
+ {
459
+ "method": "get",
460
+ "uri": "/v1alpha/{name=generatedFiles/*/operations/*}",
461
+ },
462
+ {
463
+ "method": "get",
464
+ "uri": "/v1alpha/{name=models/*/operations/*}",
465
+ },
466
+ ]
467
+ return http_options
468
+
469
+ @staticmethod
470
+ def _get_transcoded_request(http_options, request):
471
+ request_kwargs = json_format.MessageToDict(request)
472
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
473
+ return transcoded_request
474
+
475
+ @staticmethod
476
+ def _get_query_params_json(transcoded_request):
477
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
478
+ return query_params
479
+
480
+ class _BaseListOperations:
481
+ def __hash__(self): # pragma: NO COVER
482
+ return NotImplementedError("__hash__ must be implemented.")
483
+
484
+ @staticmethod
485
+ def _get_http_options():
486
+ http_options: List[Dict[str, str]] = [
487
+ {
488
+ "method": "get",
489
+ "uri": "/v1alpha/{name=tunedModels/*}/operations",
490
+ },
491
+ {
492
+ "method": "get",
493
+ "uri": "/v1alpha/{name=models/*}/operations",
494
+ },
495
+ ]
496
+ return http_options
497
+
498
+ @staticmethod
499
+ def _get_transcoded_request(http_options, request):
500
+ request_kwargs = json_format.MessageToDict(request)
501
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
502
+ return transcoded_request
503
+
504
+ @staticmethod
505
+ def _get_query_params_json(transcoded_request):
506
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
507
+ return query_params
508
+
509
+
510
+ __all__ = ("_BaseGenerativeServiceRestTransport",)
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/permission_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 PermissionServiceAsyncClient
17
+ from .client import PermissionServiceClient
18
+
19
+ __all__ = (
20
+ "PermissionServiceClient",
21
+ "PermissionServiceAsyncClient",
22
+ )
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/permission_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 PermissionServiceTransport
20
+ from .grpc import PermissionServiceGrpcTransport
21
+ from .grpc_asyncio import PermissionServiceGrpcAsyncIOTransport
22
+ from .rest import PermissionServiceRestInterceptor, PermissionServiceRestTransport
23
+
24
+ # Compile a registry of transports.
25
+ _transport_registry = OrderedDict() # type: Dict[str, Type[PermissionServiceTransport]]
26
+ _transport_registry["grpc"] = PermissionServiceGrpcTransport
27
+ _transport_registry["grpc_asyncio"] = PermissionServiceGrpcAsyncIOTransport
28
+ _transport_registry["rest"] = PermissionServiceRestTransport
29
+
30
+ __all__ = (
31
+ "PermissionServiceTransport",
32
+ "PermissionServiceGrpcTransport",
33
+ "PermissionServiceGrpcAsyncIOTransport",
34
+ "PermissionServiceRestTransport",
35
+ "PermissionServiceRestInterceptor",
36
+ )
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/permission_service/transports/__pycache__/base.cpython-311.pyc ADDED
Binary file (10.8 kB). View file
 
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/permission_service/transports/__pycache__/grpc_asyncio.cpython-311.pyc ADDED
Binary file (26.1 kB). View file
 
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/permission_service/transports/base.py ADDED
@@ -0,0 +1,272 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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_v1alpha import gapic_version as package_version
30
+ from google.ai.generativelanguage_v1alpha.types import permission as gag_permission
31
+ from google.ai.generativelanguage_v1alpha.types import permission
32
+ from google.ai.generativelanguage_v1alpha.types import permission_service
33
+
34
+ DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
35
+ gapic_version=package_version.__version__
36
+ )
37
+
38
+
39
+ class PermissionServiceTransport(abc.ABC):
40
+ """Abstract transport class for PermissionService."""
41
+
42
+ AUTH_SCOPES = ()
43
+
44
+ DEFAULT_HOST: str = "generativelanguage.googleapis.com"
45
+
46
+ def __init__(
47
+ self,
48
+ *,
49
+ host: str = DEFAULT_HOST,
50
+ credentials: Optional[ga_credentials.Credentials] = None,
51
+ credentials_file: Optional[str] = None,
52
+ scopes: Optional[Sequence[str]] = None,
53
+ quota_project_id: Optional[str] = None,
54
+ client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
55
+ always_use_jwt_access: Optional[bool] = False,
56
+ api_audience: Optional[str] = None,
57
+ **kwargs,
58
+ ) -> None:
59
+ """Instantiate the transport.
60
+
61
+ Args:
62
+ host (Optional[str]):
63
+ The hostname to connect to (default: 'generativelanguage.googleapis.com').
64
+ credentials (Optional[google.auth.credentials.Credentials]): The
65
+ authorization credentials to attach to requests. These
66
+ credentials identify the application to the service; if none
67
+ are specified, the client will attempt to ascertain the
68
+ credentials from the environment.
69
+ credentials_file (Optional[str]): A file with credentials that can
70
+ be loaded with :func:`google.auth.load_credentials_from_file`.
71
+ This argument is mutually exclusive with credentials.
72
+ scopes (Optional[Sequence[str]]): A list of scopes.
73
+ quota_project_id (Optional[str]): An optional project to use for billing
74
+ and quota.
75
+ client_info (google.api_core.gapic_v1.client_info.ClientInfo):
76
+ The client info used to send a user-agent string along with
77
+ API requests. If ``None``, then default info will be used.
78
+ Generally, you only need to set this if you're developing
79
+ your own client library.
80
+ always_use_jwt_access (Optional[bool]): Whether self signed JWT should
81
+ be used for service account credentials.
82
+ """
83
+
84
+ scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES}
85
+
86
+ # Save the scopes.
87
+ self._scopes = scopes
88
+ if not hasattr(self, "_ignore_credentials"):
89
+ self._ignore_credentials: bool = False
90
+
91
+ # If no credentials are provided, then determine the appropriate
92
+ # defaults.
93
+ if credentials and credentials_file:
94
+ raise core_exceptions.DuplicateCredentialArgs(
95
+ "'credentials_file' and 'credentials' are mutually exclusive"
96
+ )
97
+
98
+ if credentials_file is not None:
99
+ credentials, _ = google.auth.load_credentials_from_file(
100
+ credentials_file, **scopes_kwargs, quota_project_id=quota_project_id
101
+ )
102
+ elif credentials is None and not self._ignore_credentials:
103
+ credentials, _ = google.auth.default(
104
+ **scopes_kwargs, quota_project_id=quota_project_id
105
+ )
106
+ # Don't apply audience if the credentials file passed from user.
107
+ if hasattr(credentials, "with_gdch_audience"):
108
+ credentials = credentials.with_gdch_audience(
109
+ api_audience if api_audience else host
110
+ )
111
+
112
+ # If the credentials are service account credentials, then always try to use self signed JWT.
113
+ if (
114
+ always_use_jwt_access
115
+ and isinstance(credentials, service_account.Credentials)
116
+ and hasattr(service_account.Credentials, "with_always_use_jwt_access")
117
+ ):
118
+ credentials = credentials.with_always_use_jwt_access(True)
119
+
120
+ # Save the credentials.
121
+ self._credentials = credentials
122
+
123
+ # Save the hostname. Default to port 443 (HTTPS) if none is specified.
124
+ if ":" not in host:
125
+ host += ":443"
126
+ self._host = host
127
+
128
+ @property
129
+ def host(self):
130
+ return self._host
131
+
132
+ def _prep_wrapped_messages(self, client_info):
133
+ # Precompute the wrapped methods.
134
+ self._wrapped_methods = {
135
+ self.create_permission: gapic_v1.method.wrap_method(
136
+ self.create_permission,
137
+ default_timeout=None,
138
+ client_info=client_info,
139
+ ),
140
+ self.get_permission: gapic_v1.method.wrap_method(
141
+ self.get_permission,
142
+ default_timeout=None,
143
+ client_info=client_info,
144
+ ),
145
+ self.list_permissions: gapic_v1.method.wrap_method(
146
+ self.list_permissions,
147
+ default_timeout=None,
148
+ client_info=client_info,
149
+ ),
150
+ self.update_permission: gapic_v1.method.wrap_method(
151
+ self.update_permission,
152
+ default_timeout=None,
153
+ client_info=client_info,
154
+ ),
155
+ self.delete_permission: gapic_v1.method.wrap_method(
156
+ self.delete_permission,
157
+ default_timeout=None,
158
+ client_info=client_info,
159
+ ),
160
+ self.transfer_ownership: gapic_v1.method.wrap_method(
161
+ self.transfer_ownership,
162
+ default_timeout=None,
163
+ client_info=client_info,
164
+ ),
165
+ self.get_operation: gapic_v1.method.wrap_method(
166
+ self.get_operation,
167
+ default_timeout=None,
168
+ client_info=client_info,
169
+ ),
170
+ self.list_operations: gapic_v1.method.wrap_method(
171
+ self.list_operations,
172
+ default_timeout=None,
173
+ client_info=client_info,
174
+ ),
175
+ }
176
+
177
+ def close(self):
178
+ """Closes resources associated with the transport.
179
+
180
+ .. warning::
181
+ Only call this method if the transport is NOT shared
182
+ with other clients - this may cause errors in other clients!
183
+ """
184
+ raise NotImplementedError()
185
+
186
+ @property
187
+ def create_permission(
188
+ self,
189
+ ) -> Callable[
190
+ [permission_service.CreatePermissionRequest],
191
+ Union[gag_permission.Permission, Awaitable[gag_permission.Permission]],
192
+ ]:
193
+ raise NotImplementedError()
194
+
195
+ @property
196
+ def get_permission(
197
+ self,
198
+ ) -> Callable[
199
+ [permission_service.GetPermissionRequest],
200
+ Union[permission.Permission, Awaitable[permission.Permission]],
201
+ ]:
202
+ raise NotImplementedError()
203
+
204
+ @property
205
+ def list_permissions(
206
+ self,
207
+ ) -> Callable[
208
+ [permission_service.ListPermissionsRequest],
209
+ Union[
210
+ permission_service.ListPermissionsResponse,
211
+ Awaitable[permission_service.ListPermissionsResponse],
212
+ ],
213
+ ]:
214
+ raise NotImplementedError()
215
+
216
+ @property
217
+ def update_permission(
218
+ self,
219
+ ) -> Callable[
220
+ [permission_service.UpdatePermissionRequest],
221
+ Union[gag_permission.Permission, Awaitable[gag_permission.Permission]],
222
+ ]:
223
+ raise NotImplementedError()
224
+
225
+ @property
226
+ def delete_permission(
227
+ self,
228
+ ) -> Callable[
229
+ [permission_service.DeletePermissionRequest],
230
+ Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]],
231
+ ]:
232
+ raise NotImplementedError()
233
+
234
+ @property
235
+ def transfer_ownership(
236
+ self,
237
+ ) -> Callable[
238
+ [permission_service.TransferOwnershipRequest],
239
+ Union[
240
+ permission_service.TransferOwnershipResponse,
241
+ Awaitable[permission_service.TransferOwnershipResponse],
242
+ ],
243
+ ]:
244
+ raise NotImplementedError()
245
+
246
+ @property
247
+ def list_operations(
248
+ self,
249
+ ) -> Callable[
250
+ [operations_pb2.ListOperationsRequest],
251
+ Union[
252
+ operations_pb2.ListOperationsResponse,
253
+ Awaitable[operations_pb2.ListOperationsResponse],
254
+ ],
255
+ ]:
256
+ raise NotImplementedError()
257
+
258
+ @property
259
+ def get_operation(
260
+ self,
261
+ ) -> Callable[
262
+ [operations_pb2.GetOperationRequest],
263
+ Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]],
264
+ ]:
265
+ raise NotImplementedError()
266
+
267
+ @property
268
+ def kind(self) -> str:
269
+ raise NotImplementedError()
270
+
271
+
272
+ __all__ = ("PermissionServiceTransport",)
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/permission_service/transports/grpc.py ADDED
@@ -0,0 +1,541 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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_v1alpha.types import permission as gag_permission
34
+ from google.ai.generativelanguage_v1alpha.types import permission
35
+ from google.ai.generativelanguage_v1alpha.types import permission_service
36
+
37
+ from .base import DEFAULT_CLIENT_INFO, PermissionServiceTransport
38
+
39
+ try:
40
+ from google.api_core import client_logging # type: ignore
41
+
42
+ CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER
43
+ except ImportError: # pragma: NO COVER
44
+ CLIENT_LOGGING_SUPPORTED = False
45
+
46
+ _LOGGER = std_logging.getLogger(__name__)
47
+
48
+
49
+ class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER
50
+ def intercept_unary_unary(self, continuation, client_call_details, request):
51
+ logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
52
+ std_logging.DEBUG
53
+ )
54
+ if logging_enabled: # pragma: NO COVER
55
+ request_metadata = client_call_details.metadata
56
+ if isinstance(request, proto.Message):
57
+ request_payload = type(request).to_json(request)
58
+ elif isinstance(request, google.protobuf.message.Message):
59
+ request_payload = MessageToJson(request)
60
+ else:
61
+ request_payload = f"{type(request).__name__}: {pickle.dumps(request)}"
62
+
63
+ request_metadata = {
64
+ key: value.decode("utf-8") if isinstance(value, bytes) else value
65
+ for key, value in request_metadata
66
+ }
67
+ grpc_request = {
68
+ "payload": request_payload,
69
+ "requestMethod": "grpc",
70
+ "metadata": dict(request_metadata),
71
+ }
72
+ _LOGGER.debug(
73
+ f"Sending request for {client_call_details.method}",
74
+ extra={
75
+ "serviceName": "google.ai.generativelanguage.v1alpha.PermissionService",
76
+ "rpcName": client_call_details.method,
77
+ "request": grpc_request,
78
+ "metadata": grpc_request["metadata"],
79
+ },
80
+ )
81
+
82
+ response = continuation(client_call_details, request)
83
+ if logging_enabled: # pragma: NO COVER
84
+ response_metadata = response.trailing_metadata()
85
+ # Convert gRPC metadata `<class 'grpc.aio._metadata.Metadata'>` to list of tuples
86
+ metadata = (
87
+ dict([(k, str(v)) for k, v in response_metadata])
88
+ if response_metadata
89
+ else None
90
+ )
91
+ result = response.result()
92
+ if isinstance(result, proto.Message):
93
+ response_payload = type(result).to_json(result)
94
+ elif isinstance(result, google.protobuf.message.Message):
95
+ response_payload = MessageToJson(result)
96
+ else:
97
+ response_payload = f"{type(result).__name__}: {pickle.dumps(result)}"
98
+ grpc_response = {
99
+ "payload": response_payload,
100
+ "metadata": metadata,
101
+ "status": "OK",
102
+ }
103
+ _LOGGER.debug(
104
+ f"Received response for {client_call_details.method}.",
105
+ extra={
106
+ "serviceName": "google.ai.generativelanguage.v1alpha.PermissionService",
107
+ "rpcName": client_call_details.method,
108
+ "response": grpc_response,
109
+ "metadata": grpc_response["metadata"],
110
+ },
111
+ )
112
+ return response
113
+
114
+
115
+ class PermissionServiceGrpcTransport(PermissionServiceTransport):
116
+ """gRPC backend transport for PermissionService.
117
+
118
+ Provides methods for managing permissions to PaLM API
119
+ resources.
120
+
121
+ This class defines the same methods as the primary client, so the
122
+ primary client can load the underlying transport implementation
123
+ and call it.
124
+
125
+ It sends protocol buffers over the wire using gRPC (which is built on
126
+ top of HTTP/2); the ``grpcio`` package must be installed.
127
+ """
128
+
129
+ _stubs: Dict[str, Callable]
130
+
131
+ def __init__(
132
+ self,
133
+ *,
134
+ host: str = "generativelanguage.googleapis.com",
135
+ credentials: Optional[ga_credentials.Credentials] = None,
136
+ credentials_file: Optional[str] = None,
137
+ scopes: Optional[Sequence[str]] = None,
138
+ channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None,
139
+ api_mtls_endpoint: Optional[str] = None,
140
+ client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None,
141
+ ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None,
142
+ client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None,
143
+ quota_project_id: Optional[str] = None,
144
+ client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
145
+ always_use_jwt_access: Optional[bool] = False,
146
+ api_audience: Optional[str] = None,
147
+ ) -> None:
148
+ """Instantiate the transport.
149
+
150
+ Args:
151
+ host (Optional[str]):
152
+ The hostname to connect to (default: 'generativelanguage.googleapis.com').
153
+ credentials (Optional[google.auth.credentials.Credentials]): The
154
+ authorization credentials to attach to requests. These
155
+ credentials identify the application to the service; if none
156
+ are specified, the client will attempt to ascertain the
157
+ credentials from the environment.
158
+ This argument is ignored if a ``channel`` instance is provided.
159
+ credentials_file (Optional[str]): A file with credentials that can
160
+ be loaded with :func:`google.auth.load_credentials_from_file`.
161
+ This argument is ignored if a ``channel`` instance is provided.
162
+ scopes (Optional(Sequence[str])): A list of scopes. This argument is
163
+ ignored if a ``channel`` instance is provided.
164
+ channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]):
165
+ A ``Channel`` instance through which to make calls, or a Callable
166
+ that constructs and returns one. If set to None, ``self.create_channel``
167
+ is used to create the channel. If a Callable is given, it will be called
168
+ with the same arguments as used in ``self.create_channel``.
169
+ api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint.
170
+ If provided, it overrides the ``host`` argument and tries to create
171
+ a mutual TLS channel with client SSL credentials from
172
+ ``client_cert_source`` or application default SSL credentials.
173
+ client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]):
174
+ Deprecated. A callback to provide client SSL certificate bytes and
175
+ private key bytes, both in PEM format. It is ignored if
176
+ ``api_mtls_endpoint`` is None.
177
+ ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials
178
+ for the grpc channel. It is ignored if a ``channel`` instance is provided.
179
+ client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]):
180
+ A callback to provide client certificate bytes and private key bytes,
181
+ both in PEM format. It is used to configure a mutual TLS channel. It is
182
+ ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided.
183
+ quota_project_id (Optional[str]): An optional project to use for billing
184
+ and quota.
185
+ client_info (google.api_core.gapic_v1.client_info.ClientInfo):
186
+ The client info used to send a user-agent string along with
187
+ API requests. If ``None``, then default info will be used.
188
+ Generally, you only need to set this if you're developing
189
+ your own client library.
190
+ always_use_jwt_access (Optional[bool]): Whether self signed JWT should
191
+ be used for service account credentials.
192
+
193
+ Raises:
194
+ google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
195
+ creation failed for any reason.
196
+ google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
197
+ and ``credentials_file`` are passed.
198
+ """
199
+ self._grpc_channel = None
200
+ self._ssl_channel_credentials = ssl_channel_credentials
201
+ self._stubs: Dict[str, Callable] = {}
202
+
203
+ if api_mtls_endpoint:
204
+ warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning)
205
+ if client_cert_source:
206
+ warnings.warn("client_cert_source is deprecated", DeprecationWarning)
207
+
208
+ if isinstance(channel, grpc.Channel):
209
+ # Ignore credentials if a channel was passed.
210
+ credentials = None
211
+ self._ignore_credentials = True
212
+ # If a channel was explicitly provided, set it.
213
+ self._grpc_channel = channel
214
+ self._ssl_channel_credentials = None
215
+
216
+ else:
217
+ if api_mtls_endpoint:
218
+ host = api_mtls_endpoint
219
+
220
+ # Create SSL credentials with client_cert_source or application
221
+ # default SSL credentials.
222
+ if client_cert_source:
223
+ cert, key = client_cert_source()
224
+ self._ssl_channel_credentials = grpc.ssl_channel_credentials(
225
+ certificate_chain=cert, private_key=key
226
+ )
227
+ else:
228
+ self._ssl_channel_credentials = SslCredentials().ssl_credentials
229
+
230
+ else:
231
+ if client_cert_source_for_mtls and not ssl_channel_credentials:
232
+ cert, key = client_cert_source_for_mtls()
233
+ self._ssl_channel_credentials = grpc.ssl_channel_credentials(
234
+ certificate_chain=cert, private_key=key
235
+ )
236
+
237
+ # The base transport sets the host, credentials and scopes
238
+ super().__init__(
239
+ host=host,
240
+ credentials=credentials,
241
+ credentials_file=credentials_file,
242
+ scopes=scopes,
243
+ quota_project_id=quota_project_id,
244
+ client_info=client_info,
245
+ always_use_jwt_access=always_use_jwt_access,
246
+ api_audience=api_audience,
247
+ )
248
+
249
+ if not self._grpc_channel:
250
+ # initialize with the provided callable or the default channel
251
+ channel_init = channel or type(self).create_channel
252
+ self._grpc_channel = channel_init(
253
+ self._host,
254
+ # use the credentials which are saved
255
+ credentials=self._credentials,
256
+ # Set ``credentials_file`` to ``None`` here as
257
+ # the credentials that we saved earlier should be used.
258
+ credentials_file=None,
259
+ scopes=self._scopes,
260
+ ssl_credentials=self._ssl_channel_credentials,
261
+ quota_project_id=quota_project_id,
262
+ options=[
263
+ ("grpc.max_send_message_length", -1),
264
+ ("grpc.max_receive_message_length", -1),
265
+ ],
266
+ )
267
+
268
+ self._interceptor = _LoggingClientInterceptor()
269
+ self._logged_channel = grpc.intercept_channel(
270
+ self._grpc_channel, self._interceptor
271
+ )
272
+
273
+ # Wrap messages. This must be done after self._logged_channel exists
274
+ self._prep_wrapped_messages(client_info)
275
+
276
+ @classmethod
277
+ def create_channel(
278
+ cls,
279
+ host: str = "generativelanguage.googleapis.com",
280
+ credentials: Optional[ga_credentials.Credentials] = None,
281
+ credentials_file: Optional[str] = None,
282
+ scopes: Optional[Sequence[str]] = None,
283
+ quota_project_id: Optional[str] = None,
284
+ **kwargs,
285
+ ) -> grpc.Channel:
286
+ """Create and return a gRPC channel object.
287
+ Args:
288
+ host (Optional[str]): The host for the channel to use.
289
+ credentials (Optional[~.Credentials]): The
290
+ authorization credentials to attach to requests. These
291
+ credentials identify this application to the service. If
292
+ none are specified, the client will attempt to ascertain
293
+ the credentials from the environment.
294
+ credentials_file (Optional[str]): A file with credentials that can
295
+ be loaded with :func:`google.auth.load_credentials_from_file`.
296
+ This argument is mutually exclusive with credentials.
297
+ scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
298
+ service. These are only used when credentials are not specified and
299
+ are passed to :func:`google.auth.default`.
300
+ quota_project_id (Optional[str]): An optional project to use for billing
301
+ and quota.
302
+ kwargs (Optional[dict]): Keyword arguments, which are passed to the
303
+ channel creation.
304
+ Returns:
305
+ grpc.Channel: A gRPC channel object.
306
+
307
+ Raises:
308
+ google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
309
+ and ``credentials_file`` are passed.
310
+ """
311
+
312
+ return grpc_helpers.create_channel(
313
+ host,
314
+ credentials=credentials,
315
+ credentials_file=credentials_file,
316
+ quota_project_id=quota_project_id,
317
+ default_scopes=cls.AUTH_SCOPES,
318
+ scopes=scopes,
319
+ default_host=cls.DEFAULT_HOST,
320
+ **kwargs,
321
+ )
322
+
323
+ @property
324
+ def grpc_channel(self) -> grpc.Channel:
325
+ """Return the channel designed to connect to this service."""
326
+ return self._grpc_channel
327
+
328
+ @property
329
+ def create_permission(
330
+ self,
331
+ ) -> Callable[
332
+ [permission_service.CreatePermissionRequest], gag_permission.Permission
333
+ ]:
334
+ r"""Return a callable for the create permission method over gRPC.
335
+
336
+ Create a permission to a specific resource.
337
+
338
+ Returns:
339
+ Callable[[~.CreatePermissionRequest],
340
+ ~.Permission]:
341
+ A function that, when called, will call the underlying RPC
342
+ on the server.
343
+ """
344
+ # Generate a "stub function" on-the-fly which will actually make
345
+ # the request.
346
+ # gRPC handles serialization and deserialization, so we just need
347
+ # to pass in the functions for each.
348
+ if "create_permission" not in self._stubs:
349
+ self._stubs["create_permission"] = self._logged_channel.unary_unary(
350
+ "/google.ai.generativelanguage.v1alpha.PermissionService/CreatePermission",
351
+ request_serializer=permission_service.CreatePermissionRequest.serialize,
352
+ response_deserializer=gag_permission.Permission.deserialize,
353
+ )
354
+ return self._stubs["create_permission"]
355
+
356
+ @property
357
+ def get_permission(
358
+ self,
359
+ ) -> Callable[[permission_service.GetPermissionRequest], permission.Permission]:
360
+ r"""Return a callable for the get permission method over gRPC.
361
+
362
+ Gets information about a specific Permission.
363
+
364
+ Returns:
365
+ Callable[[~.GetPermissionRequest],
366
+ ~.Permission]:
367
+ A function that, when called, will call the underlying RPC
368
+ on the server.
369
+ """
370
+ # Generate a "stub function" on-the-fly which will actually make
371
+ # the request.
372
+ # gRPC handles serialization and deserialization, so we just need
373
+ # to pass in the functions for each.
374
+ if "get_permission" not in self._stubs:
375
+ self._stubs["get_permission"] = self._logged_channel.unary_unary(
376
+ "/google.ai.generativelanguage.v1alpha.PermissionService/GetPermission",
377
+ request_serializer=permission_service.GetPermissionRequest.serialize,
378
+ response_deserializer=permission.Permission.deserialize,
379
+ )
380
+ return self._stubs["get_permission"]
381
+
382
+ @property
383
+ def list_permissions(
384
+ self,
385
+ ) -> Callable[
386
+ [permission_service.ListPermissionsRequest],
387
+ permission_service.ListPermissionsResponse,
388
+ ]:
389
+ r"""Return a callable for the list permissions method over gRPC.
390
+
391
+ Lists permissions for the specific resource.
392
+
393
+ Returns:
394
+ Callable[[~.ListPermissionsRequest],
395
+ ~.ListPermissionsResponse]:
396
+ A function that, when called, will call the underlying RPC
397
+ on the server.
398
+ """
399
+ # Generate a "stub function" on-the-fly which will actually make
400
+ # the request.
401
+ # gRPC handles serialization and deserialization, so we just need
402
+ # to pass in the functions for each.
403
+ if "list_permissions" not in self._stubs:
404
+ self._stubs["list_permissions"] = self._logged_channel.unary_unary(
405
+ "/google.ai.generativelanguage.v1alpha.PermissionService/ListPermissions",
406
+ request_serializer=permission_service.ListPermissionsRequest.serialize,
407
+ response_deserializer=permission_service.ListPermissionsResponse.deserialize,
408
+ )
409
+ return self._stubs["list_permissions"]
410
+
411
+ @property
412
+ def update_permission(
413
+ self,
414
+ ) -> Callable[
415
+ [permission_service.UpdatePermissionRequest], gag_permission.Permission
416
+ ]:
417
+ r"""Return a callable for the update permission method over gRPC.
418
+
419
+ Updates the permission.
420
+
421
+ Returns:
422
+ Callable[[~.UpdatePermissionRequest],
423
+ ~.Permission]:
424
+ A function that, when called, will call the underlying RPC
425
+ on the server.
426
+ """
427
+ # Generate a "stub function" on-the-fly which will actually make
428
+ # the request.
429
+ # gRPC handles serialization and deserialization, so we just need
430
+ # to pass in the functions for each.
431
+ if "update_permission" not in self._stubs:
432
+ self._stubs["update_permission"] = self._logged_channel.unary_unary(
433
+ "/google.ai.generativelanguage.v1alpha.PermissionService/UpdatePermission",
434
+ request_serializer=permission_service.UpdatePermissionRequest.serialize,
435
+ response_deserializer=gag_permission.Permission.deserialize,
436
+ )
437
+ return self._stubs["update_permission"]
438
+
439
+ @property
440
+ def delete_permission(
441
+ self,
442
+ ) -> Callable[[permission_service.DeletePermissionRequest], empty_pb2.Empty]:
443
+ r"""Return a callable for the delete permission method over gRPC.
444
+
445
+ Deletes the permission.
446
+
447
+ Returns:
448
+ Callable[[~.DeletePermissionRequest],
449
+ ~.Empty]:
450
+ A function that, when called, will call the underlying RPC
451
+ on the server.
452
+ """
453
+ # Generate a "stub function" on-the-fly which will actually make
454
+ # the request.
455
+ # gRPC handles serialization and deserialization, so we just need
456
+ # to pass in the functions for each.
457
+ if "delete_permission" not in self._stubs:
458
+ self._stubs["delete_permission"] = self._logged_channel.unary_unary(
459
+ "/google.ai.generativelanguage.v1alpha.PermissionService/DeletePermission",
460
+ request_serializer=permission_service.DeletePermissionRequest.serialize,
461
+ response_deserializer=empty_pb2.Empty.FromString,
462
+ )
463
+ return self._stubs["delete_permission"]
464
+
465
+ @property
466
+ def transfer_ownership(
467
+ self,
468
+ ) -> Callable[
469
+ [permission_service.TransferOwnershipRequest],
470
+ permission_service.TransferOwnershipResponse,
471
+ ]:
472
+ r"""Return a callable for the transfer ownership method over gRPC.
473
+
474
+ Transfers ownership of the tuned model.
475
+ This is the only way to change ownership of the tuned
476
+ model. The current owner will be downgraded to writer
477
+ role.
478
+
479
+ Returns:
480
+ Callable[[~.TransferOwnershipRequest],
481
+ ~.TransferOwnershipResponse]:
482
+ A function that, when called, will call the underlying RPC
483
+ on the server.
484
+ """
485
+ # Generate a "stub function" on-the-fly which will actually make
486
+ # the request.
487
+ # gRPC handles serialization and deserialization, so we just need
488
+ # to pass in the functions for each.
489
+ if "transfer_ownership" not in self._stubs:
490
+ self._stubs["transfer_ownership"] = self._logged_channel.unary_unary(
491
+ "/google.ai.generativelanguage.v1alpha.PermissionService/TransferOwnership",
492
+ request_serializer=permission_service.TransferOwnershipRequest.serialize,
493
+ response_deserializer=permission_service.TransferOwnershipResponse.deserialize,
494
+ )
495
+ return self._stubs["transfer_ownership"]
496
+
497
+ def close(self):
498
+ self._logged_channel.close()
499
+
500
+ @property
501
+ def get_operation(
502
+ self,
503
+ ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]:
504
+ r"""Return a callable for the get_operation method over gRPC."""
505
+ # Generate a "stub function" on-the-fly which will actually make
506
+ # the request.
507
+ # gRPC handles serialization and deserialization, so we just need
508
+ # to pass in the functions for each.
509
+ if "get_operation" not in self._stubs:
510
+ self._stubs["get_operation"] = self._logged_channel.unary_unary(
511
+ "/google.longrunning.Operations/GetOperation",
512
+ request_serializer=operations_pb2.GetOperationRequest.SerializeToString,
513
+ response_deserializer=operations_pb2.Operation.FromString,
514
+ )
515
+ return self._stubs["get_operation"]
516
+
517
+ @property
518
+ def list_operations(
519
+ self,
520
+ ) -> Callable[
521
+ [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse
522
+ ]:
523
+ r"""Return a callable for the list_operations 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 "list_operations" not in self._stubs:
529
+ self._stubs["list_operations"] = self._logged_channel.unary_unary(
530
+ "/google.longrunning.Operations/ListOperations",
531
+ request_serializer=operations_pb2.ListOperationsRequest.SerializeToString,
532
+ response_deserializer=operations_pb2.ListOperationsResponse.FromString,
533
+ )
534
+ return self._stubs["list_operations"]
535
+
536
+ @property
537
+ def kind(self) -> str:
538
+ return "grpc"
539
+
540
+
541
+ __all__ = ("PermissionServiceGrpcTransport",)
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/permission_service/transports/grpc_asyncio.py ADDED
@@ -0,0 +1,604 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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_v1alpha.types import permission as gag_permission
37
+ from google.ai.generativelanguage_v1alpha.types import permission
38
+ from google.ai.generativelanguage_v1alpha.types import permission_service
39
+
40
+ from .base import DEFAULT_CLIENT_INFO, PermissionServiceTransport
41
+ from .grpc import PermissionServiceGrpcTransport
42
+
43
+ try:
44
+ from google.api_core import client_logging # type: ignore
45
+
46
+ CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER
47
+ except ImportError: # pragma: NO COVER
48
+ CLIENT_LOGGING_SUPPORTED = False
49
+
50
+ _LOGGER = std_logging.getLogger(__name__)
51
+
52
+
53
+ class _LoggingClientAIOInterceptor(
54
+ grpc.aio.UnaryUnaryClientInterceptor
55
+ ): # pragma: NO COVER
56
+ async def intercept_unary_unary(self, continuation, client_call_details, request):
57
+ logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
58
+ std_logging.DEBUG
59
+ )
60
+ if logging_enabled: # pragma: NO COVER
61
+ request_metadata = client_call_details.metadata
62
+ if isinstance(request, proto.Message):
63
+ request_payload = type(request).to_json(request)
64
+ elif isinstance(request, google.protobuf.message.Message):
65
+ request_payload = MessageToJson(request)
66
+ else:
67
+ request_payload = f"{type(request).__name__}: {pickle.dumps(request)}"
68
+
69
+ request_metadata = {
70
+ key: value.decode("utf-8") if isinstance(value, bytes) else value
71
+ for key, value in request_metadata
72
+ }
73
+ grpc_request = {
74
+ "payload": request_payload,
75
+ "requestMethod": "grpc",
76
+ "metadata": dict(request_metadata),
77
+ }
78
+ _LOGGER.debug(
79
+ f"Sending request for {client_call_details.method}",
80
+ extra={
81
+ "serviceName": "google.ai.generativelanguage.v1alpha.PermissionService",
82
+ "rpcName": str(client_call_details.method),
83
+ "request": grpc_request,
84
+ "metadata": grpc_request["metadata"],
85
+ },
86
+ )
87
+ response = await continuation(client_call_details, request)
88
+ if logging_enabled: # pragma: NO COVER
89
+ response_metadata = await response.trailing_metadata()
90
+ # Convert gRPC metadata `<class 'grpc.aio._metadata.Metadata'>` to list of tuples
91
+ metadata = (
92
+ dict([(k, str(v)) for k, v in response_metadata])
93
+ if response_metadata
94
+ else None
95
+ )
96
+ result = await response
97
+ if isinstance(result, proto.Message):
98
+ response_payload = type(result).to_json(result)
99
+ elif isinstance(result, google.protobuf.message.Message):
100
+ response_payload = MessageToJson(result)
101
+ else:
102
+ response_payload = f"{type(result).__name__}: {pickle.dumps(result)}"
103
+ grpc_response = {
104
+ "payload": response_payload,
105
+ "metadata": metadata,
106
+ "status": "OK",
107
+ }
108
+ _LOGGER.debug(
109
+ f"Received response to rpc {client_call_details.method}.",
110
+ extra={
111
+ "serviceName": "google.ai.generativelanguage.v1alpha.PermissionService",
112
+ "rpcName": str(client_call_details.method),
113
+ "response": grpc_response,
114
+ "metadata": grpc_response["metadata"],
115
+ },
116
+ )
117
+ return response
118
+
119
+
120
+ class PermissionServiceGrpcAsyncIOTransport(PermissionServiceTransport):
121
+ """gRPC AsyncIO backend transport for PermissionService.
122
+
123
+ Provides methods for managing permissions to PaLM API
124
+ resources.
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
+ _grpc_channel: aio.Channel
135
+ _stubs: Dict[str, Callable] = {}
136
+
137
+ @classmethod
138
+ def create_channel(
139
+ cls,
140
+ host: str = "generativelanguage.googleapis.com",
141
+ credentials: Optional[ga_credentials.Credentials] = None,
142
+ credentials_file: Optional[str] = None,
143
+ scopes: Optional[Sequence[str]] = None,
144
+ quota_project_id: Optional[str] = None,
145
+ **kwargs,
146
+ ) -> aio.Channel:
147
+ """Create and return a gRPC AsyncIO channel object.
148
+ Args:
149
+ host (Optional[str]): The host for the channel to use.
150
+ credentials (Optional[~.Credentials]): The
151
+ authorization credentials to attach to requests. These
152
+ credentials identify this application to the service. If
153
+ none are specified, the client will attempt to ascertain
154
+ the credentials from the environment.
155
+ credentials_file (Optional[str]): A file with credentials that can
156
+ be loaded with :func:`google.auth.load_credentials_from_file`.
157
+ scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
158
+ service. These are only used when credentials are not specified and
159
+ are passed to :func:`google.auth.default`.
160
+ quota_project_id (Optional[str]): An optional project to use for billing
161
+ and quota.
162
+ kwargs (Optional[dict]): Keyword arguments, which are passed to the
163
+ channel creation.
164
+ Returns:
165
+ aio.Channel: A gRPC AsyncIO channel object.
166
+ """
167
+
168
+ return grpc_helpers_async.create_channel(
169
+ host,
170
+ credentials=credentials,
171
+ credentials_file=credentials_file,
172
+ quota_project_id=quota_project_id,
173
+ default_scopes=cls.AUTH_SCOPES,
174
+ scopes=scopes,
175
+ default_host=cls.DEFAULT_HOST,
176
+ **kwargs,
177
+ )
178
+
179
+ def __init__(
180
+ self,
181
+ *,
182
+ host: str = "generativelanguage.googleapis.com",
183
+ credentials: Optional[ga_credentials.Credentials] = None,
184
+ credentials_file: Optional[str] = None,
185
+ scopes: Optional[Sequence[str]] = None,
186
+ channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None,
187
+ api_mtls_endpoint: Optional[str] = None,
188
+ client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None,
189
+ ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None,
190
+ client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None,
191
+ quota_project_id: Optional[str] = None,
192
+ client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
193
+ always_use_jwt_access: Optional[bool] = False,
194
+ api_audience: Optional[str] = None,
195
+ ) -> None:
196
+ """Instantiate the transport.
197
+
198
+ Args:
199
+ host (Optional[str]):
200
+ The hostname to connect to (default: 'generativelanguage.googleapis.com').
201
+ credentials (Optional[google.auth.credentials.Credentials]): The
202
+ authorization credentials to attach to requests. These
203
+ credentials identify the application to the service; if none
204
+ are specified, the client will attempt to ascertain the
205
+ credentials from the environment.
206
+ This argument is ignored if a ``channel`` instance is provided.
207
+ credentials_file (Optional[str]): A file with credentials that can
208
+ be loaded with :func:`google.auth.load_credentials_from_file`.
209
+ This argument is ignored if a ``channel`` instance is provided.
210
+ scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
211
+ service. These are only used when credentials are not specified and
212
+ are passed to :func:`google.auth.default`.
213
+ channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]):
214
+ A ``Channel`` instance through which to make calls, or a Callable
215
+ that constructs and returns one. If set to None, ``self.create_channel``
216
+ is used to create the channel. If a Callable is given, it will be called
217
+ with the same arguments as used in ``self.create_channel``.
218
+ api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint.
219
+ If provided, it overrides the ``host`` argument and tries to create
220
+ a mutual TLS channel with client SSL credentials from
221
+ ``client_cert_source`` or application default SSL credentials.
222
+ client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]):
223
+ Deprecated. A callback to provide client SSL certificate bytes and
224
+ private key bytes, both in PEM format. It is ignored if
225
+ ``api_mtls_endpoint`` is None.
226
+ ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials
227
+ for the grpc channel. It is ignored if a ``channel`` instance is provided.
228
+ client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]):
229
+ A callback to provide client certificate bytes and private key bytes,
230
+ both in PEM format. It is used to configure a mutual TLS channel. It is
231
+ ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided.
232
+ quota_project_id (Optional[str]): An optional project to use for billing
233
+ and quota.
234
+ client_info (google.api_core.gapic_v1.client_info.ClientInfo):
235
+ The client info used to send a user-agent string along with
236
+ API requests. If ``None``, then default info will be used.
237
+ Generally, you only need to set this if you're developing
238
+ your own client library.
239
+ always_use_jwt_access (Optional[bool]): Whether self signed JWT should
240
+ be used for service account credentials.
241
+
242
+ Raises:
243
+ google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
244
+ creation failed for any reason.
245
+ google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
246
+ and ``credentials_file`` are passed.
247
+ """
248
+ self._grpc_channel = None
249
+ self._ssl_channel_credentials = ssl_channel_credentials
250
+ self._stubs: Dict[str, Callable] = {}
251
+
252
+ if api_mtls_endpoint:
253
+ warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning)
254
+ if client_cert_source:
255
+ warnings.warn("client_cert_source is deprecated", DeprecationWarning)
256
+
257
+ if isinstance(channel, aio.Channel):
258
+ # Ignore credentials if a channel was passed.
259
+ credentials = None
260
+ self._ignore_credentials = True
261
+ # If a channel was explicitly provided, set it.
262
+ self._grpc_channel = channel
263
+ self._ssl_channel_credentials = None
264
+ else:
265
+ if api_mtls_endpoint:
266
+ host = api_mtls_endpoint
267
+
268
+ # Create SSL credentials with client_cert_source or application
269
+ # default SSL credentials.
270
+ if client_cert_source:
271
+ cert, key = client_cert_source()
272
+ self._ssl_channel_credentials = grpc.ssl_channel_credentials(
273
+ certificate_chain=cert, private_key=key
274
+ )
275
+ else:
276
+ self._ssl_channel_credentials = SslCredentials().ssl_credentials
277
+
278
+ else:
279
+ if client_cert_source_for_mtls and not ssl_channel_credentials:
280
+ cert, key = client_cert_source_for_mtls()
281
+ self._ssl_channel_credentials = grpc.ssl_channel_credentials(
282
+ certificate_chain=cert, private_key=key
283
+ )
284
+
285
+ # The base transport sets the host, credentials and scopes
286
+ super().__init__(
287
+ host=host,
288
+ credentials=credentials,
289
+ credentials_file=credentials_file,
290
+ scopes=scopes,
291
+ quota_project_id=quota_project_id,
292
+ client_info=client_info,
293
+ always_use_jwt_access=always_use_jwt_access,
294
+ api_audience=api_audience,
295
+ )
296
+
297
+ if not self._grpc_channel:
298
+ # initialize with the provided callable or the default channel
299
+ channel_init = channel or type(self).create_channel
300
+ self._grpc_channel = channel_init(
301
+ self._host,
302
+ # use the credentials which are saved
303
+ credentials=self._credentials,
304
+ # Set ``credentials_file`` to ``None`` here as
305
+ # the credentials that we saved earlier should be used.
306
+ credentials_file=None,
307
+ scopes=self._scopes,
308
+ ssl_credentials=self._ssl_channel_credentials,
309
+ quota_project_id=quota_project_id,
310
+ options=[
311
+ ("grpc.max_send_message_length", -1),
312
+ ("grpc.max_receive_message_length", -1),
313
+ ],
314
+ )
315
+
316
+ self._interceptor = _LoggingClientAIOInterceptor()
317
+ self._grpc_channel._unary_unary_interceptors.append(self._interceptor)
318
+ self._logged_channel = self._grpc_channel
319
+ self._wrap_with_kind = (
320
+ "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters
321
+ )
322
+ # Wrap messages. This must be done after self._logged_channel exists
323
+ self._prep_wrapped_messages(client_info)
324
+
325
+ @property
326
+ def grpc_channel(self) -> aio.Channel:
327
+ """Create the channel designed to connect to this service.
328
+
329
+ This property caches on the instance; repeated calls return
330
+ the same channel.
331
+ """
332
+ # Return the channel from cache.
333
+ return self._grpc_channel
334
+
335
+ @property
336
+ def create_permission(
337
+ self,
338
+ ) -> Callable[
339
+ [permission_service.CreatePermissionRequest],
340
+ Awaitable[gag_permission.Permission],
341
+ ]:
342
+ r"""Return a callable for the create permission method over gRPC.
343
+
344
+ Create a permission to a specific resource.
345
+
346
+ Returns:
347
+ Callable[[~.CreatePermissionRequest],
348
+ Awaitable[~.Permission]]:
349
+ A function that, when called, will call the underlying RPC
350
+ on the server.
351
+ """
352
+ # Generate a "stub function" on-the-fly which will actually make
353
+ # the request.
354
+ # gRPC handles serialization and deserialization, so we just need
355
+ # to pass in the functions for each.
356
+ if "create_permission" not in self._stubs:
357
+ self._stubs["create_permission"] = self._logged_channel.unary_unary(
358
+ "/google.ai.generativelanguage.v1alpha.PermissionService/CreatePermission",
359
+ request_serializer=permission_service.CreatePermissionRequest.serialize,
360
+ response_deserializer=gag_permission.Permission.deserialize,
361
+ )
362
+ return self._stubs["create_permission"]
363
+
364
+ @property
365
+ def get_permission(
366
+ self,
367
+ ) -> Callable[
368
+ [permission_service.GetPermissionRequest], Awaitable[permission.Permission]
369
+ ]:
370
+ r"""Return a callable for the get permission method over gRPC.
371
+
372
+ Gets information about a specific Permission.
373
+
374
+ Returns:
375
+ Callable[[~.GetPermissionRequest],
376
+ Awaitable[~.Permission]]:
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 "get_permission" not in self._stubs:
385
+ self._stubs["get_permission"] = self._logged_channel.unary_unary(
386
+ "/google.ai.generativelanguage.v1alpha.PermissionService/GetPermission",
387
+ request_serializer=permission_service.GetPermissionRequest.serialize,
388
+ response_deserializer=permission.Permission.deserialize,
389
+ )
390
+ return self._stubs["get_permission"]
391
+
392
+ @property
393
+ def list_permissions(
394
+ self,
395
+ ) -> Callable[
396
+ [permission_service.ListPermissionsRequest],
397
+ Awaitable[permission_service.ListPermissionsResponse],
398
+ ]:
399
+ r"""Return a callable for the list permissions method over gRPC.
400
+
401
+ Lists permissions for the specific resource.
402
+
403
+ Returns:
404
+ Callable[[~.ListPermissionsRequest],
405
+ Awaitable[~.ListPermissionsResponse]]:
406
+ A function that, when called, will call the underlying RPC
407
+ on the server.
408
+ """
409
+ # Generate a "stub function" on-the-fly which will actually make
410
+ # the request.
411
+ # gRPC handles serialization and deserialization, so we just need
412
+ # to pass in the functions for each.
413
+ if "list_permissions" not in self._stubs:
414
+ self._stubs["list_permissions"] = self._logged_channel.unary_unary(
415
+ "/google.ai.generativelanguage.v1alpha.PermissionService/ListPermissions",
416
+ request_serializer=permission_service.ListPermissionsRequest.serialize,
417
+ response_deserializer=permission_service.ListPermissionsResponse.deserialize,
418
+ )
419
+ return self._stubs["list_permissions"]
420
+
421
+ @property
422
+ def update_permission(
423
+ self,
424
+ ) -> Callable[
425
+ [permission_service.UpdatePermissionRequest],
426
+ Awaitable[gag_permission.Permission],
427
+ ]:
428
+ r"""Return a callable for the update permission method over gRPC.
429
+
430
+ Updates the permission.
431
+
432
+ Returns:
433
+ Callable[[~.UpdatePermissionRequest],
434
+ Awaitable[~.Permission]]:
435
+ A function that, when called, will call the underlying RPC
436
+ on the server.
437
+ """
438
+ # Generate a "stub function" on-the-fly which will actually make
439
+ # the request.
440
+ # gRPC handles serialization and deserialization, so we just need
441
+ # to pass in the functions for each.
442
+ if "update_permission" not in self._stubs:
443
+ self._stubs["update_permission"] = self._logged_channel.unary_unary(
444
+ "/google.ai.generativelanguage.v1alpha.PermissionService/UpdatePermission",
445
+ request_serializer=permission_service.UpdatePermissionRequest.serialize,
446
+ response_deserializer=gag_permission.Permission.deserialize,
447
+ )
448
+ return self._stubs["update_permission"]
449
+
450
+ @property
451
+ def delete_permission(
452
+ self,
453
+ ) -> Callable[
454
+ [permission_service.DeletePermissionRequest], Awaitable[empty_pb2.Empty]
455
+ ]:
456
+ r"""Return a callable for the delete permission method over gRPC.
457
+
458
+ Deletes the permission.
459
+
460
+ Returns:
461
+ Callable[[~.DeletePermissionRequest],
462
+ Awaitable[~.Empty]]:
463
+ A function that, when called, will call the underlying RPC
464
+ on the server.
465
+ """
466
+ # Generate a "stub function" on-the-fly which will actually make
467
+ # the request.
468
+ # gRPC handles serialization and deserialization, so we just need
469
+ # to pass in the functions for each.
470
+ if "delete_permission" not in self._stubs:
471
+ self._stubs["delete_permission"] = self._logged_channel.unary_unary(
472
+ "/google.ai.generativelanguage.v1alpha.PermissionService/DeletePermission",
473
+ request_serializer=permission_service.DeletePermissionRequest.serialize,
474
+ response_deserializer=empty_pb2.Empty.FromString,
475
+ )
476
+ return self._stubs["delete_permission"]
477
+
478
+ @property
479
+ def transfer_ownership(
480
+ self,
481
+ ) -> Callable[
482
+ [permission_service.TransferOwnershipRequest],
483
+ Awaitable[permission_service.TransferOwnershipResponse],
484
+ ]:
485
+ r"""Return a callable for the transfer ownership method over gRPC.
486
+
487
+ Transfers ownership of the tuned model.
488
+ This is the only way to change ownership of the tuned
489
+ model. The current owner will be downgraded to writer
490
+ role.
491
+
492
+ Returns:
493
+ Callable[[~.TransferOwnershipRequest],
494
+ Awaitable[~.TransferOwnershipResponse]]:
495
+ A function that, when called, will call the underlying RPC
496
+ on the server.
497
+ """
498
+ # Generate a "stub function" on-the-fly which will actually make
499
+ # the request.
500
+ # gRPC handles serialization and deserialization, so we just need
501
+ # to pass in the functions for each.
502
+ if "transfer_ownership" not in self._stubs:
503
+ self._stubs["transfer_ownership"] = self._logged_channel.unary_unary(
504
+ "/google.ai.generativelanguage.v1alpha.PermissionService/TransferOwnership",
505
+ request_serializer=permission_service.TransferOwnershipRequest.serialize,
506
+ response_deserializer=permission_service.TransferOwnershipResponse.deserialize,
507
+ )
508
+ return self._stubs["transfer_ownership"]
509
+
510
+ def _prep_wrapped_messages(self, client_info):
511
+ """Precompute the wrapped methods, overriding the base class method to use async wrappers."""
512
+ self._wrapped_methods = {
513
+ self.create_permission: self._wrap_method(
514
+ self.create_permission,
515
+ default_timeout=None,
516
+ client_info=client_info,
517
+ ),
518
+ self.get_permission: self._wrap_method(
519
+ self.get_permission,
520
+ default_timeout=None,
521
+ client_info=client_info,
522
+ ),
523
+ self.list_permissions: self._wrap_method(
524
+ self.list_permissions,
525
+ default_timeout=None,
526
+ client_info=client_info,
527
+ ),
528
+ self.update_permission: self._wrap_method(
529
+ self.update_permission,
530
+ default_timeout=None,
531
+ client_info=client_info,
532
+ ),
533
+ self.delete_permission: self._wrap_method(
534
+ self.delete_permission,
535
+ default_timeout=None,
536
+ client_info=client_info,
537
+ ),
538
+ self.transfer_ownership: self._wrap_method(
539
+ self.transfer_ownership,
540
+ default_timeout=None,
541
+ client_info=client_info,
542
+ ),
543
+ self.get_operation: self._wrap_method(
544
+ self.get_operation,
545
+ default_timeout=None,
546
+ client_info=client_info,
547
+ ),
548
+ self.list_operations: self._wrap_method(
549
+ self.list_operations,
550
+ default_timeout=None,
551
+ client_info=client_info,
552
+ ),
553
+ }
554
+
555
+ def _wrap_method(self, func, *args, **kwargs):
556
+ if self._wrap_with_kind: # pragma: NO COVER
557
+ kwargs["kind"] = self.kind
558
+ return gapic_v1.method_async.wrap_method(func, *args, **kwargs)
559
+
560
+ def close(self):
561
+ return self._logged_channel.close()
562
+
563
+ @property
564
+ def kind(self) -> str:
565
+ return "grpc_asyncio"
566
+
567
+ @property
568
+ def get_operation(
569
+ self,
570
+ ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]:
571
+ r"""Return a callable for the get_operation method over gRPC."""
572
+ # Generate a "stub function" on-the-fly which will actually make
573
+ # the request.
574
+ # gRPC handles serialization and deserialization, so we just need
575
+ # to pass in the functions for each.
576
+ if "get_operation" not in self._stubs:
577
+ self._stubs["get_operation"] = self._logged_channel.unary_unary(
578
+ "/google.longrunning.Operations/GetOperation",
579
+ request_serializer=operations_pb2.GetOperationRequest.SerializeToString,
580
+ response_deserializer=operations_pb2.Operation.FromString,
581
+ )
582
+ return self._stubs["get_operation"]
583
+
584
+ @property
585
+ def list_operations(
586
+ self,
587
+ ) -> Callable[
588
+ [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse
589
+ ]:
590
+ r"""Return a callable for the list_operations method over gRPC."""
591
+ # Generate a "stub function" on-the-fly which will actually make
592
+ # the request.
593
+ # gRPC handles serialization and deserialization, so we just need
594
+ # to pass in the functions for each.
595
+ if "list_operations" not in self._stubs:
596
+ self._stubs["list_operations"] = self._logged_channel.unary_unary(
597
+ "/google.longrunning.Operations/ListOperations",
598
+ request_serializer=operations_pb2.ListOperationsRequest.SerializeToString,
599
+ response_deserializer=operations_pb2.ListOperationsResponse.FromString,
600
+ )
601
+ return self._stubs["list_operations"]
602
+
603
+
604
+ __all__ = ("PermissionServiceGrpcAsyncIOTransport",)
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/permission_service/transports/rest.py ADDED
@@ -0,0 +1,1671 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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_v1alpha.types import permission as gag_permission
33
+ from google.ai.generativelanguage_v1alpha.types import permission
34
+ from google.ai.generativelanguage_v1alpha.types import permission_service
35
+
36
+ from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO
37
+ from .rest_base import _BasePermissionServiceRestTransport
38
+
39
+ try:
40
+ OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None]
41
+ except AttributeError: # pragma: NO COVER
42
+ OptionalRetry = Union[retries.Retry, object, None] # type: ignore
43
+
44
+ try:
45
+ from google.api_core import client_logging # type: ignore
46
+
47
+ CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER
48
+ except ImportError: # pragma: NO COVER
49
+ CLIENT_LOGGING_SUPPORTED = False
50
+
51
+ _LOGGER = logging.getLogger(__name__)
52
+
53
+ DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
54
+ gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
55
+ grpc_version=None,
56
+ rest_version=f"requests@{requests_version}",
57
+ )
58
+
59
+
60
+ class PermissionServiceRestInterceptor:
61
+ """Interceptor for PermissionService.
62
+
63
+ Interceptors are used to manipulate requests, request metadata, and responses
64
+ in arbitrary ways.
65
+ Example use cases include:
66
+ * Logging
67
+ * Verifying requests according to service or custom semantics
68
+ * Stripping extraneous information from responses
69
+
70
+ These use cases and more can be enabled by injecting an
71
+ instance of a custom subclass when constructing the PermissionServiceRestTransport.
72
+
73
+ .. code-block:: python
74
+ class MyCustomPermissionServiceInterceptor(PermissionServiceRestInterceptor):
75
+ def pre_create_permission(self, request, metadata):
76
+ logging.log(f"Received request: {request}")
77
+ return request, metadata
78
+
79
+ def post_create_permission(self, response):
80
+ logging.log(f"Received response: {response}")
81
+ return response
82
+
83
+ def pre_delete_permission(self, request, metadata):
84
+ logging.log(f"Received request: {request}")
85
+ return request, metadata
86
+
87
+ def pre_get_permission(self, request, metadata):
88
+ logging.log(f"Received request: {request}")
89
+ return request, metadata
90
+
91
+ def post_get_permission(self, response):
92
+ logging.log(f"Received response: {response}")
93
+ return response
94
+
95
+ def pre_list_permissions(self, request, metadata):
96
+ logging.log(f"Received request: {request}")
97
+ return request, metadata
98
+
99
+ def post_list_permissions(self, response):
100
+ logging.log(f"Received response: {response}")
101
+ return response
102
+
103
+ def pre_transfer_ownership(self, request, metadata):
104
+ logging.log(f"Received request: {request}")
105
+ return request, metadata
106
+
107
+ def post_transfer_ownership(self, response):
108
+ logging.log(f"Received response: {response}")
109
+ return response
110
+
111
+ def pre_update_permission(self, request, metadata):
112
+ logging.log(f"Received request: {request}")
113
+ return request, metadata
114
+
115
+ def post_update_permission(self, response):
116
+ logging.log(f"Received response: {response}")
117
+ return response
118
+
119
+ transport = PermissionServiceRestTransport(interceptor=MyCustomPermissionServiceInterceptor())
120
+ client = PermissionServiceClient(transport=transport)
121
+
122
+
123
+ """
124
+
125
+ def pre_create_permission(
126
+ self,
127
+ request: permission_service.CreatePermissionRequest,
128
+ metadata: Sequence[Tuple[str, Union[str, bytes]]],
129
+ ) -> Tuple[
130
+ permission_service.CreatePermissionRequest,
131
+ Sequence[Tuple[str, Union[str, bytes]]],
132
+ ]:
133
+ """Pre-rpc interceptor for create_permission
134
+
135
+ Override in a subclass to manipulate the request or metadata
136
+ before they are sent to the PermissionService server.
137
+ """
138
+ return request, metadata
139
+
140
+ def post_create_permission(
141
+ self, response: gag_permission.Permission
142
+ ) -> gag_permission.Permission:
143
+ """Post-rpc interceptor for create_permission
144
+
145
+ Override in a subclass to manipulate the response
146
+ after it is returned by the PermissionService server but before
147
+ it is returned to user code.
148
+ """
149
+ return response
150
+
151
+ def pre_delete_permission(
152
+ self,
153
+ request: permission_service.DeletePermissionRequest,
154
+ metadata: Sequence[Tuple[str, Union[str, bytes]]],
155
+ ) -> Tuple[
156
+ permission_service.DeletePermissionRequest,
157
+ Sequence[Tuple[str, Union[str, bytes]]],
158
+ ]:
159
+ """Pre-rpc interceptor for delete_permission
160
+
161
+ Override in a subclass to manipulate the request or metadata
162
+ before they are sent to the PermissionService server.
163
+ """
164
+ return request, metadata
165
+
166
+ def pre_get_permission(
167
+ self,
168
+ request: permission_service.GetPermissionRequest,
169
+ metadata: Sequence[Tuple[str, Union[str, bytes]]],
170
+ ) -> Tuple[
171
+ permission_service.GetPermissionRequest, Sequence[Tuple[str, Union[str, bytes]]]
172
+ ]:
173
+ """Pre-rpc interceptor for get_permission
174
+
175
+ Override in a subclass to manipulate the request or metadata
176
+ before they are sent to the PermissionService server.
177
+ """
178
+ return request, metadata
179
+
180
+ def post_get_permission(
181
+ self, response: permission.Permission
182
+ ) -> permission.Permission:
183
+ """Post-rpc interceptor for get_permission
184
+
185
+ Override in a subclass to manipulate the response
186
+ after it is returned by the PermissionService server but before
187
+ it is returned to user code.
188
+ """
189
+ return response
190
+
191
+ def pre_list_permissions(
192
+ self,
193
+ request: permission_service.ListPermissionsRequest,
194
+ metadata: Sequence[Tuple[str, Union[str, bytes]]],
195
+ ) -> Tuple[
196
+ permission_service.ListPermissionsRequest,
197
+ Sequence[Tuple[str, Union[str, bytes]]],
198
+ ]:
199
+ """Pre-rpc interceptor for list_permissions
200
+
201
+ Override in a subclass to manipulate the request or metadata
202
+ before they are sent to the PermissionService server.
203
+ """
204
+ return request, metadata
205
+
206
+ def post_list_permissions(
207
+ self, response: permission_service.ListPermissionsResponse
208
+ ) -> permission_service.ListPermissionsResponse:
209
+ """Post-rpc interceptor for list_permissions
210
+
211
+ Override in a subclass to manipulate the response
212
+ after it is returned by the PermissionService server but before
213
+ it is returned to user code.
214
+ """
215
+ return response
216
+
217
+ def pre_transfer_ownership(
218
+ self,
219
+ request: permission_service.TransferOwnershipRequest,
220
+ metadata: Sequence[Tuple[str, Union[str, bytes]]],
221
+ ) -> Tuple[
222
+ permission_service.TransferOwnershipRequest,
223
+ Sequence[Tuple[str, Union[str, bytes]]],
224
+ ]:
225
+ """Pre-rpc interceptor for transfer_ownership
226
+
227
+ Override in a subclass to manipulate the request or metadata
228
+ before they are sent to the PermissionService server.
229
+ """
230
+ return request, metadata
231
+
232
+ def post_transfer_ownership(
233
+ self, response: permission_service.TransferOwnershipResponse
234
+ ) -> permission_service.TransferOwnershipResponse:
235
+ """Post-rpc interceptor for transfer_ownership
236
+
237
+ Override in a subclass to manipulate the response
238
+ after it is returned by the PermissionService server but before
239
+ it is returned to user code.
240
+ """
241
+ return response
242
+
243
+ def pre_update_permission(
244
+ self,
245
+ request: permission_service.UpdatePermissionRequest,
246
+ metadata: Sequence[Tuple[str, Union[str, bytes]]],
247
+ ) -> Tuple[
248
+ permission_service.UpdatePermissionRequest,
249
+ Sequence[Tuple[str, Union[str, bytes]]],
250
+ ]:
251
+ """Pre-rpc interceptor for update_permission
252
+
253
+ Override in a subclass to manipulate the request or metadata
254
+ before they are sent to the PermissionService server.
255
+ """
256
+ return request, metadata
257
+
258
+ def post_update_permission(
259
+ self, response: gag_permission.Permission
260
+ ) -> gag_permission.Permission:
261
+ """Post-rpc interceptor for update_permission
262
+
263
+ Override in a subclass to manipulate the response
264
+ after it is returned by the PermissionService server but before
265
+ it is returned to user code.
266
+ """
267
+ return response
268
+
269
+ def pre_get_operation(
270
+ self,
271
+ request: operations_pb2.GetOperationRequest,
272
+ metadata: Sequence[Tuple[str, Union[str, bytes]]],
273
+ ) -> Tuple[
274
+ operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]
275
+ ]:
276
+ """Pre-rpc interceptor for get_operation
277
+
278
+ Override in a subclass to manipulate the request or metadata
279
+ before they are sent to the PermissionService server.
280
+ """
281
+ return request, metadata
282
+
283
+ def post_get_operation(
284
+ self, response: operations_pb2.Operation
285
+ ) -> operations_pb2.Operation:
286
+ """Post-rpc interceptor for get_operation
287
+
288
+ Override in a subclass to manipulate the response
289
+ after it is returned by the PermissionService server but before
290
+ it is returned to user code.
291
+ """
292
+ return response
293
+
294
+ def pre_list_operations(
295
+ self,
296
+ request: operations_pb2.ListOperationsRequest,
297
+ metadata: Sequence[Tuple[str, Union[str, bytes]]],
298
+ ) -> Tuple[
299
+ operations_pb2.ListOperationsRequest, Sequence[Tuple[str, Union[str, bytes]]]
300
+ ]:
301
+ """Pre-rpc interceptor for list_operations
302
+
303
+ Override in a subclass to manipulate the request or metadata
304
+ before they are sent to the PermissionService server.
305
+ """
306
+ return request, metadata
307
+
308
+ def post_list_operations(
309
+ self, response: operations_pb2.ListOperationsResponse
310
+ ) -> operations_pb2.ListOperationsResponse:
311
+ """Post-rpc interceptor for list_operations
312
+
313
+ Override in a subclass to manipulate the response
314
+ after it is returned by the PermissionService server but before
315
+ it is returned to user code.
316
+ """
317
+ return response
318
+
319
+
320
+ @dataclasses.dataclass
321
+ class PermissionServiceRestStub:
322
+ _session: AuthorizedSession
323
+ _host: str
324
+ _interceptor: PermissionServiceRestInterceptor
325
+
326
+
327
+ class PermissionServiceRestTransport(_BasePermissionServiceRestTransport):
328
+ """REST backend synchronous transport for PermissionService.
329
+
330
+ Provides methods for managing permissions to PaLM API
331
+ resources.
332
+
333
+ This class defines the same methods as the primary client, so the
334
+ primary client can load the underlying transport implementation
335
+ and call it.
336
+
337
+ It sends JSON representations of protocol buffers over HTTP/1.1
338
+ """
339
+
340
+ def __init__(
341
+ self,
342
+ *,
343
+ host: str = "generativelanguage.googleapis.com",
344
+ credentials: Optional[ga_credentials.Credentials] = None,
345
+ credentials_file: Optional[str] = None,
346
+ scopes: Optional[Sequence[str]] = None,
347
+ client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None,
348
+ quota_project_id: Optional[str] = None,
349
+ client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
350
+ always_use_jwt_access: Optional[bool] = False,
351
+ url_scheme: str = "https",
352
+ interceptor: Optional[PermissionServiceRestInterceptor] = None,
353
+ api_audience: Optional[str] = None,
354
+ ) -> None:
355
+ """Instantiate the transport.
356
+
357
+ Args:
358
+ host (Optional[str]):
359
+ The hostname to connect to (default: 'generativelanguage.googleapis.com').
360
+ credentials (Optional[google.auth.credentials.Credentials]): The
361
+ authorization credentials to attach to requests. These
362
+ credentials identify the application to the service; if none
363
+ are specified, the client will attempt to ascertain the
364
+ credentials from the environment.
365
+
366
+ credentials_file (Optional[str]): A file with credentials that can
367
+ be loaded with :func:`google.auth.load_credentials_from_file`.
368
+ This argument is ignored if ``channel`` is provided.
369
+ scopes (Optional(Sequence[str])): A list of scopes. This argument is
370
+ ignored if ``channel`` is provided.
371
+ client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client
372
+ certificate to configure mutual TLS HTTP channel. It is ignored
373
+ if ``channel`` is provided.
374
+ quota_project_id (Optional[str]): An optional project to use for billing
375
+ and quota.
376
+ client_info (google.api_core.gapic_v1.client_info.ClientInfo):
377
+ The client info used to send a user-agent string along with
378
+ API requests. If ``None``, then default info will be used.
379
+ Generally, you only need to set this if you are developing
380
+ your own client library.
381
+ always_use_jwt_access (Optional[bool]): Whether self signed JWT should
382
+ be used for service account credentials.
383
+ url_scheme: the protocol scheme for the API endpoint. Normally
384
+ "https", but for testing or local servers,
385
+ "http" can be specified.
386
+ """
387
+ # Run the base constructor
388
+ # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc.
389
+ # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the
390
+ # credentials object
391
+ super().__init__(
392
+ host=host,
393
+ credentials=credentials,
394
+ client_info=client_info,
395
+ always_use_jwt_access=always_use_jwt_access,
396
+ url_scheme=url_scheme,
397
+ api_audience=api_audience,
398
+ )
399
+ self._session = AuthorizedSession(
400
+ self._credentials, default_host=self.DEFAULT_HOST
401
+ )
402
+ if client_cert_source_for_mtls:
403
+ self._session.configure_mtls_channel(client_cert_source_for_mtls)
404
+ self._interceptor = interceptor or PermissionServiceRestInterceptor()
405
+ self._prep_wrapped_messages(client_info)
406
+
407
+ class _CreatePermission(
408
+ _BasePermissionServiceRestTransport._BaseCreatePermission,
409
+ PermissionServiceRestStub,
410
+ ):
411
+ def __hash__(self):
412
+ return hash("PermissionServiceRestTransport.CreatePermission")
413
+
414
+ @staticmethod
415
+ def _get_response(
416
+ host,
417
+ metadata,
418
+ query_params,
419
+ session,
420
+ timeout,
421
+ transcoded_request,
422
+ body=None,
423
+ ):
424
+ uri = transcoded_request["uri"]
425
+ method = transcoded_request["method"]
426
+ headers = dict(metadata)
427
+ headers["Content-Type"] = "application/json"
428
+ response = getattr(session, method)(
429
+ "{host}{uri}".format(host=host, uri=uri),
430
+ timeout=timeout,
431
+ headers=headers,
432
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
433
+ data=body,
434
+ )
435
+ return response
436
+
437
+ def __call__(
438
+ self,
439
+ request: permission_service.CreatePermissionRequest,
440
+ *,
441
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
442
+ timeout: Optional[float] = None,
443
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
444
+ ) -> gag_permission.Permission:
445
+ r"""Call the create permission method over HTTP.
446
+
447
+ Args:
448
+ request (~.permission_service.CreatePermissionRequest):
449
+ The request object. Request to create a ``Permission``.
450
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
451
+ should be retried.
452
+ timeout (float): The timeout for this request.
453
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
454
+ sent along with the request as metadata. Normally, each value must be of type `str`,
455
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
456
+ be of type `bytes`.
457
+
458
+ Returns:
459
+ ~.gag_permission.Permission:
460
+ Permission resource grants user,
461
+ group or the rest of the world access to
462
+ the PaLM API resource (e.g. a tuned
463
+ model, corpus).
464
+
465
+ A role is a collection of permitted
466
+ operations that allows users to perform
467
+ specific actions on PaLM API resources.
468
+ To make them available to users, groups,
469
+ or service accounts, you assign roles.
470
+ When you assign a role, you grant
471
+ permissions that the role contains.
472
+
473
+ There are three concentric roles. Each
474
+ role is a superset of the previous
475
+ role's permitted operations:
476
+
477
+ - reader can use the resource (e.g.
478
+ tuned model, corpus) for inference
479
+ - writer has reader's permissions and
480
+ additionally can edit and share
481
+ - owner has writer's permissions and
482
+ additionally can delete
483
+
484
+ """
485
+
486
+ http_options = (
487
+ _BasePermissionServiceRestTransport._BaseCreatePermission._get_http_options()
488
+ )
489
+
490
+ request, metadata = self._interceptor.pre_create_permission(
491
+ request, metadata
492
+ )
493
+ transcoded_request = _BasePermissionServiceRestTransport._BaseCreatePermission._get_transcoded_request(
494
+ http_options, request
495
+ )
496
+
497
+ body = _BasePermissionServiceRestTransport._BaseCreatePermission._get_request_body_json(
498
+ transcoded_request
499
+ )
500
+
501
+ # Jsonify the query params
502
+ query_params = _BasePermissionServiceRestTransport._BaseCreatePermission._get_query_params_json(
503
+ transcoded_request
504
+ )
505
+
506
+ if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
507
+ logging.DEBUG
508
+ ): # pragma: NO COVER
509
+ request_url = "{host}{uri}".format(
510
+ host=self._host, uri=transcoded_request["uri"]
511
+ )
512
+ method = transcoded_request["method"]
513
+ try:
514
+ request_payload = type(request).to_json(request)
515
+ except:
516
+ request_payload = None
517
+ http_request = {
518
+ "payload": request_payload,
519
+ "requestMethod": method,
520
+ "requestUrl": request_url,
521
+ "headers": dict(metadata),
522
+ }
523
+ _LOGGER.debug(
524
+ f"Sending request for google.ai.generativelanguage_v1alpha.PermissionServiceClient.CreatePermission",
525
+ extra={
526
+ "serviceName": "google.ai.generativelanguage.v1alpha.PermissionService",
527
+ "rpcName": "CreatePermission",
528
+ "httpRequest": http_request,
529
+ "metadata": http_request["headers"],
530
+ },
531
+ )
532
+
533
+ # Send the request
534
+ response = PermissionServiceRestTransport._CreatePermission._get_response(
535
+ self._host,
536
+ metadata,
537
+ query_params,
538
+ self._session,
539
+ timeout,
540
+ transcoded_request,
541
+ body,
542
+ )
543
+
544
+ # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
545
+ # subclass.
546
+ if response.status_code >= 400:
547
+ raise core_exceptions.from_http_response(response)
548
+
549
+ # Return the response
550
+ resp = gag_permission.Permission()
551
+ pb_resp = gag_permission.Permission.pb(resp)
552
+
553
+ json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
554
+
555
+ resp = self._interceptor.post_create_permission(resp)
556
+ if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
557
+ logging.DEBUG
558
+ ): # pragma: NO COVER
559
+ try:
560
+ response_payload = gag_permission.Permission.to_json(response)
561
+ except:
562
+ response_payload = None
563
+ http_response = {
564
+ "payload": response_payload,
565
+ "headers": dict(response.headers),
566
+ "status": response.status_code,
567
+ }
568
+ _LOGGER.debug(
569
+ "Received response for google.ai.generativelanguage_v1alpha.PermissionServiceClient.create_permission",
570
+ extra={
571
+ "serviceName": "google.ai.generativelanguage.v1alpha.PermissionService",
572
+ "rpcName": "CreatePermission",
573
+ "metadata": http_response["headers"],
574
+ "httpResponse": http_response,
575
+ },
576
+ )
577
+ return resp
578
+
579
+ class _DeletePermission(
580
+ _BasePermissionServiceRestTransport._BaseDeletePermission,
581
+ PermissionServiceRestStub,
582
+ ):
583
+ def __hash__(self):
584
+ return hash("PermissionServiceRestTransport.DeletePermission")
585
+
586
+ @staticmethod
587
+ def _get_response(
588
+ host,
589
+ metadata,
590
+ query_params,
591
+ session,
592
+ timeout,
593
+ transcoded_request,
594
+ body=None,
595
+ ):
596
+ uri = transcoded_request["uri"]
597
+ method = transcoded_request["method"]
598
+ headers = dict(metadata)
599
+ headers["Content-Type"] = "application/json"
600
+ response = getattr(session, method)(
601
+ "{host}{uri}".format(host=host, uri=uri),
602
+ timeout=timeout,
603
+ headers=headers,
604
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
605
+ )
606
+ return response
607
+
608
+ def __call__(
609
+ self,
610
+ request: permission_service.DeletePermissionRequest,
611
+ *,
612
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
613
+ timeout: Optional[float] = None,
614
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
615
+ ):
616
+ r"""Call the delete permission method over HTTP.
617
+
618
+ Args:
619
+ request (~.permission_service.DeletePermissionRequest):
620
+ The request object. Request to delete the ``Permission``.
621
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
622
+ should be retried.
623
+ timeout (float): The timeout for this request.
624
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
625
+ sent along with the request as metadata. Normally, each value must be of type `str`,
626
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
627
+ be of type `bytes`.
628
+ """
629
+
630
+ http_options = (
631
+ _BasePermissionServiceRestTransport._BaseDeletePermission._get_http_options()
632
+ )
633
+
634
+ request, metadata = self._interceptor.pre_delete_permission(
635
+ request, metadata
636
+ )
637
+ transcoded_request = _BasePermissionServiceRestTransport._BaseDeletePermission._get_transcoded_request(
638
+ http_options, request
639
+ )
640
+
641
+ # Jsonify the query params
642
+ query_params = _BasePermissionServiceRestTransport._BaseDeletePermission._get_query_params_json(
643
+ transcoded_request
644
+ )
645
+
646
+ if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
647
+ logging.DEBUG
648
+ ): # pragma: NO COVER
649
+ request_url = "{host}{uri}".format(
650
+ host=self._host, uri=transcoded_request["uri"]
651
+ )
652
+ method = transcoded_request["method"]
653
+ try:
654
+ request_payload = json_format.MessageToJson(request)
655
+ except:
656
+ request_payload = None
657
+ http_request = {
658
+ "payload": request_payload,
659
+ "requestMethod": method,
660
+ "requestUrl": request_url,
661
+ "headers": dict(metadata),
662
+ }
663
+ _LOGGER.debug(
664
+ f"Sending request for google.ai.generativelanguage_v1alpha.PermissionServiceClient.DeletePermission",
665
+ extra={
666
+ "serviceName": "google.ai.generativelanguage.v1alpha.PermissionService",
667
+ "rpcName": "DeletePermission",
668
+ "httpRequest": http_request,
669
+ "metadata": http_request["headers"],
670
+ },
671
+ )
672
+
673
+ # Send the request
674
+ response = PermissionServiceRestTransport._DeletePermission._get_response(
675
+ self._host,
676
+ metadata,
677
+ query_params,
678
+ self._session,
679
+ timeout,
680
+ transcoded_request,
681
+ )
682
+
683
+ # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
684
+ # subclass.
685
+ if response.status_code >= 400:
686
+ raise core_exceptions.from_http_response(response)
687
+
688
+ class _GetPermission(
689
+ _BasePermissionServiceRestTransport._BaseGetPermission,
690
+ PermissionServiceRestStub,
691
+ ):
692
+ def __hash__(self):
693
+ return hash("PermissionServiceRestTransport.GetPermission")
694
+
695
+ @staticmethod
696
+ def _get_response(
697
+ host,
698
+ metadata,
699
+ query_params,
700
+ session,
701
+ timeout,
702
+ transcoded_request,
703
+ body=None,
704
+ ):
705
+ uri = transcoded_request["uri"]
706
+ method = transcoded_request["method"]
707
+ headers = dict(metadata)
708
+ headers["Content-Type"] = "application/json"
709
+ response = getattr(session, method)(
710
+ "{host}{uri}".format(host=host, uri=uri),
711
+ timeout=timeout,
712
+ headers=headers,
713
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
714
+ )
715
+ return response
716
+
717
+ def __call__(
718
+ self,
719
+ request: permission_service.GetPermissionRequest,
720
+ *,
721
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
722
+ timeout: Optional[float] = None,
723
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
724
+ ) -> permission.Permission:
725
+ r"""Call the get permission method over HTTP.
726
+
727
+ Args:
728
+ request (~.permission_service.GetPermissionRequest):
729
+ The request object. Request for getting information about a specific
730
+ ``Permission``.
731
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
732
+ should be retried.
733
+ timeout (float): The timeout for this request.
734
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
735
+ sent along with the request as metadata. Normally, each value must be of type `str`,
736
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
737
+ be of type `bytes`.
738
+
739
+ Returns:
740
+ ~.permission.Permission:
741
+ Permission resource grants user,
742
+ group or the rest of the world access to
743
+ the PaLM API resource (e.g. a tuned
744
+ model, corpus).
745
+
746
+ A role is a collection of permitted
747
+ operations that allows users to perform
748
+ specific actions on PaLM API resources.
749
+ To make them available to users, groups,
750
+ or service accounts, you assign roles.
751
+ When you assign a role, you grant
752
+ permissions that the role contains.
753
+
754
+ There are three concentric roles. Each
755
+ role is a superset of the previous
756
+ role's permitted operations:
757
+
758
+ - reader can use the resource (e.g.
759
+ tuned model, corpus) for inference
760
+ - writer has reader's permissions and
761
+ additionally can edit and share
762
+ - owner has writer's permissions and
763
+ additionally can delete
764
+
765
+ """
766
+
767
+ http_options = (
768
+ _BasePermissionServiceRestTransport._BaseGetPermission._get_http_options()
769
+ )
770
+
771
+ request, metadata = self._interceptor.pre_get_permission(request, metadata)
772
+ transcoded_request = _BasePermissionServiceRestTransport._BaseGetPermission._get_transcoded_request(
773
+ http_options, request
774
+ )
775
+
776
+ # Jsonify the query params
777
+ query_params = _BasePermissionServiceRestTransport._BaseGetPermission._get_query_params_json(
778
+ transcoded_request
779
+ )
780
+
781
+ if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
782
+ logging.DEBUG
783
+ ): # pragma: NO COVER
784
+ request_url = "{host}{uri}".format(
785
+ host=self._host, uri=transcoded_request["uri"]
786
+ )
787
+ method = transcoded_request["method"]
788
+ try:
789
+ request_payload = type(request).to_json(request)
790
+ except:
791
+ request_payload = None
792
+ http_request = {
793
+ "payload": request_payload,
794
+ "requestMethod": method,
795
+ "requestUrl": request_url,
796
+ "headers": dict(metadata),
797
+ }
798
+ _LOGGER.debug(
799
+ f"Sending request for google.ai.generativelanguage_v1alpha.PermissionServiceClient.GetPermission",
800
+ extra={
801
+ "serviceName": "google.ai.generativelanguage.v1alpha.PermissionService",
802
+ "rpcName": "GetPermission",
803
+ "httpRequest": http_request,
804
+ "metadata": http_request["headers"],
805
+ },
806
+ )
807
+
808
+ # Send the request
809
+ response = PermissionServiceRestTransport._GetPermission._get_response(
810
+ self._host,
811
+ metadata,
812
+ query_params,
813
+ self._session,
814
+ timeout,
815
+ transcoded_request,
816
+ )
817
+
818
+ # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
819
+ # subclass.
820
+ if response.status_code >= 400:
821
+ raise core_exceptions.from_http_response(response)
822
+
823
+ # Return the response
824
+ resp = permission.Permission()
825
+ pb_resp = permission.Permission.pb(resp)
826
+
827
+ json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
828
+
829
+ resp = self._interceptor.post_get_permission(resp)
830
+ if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
831
+ logging.DEBUG
832
+ ): # pragma: NO COVER
833
+ try:
834
+ response_payload = permission.Permission.to_json(response)
835
+ except:
836
+ response_payload = None
837
+ http_response = {
838
+ "payload": response_payload,
839
+ "headers": dict(response.headers),
840
+ "status": response.status_code,
841
+ }
842
+ _LOGGER.debug(
843
+ "Received response for google.ai.generativelanguage_v1alpha.PermissionServiceClient.get_permission",
844
+ extra={
845
+ "serviceName": "google.ai.generativelanguage.v1alpha.PermissionService",
846
+ "rpcName": "GetPermission",
847
+ "metadata": http_response["headers"],
848
+ "httpResponse": http_response,
849
+ },
850
+ )
851
+ return resp
852
+
853
+ class _ListPermissions(
854
+ _BasePermissionServiceRestTransport._BaseListPermissions,
855
+ PermissionServiceRestStub,
856
+ ):
857
+ def __hash__(self):
858
+ return hash("PermissionServiceRestTransport.ListPermissions")
859
+
860
+ @staticmethod
861
+ def _get_response(
862
+ host,
863
+ metadata,
864
+ query_params,
865
+ session,
866
+ timeout,
867
+ transcoded_request,
868
+ body=None,
869
+ ):
870
+ uri = transcoded_request["uri"]
871
+ method = transcoded_request["method"]
872
+ headers = dict(metadata)
873
+ headers["Content-Type"] = "application/json"
874
+ response = getattr(session, method)(
875
+ "{host}{uri}".format(host=host, uri=uri),
876
+ timeout=timeout,
877
+ headers=headers,
878
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
879
+ )
880
+ return response
881
+
882
+ def __call__(
883
+ self,
884
+ request: permission_service.ListPermissionsRequest,
885
+ *,
886
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
887
+ timeout: Optional[float] = None,
888
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
889
+ ) -> permission_service.ListPermissionsResponse:
890
+ r"""Call the list permissions method over HTTP.
891
+
892
+ Args:
893
+ request (~.permission_service.ListPermissionsRequest):
894
+ The request object. Request for listing permissions.
895
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
896
+ should be retried.
897
+ timeout (float): The timeout for this request.
898
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
899
+ sent along with the request as metadata. Normally, each value must be of type `str`,
900
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
901
+ be of type `bytes`.
902
+
903
+ Returns:
904
+ ~.permission_service.ListPermissionsResponse:
905
+ Response from ``ListPermissions`` containing a paginated
906
+ list of permissions.
907
+
908
+ """
909
+
910
+ http_options = (
911
+ _BasePermissionServiceRestTransport._BaseListPermissions._get_http_options()
912
+ )
913
+
914
+ request, metadata = self._interceptor.pre_list_permissions(
915
+ request, metadata
916
+ )
917
+ transcoded_request = _BasePermissionServiceRestTransport._BaseListPermissions._get_transcoded_request(
918
+ http_options, request
919
+ )
920
+
921
+ # Jsonify the query params
922
+ query_params = _BasePermissionServiceRestTransport._BaseListPermissions._get_query_params_json(
923
+ transcoded_request
924
+ )
925
+
926
+ if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
927
+ logging.DEBUG
928
+ ): # pragma: NO COVER
929
+ request_url = "{host}{uri}".format(
930
+ host=self._host, uri=transcoded_request["uri"]
931
+ )
932
+ method = transcoded_request["method"]
933
+ try:
934
+ request_payload = type(request).to_json(request)
935
+ except:
936
+ request_payload = None
937
+ http_request = {
938
+ "payload": request_payload,
939
+ "requestMethod": method,
940
+ "requestUrl": request_url,
941
+ "headers": dict(metadata),
942
+ }
943
+ _LOGGER.debug(
944
+ f"Sending request for google.ai.generativelanguage_v1alpha.PermissionServiceClient.ListPermissions",
945
+ extra={
946
+ "serviceName": "google.ai.generativelanguage.v1alpha.PermissionService",
947
+ "rpcName": "ListPermissions",
948
+ "httpRequest": http_request,
949
+ "metadata": http_request["headers"],
950
+ },
951
+ )
952
+
953
+ # Send the request
954
+ response = PermissionServiceRestTransport._ListPermissions._get_response(
955
+ self._host,
956
+ metadata,
957
+ query_params,
958
+ self._session,
959
+ timeout,
960
+ transcoded_request,
961
+ )
962
+
963
+ # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
964
+ # subclass.
965
+ if response.status_code >= 400:
966
+ raise core_exceptions.from_http_response(response)
967
+
968
+ # Return the response
969
+ resp = permission_service.ListPermissionsResponse()
970
+ pb_resp = permission_service.ListPermissionsResponse.pb(resp)
971
+
972
+ json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
973
+
974
+ resp = self._interceptor.post_list_permissions(resp)
975
+ if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
976
+ logging.DEBUG
977
+ ): # pragma: NO COVER
978
+ try:
979
+ response_payload = (
980
+ permission_service.ListPermissionsResponse.to_json(response)
981
+ )
982
+ except:
983
+ response_payload = None
984
+ http_response = {
985
+ "payload": response_payload,
986
+ "headers": dict(response.headers),
987
+ "status": response.status_code,
988
+ }
989
+ _LOGGER.debug(
990
+ "Received response for google.ai.generativelanguage_v1alpha.PermissionServiceClient.list_permissions",
991
+ extra={
992
+ "serviceName": "google.ai.generativelanguage.v1alpha.PermissionService",
993
+ "rpcName": "ListPermissions",
994
+ "metadata": http_response["headers"],
995
+ "httpResponse": http_response,
996
+ },
997
+ )
998
+ return resp
999
+
1000
+ class _TransferOwnership(
1001
+ _BasePermissionServiceRestTransport._BaseTransferOwnership,
1002
+ PermissionServiceRestStub,
1003
+ ):
1004
+ def __hash__(self):
1005
+ return hash("PermissionServiceRestTransport.TransferOwnership")
1006
+
1007
+ @staticmethod
1008
+ def _get_response(
1009
+ host,
1010
+ metadata,
1011
+ query_params,
1012
+ session,
1013
+ timeout,
1014
+ transcoded_request,
1015
+ body=None,
1016
+ ):
1017
+ uri = transcoded_request["uri"]
1018
+ method = transcoded_request["method"]
1019
+ headers = dict(metadata)
1020
+ headers["Content-Type"] = "application/json"
1021
+ response = getattr(session, method)(
1022
+ "{host}{uri}".format(host=host, uri=uri),
1023
+ timeout=timeout,
1024
+ headers=headers,
1025
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
1026
+ data=body,
1027
+ )
1028
+ return response
1029
+
1030
+ def __call__(
1031
+ self,
1032
+ request: permission_service.TransferOwnershipRequest,
1033
+ *,
1034
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
1035
+ timeout: Optional[float] = None,
1036
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1037
+ ) -> permission_service.TransferOwnershipResponse:
1038
+ r"""Call the transfer ownership method over HTTP.
1039
+
1040
+ Args:
1041
+ request (~.permission_service.TransferOwnershipRequest):
1042
+ The request object. Request to transfer the ownership of
1043
+ the tuned model.
1044
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
1045
+ should be retried.
1046
+ timeout (float): The timeout for this request.
1047
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1048
+ sent along with the request as metadata. Normally, each value must be of type `str`,
1049
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
1050
+ be of type `bytes`.
1051
+
1052
+ Returns:
1053
+ ~.permission_service.TransferOwnershipResponse:
1054
+ Response from ``TransferOwnership``.
1055
+ """
1056
+
1057
+ http_options = (
1058
+ _BasePermissionServiceRestTransport._BaseTransferOwnership._get_http_options()
1059
+ )
1060
+
1061
+ request, metadata = self._interceptor.pre_transfer_ownership(
1062
+ request, metadata
1063
+ )
1064
+ transcoded_request = _BasePermissionServiceRestTransport._BaseTransferOwnership._get_transcoded_request(
1065
+ http_options, request
1066
+ )
1067
+
1068
+ body = _BasePermissionServiceRestTransport._BaseTransferOwnership._get_request_body_json(
1069
+ transcoded_request
1070
+ )
1071
+
1072
+ # Jsonify the query params
1073
+ query_params = _BasePermissionServiceRestTransport._BaseTransferOwnership._get_query_params_json(
1074
+ transcoded_request
1075
+ )
1076
+
1077
+ if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
1078
+ logging.DEBUG
1079
+ ): # pragma: NO COVER
1080
+ request_url = "{host}{uri}".format(
1081
+ host=self._host, uri=transcoded_request["uri"]
1082
+ )
1083
+ method = transcoded_request["method"]
1084
+ try:
1085
+ request_payload = type(request).to_json(request)
1086
+ except:
1087
+ request_payload = None
1088
+ http_request = {
1089
+ "payload": request_payload,
1090
+ "requestMethod": method,
1091
+ "requestUrl": request_url,
1092
+ "headers": dict(metadata),
1093
+ }
1094
+ _LOGGER.debug(
1095
+ f"Sending request for google.ai.generativelanguage_v1alpha.PermissionServiceClient.TransferOwnership",
1096
+ extra={
1097
+ "serviceName": "google.ai.generativelanguage.v1alpha.PermissionService",
1098
+ "rpcName": "TransferOwnership",
1099
+ "httpRequest": http_request,
1100
+ "metadata": http_request["headers"],
1101
+ },
1102
+ )
1103
+
1104
+ # Send the request
1105
+ response = PermissionServiceRestTransport._TransferOwnership._get_response(
1106
+ self._host,
1107
+ metadata,
1108
+ query_params,
1109
+ self._session,
1110
+ timeout,
1111
+ transcoded_request,
1112
+ body,
1113
+ )
1114
+
1115
+ # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
1116
+ # subclass.
1117
+ if response.status_code >= 400:
1118
+ raise core_exceptions.from_http_response(response)
1119
+
1120
+ # Return the response
1121
+ resp = permission_service.TransferOwnershipResponse()
1122
+ pb_resp = permission_service.TransferOwnershipResponse.pb(resp)
1123
+
1124
+ json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
1125
+
1126
+ resp = self._interceptor.post_transfer_ownership(resp)
1127
+ if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
1128
+ logging.DEBUG
1129
+ ): # pragma: NO COVER
1130
+ try:
1131
+ response_payload = (
1132
+ permission_service.TransferOwnershipResponse.to_json(response)
1133
+ )
1134
+ except:
1135
+ response_payload = None
1136
+ http_response = {
1137
+ "payload": response_payload,
1138
+ "headers": dict(response.headers),
1139
+ "status": response.status_code,
1140
+ }
1141
+ _LOGGER.debug(
1142
+ "Received response for google.ai.generativelanguage_v1alpha.PermissionServiceClient.transfer_ownership",
1143
+ extra={
1144
+ "serviceName": "google.ai.generativelanguage.v1alpha.PermissionService",
1145
+ "rpcName": "TransferOwnership",
1146
+ "metadata": http_response["headers"],
1147
+ "httpResponse": http_response,
1148
+ },
1149
+ )
1150
+ return resp
1151
+
1152
+ class _UpdatePermission(
1153
+ _BasePermissionServiceRestTransport._BaseUpdatePermission,
1154
+ PermissionServiceRestStub,
1155
+ ):
1156
+ def __hash__(self):
1157
+ return hash("PermissionServiceRestTransport.UpdatePermission")
1158
+
1159
+ @staticmethod
1160
+ def _get_response(
1161
+ host,
1162
+ metadata,
1163
+ query_params,
1164
+ session,
1165
+ timeout,
1166
+ transcoded_request,
1167
+ body=None,
1168
+ ):
1169
+ uri = transcoded_request["uri"]
1170
+ method = transcoded_request["method"]
1171
+ headers = dict(metadata)
1172
+ headers["Content-Type"] = "application/json"
1173
+ response = getattr(session, method)(
1174
+ "{host}{uri}".format(host=host, uri=uri),
1175
+ timeout=timeout,
1176
+ headers=headers,
1177
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
1178
+ data=body,
1179
+ )
1180
+ return response
1181
+
1182
+ def __call__(
1183
+ self,
1184
+ request: permission_service.UpdatePermissionRequest,
1185
+ *,
1186
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
1187
+ timeout: Optional[float] = None,
1188
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1189
+ ) -> gag_permission.Permission:
1190
+ r"""Call the update permission method over HTTP.
1191
+
1192
+ Args:
1193
+ request (~.permission_service.UpdatePermissionRequest):
1194
+ The request object. Request to update the ``Permission``.
1195
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
1196
+ should be retried.
1197
+ timeout (float): The timeout for this request.
1198
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1199
+ sent along with the request as metadata. Normally, each value must be of type `str`,
1200
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
1201
+ be of type `bytes`.
1202
+
1203
+ Returns:
1204
+ ~.gag_permission.Permission:
1205
+ Permission resource grants user,
1206
+ group or the rest of the world access to
1207
+ the PaLM API resource (e.g. a tuned
1208
+ model, corpus).
1209
+
1210
+ A role is a collection of permitted
1211
+ operations that allows users to perform
1212
+ specific actions on PaLM API resources.
1213
+ To make them available to users, groups,
1214
+ or service accounts, you assign roles.
1215
+ When you assign a role, you grant
1216
+ permissions that the role contains.
1217
+
1218
+ There are three concentric roles. Each
1219
+ role is a superset of the previous
1220
+ role's permitted operations:
1221
+
1222
+ - reader can use the resource (e.g.
1223
+ tuned model, corpus) for inference
1224
+ - writer has reader's permissions and
1225
+ additionally can edit and share
1226
+ - owner has writer's permissions and
1227
+ additionally can delete
1228
+
1229
+ """
1230
+
1231
+ http_options = (
1232
+ _BasePermissionServiceRestTransport._BaseUpdatePermission._get_http_options()
1233
+ )
1234
+
1235
+ request, metadata = self._interceptor.pre_update_permission(
1236
+ request, metadata
1237
+ )
1238
+ transcoded_request = _BasePermissionServiceRestTransport._BaseUpdatePermission._get_transcoded_request(
1239
+ http_options, request
1240
+ )
1241
+
1242
+ body = _BasePermissionServiceRestTransport._BaseUpdatePermission._get_request_body_json(
1243
+ transcoded_request
1244
+ )
1245
+
1246
+ # Jsonify the query params
1247
+ query_params = _BasePermissionServiceRestTransport._BaseUpdatePermission._get_query_params_json(
1248
+ transcoded_request
1249
+ )
1250
+
1251
+ if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
1252
+ logging.DEBUG
1253
+ ): # pragma: NO COVER
1254
+ request_url = "{host}{uri}".format(
1255
+ host=self._host, uri=transcoded_request["uri"]
1256
+ )
1257
+ method = transcoded_request["method"]
1258
+ try:
1259
+ request_payload = type(request).to_json(request)
1260
+ except:
1261
+ request_payload = None
1262
+ http_request = {
1263
+ "payload": request_payload,
1264
+ "requestMethod": method,
1265
+ "requestUrl": request_url,
1266
+ "headers": dict(metadata),
1267
+ }
1268
+ _LOGGER.debug(
1269
+ f"Sending request for google.ai.generativelanguage_v1alpha.PermissionServiceClient.UpdatePermission",
1270
+ extra={
1271
+ "serviceName": "google.ai.generativelanguage.v1alpha.PermissionService",
1272
+ "rpcName": "UpdatePermission",
1273
+ "httpRequest": http_request,
1274
+ "metadata": http_request["headers"],
1275
+ },
1276
+ )
1277
+
1278
+ # Send the request
1279
+ response = PermissionServiceRestTransport._UpdatePermission._get_response(
1280
+ self._host,
1281
+ metadata,
1282
+ query_params,
1283
+ self._session,
1284
+ timeout,
1285
+ transcoded_request,
1286
+ body,
1287
+ )
1288
+
1289
+ # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
1290
+ # subclass.
1291
+ if response.status_code >= 400:
1292
+ raise core_exceptions.from_http_response(response)
1293
+
1294
+ # Return the response
1295
+ resp = gag_permission.Permission()
1296
+ pb_resp = gag_permission.Permission.pb(resp)
1297
+
1298
+ json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
1299
+
1300
+ resp = self._interceptor.post_update_permission(resp)
1301
+ if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
1302
+ logging.DEBUG
1303
+ ): # pragma: NO COVER
1304
+ try:
1305
+ response_payload = gag_permission.Permission.to_json(response)
1306
+ except:
1307
+ response_payload = None
1308
+ http_response = {
1309
+ "payload": response_payload,
1310
+ "headers": dict(response.headers),
1311
+ "status": response.status_code,
1312
+ }
1313
+ _LOGGER.debug(
1314
+ "Received response for google.ai.generativelanguage_v1alpha.PermissionServiceClient.update_permission",
1315
+ extra={
1316
+ "serviceName": "google.ai.generativelanguage.v1alpha.PermissionService",
1317
+ "rpcName": "UpdatePermission",
1318
+ "metadata": http_response["headers"],
1319
+ "httpResponse": http_response,
1320
+ },
1321
+ )
1322
+ return resp
1323
+
1324
+ @property
1325
+ def create_permission(
1326
+ self,
1327
+ ) -> Callable[
1328
+ [permission_service.CreatePermissionRequest], gag_permission.Permission
1329
+ ]:
1330
+ # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
1331
+ # In C++ this would require a dynamic_cast
1332
+ return self._CreatePermission(self._session, self._host, self._interceptor) # type: ignore
1333
+
1334
+ @property
1335
+ def delete_permission(
1336
+ self,
1337
+ ) -> Callable[[permission_service.DeletePermissionRequest], empty_pb2.Empty]:
1338
+ # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
1339
+ # In C++ this would require a dynamic_cast
1340
+ return self._DeletePermission(self._session, self._host, self._interceptor) # type: ignore
1341
+
1342
+ @property
1343
+ def get_permission(
1344
+ self,
1345
+ ) -> Callable[[permission_service.GetPermissionRequest], permission.Permission]:
1346
+ # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
1347
+ # In C++ this would require a dynamic_cast
1348
+ return self._GetPermission(self._session, self._host, self._interceptor) # type: ignore
1349
+
1350
+ @property
1351
+ def list_permissions(
1352
+ self,
1353
+ ) -> Callable[
1354
+ [permission_service.ListPermissionsRequest],
1355
+ permission_service.ListPermissionsResponse,
1356
+ ]:
1357
+ # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
1358
+ # In C++ this would require a dynamic_cast
1359
+ return self._ListPermissions(self._session, self._host, self._interceptor) # type: ignore
1360
+
1361
+ @property
1362
+ def transfer_ownership(
1363
+ self,
1364
+ ) -> Callable[
1365
+ [permission_service.TransferOwnershipRequest],
1366
+ permission_service.TransferOwnershipResponse,
1367
+ ]:
1368
+ # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
1369
+ # In C++ this would require a dynamic_cast
1370
+ return self._TransferOwnership(self._session, self._host, self._interceptor) # type: ignore
1371
+
1372
+ @property
1373
+ def update_permission(
1374
+ self,
1375
+ ) -> Callable[
1376
+ [permission_service.UpdatePermissionRequest], gag_permission.Permission
1377
+ ]:
1378
+ # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
1379
+ # In C++ this would require a dynamic_cast
1380
+ return self._UpdatePermission(self._session, self._host, self._interceptor) # type: ignore
1381
+
1382
+ @property
1383
+ def get_operation(self):
1384
+ return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore
1385
+
1386
+ class _GetOperation(
1387
+ _BasePermissionServiceRestTransport._BaseGetOperation, PermissionServiceRestStub
1388
+ ):
1389
+ def __hash__(self):
1390
+ return hash("PermissionServiceRestTransport.GetOperation")
1391
+
1392
+ @staticmethod
1393
+ def _get_response(
1394
+ host,
1395
+ metadata,
1396
+ query_params,
1397
+ session,
1398
+ timeout,
1399
+ transcoded_request,
1400
+ body=None,
1401
+ ):
1402
+ uri = transcoded_request["uri"]
1403
+ method = transcoded_request["method"]
1404
+ headers = dict(metadata)
1405
+ headers["Content-Type"] = "application/json"
1406
+ response = getattr(session, method)(
1407
+ "{host}{uri}".format(host=host, uri=uri),
1408
+ timeout=timeout,
1409
+ headers=headers,
1410
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
1411
+ )
1412
+ return response
1413
+
1414
+ def __call__(
1415
+ self,
1416
+ request: operations_pb2.GetOperationRequest,
1417
+ *,
1418
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
1419
+ timeout: Optional[float] = None,
1420
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1421
+ ) -> operations_pb2.Operation:
1422
+ r"""Call the get operation method over HTTP.
1423
+
1424
+ Args:
1425
+ request (operations_pb2.GetOperationRequest):
1426
+ The request object for GetOperation method.
1427
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
1428
+ should be retried.
1429
+ timeout (float): The timeout for this request.
1430
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1431
+ sent along with the request as metadata. Normally, each value must be of type `str`,
1432
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
1433
+ be of type `bytes`.
1434
+
1435
+ Returns:
1436
+ operations_pb2.Operation: Response from GetOperation method.
1437
+ """
1438
+
1439
+ http_options = (
1440
+ _BasePermissionServiceRestTransport._BaseGetOperation._get_http_options()
1441
+ )
1442
+
1443
+ request, metadata = self._interceptor.pre_get_operation(request, metadata)
1444
+ transcoded_request = _BasePermissionServiceRestTransport._BaseGetOperation._get_transcoded_request(
1445
+ http_options, request
1446
+ )
1447
+
1448
+ # Jsonify the query params
1449
+ query_params = _BasePermissionServiceRestTransport._BaseGetOperation._get_query_params_json(
1450
+ transcoded_request
1451
+ )
1452
+
1453
+ if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
1454
+ logging.DEBUG
1455
+ ): # pragma: NO COVER
1456
+ request_url = "{host}{uri}".format(
1457
+ host=self._host, uri=transcoded_request["uri"]
1458
+ )
1459
+ method = transcoded_request["method"]
1460
+ try:
1461
+ request_payload = json_format.MessageToJson(request)
1462
+ except:
1463
+ request_payload = None
1464
+ http_request = {
1465
+ "payload": request_payload,
1466
+ "requestMethod": method,
1467
+ "requestUrl": request_url,
1468
+ "headers": dict(metadata),
1469
+ }
1470
+ _LOGGER.debug(
1471
+ f"Sending request for google.ai.generativelanguage_v1alpha.PermissionServiceClient.GetOperation",
1472
+ extra={
1473
+ "serviceName": "google.ai.generativelanguage.v1alpha.PermissionService",
1474
+ "rpcName": "GetOperation",
1475
+ "httpRequest": http_request,
1476
+ "metadata": http_request["headers"],
1477
+ },
1478
+ )
1479
+
1480
+ # Send the request
1481
+ response = PermissionServiceRestTransport._GetOperation._get_response(
1482
+ self._host,
1483
+ metadata,
1484
+ query_params,
1485
+ self._session,
1486
+ timeout,
1487
+ transcoded_request,
1488
+ )
1489
+
1490
+ # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
1491
+ # subclass.
1492
+ if response.status_code >= 400:
1493
+ raise core_exceptions.from_http_response(response)
1494
+
1495
+ content = response.content.decode("utf-8")
1496
+ resp = operations_pb2.Operation()
1497
+ resp = json_format.Parse(content, resp)
1498
+ resp = self._interceptor.post_get_operation(resp)
1499
+ if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
1500
+ logging.DEBUG
1501
+ ): # pragma: NO COVER
1502
+ try:
1503
+ response_payload = json_format.MessageToJson(resp)
1504
+ except:
1505
+ response_payload = None
1506
+ http_response = {
1507
+ "payload": response_payload,
1508
+ "headers": dict(response.headers),
1509
+ "status": response.status_code,
1510
+ }
1511
+ _LOGGER.debug(
1512
+ "Received response for google.ai.generativelanguage_v1alpha.PermissionServiceAsyncClient.GetOperation",
1513
+ extra={
1514
+ "serviceName": "google.ai.generativelanguage.v1alpha.PermissionService",
1515
+ "rpcName": "GetOperation",
1516
+ "httpResponse": http_response,
1517
+ "metadata": http_response["headers"],
1518
+ },
1519
+ )
1520
+ return resp
1521
+
1522
+ @property
1523
+ def list_operations(self):
1524
+ return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore
1525
+
1526
+ class _ListOperations(
1527
+ _BasePermissionServiceRestTransport._BaseListOperations,
1528
+ PermissionServiceRestStub,
1529
+ ):
1530
+ def __hash__(self):
1531
+ return hash("PermissionServiceRestTransport.ListOperations")
1532
+
1533
+ @staticmethod
1534
+ def _get_response(
1535
+ host,
1536
+ metadata,
1537
+ query_params,
1538
+ session,
1539
+ timeout,
1540
+ transcoded_request,
1541
+ body=None,
1542
+ ):
1543
+ uri = transcoded_request["uri"]
1544
+ method = transcoded_request["method"]
1545
+ headers = dict(metadata)
1546
+ headers["Content-Type"] = "application/json"
1547
+ response = getattr(session, method)(
1548
+ "{host}{uri}".format(host=host, uri=uri),
1549
+ timeout=timeout,
1550
+ headers=headers,
1551
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
1552
+ )
1553
+ return response
1554
+
1555
+ def __call__(
1556
+ self,
1557
+ request: operations_pb2.ListOperationsRequest,
1558
+ *,
1559
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
1560
+ timeout: Optional[float] = None,
1561
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1562
+ ) -> operations_pb2.ListOperationsResponse:
1563
+ r"""Call the list operations method over HTTP.
1564
+
1565
+ Args:
1566
+ request (operations_pb2.ListOperationsRequest):
1567
+ The request object for ListOperations method.
1568
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
1569
+ should be retried.
1570
+ timeout (float): The timeout for this request.
1571
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1572
+ sent along with the request as metadata. Normally, each value must be of type `str`,
1573
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
1574
+ be of type `bytes`.
1575
+
1576
+ Returns:
1577
+ operations_pb2.ListOperationsResponse: Response from ListOperations method.
1578
+ """
1579
+
1580
+ http_options = (
1581
+ _BasePermissionServiceRestTransport._BaseListOperations._get_http_options()
1582
+ )
1583
+
1584
+ request, metadata = self._interceptor.pre_list_operations(request, metadata)
1585
+ transcoded_request = _BasePermissionServiceRestTransport._BaseListOperations._get_transcoded_request(
1586
+ http_options, request
1587
+ )
1588
+
1589
+ # Jsonify the query params
1590
+ query_params = _BasePermissionServiceRestTransport._BaseListOperations._get_query_params_json(
1591
+ transcoded_request
1592
+ )
1593
+
1594
+ if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
1595
+ logging.DEBUG
1596
+ ): # pragma: NO COVER
1597
+ request_url = "{host}{uri}".format(
1598
+ host=self._host, uri=transcoded_request["uri"]
1599
+ )
1600
+ method = transcoded_request["method"]
1601
+ try:
1602
+ request_payload = json_format.MessageToJson(request)
1603
+ except:
1604
+ request_payload = None
1605
+ http_request = {
1606
+ "payload": request_payload,
1607
+ "requestMethod": method,
1608
+ "requestUrl": request_url,
1609
+ "headers": dict(metadata),
1610
+ }
1611
+ _LOGGER.debug(
1612
+ f"Sending request for google.ai.generativelanguage_v1alpha.PermissionServiceClient.ListOperations",
1613
+ extra={
1614
+ "serviceName": "google.ai.generativelanguage.v1alpha.PermissionService",
1615
+ "rpcName": "ListOperations",
1616
+ "httpRequest": http_request,
1617
+ "metadata": http_request["headers"],
1618
+ },
1619
+ )
1620
+
1621
+ # Send the request
1622
+ response = PermissionServiceRestTransport._ListOperations._get_response(
1623
+ self._host,
1624
+ metadata,
1625
+ query_params,
1626
+ self._session,
1627
+ timeout,
1628
+ transcoded_request,
1629
+ )
1630
+
1631
+ # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
1632
+ # subclass.
1633
+ if response.status_code >= 400:
1634
+ raise core_exceptions.from_http_response(response)
1635
+
1636
+ content = response.content.decode("utf-8")
1637
+ resp = operations_pb2.ListOperationsResponse()
1638
+ resp = json_format.Parse(content, resp)
1639
+ resp = self._interceptor.post_list_operations(resp)
1640
+ if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
1641
+ logging.DEBUG
1642
+ ): # pragma: NO COVER
1643
+ try:
1644
+ response_payload = json_format.MessageToJson(resp)
1645
+ except:
1646
+ response_payload = None
1647
+ http_response = {
1648
+ "payload": response_payload,
1649
+ "headers": dict(response.headers),
1650
+ "status": response.status_code,
1651
+ }
1652
+ _LOGGER.debug(
1653
+ "Received response for google.ai.generativelanguage_v1alpha.PermissionServiceAsyncClient.ListOperations",
1654
+ extra={
1655
+ "serviceName": "google.ai.generativelanguage.v1alpha.PermissionService",
1656
+ "rpcName": "ListOperations",
1657
+ "httpResponse": http_response,
1658
+ "metadata": http_response["headers"],
1659
+ },
1660
+ )
1661
+ return resp
1662
+
1663
+ @property
1664
+ def kind(self) -> str:
1665
+ return "rest"
1666
+
1667
+ def close(self):
1668
+ self._session.close()
1669
+
1670
+
1671
+ __all__ = ("PermissionServiceRestTransport",)
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/permission_service/transports/rest_base.py ADDED
@@ -0,0 +1,493 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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_v1alpha.types import permission as gag_permission
26
+ from google.ai.generativelanguage_v1alpha.types import permission
27
+ from google.ai.generativelanguage_v1alpha.types import permission_service
28
+
29
+ from .base import DEFAULT_CLIENT_INFO, PermissionServiceTransport
30
+
31
+
32
+ class _BasePermissionServiceRestTransport(PermissionServiceTransport):
33
+ """Base REST backend transport for PermissionService.
34
+
35
+ Note: This class is not meant to be used directly. Use its sync and
36
+ async sub-classes instead.
37
+
38
+ This class defines the same methods as the primary client, so the
39
+ primary client can load the underlying transport implementation
40
+ and call it.
41
+
42
+ It sends JSON representations of protocol buffers over HTTP/1.1
43
+ """
44
+
45
+ def __init__(
46
+ self,
47
+ *,
48
+ host: str = "generativelanguage.googleapis.com",
49
+ credentials: Optional[Any] = None,
50
+ client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
51
+ always_use_jwt_access: Optional[bool] = False,
52
+ url_scheme: str = "https",
53
+ api_audience: Optional[str] = None,
54
+ ) -> None:
55
+ """Instantiate the transport.
56
+ Args:
57
+ host (Optional[str]):
58
+ The hostname to connect to (default: 'generativelanguage.googleapis.com').
59
+ credentials (Optional[Any]): The
60
+ authorization credentials to attach to requests. These
61
+ credentials identify the application to the service; if none
62
+ are specified, the client will attempt to ascertain the
63
+ credentials from the environment.
64
+ client_info (google.api_core.gapic_v1.client_info.ClientInfo):
65
+ The client info used to send a user-agent string along with
66
+ API requests. If ``None``, then default info will be used.
67
+ Generally, you only need to set this if you are developing
68
+ your own client library.
69
+ always_use_jwt_access (Optional[bool]): Whether self signed JWT should
70
+ be used for service account credentials.
71
+ url_scheme: the protocol scheme for the API endpoint. Normally
72
+ "https", but for testing or local servers,
73
+ "http" can be specified.
74
+ """
75
+ # Run the base constructor
76
+ maybe_url_match = re.match("^(?P<scheme>http(?:s)?://)?(?P<host>.*)$", host)
77
+ if maybe_url_match is None:
78
+ raise ValueError(
79
+ f"Unexpected hostname structure: {host}"
80
+ ) # pragma: NO COVER
81
+
82
+ url_match_items = maybe_url_match.groupdict()
83
+
84
+ host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host
85
+
86
+ super().__init__(
87
+ host=host,
88
+ credentials=credentials,
89
+ client_info=client_info,
90
+ always_use_jwt_access=always_use_jwt_access,
91
+ api_audience=api_audience,
92
+ )
93
+
94
+ class _BaseCreatePermission:
95
+ def __hash__(self): # pragma: NO COVER
96
+ return NotImplementedError("__hash__ must be implemented.")
97
+
98
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
99
+
100
+ @classmethod
101
+ def _get_unset_required_fields(cls, message_dict):
102
+ return {
103
+ k: v
104
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
105
+ if k not in message_dict
106
+ }
107
+
108
+ @staticmethod
109
+ def _get_http_options():
110
+ http_options: List[Dict[str, str]] = [
111
+ {
112
+ "method": "post",
113
+ "uri": "/v1alpha/{parent=tunedModels/*}/permissions",
114
+ "body": "permission",
115
+ },
116
+ {
117
+ "method": "post",
118
+ "uri": "/v1alpha/{parent=corpora/*}/permissions",
119
+ "body": "permission",
120
+ },
121
+ ]
122
+ return http_options
123
+
124
+ @staticmethod
125
+ def _get_transcoded_request(http_options, request):
126
+ pb_request = permission_service.CreatePermissionRequest.pb(request)
127
+ transcoded_request = path_template.transcode(http_options, pb_request)
128
+ return transcoded_request
129
+
130
+ @staticmethod
131
+ def _get_request_body_json(transcoded_request):
132
+ # Jsonify the request body
133
+
134
+ body = json_format.MessageToJson(
135
+ transcoded_request["body"], use_integers_for_enums=True
136
+ )
137
+ return body
138
+
139
+ @staticmethod
140
+ def _get_query_params_json(transcoded_request):
141
+ query_params = json.loads(
142
+ json_format.MessageToJson(
143
+ transcoded_request["query_params"],
144
+ use_integers_for_enums=True,
145
+ )
146
+ )
147
+ query_params.update(
148
+ _BasePermissionServiceRestTransport._BaseCreatePermission._get_unset_required_fields(
149
+ query_params
150
+ )
151
+ )
152
+
153
+ query_params["$alt"] = "json;enum-encoding=int"
154
+ return query_params
155
+
156
+ class _BaseDeletePermission:
157
+ def __hash__(self): # pragma: NO COVER
158
+ return NotImplementedError("__hash__ must be implemented.")
159
+
160
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
161
+
162
+ @classmethod
163
+ def _get_unset_required_fields(cls, message_dict):
164
+ return {
165
+ k: v
166
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
167
+ if k not in message_dict
168
+ }
169
+
170
+ @staticmethod
171
+ def _get_http_options():
172
+ http_options: List[Dict[str, str]] = [
173
+ {
174
+ "method": "delete",
175
+ "uri": "/v1alpha/{name=tunedModels/*/permissions/*}",
176
+ },
177
+ {
178
+ "method": "delete",
179
+ "uri": "/v1alpha/{name=corpora/*/permissions/*}",
180
+ },
181
+ ]
182
+ return http_options
183
+
184
+ @staticmethod
185
+ def _get_transcoded_request(http_options, request):
186
+ pb_request = permission_service.DeletePermissionRequest.pb(request)
187
+ transcoded_request = path_template.transcode(http_options, pb_request)
188
+ return transcoded_request
189
+
190
+ @staticmethod
191
+ def _get_query_params_json(transcoded_request):
192
+ query_params = json.loads(
193
+ json_format.MessageToJson(
194
+ transcoded_request["query_params"],
195
+ use_integers_for_enums=True,
196
+ )
197
+ )
198
+ query_params.update(
199
+ _BasePermissionServiceRestTransport._BaseDeletePermission._get_unset_required_fields(
200
+ query_params
201
+ )
202
+ )
203
+
204
+ query_params["$alt"] = "json;enum-encoding=int"
205
+ return query_params
206
+
207
+ class _BaseGetPermission:
208
+ def __hash__(self): # pragma: NO COVER
209
+ return NotImplementedError("__hash__ must be implemented.")
210
+
211
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
212
+
213
+ @classmethod
214
+ def _get_unset_required_fields(cls, message_dict):
215
+ return {
216
+ k: v
217
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
218
+ if k not in message_dict
219
+ }
220
+
221
+ @staticmethod
222
+ def _get_http_options():
223
+ http_options: List[Dict[str, str]] = [
224
+ {
225
+ "method": "get",
226
+ "uri": "/v1alpha/{name=tunedModels/*/permissions/*}",
227
+ },
228
+ {
229
+ "method": "get",
230
+ "uri": "/v1alpha/{name=corpora/*/permissions/*}",
231
+ },
232
+ ]
233
+ return http_options
234
+
235
+ @staticmethod
236
+ def _get_transcoded_request(http_options, request):
237
+ pb_request = permission_service.GetPermissionRequest.pb(request)
238
+ transcoded_request = path_template.transcode(http_options, pb_request)
239
+ return transcoded_request
240
+
241
+ @staticmethod
242
+ def _get_query_params_json(transcoded_request):
243
+ query_params = json.loads(
244
+ json_format.MessageToJson(
245
+ transcoded_request["query_params"],
246
+ use_integers_for_enums=True,
247
+ )
248
+ )
249
+ query_params.update(
250
+ _BasePermissionServiceRestTransport._BaseGetPermission._get_unset_required_fields(
251
+ query_params
252
+ )
253
+ )
254
+
255
+ query_params["$alt"] = "json;enum-encoding=int"
256
+ return query_params
257
+
258
+ class _BaseListPermissions:
259
+ def __hash__(self): # pragma: NO COVER
260
+ return NotImplementedError("__hash__ must be implemented.")
261
+
262
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
263
+
264
+ @classmethod
265
+ def _get_unset_required_fields(cls, message_dict):
266
+ return {
267
+ k: v
268
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
269
+ if k not in message_dict
270
+ }
271
+
272
+ @staticmethod
273
+ def _get_http_options():
274
+ http_options: List[Dict[str, str]] = [
275
+ {
276
+ "method": "get",
277
+ "uri": "/v1alpha/{parent=tunedModels/*}/permissions",
278
+ },
279
+ {
280
+ "method": "get",
281
+ "uri": "/v1alpha/{parent=corpora/*}/permissions",
282
+ },
283
+ ]
284
+ return http_options
285
+
286
+ @staticmethod
287
+ def _get_transcoded_request(http_options, request):
288
+ pb_request = permission_service.ListPermissionsRequest.pb(request)
289
+ transcoded_request = path_template.transcode(http_options, pb_request)
290
+ return transcoded_request
291
+
292
+ @staticmethod
293
+ def _get_query_params_json(transcoded_request):
294
+ query_params = json.loads(
295
+ json_format.MessageToJson(
296
+ transcoded_request["query_params"],
297
+ use_integers_for_enums=True,
298
+ )
299
+ )
300
+ query_params.update(
301
+ _BasePermissionServiceRestTransport._BaseListPermissions._get_unset_required_fields(
302
+ query_params
303
+ )
304
+ )
305
+
306
+ query_params["$alt"] = "json;enum-encoding=int"
307
+ return query_params
308
+
309
+ class _BaseTransferOwnership:
310
+ def __hash__(self): # pragma: NO COVER
311
+ return NotImplementedError("__hash__ must be implemented.")
312
+
313
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
314
+
315
+ @classmethod
316
+ def _get_unset_required_fields(cls, message_dict):
317
+ return {
318
+ k: v
319
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
320
+ if k not in message_dict
321
+ }
322
+
323
+ @staticmethod
324
+ def _get_http_options():
325
+ http_options: List[Dict[str, str]] = [
326
+ {
327
+ "method": "post",
328
+ "uri": "/v1alpha/{name=tunedModels/*}:transferOwnership",
329
+ "body": "*",
330
+ },
331
+ ]
332
+ return http_options
333
+
334
+ @staticmethod
335
+ def _get_transcoded_request(http_options, request):
336
+ pb_request = permission_service.TransferOwnershipRequest.pb(request)
337
+ transcoded_request = path_template.transcode(http_options, pb_request)
338
+ return transcoded_request
339
+
340
+ @staticmethod
341
+ def _get_request_body_json(transcoded_request):
342
+ # Jsonify the request body
343
+
344
+ body = json_format.MessageToJson(
345
+ transcoded_request["body"], use_integers_for_enums=True
346
+ )
347
+ return body
348
+
349
+ @staticmethod
350
+ def _get_query_params_json(transcoded_request):
351
+ query_params = json.loads(
352
+ json_format.MessageToJson(
353
+ transcoded_request["query_params"],
354
+ use_integers_for_enums=True,
355
+ )
356
+ )
357
+ query_params.update(
358
+ _BasePermissionServiceRestTransport._BaseTransferOwnership._get_unset_required_fields(
359
+ query_params
360
+ )
361
+ )
362
+
363
+ query_params["$alt"] = "json;enum-encoding=int"
364
+ return query_params
365
+
366
+ class _BaseUpdatePermission:
367
+ def __hash__(self): # pragma: NO COVER
368
+ return NotImplementedError("__hash__ must be implemented.")
369
+
370
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {
371
+ "updateMask": {},
372
+ }
373
+
374
+ @classmethod
375
+ def _get_unset_required_fields(cls, message_dict):
376
+ return {
377
+ k: v
378
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
379
+ if k not in message_dict
380
+ }
381
+
382
+ @staticmethod
383
+ def _get_http_options():
384
+ http_options: List[Dict[str, str]] = [
385
+ {
386
+ "method": "patch",
387
+ "uri": "/v1alpha/{permission.name=tunedModels/*/permissions/*}",
388
+ "body": "permission",
389
+ },
390
+ {
391
+ "method": "patch",
392
+ "uri": "/v1alpha/{permission.name=corpora/*/permissions/*}",
393
+ "body": "permission",
394
+ },
395
+ ]
396
+ return http_options
397
+
398
+ @staticmethod
399
+ def _get_transcoded_request(http_options, request):
400
+ pb_request = permission_service.UpdatePermissionRequest.pb(request)
401
+ transcoded_request = path_template.transcode(http_options, pb_request)
402
+ return transcoded_request
403
+
404
+ @staticmethod
405
+ def _get_request_body_json(transcoded_request):
406
+ # Jsonify the request body
407
+
408
+ body = json_format.MessageToJson(
409
+ transcoded_request["body"], use_integers_for_enums=True
410
+ )
411
+ return body
412
+
413
+ @staticmethod
414
+ def _get_query_params_json(transcoded_request):
415
+ query_params = json.loads(
416
+ json_format.MessageToJson(
417
+ transcoded_request["query_params"],
418
+ use_integers_for_enums=True,
419
+ )
420
+ )
421
+ query_params.update(
422
+ _BasePermissionServiceRestTransport._BaseUpdatePermission._get_unset_required_fields(
423
+ query_params
424
+ )
425
+ )
426
+
427
+ query_params["$alt"] = "json;enum-encoding=int"
428
+ return query_params
429
+
430
+ class _BaseGetOperation:
431
+ def __hash__(self): # pragma: NO COVER
432
+ return NotImplementedError("__hash__ must be implemented.")
433
+
434
+ @staticmethod
435
+ def _get_http_options():
436
+ http_options: List[Dict[str, str]] = [
437
+ {
438
+ "method": "get",
439
+ "uri": "/v1alpha/{name=tunedModels/*/operations/*}",
440
+ },
441
+ {
442
+ "method": "get",
443
+ "uri": "/v1alpha/{name=generatedFiles/*/operations/*}",
444
+ },
445
+ {
446
+ "method": "get",
447
+ "uri": "/v1alpha/{name=models/*/operations/*}",
448
+ },
449
+ ]
450
+ return http_options
451
+
452
+ @staticmethod
453
+ def _get_transcoded_request(http_options, request):
454
+ request_kwargs = json_format.MessageToDict(request)
455
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
456
+ return transcoded_request
457
+
458
+ @staticmethod
459
+ def _get_query_params_json(transcoded_request):
460
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
461
+ return query_params
462
+
463
+ class _BaseListOperations:
464
+ def __hash__(self): # pragma: NO COVER
465
+ return NotImplementedError("__hash__ must be implemented.")
466
+
467
+ @staticmethod
468
+ def _get_http_options():
469
+ http_options: List[Dict[str, str]] = [
470
+ {
471
+ "method": "get",
472
+ "uri": "/v1alpha/{name=tunedModels/*}/operations",
473
+ },
474
+ {
475
+ "method": "get",
476
+ "uri": "/v1alpha/{name=models/*}/operations",
477
+ },
478
+ ]
479
+ return http_options
480
+
481
+ @staticmethod
482
+ def _get_transcoded_request(http_options, request):
483
+ request_kwargs = json_format.MessageToDict(request)
484
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
485
+ return transcoded_request
486
+
487
+ @staticmethod
488
+ def _get_query_params_json(transcoded_request):
489
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
490
+ return query_params
491
+
492
+
493
+ __all__ = ("_BasePermissionServiceRestTransport",)
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/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_v1alpha/services/retriever_service/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (415 Bytes). View file
 
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/retriever_service/__pycache__/async_client.cpython-311.pyc ADDED
Binary file (96.2 kB). View file
 
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/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_v1alpha/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_v1alpha/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_v1alpha/services/retriever_service/pagers.py ADDED
@@ -0,0 +1,509 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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_v1alpha.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_v1alpha.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_v1alpha.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_v1alpha.types.ListCorporaRequest):
78
+ The initial request object.
79
+ response (google.ai.generativelanguage_v1alpha.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_v1alpha.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_v1alpha.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_v1alpha.types.ListCorporaRequest):
154
+ The initial request object.
155
+ response (google.ai.generativelanguage_v1alpha.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_v1alpha.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_v1alpha.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_v1alpha.types.ListDocumentsRequest):
234
+ The initial request object.
235
+ response (google.ai.generativelanguage_v1alpha.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_v1alpha.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_v1alpha.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_v1alpha.types.ListDocumentsRequest):
310
+ The initial request object.
311
+ response (google.ai.generativelanguage_v1alpha.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_v1alpha.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_v1alpha.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_v1alpha.types.ListChunksRequest):
390
+ The initial request object.
391
+ response (google.ai.generativelanguage_v1alpha.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_v1alpha.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_v1alpha.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_v1alpha.types.ListChunksRequest):
466
+ The initial request object.
467
+ response (google.ai.generativelanguage_v1alpha.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_v1alpha/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_v1alpha/services/retriever_service/transports/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (920 Bytes). View file
 
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/retriever_service/transports/__pycache__/base.cpython-311.pyc ADDED
Binary file (18 kB). View file
 
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/retriever_service/transports/__pycache__/grpc.cpython-311.pyc ADDED
Binary file (36.5 kB). View file
 
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/retriever_service/transports/__pycache__/grpc_asyncio.cpython-311.pyc ADDED
Binary file (41.5 kB). View file