google-genai 1.48.0__py3-none-any.whl → 1.50.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,552 @@
1
+ # Copyright 2025 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+
16
+ # Code generated by the Google Gen AI SDK generator DO NOT EDIT.
17
+
18
+ from functools import partial
19
+ import json
20
+ import logging
21
+ from typing import Any, Optional, Union
22
+ from urllib.parse import urlencode
23
+
24
+ from . import _api_module
25
+ from . import _common
26
+ from . import types
27
+ from ._common import get_value_by_path as getv
28
+ from ._common import set_value_by_path as setv
29
+ from .pagers import AsyncPager, Pager
30
+
31
+
32
+ logger = logging.getLogger('google_genai.documents')
33
+
34
+
35
+ def _DeleteDocumentConfig_to_mldev(
36
+ from_object: Union[dict[str, Any], object],
37
+ parent_object: Optional[dict[str, Any]] = None,
38
+ ) -> dict[str, Any]:
39
+ to_object: dict[str, Any] = {}
40
+
41
+ if getv(from_object, ['force']) is not None:
42
+ setv(parent_object, ['_query', 'force'], getv(from_object, ['force']))
43
+
44
+ return to_object
45
+
46
+
47
+ def _DeleteDocumentParameters_to_mldev(
48
+ from_object: Union[dict[str, Any], object],
49
+ parent_object: Optional[dict[str, Any]] = None,
50
+ ) -> dict[str, Any]:
51
+ to_object: dict[str, Any] = {}
52
+ if getv(from_object, ['name']) is not None:
53
+ setv(to_object, ['_url', 'name'], getv(from_object, ['name']))
54
+
55
+ if getv(from_object, ['config']) is not None:
56
+ _DeleteDocumentConfig_to_mldev(getv(from_object, ['config']), to_object)
57
+
58
+ return to_object
59
+
60
+
61
+ def _GetDocumentParameters_to_mldev(
62
+ from_object: Union[dict[str, Any], object],
63
+ parent_object: Optional[dict[str, Any]] = None,
64
+ ) -> dict[str, Any]:
65
+ to_object: dict[str, Any] = {}
66
+ if getv(from_object, ['name']) is not None:
67
+ setv(to_object, ['_url', 'name'], getv(from_object, ['name']))
68
+
69
+ return to_object
70
+
71
+
72
+ def _ListDocumentsConfig_to_mldev(
73
+ from_object: Union[dict[str, Any], object],
74
+ parent_object: Optional[dict[str, Any]] = None,
75
+ ) -> dict[str, Any]:
76
+ to_object: dict[str, Any] = {}
77
+
78
+ if getv(from_object, ['page_size']) is not None:
79
+ setv(
80
+ parent_object, ['_query', 'pageSize'], getv(from_object, ['page_size'])
81
+ )
82
+
83
+ if getv(from_object, ['page_token']) is not None:
84
+ setv(
85
+ parent_object,
86
+ ['_query', 'pageToken'],
87
+ getv(from_object, ['page_token']),
88
+ )
89
+
90
+ return to_object
91
+
92
+
93
+ def _ListDocumentsParameters_to_mldev(
94
+ from_object: Union[dict[str, Any], object],
95
+ parent_object: Optional[dict[str, Any]] = None,
96
+ ) -> dict[str, Any]:
97
+ to_object: dict[str, Any] = {}
98
+ if getv(from_object, ['parent']) is not None:
99
+ setv(to_object, ['_url', 'parent'], getv(from_object, ['parent']))
100
+
101
+ if getv(from_object, ['config']) is not None:
102
+ _ListDocumentsConfig_to_mldev(getv(from_object, ['config']), to_object)
103
+
104
+ return to_object
105
+
106
+
107
+ def _ListDocumentsResponse_from_mldev(
108
+ from_object: Union[dict[str, Any], object],
109
+ parent_object: Optional[dict[str, Any]] = None,
110
+ ) -> dict[str, Any]:
111
+ to_object: dict[str, Any] = {}
112
+ if getv(from_object, ['sdkHttpResponse']) is not None:
113
+ setv(
114
+ to_object, ['sdk_http_response'], getv(from_object, ['sdkHttpResponse'])
115
+ )
116
+
117
+ if getv(from_object, ['nextPageToken']) is not None:
118
+ setv(to_object, ['next_page_token'], getv(from_object, ['nextPageToken']))
119
+
120
+ if getv(from_object, ['documents']) is not None:
121
+ setv(
122
+ to_object,
123
+ ['documents'],
124
+ [item for item in getv(from_object, ['documents'])],
125
+ )
126
+
127
+ return to_object
128
+
129
+
130
+ class Documents(_api_module.BaseModule):
131
+
132
+ def get(
133
+ self, *, name: str, config: Optional[types.GetDocumentConfigOrDict] = None
134
+ ) -> types.Document:
135
+ """Gets metadata about a Document.
136
+
137
+ Args:
138
+ name (str): The resource name of the Document.
139
+ Example: ragStores/rag-store-foo/documents/documents-bar
140
+ config (GetDocumentConfig | None): Optional parameters for the request.
141
+
142
+ Returns:
143
+ The Document.
144
+ """
145
+
146
+ parameter_model = types._GetDocumentParameters(
147
+ name=name,
148
+ config=config,
149
+ )
150
+
151
+ request_url_dict: Optional[dict[str, str]]
152
+ if self._api_client.vertexai:
153
+ raise ValueError(
154
+ 'This method is only supported in the Gemini Developer client.'
155
+ )
156
+ else:
157
+ request_dict = _GetDocumentParameters_to_mldev(parameter_model)
158
+ request_url_dict = request_dict.get('_url')
159
+ if request_url_dict:
160
+ path = '{name}'.format_map(request_url_dict)
161
+ else:
162
+ path = '{name}'
163
+
164
+ query_params = request_dict.get('_query')
165
+ if query_params:
166
+ path = f'{path}?{urlencode(query_params)}'
167
+ # TODO: remove the hack that pops config.
168
+ request_dict.pop('config', None)
169
+
170
+ http_options: Optional[types.HttpOptions] = None
171
+ if (
172
+ parameter_model.config is not None
173
+ and parameter_model.config.http_options is not None
174
+ ):
175
+ http_options = parameter_model.config.http_options
176
+
177
+ request_dict = _common.convert_to_dict(request_dict)
178
+ request_dict = _common.encode_unserializable_types(request_dict)
179
+
180
+ response = self._api_client.request('get', path, request_dict, http_options)
181
+
182
+ response_dict = {} if not response.body else json.loads(response.body)
183
+
184
+ return_value = types.Document._from_response(
185
+ response=response_dict, kwargs=parameter_model.model_dump()
186
+ )
187
+
188
+ self._api_client._verify_response(return_value)
189
+ return return_value
190
+
191
+ def delete(
192
+ self,
193
+ *,
194
+ name: str,
195
+ config: Optional[types.DeleteDocumentConfigOrDict] = None,
196
+ ) -> None:
197
+ """Deletes a Document.
198
+
199
+ Args:
200
+ name (str): The resource name of the Document.
201
+ Example: ragStores/rag-store-foo/documents/documents-bar
202
+ config (DeleteDocumentConfig | None): Optional parameters for the request.
203
+
204
+ Returns:
205
+ None
206
+ """
207
+
208
+ parameter_model = types._DeleteDocumentParameters(
209
+ name=name,
210
+ config=config,
211
+ )
212
+
213
+ request_url_dict: Optional[dict[str, str]]
214
+ if self._api_client.vertexai:
215
+ raise ValueError(
216
+ 'This method is only supported in the Gemini Developer client.'
217
+ )
218
+ else:
219
+ request_dict = _DeleteDocumentParameters_to_mldev(parameter_model)
220
+ request_url_dict = request_dict.get('_url')
221
+ if request_url_dict:
222
+ path = '{name}'.format_map(request_url_dict)
223
+ else:
224
+ path = '{name}'
225
+
226
+ query_params = request_dict.get('_query')
227
+ if query_params:
228
+ path = f'{path}?{urlencode(query_params)}'
229
+ # TODO: remove the hack that pops config.
230
+ request_dict.pop('config', None)
231
+
232
+ http_options: Optional[types.HttpOptions] = None
233
+ if (
234
+ parameter_model.config is not None
235
+ and parameter_model.config.http_options is not None
236
+ ):
237
+ http_options = parameter_model.config.http_options
238
+
239
+ request_dict = _common.convert_to_dict(request_dict)
240
+ request_dict = _common.encode_unserializable_types(request_dict)
241
+
242
+ response = self._api_client.request(
243
+ 'delete', path, request_dict, http_options
244
+ )
245
+
246
+ def _list(
247
+ self,
248
+ *,
249
+ parent: str,
250
+ config: Optional[types.ListDocumentsConfigOrDict] = None,
251
+ ) -> types.ListDocumentsResponse:
252
+ """Lists all Documents in a FileSearchStore.
253
+
254
+ Args:
255
+ parent (str): The name of the FileSearchStore containing the Documents.
256
+ config (ListDocumentsConfig | None): Optional parameters for the request,
257
+ such as page_size.
258
+
259
+ Returns:
260
+ ListDocumentsResponse: A paginated list of Documents.
261
+ """
262
+
263
+ parameter_model = types._ListDocumentsParameters(
264
+ parent=parent,
265
+ config=config,
266
+ )
267
+
268
+ request_url_dict: Optional[dict[str, str]]
269
+ if self._api_client.vertexai:
270
+ raise ValueError(
271
+ 'This method is only supported in the Gemini Developer client.'
272
+ )
273
+ else:
274
+ request_dict = _ListDocumentsParameters_to_mldev(parameter_model)
275
+ request_url_dict = request_dict.get('_url')
276
+ if request_url_dict:
277
+ path = '{parent}/documents'.format_map(request_url_dict)
278
+ else:
279
+ path = '{parent}/documents'
280
+
281
+ query_params = request_dict.get('_query')
282
+ if query_params:
283
+ path = f'{path}?{urlencode(query_params)}'
284
+ # TODO: remove the hack that pops config.
285
+ request_dict.pop('config', None)
286
+
287
+ http_options: Optional[types.HttpOptions] = None
288
+ if (
289
+ parameter_model.config is not None
290
+ and parameter_model.config.http_options is not None
291
+ ):
292
+ http_options = parameter_model.config.http_options
293
+
294
+ request_dict = _common.convert_to_dict(request_dict)
295
+ request_dict = _common.encode_unserializable_types(request_dict)
296
+
297
+ response = self._api_client.request('get', path, request_dict, http_options)
298
+
299
+ response_dict = {} if not response.body else json.loads(response.body)
300
+
301
+ if not self._api_client.vertexai:
302
+ response_dict = _ListDocumentsResponse_from_mldev(response_dict)
303
+
304
+ return_value = types.ListDocumentsResponse._from_response(
305
+ response=response_dict, kwargs=parameter_model.model_dump()
306
+ )
307
+
308
+ self._api_client._verify_response(return_value)
309
+ return return_value
310
+
311
+ def list(
312
+ self,
313
+ *,
314
+ parent: str,
315
+ config: Optional[types.ListDocumentsConfigOrDict] = None,
316
+ ) -> Pager[types.Document]:
317
+ """Lists documents.
318
+
319
+ Args:
320
+ parent (str): The name of the RagStore containing the Documents.
321
+ config (ListDocumentsConfig): Optional configuration for the list request.
322
+
323
+ Returns:
324
+ A Pager object that contains one page of documents. When iterating over
325
+ the pager, it automatically fetches the next page if there are more.
326
+ Usage:
327
+ .. code-block:: python
328
+ for document in client.documents.list(parent='rag_store_name'):
329
+ print(f"document: {document.name} - {document.display_name}")
330
+ """
331
+ list_request = partial(self._list, parent=parent)
332
+ return Pager(
333
+ 'documents',
334
+ list_request,
335
+ self._list(parent=parent, config=config),
336
+ config,
337
+ )
338
+
339
+
340
+ class AsyncDocuments(_api_module.BaseModule):
341
+
342
+ async def get(
343
+ self, *, name: str, config: Optional[types.GetDocumentConfigOrDict] = None
344
+ ) -> types.Document:
345
+ """Gets metadata about a Document.
346
+
347
+ Args:
348
+ name (str): The resource name of the Document.
349
+ Example: ragStores/rag-store-foo/documents/documents-bar
350
+ config (GetDocumentConfig | None): Optional parameters for the request.
351
+
352
+ Returns:
353
+ The Document.
354
+ """
355
+
356
+ parameter_model = types._GetDocumentParameters(
357
+ name=name,
358
+ config=config,
359
+ )
360
+
361
+ request_url_dict: Optional[dict[str, str]]
362
+ if self._api_client.vertexai:
363
+ raise ValueError(
364
+ 'This method is only supported in the Gemini Developer client.'
365
+ )
366
+ else:
367
+ request_dict = _GetDocumentParameters_to_mldev(parameter_model)
368
+ request_url_dict = request_dict.get('_url')
369
+ if request_url_dict:
370
+ path = '{name}'.format_map(request_url_dict)
371
+ else:
372
+ path = '{name}'
373
+
374
+ query_params = request_dict.get('_query')
375
+ if query_params:
376
+ path = f'{path}?{urlencode(query_params)}'
377
+ # TODO: remove the hack that pops config.
378
+ request_dict.pop('config', None)
379
+
380
+ http_options: Optional[types.HttpOptions] = None
381
+ if (
382
+ parameter_model.config is not None
383
+ and parameter_model.config.http_options is not None
384
+ ):
385
+ http_options = parameter_model.config.http_options
386
+
387
+ request_dict = _common.convert_to_dict(request_dict)
388
+ request_dict = _common.encode_unserializable_types(request_dict)
389
+
390
+ response = await self._api_client.async_request(
391
+ 'get', path, request_dict, http_options
392
+ )
393
+
394
+ response_dict = {} if not response.body else json.loads(response.body)
395
+
396
+ return_value = types.Document._from_response(
397
+ response=response_dict, kwargs=parameter_model.model_dump()
398
+ )
399
+
400
+ self._api_client._verify_response(return_value)
401
+ return return_value
402
+
403
+ async def delete(
404
+ self,
405
+ *,
406
+ name: str,
407
+ config: Optional[types.DeleteDocumentConfigOrDict] = None,
408
+ ) -> None:
409
+ """Deletes a Document.
410
+
411
+ Args:
412
+ name (str): The resource name of the Document.
413
+ Example: ragStores/rag-store-foo/documents/documents-bar
414
+ config (DeleteDocumentConfig | None): Optional parameters for the request.
415
+
416
+ Returns:
417
+ None
418
+ """
419
+
420
+ parameter_model = types._DeleteDocumentParameters(
421
+ name=name,
422
+ config=config,
423
+ )
424
+
425
+ request_url_dict: Optional[dict[str, str]]
426
+ if self._api_client.vertexai:
427
+ raise ValueError(
428
+ 'This method is only supported in the Gemini Developer client.'
429
+ )
430
+ else:
431
+ request_dict = _DeleteDocumentParameters_to_mldev(parameter_model)
432
+ request_url_dict = request_dict.get('_url')
433
+ if request_url_dict:
434
+ path = '{name}'.format_map(request_url_dict)
435
+ else:
436
+ path = '{name}'
437
+
438
+ query_params = request_dict.get('_query')
439
+ if query_params:
440
+ path = f'{path}?{urlencode(query_params)}'
441
+ # TODO: remove the hack that pops config.
442
+ request_dict.pop('config', None)
443
+
444
+ http_options: Optional[types.HttpOptions] = None
445
+ if (
446
+ parameter_model.config is not None
447
+ and parameter_model.config.http_options is not None
448
+ ):
449
+ http_options = parameter_model.config.http_options
450
+
451
+ request_dict = _common.convert_to_dict(request_dict)
452
+ request_dict = _common.encode_unserializable_types(request_dict)
453
+
454
+ response = await self._api_client.async_request(
455
+ 'delete', path, request_dict, http_options
456
+ )
457
+
458
+ async def _list(
459
+ self,
460
+ *,
461
+ parent: str,
462
+ config: Optional[types.ListDocumentsConfigOrDict] = None,
463
+ ) -> types.ListDocumentsResponse:
464
+ """Lists all Documents in a FileSearchStore.
465
+
466
+ Args:
467
+ parent (str): The name of the FileSearchStore containing the Documents.
468
+ config (ListDocumentsConfig | None): Optional parameters for the request,
469
+ such as page_size.
470
+
471
+ Returns:
472
+ ListDocumentsResponse: A paginated list of Documents.
473
+ """
474
+
475
+ parameter_model = types._ListDocumentsParameters(
476
+ parent=parent,
477
+ config=config,
478
+ )
479
+
480
+ request_url_dict: Optional[dict[str, str]]
481
+ if self._api_client.vertexai:
482
+ raise ValueError(
483
+ 'This method is only supported in the Gemini Developer client.'
484
+ )
485
+ else:
486
+ request_dict = _ListDocumentsParameters_to_mldev(parameter_model)
487
+ request_url_dict = request_dict.get('_url')
488
+ if request_url_dict:
489
+ path = '{parent}/documents'.format_map(request_url_dict)
490
+ else:
491
+ path = '{parent}/documents'
492
+
493
+ query_params = request_dict.get('_query')
494
+ if query_params:
495
+ path = f'{path}?{urlencode(query_params)}'
496
+ # TODO: remove the hack that pops config.
497
+ request_dict.pop('config', None)
498
+
499
+ http_options: Optional[types.HttpOptions] = None
500
+ if (
501
+ parameter_model.config is not None
502
+ and parameter_model.config.http_options is not None
503
+ ):
504
+ http_options = parameter_model.config.http_options
505
+
506
+ request_dict = _common.convert_to_dict(request_dict)
507
+ request_dict = _common.encode_unserializable_types(request_dict)
508
+
509
+ response = await self._api_client.async_request(
510
+ 'get', path, request_dict, http_options
511
+ )
512
+
513
+ response_dict = {} if not response.body else json.loads(response.body)
514
+
515
+ if not self._api_client.vertexai:
516
+ response_dict = _ListDocumentsResponse_from_mldev(response_dict)
517
+
518
+ return_value = types.ListDocumentsResponse._from_response(
519
+ response=response_dict, kwargs=parameter_model.model_dump()
520
+ )
521
+
522
+ self._api_client._verify_response(return_value)
523
+ return return_value
524
+
525
+ async def list(
526
+ self,
527
+ *,
528
+ parent: str,
529
+ config: Optional[types.ListDocumentsConfigOrDict] = None,
530
+ ) -> AsyncPager[types.Document]:
531
+ """Lists documents asynchronously.
532
+
533
+ Args:
534
+ parent (str): The name of the RagStore containing the Documents.
535
+ config (ListDocumentsConfig): Optional configuration for the list request.
536
+
537
+ Returns:
538
+ A Pager object that contains one page of documents. When iterating over
539
+ the pager, it automatically fetches the next page if there are more.
540
+ Usage:
541
+ .. code-block:: python
542
+ async for document in await
543
+ client.documents.list(parent='rag_store_name'):
544
+ print(f"document: {document.name} - {document.display_name}")
545
+ """
546
+ list_request = partial(self._list, parent=parent)
547
+ return AsyncPager(
548
+ 'documents',
549
+ list_request,
550
+ await self._list(parent=parent, config=config),
551
+ config,
552
+ )
google/genai/errors.py CHANGED
@@ -29,7 +29,7 @@ if TYPE_CHECKING:
29
29
  class APIError(Exception):
