From 93aad611983dc1daf415d3a73105db45bbdd1988 Mon Sep 17 00:00:00 2001 From: George Weale Date: Sun, 9 Nov 2025 19:06:17 -0800 Subject: [PATCH] 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 PiperOrigin-RevId: 830225582 --- src/google/adk/models/lite_llm.py | 14 +++++------ tests/unittests/models/test_litellm.py | 34 ++++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 7 deletions(-) diff --git a/src/google/adk/models/lite_llm.py b/src/google/adk/models/lite_llm.py index 53ce9974..3ed9a6a4 100644 --- a/src/google/adk/models/lite_llm.py +++ b/src/google/adk/models/lite_llm.py @@ -525,13 +525,13 @@ def _function_declaration_to_tool_param( }, } - if ( - function_declaration.parameters - and function_declaration.parameters.required - ): - tool_params["function"]["parameters"][ - "required" - ] = function_declaration.parameters.required + required_fields = ( + getattr(function_declaration.parameters, "required", None) + if function_declaration.parameters + else None + ) + if required_fields: + tool_params["function"]["parameters"]["required"] = required_fields return tool_params diff --git a/tests/unittests/models/test_litellm.py b/tests/unittests/models/test_litellm.py index c18d12ee..566ee9c5 100644 --- a/tests/unittests/models/test_litellm.py +++ b/tests/unittests/models/test_litellm.py @@ -1066,6 +1066,40 @@ def test_function_declaration_to_tool_param( ) +def test_function_declaration_to_tool_param_without_required_attribute(): + """Ensure tools without a required field attribute don't raise errors.""" + + class SchemaWithoutRequired: + """Mimics a Schema object that lacks the required attribute.""" + + def __init__(self): + self.properties = { + "optional_arg": types.Schema(type=types.Type.STRING), + } + + func_decl = types.FunctionDeclaration( + name="function_without_required_attr", + description="Function missing required attribute", + ) + func_decl.parameters = SchemaWithoutRequired() + + expected = { + "type": "function", + "function": { + "name": "function_without_required_attr", + "description": "Function missing required attribute", + "parameters": { + "type": "object", + "properties": { + "optional_arg": {"type": "string"}, + }, + }, + }, + } + + assert _function_declaration_to_tool_param(func_decl) == expected + + def test_function_declaration_to_tool_param_with_parameters_json_schema(): """Ensure function declarations using parameters_json_schema are handled.