1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
|
# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import inspect
import types as typing_types
from typing import Any, Callable, Literal, Union, _GenericAlias, get_args, get_origin
import pydantic
from . import types
_py_builtin_type_to_schema_type = {
str: 'STRING',
int: 'INTEGER',
float: 'NUMBER',
bool: 'BOOLEAN',
list: 'ARRAY',
dict: 'OBJECT',
}
def _is_builtin_primitive_or_compound(
annotation: inspect.Parameter.annotation,
) -> bool:
return annotation in _py_builtin_type_to_schema_type.keys()
def _raise_for_any_of_if_mldev(schema: types.Schema):
if schema.any_of:
raise ValueError(
'AnyOf is not supported in function declaration schema for Google AI.'
)
def _raise_for_default_if_mldev(schema: types.Schema):
if schema.default is not None:
raise ValueError(
'Default value is not supported in function declaration schema for'
' Google AI.'
)
def _raise_for_nullable_if_mldev(schema: types.Schema):
if schema.nullable:
raise ValueError(
'Nullable is not supported in function declaration schema for'
' Google AI.'
)
def _raise_if_schema_unsupported(variant: str, schema: types.Schema):
if not variant == 'VERTEX_AI':
_raise_for_any_of_if_mldev(schema)
_raise_for_default_if_mldev(schema)
_raise_for_nullable_if_mldev(schema)
def _is_default_value_compatible(
default_value: Any, annotation: inspect.Parameter.annotation
) -> bool:
# None type is expected to be handled external to this function
if _is_builtin_primitive_or_compound(annotation):
return isinstance(default_value, annotation)
if (
isinstance(annotation, _GenericAlias)
or isinstance(annotation, typing_types.GenericAlias)
or isinstance(annotation, typing_types.UnionType)
):
origin = get_origin(annotation)
if origin in (Union, typing_types.UnionType):
return any(
_is_default_value_compatible(default_value, arg)
for arg in get_args(annotation)
)
if origin is dict:
return isinstance(default_value, dict)
if origin is list:
if not isinstance(default_value, list):
return False
# most tricky case, element in list is union type
# need to apply any logic within all
# see test case test_generic_alias_complex_array_with_default_value
# a: typing.List[int | str | float | bool]
# default_value: [1, 'a', 1.1, True]
return all(
any(
_is_default_value_compatible(item, arg)
for arg in get_args(annotation)
)
for item in default_value
)
if origin is Literal:
return default_value in get_args(annotation)
# return False for any other unrecognized annotation
# let caller handle the raise
return False
def _parse_schema_from_parameter(
variant: str, param: inspect.Parameter, func_name: str
) -> types.Schema:
"""parse schema from parameter.
from the simplest case to the most complex case.
"""
schema = types.Schema()
default_value_error_msg = (
f'Default value {param.default} of parameter {param} of function'
f' {func_name} is not compatible with the parameter annotation'
f' {param.annotation}.'
)
if _is_builtin_primitive_or_compound(param.annotation):
if param.default is not inspect.Parameter.empty:
if not _is_default_value_compatible(param.default, param.annotation):
raise ValueError(default_value_error_msg)
schema.default = param.default
schema.type = _py_builtin_type_to_schema_type[param.annotation]
_raise_if_schema_unsupported(variant, schema)
return schema
if (
isinstance(param.annotation, typing_types.UnionType)
# only parse simple UnionType, example int | str | float | bool
# complex types.UnionType will be invoked in raise branch
and all(
(_is_builtin_primitive_or_compound(arg) or arg is type(None))
for arg in get_args(param.annotation)
)
):
schema.type = 'OBJECT'
schema.any_of = []
unique_types = set()
for arg in get_args(param.annotation):
if arg.__name__ == 'NoneType': # Optional type
schema.nullable = True
continue
schema_in_any_of = _parse_schema_from_parameter(
variant,
inspect.Parameter(
'item', inspect.Parameter.POSITIONAL_OR_KEYWORD, annotation=arg
),
func_name,
)
if (
schema_in_any_of.model_dump_json(exclude_none=True)
not in unique_types
):
schema.any_of.append(schema_in_any_of)
unique_types.add(schema_in_any_of.model_dump_json(exclude_none=True))
if len(schema.any_of) == 1: # param: list | None -> Array
schema.type = schema.any_of[0].type
schema.any_of = None
if (
param.default is not inspect.Parameter.empty
and param.default is not None
):
if not _is_default_value_compatible(param.default, param.annotation):
raise ValueError(default_value_error_msg)
schema.default = param.default
_raise_if_schema_unsupported(variant, schema)
return schema
if isinstance(param.annotation, _GenericAlias) or isinstance(
param.annotation, typing_types.GenericAlias
):
origin = get_origin(param.annotation)
args = get_args(param.annotation)
if origin is dict:
schema.type = 'OBJECT'
if param.default is not inspect.Parameter.empty:
if not _is_default_value_compatible(param.default, param.annotation):
raise ValueError(default_value_error_msg)
schema.default = param.default
_raise_if_schema_unsupported(variant, schema)
return schema
if origin is Literal:
if not all(isinstance(arg, str) for arg in args):
raise ValueError(
f'Literal type {param.annotation} must be a list of strings.'
)
schema.type = 'STRING'
schema.enum = list(args)
if param.default is not inspect.Parameter.empty:
if not _is_default_value_compatible(param.default, param.annotation):
raise ValueError(default_value_error_msg)
schema.default = param.default
_raise_if_schema_unsupported(variant, schema)
return schema
if origin is list:
schema.type = 'ARRAY'
schema.items = _parse_schema_from_parameter(
variant,
inspect.Parameter(
'item',
inspect.Parameter.POSITIONAL_OR_KEYWORD,
annotation=args[0],
),
func_name,
)
if param.default is not inspect.Parameter.empty:
if not _is_default_value_compatible(param.default, param.annotation):
raise ValueError(default_value_error_msg)
schema.default = param.default
_raise_if_schema_unsupported(variant, schema)
return schema
if origin is Union:
schema.any_of = []
schema.type = 'OBJECT'
unique_types = set()
for arg in args:
if arg.__name__ == 'NoneType': # Optional type
schema.nullable = True
continue
schema_in_any_of = _parse_schema_from_parameter(
variant,
inspect.Parameter(
'item',
inspect.Parameter.POSITIONAL_OR_KEYWORD,
annotation=arg,
),
func_name,
)
if (
schema_in_any_of.model_dump_json(exclude_none=True)
not in unique_types
):
schema.any_of.append(schema_in_any_of)
unique_types.add(schema_in_any_of.model_dump_json(exclude_none=True))
if len(schema.any_of) == 1: # param: Union[List, None] -> Array
schema.type = schema.any_of[0].type
schema.any_of = None
if (
param.default is not None
and param.default is not inspect.Parameter.empty
):
if not _is_default_value_compatible(param.default, param.annotation):
raise ValueError(default_value_error_msg)
schema.default = param.default
_raise_if_schema_unsupported(variant, schema)
return schema
# all other generic alias will be invoked in raise branch
if (
inspect.isclass(param.annotation)
# for user defined class, we only support pydantic model
and issubclass(param.annotation, pydantic.BaseModel)
):
if (
param.default is not inspect.Parameter.empty
and param.default is not None
):
schema.default = param.default
schema.type = 'OBJECT'
schema.properties = {}
for field_name, field_info in param.annotation.model_fields.items():
schema.properties[field_name] = _parse_schema_from_parameter(
variant,
inspect.Parameter(
field_name,
inspect.Parameter.POSITIONAL_OR_KEYWORD,
annotation=field_info.annotation,
),
func_name,
)
_raise_if_schema_unsupported(variant, schema)
return schema
raise ValueError(
f'Failed to parse the parameter {param} of function {func_name} for'
' automatic function calling.Automatic function calling works best with'
' simpler function signature schema,consider manually parse your'
f' function declaration for function {func_name}.'
)
def _get_required_fields(schema: types.Schema) -> list[str]:
if not schema.properties:
return
return [
field_name
for field_name, field_schema in schema.properties.items()
if not field_schema.nullable and field_schema.default is None
]
|