google-genai 1.54.0__py3-none-any.whl → 1.56.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.
Files changed (137) hide show
  1. google/genai/__init__.py +1 -0
  2. google/genai/_interactions/__init__.py +117 -0
  3. google/genai/_interactions/_base_client.py +2025 -0
  4. google/genai/_interactions/_client.py +511 -0
  5. google/genai/_interactions/_compat.py +234 -0
  6. google/genai/_interactions/_constants.py +29 -0
  7. google/genai/_interactions/_exceptions.py +122 -0
  8. google/genai/_interactions/_files.py +139 -0
  9. google/genai/_interactions/_models.py +873 -0
  10. google/genai/_interactions/_qs.py +165 -0
  11. google/genai/_interactions/_resource.py +58 -0
  12. google/genai/_interactions/_response.py +847 -0
  13. google/genai/_interactions/_streaming.py +354 -0
  14. google/genai/_interactions/_types.py +276 -0
  15. google/genai/_interactions/_utils/__init__.py +79 -0
  16. google/genai/_interactions/_utils/_compat.py +61 -0
  17. google/genai/_interactions/_utils/_datetime_parse.py +151 -0
  18. google/genai/_interactions/_utils/_logs.py +40 -0
  19. google/genai/_interactions/_utils/_proxy.py +80 -0
  20. google/genai/_interactions/_utils/_reflection.py +57 -0
  21. google/genai/_interactions/_utils/_resources_proxy.py +39 -0
  22. google/genai/_interactions/_utils/_streams.py +27 -0
  23. google/genai/_interactions/_utils/_sync.py +73 -0
  24. google/genai/_interactions/_utils/_transform.py +472 -0
  25. google/genai/_interactions/_utils/_typing.py +172 -0
  26. google/genai/_interactions/_utils/_utils.py +437 -0
  27. google/genai/_interactions/_version.py +18 -0
  28. google/genai/_interactions/py.typed +0 -0
  29. google/genai/_interactions/resources/__init__.py +34 -0
  30. google/genai/_interactions/resources/interactions.py +1350 -0
  31. google/genai/_interactions/types/__init__.py +109 -0
  32. google/genai/_interactions/types/allowed_tools.py +33 -0
  33. google/genai/_interactions/types/allowed_tools_param.py +35 -0
  34. google/genai/_interactions/types/annotation.py +42 -0
  35. google/genai/_interactions/types/annotation_param.py +42 -0
  36. google/genai/_interactions/types/audio_content.py +37 -0
  37. google/genai/_interactions/types/audio_content_param.py +44 -0
  38. google/genai/_interactions/types/audio_mime_type.py +25 -0
  39. google/genai/_interactions/types/audio_mime_type_param.py +27 -0
  40. google/genai/_interactions/types/code_execution_call_arguments.py +33 -0
  41. google/genai/_interactions/types/code_execution_call_arguments_param.py +32 -0
  42. google/genai/_interactions/types/code_execution_call_content.py +36 -0
  43. google/genai/_interactions/types/code_execution_call_content_param.py +36 -0
  44. google/genai/_interactions/types/code_execution_result_content.py +41 -0
  45. google/genai/_interactions/types/code_execution_result_content_param.py +40 -0
  46. google/genai/_interactions/types/content_delta.py +342 -0
  47. google/genai/_interactions/types/content_start.py +79 -0
  48. google/genai/_interactions/types/content_stop.py +35 -0
  49. google/genai/_interactions/types/deep_research_agent_config.py +32 -0
  50. google/genai/_interactions/types/deep_research_agent_config_param.py +31 -0
  51. google/genai/_interactions/types/document_content.py +37 -0
  52. google/genai/_interactions/types/document_content_param.py +44 -0
  53. google/genai/_interactions/types/document_mime_type.py +23 -0
  54. google/genai/_interactions/types/document_mime_type_param.py +25 -0
  55. google/genai/_interactions/types/dynamic_agent_config.py +43 -0
  56. google/genai/_interactions/types/dynamic_agent_config_param.py +32 -0
  57. google/genai/_interactions/types/error_event.py +46 -0
  58. google/genai/_interactions/types/file_search_result_content.py +45 -0
  59. google/genai/_interactions/types/file_search_result_content_param.py +45 -0
  60. google/genai/_interactions/types/function.py +38 -0
  61. google/genai/_interactions/types/function_call_content.py +38 -0
  62. google/genai/_interactions/types/function_call_content_param.py +38 -0
  63. google/genai/_interactions/types/function_param.py +37 -0
  64. google/genai/_interactions/types/function_result_content.py +51 -0
  65. google/genai/_interactions/types/function_result_content_param.py +53 -0
  66. google/genai/_interactions/types/generation_config.py +57 -0
  67. google/genai/_interactions/types/generation_config_param.py +59 -0
  68. google/genai/_interactions/types/google_search_call_arguments.py +29 -0
  69. google/genai/_interactions/types/google_search_call_arguments_param.py +31 -0
  70. google/genai/_interactions/types/google_search_call_content.py +36 -0
  71. google/genai/_interactions/types/google_search_call_content_param.py +36 -0
  72. google/genai/_interactions/types/google_search_result.py +35 -0
  73. google/genai/_interactions/types/google_search_result_content.py +42 -0
  74. google/genai/_interactions/types/google_search_result_content_param.py +43 -0
  75. google/genai/_interactions/types/google_search_result_param.py +35 -0
  76. google/genai/_interactions/types/image_content.py +40 -0
  77. google/genai/_interactions/types/image_content_param.py +47 -0
  78. google/genai/_interactions/types/image_mime_type.py +23 -0
  79. google/genai/_interactions/types/image_mime_type_param.py +25 -0
  80. google/genai/_interactions/types/interaction.py +165 -0
  81. google/genai/_interactions/types/interaction_create_params.py +212 -0
  82. google/genai/_interactions/types/interaction_event.py +37 -0
  83. google/genai/_interactions/types/interaction_get_params.py +46 -0
  84. google/genai/_interactions/types/interaction_sse_event.py +32 -0
  85. google/genai/_interactions/types/interaction_status_update.py +37 -0
  86. google/genai/_interactions/types/mcp_server_tool_call_content.py +41 -0
  87. google/genai/_interactions/types/mcp_server_tool_call_content_param.py +41 -0
  88. google/genai/_interactions/types/mcp_server_tool_result_content.py +51 -0
  89. google/genai/_interactions/types/mcp_server_tool_result_content_param.py +53 -0
  90. google/genai/_interactions/types/model.py +36 -0
  91. google/genai/_interactions/types/model_param.py +38 -0
  92. google/genai/_interactions/types/speech_config.py +35 -0
  93. google/genai/_interactions/types/speech_config_param.py +35 -0
  94. google/genai/_interactions/types/text_content.py +36 -0
  95. google/genai/_interactions/types/text_content_param.py +37 -0
  96. google/genai/_interactions/types/thinking_level.py +22 -0
  97. google/genai/_interactions/types/thought_content.py +40 -0
  98. google/genai/_interactions/types/thought_content_param.py +46 -0
  99. google/genai/_interactions/types/tool.py +100 -0
  100. google/genai/_interactions/types/tool_choice.py +26 -0
  101. google/genai/_interactions/types/tool_choice_config.py +28 -0
  102. google/genai/_interactions/types/tool_choice_config_param.py +29 -0
  103. google/genai/_interactions/types/tool_choice_param.py +28 -0
  104. google/genai/_interactions/types/tool_choice_type.py +22 -0
  105. google/genai/_interactions/types/tool_param.py +97 -0
  106. google/genai/_interactions/types/turn.py +76 -0
  107. google/genai/_interactions/types/turn_param.py +73 -0
  108. google/genai/_interactions/types/url_context_call_arguments.py +29 -0
  109. google/genai/_interactions/types/url_context_call_arguments_param.py +31 -0
  110. google/genai/_interactions/types/url_context_call_content.py +36 -0
  111. google/genai/_interactions/types/url_context_call_content_param.py +36 -0
  112. google/genai/_interactions/types/url_context_result.py +33 -0
  113. google/genai/_interactions/types/url_context_result_content.py +42 -0
  114. google/genai/_interactions/types/url_context_result_content_param.py +43 -0
  115. google/genai/_interactions/types/url_context_result_param.py +32 -0
  116. google/genai/_interactions/types/usage.py +106 -0
  117. google/genai/_interactions/types/usage_param.py +106 -0
  118. google/genai/_interactions/types/video_content.py +40 -0
  119. google/genai/_interactions/types/video_content_param.py +47 -0
  120. google/genai/_interactions/types/video_mime_type.py +36 -0
  121. google/genai/_interactions/types/video_mime_type_param.py +38 -0
  122. google/genai/_live_converters.py +33 -30
  123. google/genai/_tokens_converters.py +5 -0
  124. google/genai/batches.py +7 -0
  125. google/genai/client.py +226 -1
  126. google/genai/interactions.py +17 -0
  127. google/genai/live.py +4 -3
  128. google/genai/models.py +14 -29
  129. google/genai/tunings.py +1 -27
  130. google/genai/types.py +92 -22
  131. google/genai/version.py +1 -1
  132. {google_genai-1.54.0.dist-info → google_genai-1.56.0.dist-info}/METADATA +226 -22
  133. google_genai-1.56.0.dist-info/RECORD +162 -0
  134. google_genai-1.54.0.dist-info/RECORD +0 -41
  135. {google_genai-1.54.0.dist-info → google_genai-1.56.0.dist-info}/WHEEL +0 -0
  136. {google_genai-1.54.0.dist-info → google_genai-1.56.0.dist-info}/licenses/LICENSE +0 -0
  137. {google_genai-1.54.0.dist-info → google_genai-1.56.0.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,354 @@
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
+ # Note: initially copied from https://github.com/florimondmanca/httpx-sse/blob/master/src/httpx_sse/_decoders.py
17
+ from __future__ import annotations
18
+
19
+ import json
20
+ import inspect
21
+ from types import TracebackType
22
+ from typing import TYPE_CHECKING, Any, Generic, TypeVar, Iterator, AsyncIterator, cast
23
+ from typing_extensions import Self, Protocol, TypeGuard, override, get_origin, runtime_checkable
24
+
25
+ import httpx
26
+
27
+ from ._utils import extract_type_var_from_base
28
+
29
+ if TYPE_CHECKING:
30
+ from ._client import GeminiNextGenAPIClient, AsyncGeminiNextGenAPIClient
31
+
32
+
33
+ _T = TypeVar("_T")
34
+
35
+
36
+ class Stream(Generic[_T]):
37
+ """Provides the core interface to iterate over a synchronous stream response."""
38
+
39
+ response: httpx.Response
40
+
41
+ _decoder: SSEBytesDecoder
42
+
43
+ def __init__(
44
+ self,
45
+ *,
46
+ cast_to: type[_T],
47
+ response: httpx.Response,
48
+ client: GeminiNextGenAPIClient,
49
+ ) -> None:
50
+ self.response = response
51
+ self._cast_to = cast_to
52
+ self._client = client
53
+ self._decoder = client._make_sse_decoder()
54
+ self._iterator = self.__stream__()
55
+
56
+ def __next__(self) -> _T:
57
+ return self._iterator.__next__()
58
+
59
+ def __iter__(self) -> Iterator[_T]:
60
+ for item in self._iterator:
61
+ yield item
62
+
63
+ def _iter_events(self) -> Iterator[ServerSentEvent]:
64
+ yield from self._decoder.iter_bytes(self.response.iter_bytes())
65
+
66
+ def __stream__(self) -> Iterator[_T]:
67
+ cast_to = cast(Any, self._cast_to)
68
+ response = self.response
69
+ process_data = self._client._process_response_data
70
+ iterator = self._iter_events()
71
+
72
+ try:
73
+ for sse in iterator:
74
+ if sse.data.startswith("[DONE]"):
75
+ break
76
+
77
+ yield process_data(data=sse.json(), cast_to=cast_to, response=response)
78
+ finally:
79
+ # Ensure the response is closed even if the consumer doesn't read all data
80
+ response.close()
81
+
82
+ def __enter__(self) -> Self:
83
+ return self
84
+
85
+ def __exit__(
86
+ self,
87
+ exc_type: type[BaseException] | None,
88
+ exc: BaseException | None,
89
+ exc_tb: TracebackType | None,
90
+ ) -> None:
91
+ self.close()
92
+
93
+ def close(self) -> None:
94
+ """
95
+ Close the response and release the connection.
96
+
97
+ Automatically called if the response body is read to completion.
98
+ """
99
+ self.response.close()
100
+
101
+
102
+ class AsyncStream(Generic[_T]):
103
+ """Provides the core interface to iterate over an asynchronous stream response."""
104
+
105
+ response: httpx.Response
106
+
107
+ _decoder: SSEDecoder | SSEBytesDecoder
108
+
109
+ def __init__(
110
+ self,
111
+ *,
112
+ cast_to: type[_T],
113
+ response: httpx.Response,
114
+ client: AsyncGeminiNextGenAPIClient,
115
+ ) -> None:
116
+ self.response = response
117
+ self._cast_to = cast_to
118
+ self._client = client
119
+ self._decoder = client._make_sse_decoder()
120
+ self._iterator = self.__stream__()
121
+
122
+ async def __anext__(self) -> _T:
123
+ return await self._iterator.__anext__()
124
+
125
+ async def __aiter__(self) -> AsyncIterator[_T]:
126
+ async for item in self._iterator:
127
+ yield item
128
+
129
+ async def _iter_events(self) -> AsyncIterator[ServerSentEvent]:
130
+ async for sse in self._decoder.aiter_bytes(self.response.aiter_bytes()):
131
+ yield sse
132
+
133
+ async def __stream__(self) -> AsyncIterator[_T]:
134
+ cast_to = cast(Any, self._cast_to)
135
+ response = self.response
136
+ process_data = self._client._process_response_data
137
+ iterator = self._iter_events()
138
+
139
+ try:
140
+ async for sse in iterator:
141
+ if sse.data.startswith("[DONE]"):
142
+ break
143
+
144
+ yield process_data(data=sse.json(), cast_to=cast_to, response=response)
145
+ finally:
146
+ # Ensure the response is closed even if the consumer doesn't read all data
147
+ await response.aclose()
148
+
149
+ async def __aenter__(self) -> Self:
150
+ return self
151
+
152
+ async def __aexit__(
153
+ self,
154
+ exc_type: type[BaseException] | None,
155
+ exc: BaseException | None,
156
+ exc_tb: TracebackType | None,
157
+ ) -> None:
158
+ await self.close()
159
+
160
+ async def close(self) -> None:
161
+ """
162
+ Close the response and release the connection.
163
+
164
+ Automatically called if the response body is read to completion.
165
+ """
166
+ await self.response.aclose()
167
+
168
+
169
+ class ServerSentEvent:
170
+ def __init__(
171
+ self,
172
+ *,
173
+ event: str | None = None,
174
+ data: str | None = None,
175
+ id: str | None = None,
176
+ retry: int | None = None,
177
+ ) -> None:
178
+ if data is None:
179
+ data = ""
180
+
181
+ self._id = id
182
+ self._data = data
183
+ self._event = event or None
184
+ self._retry = retry
185
+
186
+ @property
187
+ def event(self) -> str | None:
188
+ return self._event
189
+
190
+ @property
191
+ def id(self) -> str | None:
192
+ return self._id
193
+
194
+ @property
195
+ def retry(self) -> int | None:
196
+ return self._retry
197
+
198
+ @property
199
+ def data(self) -> str:
200
+ return self._data
201
+
202
+ def json(self) -> Any:
203
+ return json.loads(self.data)
204
+
205
+ @override
206
+ def __repr__(self) -> str:
207
+ return f"ServerSentEvent(event={self.event}, data={self.data}, id={self.id}, retry={self.retry})"
208
+
209
+
210
+ class SSEDecoder:
211
+ _data: list[str]
212
+ _event: str | None
213
+ _retry: int | None
214
+ _last_event_id: str | None
215
+
216
+ def __init__(self) -> None:
217
+ self._event = None
218
+ self._data = []
219
+ self._last_event_id = None
220
+ self._retry = None
221
+
222
+ def iter_bytes(self, iterator: Iterator[bytes]) -> Iterator[ServerSentEvent]:
223
+ """Given an iterator that yields raw binary data, iterate over it & yield every event encountered"""
224
+ for chunk in self._iter_chunks(iterator):
225
+ # Split before decoding so splitlines() only uses \r and \n
226
+ for raw_line in chunk.splitlines():
227
+ line = raw_line.decode("utf-8")
228
+ sse = self.decode(line)
229
+ if sse:
230
+ yield sse
231
+
232
+ def _iter_chunks(self, iterator: Iterator[bytes]) -> Iterator[bytes]:
233
+ """Given an iterator that yields raw binary data, iterate over it and yield individual SSE chunks"""
234
+ data = b""
235
+ for chunk in iterator:
236
+ for line in chunk.splitlines(keepends=True):
237
+ data += line
238
+ if data.endswith((b"\r\r", b"\n\n", b"\r\n\r\n")):
239
+ yield data
240
+ data = b""
241
+ if data:
242
+ yield data
243
+
244
+ async def aiter_bytes(self, iterator: AsyncIterator[bytes]) -> AsyncIterator[ServerSentEvent]:
245
+ """Given an iterator that yields raw binary data, iterate over it & yield every event encountered"""
246
+ async for chunk in self._aiter_chunks(iterator):
247
+ # Split before decoding so splitlines() only uses \r and \n
248
+ for raw_line in chunk.splitlines():
249
+ line = raw_line.decode("utf-8")
250
+ sse = self.decode(line)
251
+ if sse:
252
+ yield sse
253
+
254
+ async def _aiter_chunks(self, iterator: AsyncIterator[bytes]) -> AsyncIterator[bytes]:
255
+ """Given an iterator that yields raw binary data, iterate over it and yield individual SSE chunks"""
256
+ data = b""
257
+ async for chunk in iterator:
258
+ for line in chunk.splitlines(keepends=True):
259
+ data += line
260
+ if data.endswith((b"\r\r", b"\n\n", b"\r\n\r\n")):
261
+ yield data
262
+ data = b""
263
+ if data:
264
+ yield data
265
+
266
+ def decode(self, line: str) -> ServerSentEvent | None:
267
+ # See: https://html.spec.whatwg.org/multipage/server-sent-events.html#event-stream-interpretation # noqa: E501
268
+
269
+ if not line:
270
+ if not self._event and not self._data and not self._last_event_id and self._retry is None:
271
+ return None
272
+
273
+ sse = ServerSentEvent(
274
+ event=self._event,
275
+ data="\n".join(self._data),
276
+ id=self._last_event_id,
277
+ retry=self._retry,
278
+ )
279
+
280
+ # NOTE: as per the SSE spec, do not reset last_event_id.
281
+ self._event = None
282
+ self._data = []
283
+ self._retry = None
284
+
285
+ return sse
286
+
287
+ if line.startswith(":"):
288
+ return None
289
+
290
+ fieldname, _, value = line.partition(":")
291
+
292
+ if value.startswith(" "):
293
+ value = value[1:]
294
+
295
+ if fieldname == "event":
296
+ self._event = value
297
+ elif fieldname == "data":
298
+ self._data.append(value)
299
+ elif fieldname == "id":
300
+ if "\0" in value:
301
+ pass
302
+ else:
303
+ self._last_event_id = value
304
+ elif fieldname == "retry":
305
+ try:
306
+ self._retry = int(value)
307
+ except (TypeError, ValueError):
308
+ pass
309
+ else:
310
+ pass # Field is ignored.
311
+
312
+ return None
313
+
314
+
315
+ @runtime_checkable
316
+ class SSEBytesDecoder(Protocol):
317
+ def iter_bytes(self, iterator: Iterator[bytes]) -> Iterator[ServerSentEvent]:
318
+ """Given an iterator that yields raw binary data, iterate over it & yield every event encountered"""
319
+ ...
320
+
321
+ def aiter_bytes(self, iterator: AsyncIterator[bytes]) -> AsyncIterator[ServerSentEvent]:
322
+ """Given an async iterator that yields raw binary data, iterate over it & yield every event encountered"""
323
+ ...
324
+
325
+
326
+ def is_stream_class_type(typ: type) -> TypeGuard[type[Stream[object]] | type[AsyncStream[object]]]:
327
+ """TypeGuard for determining whether or not the given type is a subclass of `Stream` / `AsyncStream`"""
328
+ origin = get_origin(typ) or typ
329
+ return inspect.isclass(origin) and issubclass(origin, (Stream, AsyncStream))
330
+
331
+
332
+ def extract_stream_chunk_type(
333
+ stream_cls: type,
334
+ *,
335
+ failure_message: str | None = None,
336
+ ) -> type:
337
+ """Given a type like `Stream[T]`, returns the generic type variable `T`.
338
+
339
+ This also handles the case where a concrete subclass is given, e.g.
340
+ ```py
341
+ class MyStream(Stream[bytes]):
342
+ ...
343
+
344
+ extract_stream_chunk_type(MyStream) -> bytes
345
+ ```
346
+ """
347
+ from ._base_client import Stream, AsyncStream
348
+
349
+ return extract_type_var_from_base(
350
+ stream_cls,
351
+ index=0,
352
+ generic_bases=cast("tuple[type, ...]", (Stream, AsyncStream)),
353
+ failure_message=failure_message,
354
+ )
@@ -0,0 +1,276 @@
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
+ from __future__ import annotations
17
+
18
+ from os import PathLike
19
+ from typing import (
20
+ IO,
21
+ TYPE_CHECKING,
22
+ Any,
23
+ Dict,
24
+ List,
25
+ Type,
26
+ Tuple,
27
+ Union,
28
+ Mapping,
29
+ TypeVar,
30
+ Callable,
31
+ Iterator,
32
+ Optional,
33
+ Sequence,
34
+ )
35
+ from typing_extensions import (
36
+ Set,
37
+ Literal,
38
+ Protocol,
39
+ TypeAlias,
40
+ TypedDict,
41
+ SupportsIndex,
42
+ overload,
43
+ override,
44
+ runtime_checkable,
45
+ )
46
+
47
+ import httpx
48
+ import pydantic
49
+ from httpx import URL, Proxy, Timeout, Response, BaseTransport, AsyncBaseTransport
50
+
51
+ if TYPE_CHECKING:
52
+ from ._models import BaseModel
53
+ from ._response import APIResponse, AsyncAPIResponse
54
+
55
+ Transport = BaseTransport
56
+ AsyncTransport = AsyncBaseTransport
57
+ Query = Mapping[str, object]
58
+ Body = object
59
+ AnyMapping = Mapping[str, object]
60
+ ModelT = TypeVar("ModelT", bound=pydantic.BaseModel)
61
+ _T = TypeVar("_T")
62
+
63
+
64
+ # Approximates httpx internal ProxiesTypes and RequestFiles types
65
+ # while adding support for `PathLike` instances
66
+ ProxiesDict = Dict["str | URL", Union[None, str, URL, Proxy]]
67
+ ProxiesTypes = Union[str, Proxy, ProxiesDict]
68
+ if TYPE_CHECKING:
69
+ Base64FileInput = Union[IO[bytes], PathLike[str]]
70
+ FileContent = Union[IO[bytes], bytes, PathLike[str]]
71
+ else:
72
+ Base64FileInput = Union[IO[bytes], PathLike]
73
+ FileContent = Union[IO[bytes], bytes, PathLike] # PathLike is not subscriptable in Python 3.8.
74
+ FileTypes = Union[
75
+ # file (or bytes)
76
+ FileContent,
77
+ # (filename, file (or bytes))
78
+ Tuple[Optional[str], FileContent],
79
+ # (filename, file (or bytes), content_type)
80
+ Tuple[Optional[str], FileContent, Optional[str]],
81
+ # (filename, file (or bytes), content_type, headers)
82
+ Tuple[Optional[str], FileContent, Optional[str], Mapping[str, str]],
83
+ ]
84
+ RequestFiles = Union[Mapping[str, FileTypes], Sequence[Tuple[str, FileTypes]]]
85
+
86
+ # duplicate of the above but without our custom file support
87
+ HttpxFileContent = Union[IO[bytes], bytes]
88
+ HttpxFileTypes = Union[
89
+ # file (or bytes)
90
+ HttpxFileContent,
91
+ # (filename, file (or bytes))
92
+ Tuple[Optional[str], HttpxFileContent],
93
+ # (filename, file (or bytes), content_type)
94
+ Tuple[Optional[str], HttpxFileContent, Optional[str]],
95
+ # (filename, file (or bytes), content_type, headers)
96
+ Tuple[Optional[str], HttpxFileContent, Optional[str], Mapping[str, str]],
97
+ ]
98
+ HttpxRequestFiles = Union[Mapping[str, HttpxFileTypes], Sequence[Tuple[str, HttpxFileTypes]]]
99
+
100
+ # Workaround to support (cast_to: Type[ResponseT]) -> ResponseT
101
+ # where ResponseT includes `None`. In order to support directly
102
+ # passing `None`, overloads would have to be defined for every
103
+ # method that uses `ResponseT` which would lead to an unacceptable
104
+ # amount of code duplication and make it unreadable. See _base_client.py
105
+ # for example usage.
106
+ #
107
+ # This unfortunately means that you will either have
108
+ # to import this type and pass it explicitly:
109
+ #
110
+ # from google.genai._interactions import NoneType
111
+ # client.get('/foo', cast_to=NoneType)
112
+ #
113
+ # or build it yourself:
114
+ #
115
+ # client.get('/foo', cast_to=type(None))
116
+ if TYPE_CHECKING:
117
+ NoneType: Type[None]
118
+ else:
119
+ NoneType = type(None)
120
+
121
+
122
+ class RequestOptions(TypedDict, total=False):
123
+ headers: Headers
124
+ max_retries: int
125
+ timeout: float | Timeout | None
126
+ params: Query
127
+ extra_json: AnyMapping
128
+ idempotency_key: str
129
+ follow_redirects: bool
130
+
131
+
132
+ # Sentinel class used until PEP 0661 is accepted
133
+ class NotGiven:
134
+ """
135
+ For parameters with a meaningful None value, we need to distinguish between
136
+ the user explicitly passing None, and the user not passing the parameter at
137
+ all.
138
+
139
+ User code shouldn't need to use not_given directly.
140
+
141
+ For example:
142
+
143
+ ```py
144
+ def create(timeout: Timeout | None | NotGiven = not_given): ...
145
+
146
+
147
+ create(timeout=1) # 1s timeout
148
+ create(timeout=None) # No timeout
149
+ create() # Default timeout behavior
150
+ ```
151
+ """
152
+
153
+ def __bool__(self) -> Literal[False]:
154
+ return False
155
+
156
+ @override
157
+ def __repr__(self) -> str:
158
+ return "NOT_GIVEN"
159
+
160
+
161
+ not_given = NotGiven()
162
+ # for backwards compatibility:
163
+ NOT_GIVEN = NotGiven()
164
+
165
+
166
+ class Omit:
167
+ """
168
+ To explicitly omit something from being sent in a request, use `omit`.
169
+
170
+ ```py
171
+ # as the default `Content-Type` header is `application/json` that will be sent
172
+ client.post("/upload/files", files={"file": b"my raw file content"})
173
+
174
+ # you can't explicitly override the header as it has to be dynamically generated
175
+ # to look something like: 'multipart/form-data; boundary=0d8382fcf5f8c3be01ca2e11002d2983'
176
+ client.post(..., headers={"Content-Type": "multipart/form-data"})
177
+
178
+ # instead you can remove the default `application/json` header by passing omit
179
+ client.post(..., headers={"Content-Type": omit})
180
+ ```
181
+ """
182
+
183
+ def __bool__(self) -> Literal[False]:
184
+ return False
185
+
186
+
187
+ omit = Omit()
188
+
189
+
190
+ @runtime_checkable
191
+ class ModelBuilderProtocol(Protocol):
192
+ @classmethod
193
+ def build(
194
+ cls: type[_T],
195
+ *,
196
+ response: Response,
197
+ data: object,
198
+ ) -> _T: ...
199
+
200
+
201
+ Headers = Mapping[str, Union[str, Omit]]
202
+
203
+
204
+ class HeadersLikeProtocol(Protocol):
205
+ def get(self, __key: str) -> str | None: ...
206
+
207
+
208
+ HeadersLike = Union[Headers, HeadersLikeProtocol]
209
+
210
+ ResponseT = TypeVar(
211
+ "ResponseT",
212
+ bound=Union[
213
+ object,
214
+ str,
215
+ None,
216
+ "BaseModel",
217
+ List[Any],
218
+ Dict[str, Any],
219
+ Response,
220
+ ModelBuilderProtocol,
221
+ "APIResponse[Any]",
222
+ "AsyncAPIResponse[Any]",
223
+ ],
224
+ )
225
+
226
+ StrBytesIntFloat = Union[str, bytes, int, float]
227
+
228
+ # Note: copied from Pydantic
229
+ # https://github.com/pydantic/pydantic/blob/6f31f8f68ef011f84357330186f603ff295312fd/pydantic/main.py#L79
230
+ IncEx: TypeAlias = Union[Set[int], Set[str], Mapping[int, Union["IncEx", bool]], Mapping[str, Union["IncEx", bool]]]
231
+
232
+ PostParser = Callable[[Any], Any]
233
+
234
+
235
+ @runtime_checkable
236
+ class InheritsGeneric(Protocol):
237
+ """Represents a type that has inherited from `Generic`
238
+
239
+ The `__orig_bases__` property can be used to determine the resolved
240
+ type variable for a given base class.
241
+ """
242
+
243
+ __orig_bases__: tuple[_GenericAlias]
244
+
245
+
246
+ class _GenericAlias(Protocol):
247
+ __origin__: type[object]
248
+
249
+
250
+ class HttpxSendArgs(TypedDict, total=False):
251
+ auth: httpx.Auth
252
+ follow_redirects: bool
253
+
254
+
255
+ _T_co = TypeVar("_T_co", covariant=True)
256
+
257
+
258
+ if TYPE_CHECKING:
259
+ # This works because str.__contains__ does not accept object (either in typeshed or at runtime)
260
+ # https://github.com/hauntsaninja/useful_types/blob/5e9710f3875107d068e7679fd7fec9cfab0eff3b/useful_types/__init__.py#L285
261
+ #
262
+ # Note: index() and count() methods are intentionally omitted to allow pyright to properly
263
+ # infer TypedDict types when dict literals are used in lists assigned to SequenceNotStr.
264
+ class SequenceNotStr(Protocol[_T_co]):
265
+ @overload
266
+ def __getitem__(self, index: SupportsIndex, /) -> _T_co: ...
267
+ @overload
268
+ def __getitem__(self, index: slice, /) -> Sequence[_T_co]: ...
269
+ def __contains__(self, value: object, /) -> bool: ...
270
+ def __len__(self) -> int: ...
271
+ def __iter__(self) -> Iterator[_T_co]: ...
272
+ def __reversed__(self) -> Iterator[_T_co]: ...
273
+ else:
274
+ # just point this to a normal `Sequence` at runtime to avoid having to special case
275
+ # deserializing our custom sequence type
276
+ SequenceNotStr = Sequence
@@ -0,0 +1,79 @@
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
+ from ._sync import asyncify as asyncify
17
+ from ._proxy import LazyProxy as LazyProxy
18
+ from ._utils import (
19
+ flatten as flatten,
20
+ is_dict as is_dict,
21
+ is_list as is_list,
22
+ is_given as is_given,
23
+ is_tuple as is_tuple,
24
+ json_safe as json_safe,
25
+ lru_cache as lru_cache,
26
+ is_mapping as is_mapping,
27
+ is_tuple_t as is_tuple_t,
28
+ is_iterable as is_iterable,
29
+ is_sequence as is_sequence,
30
+ coerce_float as coerce_float,
31
+ is_mapping_t as is_mapping_t,
32
+ removeprefix as removeprefix,
33
+ removesuffix as removesuffix,
34
+ extract_files as extract_files,
35
+ is_sequence_t as is_sequence_t,
36
+ required_args as required_args,
37
+ coerce_boolean as coerce_boolean,
38
+ coerce_integer as coerce_integer,
39
+ file_from_path as file_from_path,
40
+ strip_not_given as strip_not_given,
41
+ deepcopy_minimal as deepcopy_minimal,
42
+ get_async_library as get_async_library,
43
+ maybe_coerce_float as maybe_coerce_float,
44
+ get_required_header as get_required_header,
45
+ maybe_coerce_boolean as maybe_coerce_boolean,
46
+ maybe_coerce_integer as maybe_coerce_integer,
47
+ )
48
+ from ._compat import (
49
+ get_args as get_args,
50
+ is_union as is_union,
51
+ get_origin as get_origin,
52
+ is_typeddict as is_typeddict,
53
+ is_literal_type as is_literal_type,
54
+ )
55
+ from ._typing import (
56
+ is_list_type as is_list_type,
57
+ is_union_type as is_union_type,
58
+ extract_type_arg as extract_type_arg,
59
+ is_iterable_type as is_iterable_type,
60
+ is_required_type as is_required_type,
61
+ is_sequence_type as is_sequence_type,
62
+ is_annotated_type as is_annotated_type,
63
+ is_type_alias_type as is_type_alias_type,
64
+ strip_annotated_type as strip_annotated_type,
65
+ extract_type_var_from_base as extract_type_var_from_base,
66
+ )
67
+ from ._streams import consume_sync_iterator as consume_sync_iterator, consume_async_iterator as consume_async_iterator
68
+ from ._transform import (
69
+ PropertyInfo as PropertyInfo,
70
+ transform as transform,
71
+ async_transform as async_transform,
72
+ maybe_transform as maybe_transform,
73
+ async_maybe_transform as async_maybe_transform,
74
+ )
75
+ from ._reflection import (
76
+ function_has_argument as function_has_argument,
77
+ assert_signatures_in_sync as assert_signatures_in_sync,
78
+ )
79
+ from ._datetime_parse import parse_date as parse_date, parse_datetime as parse_datetime