koichi12 commited on
Commit
5ddb512
·
verified ·
1 Parent(s): d99afc4

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. .gitattributes +1 -0
  2. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/__pycache__/__init__.cpython-311.pyc +0 -0
  3. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/__pycache__/gapic_version.cpython-311.pyc +0 -0
  4. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/discuss_service/__init__.py +22 -0
  5. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/discuss_service/__pycache__/__init__.cpython-311.pyc +0 -0
  6. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/discuss_service/__pycache__/async_client.cpython-311.pyc +0 -0
  7. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/discuss_service/__pycache__/client.cpython-311.pyc +0 -0
  8. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/discuss_service/async_client.py +740 -0
  9. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/discuss_service/client.py +1128 -0
  10. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/discuss_service/transports/__init__.py +36 -0
  11. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/discuss_service/transports/__pycache__/__init__.cpython-311.pyc +0 -0
  12. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/discuss_service/transports/__pycache__/base.cpython-311.pyc +0 -0
  13. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/discuss_service/transports/__pycache__/grpc.cpython-311.pyc +0 -0
  14. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/discuss_service/transports/__pycache__/grpc_asyncio.cpython-311.pyc +0 -0
  15. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/discuss_service/transports/__pycache__/rest.cpython-311.pyc +0 -0
  16. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/discuss_service/transports/__pycache__/rest_base.cpython-311.pyc +0 -0
  17. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/discuss_service/transports/base.py +213 -0
  18. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/discuss_service/transports/grpc.py +431 -0
  19. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/discuss_service/transports/grpc_asyncio.py +468 -0
  20. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/discuss_service/transports/rest.py +909 -0
  21. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/discuss_service/transports/rest_base.py +268 -0
  22. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/file_service/__init__.py +22 -0
  23. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/file_service/__pycache__/__init__.cpython-311.pyc +0 -0
  24. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/file_service/__pycache__/async_client.cpython-311.pyc +0 -0
  25. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/file_service/__pycache__/client.cpython-311.pyc +0 -0
  26. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/file_service/__pycache__/pagers.cpython-311.pyc +0 -0
  27. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/file_service/async_client.py +780 -0
  28. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/file_service/client.py +1165 -0
  29. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/file_service/pagers.py +197 -0
  30. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/file_service/transports/__init__.py +36 -0
  31. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/file_service/transports/__pycache__/__init__.cpython-311.pyc +0 -0
  32. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/file_service/transports/__pycache__/base.cpython-311.pyc +0 -0
  33. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/file_service/transports/__pycache__/grpc.cpython-311.pyc +0 -0
  34. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/file_service/transports/__pycache__/grpc_asyncio.cpython-311.pyc +0 -0
  35. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/file_service/transports/__pycache__/rest.cpython-311.pyc +0 -0
  36. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/file_service/transports/__pycache__/rest_base.cpython-311.pyc +0 -0
  37. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/file_service/transports/base.py +239 -0
  38. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/file_service/transports/grpc.py +472 -0
  39. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/file_service/transports/grpc_asyncio.py +523 -0
  40. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/file_service/transports/rest.py +1191 -0
  41. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/file_service/transports/rest_base.py +323 -0
  42. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/text_service/__pycache__/__init__.cpython-311.pyc +0 -0
  43. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/text_service/__pycache__/async_client.cpython-311.pyc +0 -0
  44. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/text_service/__pycache__/client.cpython-311.pyc +0 -0
  45. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/text_service/transports/__pycache__/rest_base.cpython-311.pyc +0 -0
  46. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta2/__init__.py +85 -0
  47. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta2/gapic_metadata.json +156 -0
  48. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta2/gapic_version.py +16 -0
  49. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta2/py.typed +2 -0
  50. .venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta2/services/__init__.py +15 -0
.gitattributes CHANGED
@@ -191,3 +191,4 @@ tuning-competition-baseline/.venv/lib/python3.11/site-packages/torch/_inductor/_
191
  .venv/lib/python3.11/site-packages/pillow.libs/libfreetype-be14bf51.so.6.20.1 filter=lfs diff=lfs merge=lfs -text
192
  .venv/lib/python3.11/site-packages/pillow.libs/libpng16-58efbb84.so.16.43.0 filter=lfs diff=lfs merge=lfs -text
193
  .venv/lib/python3.11/site-packages/pillow.libs/libjpeg-77ae51ab.so.62.4.0 filter=lfs diff=lfs merge=lfs -text
 
 
191
  .venv/lib/python3.11/site-packages/pillow.libs/libfreetype-be14bf51.so.6.20.1 filter=lfs diff=lfs merge=lfs -text
192
  .venv/lib/python3.11/site-packages/pillow.libs/libpng16-58efbb84.so.16.43.0 filter=lfs diff=lfs merge=lfs -text
193
  .venv/lib/python3.11/site-packages/pillow.libs/libjpeg-77ae51ab.so.62.4.0 filter=lfs diff=lfs merge=lfs -text
