google-genai 0.0.1__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.
- google/genai/__init__.py +20 -0
- google/genai/_api_client.py +467 -0
- google/genai/_automatic_function_calling_util.py +341 -0
- google/genai/_common.py +256 -0
- google/genai/_extra_utils.py +295 -0
- google/genai/_replay_api_client.py +478 -0
- google/genai/_test_api_client.py +149 -0
- google/genai/_transformers.py +438 -0
- google/genai/batches.py +1041 -0
- google/genai/caches.py +1830 -0
- google/genai/chats.py +184 -0
- google/genai/client.py +277 -0
- google/genai/errors.py +110 -0
- google/genai/files.py +1211 -0
- google/genai/live.py +629 -0
- google/genai/models.py +5307 -0
- google/genai/pagers.py +245 -0
- google/genai/tunings.py +1366 -0
- google/genai/types.py +7639 -0
- google_genai-0.0.1.dist-info/LICENSE +202 -0
- google_genai-0.0.1.dist-info/METADATA +763 -0
- google_genai-0.0.1.dist-info/RECORD +24 -0
- google_genai-0.0.1.dist-info/WHEEL +5 -0
- google_genai-0.0.1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,295 @@
|
|
1
|
+
# Copyright 2024 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
|
+
"""Extra utils depending on types that are shared between sync and async modules.
|
17
|
+
"""
|
18
|
+
|
19
|
+
import inspect
|
20
|
+
import logging
|
21
|
+
from typing import Any, Callable, Dict, get_args, get_origin, Optional, types as typing_types, Union
|
22
|
+
|
23
|
+
import pydantic
|
24
|
+
|
25
|
+
from . import _common
|
26
|
+
from . import errors
|
27
|
+
from . import types
|
28
|
+
|
29
|
+
|
30
|
+
_DEFAULT_MAX_REMOTE_CALLS_AFC = 10
|
31
|
+
|
32
|
+
|
33
|
+
def format_destination(
|
34
|
+
src: str,
|
35
|
+
config: Optional[types.CreateBatchJobConfigOrDict] = None,
|
36
|
+
) -> types.CreateBatchJobConfig:
|
37
|
+
"""Formats the destination uri based on the source uri."""
|
38
|
+
config = (
|
39
|
+
types._CreateBatchJobParameters(config=config).config
|
40
|
+
or types.CreateBatchJobConfig()
|
41
|
+
)
|
42
|
+
|
43
|
+
unique_name = None
|
44
|
+
if not config.display_name:
|
45
|
+
unique_name = _common.timestamped_unique_name()
|
46
|
+
config.display_name = f'genai_batch_job_{unique_name}'
|
47
|
+
|
48
|
+
if not config.dest:
|
49
|
+
if src.startswith('gs://') and src.endswith('.jsonl'):
|
50
|
+
# If source uri is "gs://bucket/path/to/src.jsonl", then the destination
|
51
|
+
# uri prefix will be "gs://bucket/path/to/src/dest".
|
52
|
+
config.dest = f'{src[:-6]}/dest'
|
53
|
+
elif src.startswith('bq://'):
|
54
|
+
# If source uri is "bq://project.dataset.src", then the destination
|
55
|
+
# uri will be "bq://project.dataset.src_dest_TIMESTAMP_UUID".
|
56
|
+
unique_name = unique_name or _common.timestamped_unique_name()
|
57
|
+
config.dest = f'{src}_dest_{unique_name}'
|
58
|
+
else:
|
59
|
+
raise ValueError(f'Unsupported source: {src}')
|
60
|
+
return config
|
61
|
+
|
62
|
+
|
63
|
+
def get_function_map(
|
64
|
+
config: Optional[types.GenerateContentConfigOrDict] = None,
|
65
|
+
) -> dict[str, object]:
|
66
|
+
"""Returns a function map from the config."""
|
67
|
+
config_model = (
|
68
|
+
types.GenerateContentConfig(**config)
|
69
|
+
if config and isinstance(config, dict)
|
70
|
+
else config
|
71
|
+
)
|
72
|
+
function_map = {}
|
73
|
+
if not config_model:
|
74
|
+
return function_map
|
75
|
+
if config_model.tools:
|
76
|
+
for tool in config_model.tools:
|
77
|
+
if callable(tool):
|
78
|
+
if inspect.iscoroutinefunction(tool):
|
79
|
+
raise errors.UnsupportedFunctionError(
|
80
|
+
f'Function {tool.__name__} is a coroutine function, which is not'
|
81
|
+
' supported for automatic function calling. Please manually invoke'
|
82
|
+
f' {tool.__name__} to get the function response.'
|
83
|
+
)
|
84
|
+
function_map[tool.__name__] = tool
|
85
|
+
return function_map
|
86
|
+
|
87
|
+
|
88
|
+
def convert_number_values_for_function_call_args(
|
89
|
+
args: Union[dict[str, object], list[object], object],
|
90
|
+
) -> Union[dict[str, object], list[object], object]:
|
91
|
+
"""Converts float values with no decimal to integers."""
|
92
|
+
if isinstance(args, float) and args.is_integer():
|
93
|
+
return int(args)
|
94
|
+
if isinstance(args, dict):
|
95
|
+
return {
|
96
|
+
key: convert_number_values_for_function_call_args(value)
|
97
|
+
for key, value in args.items()
|
98
|
+
}
|
99
|
+
if isinstance(args, list):
|
100
|
+
return [
|
101
|
+
convert_number_values_for_function_call_args(value) for value in args
|
102
|
+
]
|
103
|
+
return args
|
104
|
+
|
105
|
+
|
106
|
+
def _is_annotation_pydantic_model(annotation: Any) -> bool:
|
107
|
+
return inspect.isclass(annotation) and issubclass(
|
108
|
+
annotation, pydantic.BaseModel
|
109
|
+
)
|
110
|
+
|
111
|
+
|
112
|
+
def convert_if_exist_pydantic_model(
|
113
|
+
value: Any, annotation: Any, param_name: str, func_name: str
|
114
|
+
) -> Any:
|
115
|
+
if isinstance(value, dict) and _is_annotation_pydantic_model(annotation):
|
116
|
+
try:
|
117
|
+
return annotation(**value)
|
118
|
+
except pydantic.ValidationError as e:
|
119
|
+
raise errors.UnkownFunctionCallArgumentError(
|
120
|
+
f'Failed to parse parameter {param_name} for function'
|
121
|
+
f' {func_name} from function call part because function call argument'
|
122
|
+
f' value {value} is not compatible with parameter annotation'
|
123
|
+
f' {annotation}, due to error {e}'
|
124
|
+
)
|
125
|
+
if isinstance(value, list) and get_origin(annotation) == list:
|
126
|
+
item_type = get_args(annotation)[0]
|
127
|
+
return [
|
128
|
+
convert_if_exist_pydantic_model(item, item_type, param_name, func_name)
|
129
|
+
for item in value
|
130
|
+
]
|
131
|
+
if isinstance(value, dict) and get_origin(annotation) == dict:
|
132
|
+
_, value_type = get_args(annotation)
|
133
|
+
return {
|
134
|
+
k: convert_if_exist_pydantic_model(v, value_type, param_name, func_name)
|
135
|
+
for k, v in value.items()
|
136
|
+
}
|
137
|
+
# example 1: typing.Union[int, float]
|
138
|
+
# example 2: int | float equivalent to typing.types.UnionType[int, float]
|
139
|
+
if get_origin(annotation) in (Union, typing_types.UnionType):
|
140
|
+
for arg in get_args(annotation):
|
141
|
+
if isinstance(value, arg) or (
|
142
|
+
isinstance(value, dict) and _is_annotation_pydantic_model(arg)
|
143
|
+
):
|
144
|
+
try:
|
145
|
+
return convert_if_exist_pydantic_model(
|
146
|
+
value, arg, param_name, func_name
|
147
|
+
)
|
148
|
+
# do not raise here because there could be multiple pydantic model types
|
149
|
+
# in the union type.
|
150
|
+
except pydantic.ValidationError:
|
151
|
+
continue
|
152
|
+
# if none of the union type is matched, raise error
|
153
|
+
raise errors.UnkownFunctionCallArgumentError(
|
154
|
+
f'Failed to parse parameter {param_name} for function'
|
155
|
+
f' {func_name} from function call part because function call argument'
|
156
|
+
f' value {value} cannot be converted to parameter annotation'
|
157
|
+
f' {annotation}.'
|
158
|
+
)
|
159
|
+
# the only exception for value and annotation type to be different is int and
|
160
|
+
# float. see convert_number_values_for_function_call_args function for context
|
161
|
+
if isinstance(value, int) and annotation is float:
|
162
|
+
return value
|
163
|
+
if not isinstance(value, annotation):
|
164
|
+
raise errors.UnkownFunctionCallArgumentError(
|
165
|
+
f'Failed to parse parameter {param_name} for function {func_name} from'
|
166
|
+
f' function call part because function call argument value {value} is'
|
167
|
+
f' not compatible with parameter annotation {annotation}.'
|
168
|
+
)
|
169
|
+
return value
|
170
|
+
|
171
|
+
|
172
|
+
def invoke_function_from_dict_args(
|
173
|
+
args: Dict[str, Any], function_to_invoke: Callable
|
174
|
+
) -> Any:
|
175
|
+
signature = inspect.signature(function_to_invoke)
|
176
|
+
func_name = function_to_invoke.__name__
|
177
|
+
converted_args = {}
|
178
|
+
for param_name, param in signature.parameters.items():
|
179
|
+
if param_name in args:
|
180
|
+
converted_args[param_name] = convert_if_exist_pydantic_model(
|
181
|
+
args[param_name],
|
182
|
+
param.annotation,
|
183
|
+
param_name,
|
184
|
+
func_name,
|
185
|
+
)
|
186
|
+
try:
|
187
|
+
return function_to_invoke(**converted_args)
|
188
|
+
except Exception as e:
|
189
|
+
raise errors.FunctionInvocationError(
|
190
|
+
f'Failed to invoke function {func_name} with converted arguments'
|
191
|
+
f' {converted_args} from model returned function call argument'
|
192
|
+
f' {args} because of error {e}'
|
193
|
+
)
|
194
|
+
|
195
|
+
|
196
|
+
def get_function_response_parts(
|
197
|
+
response: types.GenerateContentResponse,
|
198
|
+
function_map: dict[str, object],
|
199
|
+
) -> list[types.Part]:
|
200
|
+
"""Returns the function response parts from the response."""
|
201
|
+
func_response_parts = []
|
202
|
+
for part in response.candidates[0].content.parts:
|
203
|
+
if not part.function_call:
|
204
|
+
continue
|
205
|
+
func_name = part.function_call.name
|
206
|
+
func = function_map[func_name]
|
207
|
+
args = convert_number_values_for_function_call_args(part.function_call.args)
|
208
|
+
try:
|
209
|
+
response = {'result': invoke_function_from_dict_args(args, func)}
|
210
|
+
except Exception as e: # pylint: disable=broad-except
|
211
|
+
response = {'error': str(e)}
|
212
|
+
func_response = types.Part.from_function_response(func_name, response)
|
213
|
+
|
214
|
+
func_response_parts.append(func_response)
|
215
|
+
return func_response_parts
|
216
|
+
|
217
|
+
|
218
|
+
def should_disable_afc(
|
219
|
+
config: Optional[types.GenerateContentConfigOrDict] = None,
|
220
|
+
) -> bool:
|
221
|
+
"""Returns whether automatic function calling is enabled."""
|
222
|
+
config_model = (
|
223
|
+
types.GenerateContentConfig(**config)
|
224
|
+
if config and isinstance(config, dict)
|
225
|
+
else config
|
226
|
+
)
|
227
|
+
|
228
|
+
# If max_remote_calls is less or equal to 0, warn and disable AFC.
|
229
|
+
if (
|
230
|
+
config_model
|
231
|
+
and config_model.automatic_function_calling
|
232
|
+
and config_model.automatic_function_calling.maximum_remote_calls
|
233
|
+
is not None
|
234
|
+
and int(config_model.automatic_function_calling.maximum_remote_calls)
|
235
|
+
<= 0
|
236
|
+
):
|
237
|
+
logging.warning(
|
238
|
+
'max_remote_calls in automatic_function_calling_config'
|
239
|
+
f' {config_model.automatic_function_calling.maximum_remote_calls} is'
|
240
|
+
' less than or equal to 0. Disabling automatic function calling.'
|
241
|
+
' Please set max_remote_calls to a positive integer.'
|
242
|
+
)
|
243
|
+
return True
|
244
|
+
|
245
|
+
# Default to enable AFC if not specified.
|
246
|
+
if (
|
247
|
+
not config_model
|
248
|
+
or not config_model.automatic_function_calling
|
249
|
+
or config_model.automatic_function_calling.disable is None
|
250
|
+
):
|
251
|
+
return False
|
252
|
+
|
253
|
+
if (
|
254
|
+
config_model.automatic_function_calling.disable
|
255
|
+
and config_model.automatic_function_calling.maximum_remote_calls
|
256
|
+
is not None
|
257
|
+
and int(config_model.automatic_function_calling.maximum_remote_calls) > 0
|
258
|
+
):
|
259
|
+
logging.warning(
|
260
|
+
'`automatic_function_calling.disable` is set to `True`. But'
|
261
|
+
' `automatic_function_calling.maximum_remote_calls` is set to be a'
|
262
|
+
' positive number'
|
263
|
+
f' {config_model.automatic_function_calling.maximum_remote_calls}.'
|
264
|
+
' Disabling automatic function calling. If you want to enable'
|
265
|
+
' automatic function calling, please set'
|
266
|
+
' `automatic_function_calling.disable` to `False` or leave it unset,'
|
267
|
+
' and set `automatic_function_calling.maximum_remote_calls` to a'
|
268
|
+
' positive integer or leave'
|
269
|
+
' `automatic_function_calling.maximum_remote_calls` unset.'
|
270
|
+
)
|
271
|
+
|
272
|
+
return config_model.automatic_function_calling.disable
|
273
|
+
|
274
|
+
|
275
|
+
def get_max_remote_calls_afc(
|
276
|
+
config: Optional[types.GenerateContentConfigOrDict] = None,
|
277
|
+
) -> int:
|
278
|
+
"""Returns the remaining remote calls for automatic function calling."""
|
279
|
+
if should_disable_afc(config):
|
280
|
+
raise ValueError(
|
281
|
+
'automatic function calling is not enabled, but SDK is trying to get'
|
282
|
+
' max remote calls.'
|
283
|
+
)
|
284
|
+
config_model = (
|
285
|
+
types.GenerateContentConfig(**config)
|
286
|
+
if config and isinstance(config, dict)
|
287
|
+
else config
|
288
|
+
)
|
289
|
+
if (
|
290
|
+
not config_model
|
291
|
+
or not config_model.automatic_function_calling
|
292
|
+
or config_model.automatic_function_calling.maximum_remote_calls is None
|
293
|
+
):
|
294
|
+
return _DEFAULT_MAX_REMOTE_CALLS_AFC
|
295
|
+
return int(config_model.automatic_function_calling.maximum_remote_calls)
|