Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 14 additions & 2 deletions src/agents/function_schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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()
Expand Down
68 changes: 68 additions & 0 deletions tests/test_function_tool.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
Loading