Skip to content

Breaking: build callable-class activity tools from __call__ and raise ValueError for tools that can't be built in OpenAI Agents - #206

Merged
campoy merged 13 commits into
mainfrom
fix/openai-agents-python-activity-tool-callable-class
Nov 3, 2026
Merged

campoy merged 13 commits into
mainfrom
fix/openai-agents-python-activity-tool-callable-class

Conversation

@campoy

@campoy campoy commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

What was changed

activity_as_tool now builds a callable-class Activity's tool from its __call__, not from its constructor.

  • When given a class, it builds the schema from __call__ as an instance binds it, keeps the class name as the tool name, and takes the description from __call__'s own docstring, else the class's own docstring (unless it is exactly the one dataclasses or namedtuple generate), else that of a __call__ it inherits. Blank docstrings are skipped. A docstring whose first line is a Google section header (Args:, Arguments:, Params:, Parameters:, Returns: or Raises:, in any case) counts as having no summary, and a class docstring with no summary is skipped. When __call__'s docstring has no summary, such as one with only :param: fields, a NumPy Parameters section or a Google Args: section, the summary of the class's own docstring is used, else the tool has no description. __call__ must be a function, or a staticmethod, classmethod or functools.partialmethod over a function: binding it drops the receiver of a method, classmethod or partialmethod and keeps every parameter of a staticmethod. Calls then pass the model's arguments to __call__, which the Worker's registered instance runs.
  • __call__'s annotations are resolved in its own module, keeping Annotated metadata, so string annotations and from __future__ import annotations work. As with typing.get_type_hints, a generic function's own type parameters resolve, and a decorator's copied annotations are read on Python 3.14. The return annotation is skipped, since the tool doesn't use it, so a @typing.no_type_check function whose return type can't be resolved still builds. Methods passed as Class.method now get the same resolution; before, a string annotation failed with NameError. They drop a first parameter named self however it is annotated, as on main: the Worker registers the method bound to an instance, even when it is a module function assigned as a class attribute.
  • These now raise ValueError, so the Workflow Task fails and a run can continue once a fix is deployed: an instance of a callable-class activity in place of its class, a class whose __call__ is missing or of another kind, a __call__ whose signature or type hints can't be read, a __call__ with keyword-only parameters, and any activity with **kwargs, which the tool can't pass. The two existing errors, for a bare function and for an Activity with no name, now raise ValueError too; before, they raised an ApplicationError that failed the run.
  • Functions are unchanged, and so is the scheduled Activity name.
  • The fn docstring now names the three forms and the SDK's partialmethod limits.

No public name or option changes.

Breaking change: the change has no version gate. We are not adding version gates to these fixes. temporalio-openai-agents already shipped 1.0.0 and 1.1.0, so this break needs its next major release, 2.0.0. The runs affected had the constructor's schema, which gave the right result only when the constructor's parameters matched __call__'s. A run that called such a tool before this change recorded the constructor's arguments. Built from __call__, the tool rejects them on replay, returns an argument error to the model instead of scheduling the Activity, and the replay fails with [TMPRL1100]. The break goes both ways: a call whose arguments the constructor's schema rejected on the earlier version scheduled nothing, and the new tool accepts them on replay and schedules the Activity, so that replay fails too. This holds whether the tool was built in Workflow code or once at import time. Runs that only used function or Class.method tools are not affected, unless they caught one of the two existing errors described below. Also, a class whose __call__ takes a parameter with no JSON schema now fails tool construction, as a function Activity with that parameter does; before, it got the constructor's schema. The same holds for the classes in the ValueError bullet above. The two existing errors for a bare function and for an Activity with no name now fail the Workflow Task instead of the run. main documented them as ApplicationError, so code that catches ApplicationError around activity_as_tool no longer catches them. A run on the earlier version that caught one, for example to offer another tool, fails replay with the ValueError. In an update handler, the earlier version failed only the update; now the Workflow Task fails, so the update times out and the run waits for a fix.