194
+ .venv/lib/python3.11/site-packages/pillow.libs/libharfbuzz-89381d8f.so.0.60850.0 filter=lfs diff=lfs merge=lfs -text
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (9.71 kB). View file
 
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/__pycache__/gapic_version.cpython-311.pyc ADDED
Binary file (237 Bytes). View file
 
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/discuss_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 DiscussServiceAsyncClient
17
+ from .client import DiscussServiceClient
18
+
19
+ __all__ = (
20
+ "DiscussServiceClient",
21
+ "DiscussServiceAsyncClient",
22
+ )
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/discuss_service/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (409 Bytes). View file
 
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/discuss_service/__pycache__/async_client.cpython-311.pyc ADDED
Binary file (31 kB). View file
 
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/discuss_service/__pycache__/client.cpython-311.pyc ADDED
Binary file (47.3 kB). View file
 
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/discuss_service/async_client.py ADDED
@@ -0,0 +1,740 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
48
+ from google.ai.generativelanguage_v1alpha.types import discuss_service, safety
49
+
50
+ from .client import DiscussServiceClient
51
+ from .transports.base import DEFAULT_CLIENT_INFO, DiscussServiceTransport
52
+ from .transports.grpc_asyncio import DiscussServiceGrpcAsyncIOTransport
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
+
64
+ class DiscussServiceAsyncClient:
65
+ """An API for using Generative Language Models (GLMs) in dialog
66
+ applications.
67
+ Also known as large language models (LLMs), this API provides
68
+ models that are trained for multi-turn dialog.
69
+ """
70
+
71
+ _client: DiscussServiceClient
72
+
73
+ # Copy defaults from the synchronous client for use here.
74
+ # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead.
75
+ DEFAULT_ENDPOINT = DiscussServiceClient.DEFAULT_ENDPOINT
76
+ DEFAULT_MTLS_ENDPOINT = DiscussServiceClient.DEFAULT_MTLS_ENDPOINT
77
+ _DEFAULT_ENDPOINT_TEMPLATE = DiscussServiceClient._DEFAULT_ENDPOINT_TEMPLATE
78
+ _DEFAULT_UNIVERSE = DiscussServiceClient._DEFAULT_UNIVERSE
79
+
80
+ model_path = staticmethod(DiscussServiceClient.model_path)
81
+ parse_model_path = staticmethod(DiscussServiceClient.parse_model_path)
82
+ common_billing_account_path = staticmethod(
83
+ DiscussServiceClient.common_billing_account_path
84
+ )
85
+ parse_common_billing_account_path = staticmethod(
86
+ DiscussServiceClient.parse_common_billing_account_path
87
+ )
88
+ common_folder_path = staticmethod(DiscussServiceClient.common_folder_path)
89
+ parse_common_folder_path = staticmethod(
90
+ DiscussServiceClient.parse_common_folder_path
91
+ )
92
+ common_organization_path = staticmethod(
93
+ DiscussServiceClient.common_organization_path
94
+ )
95
+ parse_common_organization_path = staticmethod(
96
+ DiscussServiceClient.parse_common_organization_path
97
+ )
98
+ common_project_path = staticmethod(DiscussServiceClient.common_project_path)
99
+ parse_common_project_path = staticmethod(
100
+ DiscussServiceClient.parse_common_project_path
101
+ )
102
+ common_location_path = staticmethod(DiscussServiceClient.common_location_path)
103
+ parse_common_location_path = staticmethod(
104
+ DiscussServiceClient.parse_common_location_path
105
+ )
106
+
107
+ @classmethod
108
+ def from_service_account_info(cls, info: dict, *args, **kwargs):
109
+ """Creates an instance of this client using the provided credentials
110
+ info.
111
+
112
+ Args:
113
+ info (dict): The service account private key info.
114
+ args: Additional arguments to pass to the constructor.
115
+ kwargs: Additional arguments to pass to the constructor.
116
+
117
+ Returns:
118
+ DiscussServiceAsyncClient: The constructed client.
119
+ """
120
+ return DiscussServiceClient.from_service_account_info.__func__(DiscussServiceAsyncClient, info, *args, **kwargs) # type: ignore
121
+
122
+ @classmethod
123
+ def from_service_account_file(cls, filename: str, *args, **kwargs):
124
+ """Creates an instance of this client using the provided credentials
125
+ file.
126
+
127
+ Args:
128
+ filename (str): The path to the service account private key json
129
+ file.
130
+ args: Additional arguments to pass to the constructor.
131
+ kwargs: Additional arguments to pass to the constructor.
132
+
133
+ Returns:
134
+ DiscussServiceAsyncClient: The constructed client.
135
+ """
136
+ return DiscussServiceClient.from_service_account_file.__func__(DiscussServiceAsyncClient, filename, *args, **kwargs) # type: ignore
137
+
138
+ from_service_account_json = from_service_account_file
139
+
140
+ @classmethod
141
+ def get_mtls_endpoint_and_cert_source(
142
+ cls, client_options: Optional[ClientOptions] = None
143
+ ):
144
+ """Return the API endpoint and client cert source for mutual TLS.
145
+
146
+ The client cert source is determined in the following order:
147
+ (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the
148
+ client cert source is None.
149
+ (2) if `client_options.client_cert_source` is provided, use the provided one; if the
150
+ default client cert source exists, use the default one; otherwise the client cert
151
+ source is None.
152
+
153
+ The API endpoint is determined in the following order:
154
+ (1) if `client_options.api_endpoint` if provided, use the provided one.
155
+ (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the
156
+ default mTLS endpoint; if the environment variable is "never", use the default API
157
+ endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise
158
+ use the default API endpoint.
159
+
160
+ More details can be found at https://google.aip.dev/auth/4114.
161
+
162
+ Args:
163
+ client_options (google.api_core.client_options.ClientOptions): Custom options for the
164
+ client. Only the `api_endpoint` and `client_cert_source` properties may be used
165
+ in this method.
166
+
167
+ Returns:
168
+ Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the
169
+ client cert source to use.
170
+
171
+ Raises:
172
+ google.auth.exceptions.MutualTLSChannelError: If any errors happen.
173
+ """
174
+ return DiscussServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore
175
+
176
+ @property
177
+ def transport(self) -> DiscussServiceTransport:
178
+ """Returns the transport used by the client instance.
179
+
180
+ Returns:
181
+ DiscussServiceTransport: The transport used by the client instance.
182
+ """
183
+ return self._client.transport
184
+
185
+ @property
186
+ def api_endpoint(self):
187
+ """Return the API endpoint used by the client instance.
188
+
189
+ Returns:
190
+ str: The API endpoint used by the client instance.
191
+ """
192
+ return self._client._api_endpoint
193
+
194
+ @property
195
+ def universe_domain(self) -> str:
196
+ """Return the universe domain used by the client instance.
197
+
198
+ Returns:
199
+ str: The universe domain used
200
+ by the client instance.
201
+ """
202
+ return self._client._universe_domain
203
+
204
+ get_transport_class = DiscussServiceClient.get_transport_class
205
+
206
+ def __init__(
207
+ self,
208
+ *,
209
+ credentials: Optional[ga_credentials.Credentials] = None,
210
+ transport: Optional[
211
+ Union[str, DiscussServiceTransport, Callable[..., DiscussServiceTransport]]
212
+ ] = "grpc_asyncio",
213
+ client_options: Optional[ClientOptions] = None,
214
+ client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
215
+ ) -> None:
216
+ """Instantiates the discuss service async client.
217
+
218
+ Args:
219
+ credentials (Optional[google.auth.credentials.Credentials]): The
220
+ authorization credentials to attach to requests. These
221
+ credentials identify the application to the service; if none
222
+ are specified, the client will attempt to ascertain the
223
+ credentials from the environment.
224
+ transport (Optional[Union[str,DiscussServiceTransport,Callable[..., DiscussServiceTransport]]]):
225
+ The transport to use, or a Callable that constructs and returns a new transport to use.
226
+ If a Callable is given, it will be called with the same set of initialization
227
+ arguments as used in the DiscussServiceTransport constructor.
228
+ If set to None, a transport is chosen automatically.
229
+ client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]):
230
+ Custom options for the client.
231
+
232
+ 1. The ``api_endpoint`` property can be used to override the
233
+ default endpoint provided by the client when ``transport`` is
234
+ not explicitly provided. Only if this property is not set and
235
+ ``transport`` was not explicitly provided, the endpoint is
236
+ determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment
237
+ variable, which have one of the following values:
238
+ "always" (always use the default mTLS endpoint), "never" (always
239
+ use the default regular endpoint) and "auto" (auto-switch to the
240
+ default mTLS endpoint if client certificate is present; this is
241
+ the default value).
242
+
243
+ 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable
244
+ is "true", then the ``client_cert_source`` property can be used
245
+ to provide a client certificate for mTLS transport. If
246
+ not provided, the default SSL client certificate will be used if
247
+ present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not
248
+ set, no client certificate will be used.
249
+
250
+ 3. The ``universe_domain`` property can be used to override the
251
+ default "googleapis.com" universe. Note that ``api_endpoint``
252
+ property still takes precedence; and ``universe_domain`` is
253
+ currently not supported for mTLS.
254
+
255
+ client_info (google.api_core.gapic_v1.client_info.ClientInfo):
256
+ The client info used to send a user-agent string along with
257
+ API requests. If ``None``, then default info will be used.
258
+ Generally, you only need to set this if you're developing
259
+ your own client library.
260
+
261
+ Raises:
262
+ google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
263
+ creation failed for any reason.
264
+ """
265
+ self._client = DiscussServiceClient(
266
+ credentials=credentials,
267
+ transport=transport,
268
+ client_options=client_options,
269
+ client_info=client_info,
270
+ )
271
+
272
+ if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
273
+ std_logging.DEBUG
274
+ ): # pragma: NO COVER
275
+ _LOGGER.debug(
276
+ "Created client `google.ai.generativelanguage_v1alpha.DiscussServiceAsyncClient`.",
277
+ extra={
278
+ "serviceName": "google.ai.generativelanguage.v1alpha.DiscussService",
279
+ "universeDomain": getattr(
280
+ self._client._transport._credentials, "universe_domain", ""
281
+ ),
282
+ "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}",
283
+ "credentialsInfo": getattr(
284
+ self.transport._credentials, "get_cred_info", lambda: None
285
+ )(),
286
+ }
287
+ if hasattr(self._client._transport, "_credentials")
288
+ else {
289
+ "serviceName": "google.ai.generativelanguage.v1alpha.DiscussService",
290
+ "credentialsType": None,
291
+ },
292
+ )
293
+
294
+ async def generate_message(
295
+ self,
296
+ request: Optional[Union[discuss_service.GenerateMessageRequest, dict]] = None,
297
+ *,
298
+ model: Optional[str] = None,
299
+ prompt: Optional[discuss_service.MessagePrompt] = None,
300
+ temperature: Optional[float] = None,
301
+ candidate_count: Optional[int] = None,
302
+ top_p: Optional[float] = None,
303
+ top_k: Optional[int] = None,
304
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
305
+ timeout: Union[float, object] = gapic_v1.method.DEFAULT,
306
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
307
+ ) -> discuss_service.GenerateMessageResponse:
308
+ r"""Generates a response from the model given an input
309
+ ``MessagePrompt``.
310
+
311
+ .. code-block:: python
312
+
313
+ # This snippet has been automatically generated and should be regarded as a
314
+ # code template only.
315
+ # It will require modifications to work:
316
+ # - It may require correct/in-range values for request initialization.
317
+ # - It may require specifying regional endpoints when creating the service
318
+ # client as shown in:
319
+ # https://googleapis.dev/python/google-api-core/latest/client_options.html
320
+ from google.ai import generativelanguage_v1alpha
321
+
322
+ async def sample_generate_message():
323
+ # Create a client
324
+ client = generativelanguage_v1alpha.DiscussServiceAsyncClient()
325
+
326
+ # Initialize request argument(s)
327
+ prompt = generativelanguage_v1alpha.MessagePrompt()
328
+ prompt.messages.content = "content_value"
329
+
330
+ request = generativelanguage_v1alpha.GenerateMessageRequest(
331
+ model="model_value",
332
+ prompt=prompt,
333
+ )
334
+
335
+ # Make the request
336
+ response = await client.generate_message(request=request)
337
+
338
+ # Handle the response
339
+ print(response)
340
+
341
+ Args:
342
+ request (Optional[Union[google.ai.generativelanguage_v1alpha.types.GenerateMessageRequest, dict]]):
343
+ The request object. Request to generate a message
344
+ response from the model.
345
+ model (:class:`str`):
346
+ Required. The name of the model to use.
347
+
348
+ Format: ``name=models/{model}``.
349
+
350
+ This corresponds to the ``model`` field
351
+ on the ``request`` instance; if ``request`` is provided, this
352
+ should not be set.
353
+ prompt (:class:`google.ai.generativelanguage_v1alpha.types.MessagePrompt`):
354
+ Required. The structured textual
355
+ input given to the model as a prompt.
356
+ Given a
357
+ prompt, the model will return what it
358
+ predicts is the next message in the
359
+ discussion.
360
+
361
+ This corresponds to the ``prompt`` field
362
+ on the ``request`` instance; if ``request`` is provided, this
363
+ should not be set.
364
+ temperature (:class:`float`):
365
+ Optional. Controls the randomness of the output.
366
+
367
+ Values can range over ``[0.0,1.0]``, inclusive. A value
368
+ closer to ``1.0`` will produce responses that are more
369
+ varied, while a value closer to ``0.0`` will typically
370
+ result in less surprising responses from the model.
371
+
372
+ This corresponds to the ``temperature`` field
373
+ on the ``request`` instance; if ``request`` is provided, this
374
+ should not be set.
375
+ candidate_count (:class:`int`):
376
+ Optional. The number of generated response messages to
377
+ return.
378
+
379
+ This value must be between ``[1, 8]``, inclusive. If
380
+ unset, this will default to ``1``.
381
+
382
+ This corresponds to the ``candidate_count`` field
383
+ on the ``request`` instance; if ``request`` is provided, this
384
+ should not be set.
385
+ top_p (:class:`float`):
386
+ Optional. The maximum cumulative probability of tokens
387
+ to consider when sampling.
388
+
389
+ The model uses combined Top-k and nucleus sampling.
390
+
391
+ Nucleus sampling considers the smallest set of tokens
392
+ whose probability sum is at least ``top_p``.
393
+
394
+ This corresponds to the ``top_p`` field
395
+ on the ``request`` instance; if ``request`` is provided, this
396
+ should not be set.
397
+ top_k (:class:`int`):
398
+ Optional. The maximum number of tokens to consider when
399
+ sampling.
400
+
401
+ The model uses combined Top-k and nucleus sampling.
402
+
403
+ Top-k sampling considers the set of ``top_k`` most
404
+ probable tokens.
405
+
406
+ This corresponds to the ``top_k`` field
407
+ on the ``request`` instance; if ``request`` is provided, this
408
+ should not be set.
409
+ retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any,
410
+ should be retried.
411
+ timeout (float): The timeout for this request.
412
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
413
+ sent along with the request as metadata. Normally, each value must be of type `str`,
414
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
415
+ be of type `bytes`.
416
+
417
+ Returns:
418
+ google.ai.generativelanguage_v1alpha.types.GenerateMessageResponse:
419
+ The response from the model.
420
+
421
+ This includes candidate messages and
422
+ conversation history in the form of
423
+ chronologically-ordered messages.
424
+
425
+ """
426
+ # Create or coerce a protobuf request object.
427
+ # - Quick check: If we got a request object, we should *not* have
428
+ # gotten any keyword arguments that map to the request.
429
+ has_flattened_params = any(
430
+ [model, prompt, temperature, candidate_count, top_p, top_k]
431
+ )
432
+ if request is not None and has_flattened_params:
433
+ raise ValueError(
434
+ "If the `request` argument is set, then none of "
435
+ "the individual field arguments should be set."
436
+ )
437
+
438
+ # - Use the request object if provided (there's no risk of modifying the input as
439
+ # there are no flattened fields), or create one.
440
+ if not isinstance(request, discuss_service.GenerateMessageRequest):
441
+ request = discuss_service.GenerateMessageRequest(request)
442
+
443
+ # If we have keyword arguments corresponding to fields on the
444
+ # request, apply these.
445
+ if model is not None:
446
+ request.model = model
447
+ if prompt is not None:
448
+ request.prompt = prompt
449
+ if temperature is not None:
450
+ request.temperature = temperature
451
+ if candidate_count is not None:
452
+ request.candidate_count = candidate_count
453
+ if top_p is not None:
454
+ request.top_p = top_p
455
+ if top_k is not None:
456
+ request.top_k = top_k
457
+
458
+ # Wrap the RPC method; this adds retry and timeout information,
459
+ # and friendly error handling.
460
+ rpc = self._client._transport._wrapped_methods[
461
+ self._client._transport.generate_message
462
+ ]
463
+
464
+ # Certain fields should be provided within the metadata header;
465
+ # add these here.
466
+ metadata = tuple(metadata) + (
467
+ gapic_v1.routing_header.to_grpc_metadata((("model", request.model),)),
468
+ )
469
+
470
+ # Validate the universe domain.
471
+ self._client._validate_universe_domain()
472
+
473
+ # Send the request.
474
+ response = await rpc(
475
+ request,
476
+ retry=retry,
477
+ timeout=timeout,
478
+ metadata=metadata,
479
+ )
480
+
481
+ # Done; return the response.
482
+ return response
483
+
484
+ async def count_message_tokens(
485
+ self,
486
+ request: Optional[
487
+ Union[discuss_service.CountMessageTokensRequest, dict]
488
+ ] = None,
489
+ *,
490
+ model: Optional[str] = None,
491
+ prompt: Optional[discuss_service.MessagePrompt] = None,
492
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
493
+ timeout: Union[float, object] = gapic_v1.method.DEFAULT,
494
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
495
+ ) -> discuss_service.CountMessageTokensResponse:
496
+ r"""Runs a model's tokenizer on a string and returns the
497
+ token count.
498
+
499
+ .. code-block:: python
500
+
501
+ # This snippet has been automatically generated and should be regarded as a
502
+ # code template only.
503
+ # It will require modifications to work:
504
+ # - It may require correct/in-range values for request initialization.
505
+ # - It may require specifying regional endpoints when creating the service
506
+ # client as shown in:
507
+ # https://googleapis.dev/python/google-api-core/latest/client_options.html
508
+ from google.ai import generativelanguage_v1alpha
509
+
510
+ async def sample_count_message_tokens():
511
+ # Create a client
512
+ client = generativelanguage_v1alpha.DiscussServiceAsyncClient()
513
+
514
+ # Initialize request argument(s)
515
+ prompt = generativelanguage_v1alpha.MessagePrompt()
516
+ prompt.messages.content = "content_value"
517
+
518
+ request = generativelanguage_v1alpha.CountMessageTokensRequest(
519
+ model="model_value",
520
+ prompt=prompt,
521
+ )
522
+
523
+ # Make the request
524
+ response = await client.count_message_tokens(request=request)
525
+
526
+ # Handle the response
527
+ print(response)
528
+
529
+ Args:
530
+ request (Optional[Union[google.ai.generativelanguage_v1alpha.types.CountMessageTokensRequest, dict]]):
531
+ The request object. Counts the number of tokens in the ``prompt`` sent to a
532
+ model.
533
+
534
+ Models may tokenize text differently, so each model may
535
+ return a different ``token_count``.
536
+ model (:class:`str`):
537
+ Required. The model's resource name. This serves as an
538
+ ID for the Model to use.
539
+
540
+ This name should match a model name returned by the
541
+ ``ListModels`` method.
542
+
543
+ Format: ``models/{model}``
544
+
545
+ This corresponds to the ``model`` field
546
+ on the ``request`` instance; if ``request`` is provided, this
547
+ should not be set.
548
+ prompt (:class:`google.ai.generativelanguage_v1alpha.types.MessagePrompt`):
549
+ Required. The prompt, whose token
550
+ count is to be returned.
551
+
552
+ This corresponds to the ``prompt`` field
553
+ on the ``request`` instance; if ``request`` is provided, this
554
+ should not be set.
555
+ retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any,
556
+ should be retried.
557
+ timeout (float): The timeout for this request.
558
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
559
+ sent along with the request as metadata. Normally, each value must be of type `str`,
560
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
561
+ be of type `bytes`.
562
+
563
+ Returns:
564
+ google.ai.generativelanguage_v1alpha.types.CountMessageTokensResponse:
565
+ A response from CountMessageTokens.
566
+
567
+ It returns the model's token_count for the prompt.
568
+
569
+ """
570
+ # Create or coerce a protobuf request object.
571
+ # - Quick check: If we got a request object, we should *not* have
572
+ # gotten any keyword arguments that map to the request.
573
+ has_flattened_params = any([model, prompt])
574
+ if request is not None and has_flattened_params:
575
+ raise ValueError(
576
+ "If the `request` argument is set, then none of "
577
+ "the individual field arguments should be set."
578
+ )
579
+
580
+ # - Use the request object if provided (there's no risk of modifying the input as
581
+ # there are no flattened fields), or create one.
582
+ if not isinstance(request, discuss_service.CountMessageTokensRequest):
583
+ request = discuss_service.CountMessageTokensRequest(request)
584
+
585
+ # If we have keyword arguments corresponding to fields on the
586
+ # request, apply these.
587
+ if model is not None:
588
+ request.model = model
589
+ if prompt is not None:
590
+ request.prompt = prompt
591
+
592
+ # Wrap the RPC method; this adds retry and timeout information,
593
+ # and friendly error handling.
594
+ rpc = self._client._transport._wrapped_methods[
595
+ self._client._transport.count_message_tokens
596
+ ]
597
+
598
+ # Certain fields should be provided within the metadata header;
599
+ # add these here.
600
+ metadata = tuple(metadata) + (
601
+ gapic_v1.routing_header.to_grpc_metadata((("model", request.model),)),
602
+ )
603
+
604
+ # Validate the universe domain.
605
+ self._client._validate_universe_domain()
606
+
607
+ # Send the request.
608
+ response = await rpc(
609
+ request,
610
+ retry=retry,
611
+ timeout=timeout,
612
+ metadata=metadata,
613
+ )
614
+
615
+ # Done; return the response.
616
+ return response
617
+
618
+ async def list_operations(
619
+ self,
620
+ request: Optional[operations_pb2.ListOperationsRequest] = None,
621
+ *,
622
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
623
+ timeout: Union[float, object] = gapic_v1.method.DEFAULT,
624
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
625
+ ) -> operations_pb2.ListOperationsResponse:
626
+ r"""Lists operations that match the specified filter in the request.
627
+
628
+ Args:
629
+ request (:class:`~.operations_pb2.ListOperationsRequest`):
630
+ The request object. Request message for
631
+ `ListOperations` method.
632
+ retry (google.api_core.retry_async.AsyncRetry): Designation of what errors,
633
+ if any, should be retried.
634
+ timeout (float): The timeout for this request.
635
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
636
+ sent along with the request as metadata. Normally, each value must be of type `str`,
637
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
638
+ be of type `bytes`.
639
+ Returns:
640
+ ~.operations_pb2.ListOperationsResponse:
641
+ Response message for ``ListOperations`` method.
642
+ """
643
+ # Create or coerce a protobuf request object.
644
+ # The request isn't a proto-plus wrapped type,
645
+ # so it must be constructed via keyword expansion.
646
+ if isinstance(request, dict):
647
+ request = operations_pb2.ListOperationsRequest(**request)
648
+
649
+ # Wrap the RPC method; this adds retry and timeout information,
650
+ # and friendly error handling.
651
+ rpc = self.transport._wrapped_methods[self._client._transport.list_operations]
652
+
653
+ # Certain fields should be provided within the metadata header;
654
+ # add these here.
655
+ metadata = tuple(metadata) + (
656
+ gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
657
+ )
658
+
659
+ # Validate the universe domain.
660
+ self._client._validate_universe_domain()
661
+
662
+ # Send the request.
663
+ response = await rpc(
664
+ request,
665
+ retry=retry,
666
+ timeout=timeout,
667
+ metadata=metadata,
668
+ )
669
+
670
+ # Done; return the response.
671
+ return response
672
+
673
+ async def get_operation(
674
+ self,
675
+ request: Optional[operations_pb2.GetOperationRequest] = None,
676
+ *,
677
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
678
+ timeout: Union[float, object] = gapic_v1.method.DEFAULT,
679
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
680
+ ) -> operations_pb2.Operation:
681
+ r"""Gets the latest state of a long-running operation.
682
+
683
+ Args:
684
+ request (:class:`~.operations_pb2.GetOperationRequest`):
685
+ The request object. Request message for
686
+ `GetOperation` method.
687
+ retry (google.api_core.retry_async.AsyncRetry): Designation of what errors,
688
+ if any, should be retried.
689
+ timeout (float): The timeout for this request.
690
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
691
+ sent along with the request as metadata. Normally, each value must be of type `str`,
692
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
693
+ be of type `bytes`.
694
+ Returns:
695
+ ~.operations_pb2.Operation:
696
+ An ``Operation`` object.
697
+ """
698
+ # Create or coerce a protobuf request object.
699
+ # The request isn't a proto-plus wrapped type,
700
+ # so it must be constructed via keyword expansion.
701
+ if isinstance(request, dict):
702
+ request = operations_pb2.GetOperationRequest(**request)
703
+
704
+ # Wrap the RPC method; this adds retry and timeout information,
705
+ # and friendly error handling.
706
+ rpc = self.transport._wrapped_methods[self._client._transport.get_operation]
707
+
708
+ # Certain fields should be provided within the metadata header;
709
+ # add these here.
710
+ metadata = tuple(metadata) + (
711
+ gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
712
+ )
713
+
714
+ # Validate the universe domain.
715
+ self._client._validate_universe_domain()
716
+
717
+ # Send the request.
718
+ response = await rpc(
719
+ request,
720
+ retry=retry,
721
+ timeout=timeout,
722
+ metadata=metadata,
723
+ )
724
+
725
+ # Done; return the response.
726
+ return response
727
+
728
+ async def __aenter__(self) -> "DiscussServiceAsyncClient":
729
+ return self
730
+
731
+ async def __aexit__(self, exc_type, exc, tb):
732
+ await self.transport.close()
733
+
734
+
735
+ DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
736
+ gapic_version=package_version.__version__
737
+ )
738
+
739
+
740
+ __all__ = ("DiscussServiceAsyncClient",)
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/discuss_service/client.py ADDED
@@ -0,0 +1,1128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
63
+ from google.ai.generativelanguage_v1alpha.types import discuss_service, safety
64
+
65
+ from .transports.base import DEFAULT_CLIENT_INFO, DiscussServiceTransport
66
+ from .transports.grpc import DiscussServiceGrpcTransport
67
+ from .transports.grpc_asyncio import DiscussServiceGrpcAsyncIOTransport
68
+ from .transports.rest import DiscussServiceRestTransport
69
+
70
+
71
+ class DiscussServiceClientMeta(type):
72
+ """Metaclass for the DiscussService client.
73
+
74
+ This provides class-level methods for building and retrieving
75
+ support objects (e.g. transport) without polluting the client instance
76
+ objects.
77
+ """
78
+
79
+ _transport_registry = (
80
+ OrderedDict()
81
+ ) # type: Dict[str, Type[DiscussServiceTransport]]
82
+ _transport_registry["grpc"] = DiscussServiceGrpcTransport
83
+ _transport_registry["grpc_asyncio"] = DiscussServiceGrpcAsyncIOTransport
84
+ _transport_registry["rest"] = DiscussServiceRestTransport
85
+
86
+ def get_transport_class(
87
+ cls,
88
+ label: Optional[str] = None,
89
+ ) -> Type[DiscussServiceTransport]:
90
+ """Returns an appropriate transport class.
91
+
92
+ Args:
93
+ label: The name of the desired transport. If none is
94
+ provided, then the first transport in the registry is used.
95
+
96
+ Returns:
97
+ The transport class to use.
98
+ """
99
+ # If a specific transport is requested, return that one.
100
+ if label:
101
+ return cls._transport_registry[label]
102
+
103
+ # No transport is requested; return the default (that is, the first one
104
+ # in the dictionary).
105
+ return next(iter(cls._transport_registry.values()))
106
+
107
+
108
+ class DiscussServiceClient(metaclass=DiscussServiceClientMeta):
109
+ """An API for using Generative Language Models (GLMs) in dialog
110
+ applications.
111
+ Also known as large language models (LLMs), this API provides
112
+ models that are trained for multi-turn dialog.
113
+ """
114
+
115
+ @staticmethod
116
+ def _get_default_mtls_endpoint(api_endpoint):
117
+ """Converts api endpoint to mTLS endpoint.
118
+
119
+ Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to
120
+ "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively.
121
+ Args:
122
+ api_endpoint (Optional[str]): the api endpoint to convert.
123
+ Returns:
124
+ str: converted mTLS api endpoint.
125
+ """
126
+ if not api_endpoint:
127
+ return api_endpoint
128
+
129
+ mtls_endpoint_re = re.compile(
130
+ r"(?P<name>[^.]+)(?P<mtls>\.mtls)?(?P<sandbox>\.sandbox)?(?P<googledomain>\.googleapis\.com)?"
131
+ )
132
+
133
+ m = mtls_endpoint_re.match(api_endpoint)
134
+ name, mtls, sandbox, googledomain = m.groups()
135
+ if mtls or not googledomain:
136
+ return api_endpoint
137
+
138
+ if sandbox:
139
+ return api_endpoint.replace(
140
+ "sandbox.googleapis.com", "mtls.sandbox.googleapis.com"
141
+ )
142
+
143
+ return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com")
144
+
145
+ # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead.
146
+ DEFAULT_ENDPOINT = "generativelanguage.googleapis.com"
147
+ DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore
148
+ DEFAULT_ENDPOINT
149
+ )
150
+
151
+ _DEFAULT_ENDPOINT_TEMPLATE = "generativelanguage.{UNIVERSE_DOMAIN}"
152
+ _DEFAULT_UNIVERSE = "googleapis.com"
153
+
154
+ @classmethod
155
+ def from_service_account_info(cls, info: dict, *args, **kwargs):
156
+ """Creates an instance of this client using the provided credentials
157
+ info.
158
+
159
+ Args:
160
+ info (dict): The service account private key info.
161
+ args: Additional arguments to pass to the constructor.
162
+ kwargs: Additional arguments to pass to the constructor.
163
+
164
+ Returns:
165
+ DiscussServiceClient: The constructed client.
166
+ """
167
+ credentials = service_account.Credentials.from_service_account_info(info)
168
+ kwargs["credentials"] = credentials
169
+ return cls(*args, **kwargs)
170
+
171
+ @classmethod
172
+ def from_service_account_file(cls, filename: str, *args, **kwargs):
173
+ """Creates an instance of this client using the provided credentials
174
+ file.
175
+
176
+ Args:
177
+ filename (str): The path to the service account private key json
178
+ file.
179
+ args: Additional arguments to pass to the constructor.
180
+ kwargs: Additional arguments to pass to the constructor.
181
+
182
+ Returns:
183
+ DiscussServiceClient: The constructed client.
184
+ """
185
+ credentials = service_account.Credentials.from_service_account_file(filename)
186
+ kwargs["credentials"] = credentials
187
+ return cls(*args, **kwargs)
188
+
189
+ from_service_account_json = from_service_account_file
190
+
191
+ @property
192
+ def transport(self) -> DiscussServiceTransport:
193
+ """Returns the transport used by the client instance.
194
+
195
+ Returns:
196
+ DiscussServiceTransport: The transport used by the client
197
+ instance.
198
+ """
199
+ return self._transport
200
+
201
+ @staticmethod
202
+ def model_path(
203
+ model: str,
204
+ ) -> str:
205
+ """Returns a fully-qualified model string."""
206
+ return "models/{model}".format(
207
+ model=model,
208
+ )
209
+
210
+ @staticmethod
211
+ def parse_model_path(path: str) -> Dict[str, str]:
212
+ """Parses a model path into its component segments."""
213
+ m = re.match(r"^models/(?P<model>.+?)$", path)
214
+ return m.groupdict() if m else {}
215
+
216
+ @staticmethod
217
+ def common_billing_account_path(
218
+ billing_account: str,
219
+ ) -> str:
220
+ """Returns a fully-qualified billing_account string."""
221
+ return "billingAccounts/{billing_account}".format(
222
+ billing_account=billing_account,
223
+ )
224
+
225
+ @staticmethod
226
+ def parse_common_billing_account_path(path: str) -> Dict[str, str]:
227
+ """Parse a billing_account path into its component segments."""
228
+ m = re.match(r"^billingAccounts/(?P<billing_account>.+?)$", path)
229
+ return m.groupdict() if m else {}
230
+
231
+ @staticmethod
232
+ def common_folder_path(
233
+ folder: str,
234
+ ) -> str:
235
+ """Returns a fully-qualified folder string."""
236
+ return "folders/{folder}".format(
237
+ folder=folder,
238
+ )
239
+
240
+ @staticmethod
241
+ def parse_common_folder_path(path: str) -> Dict[str, str]:
242
+ """Parse a folder path into its component segments."""
243
+ m = re.match(r"^folders/(?P<folder>.+?)$", path)
244
+ return m.groupdict() if m else {}
245
+
246
+ @staticmethod
247
+ def common_organization_path(
248
+ organization: str,
249
+ ) -> str:
250
+ """Returns a fully-qualified organization string."""
251
+ return "organizations/{organization}".format(
252
+ organization=organization,
253
+ )
254
+
255
+ @staticmethod
256
+ def parse_common_organization_path(path: str) -> Dict[str, str]:
257
+ """Parse a organization path into its component segments."""
258
+ m = re.match(r"^organizations/(?P<organization>.+?)$", path)
259
+ return m.groupdict() if m else {}
260
+
261
+ @staticmethod
262
+ def common_project_path(
263
+ project: str,
264
+ ) -> str:
265
+ """Returns a fully-qualified project string."""
266
+ return "projects/{project}".format(
267
+ project=project,
268
+ )
269
+
270
+ @staticmethod
271
+ def parse_common_project_path(path: str) -> Dict[str, str]:
272
+ """Parse a project path into its component segments."""
273
+ m = re.match(r"^projects/(?P<project>.+?)$", path)
274
+ return m.groupdict() if m else {}
275
+
276
+ @staticmethod
277
+ def common_location_path(
278
+ project: str,
279
+ location: str,
280
+ ) -> str:
281
+ """Returns a fully-qualified location string."""
282
+ return "projects/{project}/locations/{location}".format(
283
+ project=project,
284
+ location=location,
285
+ )
286
+
287
+ @staticmethod
288
+ def parse_common_location_path(path: str) -> Dict[str, str]:
289
+ """Parse a location path into its component segments."""
290
+ m = re.match(r"^projects/(?P<project>.+?)/locations/(?P<location>.+?)$", path)
291
+ return m.groupdict() if m else {}
292
+
293
+ @classmethod
294
+ def get_mtls_endpoint_and_cert_source(
295
+ cls, client_options: Optional[client_options_lib.ClientOptions] = None
296
+ ):
297
+ """Deprecated. Return the API endpoint and client cert source for mutual TLS.
298
+
299
+ The client cert source is determined in the following order:
300
+ (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the
301
+ client cert source is None.
302
+ (2) if `client_options.client_cert_source` is provided, use the provided one; if the
303
+ default client cert source exists, use the default one; otherwise the client cert
304
+ source is None.
305
+
306
+ The API endpoint is determined in the following order:
307
+ (1) if `client_options.api_endpoint` if provided, use the provided one.
308
+ (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the
309
+ default mTLS endpoint; if the environment variable is "never", use the default API
310
+ endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise
311
+ use the default API endpoint.
312
+
313
+ More details can be found at https://google.aip.dev/auth/4114.
314
+
315
+ Args:
316
+ client_options (google.api_core.client_options.ClientOptions): Custom options for the
317
+ client. Only the `api_endpoint` and `client_cert_source` properties may be used
318
+ in this method.
319
+
320
+ Returns:
321
+ Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the
322
+ client cert source to use.
323
+
324
+ Raises:
325
+ google.auth.exceptions.MutualTLSChannelError: If any errors happen.
326
+ """
327
+
328
+ warnings.warn(
329
+ "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.",
330
+ DeprecationWarning,
331
+ )
332
+ if client_options is None:
333
+ client_options = client_options_lib.ClientOptions()
334
+ use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false")
335
+ use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto")
336
+ if use_client_cert not in ("true", "false"):
337
+ raise ValueError(
338
+ "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`"
339
+ )
340
+ if use_mtls_endpoint not in ("auto", "never", "always"):
341
+ raise MutualTLSChannelError(
342
+ "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`"
343
+ )
344
+
345
+ # Figure out the client cert source to use.
346
+ client_cert_source = None
347
+ if use_client_cert == "true":
348
+ if client_options.client_cert_source:
349
+ client_cert_source = client_options.client_cert_source
350
+ elif mtls.has_default_client_cert_source():
351
+ client_cert_source = mtls.default_client_cert_source()
352
+
353
+ # Figure out which api endpoint to use.
354
+ if client_options.api_endpoint is not None:
355
+ api_endpoint = client_options.api_endpoint
356
+ elif use_mtls_endpoint == "always" or (
357
+ use_mtls_endpoint == "auto" and client_cert_source
358
+ ):
359
+ api_endpoint = cls.DEFAULT_MTLS_ENDPOINT
360
+ else:
361
+ api_endpoint = cls.DEFAULT_ENDPOINT
362
+
363
+ return api_endpoint, client_cert_source
364
+
365
+ @staticmethod
366
+ def _read_environment_variables():
367
+ """Returns the environment variables used by the client.
368
+
369
+ Returns:
370
+ Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE,
371
+ GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables.
372
+
373
+ Raises:
374
+ ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not
375
+ any of ["true", "false"].
376
+ google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT
377
+ is not any of ["auto", "never", "always"].
378
+ """
379
+ use_client_cert = os.getenv(
380
+ "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"
381
+ ).lower()
382
+ use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower()
383
+ universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN")
384
+ if use_client_cert not in ("true", "false"):
385
+ raise ValueError(
386
+ "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`"
387
+ )
388
+ if use_mtls_endpoint not in ("auto", "never", "always"):
389
+ raise MutualTLSChannelError(
390
+ "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`"
391
+ )
392
+ return use_client_cert == "true", use_mtls_endpoint, universe_domain_env
393
+
394
+ @staticmethod
395
+ def _get_client_cert_source(provided_cert_source, use_cert_flag):
396
+ """Return the client cert source to be used by the client.
397
+
398
+ Args:
399
+ provided_cert_source (bytes): The client certificate source provided.
400
+ use_cert_flag (bool): A flag indicating whether to use the client certificate.
401
+
402
+ Returns:
403
+ bytes or None: The client cert source to be used by the client.
404
+ """
405
+ client_cert_source = None
406
+ if use_cert_flag:
407
+ if provided_cert_source:
408
+ client_cert_source = provided_cert_source
409
+ elif mtls.has_default_client_cert_source():
410
+ client_cert_source = mtls.default_client_cert_source()
411
+ return client_cert_source
412
+
413
+ @staticmethod
414
+ def _get_api_endpoint(
415
+ api_override, client_cert_source, universe_domain, use_mtls_endpoint
416
+ ):
417
+ """Return the API endpoint used by the client.
418
+
419
+ Args:
420
+ api_override (str): The API endpoint override. If specified, this is always
421
+ the return value of this function and the other arguments are not used.
422
+ client_cert_source (bytes): The client certificate source used by the client.
423
+ universe_domain (str): The universe domain used by the client.
424
+ use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters.
425
+ Possible values are "always", "auto", or "never".
426
+
427
+ Returns:
428
+ str: The API endpoint to be used by the client.
429
+ """
430
+ if api_override is not None:
431
+ api_endpoint = api_override
432
+ elif use_mtls_endpoint == "always" or (
433
+ use_mtls_endpoint == "auto" and client_cert_source
434
+ ):
435
+ _default_universe = DiscussServiceClient._DEFAULT_UNIVERSE
436
+ if universe_domain != _default_universe:
437
+ raise MutualTLSChannelError(
438
+ f"mTLS is not supported in any universe other than {_default_universe}."
439
+ )
440
+ api_endpoint = DiscussServiceClient.DEFAULT_MTLS_ENDPOINT
441
+ else:
442
+ api_endpoint = DiscussServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(
443
+ UNIVERSE_DOMAIN=universe_domain
444
+ )
445
+ return api_endpoint
446
+
447
+ @staticmethod
448
+ def _get_universe_domain(
449
+ client_universe_domain: Optional[str], universe_domain_env: Optional[str]
450
+ ) -> str:
451
+ """Return the universe domain used by the client.
452
+
453
+ Args:
454
+ client_universe_domain (Optional[str]): The universe domain configured via the client options.
455
+ universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable.
456
+
457
+ Returns:
458
+ str: The universe domain to be used by the client.
459
+
460
+ Raises:
461
+ ValueError: If the universe domain is an empty string.
462
+ """
463
+ universe_domain = DiscussServiceClient._DEFAULT_UNIVERSE
464
+ if client_universe_domain is not None:
465
+ universe_domain = client_universe_domain
466
+ elif universe_domain_env is not None:
467
+ universe_domain = universe_domain_env
468
+ if len(universe_domain.strip()) == 0:
469
+ raise ValueError("Universe Domain cannot be an empty string.")
470
+ return universe_domain
471
+
472
+ def _validate_universe_domain(self):
473
+ """Validates client's and credentials' universe domains are consistent.
474
+
475
+ Returns:
476
+ bool: True iff the configured universe domain is valid.
477
+
478
+ Raises:
479
+ ValueError: If the configured universe domain is not valid.
480
+ """
481
+
482
+ # NOTE (b/349488459): universe validation is disabled until further notice.
483
+ return True
484
+
485
+ @property
486
+ def api_endpoint(self):
487
+ """Return the API endpoint used by the client instance.
488
+
489
+ Returns:
490
+ str: The API endpoint used by the client instance.
491
+ """
492
+ return self._api_endpoint
493
+
494
+ @property
495
+ def universe_domain(self) -> str:
496
+ """Return the universe domain used by the client instance.
497
+
498
+ Returns:
499
+ str: The universe domain used by the client instance.
500
+ """
501
+ return self._universe_domain
502
+
503
+ def __init__(
504
+ self,
505
+ *,
506
+ credentials: Optional[ga_credentials.Credentials] = None,
507
+ transport: Optional[
508
+ Union[str, DiscussServiceTransport, Callable[..., DiscussServiceTransport]]
509
+ ] = None,
510
+ client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None,
511
+ client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
512
+ ) -> None:
513
+ """Instantiates the discuss service client.
514
+
515
+ Args:
516
+ credentials (Optional[google.auth.credentials.Credentials]): The
517
+ authorization credentials to attach to requests. These
518
+ credentials identify the application to the service; if none
519
+ are specified, the client will attempt to ascertain the
520
+ credentials from the environment.
521
+ transport (Optional[Union[str,DiscussServiceTransport,Callable[..., DiscussServiceTransport]]]):
522
+ The transport to use, or a Callable that constructs and returns a new transport.
523
+ If a Callable is given, it will be called with the same set of initialization
524
+ arguments as used in the DiscussServiceTransport constructor.
525
+ If set to None, a transport is chosen automatically.
526
+ client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]):
527
+ Custom options for the client.
528
+
529
+ 1. The ``api_endpoint`` property can be used to override the
530
+ default endpoint provided by the client when ``transport`` is
531
+ not explicitly provided. Only if this property is not set and
532
+ ``transport`` was not explicitly provided, the endpoint is
533
+ determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment
534
+ variable, which have one of the following values:
535
+ "always" (always use the default mTLS endpoint), "never" (always
536
+ use the default regular endpoint) and "auto" (auto-switch to the
537
+ default mTLS endpoint if client certificate is present; this is
538
+ the default value).
539
+
540
+ 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable
541
+ is "true", then the ``client_cert_source`` property can be used
542
+ to provide a client certificate for mTLS transport. If
543
+ not provided, the default SSL client certificate will be used if
544
+ present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not
545
+ set, no client certificate will be used.
546
+
547
+ 3. The ``universe_domain`` property can be used to override the
548
+ default "googleapis.com" universe. Note that the ``api_endpoint``
549
+ property still takes precedence; and ``universe_domain`` is
550
+ currently not supported for mTLS.
551
+
552
+ client_info (google.api_core.gapic_v1.client_info.ClientInfo):
553
+ The client info used to send a user-agent string along with
554
+ API requests. If ``None``, then default info will be used.
555
+ Generally, you only need to set this if you're developing
556
+ your own client library.
557
+
558
+ Raises:
559
+ google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
560
+ creation failed for any reason.
561
+ """
562
+ self._client_options = client_options
563
+ if isinstance(self._client_options, dict):
564
+ self._client_options = client_options_lib.from_dict(self._client_options)
565
+ if self._client_options is None:
566
+ self._client_options = client_options_lib.ClientOptions()
567
+ self._client_options = cast(
568
+ client_options_lib.ClientOptions, self._client_options
569
+ )
570
+
571
+ universe_domain_opt = getattr(self._client_options, "universe_domain", None)
572
+
573
+ (
574
+ self._use_client_cert,
575
+ self._use_mtls_endpoint,
576
+ self._universe_domain_env,
577
+ ) = DiscussServiceClient._read_environment_variables()
578
+ self._client_cert_source = DiscussServiceClient._get_client_cert_source(
579
+ self._client_options.client_cert_source, self._use_client_cert
580
+ )
581
+ self._universe_domain = DiscussServiceClient._get_universe_domain(
582
+ universe_domain_opt, self._universe_domain_env
583
+ )
584
+ self._api_endpoint = None # updated below, depending on `transport`
585
+
586
+ # Initialize the universe domain validation.
587
+ self._is_universe_domain_valid = False
588
+
589
+ if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER
590
+ # Setup logging.
591
+ client_logging.initialize_logging()
592
+
593
+ api_key_value = getattr(self._client_options, "api_key", None)
594
+ if api_key_value and credentials:
595
+ raise ValueError(
596
+ "client_options.api_key and credentials are mutually exclusive"
597
+ )
598
+
599
+ # Save or instantiate the transport.
600
+ # Ordinarily, we provide the transport, but allowing a custom transport
601
+ # instance provides an extensibility point for unusual situations.
602
+ transport_provided = isinstance(transport, DiscussServiceTransport)
603
+ if transport_provided:
604
+ # transport is a DiscussServiceTransport instance.
605
+ if credentials or self._client_options.credentials_file or api_key_value:
606
+ raise ValueError(
607
+ "When providing a transport instance, "
608
+ "provide its credentials directly."
609
+ )
610
+ if self._client_options.scopes:
611
+ raise ValueError(
612
+ "When providing a transport instance, provide its scopes "
613
+ "directly."
614
+ )
615
+ self._transport = cast(DiscussServiceTransport, transport)
616
+ self._api_endpoint = self._transport.host
617
+
618
+ self._api_endpoint = (
619
+ self._api_endpoint
620
+ or DiscussServiceClient._get_api_endpoint(
621
+ self._client_options.api_endpoint,
622
+ self._client_cert_source,
623
+ self._universe_domain,
624
+ self._use_mtls_endpoint,
625
+ )
626
+ )
627
+
628
+ if not transport_provided:
629
+ import google.auth._default # type: ignore
630
+
631
+ if api_key_value and hasattr(
632
+ google.auth._default, "get_api_key_credentials"
633
+ ):
634
+ credentials = google.auth._default.get_api_key_credentials(
635
+ api_key_value
636
+ )
637
+
638
+ transport_init: Union[
639
+ Type[DiscussServiceTransport], Callable[..., DiscussServiceTransport]
640
+ ] = (
641
+ DiscussServiceClient.get_transport_class(transport)
642
+ if isinstance(transport, str) or transport is None
643
+ else cast(Callable[..., DiscussServiceTransport], transport)
644
+ )
645
+ # initialize with the provided callable or the passed in class
646
+ self._transport = transport_init(
647
+ credentials=credentials,
648
+ credentials_file=self._client_options.credentials_file,
649
+ host=self._api_endpoint,
650
+ scopes=self._client_options.scopes,
651
+ client_cert_source_for_mtls=self._client_cert_source,
652
+ quota_project_id=self._client_options.quota_project_id,
653
+ client_info=client_info,
654
+ always_use_jwt_access=True,
655
+ api_audience=self._client_options.api_audience,
656
+ )
657
+
658
+ if "async" not in str(self._transport):
659
+ if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
660
+ std_logging.DEBUG
661
+ ): # pragma: NO COVER
662
+ _LOGGER.debug(
663
+ "Created client `google.ai.generativelanguage_v1alpha.DiscussServiceClient`.",
664
+ extra={
665
+ "serviceName": "google.ai.generativelanguage.v1alpha.DiscussService",
666
+ "universeDomain": getattr(
667
+ self._transport._credentials, "universe_domain", ""
668
+ ),
669
+ "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}",
670
+ "credentialsInfo": getattr(
671
+ self.transport._credentials, "get_cred_info", lambda: None
672
+ )(),
673
+ }
674
+ if hasattr(self._transport, "_credentials")
675
+ else {
676
+ "serviceName": "google.ai.generativelanguage.v1alpha.DiscussService",
677
+ "credentialsType": None,
678
+ },
679
+ )
680
+
681
+ def generate_message(
682
+ self,
683
+ request: Optional[Union[discuss_service.GenerateMessageRequest, dict]] = None,
684
+ *,
685
+ model: Optional[str] = None,
686
+ prompt: Optional[discuss_service.MessagePrompt] = None,
687
+ temperature: Optional[float] = None,
688
+ candidate_count: Optional[int] = None,
689
+ top_p: Optional[float] = None,
690
+ top_k: Optional[int] = None,
691
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
692
+ timeout: Union[float, object] = gapic_v1.method.DEFAULT,
693
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
694
+ ) -> discuss_service.GenerateMessageResponse:
695
+ r"""Generates a response from the model given an input
696
+ ``MessagePrompt``.
697
+
698
+ .. code-block:: python
699
+
700
+ # This snippet has been automatically generated and should be regarded as a
701
+ # code template only.
702
+ # It will require modifications to work:
703
+ # - It may require correct/in-range values for request initialization.
704
+ # - It may require specifying regional endpoints when creating the service
705
+ # client as shown in:
706
+ # https://googleapis.dev/python/google-api-core/latest/client_options.html
707
+ from google.ai import generativelanguage_v1alpha
708
+
709
+ def sample_generate_message():
710
+ # Create a client
711
+ client = generativelanguage_v1alpha.DiscussServiceClient()
712
+
713
+ # Initialize request argument(s)
714
+ prompt = generativelanguage_v1alpha.MessagePrompt()
715
+ prompt.messages.content = "content_value"
716
+
717
+ request = generativelanguage_v1alpha.GenerateMessageRequest(
718
+ model="model_value",
719
+ prompt=prompt,
720
+ )
721
+
722
+ # Make the request
723
+ response = client.generate_message(request=request)
724
+
725
+ # Handle the response
726
+ print(response)
727
+
728
+ Args:
729
+ request (Union[google.ai.generativelanguage_v1alpha.types.GenerateMessageRequest, dict]):
730
+ The request object. Request to generate a message
731
+ response from the model.
732
+ model (str):
733
+ Required. The name of the model to use.
734
+
735
+ Format: ``name=models/{model}``.
736
+
737
+ This corresponds to the ``model`` field
738
+ on the ``request`` instance; if ``request`` is provided, this
739
+ should not be set.
740
+ prompt (google.ai.generativelanguage_v1alpha.types.MessagePrompt):
741
+ Required. The structured textual
742
+ input given to the model as a prompt.
743
+ Given a
744
+ prompt, the model will return what it
745
+ predicts is the next message in the
746
+ discussion.
747
+
748
+ This corresponds to the ``prompt`` field
749
+ on the ``request`` instance; if ``request`` is provided, this
750
+ should not be set.
751
+ temperature (float):
752
+ Optional. Controls the randomness of the output.
753
+
754
+ Values can range over ``[0.0,1.0]``, inclusive. A value
755
+ closer to ``1.0`` will produce responses that are more
756
+ varied, while a value closer to ``0.0`` will typically
757
+ result in less surprising responses from the model.
758
+
759
+ This corresponds to the ``temperature`` field
760
+ on the ``request`` instance; if ``request`` is provided, this
761
+ should not be set.
762
+ candidate_count (int):
763
+ Optional. The number of generated response messages to
764
+ return.
765
+
766
+ This value must be between ``[1, 8]``, inclusive. If
767
+ unset, this will default to ``1``.
768
+
769
+ This corresponds to the ``candidate_count`` field
770
+ on the ``request`` instance; if ``request`` is provided, this
771
+ should not be set.
772
+ top_p (float):
773
+ Optional. The maximum cumulative probability of tokens
774
+ to consider when sampling.
775
+
776
+ The model uses combined Top-k and nucleus sampling.
777
+
778
+ Nucleus sampling considers the smallest set of tokens
779
+ whose probability sum is at least ``top_p``.
780
+
781
+ This corresponds to the ``top_p`` field
782
+ on the ``request`` instance; if ``request`` is provided, this
783
+ should not be set.
784
+ top_k (int):
785
+ Optional. The maximum number of tokens to consider when
786
+ sampling.
787
+
788
+ The model uses combined Top-k and nucleus sampling.
789
+
790
+ Top-k sampling considers the set of ``top_k`` most
791
+ probable tokens.
792
+
793
+ This corresponds to the ``top_k`` field
794
+ on the ``request`` instance; if ``request`` is provided, this
795
+ should not be set.
796
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
797
+ should be retried.
798
+ timeout (float): The timeout for this request.
799
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
800
+ sent along with the request as metadata. Normally, each value must be of type `str`,
801
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
802
+ be of type `bytes`.
803
+
804
+ Returns:
805
+ google.ai.generativelanguage_v1alpha.types.GenerateMessageResponse:
806
+ The response from the model.
807
+
808
+ This includes candidate messages and
809
+ conversation history in the form of
810
+ chronologically-ordered messages.
811
+
812
+ """
813
+ # Create or coerce a protobuf request object.
814
+ # - Quick check: If we got a request object, we should *not* have
815
+ # gotten any keyword arguments that map to the request.
816
+ has_flattened_params = any(
817
+ [model, prompt, temperature, candidate_count, top_p, top_k]
818
+ )
819
+ if request is not None and has_flattened_params:
820
+ raise ValueError(
821
+ "If the `request` argument is set, then none of "
822
+ "the individual field arguments should be set."
823
+ )
824
+
825
+ # - Use the request object if provided (there's no risk of modifying the input as
826
+ # there are no flattened fields), or create one.
827
+ if not isinstance(request, discuss_service.GenerateMessageRequest):
828
+ request = discuss_service.GenerateMessageRequest(request)
829
+ # If we have keyword arguments corresponding to fields on the
830
+ # request, apply these.
831
+ if model is not None:
832
+ request.model = model
833
+ if prompt is not None:
834
+ request.prompt = prompt
835
+ if temperature is not None:
836
+ request.temperature = temperature
837
+ if candidate_count is not None:
838
+ request.candidate_count = candidate_count
839
+ if top_p is not None:
840
+ request.top_p = top_p
841
+ if top_k is not None:
842
+ request.top_k = top_k
843
+
844
+ # Wrap the RPC method; this adds retry and timeout information,
845
+ # and friendly error handling.
846
+ rpc = self._transport._wrapped_methods[self._transport.generate_message]
847
+
848
+ # Certain fields should be provided within the metadata header;
849
+ # add these here.
850
+ metadata = tuple(metadata) + (
851
+ gapic_v1.routing_header.to_grpc_metadata((("model", request.model),)),
852
+ )
853
+
854
+ # Validate the universe domain.
855
+ self._validate_universe_domain()
856
+
857
+ # Send the request.
858
+ response = rpc(
859
+ request,
860
+ retry=retry,
861
+ timeout=timeout,
862
+ metadata=metadata,
863
+ )
864
+
865
+ # Done; return the response.
866
+ return response
867
+
868
+ def count_message_tokens(
869
+ self,
870
+ request: Optional[
871
+ Union[discuss_service.CountMessageTokensRequest, dict]
872
+ ] = None,
873
+ *,
874
+ model: Optional[str] = None,
875
+ prompt: Optional[discuss_service.MessagePrompt] = None,
876
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
877
+ timeout: Union[float, object] = gapic_v1.method.DEFAULT,
878
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
879
+ ) -> discuss_service.CountMessageTokensResponse:
880
+ r"""Runs a model's tokenizer on a string and returns the
881
+ token count.
882
+
883
+ .. code-block:: python
884
+
885
+ # This snippet has been automatically generated and should be regarded as a
886
+ # code template only.
887
+ # It will require modifications to work:
888
+ # - It may require correct/in-range values for request initialization.
889
+ # - It may require specifying regional endpoints when creating the service
890
+ # client as shown in:
891
+ # https://googleapis.dev/python/google-api-core/latest/client_options.html
892
+ from google.ai import generativelanguage_v1alpha
893
+
894
+ def sample_count_message_tokens():
895
+ # Create a client
896
+ client = generativelanguage_v1alpha.DiscussServiceClient()
897
+
898
+ # Initialize request argument(s)
899
+ prompt = generativelanguage_v1alpha.MessagePrompt()
900
+ prompt.messages.content = "content_value"
901
+
902
+ request = generativelanguage_v1alpha.CountMessageTokensRequest(
903
+ model="model_value",
904
+ prompt=prompt,
905
+ )
906
+
907
+ # Make the request
908
+ response = client.count_message_tokens(request=request)
909
+
910
+ # Handle the response
911
+ print(response)
912
+
913
+ Args:
914
+ request (Union[google.ai.generativelanguage_v1alpha.types.CountMessageTokensRequest, dict]):
915
+ The request object. Counts the number of tokens in the ``prompt`` sent to a
916
+ model.
917
+
918
+ Models may tokenize text differently, so each model may
919
+ return a different ``token_count``.
920
+ model (str):
921
+ Required. The model's resource name. This serves as an
922
+ ID for the Model to use.
923
+
924
+ This name should match a model name returned by the
925
+ ``ListModels`` method.
926
+
927
+ Format: ``models/{model}``
928
+
929
+ This corresponds to the ``model`` field
930
+ on the ``request`` instance; if ``request`` is provided, this
931
+ should not be set.
932
+ prompt (google.ai.generativelanguage_v1alpha.types.MessagePrompt):
933
+ Required. The prompt, whose token
934
+ count is to be returned.
935
+
936
+ This corresponds to the ``prompt`` field
937
+ on the ``request`` instance; if ``request`` is provided, this
938
+ should not be set.
939
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
940
+ should be retried.
941
+ timeout (float): The timeout for this request.
942
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
943
+ sent along with the request as metadata. Normally, each value must be of type `str`,
944
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
945
+ be of type `bytes`.
946
+
947
+ Returns:
948
+ google.ai.generativelanguage_v1alpha.types.CountMessageTokensResponse:
949
+ A response from CountMessageTokens.
950
+
951
+ It returns the model's token_count for the prompt.
952
+
953
+ """
954
+ # Create or coerce a protobuf request object.
955
+ # - Quick check: If we got a request object, we should *not* have
956
+ # gotten any keyword arguments that map to the request.
957
+ has_flattened_params = any([model, prompt])
958
+ if request is not None and has_flattened_params:
959
+ raise ValueError(
960
+ "If the `request` argument is set, then none of "
961
+ "the individual field arguments should be set."
962
+ )
963
+
964
+ # - Use the request object if provided (there's no risk of modifying the input as
965
+ # there are no flattened fields), or create one.
966
+ if not isinstance(request, discuss_service.CountMessageTokensRequest):
967
+ request = discuss_service.CountMessageTokensRequest(request)
968
+ # If we have keyword arguments corresponding to fields on the
969
+ # request, apply these.
970
+ if model is not None:
971
+ request.model = model
972
+ if prompt is not None:
973
+ request.prompt = prompt
974
+
975
+ # Wrap the RPC method; this adds retry and timeout information,
976
+ # and friendly error handling.
977
+ rpc = self._transport._wrapped_methods[self._transport.count_message_tokens]
978
+
979
+ # Certain fields should be provided within the metadata header;
980
+ # add these here.
981
+ metadata = tuple(metadata) + (
982
+ gapic_v1.routing_header.to_grpc_metadata((("model", request.model),)),
983
+ )
984
+
985
+ # Validate the universe domain.
986
+ self._validate_universe_domain()
987
+
988
+ # Send the request.
989
+ response = rpc(
990
+ request,
991
+ retry=retry,
992
+ timeout=timeout,
993
+ metadata=metadata,
994
+ )
995
+
996
+ # Done; return the response.
997
+ return response
998
+
999
+ def __enter__(self) -> "DiscussServiceClient":
1000
+ return self
1001
+
1002
+ def __exit__(self, type, value, traceback):
1003
+ """Releases underlying transport's resources.
1004
+
1005
+ .. warning::
1006
+ ONLY use as a context manager if the transport is NOT shared
1007
+ with other clients! Exiting the with block will CLOSE the transport
1008
+ and may cause errors in other clients!
1009
+ """
1010
+ self.transport.close()
1011
+
1012
+ def list_operations(
1013
+ self,
1014
+ request: Optional[operations_pb2.ListOperationsRequest] = None,
1015
+ *,
1016
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
1017
+ timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1018
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1019
+ ) -> operations_pb2.ListOperationsResponse:
1020
+ r"""Lists operations that match the specified filter in the request.
1021
+
1022
+ Args:
1023
+ request (:class:`~.operations_pb2.ListOperationsRequest`):
1024
+ The request object. Request message for
1025
+ `ListOperations` method.
1026
+ retry (google.api_core.retry.Retry): Designation of what errors,
1027
+ if any, should be retried.
1028
+ timeout (float): The timeout for this request.
1029
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1030
+ sent along with the request as metadata. Normally, each value must be of type `str`,
1031
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
1032
+ be of type `bytes`.
1033
+ Returns:
1034
+ ~.operations_pb2.ListOperationsResponse:
1035
+ Response message for ``ListOperations`` method.
1036
+ """
1037
+ # Create or coerce a protobuf request object.
1038
+ # The request isn't a proto-plus wrapped type,
1039
+ # so it must be constructed via keyword expansion.
1040
+ if isinstance(request, dict):
1041
+ request = operations_pb2.ListOperationsRequest(**request)
1042
+
1043
+ # Wrap the RPC method; this adds retry and timeout information,
1044
+ # and friendly error handling.
1045
+ rpc = self._transport._wrapped_methods[self._transport.list_operations]
1046
+
1047
+ # Certain fields should be provided within the metadata header;
1048
+ # add these here.
1049
+ metadata = tuple(metadata) + (
1050
+ gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
1051
+ )
1052
+
1053
+ # Validate the universe domain.
1054
+ self._validate_universe_domain()
1055
+
1056
+ # Send the request.
1057
+ response = rpc(
1058
+ request,
1059
+ retry=retry,
1060
+ timeout=timeout,
1061
+ metadata=metadata,
1062
+ )
1063
+
1064
+ # Done; return the response.
1065
+ return response
1066
+
1067
+ def get_operation(
1068
+ self,
1069
+ request: Optional[operations_pb2.GetOperationRequest] = None,
1070
+ *,
1071
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
1072
+ timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1073
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1074
+ ) -> operations_pb2.Operation:
1075
+ r"""Gets the latest state of a long-running operation.
1076
+
1077
+ Args:
1078
+ request (:class:`~.operations_pb2.GetOperationRequest`):
1079
+ The request object. Request message for
1080
+ `GetOperation` method.
1081
+ retry (google.api_core.retry.Retry): Designation of what errors,
1082
+ if any, should be retried.
1083
+ timeout (float): The timeout for this request.
1084
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1085
+ sent along with the request as metadata. Normally, each value must be of type `str`,
1086
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
1087
+ be of type `bytes`.
1088
+ Returns:
1089
+ ~.operations_pb2.Operation:
1090
+ An ``Operation`` object.
1091
+ """
1092
+ # Create or coerce a protobuf request object.
1093
+ # The request isn't a proto-plus wrapped type,
1094
+ # so it must be constructed via keyword expansion.
1095
+ if isinstance(request, dict):
1096
+ request = operations_pb2.GetOperationRequest(**request)
1097
+
1098
+ # Wrap the RPC method; this adds retry and timeout information,
1099
+ # and friendly error handling.
1100
+ rpc = self._transport._wrapped_methods[self._transport.get_operation]
1101
+
1102
+ # Certain fields should be provided within the metadata header;
1103
+ # add these here.
1104
+ metadata = tuple(metadata) + (
1105
+ gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
1106
+ )
1107
+
1108
+ # Validate the universe domain.
1109
+ self._validate_universe_domain()
1110
+
1111
+ # Send the request.
1112
+ response = rpc(
1113
+ request,
1114
+ retry=retry,
1115
+ timeout=timeout,
1116
+ metadata=metadata,
1117
+ )
1118
+
1119
+ # Done; return the response.
1120
+ return response
1121
+
1122
+
1123
+ DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
1124
+ gapic_version=package_version.__version__
1125
+ )
1126
+
1127
+
1128
+ __all__ = ("DiscussServiceClient",)
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/discuss_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 DiscussServiceTransport
20
+ from .grpc import DiscussServiceGrpcTransport
21
+ from .grpc_asyncio import DiscussServiceGrpcAsyncIOTransport
22
+ from .rest import DiscussServiceRestInterceptor, DiscussServiceRestTransport
23
+
24
+ # Compile a registry of transports.
25
+ _transport_registry = OrderedDict() # type: Dict[str, Type[DiscussServiceTransport]]
26
+ _transport_registry["grpc"] = DiscussServiceGrpcTransport
27
+ _transport_registry["grpc_asyncio"] = DiscussServiceGrpcAsyncIOTransport
28
+ _transport_registry["rest"] = DiscussServiceRestTransport
29
+
30
+ __all__ = (
31
+ "DiscussServiceTransport",
32
+ "DiscussServiceGrpcTransport",
33
+ "DiscussServiceGrpcAsyncIOTransport",
34
+ "DiscussServiceRestTransport",
35
+ "DiscussServiceRestInterceptor",
36
+ )
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/discuss_service/transports/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (908 Bytes). View file
 
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/discuss_service/transports/__pycache__/base.cpython-311.pyc ADDED
Binary file (8.52 kB). View file
 
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/discuss_service/transports/__pycache__/grpc.cpython-311.pyc ADDED
Binary file (19.3 kB). View file
 
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/discuss_service/transports/__pycache__/grpc_asyncio.cpython-311.pyc ADDED
Binary file (21.4 kB). View file
 
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/discuss_service/transports/__pycache__/rest.cpython-311.pyc ADDED
Binary file (36 kB). View file
 
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/discuss_service/transports/__pycache__/rest_base.cpython-311.pyc ADDED
Binary file (12.8 kB). View file
 
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/discuss_service/transports/base.py ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 discuss_service
30
+
31
+ DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
32
+ gapic_version=package_version.__version__
33
+ )
34
+
35
+
36
+ class DiscussServiceTransport(abc.ABC):
37
+ """Abstract transport class for DiscussService."""
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_message: gapic_v1.method.wrap_method(
133
+ self.generate_message,
134
+ default_timeout=None,
135
+ client_info=client_info,
136
+ ),
137
+ self.count_message_tokens: gapic_v1.method.wrap_method(
138
+ self.count_message_tokens,
139
+ default_timeout=None,
140
+ client_info=client_info,
141
+ ),
142
+ self.get_operation: gapic_v1.method.wrap_method(
143
+ self.get_operation,
144
+ default_timeout=None,
145
+ client_info=client_info,
146
+ ),
147
+ self.list_operations: gapic_v1.method.wrap_method(
148
+ self.list_operations,
149
+ default_timeout=None,
150
+ client_info=client_info,
151
+ ),
152
+ }
153
+
154
+ def close(self):
155
+ """Closes resources associated with the transport.
156
+
157
+ .. warning::
158
+ Only call this method if the transport is NOT shared
159
+ with other clients - this may cause errors in other clients!
160
+ """
161
+ raise NotImplementedError()
162
+
163
+ @property
164
+ def generate_message(
165
+ self,
166
+ ) -> Callable[
167
+ [discuss_service.GenerateMessageRequest],
168
+ Union[
169
+ discuss_service.GenerateMessageResponse,
170
+ Awaitable[discuss_service.GenerateMessageResponse],
171
+ ],
172
+ ]:
173
+ raise NotImplementedError()
174
+
175
+ @property
176
+ def count_message_tokens(
177
+ self,
178
+ ) -> Callable[
179
+ [discuss_service.CountMessageTokensRequest],
180
+ Union[
181
+ discuss_service.CountMessageTokensResponse,
182
+ Awaitable[discuss_service.CountMessageTokensResponse],
183
+ ],
184
+ ]:
185
+ raise NotImplementedError()
186
+
187
+ @property
188
+ def list_operations(
189
+ self,
190
+ ) -> Callable[
191
+ [operations_pb2.ListOperationsRequest],
192
+ Union[
193
+ operations_pb2.ListOperationsResponse,
194
+ Awaitable[operations_pb2.ListOperationsResponse],
195
+ ],
196
+ ]:
197
+ raise NotImplementedError()
198
+
199
+ @property
200
+ def get_operation(
201
+ self,
202
+ ) -> Callable[
203
+ [operations_pb2.GetOperationRequest],
204
+ Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]],
205
+ ]:
206
+ raise NotImplementedError()
207
+
208
+ @property
209
+ def kind(self) -> str:
210
+ raise NotImplementedError()
211
+
212
+
213
+ __all__ = ("DiscussServiceTransport",)
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/discuss_service/transports/grpc.py ADDED
@@ -0,0 +1,431 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 discuss_service
33
+
34
+ from .base import DEFAULT_CLIENT_INFO, DiscussServiceTransport
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.DiscussService",
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.DiscussService",
104
+ "rpcName": client_call_details.method,
105
+ "response": grpc_response,
106
+ "metadata": grpc_response["metadata"],
107
+ },
108
+ )
109
+ return response
110
+
111
+
112
+ class DiscussServiceGrpcTransport(DiscussServiceTransport):
113
+ """gRPC backend transport for DiscussService.
114
+
115
+ An API for using Generative Language Models (GLMs) in dialog
116
+ applications.
117
+ Also known as large language models (LLMs), this API provides
118
+ models that are trained for multi-turn dialog.
119
+
120
+ This class defines the same methods as the primary client, so the
121
+ primary client can load the underlying transport implementation
122
+ and call it.
123
+
124
+ It sends protocol buffers over the wire using gRPC (which is built on
125
+ top of HTTP/2); the ``grpcio`` package must be installed.
126
+ """
127
+
128
+ _stubs: Dict[str, Callable]
129
+
130
+ def __init__(
131
+ self,
132
+ *,
133
+ host: str = "generativelanguage.googleapis.com",
134
+ credentials: Optional[ga_credentials.Credentials] = None,
135
+ credentials_file: Optional[str] = None,
136
+ scopes: Optional[Sequence[str]] = None,
137
+ channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None,
138
+ api_mtls_endpoint: Optional[str] = None,
139
+ client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None,
140
+ ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None,
141
+ client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None,
142
+ quota_project_id: Optional[str] = None,
143
+ client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
144
+ always_use_jwt_access: Optional[bool] = False,
145
+ api_audience: Optional[str] = None,
146
+ ) -> None:
147
+ """Instantiate the transport.
148
+
149
+ Args:
150
+ host (Optional[str]):
151
+ The hostname to connect to (default: 'generativelanguage.googleapis.com').
152
+ credentials (Optional[google.auth.credentials.Credentials]): The
153
+ authorization credentials to attach to requests. These
154
+ credentials identify the application to the service; if none
155
+ are specified, the client will attempt to ascertain the
156
+ credentials from the environment.
157
+ This argument is ignored if a ``channel`` instance is provided.
158
+ credentials_file (Optional[str]): A file with credentials that can
159
+ be loaded with :func:`google.auth.load_credentials_from_file`.
160
+ This argument is ignored if a ``channel`` instance is provided.
161
+ scopes (Optional(Sequence[str])): A list of scopes. This argument is
162
+ ignored if a ``channel`` instance is provided.
163
+ channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]):
164
+ A ``Channel`` instance through which to make calls, or a Callable
165
+ that constructs and returns one. If set to None, ``self.create_channel``
166
+ is used to create the channel. If a Callable is given, it will be called
167
+ with the same arguments as used in ``self.create_channel``.
168
+ api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint.
169
+ If provided, it overrides the ``host`` argument and tries to create
170
+ a mutual TLS channel with client SSL credentials from
171
+ ``client_cert_source`` or application default SSL credentials.
172
+ client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]):
173
+ Deprecated. A callback to provide client SSL certificate bytes and
174
+ private key bytes, both in PEM format. It is ignored if
175
+ ``api_mtls_endpoint`` is None.
176
+ ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials
177
+ for the grpc channel. It is ignored if a ``channel`` instance is provided.
178
+ client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]):
179
+ A callback to provide client certificate bytes and private key bytes,
180
+ both in PEM format. It is used to configure a mutual TLS channel. It is
181
+ ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided.
182
+ quota_project_id (Optional[str]): An optional project to use for billing
183
+ and quota.
184
+ client_info (google.api_core.gapic_v1.client_info.ClientInfo):
185
+ The client info used to send a user-agent string along with
186
+ API requests. If ``None``, then default info will be used.
187
+ Generally, you only need to set this if you're developing
188
+ your own client library.
189
+ always_use_jwt_access (Optional[bool]): Whether self signed JWT should
190
+ be used for service account credentials.
191
+
192
+ Raises:
193
+ google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
194
+ creation failed for any reason.
195
+ google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
196
+ and ``credentials_file`` are passed.
197
+ """
198
+ self._grpc_channel = None
199
+ self._ssl_channel_credentials = ssl_channel_credentials
200
+ self._stubs: Dict[str, Callable] = {}
201
+
202
+ if api_mtls_endpoint:
203
+ warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning)
204
+ if client_cert_source:
205
+ warnings.warn("client_cert_source is deprecated", DeprecationWarning)
206
+
207
+ if isinstance(channel, grpc.Channel):
208
+ # Ignore credentials if a channel was passed.
209
+ credentials = None
210
+ self._ignore_credentials = True
211
+ # If a channel was explicitly provided, set it.
212
+ self._grpc_channel = channel
213
+ self._ssl_channel_credentials = None
214
+
215
+ else:
216
+ if api_mtls_endpoint:
217
+ host = api_mtls_endpoint
218
+
219
+ # Create SSL credentials with client_cert_source or application
220
+ # default SSL credentials.
221
+ if client_cert_source:
222
+ cert, key = client_cert_source()
223
+ self._ssl_channel_credentials = grpc.ssl_channel_credentials(
224
+ certificate_chain=cert, private_key=key
225
+ )
226
+ else:
227
+ self._ssl_channel_credentials = SslCredentials().ssl_credentials
228
+
229
+ else:
230
+ if client_cert_source_for_mtls and not ssl_channel_credentials:
231
+ cert, key = client_cert_source_for_mtls()
232
+ self._ssl_channel_credentials = grpc.ssl_channel_credentials(
233
+ certificate_chain=cert, private_key=key
234
+ )
235
+
236
+ # The base transport sets the host, credentials and scopes
237
+ super().__init__(
238
+ host=host,
239
+ credentials=credentials,
240
+ credentials_file=credentials_file,
241
+ scopes=scopes,
242
+ quota_project_id=quota_project_id,
243
+ client_info=client_info,
244
+ always_use_jwt_access=always_use_jwt_access,
245
+ api_audience=api_audience,
246
+ )
247
+
248
+ if not self._grpc_channel:
249
+ # initialize with the provided callable or the default channel
250
+ channel_init = channel or type(self).create_channel
251
+ self._grpc_channel = channel_init(
252
+ self._host,
253
+ # use the credentials which are saved
254
+ credentials=self._credentials,
255
+ # Set ``credentials_file`` to ``None`` here as
256
+ # the credentials that we saved earlier should be used.
257
+ credentials_file=None,
258
+ scopes=self._scopes,
259
+ ssl_credentials=self._ssl_channel_credentials,
260
+ quota_project_id=quota_project_id,
261
+ options=[
262
+ ("grpc.max_send_message_length", -1),
263
+ ("grpc.max_receive_message_length", -1),
264
+ ],
265
+ )
266
+
267
+ self._interceptor = _LoggingClientInterceptor()
268
+ self._logged_channel = grpc.intercept_channel(
269
+ self._grpc_channel, self._interceptor
270
+ )
271
+
272
+ # Wrap messages. This must be done after self._logged_channel exists
273
+ self._prep_wrapped_messages(client_info)
274
+
275
+ @classmethod
276
+ def create_channel(
277
+ cls,
278
+ host: str = "generativelanguage.googleapis.com",
279
+ credentials: Optional[ga_credentials.Credentials] = None,
280
+ credentials_file: Optional[str] = None,
281
+ scopes: Optional[Sequence[str]] = None,
282
+ quota_project_id: Optional[str] = None,
283
+ **kwargs,
284
+ ) -> grpc.Channel:
285
+ """Create and return a gRPC channel object.
286
+ Args:
287
+ host (Optional[str]): The host for the channel to use.
288
+ credentials (Optional[~.Credentials]): The
289
+ authorization credentials to attach to requests. These
290
+ credentials identify this application to the service. If
291
+ none are specified, the client will attempt to ascertain
292
+ the credentials from the environment.
293
+ credentials_file (Optional[str]): A file with credentials that can
294
+ be loaded with :func:`google.auth.load_credentials_from_file`.
295
+ This argument is mutually exclusive with credentials.
296
+ scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
297
+ service. These are only used when credentials are not specified and
298
+ are passed to :func:`google.auth.default`.
299
+ quota_project_id (Optional[str]): An optional project to use for billing
300
+ and quota.
301
+ kwargs (Optional[dict]): Keyword arguments, which are passed to the
302
+ channel creation.
303
+ Returns:
304
+ grpc.Channel: A gRPC channel object.
305
+
306
+ Raises:
307
+ google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
308
+ and ``credentials_file`` are passed.
309
+ """
310
+
311
+ return grpc_helpers.create_channel(
312
+ host,
313
+ credentials=credentials,
314
+ credentials_file=credentials_file,
315
+ quota_project_id=quota_project_id,
316
+ default_scopes=cls.AUTH_SCOPES,
317
+ scopes=scopes,
318
+ default_host=cls.DEFAULT_HOST,
319
+ **kwargs,
320
+ )
321
+
322
+ @property
323
+ def grpc_channel(self) -> grpc.Channel:
324
+ """Return the channel designed to connect to this service."""
325
+ return self._grpc_channel
326
+
327
+ @property
328
+ def generate_message(
329
+ self,
330
+ ) -> Callable[
331
+ [discuss_service.GenerateMessageRequest],
332
+ discuss_service.GenerateMessageResponse,
333
+ ]:
334
+ r"""Return a callable for the generate message method over gRPC.
335
+
336
+ Generates a response from the model given an input
337
+ ``MessagePrompt``.
338
+
339
+ Returns:
340
+ Callable[[~.GenerateMessageRequest],
341
+ ~.GenerateMessageResponse]:
342
+ A function that, when called, will call the underlying RPC
343
+ on the server.
344
+ """
345
+ # Generate a "stub function" on-the-fly which will actually make
346
+ # the request.
347
+ # gRPC handles serialization and deserialization, so we just need
348
+ # to pass in the functions for each.
349
+ if "generate_message" not in self._stubs:
350
+ self._stubs["generate_message"] = self._logged_channel.unary_unary(
351
+ "/google.ai.generativelanguage.v1alpha.DiscussService/GenerateMessage",
352
+ request_serializer=discuss_service.GenerateMessageRequest.serialize,
353
+ response_deserializer=discuss_service.GenerateMessageResponse.deserialize,
354
+ )
355
+ return self._stubs["generate_message"]
356
+
357
+ @property
358
+ def count_message_tokens(
359
+ self,
360
+ ) -> Callable[
361
+ [discuss_service.CountMessageTokensRequest],
362
+ discuss_service.CountMessageTokensResponse,
363
+ ]:
364
+ r"""Return a callable for the count message tokens method over gRPC.
365
+
366
+ Runs a model's tokenizer on a string and returns the
367
+ token count.
368
+
369
+ Returns:
370
+ Callable[[~.CountMessageTokensRequest],
371
+ ~.CountMessageTokensResponse]:
372
+ A function that, when called, will call the underlying RPC
373
+ on the server.
374
+ """
375
+ # Generate a "stub function" on-the-fly which will actually make
376
+ # the request.
377
+ # gRPC handles serialization and deserialization, so we just need
378
+ # to pass in the functions for each.
379
+ if "count_message_tokens" not in self._stubs:
380
+ self._stubs["count_message_tokens"] = self._logged_channel.unary_unary(
381
+ "/google.ai.generativelanguage.v1alpha.DiscussService/CountMessageTokens",
382
+ request_serializer=discuss_service.CountMessageTokensRequest.serialize,
383
+ response_deserializer=discuss_service.CountMessageTokensResponse.deserialize,
384
+ )
385
+ return self._stubs["count_message_tokens"]
386
+
387
+ def close(self):
388
+ self._logged_channel.close()
389
+
390
+ @property
391
+ def get_operation(
392
+ self,
393
+ ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]:
394
+ r"""Return a callable for the get_operation method over gRPC."""
395
+ # Generate a "stub function" on-the-fly which will actually make
396
+ # the request.
397
+ # gRPC handles serialization and deserialization, so we just need
398
+ # to pass in the functions for each.
399
+ if "get_operation" not in self._stubs:
400
+ self._stubs["get_operation"] = self._logged_channel.unary_unary(
401
+ "/google.longrunning.Operations/GetOperation",
402
+ request_serializer=operations_pb2.GetOperationRequest.SerializeToString,
403
+ response_deserializer=operations_pb2.Operation.FromString,
404
+ )
405
+ return self._stubs["get_operation"]
406
+
407
+ @property
408
+ def list_operations(
409
+ self,
410
+ ) -> Callable[
411
+ [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse
412
+ ]:
413
+ r"""Return a callable for the list_operations method over gRPC."""
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 "list_operations" not in self._stubs:
419
+ self._stubs["list_operations"] = self._logged_channel.unary_unary(
420
+ "/google.longrunning.Operations/ListOperations",
421
+ request_serializer=operations_pb2.ListOperationsRequest.SerializeToString,
422
+ response_deserializer=operations_pb2.ListOperationsResponse.FromString,
423
+ )
424
+ return self._stubs["list_operations"]
425
+
426
+ @property
427
+ def kind(self) -> str:
428
+ return "grpc"
429
+
430
+
431
+ __all__ = ("DiscussServiceGrpcTransport",)
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/discuss_service/transports/grpc_asyncio.py ADDED
@@ -0,0 +1,468 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 discuss_service
36
+
37
+ from .base import DEFAULT_CLIENT_INFO, DiscussServiceTransport
38
+ from .grpc import DiscussServiceGrpcTransport
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.DiscussService",
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.DiscussService",
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 DiscussServiceGrpcAsyncIOTransport(DiscussServiceTransport):
118
+ """gRPC AsyncIO backend transport for DiscussService.
119
+
120
+ An API for using Generative Language Models (GLMs) in dialog
121
+ applications.
122
+ Also known as large language models (LLMs), this API provides
123
+ models that are trained for multi-turn dialog.
124
+
125
+ This class defines the same methods as the primary client, so the
126
+ primary client can load the underlying transport implementation
127
+ and call it.
128
+
129
+ It sends protocol buffers over the wire using gRPC (which is built on
130
+ top of HTTP/2); the ``grpcio`` package must be installed.
131
+ """
132
+
133
+ _grpc_channel: aio.Channel
134
+ _stubs: Dict[str, Callable] = {}
135
+
136
+ @classmethod
137
+ def create_channel(
138
+ cls,
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
+ quota_project_id: Optional[str] = None,
144
+ **kwargs,
145
+ ) -> aio.Channel:
146
+ """Create and return a gRPC AsyncIO channel object.
147
+ Args:
148
+ host (Optional[str]): The host for the channel to use.
149
+ credentials (Optional[~.Credentials]): The
150
+ authorization credentials to attach to requests. These
151
+ credentials identify this application to the service. If
152
+ none are specified, the client will attempt to ascertain
153
+ the credentials from the environment.
154
+ credentials_file (Optional[str]): A file with credentials that can
155
+ be loaded with :func:`google.auth.load_credentials_from_file`.
156
+ scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
157
+ service. These are only used when credentials are not specified and
158
+ are passed to :func:`google.auth.default`.
159
+ quota_project_id (Optional[str]): An optional project to use for billing
160
+ and quota.
161
+ kwargs (Optional[dict]): Keyword arguments, which are passed to the
162
+ channel creation.
163
+ Returns:
164
+ aio.Channel: A gRPC AsyncIO channel object.
165
+ """
166
+
167
+ return grpc_helpers_async.create_channel(
168
+ host,
169
+ credentials=credentials,
170
+ credentials_file=credentials_file,
171
+ quota_project_id=quota_project_id,
172
+ default_scopes=cls.AUTH_SCOPES,
173
+ scopes=scopes,
174
+ default_host=cls.DEFAULT_HOST,
175
+ **kwargs,
176
+ )
177
+
178
+ def __init__(
179
+ self,
180
+ *,
181
+ host: str = "generativelanguage.googleapis.com",
182
+ credentials: Optional[ga_credentials.Credentials] = None,
183
+ credentials_file: Optional[str] = None,
184
+ scopes: Optional[Sequence[str]] = None,
185
+ channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None,
186
+ api_mtls_endpoint: Optional[str] = None,
187
+ client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None,
188
+ ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None,
189
+ client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None,
190
+ quota_project_id: Optional[str] = None,
191
+ client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
192
+ always_use_jwt_access: Optional[bool] = False,
193
+ api_audience: Optional[str] = None,
194
+ ) -> None:
195
+ """Instantiate the transport.
196
+
197
+ Args:
198
+ host (Optional[str]):
199
+ The hostname to connect to (default: 'generativelanguage.googleapis.com').
200
+ credentials (Optional[google.auth.credentials.Credentials]): The
201
+ authorization credentials to attach to requests. These
202
+ credentials identify the application to the service; if none
203
+ are specified, the client will attempt to ascertain the
204
+ credentials from the environment.
205
+ This argument is ignored if a ``channel`` instance is provided.
206
+ credentials_file (Optional[str]): A file with credentials that can
207
+ be loaded with :func:`google.auth.load_credentials_from_file`.
208
+ This argument is ignored if a ``channel`` instance is provided.
209
+ scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
210
+ service. These are only used when credentials are not specified and
211
+ are passed to :func:`google.auth.default`.
212
+ channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]):
213
+ A ``Channel`` instance through which to make calls, or a Callable
214
+ that constructs and returns one. If set to None, ``self.create_channel``
215
+ is used to create the channel. If a Callable is given, it will be called
216
+ with the same arguments as used in ``self.create_channel``.
217
+ api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint.
218
+ If provided, it overrides the ``host`` argument and tries to create
219
+ a mutual TLS channel with client SSL credentials from
220
+ ``client_cert_source`` or application default SSL credentials.
221
+ client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]):
222
+ Deprecated. A callback to provide client SSL certificate bytes and
223
+ private key bytes, both in PEM format. It is ignored if
224
+ ``api_mtls_endpoint`` is None.
225
+ ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials
226
+ for the grpc channel. It is ignored if a ``channel`` instance is provided.
227
+ client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]):
228
+ A callback to provide client certificate bytes and private key bytes,
229
+ both in PEM format. It is used to configure a mutual TLS channel. It is
230
+ ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided.
231
+ quota_project_id (Optional[str]): An optional project to use for billing
232
+ and quota.
233
+ client_info (google.api_core.gapic_v1.client_info.ClientInfo):
234
+ The client info used to send a user-agent string along with
235
+ API requests. If ``None``, then default info will be used.
236
+ Generally, you only need to set this if you're developing
237
+ your own client library.
238
+ always_use_jwt_access (Optional[bool]): Whether self signed JWT should
239
+ be used for service account credentials.
240
+
241
+ Raises:
242
+ google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
243
+ creation failed for any reason.
244
+ google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
245
+ and ``credentials_file`` are passed.
246
+ """
247
+ self._grpc_channel = None
248
+ self._ssl_channel_credentials = ssl_channel_credentials
249
+ self._stubs: Dict[str, Callable] = {}
250
+
251
+ if api_mtls_endpoint:
252
+ warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning)
253
+ if client_cert_source:
254
+ warnings.warn("client_cert_source is deprecated", DeprecationWarning)
255
+
256
+ if isinstance(channel, aio.Channel):
257
+ # Ignore credentials if a channel was passed.
258
+ credentials = None
259
+ self._ignore_credentials = True
260
+ # If a channel was explicitly provided, set it.
261
+ self._grpc_channel = channel
262
+ self._ssl_channel_credentials = None
263
+ else:
264
+ if api_mtls_endpoint:
265
+ host = api_mtls_endpoint
266
+
267
+ # Create SSL credentials with client_cert_source or application
268
+ # default SSL credentials.
269
+ if client_cert_source:
270
+ cert, key = client_cert_source()
271
+ self._ssl_channel_credentials = grpc.ssl_channel_credentials(
272
+ certificate_chain=cert, private_key=key
273
+ )
274
+ else:
275
+ self._ssl_channel_credentials = SslCredentials().ssl_credentials
276
+
277
+ else:
278
+ if client_cert_source_for_mtls and not ssl_channel_credentials:
279
+ cert, key = client_cert_source_for_mtls()
280
+ self._ssl_channel_credentials = grpc.ssl_channel_credentials(
281
+ certificate_chain=cert, private_key=key
282
+ )
283
+
284
+ # The base transport sets the host, credentials and scopes
285
+ super().__init__(
286
+ host=host,
287
+ credentials=credentials,
288
+ credentials_file=credentials_file,
289
+ scopes=scopes,
290
+ quota_project_id=quota_project_id,
291
+ client_info=client_info,
292
+ always_use_jwt_access=always_use_jwt_access,
293
+ api_audience=api_audience,
294
+ )
295
+
296
+ if not self._grpc_channel:
297
+ # initialize with the provided callable or the default channel
298
+ channel_init = channel or type(self).create_channel
299
+ self._grpc_channel = channel_init(
300
+ self._host,
301
+ # use the credentials which are saved
302
+ credentials=self._credentials,
303
+ # Set ``credentials_file`` to ``None`` here as
304
+ # the credentials that we saved earlier should be used.
305
+ credentials_file=None,
306
+ scopes=self._scopes,
307
+ ssl_credentials=self._ssl_channel_credentials,
308
+ quota_project_id=quota_project_id,
309
+ options=[
310
+ ("grpc.max_send_message_length", -1),
311
+ ("grpc.max_receive_message_length", -1),
312
+ ],
313
+ )
314
+
315
+ self._interceptor = _LoggingClientAIOInterceptor()
316
+ self._grpc_channel._unary_unary_interceptors.append(self._interceptor)
317
+ self._logged_channel = self._grpc_channel
318
+ self._wrap_with_kind = (
319
+ "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters
320
+ )
321
+ # Wrap messages. This must be done after self._logged_channel exists
322
+ self._prep_wrapped_messages(client_info)
323
+
324
+ @property
325
+ def grpc_channel(self) -> aio.Channel:
326
+ """Create the channel designed to connect to this service.
327
+
328
+ This property caches on the instance; repeated calls return
329
+ the same channel.
330
+ """
331
+ # Return the channel from cache.
332
+ return self._grpc_channel
333
+
334
+ @property
335
+ def generate_message(
336
+ self,
337
+ ) -> Callable[
338
+ [discuss_service.GenerateMessageRequest],
339
+ Awaitable[discuss_service.GenerateMessageResponse],
340
+ ]:
341
+ r"""Return a callable for the generate message method over gRPC.
342
+
343
+ Generates a response from the model given an input
344
+ ``MessagePrompt``.
345
+
346
+ Returns:
347
+ Callable[[~.GenerateMessageRequest],
348
+ Awaitable[~.GenerateMessageResponse]]:
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 "generate_message" not in self._stubs:
357
+ self._stubs["generate_message"] = self._logged_channel.unary_unary(
358
+ "/google.ai.generativelanguage.v1alpha.DiscussService/GenerateMessage",
359
+ request_serializer=discuss_service.GenerateMessageRequest.serialize,
360
+ response_deserializer=discuss_service.GenerateMessageResponse.deserialize,
361
+ )
362
+ return self._stubs["generate_message"]
363
+
364
+ @property
365
+ def count_message_tokens(
366
+ self,
367
+ ) -> Callable[
368
+ [discuss_service.CountMessageTokensRequest],
369
+ Awaitable[discuss_service.CountMessageTokensResponse],
370
+ ]:
371
+ r"""Return a callable for the count message tokens method over gRPC.
372
+
373
+ Runs a model's tokenizer on a string and returns the
374
+ token count.
375
+
376
+ Returns:
377
+ Callable[[~.CountMessageTokensRequest],
378
+ Awaitable[~.CountMessageTokensResponse]]:
379
+ A function that, when called, will call the underlying RPC
380
+ on the server.
381
+ """
382
+ # Generate a "stub function" on-the-fly which will actually make
383
+ # the request.
384
+ # gRPC handles serialization and deserialization, so we just need
385
+ # to pass in the functions for each.
386
+ if "count_message_tokens" not in self._stubs:
387
+ self._stubs["count_message_tokens"] = self._logged_channel.unary_unary(
388
+ "/google.ai.generativelanguage.v1alpha.DiscussService/CountMessageTokens",
389
+ request_serializer=discuss_service.CountMessageTokensRequest.serialize,
390
+ response_deserializer=discuss_service.CountMessageTokensResponse.deserialize,
391
+ )
392
+ return self._stubs["count_message_tokens"]
393
+
394
+ def _prep_wrapped_messages(self, client_info):
395
+ """Precompute the wrapped methods, overriding the base class method to use async wrappers."""
396
+ self._wrapped_methods = {
397
+ self.generate_message: self._wrap_method(
398
+ self.generate_message,
399
+ default_timeout=None,
400
+ client_info=client_info,
401
+ ),
402
+ self.count_message_tokens: self._wrap_method(
403
+ self.count_message_tokens,
404
+ default_timeout=None,
405
+ client_info=client_info,
406
+ ),
407
+ self.get_operation: self._wrap_method(
408
+ self.get_operation,
409
+ default_timeout=None,
410
+ client_info=client_info,
411
+ ),
412
+ self.list_operations: self._wrap_method(
413
+ self.list_operations,
414
+ default_timeout=None,
415
+ client_info=client_info,
416
+ ),
417
+ }
418
+
419
+ def _wrap_method(self, func, *args, **kwargs):
420
+ if self._wrap_with_kind: # pragma: NO COVER
421
+ kwargs["kind"] = self.kind
422
+ return gapic_v1.method_async.wrap_method(func, *args, **kwargs)
423
+
424
+ def close(self):
425
+ return self._logged_channel.close()
426
+
427
+ @property
428
+ def kind(self) -> str:
429
+ return "grpc_asyncio"
430
+
431
+ @property
432
+ def get_operation(
433
+ self,
434
+ ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]:
435
+ r"""Return a callable for the get_operation method over gRPC."""
436
+ # Generate a "stub function" on-the-fly which will actually make
437
+ # the request.
438
+ # gRPC handles serialization and deserialization, so we just need
439
+ # to pass in the functions for each.
440
+ if "get_operation" not in self._stubs:
441
+ self._stubs["get_operation"] = self._logged_channel.unary_unary(
442
+ "/google.longrunning.Operations/GetOperation",
443
+ request_serializer=operations_pb2.GetOperationRequest.SerializeToString,
444
+ response_deserializer=operations_pb2.Operation.FromString,
445
+ )
446
+ return self._stubs["get_operation"]
447
+
448
+ @property
449
+ def list_operations(
450
+ self,
451
+ ) -> Callable[
452
+ [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse
453
+ ]:
454
+ r"""Return a callable for the list_operations method over gRPC."""
455
+ # Generate a "stub function" on-the-fly which will actually make
456
+ # the request.
457
+ # gRPC handles serialization and deserialization, so we just need
458
+ # to pass in the functions for each.
459
+ if "list_operations" not in self._stubs:
460
+ self._stubs["list_operations"] = self._logged_channel.unary_unary(
461
+ "/google.longrunning.Operations/ListOperations",
462
+ request_serializer=operations_pb2.ListOperationsRequest.SerializeToString,
463
+ response_deserializer=operations_pb2.ListOperationsResponse.FromString,
464
+ )
465
+ return self._stubs["list_operations"]
466
+
467
+
468
+ __all__ = ("DiscussServiceGrpcAsyncIOTransport",)
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/discuss_service/transports/rest.py ADDED
@@ -0,0 +1,909 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 discuss_service
32
+
33
+ from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO
34
+ from .rest_base import _BaseDiscussServiceRestTransport
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 DiscussServiceRestInterceptor:
58
+ """Interceptor for DiscussService.
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 DiscussServiceRestTransport.
69
+
70
+ .. code-block:: python
71
+ class MyCustomDiscussServiceInterceptor(DiscussServiceRestInterceptor):
72
+ def pre_count_message_tokens(self, request, metadata):
73
+ logging.log(f"Received request: {request}")
74
+ return request, metadata
75
+
76
+ def post_count_message_tokens(self, response):
77
+ logging.log(f"Received response: {response}")
78
+ return response
79
+
80
+ def pre_generate_message(self, request, metadata):
81
+ logging.log(f"Received request: {request}")
82
+ return request, metadata
83
+
84
+ def post_generate_message(self, response):
85
+ logging.log(f"Received response: {response}")
86
+ return response
87
+
88
+ transport = DiscussServiceRestTransport(interceptor=MyCustomDiscussServiceInterceptor())
89
+ client = DiscussServiceClient(transport=transport)
90
+
91
+
92
+ """
93
+
94
+ def pre_count_message_tokens(
95
+ self,
96
+ request: discuss_service.CountMessageTokensRequest,
97
+ metadata: Sequence[Tuple[str, Union[str, bytes]]],
98
+ ) -> Tuple[
99
+ discuss_service.CountMessageTokensRequest,
100
+ Sequence[Tuple[str, Union[str, bytes]]],
101
+ ]:
102
+ """Pre-rpc interceptor for count_message_tokens
103
+
104
+ Override in a subclass to manipulate the request or metadata
105
+ before they are sent to the DiscussService server.
106
+ """
107
+ return request, metadata
108
+
109
+ def post_count_message_tokens(
110
+ self, response: discuss_service.CountMessageTokensResponse
111
+ ) -> discuss_service.CountMessageTokensResponse:
112
+ """Post-rpc interceptor for count_message_tokens
113
+
114
+ Override in a subclass to manipulate the response
115
+ after it is returned by the DiscussService server but before
116
+ it is returned to user code.
117
+ """
118
+ return response
119
+
120
+ def pre_generate_message(
121
+ self,
122
+ request: discuss_service.GenerateMessageRequest,
123
+ metadata: Sequence[Tuple[str, Union[str, bytes]]],
124
+ ) -> Tuple[
125
+ discuss_service.GenerateMessageRequest, Sequence[Tuple[str, Union[str, bytes]]]
126
+ ]:
127
+ """Pre-rpc interceptor for generate_message
128
+
129
+ Override in a subclass to manipulate the request or metadata
130
+ before they are sent to the DiscussService server.
131
+ """
132
+ return request, metadata
133
+
134
+ def post_generate_message(
135
+ self, response: discuss_service.GenerateMessageResponse
136
+ ) -> discuss_service.GenerateMessageResponse:
137
+ """Post-rpc interceptor for generate_message
138
+
139
+ Override in a subclass to manipulate the response
140
+ after it is returned by the DiscussService server but before
141
+ it is returned to user code.
142
+ """
143
+ return response
144
+
145
+ def pre_get_operation(
146
+ self,
147
+ request: operations_pb2.GetOperationRequest,
148
+ metadata: Sequence[Tuple[str, Union[str, bytes]]],
149
+ ) -> Tuple[
150
+ operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]
151
+ ]:
152
+ """Pre-rpc interceptor for get_operation
153
+
154
+ Override in a subclass to manipulate the request or metadata
155
+ before they are sent to the DiscussService server.
156
+ """
157
+ return request, metadata
158
+
159
+ def post_get_operation(
160
+ self, response: operations_pb2.Operation
161
+ ) -> operations_pb2.Operation:
162
+ """Post-rpc interceptor for get_operation
163
+
164
+ Override in a subclass to manipulate the response
165
+ after it is returned by the DiscussService server but before
166
+ it is returned to user code.
167
+ """
168
+ return response
169
+
170
+ def pre_list_operations(
171
+ self,
172
+ request: operations_pb2.ListOperationsRequest,
173
+ metadata: Sequence[Tuple[str, Union[str, bytes]]],
174
+ ) -> Tuple[
175
+ operations_pb2.ListOperationsRequest, Sequence[Tuple[str, Union[str, bytes]]]
176
+ ]:
177
+ """Pre-rpc interceptor for list_operations
178
+
179
+ Override in a subclass to manipulate the request or metadata
180
+ before they are sent to the DiscussService server.
181
+ """
182
+ return request, metadata
183
+
184
+ def post_list_operations(
185
+ self, response: operations_pb2.ListOperationsResponse
186
+ ) -> operations_pb2.ListOperationsResponse:
187
+ """Post-rpc interceptor for list_operations
188
+
189
+ Override in a subclass to manipulate the response
190
+ after it is returned by the DiscussService server but before
191
+ it is returned to user code.
192
+ """
193
+ return response
194
+
195
+
196
+ @dataclasses.dataclass
197
+ class DiscussServiceRestStub:
198
+ _session: AuthorizedSession
199
+ _host: str
200
+ _interceptor: DiscussServiceRestInterceptor
201
+
202
+
203
+ class DiscussServiceRestTransport(_BaseDiscussServiceRestTransport):
204
+ """REST backend synchronous transport for DiscussService.
205
+
206
+ An API for using Generative Language Models (GLMs) in dialog
207
+ applications.
208
+ Also known as large language models (LLMs), this API provides
209
+ models that are trained for multi-turn dialog.
210
+
211
+ This class defines the same methods as the primary client, so the
212
+ primary client can load the underlying transport implementation
213
+ and call it.
214
+
215
+ It sends JSON representations of protocol buffers over HTTP/1.1
216
+ """
217
+
218
+ def __init__(
219
+ self,
220
+ *,
221
+ host: str = "generativelanguage.googleapis.com",
222
+ credentials: Optional[ga_credentials.Credentials] = None,
223
+ credentials_file: Optional[str] = None,
224
+ scopes: Optional[Sequence[str]] = None,
225
+ client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None,
226
+ quota_project_id: Optional[str] = None,
227
+ client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
228
+ always_use_jwt_access: Optional[bool] = False,
229
+ url_scheme: str = "https",
230
+ interceptor: Optional[DiscussServiceRestInterceptor] = None,
231
+ api_audience: Optional[str] = None,
232
+ ) -> None:
233
+ """Instantiate the transport.
234
+
235
+ Args:
236
+ host (Optional[str]):
237
+ The hostname to connect to (default: 'generativelanguage.googleapis.com').
238
+ credentials (Optional[google.auth.credentials.Credentials]): The
239
+ authorization credentials to attach to requests. These
240
+ credentials identify the application to the service; if none
241
+ are specified, the client will attempt to ascertain the
242
+ credentials from the environment.
243
+
244
+ credentials_file (Optional[str]): A file with credentials that can
245
+ be loaded with :func:`google.auth.load_credentials_from_file`.
246
+ This argument is ignored if ``channel`` is provided.
247
+ scopes (Optional(Sequence[str])): A list of scopes. This argument is
248
+ ignored if ``channel`` is provided.
249
+ client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client
250
+ certificate to configure mutual TLS HTTP channel. It is ignored
251
+ if ``channel`` is provided.
252
+ quota_project_id (Optional[str]): An optional project to use for billing
253
+ and quota.
254
+ client_info (google.api_core.gapic_v1.client_info.ClientInfo):
255
+ The client info used to send a user-agent string along with
256
+ API requests. If ``None``, then default info will be used.
257
+ Generally, you only need to set this if you are developing
258
+ your own client library.
259
+ always_use_jwt_access (Optional[bool]): Whether self signed JWT should
260
+ be used for service account credentials.
261
+ url_scheme: the protocol scheme for the API endpoint. Normally
262
+ "https", but for testing or local servers,
263
+ "http" can be specified.
264
+ """
265
+ # Run the base constructor
266
+ # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc.
267
+ # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the
268
+ # credentials object
269
+ super().__init__(
270
+ host=host,
271
+ credentials=credentials,
272
+ client_info=client_info,
273
+ always_use_jwt_access=always_use_jwt_access,
274
+ url_scheme=url_scheme,
275
+ api_audience=api_audience,
276
+ )
277
+ self._session = AuthorizedSession(
278
+ self._credentials, default_host=self.DEFAULT_HOST
279
+ )
280
+ if client_cert_source_for_mtls:
281
+ self._session.configure_mtls_channel(client_cert_source_for_mtls)
282
+ self._interceptor = interceptor or DiscussServiceRestInterceptor()
283
+ self._prep_wrapped_messages(client_info)
284
+
285
+ class _CountMessageTokens(
286
+ _BaseDiscussServiceRestTransport._BaseCountMessageTokens, DiscussServiceRestStub
287
+ ):
288
+ def __hash__(self):
289
+ return hash("DiscussServiceRestTransport.CountMessageTokens")
290
+
291
+ @staticmethod
292
+ def _get_response(
293
+ host,
294
+ metadata,
295
+ query_params,
296
+ session,
297
+ timeout,
298
+ transcoded_request,
299
+ body=None,
300
+ ):
301
+ uri = transcoded_request["uri"]
302
+ method = transcoded_request["method"]
303
+ headers = dict(metadata)
304
+ headers["Content-Type"] = "application/json"
305
+ response = getattr(session, method)(
306
+ "{host}{uri}".format(host=host, uri=uri),
307
+ timeout=timeout,
308
+ headers=headers,
309
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
310
+ data=body,
311
+ )
312
+ return response
313
+
314
+ def __call__(
315
+ self,
316
+ request: discuss_service.CountMessageTokensRequest,
317
+ *,
318
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
319
+ timeout: Optional[float] = None,
320
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
321
+ ) -> discuss_service.CountMessageTokensResponse:
322
+ r"""Call the count message tokens method over HTTP.
323
+
324
+ Args:
325
+ request (~.discuss_service.CountMessageTokensRequest):
326
+ The request object. Counts the number of tokens in the ``prompt`` sent to a
327
+ model.
328
+
329
+ Models may tokenize text differently, so each model may
330
+ return a different ``token_count``.
331
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
332
+ should be retried.
333
+ timeout (float): The timeout for this request.
334
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
335
+ sent along with the request as metadata. Normally, each value must be of type `str`,
336
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
337
+ be of type `bytes`.
338
+
339
+ Returns:
340
+ ~.discuss_service.CountMessageTokensResponse:
341
+ A response from ``CountMessageTokens``.
342
+
343
+ It returns the model's ``token_count`` for the
344
+ ``prompt``.
345
+
346
+ """
347
+
348
+ http_options = (
349
+ _BaseDiscussServiceRestTransport._BaseCountMessageTokens._get_http_options()
350
+ )
351
+
352
+ request, metadata = self._interceptor.pre_count_message_tokens(
353
+ request, metadata
354
+ )
355
+ transcoded_request = _BaseDiscussServiceRestTransport._BaseCountMessageTokens._get_transcoded_request(
356
+ http_options, request
357
+ )
358
+
359
+ body = _BaseDiscussServiceRestTransport._BaseCountMessageTokens._get_request_body_json(
360
+ transcoded_request
361
+ )
362
+
363
+ # Jsonify the query params
364
+ query_params = _BaseDiscussServiceRestTransport._BaseCountMessageTokens._get_query_params_json(
365
+ transcoded_request
366
+ )
367
+
368
+ if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
369
+ logging.DEBUG
370
+ ): # pragma: NO COVER
371
+ request_url = "{host}{uri}".format(
372
+ host=self._host, uri=transcoded_request["uri"]
373
+ )
374
+ method = transcoded_request["method"]
375
+ try:
376
+ request_payload = type(request).to_json(request)
377
+ except:
378
+ request_payload = None
379
+ http_request = {
380
+ "payload": request_payload,
381
+ "requestMethod": method,
382
+ "requestUrl": request_url,
383
+ "headers": dict(metadata),
384
+ }
385
+ _LOGGER.debug(
386
+ f"Sending request for google.ai.generativelanguage_v1alpha.DiscussServiceClient.CountMessageTokens",
387
+ extra={
388
+ "serviceName": "google.ai.generativelanguage.v1alpha.DiscussService",
389
+ "rpcName": "CountMessageTokens",
390
+ "httpRequest": http_request,
391
+ "metadata": http_request["headers"],
392
+ },
393
+ )
394
+
395
+ # Send the request
396
+ response = DiscussServiceRestTransport._CountMessageTokens._get_response(
397
+ self._host,
398
+ metadata,
399
+ query_params,
400
+ self._session,
401
+ timeout,
402
+ transcoded_request,
403
+ body,
404
+ )
405
+
406
+ # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
407
+ # subclass.
408
+ if response.status_code >= 400:
409
+ raise core_exceptions.from_http_response(response)
410
+
411
+ # Return the response
412
+ resp = discuss_service.CountMessageTokensResponse()
413
+ pb_resp = discuss_service.CountMessageTokensResponse.pb(resp)
414
+
415
+ json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
416
+
417
+ resp = self._interceptor.post_count_message_tokens(resp)
418
+ if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
419
+ logging.DEBUG
420
+ ): # pragma: NO COVER
421
+ try:
422
+ response_payload = (
423
+ discuss_service.CountMessageTokensResponse.to_json(response)
424
+ )
425
+ except:
426
+ response_payload = None
427
+ http_response = {
428
+ "payload": response_payload,
429
+ "headers": dict(response.headers),
430
+ "status": response.status_code,
431
+ }
432
+ _LOGGER.debug(
433
+ "Received response for google.ai.generativelanguage_v1alpha.DiscussServiceClient.count_message_tokens",
434
+ extra={
435
+ "serviceName": "google.ai.generativelanguage.v1alpha.DiscussService",
436
+ "rpcName": "CountMessageTokens",
437
+ "metadata": http_response["headers"],
438
+ "httpResponse": http_response,
439
+ },
440
+ )
441
+ return resp
442
+
443
+ class _GenerateMessage(
444
+ _BaseDiscussServiceRestTransport._BaseGenerateMessage, DiscussServiceRestStub
445
+ ):
446
+ def __hash__(self):
447
+ return hash("DiscussServiceRestTransport.GenerateMessage")
448
+
449
+ @staticmethod
450
+ def _get_response(
451
+ host,
452
+ metadata,
453
+ query_params,
454
+ session,
455
+ timeout,
456
+ transcoded_request,
457
+ body=None,
458
+ ):
459
+ uri = transcoded_request["uri"]
460
+ method = transcoded_request["method"]
461
+ headers = dict(metadata)
462
+ headers["Content-Type"] = "application/json"
463
+ response = getattr(session, method)(
464
+ "{host}{uri}".format(host=host, uri=uri),
465
+ timeout=timeout,
466
+ headers=headers,
467
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
468
+ data=body,
469
+ )
470
+ return response
471
+
472
+ def __call__(
473
+ self,
474
+ request: discuss_service.GenerateMessageRequest,
475
+ *,
476
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
477
+ timeout: Optional[float] = None,
478
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
479
+ ) -> discuss_service.GenerateMessageResponse:
480
+ r"""Call the generate message method over HTTP.
481
+
482
+ Args:
483
+ request (~.discuss_service.GenerateMessageRequest):
484
+ The request object. Request to generate a message
485
+ response from the model.
486
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
487
+ should be retried.
488
+ timeout (float): The timeout for this request.
489
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
490
+ sent along with the request as metadata. Normally, each value must be of type `str`,
491
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
492
+ be of type `bytes`.
493
+
494
+ Returns:
495
+ ~.discuss_service.GenerateMessageResponse:
496
+ The response from the model.
497
+
498
+ This includes candidate messages and
499
+ conversation history in the form of
500
+ chronologically-ordered messages.
501
+
502
+ """
503
+
504
+ http_options = (
505
+ _BaseDiscussServiceRestTransport._BaseGenerateMessage._get_http_options()
506
+ )
507
+
508
+ request, metadata = self._interceptor.pre_generate_message(
509
+ request, metadata
510
+ )
511
+ transcoded_request = _BaseDiscussServiceRestTransport._BaseGenerateMessage._get_transcoded_request(
512
+ http_options, request
513
+ )
514
+
515
+ body = _BaseDiscussServiceRestTransport._BaseGenerateMessage._get_request_body_json(
516
+ transcoded_request
517
+ )
518
+
519
+ # Jsonify the query params
520
+ query_params = _BaseDiscussServiceRestTransport._BaseGenerateMessage._get_query_params_json(
521
+ transcoded_request
522
+ )
523
+
524
+ if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
525
+ logging.DEBUG
526
+ ): # pragma: NO COVER
527
+ request_url = "{host}{uri}".format(
528
+ host=self._host, uri=transcoded_request["uri"]
529
+ )
530
+ method = transcoded_request["method"]
531
+ try:
532
+ request_payload = type(request).to_json(request)
533
+ except:
534
+ request_payload = None
535
+ http_request = {
536
+ "payload": request_payload,
537
+ "requestMethod": method,
538
+ "requestUrl": request_url,
539
+ "headers": dict(metadata),
540
+ }
541
+ _LOGGER.debug(
542
+ f"Sending request for google.ai.generativelanguage_v1alpha.DiscussServiceClient.GenerateMessage",
543
+ extra={
544
+ "serviceName": "google.ai.generativelanguage.v1alpha.DiscussService",
545
+ "rpcName": "GenerateMessage",
546
+ "httpRequest": http_request,
547
+ "metadata": http_request["headers"],
548
+ },
549
+ )
550
+
551
+ # Send the request
552
+ response = DiscussServiceRestTransport._GenerateMessage._get_response(
553
+ self._host,
554
+ metadata,
555
+ query_params,
556
+ self._session,
557
+ timeout,
558
+ transcoded_request,
559
+ body,
560
+ )
561
+
562
+ # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
563
+ # subclass.
564
+ if response.status_code >= 400:
565
+ raise core_exceptions.from_http_response(response)
566
+
567
+ # Return the response
568
+ resp = discuss_service.GenerateMessageResponse()
569
+ pb_resp = discuss_service.GenerateMessageResponse.pb(resp)
570
+
571
+ json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
572
+
573
+ resp = self._interceptor.post_generate_message(resp)
574
+ if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
575
+ logging.DEBUG
576
+ ): # pragma: NO COVER
577
+ try:
578
+ response_payload = discuss_service.GenerateMessageResponse.to_json(
579
+ response
580
+ )
581
+ except:
582
+ response_payload = None
583
+ http_response = {
584
+ "payload": response_payload,
585
+ "headers": dict(response.headers),
586
+ "status": response.status_code,
587
+ }
588
+ _LOGGER.debug(
589
+ "Received response for google.ai.generativelanguage_v1alpha.DiscussServiceClient.generate_message",
590
+ extra={
591
+ "serviceName": "google.ai.generativelanguage.v1alpha.DiscussService",
592
+ "rpcName": "GenerateMessage",
593
+ "metadata": http_response["headers"],
594
+ "httpResponse": http_response,
595
+ },
596
+ )
597
+ return resp
598
+
599
+ @property
600
+ def count_message_tokens(
601
+ self,
602
+ ) -> Callable[
603
+ [discuss_service.CountMessageTokensRequest],
604
+ discuss_service.CountMessageTokensResponse,
605
+ ]:
606
+ # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
607
+ # In C++ this would require a dynamic_cast
608
+ return self._CountMessageTokens(self._session, self._host, self._interceptor) # type: ignore
609
+
610
+ @property
611
+ def generate_message(
612
+ self,
613
+ ) -> Callable[
614
+ [discuss_service.GenerateMessageRequest],
615
+ discuss_service.GenerateMessageResponse,
616
+ ]:
617
+ # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
618
+ # In C++ this would require a dynamic_cast
619
+ return self._GenerateMessage(self._session, self._host, self._interceptor) # type: ignore
620
+
621
+ @property
622
+ def get_operation(self):
623
+ return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore
624
+
625
+ class _GetOperation(
626
+ _BaseDiscussServiceRestTransport._BaseGetOperation, DiscussServiceRestStub
627
+ ):
628
+ def __hash__(self):
629
+ return hash("DiscussServiceRestTransport.GetOperation")
630
+
631
+ @staticmethod
632
+ def _get_response(
633
+ host,
634
+ metadata,
635
+ query_params,
636
+ session,
637
+ timeout,
638
+ transcoded_request,
639
+ body=None,
640
+ ):
641
+ uri = transcoded_request["uri"]
642
+ method = transcoded_request["method"]
643
+ headers = dict(metadata)
644
+ headers["Content-Type"] = "application/json"
645
+ response = getattr(session, method)(
646
+ "{host}{uri}".format(host=host, uri=uri),
647
+ timeout=timeout,
648
+ headers=headers,
649
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
650
+ )
651
+ return response
652
+
653
+ def __call__(
654
+ self,
655
+ request: operations_pb2.GetOperationRequest,
656
+ *,
657
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
658
+ timeout: Optional[float] = None,
659
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
660
+ ) -> operations_pb2.Operation:
661
+ r"""Call the get operation method over HTTP.
662
+
663
+ Args:
664
+ request (operations_pb2.GetOperationRequest):
665
+ The request object for GetOperation method.
666
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
667
+ should be retried.
668
+ timeout (float): The timeout for this request.
669
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
670
+ sent along with the request as metadata. Normally, each value must be of type `str`,
671
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
672
+ be of type `bytes`.
673
+
674
+ Returns:
675
+ operations_pb2.Operation: Response from GetOperation method.
676
+ """
677
+
678
+ http_options = (
679
+ _BaseDiscussServiceRestTransport._BaseGetOperation._get_http_options()
680
+ )
681
+
682
+ request, metadata = self._interceptor.pre_get_operation(request, metadata)
683
+ transcoded_request = _BaseDiscussServiceRestTransport._BaseGetOperation._get_transcoded_request(
684
+ http_options, request
685
+ )
686
+
687
+ # Jsonify the query params
688
+ query_params = _BaseDiscussServiceRestTransport._BaseGetOperation._get_query_params_json(
689
+ transcoded_request
690
+ )
691
+
692
+ if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
693
+ logging.DEBUG
694
+ ): # pragma: NO COVER
695
+ request_url = "{host}{uri}".format(
696
+ host=self._host, uri=transcoded_request["uri"]
697
+ )
698
+ method = transcoded_request["method"]
699
+ try:
700
+ request_payload = json_format.MessageToJson(request)
701
+ except:
702
+ request_payload = None
703
+ http_request = {
704
+ "payload": request_payload,
705
+ "requestMethod": method,
706
+ "requestUrl": request_url,
707
+ "headers": dict(metadata),
708
+ }
709
+ _LOGGER.debug(
710
+ f"Sending request for google.ai.generativelanguage_v1alpha.DiscussServiceClient.GetOperation",
711
+ extra={
712
+ "serviceName": "google.ai.generativelanguage.v1alpha.DiscussService",
713
+ "rpcName": "GetOperation",
714
+ "httpRequest": http_request,
715
+ "metadata": http_request["headers"],
716
+ },
717
+ )
718
+
719
+ # Send the request
720
+ response = DiscussServiceRestTransport._GetOperation._get_response(
721
+ self._host,
722
+ metadata,
723
+ query_params,
724
+ self._session,
725
+ timeout,
726
+ transcoded_request,
727
+ )
728
+
729
+ # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
730
+ # subclass.
731
+ if response.status_code >= 400:
732
+ raise core_exceptions.from_http_response(response)
733
+
734
+ content = response.content.decode("utf-8")
735
+ resp = operations_pb2.Operation()
736
+ resp = json_format.Parse(content, resp)
737
+ resp = self._interceptor.post_get_operation(resp)
738
+ if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
739
+ logging.DEBUG
740
+ ): # pragma: NO COVER
741
+ try:
742
+ response_payload = json_format.MessageToJson(resp)
743
+ except:
744
+ response_payload = None
745
+ http_response = {
746
+ "payload": response_payload,
747
+ "headers": dict(response.headers),
748
+ "status": response.status_code,
749
+ }
750
+ _LOGGER.debug(
751
+ "Received response for google.ai.generativelanguage_v1alpha.DiscussServiceAsyncClient.GetOperation",
752
+ extra={
753
+ "serviceName": "google.ai.generativelanguage.v1alpha.DiscussService",
754
+ "rpcName": "GetOperation",
755
+ "httpResponse": http_response,
756
+ "metadata": http_response["headers"],
757
+ },
758
+ )
759
+ return resp
760
+
761
+ @property
762
+ def list_operations(self):
763
+ return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore
764
+
765
+ class _ListOperations(
766
+ _BaseDiscussServiceRestTransport._BaseListOperations, DiscussServiceRestStub
767
+ ):
768
+ def __hash__(self):
769
+ return hash("DiscussServiceRestTransport.ListOperations")
770
+
771
+ @staticmethod
772
+ def _get_response(
773
+ host,
774
+ metadata,
775
+ query_params,
776
+ session,
777
+ timeout,
778
+ transcoded_request,
779
+ body=None,
780
+ ):
781
+ uri = transcoded_request["uri"]
782
+ method = transcoded_request["method"]
783
+ headers = dict(metadata)
784
+ headers["Content-Type"] = "application/json"
785
+ response = getattr(session, method)(
786
+ "{host}{uri}".format(host=host, uri=uri),
787
+ timeout=timeout,
788
+ headers=headers,
789
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
790
+ )
791
+ return response
792
+
793
+ def __call__(
794
+ self,
795
+ request: operations_pb2.ListOperationsRequest,
796
+ *,
797
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
798
+ timeout: Optional[float] = None,
799
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
800
+ ) -> operations_pb2.ListOperationsResponse:
801
+ r"""Call the list operations method over HTTP.
802
+
803
+ Args:
804
+ request (operations_pb2.ListOperationsRequest):
805
+ The request object for ListOperations method.
806
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
807
+ should be retried.
808
+ timeout (float): The timeout for this request.
809
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
810
+ sent along with the request as metadata. Normally, each value must be of type `str`,
811
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
812
+ be of type `bytes`.
813
+
814
+ Returns:
815
+ operations_pb2.ListOperationsResponse: Response from ListOperations method.
816
+ """
817
+
818
+ http_options = (
819
+ _BaseDiscussServiceRestTransport._BaseListOperations._get_http_options()
820
+ )
821
+
822
+ request, metadata = self._interceptor.pre_list_operations(request, metadata)
823
+ transcoded_request = _BaseDiscussServiceRestTransport._BaseListOperations._get_transcoded_request(
824
+ http_options, request
825
+ )
826
+
827
+ # Jsonify the query params
828
+ query_params = _BaseDiscussServiceRestTransport._BaseListOperations._get_query_params_json(
829
+ transcoded_request
830
+ )
831
+
832
+ if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
833
+ logging.DEBUG
834
+ ): # pragma: NO COVER
835
+ request_url = "{host}{uri}".format(
836
+ host=self._host, uri=transcoded_request["uri"]
837
+ )
838
+ method = transcoded_request["method"]
839
+ try:
840
+ request_payload = json_format.MessageToJson(request)
841
+ except:
842
+ request_payload = None
843
+ http_request = {
844
+ "payload": request_payload,
845
+ "requestMethod": method,
846
+ "requestUrl": request_url,
847
+ "headers": dict(metadata),
848
+ }
849
+ _LOGGER.debug(
850
+ f"Sending request for google.ai.generativelanguage_v1alpha.DiscussServiceClient.ListOperations",
851
+ extra={
852
+ "serviceName": "google.ai.generativelanguage.v1alpha.DiscussService",
853
+ "rpcName": "ListOperations",
854
+ "httpRequest": http_request,
855
+ "metadata": http_request["headers"],
856
+ },
857
+ )
858
+
859
+ # Send the request
860
+ response = DiscussServiceRestTransport._ListOperations._get_response(
861
+ self._host,
862
+ metadata,
863
+ query_params,
864
+ self._session,
865
+ timeout,
866
+ transcoded_request,
867
+ )
868
+
869
+ # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
870
+ # subclass.
871
+ if response.status_code >= 400:
872
+ raise core_exceptions.from_http_response(response)
873
+
874
+ content = response.content.decode("utf-8")
875
+ resp = operations_pb2.ListOperationsResponse()
876
+ resp = json_format.Parse(content, resp)
877
+ resp = self._interceptor.post_list_operations(resp)
878
+ if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
879
+ logging.DEBUG
880
+ ): # pragma: NO COVER
881
+ try:
882
+ response_payload = json_format.MessageToJson(resp)
883
+ except:
884
+ response_payload = None
885
+ http_response = {
886
+ "payload": response_payload,
887
+ "headers": dict(response.headers),
888
+ "status": response.status_code,
889
+ }
890
+ _LOGGER.debug(
891
+ "Received response for google.ai.generativelanguage_v1alpha.DiscussServiceAsyncClient.ListOperations",
892
+ extra={
893
+ "serviceName": "google.ai.generativelanguage.v1alpha.DiscussService",
894
+ "rpcName": "ListOperations",
895
+ "httpResponse": http_response,
896
+ "metadata": http_response["headers"],
897
+ },
898
+ )
899
+ return resp
900
+
901
+ @property
902
+ def kind(self) -> str:
903
+ return "rest"
904
+
905
+ def close(self):
906
+ self._session.close()
907
+
908
+
909
+ __all__ = ("DiscussServiceRestTransport",)
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/discuss_service/transports/rest_base.py ADDED
@@ -0,0 +1,268 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 discuss_service
25
+
26
+ from .base import DEFAULT_CLIENT_INFO, DiscussServiceTransport
27
+
28
+
29
+ class _BaseDiscussServiceRestTransport(DiscussServiceTransport):
30
+ """Base REST backend transport for DiscussService.
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 _BaseCountMessageTokens:
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/*}:countMessageTokens",
111
+ "body": "*",
112
+ },
113
+ ]
114
+ return http_options
115
+
116
+ @staticmethod
117
+ def _get_transcoded_request(http_options, request):
118
+ pb_request = discuss_service.CountMessageTokensRequest.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
+ _BaseDiscussServiceRestTransport._BaseCountMessageTokens._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 _BaseGenerateMessage:
149
+ def __hash__(self): # pragma: NO COVER
150
+ return NotImplementedError("__hash__ must be implemented.")
151
+
152
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
153
+
154
+ @classmethod
155
+ def _get_unset_required_fields(cls, message_dict):
156
+ return {
157
+ k: v
158
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
159
+ if k not in message_dict
160
+ }
161
+
162
+ @staticmethod
163
+ def _get_http_options():
164
+ http_options: List[Dict[str, str]] = [
165
+ {
166
+ "method": "post",
167
+ "uri": "/v1alpha/{model=models/*}:generateMessage",
168
+ "body": "*",
169
+ },
170
+ ]
171
+ return http_options
172
+
173
+ @staticmethod
174
+ def _get_transcoded_request(http_options, request):
175
+ pb_request = discuss_service.GenerateMessageRequest.pb(request)
176
+ transcoded_request = path_template.transcode(http_options, pb_request)
177
+ return transcoded_request
178
+
179
+ @staticmethod
180
+ def _get_request_body_json(transcoded_request):
181
+ # Jsonify the request body
182
+
183
+ body = json_format.MessageToJson(
184
+ transcoded_request["body"], use_integers_for_enums=True
185
+ )
186
+ return body
187
+
188
+ @staticmethod
189
+ def _get_query_params_json(transcoded_request):
190
+ query_params = json.loads(
191
+ json_format.MessageToJson(
192
+ transcoded_request["query_params"],
193
+ use_integers_for_enums=True,
194
+ )
195
+ )
196
+ query_params.update(
197
+ _BaseDiscussServiceRestTransport._BaseGenerateMessage._get_unset_required_fields(
198
+ query_params
199
+ )
200
+ )
201
+
202
+ query_params["$alt"] = "json;enum-encoding=int"
203
+ return query_params
204
+
205
+ class _BaseGetOperation:
206
+ def __hash__(self): # pragma: NO COVER
207
+ return NotImplementedError("__hash__ must be implemented.")
208
+
209
+ @staticmethod
210
+ def _get_http_options():
211
+ http_options: List[Dict[str, str]] = [
212
+ {
213
+ "method": "get",
214
+ "uri": "/v1alpha/{name=tunedModels/*/operations/*}",
215
+ },
216
+ {
217
+ "method": "get",
218
+ "uri": "/v1alpha/{name=generatedFiles/*/operations/*}",
219
+ },
220
+ {
221
+ "method": "get",
222
+ "uri": "/v1alpha/{name=models/*/operations/*}",
223
+ },
224
+ ]
225
+ return http_options
226
+
227
+ @staticmethod
228
+ def _get_transcoded_request(http_options, request):
229
+ request_kwargs = json_format.MessageToDict(request)
230
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
231
+ return transcoded_request
232
+
233
+ @staticmethod
234
+ def _get_query_params_json(transcoded_request):
235
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
236
+ return query_params
237
+
238
+ class _BaseListOperations:
239
+ def __hash__(self): # pragma: NO COVER
240
+ return NotImplementedError("__hash__ must be implemented.")
241
+
242
+ @staticmethod
243
+ def _get_http_options():
244
+ http_options: List[Dict[str, str]] = [
245
+ {
246
+ "method": "get",
247
+ "uri": "/v1alpha/{name=tunedModels/*}/operations",
248
+ },
249
+ {
250
+ "method": "get",
251
+ "uri": "/v1alpha/{name=models/*}/operations",
252
+ },
253
+ ]
254
+ return http_options
255
+
256
+ @staticmethod
257
+ def _get_transcoded_request(http_options, request):
258
+ request_kwargs = json_format.MessageToDict(request)
259
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
260
+ return transcoded_request
261
+
262
+ @staticmethod
263
+ def _get_query_params_json(transcoded_request):
264
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
265
+ return query_params
266
+
267
+
268
+ __all__ = ("_BaseDiscussServiceRestTransport",)
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/file_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 FileServiceAsyncClient
17
+ from .client import FileServiceClient
18
+
19
+ __all__ = (
20
+ "FileServiceClient",
21
+ "FileServiceAsyncClient",
22
+ )
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/file_service/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (400 Bytes). View file
 
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/file_service/__pycache__/async_client.cpython-311.pyc ADDED
Binary file (32.2 kB). View file
 
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/file_service/__pycache__/client.cpython-311.pyc ADDED
Binary file (48.2 kB). View file
 
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/file_service/__pycache__/pagers.cpython-311.pyc ADDED
Binary file (10 kB). View file
 
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/file_service/async_client.py ADDED
@@ -0,0 +1,780 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 timestamp_pb2 # type: ignore
48
+ from google.rpc import status_pb2 # type: ignore
49
+
50
+ from google.ai.generativelanguage_v1alpha.services.file_service import pagers
51
+ from google.ai.generativelanguage_v1alpha.types import file, file_service
52
+
53
+ from .client import FileServiceClient
54
+ from .transports.base import DEFAULT_CLIENT_INFO, FileServiceTransport
55
+ from .transports.grpc_asyncio import FileServiceGrpcAsyncIOTransport
56
+
57
+ try:
58
+ from google.api_core import client_logging # type: ignore
59
+
60
+ CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER
61
+ except ImportError: # pragma: NO COVER
62
+ CLIENT_LOGGING_SUPPORTED = False
63
+
64
+ _LOGGER = std_logging.getLogger(__name__)
65
+
66
+
67
+ class FileServiceAsyncClient:
68
+ """An API for uploading and managing files."""
69
+
70
+ _client: FileServiceClient
71
+
72
+ # Copy defaults from the synchronous client for use here.
73
+ # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead.
74
+ DEFAULT_ENDPOINT = FileServiceClient.DEFAULT_ENDPOINT
75
+ DEFAULT_MTLS_ENDPOINT = FileServiceClient.DEFAULT_MTLS_ENDPOINT
76
+ _DEFAULT_ENDPOINT_TEMPLATE = FileServiceClient._DEFAULT_ENDPOINT_TEMPLATE
77
+ _DEFAULT_UNIVERSE = FileServiceClient._DEFAULT_UNIVERSE
78
+
79
+ file_path = staticmethod(FileServiceClient.file_path)
80
+ parse_file_path = staticmethod(FileServiceClient.parse_file_path)
81
+ common_billing_account_path = staticmethod(
82
+ FileServiceClient.common_billing_account_path
83
+ )
84
+ parse_common_billing_account_path = staticmethod(
85
+ FileServiceClient.parse_common_billing_account_path
86
+ )
87
+ common_folder_path = staticmethod(FileServiceClient.common_folder_path)
88
+ parse_common_folder_path = staticmethod(FileServiceClient.parse_common_folder_path)
89
+ common_organization_path = staticmethod(FileServiceClient.common_organization_path)
90
+ parse_common_organization_path = staticmethod(
91
+ FileServiceClient.parse_common_organization_path
92
+ )
93
+ common_project_path = staticmethod(FileServiceClient.common_project_path)
94
+ parse_common_project_path = staticmethod(
95
+ FileServiceClient.parse_common_project_path
96
+ )
97
+ common_location_path = staticmethod(FileServiceClient.common_location_path)
98
+ parse_common_location_path = staticmethod(
99
+ FileServiceClient.parse_common_location_path
100
+ )
101
+
102
+ @classmethod
103
+ def from_service_account_info(cls, info: dict, *args, **kwargs):
104
+ """Creates an instance of this client using the provided credentials
105
+ info.
106
+
107
+ Args:
108
+ info (dict): The service account private key info.
109
+ args: Additional arguments to pass to the constructor.
110
+ kwargs: Additional arguments to pass to the constructor.
111
+
112
+ Returns:
113
+ FileServiceAsyncClient: The constructed client.
114
+ """
115
+ return FileServiceClient.from_service_account_info.__func__(FileServiceAsyncClient, info, *args, **kwargs) # type: ignore
116
+
117
+ @classmethod
118
+ def from_service_account_file(cls, filename: str, *args, **kwargs):
119
+ """Creates an instance of this client using the provided credentials
120
+ file.
121
+
122
+ Args:
123
+ filename (str): The path to the service account private key json
124
+ file.
125
+ args: Additional arguments to pass to the constructor.
126
+ kwargs: Additional arguments to pass to the constructor.
127
+
128
+ Returns:
129
+ FileServiceAsyncClient: The constructed client.
130
+ """
131
+ return FileServiceClient.from_service_account_file.__func__(FileServiceAsyncClient, filename, *args, **kwargs) # type: ignore
132
+
133
+ from_service_account_json = from_service_account_file
134
+
135
+ @classmethod
136
+ def get_mtls_endpoint_and_cert_source(
137
+ cls, client_options: Optional[ClientOptions] = None
138
+ ):
139
+ """Return the API endpoint and client cert source for mutual TLS.
140
+
141
+ The client cert source is determined in the following order:
142
+ (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the
143
+ client cert source is None.
144
+ (2) if `client_options.client_cert_source` is provided, use the provided one; if the
145
+ default client cert source exists, use the default one; otherwise the client cert
146
+ source is None.
147
+
148
+ The API endpoint is determined in the following order:
149
+ (1) if `client_options.api_endpoint` if provided, use the provided one.
150
+ (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the
151
+ default mTLS endpoint; if the environment variable is "never", use the default API
152
+ endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise
153
+ use the default API endpoint.
154
+
155
+ More details can be found at https://google.aip.dev/auth/4114.
156
+
157
+ Args:
158
+ client_options (google.api_core.client_options.ClientOptions): Custom options for the
159
+ client. Only the `api_endpoint` and `client_cert_source` properties may be used
160
+ in this method.
161
+
162
+ Returns:
163
+ Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the
164
+ client cert source to use.
165
+
166
+ Raises:
167
+ google.auth.exceptions.MutualTLSChannelError: If any errors happen.
168
+ """
169
+ return FileServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore
170
+
171
+ @property
172
+ def transport(self) -> FileServiceTransport:
173
+ """Returns the transport used by the client instance.
174
+
175
+ Returns:
176
+ FileServiceTransport: The transport used by the client instance.
177
+ """
178
+ return self._client.transport
179
+
180
+ @property
181
+ def api_endpoint(self):
182
+ """Return the API endpoint used by the client instance.
183
+
184
+ Returns:
185
+ str: The API endpoint used by the client instance.
186
+ """
187
+ return self._client._api_endpoint
188
+
189
+ @property
190
+ def universe_domain(self) -> str:
191
+ """Return the universe domain used by the client instance.
192
+
193
+ Returns:
194
+ str: The universe domain used
195
+ by the client instance.
196
+ """
197
+ return self._client._universe_domain
198
+
199
+ get_transport_class = FileServiceClient.get_transport_class
200
+
201
+ def __init__(
202
+ self,
203
+ *,
204
+ credentials: Optional[ga_credentials.Credentials] = None,
205
+ transport: Optional[
206
+ Union[str, FileServiceTransport, Callable[..., FileServiceTransport]]
207
+ ] = "grpc_asyncio",
208
+ client_options: Optional[ClientOptions] = None,
209
+ client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
210
+ ) -> None:
211
+ """Instantiates the file service async client.
212
+
213
+ Args:
214
+ credentials (Optional[google.auth.credentials.Credentials]): The
215
+ authorization credentials to attach to requests. These
216
+ credentials identify the application to the service; if none
217
+ are specified, the client will attempt to ascertain the
218
+ credentials from the environment.
219
+ transport (Optional[Union[str,FileServiceTransport,Callable[..., FileServiceTransport]]]):
220
+ The transport to use, or a Callable that constructs and returns a new transport to use.
221
+ If a Callable is given, it will be called with the same set of initialization
222
+ arguments as used in the FileServiceTransport constructor.
223
+ If set to None, a transport is chosen automatically.
224
+ client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]):
225
+ Custom options for the client.
226
+
227
+ 1. The ``api_endpoint`` property can be used to override the
228
+ default endpoint provided by the client when ``transport`` is
229
+ not explicitly provided. Only if this property is not set and
230
+ ``transport`` was not explicitly provided, the endpoint is
231
+ determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment
232
+ variable, which have one of the following values:
233
+ "always" (always use the default mTLS endpoint), "never" (always
234
+ use the default regular endpoint) and "auto" (auto-switch to the
235
+ default mTLS endpoint if client certificate is present; this is
236
+ the default value).
237
+
238
+ 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable
239
+ is "true", then the ``client_cert_source`` property can be used
240
+ to provide a client certificate for mTLS transport. If
241
+ not provided, the default SSL client certificate will be used if
242
+ present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not
243
+ set, no client certificate will be used.
244
+
245
+ 3. The ``universe_domain`` property can be used to override the
246
+ default "googleapis.com" universe. Note that ``api_endpoint``
247
+ property still takes precedence; and ``universe_domain`` is
248
+ currently not supported for mTLS.
249
+
250
+ client_info (google.api_core.gapic_v1.client_info.ClientInfo):
251
+ The client info used to send a user-agent string along with
252
+ API requests. If ``None``, then default info will be used.
253
+ Generally, you only need to set this if you're developing
254
+ your own client library.
255
+
256
+ Raises:
257
+ google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
258
+ creation failed for any reason.
259
+ """
260
+ self._client = FileServiceClient(
261
+ credentials=credentials,
262
+ transport=transport,
263
+ client_options=client_options,
264
+ client_info=client_info,
265
+ )
266
+
267
+ if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
268
+ std_logging.DEBUG
269
+ ): # pragma: NO COVER
270
+ _LOGGER.debug(
271
+ "Created client `google.ai.generativelanguage_v1alpha.FileServiceAsyncClient`.",
272
+ extra={
273
+ "serviceName": "google.ai.generativelanguage.v1alpha.FileService",
274
+ "universeDomain": getattr(
275
+ self._client._transport._credentials, "universe_domain", ""
276
+ ),
277
+ "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}",
278
+ "credentialsInfo": getattr(
279
+ self.transport._credentials, "get_cred_info", lambda: None
280
+ )(),
281
+ }
282
+ if hasattr(self._client._transport, "_credentials")
283
+ else {
284
+ "serviceName": "google.ai.generativelanguage.v1alpha.FileService",
285
+ "credentialsType": None,
286
+ },
287
+ )
288
+
289
+ async def create_file(
290
+ self,
291
+ request: Optional[Union[file_service.CreateFileRequest, dict]] = None,
292
+ *,
293
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
294
+ timeout: Union[float, object] = gapic_v1.method.DEFAULT,
295
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
296
+ ) -> file_service.CreateFileResponse:
297
+ r"""Creates a ``File``.
298
+
299
+ .. code-block:: python
300
+
301
+ # This snippet has been automatically generated and should be regarded as a
302
+ # code template only.
303
+ # It will require modifications to work:
304
+ # - It may require correct/in-range values for request initialization.
305
+ # - It may require specifying regional endpoints when creating the service
306
+ # client as shown in:
307
+ # https://googleapis.dev/python/google-api-core/latest/client_options.html
308
+ from google.ai import generativelanguage_v1alpha
309
+
310
+ async def sample_create_file():
311
+ # Create a client
312
+ client = generativelanguage_v1alpha.FileServiceAsyncClient()
313
+
314
+ # Initialize request argument(s)
315
+ request = generativelanguage_v1alpha.CreateFileRequest(
316
+ )
317
+
318
+ # Make the request
319
+ response = await client.create_file(request=request)
320
+
321
+ # Handle the response
322
+ print(response)
323
+
324
+ Args:
325
+ request (Optional[Union[google.ai.generativelanguage_v1alpha.types.CreateFileRequest, dict]]):
326
+ The request object. Request for ``CreateFile``.
327
+ retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any,
328
+ should be retried.
329
+ timeout (float): The timeout for this request.
330
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
331
+ sent along with the request as metadata. Normally, each value must be of type `str`,
332
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
333
+ be of type `bytes`.
334
+
335
+ Returns:
336
+ google.ai.generativelanguage_v1alpha.types.CreateFileResponse:
337
+ Response for CreateFile.
338
+ """
339
+ # Create or coerce a protobuf request object.
340
+ # - Use the request object if provided (there's no risk of modifying the input as
341
+ # there are no flattened fields), or create one.
342
+ if not isinstance(request, file_service.CreateFileRequest):
343
+ request = file_service.CreateFileRequest(request)
344
+
345
+ # Wrap the RPC method; this adds retry and timeout information,
346
+ # and friendly error handling.
347
+ rpc = self._client._transport._wrapped_methods[
348
+ self._client._transport.create_file
349
+ ]
350
+
351
+ # Validate the universe domain.
352
+ self._client._validate_universe_domain()
353
+
354
+ # Send the request.
355
+ response = await rpc(
356
+ request,
357
+ retry=retry,
358
+ timeout=timeout,
359
+ metadata=metadata,
360
+ )
361
+
362
+ # Done; return the response.
363
+ return response
364
+
365
+ async def list_files(
366
+ self,
367
+ request: Optional[Union[file_service.ListFilesRequest, dict]] = None,
368
+ *,
369
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
370
+ timeout: Union[float, object] = gapic_v1.method.DEFAULT,
371
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
372
+ ) -> pagers.ListFilesAsyncPager:
373
+ r"""Lists the metadata for ``File``\ s owned by the requesting
374
+ project.
375
+
376
+ .. code-block:: python
377
+
378
+ # This snippet has been automatically generated and should be regarded as a
379
+ # code template only.
380
+ # It will require modifications to work:
381
+ # - It may require correct/in-range values for request initialization.
382
+ # - It may require specifying regional endpoints when creating the service
383
+ # client as shown in:
384
+ # https://googleapis.dev/python/google-api-core/latest/client_options.html
385
+ from google.ai import generativelanguage_v1alpha
386
+
387
+ async def sample_list_files():
388
+ # Create a client
389
+ client = generativelanguage_v1alpha.FileServiceAsyncClient()
390
+
391
+ # Initialize request argument(s)
392
+ request = generativelanguage_v1alpha.ListFilesRequest(
393
+ )
394
+
395
+ # Make the request
396
+ page_result = client.list_files(request=request)
397
+
398
+ # Handle the response
399
+ async for response in page_result:
400
+ print(response)
401
+
402
+ Args:
403
+ request (Optional[Union[google.ai.generativelanguage_v1alpha.types.ListFilesRequest, dict]]):
404
+ The request object. Request for ``ListFiles``.
405
+ retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any,
406
+ should be retried.
407
+ timeout (float): The timeout for this request.
408
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
409
+ sent along with the request as metadata. Normally, each value must be of type `str`,
410
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
411
+ be of type `bytes`.
412
+
413
+ Returns:
414
+ google.ai.generativelanguage_v1alpha.services.file_service.pagers.ListFilesAsyncPager:
415
+ Response for ListFiles.
416
+
417
+ Iterating over this object will yield results and
418
+ resolve additional pages automatically.
419
+
420
+ """
421
+ # Create or coerce a protobuf request object.
422
+ # - Use the request object if provided (there's no risk of modifying the input as
423
+ # there are no flattened fields), or create one.
424
+ if not isinstance(request, file_service.ListFilesRequest):
425
+ request = file_service.ListFilesRequest(request)
426
+
427
+ # Wrap the RPC method; this adds retry and timeout information,
428
+ # and friendly error handling.
429
+ rpc = self._client._transport._wrapped_methods[
430
+ self._client._transport.list_files
431
+ ]
432
+
433
+ # Validate the universe domain.
434
+ self._client._validate_universe_domain()
435
+
436
+ # Send the request.
437
+ response = await rpc(
438
+ request,
439
+ retry=retry,
440
+ timeout=timeout,
441
+ metadata=metadata,
442
+ )
443
+
444
+ # This method is paged; wrap the response in a pager, which provides
445
+ # an `__aiter__` convenience method.
446
+ response = pagers.ListFilesAsyncPager(
447
+ method=rpc,
448
+ request=request,
449
+ response=response,
450
+ retry=retry,
451
+ timeout=timeout,
452
+ metadata=metadata,
453
+ )
454
+
455
+ # Done; return the response.
456
+ return response
457
+
458
+ async def get_file(
459
+ self,
460
+ request: Optional[Union[file_service.GetFileRequest, dict]] = None,
461
+ *,
462
+ name: Optional[str] = None,
463
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
464
+ timeout: Union[float, object] = gapic_v1.method.DEFAULT,
465
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
466
+ ) -> file.File:
467
+ r"""Gets the metadata for the given ``File``.
468
+
469
+ .. code-block:: python
470
+
471
+ # This snippet has been automatically generated and should be regarded as a
472
+ # code template only.
473
+ # It will require modifications to work:
474
+ # - It may require correct/in-range values for request initialization.
475
+ # - It may require specifying regional endpoints when creating the service
476
+ # client as shown in:
477
+ # https://googleapis.dev/python/google-api-core/latest/client_options.html
478
+ from google.ai import generativelanguage_v1alpha
479
+
480
+ async def sample_get_file():
481
+ # Create a client
482
+ client = generativelanguage_v1alpha.FileServiceAsyncClient()
483
+
484
+ # Initialize request argument(s)
485
+ request = generativelanguage_v1alpha.GetFileRequest(
486
+ name="name_value",
487
+ )
488
+
489
+ # Make the request
490
+ response = await client.get_file(request=request)
491
+
492
+ # Handle the response
493
+ print(response)
494
+
495
+ Args:
496
+ request (Optional[Union[google.ai.generativelanguage_v1alpha.types.GetFileRequest, dict]]):
497
+ The request object. Request for ``GetFile``.
498
+ name (:class:`str`):
499
+ Required. The name of the ``File`` to get. Example:
500
+ ``files/abc-123``
501
+
502
+ This corresponds to the ``name`` field
503
+ on the ``request`` instance; if ``request`` is provided, this
504
+ should not be set.
505
+ retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any,
506
+ should be retried.
507
+ timeout (float): The timeout for this request.
508
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
509
+ sent along with the request as metadata. Normally, each value must be of type `str`,
510
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
511
+ be of type `bytes`.
512
+
513
+ Returns:
514
+ google.ai.generativelanguage_v1alpha.types.File:
515
+ A file uploaded to the API.
516
+ Next ID: 15
517
+
518
+ """
519
+ # Create or coerce a protobuf request object.
520
+ # - Quick check: If we got a request object, we should *not* have
521
+ # gotten any keyword arguments that map to the request.
522
+ has_flattened_params = any([name])
523
+ if request is not None and has_flattened_params:
524
+ raise ValueError(
525
+ "If the `request` argument is set, then none of "
526
+ "the individual field arguments should be set."
527
+ )
528
+
529
+ # - Use the request object if provided (there's no risk of modifying the input as
530
+ # there are no flattened fields), or create one.
531
+ if not isinstance(request, file_service.GetFileRequest):
532
+ request = file_service.GetFileRequest(request)
533
+
534
+ # If we have keyword arguments corresponding to fields on the
535
+ # request, apply these.
536
+ if name is not None:
537
+ request.name = name
538
+
539
+ # Wrap the RPC method; this adds retry and timeout information,
540
+ # and friendly error handling.
541
+ rpc = self._client._transport._wrapped_methods[self._client._transport.get_file]
542
+
543
+ # Certain fields should be provided within the metadata header;
544
+ # add these here.
545
+ metadata = tuple(metadata) + (
546
+ gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
547
+ )
548
+
549
+ # Validate the universe domain.
550
+ self._client._validate_universe_domain()
551
+
552
+ # Send the request.
553
+ response = await rpc(
554
+ request,
555
+ retry=retry,
556
+ timeout=timeout,
557
+ metadata=metadata,
558
+ )
559
+
560
+ # Done; return the response.
561
+ return response
562
+
563
+ async def delete_file(
564
+ self,
565
+ request: Optional[Union[file_service.DeleteFileRequest, dict]] = None,
566
+ *,
567
+ name: Optional[str] = None,
568
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
569
+ timeout: Union[float, object] = gapic_v1.method.DEFAULT,
570
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
571
+ ) -> None:
572
+ r"""Deletes the ``File``.
573
+
574
+ .. code-block:: python
575
+
576
+ # This snippet has been automatically generated and should be regarded as a
577
+ # code template only.
578
+ # It will require modifications to work:
579
+ # - It may require correct/in-range values for request initialization.
580
+ # - It may require specifying regional endpoints when creating the service
581
+ # client as shown in:
582
+ # https://googleapis.dev/python/google-api-core/latest/client_options.html
583
+ from google.ai import generativelanguage_v1alpha
584
+
585
+ async def sample_delete_file():
586
+ # Create a client
587
+ client = generativelanguage_v1alpha.FileServiceAsyncClient()
588
+
589
+ # Initialize request argument(s)
590
+ request = generativelanguage_v1alpha.DeleteFileRequest(
591
+ name="name_value",
592
+ )
593
+
594
+ # Make the request
595
+ await client.delete_file(request=request)
596
+
597
+ Args:
598
+ request (Optional[Union[google.ai.generativelanguage_v1alpha.types.DeleteFileRequest, dict]]):
599
+ The request object. Request for ``DeleteFile``.
600
+ name (:class:`str`):
601
+ Required. The name of the ``File`` to delete. Example:
602
+ ``files/abc-123``
603
+
604
+ This corresponds to the ``name`` field
605
+ on the ``request`` instance; if ``request`` is provided, this
606
+ should not be set.
607
+ retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any,
608
+ should be retried.
609
+ timeout (float): The timeout for this request.
610
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
611
+ sent along with the request as metadata. Normally, each value must be of type `str`,
612
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
613
+ be of type `bytes`.
614
+ """
615
+ # Create or coerce a protobuf request object.
616
+ # - Quick check: If we got a request object, we should *not* have
617
+ # gotten any keyword arguments that map to the request.
618
+ has_flattened_params = any([name])
619
+ if request is not None and has_flattened_params:
620
+ raise ValueError(
621
+ "If the `request` argument is set, then none of "
622
+ "the individual field arguments should be set."
623
+ )
624
+
625
+ # - Use the request object if provided (there's no risk of modifying the input as
626
+ # there are no flattened fields), or create one.
627
+ if not isinstance(request, file_service.DeleteFileRequest):
628
+ request = file_service.DeleteFileRequest(request)
629
+
630
+ # If we have keyword arguments corresponding to fields on the
631
+ # request, apply these.
632
+ if name is not None:
633
+ request.name = name
634
+
635
+ # Wrap the RPC method; this adds retry and timeout information,
636
+ # and friendly error handling.
637
+ rpc = self._client._transport._wrapped_methods[
638
+ self._client._transport.delete_file
639
+ ]
640
+
641
+ # Certain fields should be provided within the metadata header;
642
+ # add these here.
643
+ metadata = tuple(metadata) + (
644
+ gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
645
+ )
646
+
647
+ # Validate the universe domain.
648
+ self._client._validate_universe_domain()
649
+
650
+ # Send the request.
651
+ await rpc(
652
+ request,
653
+ retry=retry,
654
+ timeout=timeout,
655
+ metadata=metadata,
656
+ )
657
+
658
+ async def list_operations(
659
+ self,
660
+ request: Optional[operations_pb2.ListOperationsRequest] = None,
661
+ *,
662
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
663
+ timeout: Union[float, object] = gapic_v1.method.DEFAULT,
664
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
665
+ ) -> operations_pb2.ListOperationsResponse:
666
+ r"""Lists operations that match the specified filter in the request.
667
+
668
+ Args:
669
+ request (:class:`~.operations_pb2.ListOperationsRequest`):
670
+ The request object. Request message for
671
+ `ListOperations` method.
672
+ retry (google.api_core.retry_async.AsyncRetry): Designation of what errors,
673
+ if any, should be retried.
674
+ timeout (float): The timeout for this request.
675
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
676
+ sent along with the request as metadata. Normally, each value must be of type `str`,
677
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
678
+ be of type `bytes`.
679
+ Returns:
680
+ ~.operations_pb2.ListOperationsResponse:
681
+ Response message for ``ListOperations`` method.
682
+ """
683
+ # Create or coerce a protobuf request object.
684
+ # The request isn't a proto-plus wrapped type,
685
+ # so it must be constructed via keyword expansion.
686
+ if isinstance(request, dict):
687
+ request = operations_pb2.ListOperationsRequest(**request)
688
+
689
+ # Wrap the RPC method; this adds retry and timeout information,
690
+ # and friendly error handling.
691
+ rpc = self.transport._wrapped_methods[self._client._transport.list_operations]
692
+
693
+ # Certain fields should be provided within the metadata header;
694
+ # add these here.
695
+ metadata = tuple(metadata) + (
696
+ gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
697
+ )
698
+
699
+ # Validate the universe domain.
700
+ self._client._validate_universe_domain()
701
+
702
+ # Send the request.
703
+ response = await rpc(
704
+ request,
705
+ retry=retry,
706
+ timeout=timeout,
707
+ metadata=metadata,
708
+ )
709
+
710
+ # Done; return the response.
711
+ return response
712
+
713
+ async def get_operation(
714
+ self,
715
+ request: Optional[operations_pb2.GetOperationRequest] = None,
716
+ *,
717
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
718
+ timeout: Union[float, object] = gapic_v1.method.DEFAULT,
719
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
720
+ ) -> operations_pb2.Operation:
721
+ r"""Gets the latest state of a long-running operation.
722
+
723
+ Args:
724
+ request (:class:`~.operations_pb2.GetOperationRequest`):
725
+ The request object. Request message for
726
+ `GetOperation` method.
727
+ retry (google.api_core.retry_async.AsyncRetry): Designation of what errors,
728
+ if any, should be retried.
729
+ timeout (float): The timeout for this request.
730
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
731
+ sent along with the request as metadata. Normally, each value must be of type `str`,
732
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
733
+ be of type `bytes`.
734
+ Returns:
735
+ ~.operations_pb2.Operation:
736
+ An ``Operation`` object.
737
+ """
738
+ # Create or coerce a protobuf request object.
739
+ # The request isn't a proto-plus wrapped type,
740
+ # so it must be constructed via keyword expansion.
741
+ if isinstance(request, dict):
742
+ request = operations_pb2.GetOperationRequest(**request)
743
+
744
+ # Wrap the RPC method; this adds retry and timeout information,
745
+ # and friendly error handling.
746
+ rpc = self.transport._wrapped_methods[self._client._transport.get_operation]
747
+
748
+ # Certain fields should be provided within the metadata header;
749
+ # add these here.
750
+ metadata = tuple(metadata) + (
751
+ gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
752
+ )
753
+
754
+ # Validate the universe domain.
755
+ self._client._validate_universe_domain()
756
+
757
+ # Send the request.
758
+ response = await rpc(
759
+ request,
760
+ retry=retry,
761
+ timeout=timeout,
762
+ metadata=metadata,
763
+ )
764
+
765
+ # Done; return the response.
766
+ return response
767
+
768
+ async def __aenter__(self) -> "FileServiceAsyncClient":
769
+ return self
770
+
771
+ async def __aexit__(self, exc_type, exc, tb):
772
+ await self.transport.close()
773
+
774
+
775
+ DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
776
+ gapic_version=package_version.__version__
777
+ )
778
+
779
+
780
+ __all__ = ("FileServiceAsyncClient",)
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/file_service/client.py ADDED
@@ -0,0 +1,1165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 timestamp_pb2 # type: ignore
63
+ from google.rpc import status_pb2 # type: ignore
64
+
65
+ from google.ai.generativelanguage_v1alpha.services.file_service import pagers
66
+ from google.ai.generativelanguage_v1alpha.types import file, file_service
67
+
68
+ from .transports.base import DEFAULT_CLIENT_INFO, FileServiceTransport
69
+ from .transports.grpc import FileServiceGrpcTransport
70
+ from .transports.grpc_asyncio import FileServiceGrpcAsyncIOTransport
71
+ from .transports.rest import FileServiceRestTransport
72
+
73
+
74
+ class FileServiceClientMeta(type):
75
+ """Metaclass for the FileService client.
76
+
77
+ This provides class-level methods for building and retrieving
78
+ support objects (e.g. transport) without polluting the client instance
79
+ objects.
80
+ """
81
+
82
+ _transport_registry = OrderedDict() # type: Dict[str, Type[FileServiceTransport]]
83
+ _transport_registry["grpc"] = FileServiceGrpcTransport
84
+ _transport_registry["grpc_asyncio"] = FileServiceGrpcAsyncIOTransport
85
+ _transport_registry["rest"] = FileServiceRestTransport
86
+
87
+ def get_transport_class(
88
+ cls,
89
+ label: Optional[str] = None,
90
+ ) -> Type[FileServiceTransport]:
91
+ """Returns an appropriate transport class.
92
+
93
+ Args:
94
+ label: The name of the desired transport. If none is
95
+ provided, then the first transport in the registry is used.
96
+
97
+ Returns:
98
+ The transport class to use.
99
+ """
100
+ # If a specific transport is requested, return that one.
101
+ if label:
102
+ return cls._transport_registry[label]
103
+
104
+ # No transport is requested; return the default (that is, the first one
105
+ # in the dictionary).
106
+ return next(iter(cls._transport_registry.values()))
107
+
108
+
109
+ class FileServiceClient(metaclass=FileServiceClientMeta):
110
+ """An API for uploading and managing files."""
111
+
112
+ @staticmethod
113
+ def _get_default_mtls_endpoint(api_endpoint):
114
+ """Converts api endpoint to mTLS endpoint.
115
+
116
+ Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to
117
+ "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively.
118
+ Args:
119
+ api_endpoint (Optional[str]): the api endpoint to convert.
120
+ Returns:
121
+ str: converted mTLS api endpoint.
122
+ """
123
+ if not api_endpoint:
124
+ return api_endpoint
125
+
126
+ mtls_endpoint_re = re.compile(
127
+ r"(?P<name>[^.]+)(?P<mtls>\.mtls)?(?P<sandbox>\.sandbox)?(?P<googledomain>\.googleapis\.com)?"
128
+ )
129
+
130
+ m = mtls_endpoint_re.match(api_endpoint)
131
+ name, mtls, sandbox, googledomain = m.groups()
132
+ if mtls or not googledomain:
133
+ return api_endpoint
134
+
135
+ if sandbox:
136
+ return api_endpoint.replace(
137
+ "sandbox.googleapis.com", "mtls.sandbox.googleapis.com"
138
+ )
139
+
140
+ return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com")
141
+
142
+ # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead.
143
+ DEFAULT_ENDPOINT = "generativelanguage.googleapis.com"
144
+ DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore
145
+ DEFAULT_ENDPOINT
146
+ )
147
+
148
+ _DEFAULT_ENDPOINT_TEMPLATE = "generativelanguage.{UNIVERSE_DOMAIN}"
149
+ _DEFAULT_UNIVERSE = "googleapis.com"
150
+
151
+ @classmethod
152
+ def from_service_account_info(cls, info: dict, *args, **kwargs):
153
+ """Creates an instance of this client using the provided credentials
154
+ info.
155
+
156
+ Args:
157
+ info (dict): The service account private key info.
158
+ args: Additional arguments to pass to the constructor.
159
+ kwargs: Additional arguments to pass to the constructor.
160
+
161
+ Returns:
162
+ FileServiceClient: The constructed client.
163
+ """
164
+ credentials = service_account.Credentials.from_service_account_info(info)
165
+ kwargs["credentials"] = credentials
166
+ return cls(*args, **kwargs)
167
+
168
+ @classmethod
169
+ def from_service_account_file(cls, filename: str, *args, **kwargs):
170
+ """Creates an instance of this client using the provided credentials
171
+ file.
172
+
173
+ Args:
174
+ filename (str): The path to the service account private key json
175
+ file.
176
+ args: Additional arguments to pass to the constructor.
177
+ kwargs: Additional arguments to pass to the constructor.
178
+
179
+ Returns:
180
+ FileServiceClient: The constructed client.
181
+ """
182
+ credentials = service_account.Credentials.from_service_account_file(filename)
183
+ kwargs["credentials"] = credentials
184
+ return cls(*args, **kwargs)
185
+
186
+ from_service_account_json = from_service_account_file
187
+
188
+ @property
189
+ def transport(self) -> FileServiceTransport:
190
+ """Returns the transport used by the client instance.
191
+
192
+ Returns:
193
+ FileServiceTransport: The transport used by the client
194
+ instance.
195
+ """
196
+ return self._transport
197
+
198
+ @staticmethod
199
+ def file_path(
200
+ file: str,
201
+ ) -> str:
202
+ """Returns a fully-qualified file string."""
203
+ return "files/{file}".format(
204
+ file=file,
205
+ )
206
+
207
+ @staticmethod
208
+ def parse_file_path(path: str) -> Dict[str, str]:
209
+ """Parses a file path into its component segments."""
210
+ m = re.match(r"^files/(?P<file>.+?)$", path)
211
+ return m.groupdict() if m else {}
212
+
213
+ @staticmethod
214
+ def common_billing_account_path(
215
+ billing_account: str,
216
+ ) -> str:
217
+ """Returns a fully-qualified billing_account string."""
218
+ return "billingAccounts/{billing_account}".format(
219
+ billing_account=billing_account,
220
+ )
221
+
222
+ @staticmethod
223
+ def parse_common_billing_account_path(path: str) -> Dict[str, str]:
224
+ """Parse a billing_account path into its component segments."""
225
+ m = re.match(r"^billingAccounts/(?P<billing_account>.+?)$", path)
226
+ return m.groupdict() if m else {}
227
+
228
+ @staticmethod
229
+ def common_folder_path(
230
+ folder: str,
231
+ ) -> str:
232
+ """Returns a fully-qualified folder string."""
233
+ return "folders/{folder}".format(
234
+ folder=folder,
235
+ )
236
+
237
+ @staticmethod
238
+ def parse_common_folder_path(path: str) -> Dict[str, str]:
239
+ """Parse a folder path into its component segments."""
240
+ m = re.match(r"^folders/(?P<folder>.+?)$", path)
241
+ return m.groupdict() if m else {}
242
+
243
+ @staticmethod
244
+ def common_organization_path(
245
+ organization: str,
246
+ ) -> str:
247
+ """Returns a fully-qualified organization string."""
248
+ return "organizations/{organization}".format(
249
+ organization=organization,
250
+ )
251
+
252
+ @staticmethod
253
+ def parse_common_organization_path(path: str) -> Dict[str, str]:
254
+ """Parse a organization path into its component segments."""
255
+ m = re.match(r"^organizations/(?P<organization>.+?)$", path)
256
+ return m.groupdict() if m else {}
257
+
258
+ @staticmethod
259
+ def common_project_path(
260
+ project: str,
261
+ ) -> str:
262
+ """Returns a fully-qualified project string."""
263
+ return "projects/{project}".format(
264
+ project=project,
265
+ )
266
+
267
+ @staticmethod
268
+ def parse_common_project_path(path: str) -> Dict[str, str]:
269
+ """Parse a project path into its component segments."""
270
+ m = re.match(r"^projects/(?P<project>.+?)$", path)
271
+ return m.groupdict() if m else {}
272
+
273
+ @staticmethod
274
+ def common_location_path(
275
+ project: str,
276
+ location: str,
277
+ ) -> str:
278
+ """Returns a fully-qualified location string."""
279
+ return "projects/{project}/locations/{location}".format(
280
+ project=project,
281
+ location=location,
282
+ )
283
+
284
+ @staticmethod
285
+ def parse_common_location_path(path: str) -> Dict[str, str]:
286
+ """Parse a location path into its component segments."""
287
+ m = re.match(r"^projects/(?P<project>.+?)/locations/(?P<location>.+?)$", path)
288
+ return m.groupdict() if m else {}
289
+
290
+ @classmethod
291
+ def get_mtls_endpoint_and_cert_source(
292
+ cls, client_options: Optional[client_options_lib.ClientOptions] = None
293
+ ):
294
+ """Deprecated. Return the API endpoint and client cert source for mutual TLS.
295
+
296
+ The client cert source is determined in the following order:
297
+ (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the
298
+ client cert source is None.
299
+ (2) if `client_options.client_cert_source` is provided, use the provided one; if the
300
+ default client cert source exists, use the default one; otherwise the client cert
301
+ source is None.
302
+
303
+ The API endpoint is determined in the following order:
304
+ (1) if `client_options.api_endpoint` if provided, use the provided one.
305
+ (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the
306
+ default mTLS endpoint; if the environment variable is "never", use the default API
307
+ endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise
308
+ use the default API endpoint.
309
+
310
+ More details can be found at https://google.aip.dev/auth/4114.
311
+
312
+ Args:
313
+ client_options (google.api_core.client_options.ClientOptions): Custom options for the
314
+ client. Only the `api_endpoint` and `client_cert_source` properties may be used
315
+ in this method.
316
+
317
+ Returns:
318
+ Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the
319
+ client cert source to use.
320
+
321
+ Raises:
322
+ google.auth.exceptions.MutualTLSChannelError: If any errors happen.
323
+ """
324
+
325
+ warnings.warn(
326
+ "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.",
327
+ DeprecationWarning,
328
+ )
329
+ if client_options is None:
330
+ client_options = client_options_lib.ClientOptions()
331
+ use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false")
332
+ use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto")
333
+ if use_client_cert not in ("true", "false"):
334
+ raise ValueError(
335
+ "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`"
336
+ )
337
+ if use_mtls_endpoint not in ("auto", "never", "always"):
338
+ raise MutualTLSChannelError(
339
+ "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`"
340
+ )
341
+
342
+ # Figure out the client cert source to use.
343
+ client_cert_source = None
344
+ if use_client_cert == "true":
345
+ if client_options.client_cert_source:
346
+ client_cert_source = client_options.client_cert_source
347
+ elif mtls.has_default_client_cert_source():
348
+ client_cert_source = mtls.default_client_cert_source()
349
+
350
+ # Figure out which api endpoint to use.
351
+ if client_options.api_endpoint is not None:
352
+ api_endpoint = client_options.api_endpoint
353
+ elif use_mtls_endpoint == "always" or (
354
+ use_mtls_endpoint == "auto" and client_cert_source
355
+ ):
356
+ api_endpoint = cls.DEFAULT_MTLS_ENDPOINT
357
+ else:
358
+ api_endpoint = cls.DEFAULT_ENDPOINT
359
+
360
+ return api_endpoint, client_cert_source
361
+
362
+ @staticmethod
363
+ def _read_environment_variables():
364
+ """Returns the environment variables used by the client.
365
+
366
+ Returns:
367
+ Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE,
368
+ GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables.
369
+
370
+ Raises:
371
+ ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not
372
+ any of ["true", "false"].
373
+ google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT
374
+ is not any of ["auto", "never", "always"].
375
+ """
376
+ use_client_cert = os.getenv(
377
+ "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"
378
+ ).lower()
379
+ use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower()
380
+ universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN")
381
+ if use_client_cert not in ("true", "false"):
382
+ raise ValueError(
383
+ "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`"
384
+ )
385
+ if use_mtls_endpoint not in ("auto", "never", "always"):
386
+ raise MutualTLSChannelError(
387
+ "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`"
388
+ )
389
+ return use_client_cert == "true", use_mtls_endpoint, universe_domain_env
390
+
391
+ @staticmethod
392
+ def _get_client_cert_source(provided_cert_source, use_cert_flag):
393
+ """Return the client cert source to be used by the client.
394
+
395
+ Args:
396
+ provided_cert_source (bytes): The client certificate source provided.
397
+ use_cert_flag (bool): A flag indicating whether to use the client certificate.
398
+
399
+ Returns:
400
+ bytes or None: The client cert source to be used by the client.
401
+ """
402
+ client_cert_source = None
403
+ if use_cert_flag:
404
+ if provided_cert_source:
405
+ client_cert_source = provided_cert_source
406
+ elif mtls.has_default_client_cert_source():
407
+ client_cert_source = mtls.default_client_cert_source()
408
+ return client_cert_source
409
+
410
+ @staticmethod
411
+ def _get_api_endpoint(
412
+ api_override, client_cert_source, universe_domain, use_mtls_endpoint
413
+ ):
414
+ """Return the API endpoint used by the client.
415
+
416
+ Args:
417
+ api_override (str): The API endpoint override. If specified, this is always
418
+ the return value of this function and the other arguments are not used.
419
+ client_cert_source (bytes): The client certificate source used by the client.
420
+ universe_domain (str): The universe domain used by the client.
421
+ use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters.
422
+ Possible values are "always", "auto", or "never".
423
+
424
+ Returns:
425
+ str: The API endpoint to be used by the client.
426
+ """
427
+ if api_override is not None:
428
+ api_endpoint = api_override
429
+ elif use_mtls_endpoint == "always" or (
430
+ use_mtls_endpoint == "auto" and client_cert_source
431
+ ):
432
+ _default_universe = FileServiceClient._DEFAULT_UNIVERSE
433
+ if universe_domain != _default_universe:
434
+ raise MutualTLSChannelError(
435
+ f"mTLS is not supported in any universe other than {_default_universe}."
436
+ )
437
+ api_endpoint = FileServiceClient.DEFAULT_MTLS_ENDPOINT
438
+ else:
439
+ api_endpoint = FileServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(
440
+ UNIVERSE_DOMAIN=universe_domain
441
+ )
442
+ return api_endpoint
443
+
444
+ @staticmethod
445
+ def _get_universe_domain(
446
+ client_universe_domain: Optional[str], universe_domain_env: Optional[str]
447
+ ) -> str:
448
+ """Return the universe domain used by the client.
449
+
450
+ Args:
451
+ client_universe_domain (Optional[str]): The universe domain configured via the client options.
452
+ universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable.
453
+
454
+ Returns:
455
+ str: The universe domain to be used by the client.
456
+
457
+ Raises:
458
+ ValueError: If the universe domain is an empty string.
459
+ """
460
+ universe_domain = FileServiceClient._DEFAULT_UNIVERSE
461
+ if client_universe_domain is not None:
462
+ universe_domain = client_universe_domain
463
+ elif universe_domain_env is not None:
464
+ universe_domain = universe_domain_env
465
+ if len(universe_domain.strip()) == 0:
466
+ raise ValueError("Universe Domain cannot be an empty string.")
467
+ return universe_domain
468
+
469
+ def _validate_universe_domain(self):
470
+ """Validates client's and credentials' universe domains are consistent.
471
+
472
+ Returns:
473
+ bool: True iff the configured universe domain is valid.
474
+
475
+ Raises:
476
+ ValueError: If the configured universe domain is not valid.
477
+ """
478
+
479
+ # NOTE (b/349488459): universe validation is disabled until further notice.
480
+ return True
481
+
482
+ @property
483
+ def api_endpoint(self):
484
+ """Return the API endpoint used by the client instance.
485
+
486
+ Returns:
487
+ str: The API endpoint used by the client instance.
488
+ """
489
+ return self._api_endpoint
490
+
491
+ @property
492
+ def universe_domain(self) -> str:
493
+ """Return the universe domain used by the client instance.
494
+
495
+ Returns:
496
+ str: The universe domain used by the client instance.
497
+ """
498
+ return self._universe_domain
499
+
500
+ def __init__(
501
+ self,
502
+ *,
503
+ credentials: Optional[ga_credentials.Credentials] = None,
504
+ transport: Optional[
505
+ Union[str, FileServiceTransport, Callable[..., FileServiceTransport]]
506
+ ] = None,
507
+ client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None,
508
+ client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
509
+ ) -> None:
510
+ """Instantiates the file service client.
511
+
512
+ Args:
513
+ credentials (Optional[google.auth.credentials.Credentials]): The
514
+ authorization credentials to attach to requests. These
515
+ credentials identify the application to the service; if none
516
+ are specified, the client will attempt to ascertain the
517
+ credentials from the environment.
518
+ transport (Optional[Union[str,FileServiceTransport,Callable[..., FileServiceTransport]]]):
519
+ The transport to use, or a Callable that constructs and returns a new transport.
520
+ If a Callable is given, it will be called with the same set of initialization
521
+ arguments as used in the FileServiceTransport constructor.
522
+ If set to None, a transport is chosen automatically.
523
+ client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]):
524
+ Custom options for the client.
525
+
526
+ 1. The ``api_endpoint`` property can be used to override the
527
+ default endpoint provided by the client when ``transport`` is
528
+ not explicitly provided. Only if this property is not set and
529
+ ``transport`` was not explicitly provided, the endpoint is
530
+ determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment
531
+ variable, which have one of the following values:
532
+ "always" (always use the default mTLS endpoint), "never" (always
533
+ use the default regular endpoint) and "auto" (auto-switch to the
534
+ default mTLS endpoint if client certificate is present; this is
535
+ the default value).
536
+
537
+ 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable
538
+ is "true", then the ``client_cert_source`` property can be used
539
+ to provide a client certificate for mTLS transport. If
540
+ not provided, the default SSL client certificate will be used if
541
+ present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not
542
+ set, no client certificate will be used.
543
+
544
+ 3. The ``universe_domain`` property can be used to override the
545
+ default "googleapis.com" universe. Note that the ``api_endpoint``
546
+ property still takes precedence; and ``universe_domain`` is
547
+ currently not supported for mTLS.
548
+
549
+ client_info (google.api_core.gapic_v1.client_info.ClientInfo):
550
+ The client info used to send a user-agent string along with
551
+ API requests. If ``None``, then default info will be used.
552
+ Generally, you only need to set this if you're developing
553
+ your own client library.
554
+
555
+ Raises:
556
+ google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
557
+ creation failed for any reason.
558
+ """
559
+ self._client_options = client_options
560
+ if isinstance(self._client_options, dict):
561
+ self._client_options = client_options_lib.from_dict(self._client_options)
562
+ if self._client_options is None:
563
+ self._client_options = client_options_lib.ClientOptions()
564
+ self._client_options = cast(
565
+ client_options_lib.ClientOptions, self._client_options
566
+ )
567
+
568
+ universe_domain_opt = getattr(self._client_options, "universe_domain", None)
569
+
570
+ (
571
+ self._use_client_cert,
572
+ self._use_mtls_endpoint,
573
+ self._universe_domain_env,
574
+ ) = FileServiceClient._read_environment_variables()
575
+ self._client_cert_source = FileServiceClient._get_client_cert_source(
576
+ self._client_options.client_cert_source, self._use_client_cert
577
+ )
578
+ self._universe_domain = FileServiceClient._get_universe_domain(
579
+ universe_domain_opt, self._universe_domain_env
580
+ )
581
+ self._api_endpoint = None # updated below, depending on `transport`
582
+
583
+ # Initialize the universe domain validation.
584
+ self._is_universe_domain_valid = False
585
+
586
+ if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER
587
+ # Setup logging.
588
+ client_logging.initialize_logging()
589
+
590
+ api_key_value = getattr(self._client_options, "api_key", None)
591
+ if api_key_value and credentials:
592
+ raise ValueError(
593
+ "client_options.api_key and credentials are mutually exclusive"
594
+ )
595
+
596
+ # Save or instantiate the transport.
597
+ # Ordinarily, we provide the transport, but allowing a custom transport
598
+ # instance provides an extensibility point for unusual situations.
599
+ transport_provided = isinstance(transport, FileServiceTransport)
600
+ if transport_provided:
601
+ # transport is a FileServiceTransport instance.
602
+ if credentials or self._client_options.credentials_file or api_key_value:
603
+ raise ValueError(
604
+ "When providing a transport instance, "
605
+ "provide its credentials directly."
606
+ )
607
+ if self._client_options.scopes:
608
+ raise ValueError(
609
+ "When providing a transport instance, provide its scopes "
610
+ "directly."
611
+ )
612
+ self._transport = cast(FileServiceTransport, transport)
613
+ self._api_endpoint = self._transport.host
614
+
615
+ self._api_endpoint = self._api_endpoint or FileServiceClient._get_api_endpoint(
616
+ self._client_options.api_endpoint,
617
+ self._client_cert_source,
618
+ self._universe_domain,
619
+ self._use_mtls_endpoint,
620
+ )
621
+
622
+ if not transport_provided:
623
+ import google.auth._default # type: ignore
624
+
625
+ if api_key_value and hasattr(
626
+ google.auth._default, "get_api_key_credentials"
627
+ ):
628
+ credentials = google.auth._default.get_api_key_credentials(
629
+ api_key_value
630
+ )
631
+
632
+ transport_init: Union[
633
+ Type[FileServiceTransport], Callable[..., FileServiceTransport]
634
+ ] = (
635
+ FileServiceClient.get_transport_class(transport)
636
+ if isinstance(transport, str) or transport is None
637
+ else cast(Callable[..., FileServiceTransport], transport)
638
+ )
639
+ # initialize with the provided callable or the passed in class
640
+ self._transport = transport_init(
641
+ credentials=credentials,
642
+ credentials_file=self._client_options.credentials_file,
643
+ host=self._api_endpoint,
644
+ scopes=self._client_options.scopes,
645
+ client_cert_source_for_mtls=self._client_cert_source,
646
+ quota_project_id=self._client_options.quota_project_id,
647
+ client_info=client_info,
648
+ always_use_jwt_access=True,
649
+ api_audience=self._client_options.api_audience,
650
+ )
651
+
652
+ if "async" not in str(self._transport):
653
+ if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
654
+ std_logging.DEBUG
655
+ ): # pragma: NO COVER
656
+ _LOGGER.debug(
657
+ "Created client `google.ai.generativelanguage_v1alpha.FileServiceClient`.",
658
+ extra={
659
+ "serviceName": "google.ai.generativelanguage.v1alpha.FileService",
660
+ "universeDomain": getattr(
661
+ self._transport._credentials, "universe_domain", ""
662
+ ),
663
+ "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}",
664
+ "credentialsInfo": getattr(
665
+ self.transport._credentials, "get_cred_info", lambda: None
666
+ )(),
667
+ }
668
+ if hasattr(self._transport, "_credentials")
669
+ else {
670
+ "serviceName": "google.ai.generativelanguage.v1alpha.FileService",
671
+ "credentialsType": None,
672
+ },
673
+ )
674
+
675
+ def create_file(
676
+ self,
677
+ request: Optional[Union[file_service.CreateFileRequest, dict]] = None,
678
+ *,
679
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
680
+ timeout: Union[float, object] = gapic_v1.method.DEFAULT,
681
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
682
+ ) -> file_service.CreateFileResponse:
683
+ r"""Creates a ``File``.
684
+
685
+ .. code-block:: python
686
+
687
+ # This snippet has been automatically generated and should be regarded as a
688
+ # code template only.
689
+ # It will require modifications to work:
690
+ # - It may require correct/in-range values for request initialization.
691
+ # - It may require specifying regional endpoints when creating the service
692
+ # client as shown in:
693
+ # https://googleapis.dev/python/google-api-core/latest/client_options.html
694
+ from google.ai import generativelanguage_v1alpha
695
+
696
+ def sample_create_file():
697
+ # Create a client
698
+ client = generativelanguage_v1alpha.FileServiceClient()
699
+
700
+ # Initialize request argument(s)
701
+ request = generativelanguage_v1alpha.CreateFileRequest(
702
+ )
703
+
704
+ # Make the request
705
+ response = client.create_file(request=request)
706
+
707
+ # Handle the response
708
+ print(response)
709
+
710
+ Args:
711
+ request (Union[google.ai.generativelanguage_v1alpha.types.CreateFileRequest, dict]):
712
+ The request object. Request for ``CreateFile``.
713
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
714
+ should be retried.
715
+ timeout (float): The timeout for this request.
716
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
717
+ sent along with the request as metadata. Normally, each value must be of type `str`,
718
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
719
+ be of type `bytes`.
720
+
721
+ Returns:
722
+ google.ai.generativelanguage_v1alpha.types.CreateFileResponse:
723
+ Response for CreateFile.
724
+ """
725
+ # Create or coerce a protobuf request object.
726
+ # - Use the request object if provided (there's no risk of modifying the input as
727
+ # there are no flattened fields), or create one.
728
+ if not isinstance(request, file_service.CreateFileRequest):
729
+ request = file_service.CreateFileRequest(request)
730
+
731
+ # Wrap the RPC method; this adds retry and timeout information,
732
+ # and friendly error handling.
733
+ rpc = self._transport._wrapped_methods[self._transport.create_file]
734
+
735
+ # Validate the universe domain.
736
+ self._validate_universe_domain()
737
+
738
+ # Send the request.
739
+ response = rpc(
740
+ request,
741
+ retry=retry,
742
+ timeout=timeout,
743
+ metadata=metadata,
744
+ )
745
+
746
+ # Done; return the response.
747
+ return response
748
+
749
+ def list_files(
750
+ self,
751
+ request: Optional[Union[file_service.ListFilesRequest, dict]] = None,
752
+ *,
753
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
754
+ timeout: Union[float, object] = gapic_v1.method.DEFAULT,
755
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
756
+ ) -> pagers.ListFilesPager:
757
+ r"""Lists the metadata for ``File``\ s owned by the requesting
758
+ project.
759
+
760
+ .. code-block:: python
761
+
762
+ # This snippet has been automatically generated and should be regarded as a
763
+ # code template only.
764
+ # It will require modifications to work:
765
+ # - It may require correct/in-range values for request initialization.
766
+ # - It may require specifying regional endpoints when creating the service
767
+ # client as shown in:
768
+ # https://googleapis.dev/python/google-api-core/latest/client_options.html
769
+ from google.ai import generativelanguage_v1alpha
770
+
771
+ def sample_list_files():
772
+ # Create a client
773
+ client = generativelanguage_v1alpha.FileServiceClient()
774
+
775
+ # Initialize request argument(s)
776
+ request = generativelanguage_v1alpha.ListFilesRequest(
777
+ )
778
+
779
+ # Make the request
780
+ page_result = client.list_files(request=request)
781
+
782
+ # Handle the response
783
+ for response in page_result:
784
+ print(response)
785
+
786
+ Args:
787
+ request (Union[google.ai.generativelanguage_v1alpha.types.ListFilesRequest, dict]):
788
+ The request object. Request for ``ListFiles``.
789
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
790
+ should be retried.
791
+ timeout (float): The timeout for this request.
792
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
793
+ sent along with the request as metadata. Normally, each value must be of type `str`,
794
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
795
+ be of type `bytes`.
796
+
797
+ Returns:
798
+ google.ai.generativelanguage_v1alpha.services.file_service.pagers.ListFilesPager:
799
+ Response for ListFiles.
800
+
801
+ Iterating over this object will yield results and
802
+ resolve additional pages automatically.
803
+
804
+ """
805
+ # Create or coerce a protobuf request object.
806
+ # - Use the request object if provided (there's no risk of modifying the input as
807
+ # there are no flattened fields), or create one.
808
+ if not isinstance(request, file_service.ListFilesRequest):
809
+ request = file_service.ListFilesRequest(request)
810
+
811
+ # Wrap the RPC method; this adds retry and timeout information,
812
+ # and friendly error handling.
813
+ rpc = self._transport._wrapped_methods[self._transport.list_files]
814
+
815
+ # Validate the universe domain.
816
+ self._validate_universe_domain()
817
+
818
+ # Send the request.
819
+ response = rpc(
820
+ request,
821
+ retry=retry,
822
+ timeout=timeout,
823
+ metadata=metadata,
824
+ )
825
+
826
+ # This method is paged; wrap the response in a pager, which provides
827
+ # an `__iter__` convenience method.
828
+ response = pagers.ListFilesPager(
829
+ method=rpc,
830
+ request=request,
831
+ response=response,
832
+ retry=retry,
833
+ timeout=timeout,
834
+ metadata=metadata,
835
+ )
836
+
837
+ # Done; return the response.
838
+ return response
839
+
840
+ def get_file(
841
+ self,
842
+ request: Optional[Union[file_service.GetFileRequest, dict]] = None,
843
+ *,
844
+ name: Optional[str] = None,
845
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
846
+ timeout: Union[float, object] = gapic_v1.method.DEFAULT,
847
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
848
+ ) -> file.File:
849
+ r"""Gets the metadata for the given ``File``.
850
+
851
+ .. code-block:: python
852
+
853
+ # This snippet has been automatically generated and should be regarded as a
854
+ # code template only.
855
+ # It will require modifications to work:
856
+ # - It may require correct/in-range values for request initialization.
857
+ # - It may require specifying regional endpoints when creating the service
858
+ # client as shown in:
859
+ # https://googleapis.dev/python/google-api-core/latest/client_options.html
860
+ from google.ai import generativelanguage_v1alpha
861
+
862
+ def sample_get_file():
863
+ # Create a client
864
+ client = generativelanguage_v1alpha.FileServiceClient()
865
+
866
+ # Initialize request argument(s)
867
+ request = generativelanguage_v1alpha.GetFileRequest(
868
+ name="name_value",
869
+ )
870
+
871
+ # Make the request
872
+ response = client.get_file(request=request)
873
+
874
+ # Handle the response
875
+ print(response)
876
+
877
+ Args:
878
+ request (Union[google.ai.generativelanguage_v1alpha.types.GetFileRequest, dict]):
879
+ The request object. Request for ``GetFile``.
880
+ name (str):
881
+ Required. The name of the ``File`` to get. Example:
882
+ ``files/abc-123``
883
+
884
+ This corresponds to the ``name`` field
885
+ on the ``request`` instance; if ``request`` is provided, this
886
+ should not be set.
887
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
888
+ should be retried.
889
+ timeout (float): The timeout for this request.
890
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
891
+ sent along with the request as metadata. Normally, each value must be of type `str`,
892
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
893
+ be of type `bytes`.
894
+
895
+ Returns:
896
+ google.ai.generativelanguage_v1alpha.types.File:
897
+ A file uploaded to the API.
898
+ Next ID: 15
899
+
900
+ """
901
+ # Create or coerce a protobuf request object.
902
+ # - Quick check: If we got a request object, we should *not* have
903
+ # gotten any keyword arguments that map to the request.
904
+ has_flattened_params = any([name])
905
+ if request is not None and has_flattened_params:
906
+ raise ValueError(
907
+ "If the `request` argument is set, then none of "
908
+ "the individual field arguments should be set."
909
+ )
910
+
911
+ # - Use the request object if provided (there's no risk of modifying the input as
912
+ # there are no flattened fields), or create one.
913
+ if not isinstance(request, file_service.GetFileRequest):
914
+ request = file_service.GetFileRequest(request)
915
+ # If we have keyword arguments corresponding to fields on the
916
+ # request, apply these.
917
+ if name is not None:
918
+ request.name = name
919
+
920
+ # Wrap the RPC method; this adds retry and timeout information,
921
+ # and friendly error handling.
922
+ rpc = self._transport._wrapped_methods[self._transport.get_file]
923
+
924
+ # Certain fields should be provided within the metadata header;
925
+ # add these here.
926
+ metadata = tuple(metadata) + (
927
+ gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
928
+ )
929
+
930
+ # Validate the universe domain.
931
+ self._validate_universe_domain()
932
+
933
+ # Send the request.
934
+ response = rpc(
935
+ request,
936
+ retry=retry,
937
+ timeout=timeout,
938
+ metadata=metadata,
939
+ )
940
+
941
+ # Done; return the response.
942
+ return response
943
+
944
+ def delete_file(
945
+ self,
946
+ request: Optional[Union[file_service.DeleteFileRequest, dict]] = None,
947
+ *,
948
+ name: Optional[str] = None,
949
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
950
+ timeout: Union[float, object] = gapic_v1.method.DEFAULT,
951
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
952
+ ) -> None:
953
+ r"""Deletes the ``File``.
954
+
955
+ .. code-block:: python
956
+
957
+ # This snippet has been automatically generated and should be regarded as a
958
+ # code template only.
959
+ # It will require modifications to work:
960
+ # - It may require correct/in-range values for request initialization.
961
+ # - It may require specifying regional endpoints when creating the service
962
+ # client as shown in:
963
+ # https://googleapis.dev/python/google-api-core/latest/client_options.html
964
+ from google.ai import generativelanguage_v1alpha
965
+
966
+ def sample_delete_file():
967
+ # Create a client
968
+ client = generativelanguage_v1alpha.FileServiceClient()
969
+
970
+ # Initialize request argument(s)
971
+ request = generativelanguage_v1alpha.DeleteFileRequest(
972
+ name="name_value",
973
+ )
974
+
975
+ # Make the request
976
+ client.delete_file(request=request)
977
+
978
+ Args:
979
+ request (Union[google.ai.generativelanguage_v1alpha.types.DeleteFileRequest, dict]):
980
+ The request object. Request for ``DeleteFile``.
981
+ name (str):
982
+ Required. The name of the ``File`` to delete. Example:
983
+ ``files/abc-123``
984
+
985
+ This corresponds to the ``name`` field
986
+ on the ``request`` instance; if ``request`` is provided, this
987
+ should not be set.
988
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
989
+ should be retried.
990
+ timeout (float): The timeout for this request.
991
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
992
+ sent along with the request as metadata. Normally, each value must be of type `str`,
993
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
994
+ be of type `bytes`.
995
+ """
996
+ # Create or coerce a protobuf request object.
997
+ # - Quick check: If we got a request object, we should *not* have
998
+ # gotten any keyword arguments that map to the request.
999
+ has_flattened_params = any([name])
1000
+ if request is not None and has_flattened_params:
1001
+ raise ValueError(
1002
+ "If the `request` argument is set, then none of "
1003
+ "the individual field arguments should be set."
1004
+ )
1005
+
1006
+ # - Use the request object if provided (there's no risk of modifying the input as
1007
+ # there are no flattened fields), or create one.
1008
+ if not isinstance(request, file_service.DeleteFileRequest):
1009
+ request = file_service.DeleteFileRequest(request)
1010
+ # If we have keyword arguments corresponding to fields on the
1011
+ # request, apply these.
1012
+ if name is not None:
1013
+ request.name = name
1014
+
1015
+ # Wrap the RPC method; this adds retry and timeout information,
1016
+ # and friendly error handling.
1017
+ rpc = self._transport._wrapped_methods[self._transport.delete_file]
1018
+
1019
+ # Certain fields should be provided within the metadata header;
1020
+ # add these here.
1021
+ metadata = tuple(metadata) + (
1022
+ gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
1023
+ )
1024
+
1025
+ # Validate the universe domain.
1026
+ self._validate_universe_domain()
1027
+
1028
+ # Send the request.
1029
+ rpc(
1030
+ request,
1031
+ retry=retry,
1032
+ timeout=timeout,
1033
+ metadata=metadata,
1034
+ )
1035
+
1036
+ def __enter__(self) -> "FileServiceClient":
1037
+ return self
1038
+
1039
+ def __exit__(self, type, value, traceback):
1040
+ """Releases underlying transport's resources.
1041
+
1042
+ .. warning::
1043
+ ONLY use as a context manager if the transport is NOT shared
1044
+ with other clients! Exiting the with block will CLOSE the transport
1045
+ and may cause errors in other clients!
1046
+ """
1047
+ self.transport.close()
1048
+
1049
+ def list_operations(
1050
+ self,
1051
+ request: Optional[operations_pb2.ListOperationsRequest] = None,
1052
+ *,
1053
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
1054
+ timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1055
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1056
+ ) -> operations_pb2.ListOperationsResponse:
1057
+ r"""Lists operations that match the specified filter in the request.
1058
+
1059
+ Args:
1060
+ request (:class:`~.operations_pb2.ListOperationsRequest`):
1061
+ The request object. Request message for
1062
+ `ListOperations` method.
1063
+ retry (google.api_core.retry.Retry): Designation of what errors,
1064
+ if any, should be retried.
1065
+ timeout (float): The timeout for this request.
1066
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1067
+ sent along with the request as metadata. Normally, each value must be of type `str`,
1068
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
1069
+ be of type `bytes`.
1070
+ Returns:
1071
+ ~.operations_pb2.ListOperationsResponse:
1072
+ Response message for ``ListOperations`` method.
1073
+ """
1074
+ # Create or coerce a protobuf request object.
1075
+ # The request isn't a proto-plus wrapped type,
1076
+ # so it must be constructed via keyword expansion.
1077
+ if isinstance(request, dict):
1078
+ request = operations_pb2.ListOperationsRequest(**request)
1079
+
1080
+ # Wrap the RPC method; this adds retry and timeout information,
1081
+ # and friendly error handling.
1082
+ rpc = self._transport._wrapped_methods[self._transport.list_operations]
1083
+
1084
+ # Certain fields should be provided within the metadata header;
1085
+ # add these here.
1086
+ metadata = tuple(metadata) + (
1087
+ gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
1088
+ )
1089
+
1090
+ # Validate the universe domain.
1091
+ self._validate_universe_domain()
1092
+
1093
+ # Send the request.
1094
+ response = rpc(
1095
+ request,
1096
+ retry=retry,
1097
+ timeout=timeout,
1098
+ metadata=metadata,
1099
+ )
1100
+
1101
+ # Done; return the response.
1102
+ return response
1103
+
1104
+ def get_operation(
1105
+ self,
1106
+ request: Optional[operations_pb2.GetOperationRequest] = None,
1107
+ *,
1108
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
1109
+ timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1110
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1111
+ ) -> operations_pb2.Operation:
1112
+ r"""Gets the latest state of a long-running operation.
1113
+
1114
+ Args:
1115
+ request (:class:`~.operations_pb2.GetOperationRequest`):
1116
+ The request object. Request message for
1117
+ `GetOperation` method.
1118
+ retry (google.api_core.retry.Retry): Designation of what errors,
1119
+ if any, should be retried.
1120
+ timeout (float): The timeout for this request.
1121
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1122
+ sent along with the request as metadata. Normally, each value must be of type `str`,
1123
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
1124
+ be of type `bytes`.
1125
+ Returns:
1126
+ ~.operations_pb2.Operation:
1127
+ An ``Operation`` object.
1128
+ """
1129
+ # Create or coerce a protobuf request object.
1130
+ # The request isn't a proto-plus wrapped type,
1131
+ # so it must be constructed via keyword expansion.
1132
+ if isinstance(request, dict):
1133
+ request = operations_pb2.GetOperationRequest(**request)
1134
+
1135
+ # Wrap the RPC method; this adds retry and timeout information,
1136
+ # and friendly error handling.
1137
+ rpc = self._transport._wrapped_methods[self._transport.get_operation]
1138
+
1139
+ # Certain fields should be provided within the metadata header;
1140
+ # add these here.
1141
+ metadata = tuple(metadata) + (
1142
+ gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
1143
+ )
1144
+
1145
+ # Validate the universe domain.
1146
+ self._validate_universe_domain()
1147
+
1148
+ # Send the request.
1149
+ response = rpc(
1150
+ request,
1151
+ retry=retry,
1152
+ timeout=timeout,
1153
+ metadata=metadata,
1154
+ )
1155
+
1156
+ # Done; return the response.
1157
+ return response
1158
+
1159
+
1160
+ DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
1161
+ gapic_version=package_version.__version__
1162
+ )
1163
+
1164
+
1165
+ __all__ = ("FileServiceClient",)
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/file_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 file, file_service
42
+
43
+
44
+ class ListFilesPager:
45
+ """A pager for iterating through ``list_files`` requests.
46
+
47
+ This class thinly wraps an initial
48
+ :class:`google.ai.generativelanguage_v1alpha.types.ListFilesResponse` object, and
49
+ provides an ``__iter__`` method to iterate through its
50
+ ``files`` field.
51
+
52
+ If there are more pages, the ``__iter__`` method will make additional
53
+ ``ListFiles`` requests and continue to iterate
54
+ through the ``files`` field on the
55
+ corresponding responses.
56
+
57
+ All the usual :class:`google.ai.generativelanguage_v1alpha.types.ListFilesResponse`
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[..., file_service.ListFilesResponse],
65
+ request: file_service.ListFilesRequest,
66
+ response: file_service.ListFilesResponse,
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.ListFilesRequest):
78
+ The initial request object.
79
+ response (google.ai.generativelanguage_v1alpha.types.ListFilesResponse):
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 = file_service.ListFilesRequest(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[file_service.ListFilesResponse]:
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[file.File]:
113
+ for page in self.pages:
114
+ yield from page.files
115
+
116
+ def __repr__(self) -> str:
117
+ return "{0}<{1!r}>".format(self.__class__.__name__, self._response)
118
+
119
+
120
+ class ListFilesAsyncPager:
121
+ """A pager for iterating through ``list_files`` requests.
122
+
123
+ This class thinly wraps an initial
124
+ :class:`google.ai.generativelanguage_v1alpha.types.ListFilesResponse` object, and
125
+ provides an ``__aiter__`` method to iterate through its
126
+ ``files`` field.
127
+
128
+ If there are more pages, the ``__aiter__`` method will make additional
129
+ ``ListFiles`` requests and continue to iterate
130
+ through the ``files`` field on the
131
+ corresponding responses.
132
+
133
+ All the usual :class:`google.ai.generativelanguage_v1alpha.types.ListFilesResponse`
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[file_service.ListFilesResponse]],
141
+ request: file_service.ListFilesRequest,
142
+ response: file_service.ListFilesResponse,
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.ListFilesRequest):
154
+ The initial request object.
155
+ response (google.ai.generativelanguage_v1alpha.types.ListFilesResponse):
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 = file_service.ListFilesRequest(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[file_service.ListFilesResponse]:
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[file.File]:
189
+ async def async_generator():
190
+ async for page in self.pages:
191
+ for response in page.files:
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/file_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 FileServiceTransport
20
+ from .grpc import FileServiceGrpcTransport
21
+ from .grpc_asyncio import FileServiceGrpcAsyncIOTransport
22
+ from .rest import FileServiceRestInterceptor, FileServiceRestTransport
23
+
24
+ # Compile a registry of transports.
25
+ _transport_registry = OrderedDict() # type: Dict[str, Type[FileServiceTransport]]
26
+ _transport_registry["grpc"] = FileServiceGrpcTransport
27
+ _transport_registry["grpc_asyncio"] = FileServiceGrpcAsyncIOTransport
28
+ _transport_registry["rest"] = FileServiceRestTransport
29
+
30
+ __all__ = (
31
+ "FileServiceTransport",
32
+ "FileServiceGrpcTransport",
33
+ "FileServiceGrpcAsyncIOTransport",
34
+ "FileServiceRestTransport",
35
+ "FileServiceRestInterceptor",
36
+ )
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/file_service/transports/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (890 Bytes). View file
 
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/file_service/transports/__pycache__/base.cpython-311.pyc ADDED
Binary file (9.52 kB). View file
 
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/file_service/transports/__pycache__/grpc.cpython-311.pyc ADDED
Binary file (20.9 kB). View file
 
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/file_service/transports/__pycache__/grpc_asyncio.cpython-311.pyc ADDED
Binary file (23.3 kB). View file
 
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/file_service/transports/__pycache__/rest.cpython-311.pyc ADDED
Binary file (46.1 kB). View file
 
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/file_service/transports/__pycache__/rest_base.cpython-311.pyc ADDED
Binary file (15.2 kB). View file
 
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/file_service/transports/base.py ADDED
@@ -0,0 +1,239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 file, file_service
31
+
32
+ DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
33
+ gapic_version=package_version.__version__
34
+ )
35
+
36
+
37
+ class FileServiceTransport(abc.ABC):
38
+ """Abstract transport class for FileService."""
39
+
40
+ AUTH_SCOPES = ()
41
+
42
+ DEFAULT_HOST: str = "generativelanguage.googleapis.com"
43
+
44
+ def __init__(
45
+ self,
46
+ *,
47
+ host: str = DEFAULT_HOST,
48
+ credentials: Optional[ga_credentials.Credentials] = None,
49
+ credentials_file: Optional[str] = None,
50
+ scopes: Optional[Sequence[str]] = None,
51
+ quota_project_id: Optional[str] = None,
52
+ client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
53
+ always_use_jwt_access: Optional[bool] = False,
54
+ api_audience: Optional[str] = None,
55
+ **kwargs,
56
+ ) -> None:
57
+ """Instantiate the transport.
58
+
59
+ Args:
60
+ host (Optional[str]):
61
+ The hostname to connect to (default: 'generativelanguage.googleapis.com').
62
+ credentials (Optional[google.auth.credentials.Credentials]): The
63
+ authorization credentials to attach to requests. These
64
+ credentials identify the application to the service; if none
65
+ are specified, the client will attempt to ascertain the
66
+ credentials from the environment.
67
+ credentials_file (Optional[str]): A file with credentials that can
68
+ be loaded with :func:`google.auth.load_credentials_from_file`.
69
+ This argument is mutually exclusive with credentials.
70
+ scopes (Optional[Sequence[str]]): A list of scopes.
71
+ quota_project_id (Optional[str]): An optional project to use for billing
72
+ and quota.
73
+ client_info (google.api_core.gapic_v1.client_info.ClientInfo):
74
+ The client info used to send a user-agent string along with
75
+ API requests. If ``None``, then default info will be used.
76
+ Generally, you only need to set this if you're developing
77
+ your own client library.
78
+ always_use_jwt_access (Optional[bool]): Whether self signed JWT should
79
+ be used for service account credentials.
80
+ """
81
+
82
+ scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES}
83
+
84
+ # Save the scopes.
85
+ self._scopes = scopes
86
+ if not hasattr(self, "_ignore_credentials"):
87
+ self._ignore_credentials: bool = False
88
+
89
+ # If no credentials are provided, then determine the appropriate
90
+ # defaults.
91
+ if credentials and credentials_file:
92
+ raise core_exceptions.DuplicateCredentialArgs(
93
+ "'credentials_file' and 'credentials' are mutually exclusive"
94
+ )
95
+
96
+ if credentials_file is not None:
97
+ credentials, _ = google.auth.load_credentials_from_file(
98
+ credentials_file, **scopes_kwargs, quota_project_id=quota_project_id
99
+ )
100
+ elif credentials is None and not self._ignore_credentials:
101
+ credentials, _ = google.auth.default(
102
+ **scopes_kwargs, quota_project_id=quota_project_id
103
+ )
104
+ # Don't apply audience if the credentials file passed from user.
105
+ if hasattr(credentials, "with_gdch_audience"):
106
+ credentials = credentials.with_gdch_audience(
107
+ api_audience if api_audience else host
108
+ )
109
+
110
+ # If the credentials are service account credentials, then always try to use self signed JWT.
111
+ if (
112
+ always_use_jwt_access
113
+ and isinstance(credentials, service_account.Credentials)
114
+ and hasattr(service_account.Credentials, "with_always_use_jwt_access")
115
+ ):
116
+ credentials = credentials.with_always_use_jwt_access(True)
117
+
118
+ # Save the credentials.
119
+ self._credentials = credentials
120
+
121
+ # Save the hostname. Default to port 443 (HTTPS) if none is specified.
122
+ if ":" not in host:
123
+ host += ":443"
124
+ self._host = host
125
+
126
+ @property
127
+ def host(self):
128
+ return self._host
129
+
130
+ def _prep_wrapped_messages(self, client_info):
131
+ # Precompute the wrapped methods.
132
+ self._wrapped_methods = {
133
+ self.create_file: gapic_v1.method.wrap_method(
134
+ self.create_file,
135
+ default_timeout=None,
136
+ client_info=client_info,
137
+ ),
138
+ self.list_files: gapic_v1.method.wrap_method(
139
+ self.list_files,
140
+ default_timeout=None,
141
+ client_info=client_info,
142
+ ),
143
+ self.get_file: gapic_v1.method.wrap_method(
144
+ self.get_file,
145
+ default_timeout=None,
146
+ client_info=client_info,
147
+ ),
148
+ self.delete_file: gapic_v1.method.wrap_method(
149
+ self.delete_file,
150
+ default_timeout=None,
151
+ client_info=client_info,
152
+ ),
153
+ self.get_operation: gapic_v1.method.wrap_method(
154
+ self.get_operation,
155
+ default_timeout=None,
156
+ client_info=client_info,
157
+ ),
158
+ self.list_operations: gapic_v1.method.wrap_method(
159
+ self.list_operations,
160
+ default_timeout=None,
161
+ client_info=client_info,
162
+ ),
163
+ }
164
+
165
+ def close(self):
166
+ """Closes resources associated with the transport.
167
+
168
+ .. warning::
169
+ Only call this method if the transport is NOT shared
170
+ with other clients - this may cause errors in other clients!
171
+ """
172
+ raise NotImplementedError()
173
+
174
+ @property
175
+ def create_file(
176
+ self,
177
+ ) -> Callable[
178
+ [file_service.CreateFileRequest],
179
+ Union[
180
+ file_service.CreateFileResponse, Awaitable[file_service.CreateFileResponse]
181
+ ],
182
+ ]:
183
+ raise NotImplementedError()
184
+
185
+ @property
186
+ def list_files(
187
+ self,
188
+ ) -> Callable[
189
+ [file_service.ListFilesRequest],
190
+ Union[
191
+ file_service.ListFilesResponse, Awaitable[file_service.ListFilesResponse]
192
+ ],
193
+ ]:
194
+ raise NotImplementedError()
195
+
196
+ @property
197
+ def get_file(
198
+ self,
199
+ ) -> Callable[
200
+ [file_service.GetFileRequest], Union[file.File, Awaitable[file.File]]
201
+ ]:
202
+ raise NotImplementedError()
203
+
204
+ @property
205
+ def delete_file(
206
+ self,
207
+ ) -> Callable[
208
+ [file_service.DeleteFileRequest],
209
+ Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]],
210
+ ]:
211
+ raise NotImplementedError()
212
+
213
+ @property
214
+ def list_operations(
215
+ self,
216
+ ) -> Callable[
217
+ [operations_pb2.ListOperationsRequest],
218
+ Union[
219
+ operations_pb2.ListOperationsResponse,
220
+ Awaitable[operations_pb2.ListOperationsResponse],
221
+ ],
222
+ ]:
223
+ raise NotImplementedError()
224
+
225
+ @property
226
+ def get_operation(
227
+ self,
228
+ ) -> Callable[
229
+ [operations_pb2.GetOperationRequest],
230
+ Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]],
231
+ ]:
232
+ raise NotImplementedError()
233
+
234
+ @property
235
+ def kind(self) -> str:
236
+ raise NotImplementedError()
237
+
238
+
239
+ __all__ = ("FileServiceTransport",)
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/file_service/transports/grpc.py ADDED
@@ -0,0 +1,472 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 file, file_service
34
+
35
+ from .base import DEFAULT_CLIENT_INFO, FileServiceTransport
36
+
37
+ try:
38
+ from google.api_core import client_logging # type: ignore
39
+
40
+ CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER
41
+ except ImportError: # pragma: NO COVER
42
+ CLIENT_LOGGING_SUPPORTED = False
43
+
44
+ _LOGGER = std_logging.getLogger(__name__)
45
+
46
+
47
+ class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER
48
+ def intercept_unary_unary(self, continuation, client_call_details, request):
49
+ logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
50
+ std_logging.DEBUG
51
+ )
52
+ if logging_enabled: # pragma: NO COVER
53
+ request_metadata = client_call_details.metadata
54
+ if isinstance(request, proto.Message):
55
+ request_payload = type(request).to_json(request)
56
+ elif isinstance(request, google.protobuf.message.Message):
57
+ request_payload = MessageToJson(request)
58
+ else:
59
+ request_payload = f"{type(request).__name__}: {pickle.dumps(request)}"
60
+
61
+ request_metadata = {
62
+ key: value.decode("utf-8") if isinstance(value, bytes) else value
63
+ for key, value in request_metadata
64
+ }
65
+ grpc_request = {
66
+ "payload": request_payload,
67
+ "requestMethod": "grpc",
68
+ "metadata": dict(request_metadata),
69
+ }
70
+ _LOGGER.debug(
71
+ f"Sending request for {client_call_details.method}",
72
+ extra={
73
+ "serviceName": "google.ai.generativelanguage.v1alpha.FileService",
74
+ "rpcName": client_call_details.method,
75
+ "request": grpc_request,
76
+ "metadata": grpc_request["metadata"],
77
+ },
78
+ )
79
+
80
+ response = continuation(client_call_details, request)
81
+ if logging_enabled: # pragma: NO COVER
82
+ response_metadata = response.trailing_metadata()
83
+ # Convert gRPC metadata `<class 'grpc.aio._metadata.Metadata'>` to list of tuples
84
+ metadata = (
85
+ dict([(k, str(v)) for k, v in response_metadata])
86
+ if response_metadata
87
+ else None
88
+ )
89
+ result = response.result()
90
+ if isinstance(result, proto.Message):
91
+ response_payload = type(result).to_json(result)
92
+ elif isinstance(result, google.protobuf.message.Message):
93
+ response_payload = MessageToJson(result)
94
+ else:
95
+ response_payload = f"{type(result).__name__}: {pickle.dumps(result)}"
96
+ grpc_response = {
97
+ "payload": response_payload,
98
+ "metadata": metadata,
99
+ "status": "OK",
100
+ }
101
+ _LOGGER.debug(
102
+ f"Received response for {client_call_details.method}.",
103
+ extra={
104
+ "serviceName": "google.ai.generativelanguage.v1alpha.FileService",
105
+ "rpcName": client_call_details.method,
106
+ "response": grpc_response,
107
+ "metadata": grpc_response["metadata"],
108
+ },
109
+ )
110
+ return response
111
+
112
+
113
+ class FileServiceGrpcTransport(FileServiceTransport):
114
+ """gRPC backend transport for FileService.
115
+
116
+ An API for uploading and managing files.
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 create_file(
327
+ self,
328
+ ) -> Callable[[file_service.CreateFileRequest], file_service.CreateFileResponse]:
329
+ r"""Return a callable for the create file method over gRPC.
330
+
331
+ Creates a ``File``.
332
+
333
+ Returns:
334
+ Callable[[~.CreateFileRequest],
335
+ ~.CreateFileResponse]:
336
+ A function that, when called, will call the underlying RPC
337
+ on the server.
338
+ """
339
+ # Generate a "stub function" on-the-fly which will actually make
340
+ # the request.
341
+ # gRPC handles serialization and deserialization, so we just need
342
+ # to pass in the functions for each.
343
+ if "create_file" not in self._stubs:
344
+ self._stubs["create_file"] = self._logged_channel.unary_unary(
345
+ "/google.ai.generativelanguage.v1alpha.FileService/CreateFile",
346
+ request_serializer=file_service.CreateFileRequest.serialize,
347
+ response_deserializer=file_service.CreateFileResponse.deserialize,
348
+ )
349
+ return self._stubs["create_file"]
350
+
351
+ @property
352
+ def list_files(
353
+ self,
354
+ ) -> Callable[[file_service.ListFilesRequest], file_service.ListFilesResponse]:
355
+ r"""Return a callable for the list files method over gRPC.
356
+
357
+ Lists the metadata for ``File``\ s owned by the requesting
358
+ project.
359
+
360
+ Returns:
361
+ Callable[[~.ListFilesRequest],
362
+ ~.ListFilesResponse]:
363
+ A function that, when called, will call the underlying RPC
364
+ on the server.
365
+ """
366
+ # Generate a "stub function" on-the-fly which will actually make
367
+ # the request.
368
+ # gRPC handles serialization and deserialization, so we just need
369
+ # to pass in the functions for each.
370
+ if "list_files" not in self._stubs:
371
+ self._stubs["list_files"] = self._logged_channel.unary_unary(
372
+ "/google.ai.generativelanguage.v1alpha.FileService/ListFiles",
373
+ request_serializer=file_service.ListFilesRequest.serialize,
374
+ response_deserializer=file_service.ListFilesResponse.deserialize,
375
+ )
376
+ return self._stubs["list_files"]
377
+
378
+ @property
379
+ def get_file(self) -> Callable[[file_service.GetFileRequest], file.File]:
380
+ r"""Return a callable for the get file method over gRPC.
381
+
382
+ Gets the metadata for the given ``File``.
383
+
384
+ Returns:
385
+ Callable[[~.GetFileRequest],
386
+ ~.File]:
387
+ A function that, when called, will call the underlying RPC
388
+ on the server.
389
+ """
390
+ # Generate a "stub function" on-the-fly which will actually make
391
+ # the request.
392
+ # gRPC handles serialization and deserialization, so we just need
393
+ # to pass in the functions for each.
394
+ if "get_file" not in self._stubs:
395
+ self._stubs["get_file"] = self._logged_channel.unary_unary(
396
+ "/google.ai.generativelanguage.v1alpha.FileService/GetFile",
397
+ request_serializer=file_service.GetFileRequest.serialize,
398
+ response_deserializer=file.File.deserialize,
399
+ )
400
+ return self._stubs["get_file"]
401
+
402
+ @property
403
+ def delete_file(
404
+ self,
405
+ ) -> Callable[[file_service.DeleteFileRequest], empty_pb2.Empty]:
406
+ r"""Return a callable for the delete file method over gRPC.
407
+
408
+ Deletes the ``File``.
409
+
410
+ Returns:
411
+ Callable[[~.DeleteFileRequest],
412
+ ~.Empty]:
413
+ A function that, when called, will call the underlying RPC
414
+ on the server.
415
+ """
416
+ # Generate a "stub function" on-the-fly which will actually make
417
+ # the request.
418
+ # gRPC handles serialization and deserialization, so we just need
419
+ # to pass in the functions for each.
420
+ if "delete_file" not in self._stubs:
421
+ self._stubs["delete_file"] = self._logged_channel.unary_unary(
422
+ "/google.ai.generativelanguage.v1alpha.FileService/DeleteFile",
423
+ request_serializer=file_service.DeleteFileRequest.serialize,
424
+ response_deserializer=empty_pb2.Empty.FromString,
425
+ )
426
+ return self._stubs["delete_file"]
427
+
428
+ def close(self):
429
+ self._logged_channel.close()
430
+
431
+ @property
432
+ def get_operation(
433
+ self,
434
+ ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]:
435
+ r"""Return a callable for the get_operation method over gRPC."""
436
+ # Generate a "stub function" on-the-fly which will actually make
437
+ # the request.
438
+ # gRPC handles serialization and deserialization, so we just need
439
+ # to pass in the functions for each.
440
+ if "get_operation" not in self._stubs:
441
+ self._stubs["get_operation"] = self._logged_channel.unary_unary(
442
+ "/google.longrunning.Operations/GetOperation",
443
+ request_serializer=operations_pb2.GetOperationRequest.SerializeToString,
444
+ response_deserializer=operations_pb2.Operation.FromString,
445
+ )
446
+ return self._stubs["get_operation"]
447
+
448
+ @property
449
+ def list_operations(
450
+ self,
451
+ ) -> Callable[
452
+ [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse
453
+ ]:
454
+ r"""Return a callable for the list_operations method over gRPC."""
455
+ # Generate a "stub function" on-the-fly which will actually make
456
+ # the request.
457
+ # gRPC handles serialization and deserialization, so we just need
458
+ # to pass in the functions for each.
459
+ if "list_operations" not in self._stubs:
460
+ self._stubs["list_operations"] = self._logged_channel.unary_unary(
461
+ "/google.longrunning.Operations/ListOperations",
462
+ request_serializer=operations_pb2.ListOperationsRequest.SerializeToString,
463
+ response_deserializer=operations_pb2.ListOperationsResponse.FromString,
464
+ )
465
+ return self._stubs["list_operations"]
466
+
467
+ @property
468
+ def kind(self) -> str:
469
+ return "grpc"
470
+
471
+
472
+ __all__ = ("FileServiceGrpcTransport",)
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/file_service/transports/grpc_asyncio.py ADDED
@@ -0,0 +1,523 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 file, file_service
37
+
38
+ from .base import DEFAULT_CLIENT_INFO, FileServiceTransport
39
+ from .grpc import FileServiceGrpcTransport
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 _LoggingClientAIOInterceptor(
52
+ grpc.aio.UnaryUnaryClientInterceptor
53
+ ): # pragma: NO COVER
54
+ async def intercept_unary_unary(self, continuation, client_call_details, request):
55
+ logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
56
+ std_logging.DEBUG
57
+ )
58
+ if logging_enabled: # pragma: NO COVER
59
+ request_metadata = client_call_details.metadata
60
+ if isinstance(request, proto.Message):
61
+ request_payload = type(request).to_json(request)
62
+ elif isinstance(request, google.protobuf.message.Message):
63
+ request_payload = MessageToJson(request)
64
+ else:
65
+ request_payload = f"{type(request).__name__}: {pickle.dumps(request)}"
66
+
67
+ request_metadata = {
68
+ key: value.decode("utf-8") if isinstance(value, bytes) else value
69
+ for key, value in request_metadata
70
+ }
71
+ grpc_request = {
72
+ "payload": request_payload,
73
+ "requestMethod": "grpc",
74
+ "metadata": dict(request_metadata),
75
+ }
76
+ _LOGGER.debug(
77
+ f"Sending request for {client_call_details.method}",
78
+ extra={
79
+ "serviceName": "google.ai.generativelanguage.v1alpha.FileService",
80
+ "rpcName": str(client_call_details.method),
81
+ "request": grpc_request,
82
+ "metadata": grpc_request["metadata"],
83
+ },
84
+ )
85
+ response = await continuation(client_call_details, request)
86
+ if logging_enabled: # pragma: NO COVER
87
+ response_metadata = await response.trailing_metadata()
88
+ # Convert gRPC metadata `<class 'grpc.aio._metadata.Metadata'>` to list of tuples
89
+ metadata = (
90
+ dict([(k, str(v)) for k, v in response_metadata])
91
+ if response_metadata
92
+ else None
93
+ )
94
+ result = await response
95
+ if isinstance(result, proto.Message):
96
+ response_payload = type(result).to_json(result)
97
+ elif isinstance(result, google.protobuf.message.Message):
98
+ response_payload = MessageToJson(result)
99
+ else:
100
+ response_payload = f"{type(result).__name__}: {pickle.dumps(result)}"
101
+ grpc_response = {
102
+ "payload": response_payload,
103
+ "metadata": metadata,
104
+ "status": "OK",
105
+ }
106
+ _LOGGER.debug(
107
+ f"Received response to rpc {client_call_details.method}.",
108
+ extra={
109
+ "serviceName": "google.ai.generativelanguage.v1alpha.FileService",
110
+ "rpcName": str(client_call_details.method),
111
+ "response": grpc_response,
112
+ "metadata": grpc_response["metadata"],
113
+ },
114
+ )
115
+ return response
116
+
117
+
118
+ class FileServiceGrpcAsyncIOTransport(FileServiceTransport):
119
+ """gRPC AsyncIO backend transport for FileService.
120
+
121
+ An API for uploading and managing files.
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 create_file(
334
+ self,
335
+ ) -> Callable[
336
+ [file_service.CreateFileRequest], Awaitable[file_service.CreateFileResponse]
337
+ ]:
338
+ r"""Return a callable for the create file method over gRPC.
339
+
340
+ Creates a ``File``.
341
+
342
+ Returns:
343
+ Callable[[~.CreateFileRequest],
344
+ Awaitable[~.CreateFileResponse]]:
345
+ A function that, when called, will call the underlying RPC
346
+ on the server.
347
+ """
348
+ # Generate a "stub function" on-the-fly which will actually make
349
+ # the request.
350
+ # gRPC handles serialization and deserialization, so we just need
351
+ # to pass in the functions for each.
352
+ if "create_file" not in self._stubs:
353
+ self._stubs["create_file"] = self._logged_channel.unary_unary(
354
+ "/google.ai.generativelanguage.v1alpha.FileService/CreateFile",
355
+ request_serializer=file_service.CreateFileRequest.serialize,
356
+ response_deserializer=file_service.CreateFileResponse.deserialize,
357
+ )
358
+ return self._stubs["create_file"]
359
+
360
+ @property
361
+ def list_files(
362
+ self,
363
+ ) -> Callable[
364
+ [file_service.ListFilesRequest], Awaitable[file_service.ListFilesResponse]
365
+ ]:
366
+ r"""Return a callable for the list files method over gRPC.
367
+
368
+ Lists the metadata for ``File``\ s owned by the requesting
369
+ project.
370
+
371
+ Returns:
372
+ Callable[[~.ListFilesRequest],
373
+ Awaitable[~.ListFilesResponse]]:
374
+ A function that, when called, will call the underlying RPC
375
+ on the server.
376
+ """
377
+ # Generate a "stub function" on-the-fly which will actually make
378
+ # the request.
379
+ # gRPC handles serialization and deserialization, so we just need
380
+ # to pass in the functions for each.
381
+ if "list_files" not in self._stubs:
382
+ self._stubs["list_files"] = self._logged_channel.unary_unary(
383
+ "/google.ai.generativelanguage.v1alpha.FileService/ListFiles",
384
+ request_serializer=file_service.ListFilesRequest.serialize,
385
+ response_deserializer=file_service.ListFilesResponse.deserialize,
386
+ )
387
+ return self._stubs["list_files"]
388
+
389
+ @property
390
+ def get_file(self) -> Callable[[file_service.GetFileRequest], Awaitable[file.File]]:
391
+ r"""Return a callable for the get file method over gRPC.
392
+
393
+ Gets the metadata for the given ``File``.
394
+
395
+ Returns:
396
+ Callable[[~.GetFileRequest],
397
+ Awaitable[~.File]]:
398
+ A function that, when called, will call the underlying RPC
399
+ on the server.
400
+ """
401
+ # Generate a "stub function" on-the-fly which will actually make
402
+ # the request.
403
+ # gRPC handles serialization and deserialization, so we just need
404
+ # to pass in the functions for each.
405
+ if "get_file" not in self._stubs:
406
+ self._stubs["get_file"] = self._logged_channel.unary_unary(
407
+ "/google.ai.generativelanguage.v1alpha.FileService/GetFile",
408
+ request_serializer=file_service.GetFileRequest.serialize,
409
+ response_deserializer=file.File.deserialize,
410
+ )
411
+ return self._stubs["get_file"]
412
+
413
+ @property
414
+ def delete_file(
415
+ self,
416
+ ) -> Callable[[file_service.DeleteFileRequest], Awaitable[empty_pb2.Empty]]:
417
+ r"""Return a callable for the delete file method over gRPC.
418
+
419
+ Deletes the ``File``.
420
+
421
+ Returns:
422
+ Callable[[~.DeleteFileRequest],
423
+ Awaitable[~.Empty]]:
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 "delete_file" not in self._stubs:
432
+ self._stubs["delete_file"] = self._logged_channel.unary_unary(
433
+ "/google.ai.generativelanguage.v1alpha.FileService/DeleteFile",
434
+ request_serializer=file_service.DeleteFileRequest.serialize,
435
+ response_deserializer=empty_pb2.Empty.FromString,
436
+ )
437
+ return self._stubs["delete_file"]
438
+
439
+ def _prep_wrapped_messages(self, client_info):
440
+ """Precompute the wrapped methods, overriding the base class method to use async wrappers."""
441
+ self._wrapped_methods = {
442
+ self.create_file: self._wrap_method(
443
+ self.create_file,
444
+ default_timeout=None,
445
+ client_info=client_info,
446
+ ),
447
+ self.list_files: self._wrap_method(
448
+ self.list_files,
449
+ default_timeout=None,
450
+ client_info=client_info,
451
+ ),
452
+ self.get_file: self._wrap_method(
453
+ self.get_file,
454
+ default_timeout=None,
455
+ client_info=client_info,
456
+ ),
457
+ self.delete_file: self._wrap_method(
458
+ self.delete_file,
459
+ default_timeout=None,
460
+ client_info=client_info,
461
+ ),
462
+ self.get_operation: self._wrap_method(
463
+ self.get_operation,
464
+ default_timeout=None,
465
+ client_info=client_info,
466
+ ),
467
+ self.list_operations: self._wrap_method(
468
+ self.list_operations,
469
+ default_timeout=None,
470
+ client_info=client_info,
471
+ ),
472
+ }
473
+
474
+ def _wrap_method(self, func, *args, **kwargs):
475
+ if self._wrap_with_kind: # pragma: NO COVER
476
+ kwargs["kind"] = self.kind
477
+ return gapic_v1.method_async.wrap_method(func, *args, **kwargs)
478
+
479
+ def close(self):
480
+ return self._logged_channel.close()
481
+
482
+ @property
483
+ def kind(self) -> str:
484
+ return "grpc_asyncio"
485
+
486
+ @property
487
+ def get_operation(
488
+ self,
489
+ ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]:
490
+ r"""Return a callable for the get_operation method over gRPC."""
491
+ # Generate a "stub function" on-the-fly which will actually make
492
+ # the request.
493
+ # gRPC handles serialization and deserialization, so we just need
494
+ # to pass in the functions for each.
495
+ if "get_operation" not in self._stubs:
496
+ self._stubs["get_operation"] = self._logged_channel.unary_unary(
497
+ "/google.longrunning.Operations/GetOperation",
498
+ request_serializer=operations_pb2.GetOperationRequest.SerializeToString,
499
+ response_deserializer=operations_pb2.Operation.FromString,
500
+ )
501
+ return self._stubs["get_operation"]
502
+
503
+ @property
504
+ def list_operations(
505
+ self,
506
+ ) -> Callable[
507
+ [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse
508
+ ]:
509
+ r"""Return a callable for the list_operations method over gRPC."""
510
+ # Generate a "stub function" on-the-fly which will actually make
511
+ # the request.
512
+ # gRPC handles serialization and deserialization, so we just need
513
+ # to pass in the functions for each.
514
+ if "list_operations" not in self._stubs:
515
+ self._stubs["list_operations"] = self._logged_channel.unary_unary(
516
+ "/google.longrunning.Operations/ListOperations",
517
+ request_serializer=operations_pb2.ListOperationsRequest.SerializeToString,
518
+ response_deserializer=operations_pb2.ListOperationsResponse.FromString,
519
+ )
520
+ return self._stubs["list_operations"]
521
+
522
+
523
+ __all__ = ("FileServiceGrpcAsyncIOTransport",)
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/file_service/transports/rest.py ADDED
@@ -0,0 +1,1191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 file, file_service
33
+
34
+ from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO
35
+ from .rest_base import _BaseFileServiceRestTransport
36
+
37
+ try:
38
+ OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None]
39
+ except AttributeError: # pragma: NO COVER
40
+ OptionalRetry = Union[retries.Retry, object, None] # type: ignore
41
+
42
+ try:
43
+ from google.api_core import client_logging # type: ignore
44
+
45
+ CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER
46
+ except ImportError: # pragma: NO COVER
47
+ CLIENT_LOGGING_SUPPORTED = False
48
+
49
+ _LOGGER = logging.getLogger(__name__)
50
+
51
+ DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
52
+ gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
53
+ grpc_version=None,
54
+ rest_version=f"requests@{requests_version}",
55
+ )
56
+
57
+
58
+ class FileServiceRestInterceptor:
59
+ """Interceptor for FileService.
60
+
61
+ Interceptors are used to manipulate requests, request metadata, and responses
62
+ in arbitrary ways.
63
+ Example use cases include:
64
+ * Logging
65
+ * Verifying requests according to service or custom semantics
66
+ * Stripping extraneous information from responses
67
+
68
+ These use cases and more can be enabled by injecting an
69
+ instance of a custom subclass when constructing the FileServiceRestTransport.
70
+
71
+ .. code-block:: python
72
+ class MyCustomFileServiceInterceptor(FileServiceRestInterceptor):
73
+ def pre_create_file(self, request, metadata):
74
+ logging.log(f"Received request: {request}")
75
+ return request, metadata
76
+
77
+ def post_create_file(self, response):
78
+ logging.log(f"Received response: {response}")
79
+ return response
80
+
81
+ def pre_delete_file(self, request, metadata):
82
+ logging.log(f"Received request: {request}")
83
+ return request, metadata
84
+
85
+ def pre_get_file(self, request, metadata):
86
+ logging.log(f"Received request: {request}")
87
+ return request, metadata
88
+
89
+ def post_get_file(self, response):
90
+ logging.log(f"Received response: {response}")
91
+ return response
92
+
93
+ def pre_list_files(self, request, metadata):
94
+ logging.log(f"Received request: {request}")
95
+ return request, metadata
96
+
97
+ def post_list_files(self, response):
98
+ logging.log(f"Received response: {response}")
99
+ return response
100
+
101
+ transport = FileServiceRestTransport(interceptor=MyCustomFileServiceInterceptor())
102
+ client = FileServiceClient(transport=transport)
103
+
104
+
105
+ """
106
+
107
+ def pre_create_file(
108
+ self,
109
+ request: file_service.CreateFileRequest,
110
+ metadata: Sequence[Tuple[str, Union[str, bytes]]],
111
+ ) -> Tuple[file_service.CreateFileRequest, Sequence[Tuple[str, Union[str, bytes]]]]:
112
+ """Pre-rpc interceptor for create_file
113
+
114
+ Override in a subclass to manipulate the request or metadata
115
+ before they are sent to the FileService server.
116
+ """
117
+ return request, metadata
118
+
119
+ def post_create_file(
120
+ self, response: file_service.CreateFileResponse
121
+ ) -> file_service.CreateFileResponse:
122
+ """Post-rpc interceptor for create_file
123
+
124
+ Override in a subclass to manipulate the response
125
+ after it is returned by the FileService server but before
126
+ it is returned to user code.
127
+ """
128
+ return response
129
+
130
+ def pre_delete_file(
131
+ self,
132
+ request: file_service.DeleteFileRequest,
133
+ metadata: Sequence[Tuple[str, Union[str, bytes]]],
134
+ ) -> Tuple[file_service.DeleteFileRequest, Sequence[Tuple[str, Union[str, bytes]]]]:
135
+ """Pre-rpc interceptor for delete_file
136
+
137
+ Override in a subclass to manipulate the request or metadata
138
+ before they are sent to the FileService server.
139
+ """
140
+ return request, metadata
141
+
142
+ def pre_get_file(
143
+ self,
144
+ request: file_service.GetFileRequest,
145
+ metadata: Sequence[Tuple[str, Union[str, bytes]]],
146
+ ) -> Tuple[file_service.GetFileRequest, Sequence[Tuple[str, Union[str, bytes]]]]:
147
+ """Pre-rpc interceptor for get_file
148
+
149
+ Override in a subclass to manipulate the request or metadata
150
+ before they are sent to the FileService server.
151
+ """
152
+ return request, metadata
153
+
154
+ def post_get_file(self, response: file.File) -> file.File:
155
+ """Post-rpc interceptor for get_file
156
+
157
+ Override in a subclass to manipulate the response
158
+ after it is returned by the FileService server but before
159
+ it is returned to user code.
160
+ """
161
+ return response
162
+
163
+ def pre_list_files(
164
+ self,
165
+ request: file_service.ListFilesRequest,
166
+ metadata: Sequence[Tuple[str, Union[str, bytes]]],
167
+ ) -> Tuple[file_service.ListFilesRequest, Sequence[Tuple[str, Union[str, bytes]]]]:
168
+ """Pre-rpc interceptor for list_files
169
+
170
+ Override in a subclass to manipulate the request or metadata
171
+ before they are sent to the FileService server.
172
+ """
173
+ return request, metadata
174
+
175
+ def post_list_files(
176
+ self, response: file_service.ListFilesResponse
177
+ ) -> file_service.ListFilesResponse:
178
+ """Post-rpc interceptor for list_files
179
+
180
+ Override in a subclass to manipulate the response
181
+ after it is returned by the FileService server but before
182
+ it is returned to user code.
183
+ """
184
+ return response
185
+
186
+ def pre_get_operation(
187
+ self,
188
+ request: operations_pb2.GetOperationRequest,
189
+ metadata: Sequence[Tuple[str, Union[str, bytes]]],
190
+ ) -> Tuple[
191
+ operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]
192
+ ]:
193
+ """Pre-rpc interceptor for get_operation
194
+
195
+ Override in a subclass to manipulate the request or metadata
196
+ before they are sent to the FileService server.
197
+ """
198
+ return request, metadata
199
+
200
+ def post_get_operation(
201
+ self, response: operations_pb2.Operation
202
+ ) -> operations_pb2.Operation:
203
+ """Post-rpc interceptor for get_operation
204
+
205
+ Override in a subclass to manipulate the response
206
+ after it is returned by the FileService server but before
207
+ it is returned to user code.
208
+ """
209
+ return response
210
+
211
+ def pre_list_operations(
212
+ self,
213
+ request: operations_pb2.ListOperationsRequest,
214
+ metadata: Sequence[Tuple[str, Union[str, bytes]]],
215
+ ) -> Tuple[
216
+ operations_pb2.ListOperationsRequest, Sequence[Tuple[str, Union[str, bytes]]]
217
+ ]:
218
+ """Pre-rpc interceptor for list_operations
219
+
220
+ Override in a subclass to manipulate the request or metadata
221
+ before they are sent to the FileService server.
222
+ """
223
+ return request, metadata
224
+
225
+ def post_list_operations(
226
+ self, response: operations_pb2.ListOperationsResponse
227
+ ) -> operations_pb2.ListOperationsResponse:
228
+ """Post-rpc interceptor for list_operations
229
+
230
+ Override in a subclass to manipulate the response
231
+ after it is returned by the FileService server but before
232
+ it is returned to user code.
233
+ """
234
+ return response
235
+
236
+
237
+ @dataclasses.dataclass
238
+ class FileServiceRestStub:
239
+ _session: AuthorizedSession
240
+ _host: str
241
+ _interceptor: FileServiceRestInterceptor
242
+
243
+
244
+ class FileServiceRestTransport(_BaseFileServiceRestTransport):
245
+ """REST backend synchronous transport for FileService.
246
+
247
+ An API for uploading and managing files.
248
+
249
+ This class defines the same methods as the primary client, so the
250
+ primary client can load the underlying transport implementation
251
+ and call it.
252
+
253
+ It sends JSON representations of protocol buffers over HTTP/1.1
254
+ """
255
+
256
+ def __init__(
257
+ self,
258
+ *,
259
+ host: str = "generativelanguage.googleapis.com",
260
+ credentials: Optional[ga_credentials.Credentials] = None,
261
+ credentials_file: Optional[str] = None,
262
+ scopes: Optional[Sequence[str]] = None,
263
+ client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None,
264
+ quota_project_id: Optional[str] = None,
265
+ client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
266
+ always_use_jwt_access: Optional[bool] = False,
267
+ url_scheme: str = "https",
268
+ interceptor: Optional[FileServiceRestInterceptor] = None,
269
+ api_audience: Optional[str] = None,
270
+ ) -> None:
271
+ """Instantiate the transport.
272
+
273
+ Args:
274
+ host (Optional[str]):
275
+ The hostname to connect to (default: 'generativelanguage.googleapis.com').
276
+ credentials (Optional[google.auth.credentials.Credentials]): The
277
+ authorization credentials to attach to requests. These
278
+ credentials identify the application to the service; if none
279
+ are specified, the client will attempt to ascertain the
280
+ credentials from the environment.
281
+
282
+ credentials_file (Optional[str]): A file with credentials that can
283
+ be loaded with :func:`google.auth.load_credentials_from_file`.
284
+ This argument is ignored if ``channel`` is provided.
285
+ scopes (Optional(Sequence[str])): A list of scopes. This argument is
286
+ ignored if ``channel`` is provided.
287
+ client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client
288
+ certificate to configure mutual TLS HTTP channel. It is ignored
289
+ if ``channel`` is provided.
290
+ quota_project_id (Optional[str]): An optional project to use for billing
291
+ and quota.
292
+ client_info (google.api_core.gapic_v1.client_info.ClientInfo):
293
+ The client info used to send a user-agent string along with
294
+ API requests. If ``None``, then default info will be used.
295
+ Generally, you only need to set this if you are developing
296
+ your own client library.
297
+ always_use_jwt_access (Optional[bool]): Whether self signed JWT should
298
+ be used for service account credentials.
299
+ url_scheme: the protocol scheme for the API endpoint. Normally
300
+ "https", but for testing or local servers,
301
+ "http" can be specified.
302
+ """
303
+ # Run the base constructor
304
+ # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc.
305
+ # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the
306
+ # credentials object
307
+ super().__init__(
308
+ host=host,
309
+ credentials=credentials,
310
+ client_info=client_info,
311
+ always_use_jwt_access=always_use_jwt_access,
312
+ url_scheme=url_scheme,
313
+ api_audience=api_audience,
314
+ )
315
+ self._session = AuthorizedSession(
316
+ self._credentials, default_host=self.DEFAULT_HOST
317
+ )
318
+ if client_cert_source_for_mtls:
319
+ self._session.configure_mtls_channel(client_cert_source_for_mtls)
320
+ self._interceptor = interceptor or FileServiceRestInterceptor()
321
+ self._prep_wrapped_messages(client_info)
322
+
323
+ class _CreateFile(
324
+ _BaseFileServiceRestTransport._BaseCreateFile, FileServiceRestStub
325
+ ):
326
+ def __hash__(self):
327
+ return hash("FileServiceRestTransport.CreateFile")
328
+
329
+ @staticmethod
330
+ def _get_response(
331
+ host,
332
+ metadata,
333
+ query_params,
334
+ session,
335
+ timeout,
336
+ transcoded_request,
337
+ body=None,
338
+ ):
339
+ uri = transcoded_request["uri"]
340
+ method = transcoded_request["method"]
341
+ headers = dict(metadata)
342
+ headers["Content-Type"] = "application/json"
343
+ response = getattr(session, method)(
344
+ "{host}{uri}".format(host=host, uri=uri),
345
+ timeout=timeout,
346
+ headers=headers,
347
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
348
+ data=body,
349
+ )
350
+ return response
351
+
352
+ def __call__(
353
+ self,
354
+ request: file_service.CreateFileRequest,
355
+ *,
356
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
357
+ timeout: Optional[float] = None,
358
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
359
+ ) -> file_service.CreateFileResponse:
360
+ r"""Call the create file method over HTTP.
361
+
362
+ Args:
363
+ request (~.file_service.CreateFileRequest):
364
+ The request object. Request for ``CreateFile``.
365
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
366
+ should be retried.
367
+ timeout (float): The timeout for this request.
368
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
369
+ sent along with the request as metadata. Normally, each value must be of type `str`,
370
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
371
+ be of type `bytes`.
372
+
373
+ Returns:
374
+ ~.file_service.CreateFileResponse:
375
+ Response for ``CreateFile``.
376
+ """
377
+
378
+ http_options = (
379
+ _BaseFileServiceRestTransport._BaseCreateFile._get_http_options()
380
+ )
381
+
382
+ request, metadata = self._interceptor.pre_create_file(request, metadata)
383
+ transcoded_request = (
384
+ _BaseFileServiceRestTransport._BaseCreateFile._get_transcoded_request(
385
+ http_options, request
386
+ )
387
+ )
388
+
389
+ body = _BaseFileServiceRestTransport._BaseCreateFile._get_request_body_json(
390
+ transcoded_request
391
+ )
392
+
393
+ # Jsonify the query params
394
+ query_params = (
395
+ _BaseFileServiceRestTransport._BaseCreateFile._get_query_params_json(
396
+ transcoded_request
397
+ )
398
+ )
399
+
400
+ if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
401
+ logging.DEBUG
402
+ ): # pragma: NO COVER
403
+ request_url = "{host}{uri}".format(
404
+ host=self._host, uri=transcoded_request["uri"]
405
+ )
406
+ method = transcoded_request["method"]
407
+ try:
408
+ request_payload = type(request).to_json(request)
409
+ except:
410
+ request_payload = None
411
+ http_request = {
412
+ "payload": request_payload,
413
+ "requestMethod": method,
414
+ "requestUrl": request_url,
415
+ "headers": dict(metadata),
416
+ }
417
+ _LOGGER.debug(
418
+ f"Sending request for google.ai.generativelanguage_v1alpha.FileServiceClient.CreateFile",
419
+ extra={
420
+ "serviceName": "google.ai.generativelanguage.v1alpha.FileService",
421
+ "rpcName": "CreateFile",
422
+ "httpRequest": http_request,
423
+ "metadata": http_request["headers"],
424
+ },
425
+ )
426
+
427
+ # Send the request
428
+ response = FileServiceRestTransport._CreateFile._get_response(
429
+ self._host,
430
+ metadata,
431
+ query_params,
432
+ self._session,
433
+ timeout,
434
+ transcoded_request,
435
+ body,
436
+ )
437
+
438
+ # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
439
+ # subclass.
440
+ if response.status_code >= 400:
441
+ raise core_exceptions.from_http_response(response)
442
+
443
+ # Return the response
444
+ resp = file_service.CreateFileResponse()
445
+ pb_resp = file_service.CreateFileResponse.pb(resp)
446
+
447
+ json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
448
+
449
+ resp = self._interceptor.post_create_file(resp)
450
+ if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
451
+ logging.DEBUG
452
+ ): # pragma: NO COVER
453
+ try:
454
+ response_payload = file_service.CreateFileResponse.to_json(response)
455
+ except:
456
+ response_payload = None
457
+ http_response = {
458
+ "payload": response_payload,
459
+ "headers": dict(response.headers),
460
+ "status": response.status_code,
461
+ }
462
+ _LOGGER.debug(
463
+ "Received response for google.ai.generativelanguage_v1alpha.FileServiceClient.create_file",
464
+ extra={
465
+ "serviceName": "google.ai.generativelanguage.v1alpha.FileService",
466
+ "rpcName": "CreateFile",
467
+ "metadata": http_response["headers"],
468
+ "httpResponse": http_response,
469
+ },
470
+ )
471
+ return resp
472
+
473
+ class _DeleteFile(
474
+ _BaseFileServiceRestTransport._BaseDeleteFile, FileServiceRestStub
475
+ ):
476
+ def __hash__(self):
477
+ return hash("FileServiceRestTransport.DeleteFile")
478
+
479
+ @staticmethod
480
+ def _get_response(
481
+ host,
482
+ metadata,
483
+ query_params,
484
+ session,
485
+ timeout,
486
+ transcoded_request,
487
+ body=None,
488
+ ):
489
+ uri = transcoded_request["uri"]
490
+ method = transcoded_request["method"]
491
+ headers = dict(metadata)
492
+ headers["Content-Type"] = "application/json"
493
+ response = getattr(session, method)(
494
+ "{host}{uri}".format(host=host, uri=uri),
495
+ timeout=timeout,
496
+ headers=headers,
497
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
498
+ )
499
+ return response
500
+
501
+ def __call__(
502
+ self,
503
+ request: file_service.DeleteFileRequest,
504
+ *,
505
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
506
+ timeout: Optional[float] = None,
507
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
508
+ ):
509
+ r"""Call the delete file method over HTTP.
510
+
511
+ Args:
512
+ request (~.file_service.DeleteFileRequest):
513
+ The request object. Request for ``DeleteFile``.
514
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
515
+ should be retried.
516
+ timeout (float): The timeout for this request.
517
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
518
+ sent along with the request as metadata. Normally, each value must be of type `str`,
519
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
520
+ be of type `bytes`.
521
+ """
522
+
523
+ http_options = (
524
+ _BaseFileServiceRestTransport._BaseDeleteFile._get_http_options()
525
+ )
526
+
527
+ request, metadata = self._interceptor.pre_delete_file(request, metadata)
528
+ transcoded_request = (
529
+ _BaseFileServiceRestTransport._BaseDeleteFile._get_transcoded_request(
530
+ http_options, request
531
+ )
532
+ )
533
+
534
+ # Jsonify the query params
535
+ query_params = (
536
+ _BaseFileServiceRestTransport._BaseDeleteFile._get_query_params_json(
537
+ transcoded_request
538
+ )
539
+ )
540
+
541
+ if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
542
+ logging.DEBUG
543
+ ): # pragma: NO COVER
544
+ request_url = "{host}{uri}".format(
545
+ host=self._host, uri=transcoded_request["uri"]
546
+ )
547
+ method = transcoded_request["method"]
548
+ try:
549
+ request_payload = json_format.MessageToJson(request)
550
+ except:
551
+ request_payload = None
552
+ http_request = {
553
+ "payload": request_payload,
554
+ "requestMethod": method,
555
+ "requestUrl": request_url,
556
+ "headers": dict(metadata),
557
+ }
558
+ _LOGGER.debug(
559
+ f"Sending request for google.ai.generativelanguage_v1alpha.FileServiceClient.DeleteFile",
560
+ extra={
561
+ "serviceName": "google.ai.generativelanguage.v1alpha.FileService",
562
+ "rpcName": "DeleteFile",
563
+ "httpRequest": http_request,
564
+ "metadata": http_request["headers"],
565
+ },
566
+ )
567
+
568
+ # Send the request
569
+ response = FileServiceRestTransport._DeleteFile._get_response(
570
+ self._host,
571
+ metadata,
572
+ query_params,
573
+ self._session,
574
+ timeout,
575
+ transcoded_request,
576
+ )
577
+
578
+ # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
579
+ # subclass.
580
+ if response.status_code >= 400:
581
+ raise core_exceptions.from_http_response(response)
582
+
583
+ class _GetFile(_BaseFileServiceRestTransport._BaseGetFile, FileServiceRestStub):
584
+ def __hash__(self):
585
+ return hash("FileServiceRestTransport.GetFile")
586
+
587
+ @staticmethod
588
+ def _get_response(
589
+ host,
590
+ metadata,
591
+ query_params,
592
+ session,
593
+ timeout,
594
+ transcoded_request,
595
+ body=None,
596
+ ):
597
+ uri = transcoded_request["uri"]
598
+ method = transcoded_request["method"]
599
+ headers = dict(metadata)
600
+ headers["Content-Type"] = "application/json"
601
+ response = getattr(session, method)(
602
+ "{host}{uri}".format(host=host, uri=uri),
603
+ timeout=timeout,
604
+ headers=headers,
605
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
606
+ )
607
+ return response
608
+
609
+ def __call__(
610
+ self,
611
+ request: file_service.GetFileRequest,
612
+ *,
613
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
614
+ timeout: Optional[float] = None,
615
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
616
+ ) -> file.File:
617
+ r"""Call the get file method over HTTP.
618
+
619
+ Args:
620
+ request (~.file_service.GetFileRequest):
621
+ The request object. Request for ``GetFile``.
622
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
623
+ should be retried.
624
+ timeout (float): The timeout for this request.
625
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
626
+ sent along with the request as metadata. Normally, each value must be of type `str`,
627
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
628
+ be of type `bytes`.
629
+
630
+ Returns:
631
+ ~.file.File:
632
+ A file uploaded to the API.
633
+ Next ID: 15
634
+
635
+ """
636
+
637
+ http_options = (
638
+ _BaseFileServiceRestTransport._BaseGetFile._get_http_options()
639
+ )
640
+
641
+ request, metadata = self._interceptor.pre_get_file(request, metadata)
642
+ transcoded_request = (
643
+ _BaseFileServiceRestTransport._BaseGetFile._get_transcoded_request(
644
+ http_options, request
645
+ )
646
+ )
647
+
648
+ # Jsonify the query params
649
+ query_params = (
650
+ _BaseFileServiceRestTransport._BaseGetFile._get_query_params_json(
651
+ transcoded_request
652
+ )
653
+ )
654
+
655
+ if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
656
+ logging.DEBUG
657
+ ): # pragma: NO COVER
658
+ request_url = "{host}{uri}".format(
659
+ host=self._host, uri=transcoded_request["uri"]
660
+ )
661
+ method = transcoded_request["method"]
662
+ try:
663
+ request_payload = type(request).to_json(request)
664
+ except:
665
+ request_payload = None
666
+ http_request = {
667
+ "payload": request_payload,
668
+ "requestMethod": method,
669
+ "requestUrl": request_url,
670
+ "headers": dict(metadata),
671
+ }
672
+ _LOGGER.debug(
673
+ f"Sending request for google.ai.generativelanguage_v1alpha.FileServiceClient.GetFile",
674
+ extra={
675
+ "serviceName": "google.ai.generativelanguage.v1alpha.FileService",
676
+ "rpcName": "GetFile",
677
+ "httpRequest": http_request,
678
+ "metadata": http_request["headers"],
679
+ },
680
+ )
681
+
682
+ # Send the request
683
+ response = FileServiceRestTransport._GetFile._get_response(
684
+ self._host,
685
+ metadata,
686
+ query_params,
687
+ self._session,
688
+ timeout,
689
+ transcoded_request,
690
+ )
691
+
692
+ # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
693
+ # subclass.
694
+ if response.status_code >= 400:
695
+ raise core_exceptions.from_http_response(response)
696
+
697
+ # Return the response
698
+ resp = file.File()
699
+ pb_resp = file.File.pb(resp)
700
+
701
+ json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
702
+
703
+ resp = self._interceptor.post_get_file(resp)
704
+ if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
705
+ logging.DEBUG
706
+ ): # pragma: NO COVER
707
+ try:
708
+ response_payload = file.File.to_json(response)
709
+ except:
710
+ response_payload = None
711
+ http_response = {
712
+ "payload": response_payload,
713
+ "headers": dict(response.headers),
714
+ "status": response.status_code,
715
+ }
716
+ _LOGGER.debug(
717
+ "Received response for google.ai.generativelanguage_v1alpha.FileServiceClient.get_file",
718
+ extra={
719
+ "serviceName": "google.ai.generativelanguage.v1alpha.FileService",
720
+ "rpcName": "GetFile",
721
+ "metadata": http_response["headers"],
722
+ "httpResponse": http_response,
723
+ },
724
+ )
725
+ return resp
726
+
727
+ class _ListFiles(_BaseFileServiceRestTransport._BaseListFiles, FileServiceRestStub):
728
+ def __hash__(self):
729
+ return hash("FileServiceRestTransport.ListFiles")
730
+
731
+ @staticmethod
732
+ def _get_response(
733
+ host,
734
+ metadata,
735
+ query_params,
736
+ session,
737
+ timeout,
738
+ transcoded_request,
739
+ body=None,
740
+ ):
741
+ uri = transcoded_request["uri"]
742
+ method = transcoded_request["method"]
743
+ headers = dict(metadata)
744
+ headers["Content-Type"] = "application/json"
745
+ response = getattr(session, method)(
746
+ "{host}{uri}".format(host=host, uri=uri),
747
+ timeout=timeout,
748
+ headers=headers,
749
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
750
+ )
751
+ return response
752
+
753
+ def __call__(
754
+ self,
755
+ request: file_service.ListFilesRequest,
756
+ *,
757
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
758
+ timeout: Optional[float] = None,
759
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
760
+ ) -> file_service.ListFilesResponse:
761
+ r"""Call the list files method over HTTP.
762
+
763
+ Args:
764
+ request (~.file_service.ListFilesRequest):
765
+ The request object. Request for ``ListFiles``.
766
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
767
+ should be retried.
768
+ timeout (float): The timeout for this request.
769
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
770
+ sent along with the request as metadata. Normally, each value must be of type `str`,
771
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
772
+ be of type `bytes`.
773
+
774
+ Returns:
775
+ ~.file_service.ListFilesResponse:
776
+ Response for ``ListFiles``.
777
+ """
778
+
779
+ http_options = (
780
+ _BaseFileServiceRestTransport._BaseListFiles._get_http_options()
781
+ )
782
+
783
+ request, metadata = self._interceptor.pre_list_files(request, metadata)
784
+ transcoded_request = (
785
+ _BaseFileServiceRestTransport._BaseListFiles._get_transcoded_request(
786
+ http_options, request
787
+ )
788
+ )
789
+
790
+ # Jsonify the query params
791
+ query_params = (
792
+ _BaseFileServiceRestTransport._BaseListFiles._get_query_params_json(
793
+ transcoded_request
794
+ )
795
+ )
796
+
797
+ if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
798
+ logging.DEBUG
799
+ ): # pragma: NO COVER
800
+ request_url = "{host}{uri}".format(
801
+ host=self._host, uri=transcoded_request["uri"]
802
+ )
803
+ method = transcoded_request["method"]
804
+ try:
805
+ request_payload = type(request).to_json(request)
806
+ except:
807
+ request_payload = None
808
+ http_request = {
809
+ "payload": request_payload,
810
+ "requestMethod": method,
811
+ "requestUrl": request_url,
812
+ "headers": dict(metadata),
813
+ }
814
+ _LOGGER.debug(
815
+ f"Sending request for google.ai.generativelanguage_v1alpha.FileServiceClient.ListFiles",
816
+ extra={
817
+ "serviceName": "google.ai.generativelanguage.v1alpha.FileService",
818
+ "rpcName": "ListFiles",
819
+ "httpRequest": http_request,
820
+ "metadata": http_request["headers"],
821
+ },
822
+ )
823
+
824
+ # Send the request
825
+ response = FileServiceRestTransport._ListFiles._get_response(
826
+ self._host,
827
+ metadata,
828
+ query_params,
829
+ self._session,
830
+ timeout,
831
+ transcoded_request,
832
+ )
833
+
834
+ # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
835
+ # subclass.
836
+ if response.status_code >= 400:
837
+ raise core_exceptions.from_http_response(response)
838
+
839
+ # Return the response
840
+ resp = file_service.ListFilesResponse()
841
+ pb_resp = file_service.ListFilesResponse.pb(resp)
842
+
843
+ json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
844
+
845
+ resp = self._interceptor.post_list_files(resp)
846
+ if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
847
+ logging.DEBUG
848
+ ): # pragma: NO COVER
849
+ try:
850
+ response_payload = file_service.ListFilesResponse.to_json(response)
851
+ except:
852
+ response_payload = None
853
+ http_response = {
854
+ "payload": response_payload,
855
+ "headers": dict(response.headers),
856
+ "status": response.status_code,
857
+ }
858
+ _LOGGER.debug(
859
+ "Received response for google.ai.generativelanguage_v1alpha.FileServiceClient.list_files",
860
+ extra={
861
+ "serviceName": "google.ai.generativelanguage.v1alpha.FileService",
862
+ "rpcName": "ListFiles",
863
+ "metadata": http_response["headers"],
864
+ "httpResponse": http_response,
865
+ },
866
+ )
867
+ return resp
868
+
869
+ @property
870
+ def create_file(
871
+ self,
872
+ ) -> Callable[[file_service.CreateFileRequest], file_service.CreateFileResponse]:
873
+ # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
874
+ # In C++ this would require a dynamic_cast
875
+ return self._CreateFile(self._session, self._host, self._interceptor) # type: ignore
876
+
877
+ @property
878
+ def delete_file(
879
+ self,
880
+ ) -> Callable[[file_service.DeleteFileRequest], empty_pb2.Empty]:
881
+ # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
882
+ # In C++ this would require a dynamic_cast
883
+ return self._DeleteFile(self._session, self._host, self._interceptor) # type: ignore
884
+
885
+ @property
886
+ def get_file(self) -> Callable[[file_service.GetFileRequest], file.File]:
887
+ # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
888
+ # In C++ this would require a dynamic_cast
889
+ return self._GetFile(self._session, self._host, self._interceptor) # type: ignore
890
+
891
+ @property
892
+ def list_files(
893
+ self,
894
+ ) -> Callable[[file_service.ListFilesRequest], file_service.ListFilesResponse]:
895
+ # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
896
+ # In C++ this would require a dynamic_cast
897
+ return self._ListFiles(self._session, self._host, self._interceptor) # type: ignore
898
+
899
+ @property
900
+ def get_operation(self):
901
+ return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore
902
+
903
+ class _GetOperation(
904
+ _BaseFileServiceRestTransport._BaseGetOperation, FileServiceRestStub
905
+ ):
906
+ def __hash__(self):
907
+ return hash("FileServiceRestTransport.GetOperation")
908
+
909
+ @staticmethod
910
+ def _get_response(
911
+ host,
912
+ metadata,
913
+ query_params,
914
+ session,
915
+ timeout,
916
+ transcoded_request,
917
+ body=None,
918
+ ):
919
+ uri = transcoded_request["uri"]
920
+ method = transcoded_request["method"]
921
+ headers = dict(metadata)
922
+ headers["Content-Type"] = "application/json"
923
+ response = getattr(session, method)(
924
+ "{host}{uri}".format(host=host, uri=uri),
925
+ timeout=timeout,
926
+ headers=headers,
927
+ params=rest_helpers.flatten_query_params(query_params, strict=True),
928
+ )
929
+ return response
930
+
931
+ def __call__(
932
+ self,
933
+ request: operations_pb2.GetOperationRequest,
934
+ *,
935
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
936
+ timeout: Optional[float] = None,
937
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
938
+ ) -> operations_pb2.Operation:
939
+ r"""Call the get operation method over HTTP.
940
+
941
+ Args:
942
+ request (operations_pb2.GetOperationRequest):
943
+ The request object for GetOperation method.
944
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
945
+ should be retried.
946
+ timeout (float): The timeout for this request.
947
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
948
+ sent along with the request as metadata. Normally, each value must be of type `str`,
949
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
950
+ be of type `bytes`.
951
+
952
+ Returns:
953
+ operations_pb2.Operation: Response from GetOperation method.
954
+ """
955
+
956
+ http_options = (
957
+ _BaseFileServiceRestTransport._BaseGetOperation._get_http_options()
958
+ )
959
+
960
+ request, metadata = self._interceptor.pre_get_operation(request, metadata)
961
+ transcoded_request = (
962
+ _BaseFileServiceRestTransport._BaseGetOperation._get_transcoded_request(
963
+ http_options, request
964
+ )
965
+ )
966
+
967
+ # Jsonify the query params
968
+ query_params = (
969
+ _BaseFileServiceRestTransport._BaseGetOperation._get_query_params_json(
970
+ transcoded_request
971
+ )
972
+ )
973
+
974
+ if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
975
+ logging.DEBUG
976
+ ): # pragma: NO COVER
977
+ request_url = "{host}{uri}".format(
978
+ host=self._host, uri=transcoded_request["uri"]
979
+ )
980
+ method = transcoded_request["method"]
981
+ try:
982
+ request_payload = json_format.MessageToJson(request)
983
+ except:
984
+ request_payload = None
985
+ http_request = {
986
+ "payload": request_payload,
987
+ "requestMethod": method,
988
+ "requestUrl": request_url,
989
+ "headers": dict(metadata),
990
+ }
991
+ _LOGGER.debug(
992
+ f"Sending request for google.ai.generativelanguage_v1alpha.FileServiceClient.GetOperation",
993
+ extra={
994
+ "serviceName": "google.ai.generativelanguage.v1alpha.FileService",
995
+ "rpcName": "GetOperation",
996
+ "httpRequest": http_request,
997
+ "metadata": http_request["headers"],
998
+ },
999
+ )
1000
+
1001
+ # Send the request
1002
+ response = FileServiceRestTransport._GetOperation._get_response(
1003
+ self._host,
1004
+ metadata,
1005
+ query_params,
1006
+ self._session,
1007
+ timeout,
1008
+ transcoded_request,
1009
+ )
1010
+
1011
+ # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
1012
+ # subclass.
1013
+ if response.status_code >= 400:
1014
+ raise core_exceptions.from_http_response(response)
1015
+
1016
+ content = response.content.decode("utf-8")
1017
+ resp = operations_pb2.Operation()
1018
+ resp = json_format.Parse(content, resp)
1019
+ resp = self._interceptor.post_get_operation(resp)
1020
+ if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
1021
+ logging.DEBUG
1022
+ ): # pragma: NO COVER
1023
+ try:
1024
+ response_payload = json_format.MessageToJson(resp)
1025
+ except:
1026
+ response_payload = None
1027
+ http_response = {
1028
+ "payload": response_payload,
1029
+ "headers": dict(response.headers),
1030
+ "status": response.status_code,
1031
+ }
1032
+ _LOGGER.debug(
1033
+ "Received response for google.ai.generativelanguage_v1alpha.FileServiceAsyncClient.GetOperation",
1034
+ extra={
1035
+ "serviceName": "google.ai.generativelanguage.v1alpha.FileService",
1036
+ "rpcName": "GetOperation",
1037
+ "httpResponse": http_response,
1038
+ "metadata": http_response["headers"],
1039
+ },
1040
+ )
1041
+ return resp
1042
+
1043
+ @property
1044
+ def list_operations(self):
1045
+ return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore
1046
+
1047
+ class _ListOperations(
1048
+ _BaseFileServiceRestTransport._BaseListOperations, FileServiceRestStub
1049
+ ):
1050
+ def __hash__(self):
1051
+ return hash("FileServiceRestTransport.ListOperations")
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
+ )
1073
+ return response
1074
+
1075
+ def __call__(
1076
+ self,
1077
+ request: operations_pb2.ListOperationsRequest,
1078
+ *,
1079
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
1080
+ timeout: Optional[float] = None,
1081
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1082
+ ) -> operations_pb2.ListOperationsResponse:
1083
+ r"""Call the list operations method over HTTP.
1084
+
1085
+ Args:
1086
+ request (operations_pb2.ListOperationsRequest):
1087
+ The request object for ListOperations method.
1088
+ retry (google.api_core.retry.Retry): 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
+ operations_pb2.ListOperationsResponse: Response from ListOperations method.
1098
+ """
1099
+
1100
+ http_options = (
1101
+ _BaseFileServiceRestTransport._BaseListOperations._get_http_options()
1102
+ )
1103
+
1104
+ request, metadata = self._interceptor.pre_list_operations(request, metadata)
1105
+ transcoded_request = _BaseFileServiceRestTransport._BaseListOperations._get_transcoded_request(
1106
+ http_options, request
1107
+ )
1108
+
1109
+ # Jsonify the query params
1110
+ query_params = _BaseFileServiceRestTransport._BaseListOperations._get_query_params_json(
1111
+ transcoded_request
1112
+ )
1113
+
1114
+ if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
1115
+ logging.DEBUG
1116
+ ): # pragma: NO COVER
1117
+ request_url = "{host}{uri}".format(
1118
+ host=self._host, uri=transcoded_request["uri"]
1119
+ )
1120
+ method = transcoded_request["method"]
1121
+ try:
1122
+ request_payload = json_format.MessageToJson(request)
1123
+ except:
1124
+ request_payload = None
1125
+ http_request = {
1126
+ "payload": request_payload,
1127
+ "requestMethod": method,
1128
+ "requestUrl": request_url,
1129
+ "headers": dict(metadata),
1130
+ }
1131
+ _LOGGER.debug(
1132
+ f"Sending request for google.ai.generativelanguage_v1alpha.FileServiceClient.ListOperations",
1133
+ extra={
1134
+ "serviceName": "google.ai.generativelanguage.v1alpha.FileService",
1135
+ "rpcName": "ListOperations",
1136
+ "httpRequest": http_request,
1137
+ "metadata": http_request["headers"],
1138
+ },
1139
+ )
1140
+
1141
+ # Send the request
1142
+ response = FileServiceRestTransport._ListOperations._get_response(
1143
+ self._host,
1144
+ metadata,
1145
+ query_params,
1146
+ self._session,
1147
+ timeout,
1148
+ transcoded_request,
1149
+ )
1150
+
1151
+ # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
1152
+ # subclass.
1153
+ if response.status_code >= 400:
1154
+ raise core_exceptions.from_http_response(response)
1155
+
1156
+ content = response.content.decode("utf-8")
1157
+ resp = operations_pb2.ListOperationsResponse()
1158
+ resp = json_format.Parse(content, resp)
1159
+ resp = self._interceptor.post_list_operations(resp)
1160
+ if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
1161
+ logging.DEBUG
1162
+ ): # pragma: NO COVER
1163
+ try:
1164
+ response_payload = json_format.MessageToJson(resp)
1165
+ except:
1166
+ response_payload = None
1167
+ http_response = {
1168
+ "payload": response_payload,
1169
+ "headers": dict(response.headers),
1170
+ "status": response.status_code,
1171
+ }
1172
+ _LOGGER.debug(
1173
+ "Received response for google.ai.generativelanguage_v1alpha.FileServiceAsyncClient.ListOperations",
1174
+ extra={
1175
+ "serviceName": "google.ai.generativelanguage.v1alpha.FileService",
1176
+ "rpcName": "ListOperations",
1177
+ "httpResponse": http_response,
1178
+ "metadata": http_response["headers"],
1179
+ },
1180
+ )
1181
+ return resp
1182
+
1183
+ @property
1184
+ def kind(self) -> str:
1185
+ return "rest"
1186
+
1187
+ def close(self):
1188
+ self._session.close()
1189
+
1190
+
1191
+ __all__ = ("FileServiceRestTransport",)
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/file_service/transports/rest_base.py ADDED
@@ -0,0 +1,323 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 file, file_service
26
+
27
+ from .base import DEFAULT_CLIENT_INFO, FileServiceTransport
28
+
29
+
30
+ class _BaseFileServiceRestTransport(FileServiceTransport):
31
+ """Base REST backend transport for FileService.
32
+
33
+ Note: This class is not meant to be used directly. Use its sync and
34
+ async sub-classes instead.
35
+
36
+ This class defines the same methods as the primary client, so the
37
+ primary client can load the underlying transport implementation
38
+ and call it.
39
+
40
+ It sends JSON representations of protocol buffers over HTTP/1.1
41
+ """
42
+
43
+ def __init__(
44
+ self,
45
+ *,
46
+ host: str = "generativelanguage.googleapis.com",
47
+ credentials: Optional[Any] = None,
48
+ client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
49
+ always_use_jwt_access: Optional[bool] = False,
50
+ url_scheme: str = "https",
51
+ api_audience: Optional[str] = None,
52
+ ) -> None:
53
+ """Instantiate the transport.
54
+ Args:
55
+ host (Optional[str]):
56
+ The hostname to connect to (default: 'generativelanguage.googleapis.com').
57
+ credentials (Optional[Any]): The
58
+ authorization credentials to attach to requests. These
59
+ credentials identify the application to the service; if none
60
+ are specified, the client will attempt to ascertain the
61
+ credentials from the environment.
62
+ client_info (google.api_core.gapic_v1.client_info.ClientInfo):
63
+ The client info used to send a user-agent string along with
64
+ API requests. If ``None``, then default info will be used.
65
+ Generally, you only need to set this if you are developing
66
+ your own client library.
67
+ always_use_jwt_access (Optional[bool]): Whether self signed JWT should
68
+ be used for service account credentials.
69
+ url_scheme: the protocol scheme for the API endpoint. Normally
70
+ "https", but for testing or local servers,
71
+ "http" can be specified.
72
+ """
73
+ # Run the base constructor
74
+ maybe_url_match = re.match("^(?P<scheme>http(?:s)?://)?(?P<host>.*)$", host)
75
+ if maybe_url_match is None:
76
+ raise ValueError(
77
+ f"Unexpected hostname structure: {host}"
78
+ ) # pragma: NO COVER
79
+
80
+ url_match_items = maybe_url_match.groupdict()
81
+
82
+ host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host
83
+
84
+ super().__init__(
85
+ host=host,
86
+ credentials=credentials,
87
+ client_info=client_info,
88
+ always_use_jwt_access=always_use_jwt_access,
89
+ api_audience=api_audience,
90
+ )
91
+
92
+ class _BaseCreateFile:
93
+ def __hash__(self): # pragma: NO COVER
94
+ return NotImplementedError("__hash__ must be implemented.")
95
+
96
+ @staticmethod
97
+ def _get_http_options():
98
+ http_options: List[Dict[str, str]] = [
99
+ {
100
+ "method": "post",
101
+ "uri": "/v1alpha/files",
102
+ "body": "*",
103
+ },
104
+ ]
105
+ return http_options
106
+
107
+ @staticmethod
108
+ def _get_transcoded_request(http_options, request):
109
+ pb_request = file_service.CreateFileRequest.pb(request)
110
+ transcoded_request = path_template.transcode(http_options, pb_request)
111
+ return transcoded_request
112
+
113
+ @staticmethod
114
+ def _get_request_body_json(transcoded_request):
115
+ # Jsonify the request body
116
+
117
+ body = json_format.MessageToJson(
118
+ transcoded_request["body"], use_integers_for_enums=True
119
+ )
120
+ return body
121
+
122
+ @staticmethod
123
+ def _get_query_params_json(transcoded_request):
124
+ query_params = json.loads(
125
+ json_format.MessageToJson(
126
+ transcoded_request["query_params"],
127
+ use_integers_for_enums=True,
128
+ )
129
+ )
130
+
131
+ query_params["$alt"] = "json;enum-encoding=int"
132
+ return query_params
133
+
134
+ class _BaseDeleteFile:
135
+ def __hash__(self): # pragma: NO COVER
136
+ return NotImplementedError("__hash__ must be implemented.")
137
+
138
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
139
+
140
+ @classmethod
141
+ def _get_unset_required_fields(cls, message_dict):
142
+ return {
143
+ k: v
144
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
145
+ if k not in message_dict
146
+ }
147
+
148
+ @staticmethod
149
+ def _get_http_options():
150
+ http_options: List[Dict[str, str]] = [
151
+ {
152
+ "method": "delete",
153
+ "uri": "/v1alpha/{name=files/*}",
154
+ },
155
+ ]
156
+ return http_options
157
+
158
+ @staticmethod
159
+ def _get_transcoded_request(http_options, request):
160
+ pb_request = file_service.DeleteFileRequest.pb(request)
161
+ transcoded_request = path_template.transcode(http_options, pb_request)
162
+ return transcoded_request
163
+
164
+ @staticmethod
165
+ def _get_query_params_json(transcoded_request):
166
+ query_params = json.loads(
167
+ json_format.MessageToJson(
168
+ transcoded_request["query_params"],
169
+ use_integers_for_enums=True,
170
+ )
171
+ )
172
+ query_params.update(
173
+ _BaseFileServiceRestTransport._BaseDeleteFile._get_unset_required_fields(
174
+ query_params
175
+ )
176
+ )
177
+
178
+ query_params["$alt"] = "json;enum-encoding=int"
179
+ return query_params
180
+
181
+ class _BaseGetFile:
182
+ def __hash__(self): # pragma: NO COVER
183
+ return NotImplementedError("__hash__ must be implemented.")
184
+
185
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
186
+
187
+ @classmethod
188
+ def _get_unset_required_fields(cls, message_dict):
189
+ return {
190
+ k: v
191
+ for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
192
+ if k not in message_dict
193
+ }
194
+
195
+ @staticmethod
196
+ def _get_http_options():
197
+ http_options: List[Dict[str, str]] = [
198
+ {
199
+ "method": "get",
200
+ "uri": "/v1alpha/{name=files/*}",
201
+ },
202
+ ]
203
+ return http_options
204
+
205
+ @staticmethod
206
+ def _get_transcoded_request(http_options, request):
207
+ pb_request = file_service.GetFileRequest.pb(request)
208
+ transcoded_request = path_template.transcode(http_options, pb_request)
209
+ return transcoded_request
210
+
211
+ @staticmethod
212
+ def _get_query_params_json(transcoded_request):
213
+ query_params = json.loads(
214
+ json_format.MessageToJson(
215
+ transcoded_request["query_params"],
216
+ use_integers_for_enums=True,
217
+ )
218
+ )
219
+ query_params.update(
220
+ _BaseFileServiceRestTransport._BaseGetFile._get_unset_required_fields(
221
+ query_params
222
+ )
223
+ )
224
+
225
+ query_params["$alt"] = "json;enum-encoding=int"
226
+ return query_params
227
+
228
+ class _BaseListFiles:
229
+ def __hash__(self): # pragma: NO COVER
230
+ return NotImplementedError("__hash__ must be implemented.")
231
+
232
+ @staticmethod
233
+ def _get_http_options():
234
+ http_options: List[Dict[str, str]] = [
235
+ {
236
+ "method": "get",
237
+ "uri": "/v1alpha/files",
238
+ },
239
+ ]
240
+ return http_options
241
+
242
+ @staticmethod
243
+ def _get_transcoded_request(http_options, request):
244
+ pb_request = file_service.ListFilesRequest.pb(request)
245
+ transcoded_request = path_template.transcode(http_options, pb_request)
246
+ return transcoded_request
247
+
248
+ @staticmethod
249
+ def _get_query_params_json(transcoded_request):
250
+ query_params = json.loads(
251
+ json_format.MessageToJson(
252
+ transcoded_request["query_params"],
253
+ use_integers_for_enums=True,
254
+ )
255
+ )
256
+
257
+ query_params["$alt"] = "json;enum-encoding=int"
258
+ return query_params
259
+
260
+ class _BaseGetOperation:
261
+ def __hash__(self): # pragma: NO COVER
262
+ return NotImplementedError("__hash__ must be implemented.")
263
+
264
+ @staticmethod
265
+ def _get_http_options():
266
+ http_options: List[Dict[str, str]] = [
267
+ {
268
+ "method": "get",
269
+ "uri": "/v1alpha/{name=tunedModels/*/operations/*}",
270
+ },
271
+ {
272
+ "method": "get",
273
+ "uri": "/v1alpha/{name=generatedFiles/*/operations/*}",
274
+ },
275
+ {
276
+ "method": "get",
277
+ "uri": "/v1alpha/{name=models/*/operations/*}",
278
+ },
279
+ ]
280
+ return http_options
281
+
282
+ @staticmethod
283
+ def _get_transcoded_request(http_options, request):
284
+ request_kwargs = json_format.MessageToDict(request)
285
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
286
+ return transcoded_request
287
+
288
+ @staticmethod
289
+ def _get_query_params_json(transcoded_request):
290
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
291
+ return query_params
292
+
293
+ class _BaseListOperations:
294
+ def __hash__(self): # pragma: NO COVER
295
+ return NotImplementedError("__hash__ must be implemented.")
296
+
297
+ @staticmethod
298
+ def _get_http_options():
299
+ http_options: List[Dict[str, str]] = [
300
+ {
301
+ "method": "get",
302
+ "uri": "/v1alpha/{name=tunedModels/*}/operations",
303
+ },
304
+ {
305
+ "method": "get",
306
+ "uri": "/v1alpha/{name=models/*}/operations",
307
+ },
308
+ ]
309
+ return http_options
310
+
311
+ @staticmethod
312
+ def _get_transcoded_request(http_options, request):
313
+ request_kwargs = json_format.MessageToDict(request)
314
+ transcoded_request = path_template.transcode(http_options, **request_kwargs)
315
+ return transcoded_request
316
+
317
+ @staticmethod
318
+ def _get_query_params_json(transcoded_request):
319
+ query_params = json.loads(json.dumps(transcoded_request["query_params"]))
320
+ return query_params
321
+
322
+
323
+ __all__ = ("_BaseFileServiceRestTransport",)
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/text_service/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (400 Bytes). View file
 
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/text_service/__pycache__/async_client.cpython-311.pyc ADDED
Binary file (40.9 kB). View file
 
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/text_service/__pycache__/client.cpython-311.pyc ADDED
Binary file (56.8 kB). View file
 
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1alpha/services/text_service/transports/__pycache__/rest_base.cpython-311.pyc ADDED
Binary file (17.8 kB). View file
 
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta2/__init__.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 google.ai.generativelanguage_v1beta2 import gapic_version as package_version
17
+
18
+ __version__ = package_version.__version__
19
+
20
+
21
+ from .services.discuss_service import DiscussServiceAsyncClient, DiscussServiceClient
22
+ from .services.model_service import ModelServiceAsyncClient, ModelServiceClient
23
+ from .services.text_service import TextServiceAsyncClient, TextServiceClient
24
+ from .types.citation import CitationMetadata, CitationSource
25
+ from .types.discuss_service import (
26
+ CountMessageTokensRequest,
27
+ CountMessageTokensResponse,
28
+ Example,
29
+ GenerateMessageRequest,
30
+ GenerateMessageResponse,
31
+ Message,
32
+ MessagePrompt,
33
+ )
34
+ from .types.model import Model
35
+ from .types.model_service import GetModelRequest, ListModelsRequest, ListModelsResponse
36
+ from .types.safety import (
37
+ ContentFilter,
38
+ HarmCategory,
39
+ SafetyFeedback,
40
+ SafetyRating,
41
+ SafetySetting,
42
+ )
43
+ from .types.text_service import (
44
+ Embedding,
45
+ EmbedTextRequest,
46
+ EmbedTextResponse,
47
+ GenerateTextRequest,
48
+ GenerateTextResponse,
49
+ TextCompletion,
50
+ TextPrompt,
51
+ )
52
+
53
+ __all__ = (
54
+ "DiscussServiceAsyncClient",
55
+ "ModelServiceAsyncClient",
56
+ "TextServiceAsyncClient",
57
+ "CitationMetadata",
58
+ "CitationSource",
59
+ "ContentFilter",
60
+ "CountMessageTokensRequest",
61
+ "CountMessageTokensResponse",
62
+ "DiscussServiceClient",
63
+ "EmbedTextRequest",
64
+ "EmbedTextResponse",
65
+ "Embedding",
66
+ "Example",
67
+ "GenerateMessageRequest",
68
+ "GenerateMessageResponse",
69
+ "GenerateTextRequest",
70
+ "GenerateTextResponse",
71
+ "GetModelRequest",
72
+ "HarmCategory",
73
+ "ListModelsRequest",
74
+ "ListModelsResponse",
75
+ "Message",
76
+ "MessagePrompt",
77
+ "Model",
78
+ "ModelServiceClient",
79
+ "SafetyFeedback",
80
+ "SafetyRating",
81
+ "SafetySetting",
82
+ "TextCompletion",
83
+ "TextPrompt",
84
+ "TextServiceClient",
85
+ )
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta2/gapic_metadata.json ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "comment": "This file maps proto services/RPCs to the corresponding library clients/methods",
3
+ "language": "python",
4
+ "libraryPackage": "google.ai.generativelanguage_v1beta2",
5
+ "protoPackage": "google.ai.generativelanguage.v1beta2",
6
+ "schema": "1.0",
7
+ "services": {
8
+ "DiscussService": {
9
+ "clients": {
10
+ "grpc": {
11
+ "libraryClient": "DiscussServiceClient",
12
+ "rpcs": {
13
+ "CountMessageTokens": {
14
+ "methods": [
15
+ "count_message_tokens"
16
+ ]
17
+ },
18
+ "GenerateMessage": {
19
+ "methods": [
20
+ "generate_message"
21
+ ]
22
+ }
23
+ }
24
+ },
25
+ "grpc-async": {
26
+ "libraryClient": "DiscussServiceAsyncClient",
27
+ "rpcs": {
28
+ "CountMessageTokens": {
29
+ "methods": [
30
+ "count_message_tokens"
31
+ ]
32
+ },
33
+ "GenerateMessage": {
34
+ "methods": [
35
+ "generate_message"
36
+ ]
37
+ }
38
+ }
39
+ },
40
+ "rest": {
41
+ "libraryClient": "DiscussServiceClient",
42
+ "rpcs": {
43
+ "CountMessageTokens": {
44
+ "methods": [
45
+ "count_message_tokens"
46
+ ]
47
+ },
48
+ "GenerateMessage": {
49
+ "methods": [
50
+ "generate_message"
51
+ ]
52
+ }
53
+ }
54
+ }
55
+ }
56
+ },
57
+ "ModelService": {
58
+ "clients": {
59
+ "grpc": {
60
+ "libraryClient": "ModelServiceClient",
61
+ "rpcs": {
62
+ "GetModel": {
63
+ "methods": [
64
+ "get_model"
65
+ ]
66
+ },
67
+ "ListModels": {
68
+ "methods": [
69
+ "list_models"
70
+ ]
71
+ }
72
+ }
73
+ },
74
+ "grpc-async": {
75
+ "libraryClient": "ModelServiceAsyncClient",
76
+ "rpcs": {
77
+ "GetModel": {
78
+ "methods": [
79
+ "get_model"
80
+ ]
81
+ },
82
+ "ListModels": {
83
+ "methods": [
84
+ "list_models"
85
+ ]
86
+ }
87
+ }
88
+ },
89
+ "rest": {
90
+ "libraryClient": "ModelServiceClient",
91
+ "rpcs": {
92
+ "GetModel": {
93
+ "methods": [
94
+ "get_model"
95
+ ]
96
+ },
97
+ "ListModels": {
98
+ "methods": [
99
+ "list_models"
100
+ ]
101
+ }
102
+ }
103
+ }
104
+ }
105
+ },
106
+ "TextService": {
107
+ "clients": {
108
+ "grpc": {
109
+ "libraryClient": "TextServiceClient",
110
+ "rpcs": {
111
+ "EmbedText": {
112
+ "methods": [
113
+ "embed_text"
114
+ ]
115
+ },
116
+ "GenerateText": {
117
+ "methods": [
118
+ "generate_text"
119
+ ]
120
+ }
121
+ }
122
+ },
123
+ "grpc-async": {
124
+ "libraryClient": "TextServiceAsyncClient",
125
+ "rpcs": {
126
+ "EmbedText": {
127
+ "methods": [
128
+ "embed_text"
129
+ ]
130
+ },
131
+ "GenerateText": {
132
+ "methods": [
133
+ "generate_text"
134
+ ]
135
+ }
136
+ }
137
+ },
138
+ "rest": {
139
+ "libraryClient": "TextServiceClient",
140
+ "rpcs": {
141
+ "EmbedText": {
142
+ "methods": [
143
+ "embed_text"
144
+ ]
145
+ },
146
+ "GenerateText": {
147
+ "methods": [
148
+ "generate_text"
149
+ ]
150
+ }
151
+ }
152
+ }
153
+ }
154
+ }
155
+ }
156
+ }
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta2/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_v1beta2/py.typed ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ # Marker file for PEP 561.
2
+ # The google-ai-generativelanguage package uses inline types.
.venv/lib/python3.11/site-packages/google/ai/generativelanguage_v1beta2/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
+ #