Repository navigation
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 intoNov 3, 2026
Conversation
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
What was changed
activity_as_toolnow builds a callable-class Activity's tool from its__call__, not from its constructor.__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:orRaises:, 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 NumPyParameterssection or a GoogleArgs: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 orfunctools.partialmethodover 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, keepingAnnotatedmetadata, so string annotations andfrom __future__ import annotationswork. As withtyping.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_checkfunction whose return type can't be resolved still builds. Methods passed asClass.methodnow get the same resolution; before, a string annotation failed withNameError. They drop a first parameter namedselfhowever it is annotated, as onmain: the Worker registers the method bound to an instance, even when it is a module function assigned as a class attribute.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 raiseValueErrortoo; before, they raised anApplicationErrorthat failed the run.fndocstring now names the three forms and the SDK'spartialmethodlimits.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 orClass.methodtools 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 theValueErrorbullet 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.maindocumented them asApplicationError, so code that catchesApplicationErroraroundactivity_as_toolno longer catches them. A run on the earlier version that caught one, for example to offer another tool, fails replay with theValueError. 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 asdict[str, Any]or aMapping, or keyword-only or**kwargsparameters, or anything elsefunction_schemarejects for a function with the same parameters, or when__call__is not a function, or a staticmethod, classmethod orfunctools.partialmethodover a function. A function orClass.methodtool that takes**kwargsalready failed with the Agents SDK'sUserError; 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 withactivity_as_toolin a test on the new version. Other function andClass.methodtools offer the same parameters as before. As before, a first parameter namedselfis never offered to the model, so a module-function activity that takes a realselfargument 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_classdoes, butactivity_as_toolbuilt the tool frominspect.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 withTypeError.Checklist
Closes [Bug] openai_agents:
activity_as_toolbuilds a callable-class Activity's tool from its constructor #205How was this tested:
test_tool_workflowintests/test_openai.pygains a callable-class Activity,ActivityWeatherClass(constructor takesconditions,__call__takescity: "CityName", a string naming a module-level alias), passed toactivity_as_toolas its class and registered asActivityWeatherClass("Cloudy"). The test now also checks that the class's Activity is scheduled with the model'scity.mainatfc2da34it fails the Workflow Task withNameError: name 'CityName' is not definedwhile building the method tool, then times out.tools-workflow-history.jsonfail withNameError: name 'CityName' is not defined.test_callable_class_tool_schemachecks the schema and description for a@staticmethod __call__(self: str)on anabc.ABCsubclass and a@classmethod __call__(cls, self: str)(both offerself), a__call__set withfunctools.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 whosereprraises, an undocumented method passed asClass.__call__, aself: Tmethod and aself: Anymodule function assigned as a class attribute (both dropself), a dataclass with its own__init__, an undocumentedNamedTuple, a class whose__doc__is a property, aClass.methodbehindfunctools.lru_cache, and a@typing.no_type_checkclass andClass.methodthat takecity: "CityName"and return an unknown"UnknownReturn". It checks the schema only, because before Python 3.13 the SDK registers an asyncpartialmethod__call__as sync.test_invalid_callable_class_toolchecks theValueErrormessage for an undecorated function, a dynamic Activity, a class with no__call__, a zero-parameter function as__call__, keyword-only parameters, apartialmethodthat binds an argument by keyword,**kwargson 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 barefunctools.partial__call__.test_callable_class_tool_summary_from_class_docstringchecks that a__call__docstring with only:param city:or a GoogleArgs:section gets the class summary, that a class docstring with onlyArgs: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 onlyParameters:gives way to an inherited__call__docstring.test_callable_class_tool_activity_summarychecks that a caller'ssummary=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__andClass.methodunder postponed annotations, andtest_method_tool_with_none_defaultschecks that a method's context and aliased parameters withNonedefaults keep their types on Python 3.10.ActivityWeatherService.get_weather_methodnow takescity: "CityName", sotest_tool_workflowand theToolsWorkflowreplays cover theClass.methodannotation resolution.eb0631e'sactivity_as_tool, on Python 3.10 and 3.14, 7 of the new or changed cases fail: both@no_type_checkcases, with pydantic'sPydanticUserError(CityNameis not defined), and the five section-only cases, which show or schedule the section.f616f3a'sactivity_as_tool, on Python 3.10 and 3.14, the two caller-summary cases, the two GoogleArgs:cases and both@no_type_checkcases fail; on 3.14 the generic test and thelru_cachemethod fail too.3fe1d75'sactivity_as_tool, the invalid-tool cases raiseApplicationErrorinstead ofValueError, the__doc__property raisesAttributeError, the summary fallback gets'', and on Python 3.10 the context method raisesUserErrorand the aliased one offerscity. Withb111f83's, theself: Tmethod, the assignedself: Anymodule function and the dataclass with its own__init__fail.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'srequired-version, withUV_RUNpointed at it. CI coversmake lintandmake test.activity_as_toolbuilds a callable-class Activity's tool from its constructor #205's reproduction exits 1 on 1.1.0, onmainatc664a34and ontemporalio.contrib.openai_agentsintemporalio1.33.0. On this branch the model is offeredparcel_idand the Activity returnsparcel P-1717 via acme-post.tests/histories/tools-workflow-callable-class-history.json, recorded on this branch, has the model callActivityWeatherClass(23 events), andtest_replayreplays it on Python 3.10, 3.12, 3.13 and 3.14. A version of it recorded with all three class tools (ine0e076a) failed onmain'sactivity_as_toolwith[TMPRL1100], whiletools-workflow-history.jsonreplayed.mainfrom aToolsWorkflowrun 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 eightmainhistories with a class tool failed with[TMPRL1100], and the two function-tool histories replayed.Any docs updates needed?
The
activity_as_tooldocstring is updated here. Release notes should say which runs stop replaying (see "Breaking change").Not covered:
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._type_hints_from_funcskips a first parameter only when it is namedselfand is unannotated or annotated with texttyping.Self. For__call__(this, loc: Loc),self: Selfunderfrom __future__ import annotations,self: T,self: "Svc"ortyping_extensions.Selfon 3.10, the Worker decodes the other arguments without their types. With this PR's string-annotation support,self: Selfunder postponed annotations builds a tool wheremainfailed withNameError. That is the SDK's, also affectsworkflow.execute_activity_classandexecute_activity_method, and is filed as [Bug] An activity method with an annotatedselfreceives its arguments without their types sdk-python#2063.*argsare passed, as onmainfor functions. With*args, the SDK reads no argument types, so the Worker decodes every argument without its type: a dataclass parameter next to*tagsreaches the Activity as a dict. Deep Agents rejects*argsand Google ADK leaves them out of the tool; [Bug] deepagents, google_adk:activity_as_toolcan't pass an Activity's*args#390 asks both to pass them as this plugin does.function_schemadoesn't get the caller'sstrict_json_schema.temporalio1.34.x still bundles the old code astemporalio.contrib.openai_agents. No backport here.Open questions:
temporalio1.34.x get a backport?