Upgrade: before upgrading, let these runs finish on the earlier version, or keep them there with Worker Versioning: every run whose model called a callable-class tool (only runs where both schemas accept, or both reject, the recorded arguments still replay); and runs that build a class tool whose __call__ can't be made into a tool. A class tool can't be built when __call__ has a parameter whose type has no JSON schema (even an optional one), or a type the strict schema rejects, such as dict[str, Any] or a Mapping, or keyword-only or **kwargs parameters, or anything else function_schema rejects for a function with the same parameters, or when __call__ is not a function, or a staticmethod, classmethod or functools.partialmethod over a function. A function or Class.method tool that takes **kwargs already failed with the Agents SDK's UserError; only the exception type changes. Draining only protects recorded runs: new runs that build such a tool fail their Workflow Task, and a tool list built at import time raises when the module is imported, so the Worker can't start. Before upgrading, change those parameters or their types, or register the Activity in another form. The reliable check: before upgrading, build every class tool with activity_as_tool in a test on the new version. Other function and Class.method tools offer the same parameters as before. As before, a first parameter named self is never offered to the model, so a module-function activity that takes a real self argument must rename it. Do not roll a Worker back to 1.x while runs that called a class tool on 2.0 are open: the same runs fail replay there.

Why?

See #205. Workflow code references a callable-class Activity by its class, as workflow.execute_activity_class does, but activity_as_tool built the tool from inspect.signature(cls), the constructor's. The model was offered the constructor's parameters and its values went to __call__ by position: with a one-string constructor and a one-string call, the run completed with a wrong result and no error. Other constructors failed tool construction in Workflow code, or failed every call with TypeError.

Checklist

  1. Closes [Bug] openai_agents: activity_as_tool builds a callable-class Activity's tool from its constructor #205

  2. How was this tested:

    • test_tool_workflow in tests/test_openai.py gains a callable-class Activity, ActivityWeatherClass (constructor takes conditions, __call__ takes city: "CityName", a string naming a module-level alias), passed to activity_as_tool as its class and registered as ActivityWeatherClass("Cloudy"). The test now also checks that the class's Activity is scheduled with the model's city.
      • On main at fc2da34 it fails the Workflow Task with NameError: name 'CityName' is not defined while building the method tool, then times out.
      • Without the annotation resolution, it and the replay of the existing tools-workflow-history.json fail with NameError: name 'CityName' is not defined.
      • Both pass with the change.
    • test_callable_class_tool_schema checks the schema and description for a @staticmethod __call__(self: str) on an abc.ABC subclass and a @classmethod __call__(cls, self: str) (both offer self), a __call__ set with functools.partialmethod, an undocumented and a documented dataclass, a __call__ that overrides a documented one, a class docstring next to an inherited __call__ docstring and a blank one, a dataclass with a default whose repr raises, an undocumented method passed as Class.__call__, a self: T method and a self: Any module function assigned as a class attribute (both drop self), a dataclass with its own __init__, an undocumented NamedTuple, a class whose __doc__ is a property, a Class.method behind functools.lru_cache, and a @typing.no_type_check class and Class.method that take city: "CityName" and return an unknown "UnknownReturn". It checks the schema only, because before Python 3.13 the SDK registers an async partialmethod __call__ as sync. test_invalid_callable_class_tool checks the ValueError message for an undecorated function, a dynamic Activity, a class with no __call__, a zero-parameter function as __call__, keyword-only parameters, a partialmethod that binds an argument by keyword, **kwargs on a class and on a function, an annotation that can't be resolved, and an instance. test_callable_class_tool_on_python_314 (3.14 only) checks a dataclass whose forward reference resolves after the class is made, and the rejection of a bare functools.partial __call__. test_callable_class_tool_summary_from_class_docstring checks that a __call__ docstring with only :param city: or a Google Args: section gets the class summary, that a class docstring with only Args: is not used, that a section-only docstring (args: on __call__, Returns: on the class) gives no description when the class has no summary, and that a class docstring with only Parameters: gives way to an inherited __call__ docstring. test_callable_class_tool_activity_summary checks that a caller's summary= still labels the scheduled Activity when the description comes from the class docstring, and that a section-only docstring labels nothing. test_generic_tool_on_python_312 (3.12+) checks a generic __call__ and Class.method under postponed annotations, and test_method_tool_with_none_defaults checks that a method's context and aliased parameters with None defaults keep their types on Python 3.10.
    • ActivityWeatherService.get_weather_method now takes city: "CityName", so test_tool_workflow and the ToolsWorkflow replays cover the Class.method annotation resolution.
    • With eb0631e's activity_as_tool, on Python 3.10 and 3.14, 7 of the new or changed cases fail: both @no_type_check cases, with pydantic's PydanticUserError (CityName is not defined), and the five section-only cases, which show or schedule the section.
    • With f616f3a's activity_as_tool, on Python 3.10 and 3.14, the two caller-summary cases, the two Google Args: cases and both @no_type_check cases fail; on 3.14 the generic test and the lru_cache method fail too.
    • With 3fe1d75's activity_as_tool, the invalid-tool cases raise ApplicationError instead of ValueError, the __doc__ property raises AttributeError, the summary fallback gets '', and on Python 3.10 the context method raises UserError and the aliased one offers city. With b111f83's, the self: T method, the assigned self: Any module function and the dataclass with its own __init__ fail.
    • Locally, the full suite passes (434 passed, and the 3.14-only test is skipped on 3.13), the targeted tests and type checkers pass on 3.10, 3.12, 3.13 and 3.14, and make lint (ruff check --select I, ruff format --check, pyright, mypy, basedpyright, pydocstyle) passes. These ran in a cached environment with uv 0.13.1, outside the plugin's required-version, with UV_RUN pointed at it. CI covers make lint and make test.
    • [Bug] openai_agents: activity_as_tool builds a callable-class Activity's tool from its constructor #205's reproduction exits 1 on 1.1.0, on main at c664a34 and on temporalio.contrib.openai_agents in temporalio 1.33.0. On this branch the model is offered parcel_id and the Activity returns parcel P-1717 via acme-post.
    • Replay: tests/histories/tools-workflow-callable-class-history.json, recorded on this branch, has the model call ActivityWeatherClass (23 events), and test_replay replays it on Python 3.10, 3.12, 3.13 and 3.14. A version of it recorded with all three class tools (in e0e076a) failed on main's activity_as_tool with [TMPRL1100], while tools-workflow-history.json replayed.
    • A History recorded on main from a ToolsWorkflow run whose model called the class tool fails on this branch with [TMPRL1100] Nondeterminism error: Activity type of scheduled event 'ActivityWeatherClass' does not match activity type of activity command 'invoke_model_activity'. Earlier checks on a gated version of this change, with Workers with no Workflow cache, covered a class tool built in Workflow code and one built at import time, each for one and two turns around a held Activity, and a function tool as a control. Without the gate, all eight main histories with a class tool failed with [TMPRL1100], and the two function-tool histories replayed.
  3. Any docs updates needed?
    The activity_as_tool docstring is updated here. Release notes should say which runs stop replaying (see "Breaking change").

