Backtestsopenai-agents-pythonrun-20261024-184640#94
Add method_tool Functionality
Our patch was judged better than the merged fix.
In this judgment, Patch A = our agent, Patch B = the merged fix.
Both patches fix the reported problem: the independent tests show every scenario (schema without `self`, instance state, async, two instances, run_sync) passing on A and B alike. The difference is in how robustly each gets there. Patch A detects a class-body function whose first positional parameter is `self` (via qualname plus signature), derives the schema by binding a placeholder receiver so `inspect.signature`/docstring handling drop `self` through the normal path, and on instance access builds a genuinely new FunctionTool through the same `_create_function_tool` path with a real bound method. It reuses the existing invocation code unchanged, handles `RunContextWrapper` in the second position for free, deliberately avoids caching on the instance (so copy/deepcopy/pickle of the owner keep working, and tests prove it), and gives a clear UserError when the class-level tool is invoked. Its tests cover schema, docstring args, name_override, context, async, undocumented methods (guarding the `inspect.getdoc` class-fallback trap it explicitly comments on), copy/deepcopy/pickle of the owning object, non-method functions that happen to have a `self` parameter, and a full Runner run with FakeModel. The main cost is that each attribute access regenerates the pydantic schema, a performance smell rather than a correctness bug. Patch B changes the public `function_schema` to strip any unannotated first `self`/`cls` and adds a `skips_receiver` field, then in `function_tool` duplicates the entire ~45-line invocation body into a receiver-aware variant. Binding in `__get__` is done by `copy.copy(self)` and then poking the private `_invoke_tool_impl` attribute on the copied `_FailureHandlingFunctionToolInvoker`; this only stays isolated per instance because the tool's copy machinery happens to rebind the invoker, and it silently returns an unbound copy if the handler is a different type. Its heuristic also misses methods whose `self` is annotated (e.g. `Self`) and treats any plain function with an unannotated `self`/`cls` first param as a method. Tests are reasonable (schema unit tests, descriptor behavior, context, async, unbound error) but stop at `on_invoke_tool`; there is no agent/Runner-level test, no copy/deepcopy coverage, and the `cls` test exercises a bare function rather than a real classmethod. On scope, B's edits to `function_schema` and the duplicated invoker widen the blast radius for no additional benefit on the issue's ask. On craft, A integrates with existing construction and error-handling paths and documents the new behavior in the `function_tool` docstring, while B relies on private internals and copy semantics. A is the better fix.
Four judges ruled on this ticket in parallel, and the verdict comes from counting their votes. Each saw the issue and the two patches, labelled A and B in random order (two of them saw ours as A), with issue links and version numbers removed. Where tests could check the fix, they also saw the results of tests a separate agent wrote for the issue, run on both patches. None was told which patch was ours. The reasoning above is one judge's, shown verbatim.
Solve
8m 36s
Wall-clock time in the container
Full test suite
No new failures
748 passed · 0 skipped · 748 total
Contamination audit
Clean
No sign the agent saw the real fix
Patch size
218vs 489 merged
Changed lines, ours vs merged
The issue
View on GitHubI group my tools into classes, and they leverage attributes of the instantiated object to work properly. The function_tool decorator doesn't seem to support this. For example, the following works (as expected):
@function_tool
def get_random_number() -> int:
"""Get a random number."""
return random.randint(0, 100)
agent = Agent(
name="Assistant",
instructions="You are a helpful assistant",
tools=[get_random_number]
)
result = Runner.run_sync(agent, input="Get me a random number")
print(result.final_output)
But the following doesn't:
class Tools:
@function_tool
def get_random_number(self) -> int:
"""Get a random number."""
return random.randint(0, 100)
tools = Tools()
agent = Agent(
name="Assistant",
instructions="You are a helpful assistant",
tools=[tools.get_random_number]
)
result = Runner.run_sync(agent, input="Get me a random number")
print(result.final_output)
Running this produces an error like:
openai.BadRequestError: Error code: 400 - {'error': {'message': "Invalid schema for function 'get_random_number': In context=('properties', 'self'), schema must have a 'type' key.", 'type': 'invalid_request_error', 'param': 'tools[0].parameters', 'code': 'invalid_function_parameters'}}
i.e., the self parameter isn't accounted for.
There's probably a ton of different ways of approaching this, but I've been utilizing the class-based tool pattern quite extensively and I've found it works pretty well for keeping tooling clean and simple. I'm happy to consider alternative approaches, but if there was just a way to ignore the self parameter, then I think everything else would just work, no?
The two patches
src/agents/tool.pyindex 1ac3c29..2eee874 100644@@ -10,7 +10,7 @@ import math import weakref from collections.abc import Awaitable, Mapping from dataclasses import dataclass, field-from types import UnionType+from types import MethodType, UnionType from typing import ( TYPE_CHECKING, Annotated,@@ -353,6 +353,43 @@ class FunctionTool: setattr(copied_tool, attr_name, attr_value) return copied_tool + def __get__(self, instance: object | None, owner: type | None = None) -> FunctionTool:+ """Bind tools created from instance methods to the instance they are accessed through.++ Accessing an `@function_tool`-decorated method through an instance returns a FunctionTool+ that calls the method with that instance as `self`. All other tools are returned as-is.+ """+ binder: Callable[[object], FunctionTool] | None = getattr(+ self, _METHOD_TOOL_BINDER_ATTR, None+ )+ if instance is None or binder is None:+ return self+ # Not cached on the instance: a cached tool would stay bound to the original object+ # across copy/deepcopy and would make the instance unpicklable.+ return binder(instance)+++_METHOD_TOOL_BINDER_ATTR = "_agents_method_tool_binder"+++class _UnboundMethodSelfPlaceholder:+ """Stand-in `self` used only to derive the schema of an unbound method tool."""+++_UNBOUND_METHOD_SELF_PLACEHOLDER = _UnboundMethodSelfPlaceholder()+++def _is_unbound_instance_method(func: Callable[..., Any]) -> bool:+ """Return True if `func` is a plain function defined in a class body that takes `self`."""+ if not inspect.isfunction(func):+ return False+ qualname_parts = func.__qualname__.split(".")+ if len(qualname_parts) < 2 or qualname_parts[-2] == "<locals>":+ return False+ params = list(inspect.signature(func).parameters.values())+ positional_kinds = (inspect.Parameter.POSITIONAL_ONLY, inspect.Parameter.POSITIONAL_OR_KEYWORD)+ return bool(params) and params[0].name == "self" and params[0].kind in positional_kinds+ class _FailureHandlingFunctionToolInvoker: """Internal callable that rebinds wrapper error handling for copied FunctionTools."""@@ -1622,6 +1659,10 @@ def function_tool( If the function takes a `RunContextWrapper` as the first argument, it *must* match the context type of the agent that uses the tool. + The decorator can also be applied to instance methods defined in a class body. The `self`+ parameter is excluded from the tool schema, and accessing the tool through an instance+ (e.g. `tools=[my_tools.get_weather]`) returns a FunctionTool bound to that instance.+ Args: func: The function to wrap. name_override: If provided, use this name for the tool instead of the function's name.@@ -1658,10 +1699,19 @@ def function_tool( explicitly loads it. """ - def _create_function_tool(the_func: ToolFunction[...]) -> FunctionTool:+ def _create_function_tool(+ the_func: ToolFunction[...], method_self: object | None = None+ ) -> FunctionTool:+ is_unbound_method = method_self is None and _is_unbound_instance_method(the_func)+ is_method = is_unbound_method or method_self is not None+ # For instance methods, derive the schema without `self` from a placeholder binding, so+ # docstring lookup never falls back to the owner class (where it would find this tool).+ schema_func = MethodType(the_func, _UNBOUND_METHOD_SELF_PLACEHOLDER) if is_method else None+ if method_self is not None:+ the_func = MethodType(the_func, method_self) is_sync_function_tool = not inspect.iscoroutinefunction(the_func) schema = function_schema(- func=the_func,+ func=schema_func or the_func, name_override=name_override, description_override=description_override, docstring_style=docstring_style,@@ -1671,6 +1721,12 @@ def function_tool( async def _on_invoke_tool_impl(ctx: ToolContext[Any], input: str) -> Any: tool_name = ctx.tool_name+ if is_unbound_method:+ raise UserError(+ f"Tool {tool_name} was created from the instance method "+ f"{the_func.__qualname__} but is not bound to an instance. Pass the tool "+ "via an instance (e.g. `tools=[my_instance.method]`), not via the class."+ ) json_data = _parse_function_tool_json_input(tool_name=tool_name, input_json=input) _log_function_tool_invocation(tool_name=tool_name, input_json=input) @@ -1728,6 +1784,13 @@ def function_tool( defer_loading=defer_loading, sync_invoker=is_sync_function_tool, )+ if is_unbound_method:+ unbound_func = the_func++ def _bind_to_instance(instance: object) -> FunctionTool:+ return _create_function_tool(unbound_func, method_self=instance)++ setattr(function_tool, _METHOD_TOOL_BINDER_ATTR, _bind_to_instance) return function_tool # If func is actually a callable, we were used as @function_tool with no parenthesestests/test_function_tool_methods.pynew file mode 100644index 0000000..be181a8@@ -0,0 +1,149 @@+from __future__ import annotations++import copy+import json+import pickle+from typing import Any++import pytest++from agents import Agent, FunctionTool, Runner, UserError, function_tool+from agents.run_context import RunContextWrapper+from agents.tool_context import ToolContext++from .fake_model import FakeModel+from .test_responses import get_function_tool_call, get_text_message+++def make_ctx(context: Any = None) -> ToolContext[Any]:+ return ToolContext(context=context, tool_name="dummy", tool_call_id="1", tool_arguments="")+++class Tools:+ def __init__(self, base: int) -> None:+ self.base = base++ @function_tool+ def get_number(self) -> int:+ """Get a number."""+ return self.base++ @function_tool(name_override="add_to_base")+ async def add(self, value: int) -> int:+ """Add a value to the base.++ Args:+ value: The value to add.+ """+ return self.base + value++ @function_tool+ def with_context(self, ctx: RunContextWrapper[str], suffix: str) -> str:+ return f"{ctx.context}-{self.base}-{suffix}"+++def test_method_tool_schema_excludes_self():+ tools = Tools(1)+ for tool in (tools.get_number, Tools.get_number):+ assert isinstance(tool, FunctionTool)+ assert tool.name == "get_number"+ assert tool.description == "Get a number."+ assert "self" not in tool.params_json_schema["properties"]+ assert tool.params_json_schema["properties"] == {}++ add_schema = tools.add.params_json_schema+ assert tools.add.name == "add_to_base"+ assert list(add_schema["properties"]) == ["value"]+ assert add_schema["properties"]["value"]["description"] == "The value to add."+ assert add_schema["required"] == ["value"]++ assert list(tools.with_context.params_json_schema["properties"]) == ["suffix"]+++@pytest.mark.asyncio+async def test_method_tool_invocation_uses_instance_attributes():+ first, second = Tools(10), Tools(20)++ assert await first.get_number.on_invoke_tool(make_ctx(), "") == 10+ assert await second.get_number.on_invoke_tool(make_ctx(), "") == 20+ assert await first.add.on_invoke_tool(make_ctx(), json.dumps({"value": 5})) == 15+ assert (+ await second.with_context.on_invoke_tool(make_ctx("ctx"), json.dumps({"suffix": "x"}))+ == "ctx-20-x"+ )+++def test_undocumented_method_tool_has_empty_description():+ class Undocumented:+ @function_tool+ def ping(self, value: int) -> int:+ return value++ assert Undocumented.ping.description == ""+ assert Undocumented().ping.description == ""+++@pytest.mark.asyncio+async def test_copied_instance_binds_method_tool_to_copy():+ original = Tools(1)+ assert await original.get_number.on_invoke_tool(make_ctx(), "") == 1++ for copied in (copy.copy(original), copy.deepcopy(original)):+ copied.base = 100+ assert await copied.get_number.on_invoke_tool(make_ctx(), "") == 100++ pickle.dumps(original)+ assert Tools.get_number is Tools.get_number+++@pytest.mark.asyncio+async def test_unbound_method_tool_reports_error():+ result = await Tools.get_number.on_invoke_tool(make_ctx(), "")+ assert "not bound to an instance" in result+++@pytest.mark.asyncio+async def test_unbound_method_tool_raises_without_failure_error_function():+ class RaisingTools:+ @function_tool(failure_error_function=None)+ def get_value(self) -> int:+ return 1++ with pytest.raises(UserError, match="not bound to an instance"):+ await RaisingTools.get_value.on_invoke_tool(make_ctx(), "")+ assert await RaisingTools().get_value.on_invoke_tool(make_ctx(), "") == 1+++def test_non_method_functions_named_self_are_unchanged():+ @function_tool+ def local_tool(self: int) -> int:+ return self++ assert list(local_tool.params_json_schema["properties"]) == ["self"]++ class Holder:+ tool = local_tool++ assert Holder().tool is local_tool+++@pytest.mark.asyncio+async def test_method_tool_runs_with_agent():+ model = FakeModel()+ tools = Tools(42)+ agent = Agent(name="test", model=model, tools=[tools.get_number, tools.add])+ model.add_multiple_turn_outputs(+ [+ [+ get_function_tool_call("get_number", "{}", call_id="a"),+ get_function_tool_call("add_to_base", json.dumps({"value": 1}), call_id="b"),+ ],+ [get_text_message("done")],+ ]+ )++ result = await Runner.run(agent, input="go")++ assert result.final_output == "done"+ outputs = [item.output for item in result.new_items if item.type == "tool_call_output_item"]+ assert outputs == [42, 43]
src/agents/function_schema.pyindex 881ebdf00..e44989c2a 100644@@ -36,6 +36,10 @@ class FuncSchema: """The signature of the function.""" takes_context: bool = False """Whether the function takes a RunContextWrapper argument (must be the first argument)."""+ skips_receiver: bool = False+ """Whether the function's leading ``self`` or ``cls`` parameter was stripped from the schema.+ When True, the tool is a *method tool* and must be called with a receiver prepended to the+ argument list (see :meth:`FunctionTool.__get__`).""" strict_json_schema: bool = True """Whether the JSON schema is in strict mode. We **strongly** recommend setting this to True, as it increases the likelihood of correct JSON input."""@@ -286,23 +290,46 @@ def function_schema( sig = inspect.signature(func) params = list(sig.parameters.items()) takes_context = False+ skips_receiver = False filtered_params = []+ # Index into `params` where non-receiver, non-context processing begins.+ _params_start = 0 if params: first_name, first_param = params[0] # Prefer the evaluated type hint if available ann = type_hints.get(first_name, first_param.annotation)- if ann != inspect._empty:+ if ann == inspect._empty and first_name in ("self", "cls"):+ # Unannotated self/cls → this is an instance or class method receiver.+ # Exclude it from the schema so the LLM never sees it; the tool's __get__+ # descriptor will supply the receiver at call time.+ skips_receiver = True+ _params_start = 1+ elif ann != inspect._empty: origin = get_origin(ann) or ann if origin is RunContextWrapper or origin is ToolContext: takes_context = True # Mark that the function takes context+ _params_start = 1 else: filtered_params.append((first_name, first_param))+ _params_start = 1 else: filtered_params.append((first_name, first_param))+ _params_start = 1++ # When the first param is a method receiver, the *next* param may be a context arg.+ if skips_receiver and len(params) > 1:+ second_name, second_param = params[1]+ second_ann = type_hints.get(second_name, second_param.annotation)+ if second_ann != inspect._empty:+ origin = get_origin(second_ann) or second_ann+ if origin is RunContextWrapper or origin is ToolContext:+ takes_context = True+ _params_start = 2 - # For parameters other than the first, raise error if any use RunContextWrapper or ToolContext.- for name, param in params[1:]:+ # For parameters beyond the first (and optional context), raise an error if any use+ # RunContextWrapper or ToolContext in an unsupported position.+ for name, param in params[_params_start:]: ann = type_hints.get(name, param.annotation) if ann != inspect._empty: origin = get_origin(ann) or ann@@ -313,6 +340,12 @@ def function_schema( ) filtered_params.append((name, param)) + # If this is a method, strip the receiver from the stored signature so that+ # to_call_args() never attempts to populate self/cls from LLM-supplied JSON.+ if skips_receiver:+ receiver_name = params[0][0]+ sig = sig.replace(parameters=[p for n, p in sig.parameters.items() if n != receiver_name])+ # We will collect field definitions for create_model as a dict: # field_name -> (type_annotation, default_value_or_Field(...)) fields: dict[str, Any] = {}@@ -419,5 +452,6 @@ def function_schema( params_json_schema=json_schema, signature=sig, takes_context=takes_context,+ skips_receiver=skips_receiver, strict_json_schema=strict_json_schema, )src/agents/tool.pyindex 1ac3c29ae..0e6e01982 100644@@ -353,6 +353,31 @@ class FunctionTool: setattr(copied_tool, attr_name, attr_value) return copied_tool + def __get__(self, obj: Any, objtype: Any = None) -> FunctionTool:+ """Descriptor protocol: bind this method tool to a class instance.++ When a :func:`function_tool`-decorated method is accessed on an instance+ (e.g. ``my_instance.my_tool``), this returns a new :class:`FunctionTool`+ whose invocation automatically prepends ``my_instance`` as the receiver,+ so the underlying method receives the correct ``self``/``cls`` argument.++ Accessing the tool on the *class* (``MyClass.my_tool``) returns the+ unbound :class:`FunctionTool` unchanged.+ """+ if obj is None:+ # Class-level access — return the unbound tool descriptor.+ return self+ make_impl = getattr(self, "_make_impl", None)+ if make_impl is None:+ # Not a method tool; behave as a plain attribute (no binding needed).+ return self+ # Build a copy and rewire its invoker to use the bound receiver.+ bound_tool = copy.copy(self)+ handler = bound_tool.on_invoke_tool+ if isinstance(handler, _FailureHandlingFunctionToolInvoker):+ handler._invoke_tool_impl = make_impl(obj)+ return bound_tool+ class _FailureHandlingFunctionToolInvoker: """Internal callable that rebinds wrapper error handling for copied FunctionTools."""@@ -1669,6 +1694,97 @@ def function_tool( strict_json_schema=strict_mode, ) + _on_handled_error = _build_handled_function_tool_error_handler(+ span_message="Error running tool (non-fatal)",+ span_message_for_json_decode_error="Error running tool",+ log_label="Tool",+ )++ if schema.skips_receiver:+ # The decorated function is an unbound instance/class method. We+ # store a factory (_make_impl) on the returned FunctionTool so that+ # the __get__ descriptor can produce a correctly-bound invoker when+ # the tool is accessed via a class instance.+ def _make_impl(+ receiver: Any,+ ) -> Callable[[ToolContext[Any], str], Awaitable[Any]]:+ async def _method_invoke_impl(ctx: ToolContext[Any], input: str) -> Any:+ tool_name = ctx.tool_name+ json_data = _parse_function_tool_json_input(+ tool_name=tool_name, input_json=input+ )+ _log_function_tool_invocation(tool_name=tool_name, input_json=input)++ try:+ parsed = (+ schema.params_pydantic_model(**json_data)+ if json_data+ else schema.params_pydantic_model()+ )+ except ValidationError as e:+ raise ModelBehaviorError(+ f"Invalid JSON input for tool {tool_name}: {e}"+ ) from e++ args, kwargs_dict = schema.to_call_args(parsed)++ if not _debug.DONT_LOG_TOOL_DATA:+ logger.debug(f"Tool call args: {args}, kwargs: {kwargs_dict}")++ if receiver is None:+ raise UserError(+ f"Tool '{schema.name}' was decorated on a class method and must be "+ f"accessed via a class instance before being invoked. "+ f"Use 'instance.{schema.name}' or bind the tool with "+ f"'tool.__get__(instance)' before adding it to an agent."+ )++ if not is_sync_function_tool:+ if schema.takes_context:+ result = await the_func(receiver, ctx, *args, **kwargs_dict)+ else:+ result = await the_func(receiver, *args, **kwargs_dict)+ else:+ if schema.takes_context:+ result = await asyncio.to_thread(+ the_func, receiver, ctx, *args, **kwargs_dict+ )+ else:+ result = await asyncio.to_thread(+ the_func, receiver, *args, **kwargs_dict+ )++ if _debug.DONT_LOG_TOOL_DATA:+ logger.debug(f"Tool {tool_name} completed.")+ else:+ logger.debug(f"Tool {tool_name} returned {result}")++ return result++ return _method_invoke_impl++ function_tool = _build_wrapped_function_tool(+ name=schema.name,+ description=schema.description or "",+ params_json_schema=schema.params_json_schema,+ invoke_tool_impl=_make_impl(None), # unbound placeholder+ on_handled_error=_on_handled_error,+ failure_error_function=failure_error_function,+ strict_json_schema=strict_mode,+ is_enabled=is_enabled,+ needs_approval=needs_approval,+ tool_input_guardrails=tool_input_guardrails,+ tool_output_guardrails=tool_output_guardrails,+ timeout_seconds=timeout,+ timeout_behavior=timeout_behavior,+ timeout_error_function=timeout_error_function,+ defer_loading=defer_loading,+ sync_invoker=is_sync_function_tool,+ )+ # Store the factory so __get__ can bind a receiver on instance access.+ function_tool._make_impl = _make_impl # type: ignore[attr-defined]+ return function_tool+ async def _on_invoke_tool_impl(ctx: ToolContext[Any], input: str) -> Any: tool_name = ctx.tool_name json_data = _parse_function_tool_json_input(tool_name=tool_name, input_json=input)@@ -1711,11 +1827,7 @@ def function_tool( description=schema.description or "", params_json_schema=schema.params_json_schema, invoke_tool_impl=_on_invoke_tool_impl,- on_handled_error=_build_handled_function_tool_error_handler(- span_message="Error running tool (non-fatal)",- span_message_for_json_decode_error="Error running tool",- log_label="Tool",- ),+ on_handled_error=_on_handled_error, failure_error_function=failure_error_function, strict_json_schema=strict_mode, is_enabled=is_enabled,tests/test_method_tool.pynew file mode 100644index 000000000..27e781a95@@ -0,0 +1,327 @@+"""Tests for @function_tool applied to class instance methods (issue #94).++Covers the descriptor protocol (__get__), schema generation (self/cls stripped),+receiver binding at call time, and edge cases flagged in previous review rounds.+"""++from __future__ import annotations++import pytest++from agents import RunContextWrapper+from agents.exceptions import UserError+from agents.function_schema import function_schema+from agents.tool import FunctionTool, function_tool+from agents.tool_context import ToolContext++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------+++def _make_tool_context(tool_name: str = "test_tool") -> ToolContext:+ return ToolContext(context=None, tool_name=tool_name, tool_call_id="1", tool_arguments="")+++# ---------------------------------------------------------------------------+# function_schema unit tests+# ---------------------------------------------------------------------------+++class _BasicMethodClass:+ multiplier: int++ def __init__(self, multiplier: int) -> None:+ self.multiplier = multiplier++ def multiply(self, x: int) -> int:+ """Multiply x by the instance multiplier.++ Args:+ x: The value to multiply.+ """+ return x * self.multiplier+++def test_function_schema_strips_self() -> None:+ """function_schema must not include self in the JSON schema."""+ schema = function_schema(_BasicMethodClass.multiply)+ assert schema.skips_receiver is True+ assert schema.takes_context is False+ assert "self" not in schema.params_json_schema.get("properties", {})+ assert "x" in schema.params_json_schema.get("properties", {})+++def test_function_schema_strips_self_from_stored_signature() -> None:+ """The stored signature must not include self so to_call_args never fetches it."""+ schema = function_schema(_BasicMethodClass.multiply)+ assert "self" not in schema.signature.parameters+++def test_function_schema_to_call_args_without_receiver() -> None:+ """to_call_args must return only the non-receiver arguments."""+ schema = function_schema(_BasicMethodClass.multiply)+ parsed = schema.params_pydantic_model(x=7)+ args, kwargs = schema.to_call_args(parsed)+ # args should be [7]; no None placeholder for self+ assert args == [7]+ assert kwargs == {}+++def test_function_schema_cls_is_stripped() -> None:+ """Leading cls parameter (unannotated) must also be treated as a receiver.++ We test the undecorated classmethod function directly (before @classmethod+ binds cls) because @classmethod already hides cls from the signature.+ """++ # Define an unbound function that uses cls as its first unannotated param,+ # as if it were the raw underlying function of a classmethod.+ def greet(cls, name: str) -> str:+ """Say hi.++ Args:+ name: Who to greet.+ """+ return f"hi {name}"++ schema = function_schema(greet)+ assert schema.skips_receiver is True+ assert "cls" not in schema.params_json_schema.get("properties", {})+ assert "name" in schema.params_json_schema.get("properties", {})+++def test_function_schema_annotated_self_not_stripped() -> None:+ """A first parameter named self *with* a type annotation must not be stripped."""++ def weird(self: int, y: int) -> int:+ return self + y++ schema = function_schema(weird)+ assert schema.skips_receiver is False+ assert "self" in schema.params_json_schema.get("properties", {})+++def test_function_schema_self_with_context_param() -> None:+ """self followed immediately by RunContextWrapper must set both flags correctly."""++ class _WithCtx:+ def act(self, ctx: RunContextWrapper[None], value: int) -> int:+ """Do something.++ Args:+ value: The input value.+ """+ return value++ schema = function_schema(_WithCtx.act)+ assert schema.skips_receiver is True+ assert schema.takes_context is True+ assert "self" not in schema.params_json_schema.get("properties", {})+ assert "ctx" not in schema.params_json_schema.get("properties", {})+ assert "value" in schema.params_json_schema.get("properties", {})+++def test_function_schema_context_in_wrong_position_raises() -> None:+ """RunContextWrapper after self but not in position 1 must raise UserError."""++ class _Bad:+ def bad(self, x: int, ctx: RunContextWrapper[None]) -> int:+ return x++ with pytest.raises(UserError, match="non-first position"):+ function_schema(_Bad.bad)+++def test_function_schema_regular_function_unchanged() -> None:+ """function_schema on a plain function must behave exactly as before."""++ def add(a: int, b: int) -> int:+ """Add two numbers.++ Args:+ a: First.+ b: Second.+ """+ return a + b++ schema = function_schema(add)+ assert schema.skips_receiver is False+ assert schema.takes_context is False+ assert "a" in schema.params_json_schema.get("properties", {})+ assert "b" in schema.params_json_schema.get("properties", {})+++# ---------------------------------------------------------------------------+# FunctionTool descriptor / __get__ tests+# ---------------------------------------------------------------------------+++class _Calculator:+ def __init__(self, base: int) -> None:+ self.base = base++ @function_tool+ def add(self, x: int) -> int:+ """Add x to the base.++ Args:+ x: Value to add.+ """+ return self.base + x++ @function_tool+ async def async_add(self, x: int) -> int:+ """Async-add x to the base.++ Args:+ x: Value to add.+ """+ return self.base + x+++def test_class_level_access_returns_function_tool() -> None:+ """Accessing the tool on the class should return a FunctionTool (unbound)."""+ assert isinstance(_Calculator.add, FunctionTool)+++def test_instance_access_returns_function_tool() -> None:+ """Accessing the tool on an instance should also return a FunctionTool."""+ calc = _Calculator(base=10)+ assert isinstance(calc.add, FunctionTool)+++def test_instance_access_returns_different_object() -> None:+ """Each instance access should produce a new (bound) FunctionTool."""+ calc = _Calculator(base=10)+ bound1 = calc.add+ bound2 = calc.add+ assert bound1 is not bound2+ assert bound1 is not _Calculator.add+++def test_bound_tool_schema_unchanged() -> None:+ """The schema of the bound tool must be identical to the class-level tool."""+ calc = _Calculator(base=10)+ assert calc.add.params_json_schema == _Calculator.add.params_json_schema+ assert calc.add.name == _Calculator.add.name+++@pytest.mark.asyncio+async def test_bound_tool_invokes_correct_instance() -> None:+ """The bound tool must call the method on the correct instance."""+ calc5 = _Calculator(base=5)+ calc20 = _Calculator(base=20)++ ctx = _make_tool_context("add")+ result5 = await calc5.add.on_invoke_tool(ctx, '{"x": 3}')+ result20 = await calc20.add.on_invoke_tool(ctx, '{"x": 3}')++ assert result5 == 8 # 5 + 3+ assert result20 == 23 # 20 + 3+++@pytest.mark.asyncio+async def test_async_bound_tool_invokes_correct_instance() -> None:+ """The async variant also dispatches to the right instance."""+ calc = _Calculator(base=100)+ ctx = _make_tool_context("async_add")+ result = await calc.async_add.on_invoke_tool(ctx, '{"x": 1}')+ assert result == 101+++@pytest.mark.asyncio+async def test_unbound_tool_returns_error_message() -> None:+ """Calling the class-level (unbound) tool must produce an error message.++ The UserError raised internally is caught by the failure error handler and+ returned as a string so the LLM receives a meaningful error rather than+ crashing the run.+ """+ ctx = _make_tool_context("add")+ result = await _Calculator.add.on_invoke_tool(ctx, '{"x": 1}')+ assert isinstance(result, str)+ assert "class instance" in result+++# ---------------------------------------------------------------------------+# Method tool with RunContextWrapper+# ---------------------------------------------------------------------------+++class _ContextAwareService:+ def __init__(self, prefix: str) -> None:+ self.prefix = prefix++ @function_tool+ def greet(self, ctx: RunContextWrapper[None], name: str) -> str:+ """Greet someone.++ Args:+ name: The person's name.+ """+ return f"{self.prefix}: hello {name}"+++@pytest.mark.asyncio+async def test_method_tool_with_context() -> None:+ """Method tool that also takes RunContextWrapper must pass ctx correctly."""+ svc = _ContextAwareService(prefix="BOT")+ tool_ctx = _make_tool_context("greet")++ result = await svc.greet.on_invoke_tool(tool_ctx, '{"name": "Alice"}')+ assert result == "BOT: hello Alice"+++# ---------------------------------------------------------------------------+# Only the leading self/cls is stripped (not all params named self)+# ---------------------------------------------------------------------------+++def test_only_leading_self_is_stripped() -> None:+ """A parameter named 'self' that is NOT the first parameter must appear in the schema."""++ class _Tricky:+ def method(self, value: int, self_count: int = 0) -> int:+ """Do something.++ Args:+ value: Main value.+ self_count: Extra count (not a receiver).+ """+ return value + self_count++ schema = function_schema(_Tricky.method)+ props = schema.params_json_schema.get("properties", {})+ assert "self" not in props+ assert "value" in props+ assert "self_count" in props+++# ---------------------------------------------------------------------------+# Decorator with arguments still works for methods+# ---------------------------------------------------------------------------+++class _Described:+ @function_tool(name_override="my_described_tool", description_override="A described tool.")+ def compute(self, n: int) -> int:+ """Fallback docstring.++ Args:+ n: Input.+ """+ return n * 2+++def test_function_tool_with_args_on_method() -> None:+ assert _Described.compute.name == "my_described_tool"+ assert _Described.compute.description == "A described tool."+++@pytest.mark.asyncio+async def test_function_tool_with_args_on_method_binding() -> None:+ obj = _Described()+ ctx = _make_tool_context("my_described_tool")+ result = await obj.compute.on_invoke_tool(ctx, '{"n": 4}')+ assert result == 8