Repository navigation
Breaking: support method and callable-class Activities in Strands Agents activity_as_tool - #402
Conversation
…nts activity_as_tool activity_as_tool built the tool from inspect.signature of the object it was given. A callable-class Activity passed as its class offered the model its constructor's parameters, whose values reached __call__, and a method passed as Class.method failed every call because the binding kept self. Build a class's tool from __call__ as an instance binds it, with __call__'s types and docstring, and drop a first self parameter from the binding. Raise ValueError for a class whose __call__ can't be used or takes *args, keyword-only arguments or **kwargs, and for a callable-class instance. Breaking: classes whose constructor matched __call__ and whose __call__ takes such parameters, or a parameter with no JSON schema, now fail when the tool is built. Runs recorded before this change that called a Class.method tool, or a class tool whose constructor differs from __call__, fail replay. Part of #278
|
Scope decision for this PR: keep it to the minimal fix. Dropped on purpose, so please don't re-add them in later rounds:
The cases those handled are listed as Caller-breaking by decision in the PR body. |
DABH
left a comment
There was a problem hiding this comment.
Review at head 7714e96 (six commits on 9d6f9ff; main has not touched python/strands_agents since, and the branch merges cleanly with main at 52bcb2b). On a worktree at the head, make lint is clean and make test passes 228 of 228 on Python 3.14.3 and on 3.10.20 (temporalio 1.34.0, strands-agents 1.56.0); CI is green on all four cells. I compared main's and the head's activity_as_tool by probe on 3.10 and 3.14 over about 100 function, method and class shapes, including what the Worker's registered instance or bound method then receives. I also recorded nine runs with real Workers on the pinned dev server on each build and replayed each build's histories on the other, ran the head's new tests against main's build, and ran ten one-line mutations of _temporal_activity_tool.py against the tool tests. Every finding below was reproduced. Checked and fine: self: Self under from __future__ import annotations, on a method and on __call__, and self: T, on 3.10 (with typing_extensions.Self) and 3.14; the staticmethod, classmethod and positional partialmethod forms of __call__, and a partialmethod that binds by keyword is refused with the sentence that names it; instances are refused with ValueError (main never built one); generated dataclass and namedtuple docstrings are skipped, and library docstrings (abc.ABC, typing.Generic) no longer become the description, as they did on main; dict[str, Any] and Mapping[str, str] parameters on __call__ build and pass the model's object; a PEP 695 __call__[T] with and without postponed annotations on 3.14; a Class.method behind functools.lru_cache or a class-based decorator, and functools.wraps or wrapt on __call__; dataclass and namedtuple class tools built inside the Workflow sandbox; summary= reaches every scheduled Activity unchanged, since nothing shadows it; and on 3.10 the implicit Optional from typing.get_type_hints gives a class tool the same schema Strands gives a function with the same parameter, because Strands reads the resolved hints only for string annotations. Nothing in Strands' runtime (registry, executors, hooks, interrupts, concurrent tools) sees the stand-in, which only builds the spec. The cases your scope comment leaves out (the staticmethod self lookup, agent and cls, _-prefixed names, eager nested forward references) behave as the body lists, and I haven't re-raised them. Not verified: the body's carries of held runs and its replays of e918c4e histories.
Severity: P1 = wrong result or stuck run in realistic use; P2 = correctness or robustness in an edge case; P3 = docs, tests, cleanup.
Replay. The break is the disclosed one, in both directions. Main's histories on the head: a method tool, a positional-only function, and TrackParcel(carrier) called either with the constructor's arguments (main scheduled track_parcel with ["rail"] and the Worker answered parcel rail via acme-post, the #278 wrong result) or with __call__'s (main returned the bind error to the model) fail with [TMPRL1100], for example Activity type of scheduled event 'invoke_model' does not match activity type of activity command 'track_parcel'. A function tool, a class whose constructor and __call__ take the same parameter, and a class tool that was built but never called all replay. A run that only built a class whose __call__ takes a keyword-only argument fails its Workflow Task with the new ValueError, as the Breaking change section says. The head's histories on main fail for the same four shapes and replay for the rest, as the rollback sentence says. The body explains only the constructor-shaped call ('the class call's recorded arguments, the constructor's, no longer bind'). A call with __call__'s arguments, which main failed before scheduling, now schedules, but the drain rule ('whose model called ... a callable-class tool whose constructor parameters differ') already covers it. No version gate, per the stated policy.
Parity with #206, #300 and #312 on main. The class branch is their code: the __get__ binding, the four __call__ forms, the docstring order, the gated 3.14 dataclass check and the partialmethod sentence. The method branch drops self by name, as #206 and #300 do (#312 also checks that the function sits in a class body). Instances are refused, as in #206 and #300 (#312 accepts them by design). Every refusal is a ValueError, which fails the Workflow Task, as in all three: with a real Worker, a run that builds a class whose __call__ takes a keyword-only argument stays open with that Task failure. Three fixes #206 made in its later rounds are missing here, as they are from #300's and #312's copies. Two are inline: the non-string __doc__ check, and the handling of a docstring with no summary, which matters more here because Strands hides an Args: section. The third is skipping the return annotation when resolving __call__'s types. Only a partialmethod __call__ whose return type is imported under TYPE_CHECKING shows it: the head refuses that class as unreadable, while the SDK registers it (arg_types [None]) and an instance call runs. Main built it with no parameters, so nothing that worked breaks. The SDK-side partialmethod limits that #206's docstring states also hold here, unmentioned, as in #300 and #312: the Worker decodes the arguments without types, and an async one is registered as sync before Python 3.13 (is_async is False on 3.10 and 3.12, True on 3.13 and 3.14). One difference is new: *args and **kwargs are refused only in __call__ (inline). On 3.10 there is nothing to match, since #300 and #312 require 3.11+ and here class and function tools get the same schema. TypeScript's activityAsTool takes a registered name and an explicit schema, so it has no class form.
Where the problems cluster: the binding is right for every form the PR names, and the replay break matches the body. What is left sits in the parts copied from the siblings before their later fixes (descriptions, and the *args/**kwargs rule for functions), in tests that pin none of the description or descriptor behaviour, and in the docs.
Approving: there is no P1 or P2, CI is green, and the replay break is the disclosed one in both directions; everything below is non-blocking.
Outside the diff (all P3, non-blocking)
python/strands_agents/README.md:389: the Tools section shows only function activities, and nothing a user reads mentions the replay break. Release notes come from commit subjects only (scripts/release/release_tool.py:456), and this README already documents other replay breaks the same way (lines 80, 115, 121, 675 and 677). Two or three sentences would do. Pass a method asClass.methodand register the bound method on the Worker, or pass a callable-class activity as its class and register an instance. An instance, or a__call__that takes*args, keyword-only arguments or**kwargs, raisesValueError, and parameters namedagentorclsare not offered. Runs whose model called a method tool, or a class tool whose constructor's parameters differ from__call__'s, fail replay after the upgrade, so let them finish first or use Worker Versioning.- PR body, How was this tested: on main the first
ship_parcelcall (P-3) is scheduled, becauseShipParcel's constructor takesparcel_id; only theP-4call, which addscarrier, fails before scheduling. 'the instance raisesTypeError' holds on 3.10 for a class without class-level annotations; on 3.14, or with class-level annotations, main raisedAttributeError: 'TrackParcel' object has no attribute '__name__'from Strands.
| stand_in.__annotations__ = hints | ||
| # __call__'s own docstring, else the class's, else that of a __call__ it | ||
| # inherits. | ||
| stand_in.__doc__ = ( |
There was a problem hiding this comment.
P3 (non-blocking): the class docstring is applied whole, so an Args:-only __call__ docstring hides the class's description, and a class docstring that documents the constructor describes __call__'s parameters. Strands leaves Args sections out of the description and falls back to func.__name__ (_extract_description_from_docstring in strands/tools/decorator.py). docstring_parser, which supplies the parameter descriptions, reads a leading Args: as the summary and finds no parameters. Probes on 3.10 and 3.14:
- A class documented 'Track a parcel through the carrier network.' whose
__call__(self, parcel_id: str)docstring holds onlyArgs:/parcel_id: The parcel to track.is described as'ArgsOnlyCall2', andparcel_idas 'Parameter parcel_id'. Main used the class docstring, next to the constructor's schema. - A class whose docstring is 'Ship parcels with a fixed carrier.' plus
Args:for its constructor'sparcel_idandcarrieroffers__call__(self, parcel_id)withparcel_iddescribed as 'The default parcel used when the activity is constructed.' - A class documented only
Args:/carrier: ...that inherits a__call__documented 'Quote shipping for a parcel.' is described as its class name, as on main, although the body's order promises the inherited docstring.
A Strands function tool with an Args:-only docstring is also described by its name, so only the precedence is new; #206 handles the first and third cases. Fix, verified on a patched copy on both versions: have _class_doc return only the text before the class docstring's first Args header (Strands strips args:, arguments:, parameters:, param: and params:), or None if there is none, through a small _description(doc) helper. Then put that text in front of a __call__ docstring that has none of its own:
own = _docstring(_call_function(vars(cls).get("__call__")))
class_doc = _class_doc(cls) # the text before the class docstring's Args section
if own is not None and class_doc is not None and _description(own) is None:
own = class_doc + "\n\n" + inspect.cleandoc(own)
stand_in.__doc__ = (
own
or class_doc
or next(filter(None, map(_docstring, map(_call_function, calls))), None)
)That gives 'Track a parcel through the carrier network.' with parcel_id described as 'The parcel to track.', 'Parameter parcel_id' in the constructor case, and 'Quote shipping for a parcel.' in the inherited case. The other 13 shapes I ran keep their descriptions. A class docstring whose Args: documents __call__'s parameters would lose them; __call__'s own docstring is the place for those.
There was a problem hiding this comment.
Thanks, fixed in 0981d9d. _class_doc now returns only the text before the class docstring's Args section, and a __call__ docstring with only an Args section gets that text in front. DescribeParcel in test_tool pins your first two cases: it's described as "Track a parcel through the carrier network.", and parcel_id as "The parcel to track.", not the constructor's text. On 7714e96 it was described as DescribeParcel.
| def _docstring(fn: Any) -> str | None: | ||
| """Return ``fn``'s docstring, unless it is missing or blank.""" | ||
| doc = getattr(fn, "__doc__", None) if fn is not None else None | ||
| return doc if doc and doc.strip() else None |
There was a problem hiding this comment.
P3 (non-blocking, contrived): a class whose __doc__ isn't a string makes _docstring raise a raw AttributeError from Workflow code, where main built the tool. @activity.defn class DocProperty with __doc__ = property(lambda self: "per-instance doc") and an undocumented __call__(self, parcel_id: str) raises AttributeError: 'property' object has no attribute 'strip' on 3.10 and 3.14. That fails the Workflow Task with a raw error instead of the documented ValueError. Main built the tool, because inspect.getdoc ignores a __doc__ that isn't a string. #206 checks isinstance(doc, str) here; #300's and #312's copies don't. Fix: return doc if isinstance(doc, str) and doc.strip() else None, which builds the tool, described as 'DocProperty' (verified).
| # @activity.defn checks the constructor's signature, not __call__'s, so | ||
| # __call__ can take *args, keyword-only arguments or **kwargs, which the | ||
| # tool can't pass: it sends one argument per parameter, by position. | ||
| for p in signature.parameters.values(): |
There was a problem hiding this comment.
P3 (non-blocking, pre-existing, parity): *args and **kwargs are refused only in __call__, so a function or Class.method activity that takes them still gets a tool that can't work, and the body's parity sentences don't match #312 and #300. The reason in the comment above (one argument per parameter, by position) holds for every form.
@activity.defn async def fn_star_args(first: str, *rest: str)builds a tool that offersrestas a required string. A call that fills it fails instreamwithgot an unexpected keyword argument 'rest', which goes back to the model.fn_kwargs(first: str, **extra: str)offersextraas a required string.{"first": "a"}schedules["a", {}], becauseapply_defaultsadds the empty dict andstreampasses it by position. With a real Worker every attempt fails withfn_kwargs() takes 1 positional argument but 2 were given, and the default retry policy retries it indefinitely.
Both behave this way on main, so neither is a regression. But #300 refuses *args, keyword-only arguments and **kwargs for every form, and #206 refuses **kwargs for every form. The body says 'Like #312, *args, keyword-only arguments and **kwargs are refused only in a class's __call__', but #312 refuses only keyword-only arguments and **kwargs there. It also says 'Like #300, *args is refused too', but #300 refuses it for functions as well. Fix, verified on a patched copy: check params for VAR_POSITIONAL and VAR_KEYWORD in __init__, after the self drop, for every form. Both functions then raise ValueError, and every other shape builds as before (keyword-only parameters can't reach a function, since @activity.defn rejects them). A run that merely builds such a function tool would then fail its Workflow Task, so it needs a line under Breaking change. If you'd rather keep the scope, correct the two parity sentences instead.
There was a problem hiding this comment.
Agreed, the same reason holds for every form. It fails the same way on main, though, and refusing it for functions and Class.method would widen this PR past the defect, so per the scope decision I'm leaving it for a follow-up. I corrected the two parity sentences in the body: #312 refuses only keyword-only arguments and **kwargs in __call__, and #300 refuses all three for every form.
| (["P-7"], "weigh P-7 with WeighParcel"), | ||
| ] | ||
|
|
||
| cases: list[tuple[Callable[..., Any], list[str], list[str]]] = [ |
There was a problem hiding this comment.
P3 (non-blocking, tests): the tests pin the offered properties and the scheduled arguments, but none of the description order, the generated-docstring filter, the staticmethod and partialmethod forms, the refusals for a missing __call__ or for the partialmethod keyword case, or resolving __call__'s types in its own module. With six one-line mutations of _temporal_activity_tool.py applied together, test_tool.py, test_tool_errors.py and test_interrupt_exception.py still pass (12 of 12). The six: no staticmethod unwrapping in _call_function, the generated dataclass docstring kept, the class docstring ahead of __call__'s, stand_in.__annotations__ = {}, include_extras dropped, and the partialmethod sentence removed. Four more, applied together, also leave test_tool.py green (5 of 5): taking the last __call__ in the MRO instead of the first (every test class defines its own), converting positional-only parameters for classes only (the body's positional-only function claim has no test), if func is None and calls: (a class without __call__ then raises IndexError), and narrowing the except Exception around the reflection. Two of the first six matter only under from __future__ import annotations, which no test module uses. With stand_in.__annotations__ = {}, a class whose __call__ takes a module-local dataclass fails with PydanticUserError: ... you should define Parcel. Without include_extras, an Annotated[str, "The city"] parameter loses its description. Smallest additions:
tool_spec["description"]assertions for a class with its own__call__docstring, an undocumented dataclass, and a dataclass that inherits a documented__call__;- rows here for a staticmethod
__call__, a positionalpartialmethod(['passengers', 'currency']forpartialmethod(_quote, "SFO")) and a subclass that inherits__call__; - a positional-only function in
test_tool; - a class without
__call__and a keyword-bindingpartialmethodintest_activity_as_tool_refuses; - one class in a small postponed-annotations module whose
__call__takes a dataclass defined there.
There was a problem hiding this comment.
Added in 0981d9d, as tool-spec rows in test_tool (properties, required and description) plus two refusals:
- descriptions for the Args-only
__call__docstring with a class description, an undocumented dataclass that inherits a documented__call__(generated docstring skipped), and a non-string__doc__; - a staticmethod
__call__, a positionalpartialmethod(['destination', 'parcel_id']), and the inherited__call__above; - a positional-only function, run through the agent;
- a class without
__call__and a keyword-bindingpartialmethodintest_activity_as_tool_refuses; LoadParcelsintests/postponed_activities.py, a postponed-annotations module, whose__call__takes a dataclass defined there.
I didn't add rows for include_extras, the MRO order or the narrowed except.
Give a __call__ docstring with only an Args section the class's description, and use only the text before the class docstring's Args section, which documents the constructor. Ignore a __doc__ that isn't a string. Pin the description order, the generated-docstring filter, the staticmethod and partialmethod forms, a positional-only function, the missing-__call__ and keyword partialmethod refusals, and types resolved in __call__'s module. Document the class and method forms and the replay break in the README.
|
Thanks for the thorough review. Summary items:
|
What was changed
activity_as_toolinstrands_agentsnow builds the tool from the parameters the Activity is called with:__call__as an instance binds it (without the receiver of a method, classmethod orfunctools.partialmethod, with every parameter of a staticmethod), not from the constructor.__call__'s annotations are resolved in its own module. The description is__call__'s own docstring, else the class's (unless dataclasses or namedtuple wrote it), else that of a__call__it inherits. Only the text before the class docstring's Args section is used, since that section documents the constructor, and a__call__docstring with only an Args section gets that text in front. The tool keeps the Activity's name.Class.method, a first parameter namedselfis dropped from the binding, as Breaking: build callable-class activity tools from__call__and raise ValueError for tools that can't be built in OpenAI Agents #206 and Breaking: support method and callable-class Activities in Deep Agents activity_as_tool #300 do. Strands already leftselfout of the tool spec, so every call failed withmissing a required argument: 'self'.__call__takes positional-only parameters worked onmainthrough its constructor's parameters, so the class change needs this. Function Activities with positional-only parameters, whose calls failed before scheduling onmain, now work too.ValueErrorwhen the tool is built:__call__is missing or of another kind, can't be read, or takes*args, keyword-only arguments or**kwargs.@activity.defnchecks a class's constructor, not its__call__, and the tool passes one argument per parameter, by position;TypeErrorfromtyping.get_type_hintsbefore.This is the design of #206 (
openai_agents), #300 (deepagents) and #312 (google_adk), with their helpers' code and messages.*args, keyword-only arguments and**kwargsare refused only in a class's__call__: #312 refuses keyword-only arguments and**kwargsthere, and #300 refuses all three for every form.*argsis refused because Strands makes it a required property that the binding can't take by name. Function andClass.methodActivities that take*argsor**kwargsfail onmaintoo; refusing them is left for a follow-up. Like #206 and #300, an instance is refused. No public name or option changes.Breaking change. The change has no version gate: we are not adding version gates to these fixes, and breaking old histories is accepted with the plugins' 1.0 releases.
__call__worked, because the model's values happened to reach the right place. If its__call__also takes a keyword-only parameter,*argsor**kwargs,activity_as_toolnow raisesValueError. If it takes an optional parameter whose type has no JSON schema, such asclient: Client | None = None, Strands now fails to build the tool spec (PydanticSchemaGenerationError). In a Workflow, both fail the Workflow Task. Change__call__, or wrap it in a function Activity with the same name, in the same deployment as the upgrade.Class.method, whose first parameter is namedselfand has a default worked with that default. The tool now dropsselfby name, so the model's first argument reachesself. Rename the parameter.__call__takes_-prefixed parameter names, or forward references such asList["Parcel"], worked only because the tool used the constructor's annotations. Strands now fails to build the tool spec, as it does for a function with those parameters. Rename the parameters, or write the type itself instead of a string.agentorcls, orselfin a staticmethod__call__, stay unsupported, as in Strands' own@tool, which leaves these names out of the spec.Class.methodtool, or a callable-class tool whose constructor parameters differ from__call__'s, fail replay with[TMPRL1100]. Rolling back fails the same kinds of runs recorded on this change, and runs whose model filled a parameter only__call__has. The method call failed before scheduling an Activity and now schedules one; the class call's recorded arguments, the constructor's, no longer bind, and a class call with__call__'s arguments, which failed before scheduling, now schedules. Likewise, a call that failed before scheduling because a parameter was positional-only now schedules its Activity. Let those runs finish before upgrading, or keep them on the old version with Worker Versioning.Why?
See #278.
activity_as_toolreadinspect.signatureof the object it was given. A callable class passed as its class offered the model its constructor's parameters, and their values reached__call__: with a one-string constructor and a one-string call, the run completed with a wrong result and no error. A method passed asClass.methodfailed every call before its Activity was scheduled.Checklist
Part of [Bug] deepagents, google_adk, google_genai, strands_agents:
activity_as_toolbuilds a callable-class Activity's tool from its constructor #278: this fixes itsstrands_agentspart.deepagentsandgoogle_adkare fixed;google_genaihas its own PR.How was this tested:
test_toolnow also gives the agent a callable class (TrackParcel(carrier)with__call__(parcel_id)) passed as its class, a method passed asClass.method, a class whose__call__takes positional-only parameters (parcel_id, carrier="road", /, with a constructor takingparcel_id), a class whose__call__is a classmethod, and a function with a positional-only parameter. It checks each tool's offered and required properties and description, and each Activity's arguments and result from the history. It also builds tools for a class with a constructor-documenting class docstring and an Args-only__call__docstring, an undocumented dataclass that inherits a documented__call__, a class whose__doc__isn't a string, a staticmethod__call__, a positionalpartialmethod__call__, and a class in a postponed-annotations module whose__call__takes a dataclass defined there. Onmainthe class and method Activities, and theship_parcelcall that addscarrier, are not scheduled (At index 6 diff: 'invoke_model' != 'track_parcel'). On this PR's first revision (e918c4e) neithership_parcelcall is scheduled (At index 10 diff: 'invoke_model' != 'ship_parcel'). On7714e96, the Args-only class is described by its name and the non-string__doc__raisesAttributeError.test_activity_as_tool_refuseschecks theValueErrorfor__call__with a keyword-only parameter,*argsand**kwargs, for a class without__call__, for apartialmethodthat binds by keyword, and for an instance. Onmainthe three__call__classes build a tool, and the instance raisesTypeError(on Python 3.14, or with class-level annotations,AttributeErrorfrom Strands).make lintandmake testpass locally in Docker with Python 3.13 (230 passed).Replayer: Workers with no Workflow cache recorded, onmainand on this branch, a finished run and a run held between two agent turns for five tools: a function, a callable class whose constructor takes the same parameter as__call__, a method, a callable class whose constructor differs, and a class whose__call__takes positional-only parameters. The scripted model fills the offered schema.e918c4e.mainhistories on this branch: the method ones fail with[TMPRL1100] ... scheduled event 'invoke_model' does not match activity type of activity command 'shipping-track', the class ones with... 'shipping-quote' does not match ... 'invoke_model'; the function, matching-class and positional-only ones replay.main(the rollback target): the method and class ones fail with[TMPRL1100], and so do the positional-only ones, whose model filledcarrier, whichmaindoesn't offer; the others replay.[TMPRL1100].[TMPRL1100]when carried in either direction. A held positional-only run completes on a replacement Worker and when carried frommainto this branch, and stops with[TMPRL1100]when carried back tomain.['parcel_id']for the class with this change (['carrier']onmain). The defect's end-to-end reproduction, with a scripted model: onmainand on 0.1.0 the class tool sent the model'scarriervalue asparcel_id, the method tool scheduled nothing, a class whose constructor takes a client object failed its Workflow Task, and one with a two-string constructor failed every attempt; with this change all four complete with the model'sparcel_id.Any docs updates needed? The README's Tools section now covers the method and class forms, the refusals and the replay break, and the
activity_as_tooldocstring names the accepted forms and theValueErrors.Decisions:
ValueErrorrefusals of*args, keyword-only arguments,**kwargsand instances, as Breaking: build callable-class activity tools from__call__and raise ValueError for tools that can't be built in OpenAI Agents #206, Breaking: support method and callable-class Activities in Deep Agents activity_as_tool #300 and Breaking: support method and callable-class Activities in Google ADK activity_as_tool #312 do; thegoogle_genaiPR Breaking: build Google GenAI callable-class activity tools from__call__, not the constructor #404 is being changed to match.selflookup, the spec layer foragent,cls,_-prefixed names and forward references, and thepydanticdependency were dropped. The cases they handled are listed as breaking above.