forked from microsoft/autogen
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_function_utils.py
409 lines (320 loc) · 14 KB
/
test_function_utils.py
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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
import asyncio
import inspect
import unittest.mock
from typing import Any, Dict, List, Literal, Optional, Tuple
import pytest
from pydantic import BaseModel, Field
from typing_extensions import Annotated
from autogen._pydantic import PYDANTIC_V1, model_dump
from autogen.function_utils import (
get_default_values,
get_function_schema,
get_load_param_if_needed_function,
get_missing_annotations,
get_param_annotations,
get_parameter_json_schema,
get_parameters,
get_required_params,
get_typed_annotation,
get_typed_return_annotation,
get_typed_signature,
load_basemodels_if_needed,
serialize_to_str,
)
def f(a: Annotated[str, "Parameter a"], b: int = 2, c: Annotated[float, "Parameter c"] = 0.1, *, d): # type: ignore[no-untyped-def]
pass
def g( # type: ignore[empty-body]
a: Annotated[str, "Parameter a"],
b: int = 2,
c: Annotated[float, "Parameter c"] = 0.1,
*,
d: Dict[str, Tuple[Optional[int], List[float]]],
) -> str:
pass
async def a_g( # type: ignore[empty-body]
a: Annotated[str, "Parameter a"],
b: int = 2,
c: Annotated[float, "Parameter c"] = 0.1,
*,
d: Dict[str, Tuple[Optional[int], List[float]]],
) -> str:
pass
def test_get_typed_annotation() -> None:
globalns = getattr(f, "__globals__", {})
assert get_typed_annotation(str, globalns) == str
assert get_typed_annotation("float", globalns) == float
def test_get_typed_signature() -> None:
assert get_typed_signature(f).parameters == inspect.signature(f).parameters
assert get_typed_signature(g).parameters == inspect.signature(g).parameters
def test_get_typed_return_annotation() -> None:
assert get_typed_return_annotation(f) is None
assert get_typed_return_annotation(g) == str
def test_get_parameter_json_schema() -> None:
assert get_parameter_json_schema("c", str, {}) == {"type": "string", "description": "c"}
assert get_parameter_json_schema("c", str, {"c": "ccc"}) == {"type": "string", "description": "c", "default": "ccc"}
assert get_parameter_json_schema("a", Annotated[str, "parameter a"], {}) == {
"type": "string",
"description": "parameter a",
}
assert get_parameter_json_schema("a", Annotated[str, "parameter a"], {"a": "3.14"}) == {
"type": "string",
"description": "parameter a",
"default": "3.14",
}
class B(BaseModel):
b: float
c: str
expected: Dict[str, Any] = {
"description": "b",
"properties": {"b": {"title": "B", "type": "number"}, "c": {"title": "C", "type": "string"}},
"required": ["b", "c"],
"title": "B",
"type": "object",
}
assert get_parameter_json_schema("b", B, {}) == expected
expected["default"] = B(b=1.2, c="3.4")
assert get_parameter_json_schema("b", B, {"b": B(b=1.2, c="3.4")}) == expected
def test_get_required_params() -> None:
assert get_required_params(inspect.signature(f)) == ["a", "d"]
assert get_required_params(inspect.signature(g)) == ["a", "d"]
def test_get_default_values() -> None:
assert get_default_values(inspect.signature(f)) == {"b": 2, "c": 0.1}
assert get_default_values(inspect.signature(g)) == {"b": 2, "c": 0.1}
def test_get_param_annotations() -> None:
def f(a: Annotated[str, "Parameter a"], b=1, c: Annotated[float, "Parameter c"] = 1.0): # type: ignore[no-untyped-def]
pass
expected = {"a": Annotated[str, "Parameter a"], "c": Annotated[float, "Parameter c"]}
typed_signature = get_typed_signature(f)
param_annotations = get_param_annotations(typed_signature)
assert param_annotations == expected, param_annotations
def test_get_missing_annotations() -> None:
def _f1(a: str, b=2): # type: ignore[no-untyped-def]
pass
missing, unannotated_with_default = get_missing_annotations(get_typed_signature(_f1), ["a"])
assert missing == set()
assert unannotated_with_default == {"b"}
def _f2(a: str, b) -> str: # type: ignore[empty-body,no-untyped-def]
"ok"
missing, unannotated_with_default = get_missing_annotations(get_typed_signature(_f2), ["a", "b"])
assert missing == {"b"}
assert unannotated_with_default == set()
def _f3() -> None:
pass
missing, unannotated_with_default = get_missing_annotations(get_typed_signature(_f3), [])
assert missing == set()
assert unannotated_with_default == set()
def test_get_parameters() -> None:
def f(a: Annotated[str, "Parameter a"], b=1, c: Annotated[float, "Parameter c"] = 1.0): # type: ignore[no-untyped-def]
pass
typed_signature = get_typed_signature(f)
param_annotations = get_param_annotations(typed_signature)
required = get_required_params(typed_signature)
default_values = get_default_values(typed_signature)
expected = {
"type": "object",
"properties": {
"a": {"type": "string", "description": "Parameter a"},
"c": {"type": "number", "description": "Parameter c", "default": 1.0},
},
"required": ["a"],
}
actual = model_dump(get_parameters(required, param_annotations, default_values))
assert actual == expected, actual
def test_get_function_schema_no_return_type() -> None:
def f(a: Annotated[str, "Parameter a"], b: int, c: float = 0.1): # type: ignore[no-untyped-def]
pass
expected = (
"The return type of the function 'f' is not annotated. Although annotating it is "
+ "optional, the function should return either a string, a subclass of 'pydantic.BaseModel'."
)
with unittest.mock.patch("autogen.function_utils.logger.warning") as mock_logger_warning:
get_function_schema(f, description="function g")
mock_logger_warning.assert_called_once_with(expected)
def test_get_function_schema_unannotated_with_default() -> None:
with unittest.mock.patch("autogen.function_utils.logger.warning") as mock_logger_warning:
def f( # type: ignore[no-untyped-def]
a: Annotated[str, "Parameter a"], b=2, c: Annotated[float, "Parameter c"] = 0.1, d="whatever", e=None
) -> str:
return "ok"
get_function_schema(f, description="function f")
mock_logger_warning.assert_called_once_with(
"The following parameters of the function 'f' with default values are not annotated: 'b', 'd', 'e'."
)
def test_get_function_schema_missing() -> None:
def f(a: Annotated[str, "Parameter a"], b, c: Annotated[float, "Parameter c"] = 0.1) -> float: # type: ignore[no-untyped-def, empty-body]
pass
expected = (
"All parameters of the function 'f' without default values must be annotated. "
+ "The annotations are missing for the following parameters: 'b'"
)
with pytest.raises(TypeError) as e:
get_function_schema(f, description="function f")
assert str(e.value) == expected, e.value
def test_get_function_schema() -> None:
expected_v2 = {
"type": "function",
"function": {
"description": "function g",
"name": "fancy name for g",
"parameters": {
"type": "object",
"properties": {
"a": {"type": "string", "description": "Parameter a"},
"b": {"type": "integer", "description": "b", "default": 2},
"c": {"type": "number", "description": "Parameter c", "default": 0.1},
"d": {
"additionalProperties": {
"maxItems": 2,
"minItems": 2,
"prefixItems": [
{"anyOf": [{"type": "integer"}, {"type": "null"}]},
{"items": {"type": "number"}, "type": "array"},
],
"type": "array",
},
"type": "object",
"description": "d",
},
},
"required": ["a", "d"],
},
},
}
# the difference is that the v1 version does not handle Union types (Optional is Union[T, None])
expected_v1 = {
"type": "function",
"function": {
"description": "function g",
"name": "fancy name for g",
"parameters": {
"type": "object",
"properties": {
"a": {"type": "string", "description": "Parameter a"},
"b": {"type": "integer", "description": "b", "default": 2},
"c": {"type": "number", "description": "Parameter c", "default": 0.1},
"d": {
"type": "object",
"additionalProperties": {
"type": "array",
"minItems": 2,
"maxItems": 2,
"items": [{"type": "integer"}, {"type": "array", "items": {"type": "number"}}],
},
"description": "d",
},
},
"required": ["a", "d"],
},
},
}
actual = get_function_schema(g, description="function g", name="fancy name for g")
if PYDANTIC_V1:
assert actual == expected_v1, actual
else:
assert actual == expected_v2, actual
actual = get_function_schema(a_g, description="function g", name="fancy name for g")
if PYDANTIC_V1:
assert actual == expected_v1, actual
else:
assert actual == expected_v2, actual
CurrencySymbol = Literal["USD", "EUR"]
class Currency(BaseModel):
currency: Annotated[CurrencySymbol, Field(..., description="Currency code")]
amount: Annotated[float, Field(100.0, description="Amount of money in the currency")]
def test_get_function_schema_pydantic() -> None:
def currency_calculator( # type: ignore[empty-body]
base: Annotated[Currency, "Base currency: amount and currency symbol"],
quote_currency: Annotated[CurrencySymbol, "Quote currency symbol (default: 'EUR')"] = "EUR",
) -> Currency:
pass
expected = {
"type": "function",
"function": {
"description": "Currency exchange calculator.",
"name": "currency_calculator",
"parameters": {
"type": "object",
"properties": {
"base": {
"properties": {
"currency": {
"description": "Currency code",
"enum": ["USD", "EUR"],
"title": "Currency",
"type": "string",
},
"amount": {
"default": 100.0,
"description": "Amount of money in the currency",
"title": "Amount",
"type": "number",
},
},
"required": ["currency"],
"title": "Currency",
"type": "object",
"description": "Base currency: amount and currency symbol",
},
"quote_currency": {
"enum": ["USD", "EUR"],
"type": "string",
"default": "EUR",
"description": "Quote currency symbol (default: 'EUR')",
},
},
"required": ["base"],
},
},
}
actual = get_function_schema(
currency_calculator, description="Currency exchange calculator.", name="currency_calculator"
)
assert actual == expected, actual
def test_get_load_param_if_needed_function() -> None:
assert get_load_param_if_needed_function(CurrencySymbol) is None
assert get_load_param_if_needed_function(Currency)({"currency": "USD", "amount": 123.45}, Currency) == Currency( # type: ignore[misc]
currency="USD", amount=123.45
)
f = get_load_param_if_needed_function(Annotated[Currency, "amount and a symbol of a currency"])
actual = f({"currency": "USD", "amount": 123.45}, Currency) # type: ignore[misc]
expected = Currency(currency="USD", amount=123.45)
assert actual == expected, actual
def test_load_basemodels_if_needed_sync() -> None:
@load_basemodels_if_needed
def f(
base: Annotated[Currency, "Base currency"],
quote_currency: Annotated[CurrencySymbol, "Quote currency"] = "EUR",
) -> Tuple[Currency, CurrencySymbol]:
return base, quote_currency
assert not inspect.iscoroutinefunction(f)
actual = f(base={"currency": "USD", "amount": 123.45}, quote_currency="EUR")
assert isinstance(actual[0], Currency)
assert actual[0].amount == 123.45
assert actual[0].currency == "USD"
assert actual[1] == "EUR"
@pytest.mark.asyncio
async def test_load_basemodels_if_needed_async() -> None:
@load_basemodels_if_needed
async def f(
base: Annotated[Currency, "Base currency"],
quote_currency: Annotated[CurrencySymbol, "Quote currency"] = "EUR",
) -> Tuple[Currency, CurrencySymbol]:
return base, quote_currency
assert inspect.iscoroutinefunction(f)
actual = await f(base={"currency": "USD", "amount": 123.45}, quote_currency="EUR")
assert isinstance(actual[0], Currency)
assert actual[0].amount == 123.45
assert actual[0].currency == "USD"
assert actual[1] == "EUR"
def test_serialize_to_str_with_nonascii() -> None:
assert serialize_to_str("中文") == "中文"
def test_serialize_to_json() -> None:
assert serialize_to_str("abc") == "abc"
assert serialize_to_str(123) == "123"
assert serialize_to_str([123, 456]) == "[123, 456]"
assert serialize_to_str({"a": 1, "b": 2.3}) == '{"a": 1, "b": 2.3}'
class A(BaseModel):
a: int
b: float
c: str
assert serialize_to_str(A(a=1, b=2.3, c="abc")) == '{"a":1,"b":2.3,"c":"abc"}'