Skip to content

Commit 93aad61

Browse files
GWealecopybara-github
authored andcommitted
fix: Safely handle FunctionDeclaration without a required attribute
Update `_function_declaration_to_tool_param` to use `getattr` when accessing the `required` field within `function_declaration.parameters`. This prevents `AttributeError` when a `FunctionDeclaration`'s parameters schema does not include a `required` attribute Close #2891 Co-authored-by: George Weale <gweale@google.com> PiperOrigin-RevId: 830225582
1 parent 2882995 commit 93aad61

File tree

2 files changed

+41
-7
lines changed

2 files changed

+41
-7
lines changed

src/google/adk/models/lite_llm.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -525,13 +525,13 @@ def _function_declaration_to_tool_param(
525525
},
526526
}
527527

528-
if (
529-
function_declaration.parameters
530-
and function_declaration.parameters.required
531-
):
532-
tool_params["function"]["parameters"][
533-
"required"
534-
] = function_declaration.parameters.required
528+
required_fields = (
529+
getattr(function_declaration.parameters, "required", None)
530+
if function_declaration.parameters
531+
else None
532+
)
533+
if required_fields:
534+
tool_params["function"]["parameters"]["required"] = required_fields
535535

536536
return tool_params
537537

tests/unittests/models/test_litellm.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1066,6 +1066,40 @@ def test_function_declaration_to_tool_param(
10661066
)
10671067

10681068

1069+
def test_function_declaration_to_tool_param_without_required_attribute():
1070+
"""Ensure tools without a required field attribute don't raise errors."""
1071+
1072+
class SchemaWithoutRequired:
1073+
"""Mimics a Schema object that lacks the required attribute."""
1074+
1075+
def __init__(self):
1076+
self.properties = {
1077+
"optional_arg": types.Schema(type=types.Type.STRING),
1078+
}
1079+
1080+
func_decl = types.FunctionDeclaration(
1081+
name="function_without_required_attr",
1082+
description="Function missing required attribute",
1083+
)
1084+
func_decl.parameters = SchemaWithoutRequired()
1085+
1086+
expected = {
1087+
"type": "function",
1088+
"function": {
1089+
"name": "function_without_required_attr",
1090+
"description": "Function missing required attribute",
1091+
"parameters": {
1092+
"type": "object",
1093+
"properties": {
1094+
"optional_arg": {"type": "string"},
1095+
},
1096+
},
1097+
},
1098+
}
1099+
1100+
assert _function_declaration_to_tool_param(func_decl) == expected
1101+
1102+
10691103
def test_function_declaration_to_tool_param_with_parameters_json_schema():
10701104
"""Ensure function declarations using parameters_json_schema are handled.
10711105

0 commit comments

Comments
 (0)