Not covered:

  • A functools.partialmethod __call__ runs only as far as the SDK supports it. The SDK registers an async one as sync before Python 3.13, and it reads no argument types for it (arg_types == [None]), so arguments that aren't JSON primitives are not converted.
  • The SDK's _type_hints_from_func skips a first parameter only when it is named self and is unannotated or annotated with text typing.Self. For __call__(this, loc: Loc), self: Self under from __future__ import annotations, self: T, self: "Svc" or typing_extensions.Self on 3.10, the Worker decodes the other arguments without their types. With this PR's string-annotation support, self: Self under postponed annotations builds a tool where main failed with NameError. That is the SDK's, also affects workflow.execute_activity_class and execute_activity_method, and is filed as [Bug] An activity method with an annotated self receives its arguments without their types sdk-python#2063.
  • An Activity's *args are passed, as on main for functions. With *args, the SDK reads no argument types, so the Worker decodes every argument without its type: a dataclass parameter next to *tags reaches the Activity as a dict. Deep Agents rejects *args and Google ADK leaves them out of the tool; [Bug] deepagents, google_adk: activity_as_tool can't pass an Activity's *args #390 asks both to pass them as this plugin does.
  • Not changed here: function_schema doesn't get the caller's strict_json_schema.
  • Inferred, not run: when the constructor's schema cannot be built (a constructor that takes a client object), building the tool failed in Workflow code before this change. A Workflow that caught that error and offered another tool now builds the class tool instead, so a run that took that path before the upgrade can fail replay.
  • temporalio 1.34.x still bundles the old code as temporalio.contrib.openai_agents. No backport here.

Open questions:

  • Should temporalio 1.34.x get a backport?

Loading
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] openai_agents: activity_as_tool builds a callable-class Activity's tool from its constructor

3 participants