-
Notifications
You must be signed in to change notification settings - Fork 3k
fix: validate and coerce function tool argument types #4664
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
yuvrajangadsingh
wants to merge
13
commits into
google:main
Choose a base branch
from
yuvrajangadsingh:fix/enforce-arg-types-4612
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+306
−61
Open
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
63fab0c
fix: validate and coerce function tool argument types (#4612)
yuvrajangadsingh 3c29a55
refactor: narrow except clause and extract validation error helper
yuvrajangadsingh 420253b
refactor: apply Gemini review round 2 feedback
yuvrajangadsingh a93d71f
style: use __name__ for cleaner type names in error messages
yuvrajangadsingh d410954
style: use deferred string formatting in logger.warning
yuvrajangadsingh ab7cb7c
refactor: hoist Optional None check before Pydantic branch
yuvrajangadsingh 825f3b9
fix: handle Python 3.10+ union syntax (T | None) in Optional unwrap
yuvrajangadsingh 04c9cab
refactor: let TypeAdapter handle all types uniformly, skip framework …
yuvrajangadsingh 0024441
perf: cache TypeAdapter instances across tool invocations
yuvrajangadsingh 2c808f8
refactor: remove manual Optional unwrap, TypeAdapter handles it natively
yuvrajangadsingh f9ce14c
fix: handle unhashable types in TypeAdapter cache without skipping va…
yuvrajangadsingh ba3c4ea
refactor: split cache except into separate TypeError and KeyError han…
yuvrajangadsingh 3dcb209
Merge branch 'main' into fix/enforce-arg-types-4612
rohityan File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
213 changes: 213 additions & 0 deletions
213
tests/unittests/tools/test_function_tool_arg_validation.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,213 @@ | ||
| # Copyright 2026 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. | ||
|
|
||
| """Tests for FunctionTool argument type validation and coercion.""" | ||
|
|
||
| from enum import Enum | ||
| from typing import Optional | ||
| from unittest.mock import MagicMock | ||
|
|
||
| from google.adk.agents.invocation_context import InvocationContext | ||
| from google.adk.sessions.session import Session | ||
| from google.adk.tools.function_tool import FunctionTool | ||
| from google.adk.tools.tool_context import ToolContext | ||
| import pytest | ||
|
|
||
|
|
||
| class Color(Enum): | ||
| RED = "red" | ||
| GREEN = "green" | ||
| BLUE = "blue" | ||
|
|
||
|
|
||
| def int_func(num: int) -> int: | ||
| return num | ||
|
|
||
|
|
||
| def float_func(val: float) -> float: | ||
| return val | ||
|
|
||
|
|
||
| def bool_func(flag: bool) -> bool: | ||
| return flag | ||
|
|
||
|
|
||
| def enum_func(color: Color) -> str: | ||
| return color.value | ||
|
|
||
|
|
||
| def list_int_func(nums: list[int]) -> list[int]: | ||
| return nums | ||
|
|
||
|
|
||
| def optional_int_func(num: Optional[int] = None) -> Optional[int]: | ||
| return num | ||
|
|
||
|
|
||
| def multi_param_func(name: str, count: int, flag: bool) -> dict: | ||
| return {"name": name, "count": count, "flag": flag} | ||
|
|
||
|
|
||
| # --- _preprocess_args coercion tests --- | ||
|
|
||
|
|
||
| class TestArgCoercion: | ||
|
|
||
| def test_string_to_int(self): | ||
| tool = FunctionTool(int_func) | ||
| args, errors = tool._preprocess_args({"num": "42"}) | ||
| assert errors == [] | ||
| assert args["num"] == 42 | ||
| assert isinstance(args["num"], int) | ||
|
|
||
| def test_float_to_int(self): | ||
| """Pydantic lax mode truncates float to int.""" | ||
| tool = FunctionTool(int_func) | ||
| args, errors = tool._preprocess_args({"num": 3.0}) | ||
| assert errors == [] | ||
| assert args["num"] == 3 | ||
| assert isinstance(args["num"], int) | ||
|
|
||
| def test_string_to_float(self): | ||
| tool = FunctionTool(float_func) | ||
| args, errors = tool._preprocess_args({"val": "3.14"}) | ||
| assert errors == [] | ||
| assert abs(args["val"] - 3.14) < 1e-9 | ||
|
|
||
| def test_int_to_float(self): | ||
| tool = FunctionTool(float_func) | ||
| args, errors = tool._preprocess_args({"val": 5}) | ||
| assert errors == [] | ||
| assert args["val"] == 5.0 | ||
| assert isinstance(args["val"], float) | ||
|
|
||
| def test_enum_valid_value(self): | ||
| tool = FunctionTool(enum_func) | ||
| args, errors = tool._preprocess_args({"color": "red"}) | ||
| assert errors == [] | ||
| assert args["color"] == Color.RED | ||
|
|
||
| def test_enum_invalid_value(self): | ||
| tool = FunctionTool(enum_func) | ||
| args, errors = tool._preprocess_args({"color": "purple"}) | ||
| assert len(errors) == 1 | ||
| assert "color" in errors[0] | ||
|
|
||
| def test_list_int_coercion(self): | ||
| tool = FunctionTool(list_int_func) | ||
| args, errors = tool._preprocess_args({"nums": ["1", "2", "3"]}) | ||
| assert errors == [] | ||
| assert args["nums"] == [1, 2, 3] | ||
|
|
||
| def test_optional_none_skipped(self): | ||
| tool = FunctionTool(optional_int_func) | ||
| args, errors = tool._preprocess_args({"num": None}) | ||
| assert errors == [] | ||
| assert args["num"] is None | ||
|
|
||
| def test_optional_value_coerced(self): | ||
| tool = FunctionTool(optional_int_func) | ||
| args, errors = tool._preprocess_args({"num": "7"}) | ||
| assert errors == [] | ||
| assert args["num"] == 7 | ||
|
|
||
| def test_bool_from_int(self): | ||
| tool = FunctionTool(bool_func) | ||
| args, errors = tool._preprocess_args({"flag": 1}) | ||
| assert errors == [] | ||
| assert args["flag"] is True | ||
|
|
||
|
|
||
| # --- _preprocess_args validation error tests --- | ||
|
|
||
|
|
||
| class TestArgValidationErrors: | ||
|
|
||
| def test_string_for_int_returns_error(self): | ||
| tool = FunctionTool(int_func) | ||
| args, errors = tool._preprocess_args({"num": "foobar"}) | ||
| assert len(errors) == 1 | ||
| assert "num" in errors[0] | ||
|
|
||
| def test_none_for_required_int_returns_error(self): | ||
| """None for a non-Optional int should be flagged.""" | ||
| tool = FunctionTool(int_func) | ||
| # None passed for a required int param. The Optional unwrap won't | ||
| # trigger because the annotation is plain `int`, not Optional[int]. | ||
| # TypeAdapter(int).validate_python(None) raises ValidationError. | ||
| args, errors = tool._preprocess_args({"num": None}) | ||
| assert len(errors) == 1 | ||
| assert "num" in errors[0] | ||
|
|
||
| def test_multiple_param_errors(self): | ||
| tool = FunctionTool(multi_param_func) | ||
| args, errors = tool._preprocess_args( | ||
| {"name": 123, "count": "not_a_number", "flag": "not_a_bool"} | ||
| ) | ||
| # All three fail: pydantic rejects int->str, "not_a_number"->int, | ||
| # and "not_a_bool"->bool. | ||
| assert len(errors) == 3 | ||
| assert any("name" in e for e in errors) | ||
| assert any("count" in e for e in errors) | ||
| assert any("flag" in e for e in errors) | ||
yuvrajangadsingh marked this conversation as resolved.
Show resolved
Hide resolved
yuvrajangadsingh marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
|
|
||
| # --- run_async integration tests --- | ||
|
|
||
|
|
||
| def _make_tool_context(): | ||
| tool_context_mock = MagicMock(spec=ToolContext) | ||
| invocation_context_mock = MagicMock(spec=InvocationContext) | ||
| session_mock = MagicMock(spec=Session) | ||
| invocation_context_mock.session = session_mock | ||
| tool_context_mock.invocation_context = invocation_context_mock | ||
| return tool_context_mock | ||
|
|
||
|
|
||
| class TestRunAsyncValidation: | ||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_invalid_arg_returns_error_to_llm(self): | ||
| tool = FunctionTool(int_func) | ||
| result = await tool.run_async( | ||
| args={"num": "foobar"}, tool_context=_make_tool_context() | ||
| ) | ||
| assert isinstance(result, dict) | ||
| assert "error" in result | ||
| assert "validation error" in result["error"].lower() | ||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_valid_coercion_invokes_function(self): | ||
| tool = FunctionTool(int_func) | ||
| result = await tool.run_async( | ||
| args={"num": "42"}, tool_context=_make_tool_context() | ||
| ) | ||
| assert result == 42 | ||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_enum_invalid_returns_error(self): | ||
| tool = FunctionTool(enum_func) | ||
| result = await tool.run_async( | ||
| args={"color": "purple"}, tool_context=_make_tool_context() | ||
| ) | ||
| assert isinstance(result, dict) | ||
| assert "error" in result | ||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_enum_valid_invokes_function(self): | ||
| tool = FunctionTool(enum_func) | ||
| result = await tool.run_async( | ||
| args={"color": "green"}, tool_context=_make_tool_context() | ||
| ) | ||
| assert result == "green" | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.