30
30
  """General errors raised by the GenAI API."""
31
31
  code: int
32
- response: Union['ReplayResponse', httpx.Response]
32
+ response: Union['ReplayResponse', httpx.Response, 'aiohttp.ClientResponse']
33
33
 
34
34
  status: Optional[str] = None
35
35
  message: Optional[str] = None
@@ -103,7 +103,30 @@ class APIError(Exception):
103
103
  else:
104
104
  response_json = response.body_segments[0].get('error', {})
105
105
 
106
- status_code = response.status_code
106
+ cls.raise_error(response.status_code, response_json, response)
107
+
108
+ @classmethod
109
+ def raise_error(
110
+ cls,
111
+ status_code: int,
112
+ response_json: Any,
113
+ response: Optional[
114
+ Union['ReplayResponse', httpx.Response, 'aiohttp.ClientResponse']
115
+ ],
116
+ ) -> None:
117
+ """Raises an appropriate APIError subclass based on the status code.
118
+
119
+ Args:
120
+ status_code: The HTTP status code of the response.
121
+ response_json: The JSON body of the response, or a dict containing error
122
+ details.
123
+ response: The original response object.
124
+
125
+ Raises:
126
+ ClientError: If the status code is in the 4xx range.
127
+ ServerError: If the status code is in the 5xx range.
128
+ APIError: For other error status codes.
129
+ """
107
130
  if 400 <= status_code < 500:
108
131
  raise ClientError(status_code, response_json, response)
109
132
  elif 500 <= status_code < 600:
@@ -162,6 +185,27 @@ class APIError(Exception):
162
185
  except ImportError:
163
186
  raise ValueError(f'Unsupported response type: {type(response)}')
164
187
 
188
+ await cls.raise_error_async(status_code, response_json, response)
189
+
190
+ @classmethod
191
+ async def raise_error_async(
192
+ cls, status_code: int, response_json: Any, response: Optional[
193
+ Union['ReplayResponse', httpx.Response, 'aiohttp.ClientResponse']
194
+ ]
195
+ ) -> None:
196
+ """Raises an appropriate APIError subclass based on the status code.
197
+
198
+ Args:
199
+ status_code: The HTTP status code of the response.
200
+ response_json: The JSON body of the response, or a dict containing error
201
+ details.
202
+ response: The original response object.
203
+
204
+ Raises:
205
+ ClientError: If the status code is in the 4xx range.
206
+ ServerError: If the status code is in the 5xx range.
207
+ APIError: For other error status codes.
208
+ """
165
209
  if 400 <= status_code < 500:
166
210
  raise ClientError(status_code, response_json, response)
167
211
  elif 500 <= status_code < 600: