From 45cc38fe443f2c92cd092b7ece0a9b3c88b237e8 Mon Sep 17 00:00:00 2001 From: Justin Beckwith Date: Fri, 25 Sep 2026 09:27:11 -0700 Subject: [PATCH] fix: Reject silently discarded kwargs tool arguments --- src/agents/function_schema.py | 16 +++++++-- tests/test_function_tool.py | 68 +++++++++++++++++++++++++++++++++++ 2 files changed, 82 insertions(+), 2 deletions(-) diff --git a/src/agents/function_schema.py b/src/agents/function_schema.py index b11a76ee74..a15f604f75 100644 --- a/src/agents/function_schema.py +++ b/src/agents/function_schema.py @@ -10,7 +10,7 @@ # griffelib exposes the `griffe` package at runtime but currently does not ship typing markers. from griffe import Docstring, DocstringSectionKind # type: ignore[import-untyped] -from pydantic import BaseModel, Field, create_model +from pydantic import BaseModel, ConfigDict, Field, create_model from pydantic.fields import FieldInfo from .exceptions import ModelBehaviorError, UserError @@ -421,6 +421,7 @@ def function_schema( # We will collect field definitions for create_model as a dict: # field_name -> (type_annotation, default_value_or_Field(...)) fields: dict[str, Any] = {} + model_config = ConfigDict() for name, param in filtered_params: ann = type_hints.get(name, param.annotation) @@ -469,6 +470,15 @@ def function_schema( ) elif param.kind == param.VAR_KEYWORD: + if strict_json_schema: + raise UserError( + f"Variadic keyword parameter `**{name}` in function {func.__name__} cannot" + " use a strict schema. Set strict_mode=False on the function tool" + " (or strict_json_schema=False on function_schema) and pass keyword arguments" + f" in the nested `{name}` object, or use explicit parameters for a strict tool." + ) + # Reject flat keyword arguments instead of silently dropping them before invocation. + model_config["extra"] = "forbid" # **kwargs handling: a ``**kwargs: X`` annotation applies to each keyword *value* # (PEP 484), so the collected container is always ``dict[str, X]``. Preserve the full # annotation as the value type -- mirroring the variadic-positional handling above, @@ -518,7 +528,9 @@ def function_schema( ) # 3. Dynamically build a Pydantic model - dynamic_model = create_model(f"{func_name}_args", __base__=BaseModel, **fields) + dynamic_model = create_model( + f"{func_name}_args", __base__=BaseModel, __config__=model_config, **fields + ) # 4. Build JSON schema from that model json_schema = dynamic_model.model_json_schema() diff --git a/tests/test_function_tool.py b/tests/test_function_tool.py index c9790b7173..e4e06efa3d 100644 --- a/tests/test_function_tool.py +++ b/tests/test_function_tool.py @@ -1583,6 +1583,74 @@ def kwargs_collision_function(x: int, *rest: int, **kw: Any) -> str: return f"x={x} rest={rest} kw={kw}" +@pytest.mark.asyncio +@pytest.mark.parametrize("payload", [{"a": 1, "b": "x"}, {"kwargs": {"a": 1}, "b": "x"}]) +async def test_kwargs_tool_rejects_flat_arguments_before_invocation(payload): + calls = [] + + def collect(**kwargs): + calls.append(kwargs) + return kwargs + + tool = function_tool(collect, strict_mode=False, failure_error_function=None) + arguments = json.dumps(payload) + context = ToolContext(None, tool_name=tool.name, tool_call_id="1", tool_arguments=arguments) + + with pytest.raises(ModelBehaviorError, match="Invalid JSON input for tool collect"): + await tool.on_invoke_tool(context, arguments) + + assert calls == [] + assert tool.params_json_schema["additionalProperties"] is False + assert tool.params_json_schema["properties"]["kwargs"]["additionalProperties"] is True + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "payload, expected", [({"kwargs": {"a": 1, "b": "x"}}, {"a": 1, "b": "x"}), ({}, {})] +) +async def test_kwargs_tool_preserves_nested_arguments_and_empty_default(payload, expected): + def collect(**kwargs): + return kwargs + + tool = function_tool(collect, strict_mode=False, failure_error_function=None) + arguments = json.dumps(payload) + context = ToolContext(None, tool_name=tool.name, tool_call_id="1", tool_arguments=arguments) + + assert await tool.on_invoke_tool(context, arguments) == expected + + +@pytest.mark.asyncio +async def test_kwargs_tool_preserves_named_arguments_and_typed_nested_values(): + calls = [] + + async def collect(label: str, **options: int): + calls.append((label, options)) + return options + + tool = function_tool(collect, strict_mode=False, failure_error_function=None) + arguments = '{"label": "sample", "options": {"a": 1}}' + context = ToolContext(None, tool_name=tool.name, tool_call_id="1", tool_arguments=arguments) + assert await tool.on_invoke_tool(context, arguments) == {"a": 1} + assert calls == [("sample", {"a": 1})] + + for arguments in ( + '{"label": "sample", "a": 1}', + '{"label": "sample", "options": {"a": "invalid"}}', + ): + context = ToolContext(None, tool_name=tool.name, tool_call_id="2", tool_arguments=arguments) + with pytest.raises(ModelBehaviorError): + await tool.on_invoke_tool(context, arguments) + assert calls == [("sample", {"a": 1})] + + +def test_kwargs_tool_strict_error_explains_non_strict_nested_input(): + def collect(**options: Any): + return options + + with pytest.raises(UserError, match=r"\*\*options.*strict_mode=False.*nested.*options"): + function_tool(collect) + + @pytest.mark.asyncio async def test_kwargs_key_colliding_with_param_is_reported_as_model_behavior_error(): """The collision reaches the model as feedback, not as an unhandled TypeError.