Repository navigation
Breaking: support method and callable-class Activities in Google ADK activity_as_tool - #312
Conversation
…activity_as_tool activity_as_tool built the tool from the signature of the object it was given. A method passed as Class.method asked the model for self, and a callable class passed as its class offered its constructor's parameters, whose values then reached __call__. The tool now drops a method's self the way the SDK does, and builds a class's tool from __call__ as an instance binds it, with __call__'s types and docstring. A class whose __call__ can't be read or takes keyword-only arguments or **kwargs fails when the tool is built. Runs that called a method or callable-class tool before this change fail replay with [TMPRL1100].
DABH
left a comment
There was a problem hiding this comment.
Review at head 4ead9a6 (four commits on db14ec3; main has not touched python/google_adk since). On a worktree at the head: make lint is clean and make test gives 173 passed, 5 skipped (Python 3.14.3, temporalio 1.34.0, google-adk 2.12.0); CI is green. Every finding below was reproduced with a probe against the installed head and main builds, through ADK's FunctionTool and InMemoryRunner with a scripted model. I re-ran the replay claims at the head, since the body's matrix dates from 5cbb334: real Workers on the pinned dev server recorded 19 tool scenarios on each version, each version replayed the other's histories, a main Worker was swapped for a head Worker mid-run, and every ActivityTaskScheduled event was compared byte for byte. A pass of single-line mutations over workflow.py checked what the new tests pin. Checked and refuted: any change in name, description, schema or scheduled bytes for function, bound-method, staticmethod and callable-instance tools (two independent probe sets on both ADK declaration paths, plus the replay byte comparison; only the disclosed positional-only binding differs); _is_method misclassifying realistic code (functools.wraps decorators from other modules, dataclass(slots=True), attrs, Generic and PEP 695 classes, private nested classes, methods inherited across modules, wrapt; 3.14, and the class branch also on 3.11); classification changing with module placement or runner outside the fallback case below; positional-only runs stuck on main needing manual action (they complete after the swap); unresolvable __call__ annotations as a new break (@activity.defn already rejects them). Nothing material was left unverified.
Severity: P1 = wrong result or stuck run in realistic use; P2 = correctness or robustness in an edge case; P3 = docs, tests, cleanup.
Where the problems cluster: the main paths are right and well covered. Method and class tools now offer what the Worker's instance runs, the replay break is exactly the one the body describes, and the unchanged forms schedule byte-identical commands. What is left sits at the edges of the new code: the receiver check reads the annotation's text, so self: Self under PEP 563 slips through; the class lookup has a sys.modules fallback whose answer depends on the runner; the Breaking change list misses one class shape; the callable-instance branch the PR keeps on purpose still resolves nothing; and local runs, the README and the tests lag behind the new forms.
Approving: there is no P1 and nothing that should block the merge (the three P2s are edge cases or a body edit), CI is green, and the replay break is the disclosed one.
Replay, at the head: histories recorded on main replay on the head, and the head's replay on main, for function, bound-method, staticmethod with self, module-level function with self, callable-instance, tool_context function and instance, a class whose constructor and __call__ take the same parameter, a class with no parameters, and a function tool called next to a method tool the model never called. Method tools called without self and classes called with constructor arguments fail with the disclosed [TMPRL1100] in both directions. A positional-only run stuck on main completed after the Worker swap. Three additions for the body: (1) the 'not checked' case, where the model filled self, replays on the head but never recovers. The server keeps retrying the recorded two-argument input (attempt 6 still failed with takes 2 positional arguments but 3 were given after the swap), so those runs need a reset to before the model call, or termination; draining does not apply. (2) A staticmethod with self in a function-local class, which the body lists under Breaking change, also stops replaying, because its tool now raises at build. (3) Rolling a run that used a positional-only tool back to main fails its Workflow Task again (missing a required positional-only argument). No version gate, per the stated 1.0 policy.
Open questions. Instances: I'd keep accepting them, since they work today and replay. The tool name wrapper is a hazard of its own, though (pre-existing): two instance tools given to one Agent are both declared as wrapper, and ADK dispatches every call to the last one. A model asked to quote got cancelled P-1 from the second tool, on main too. Naming them after the Activity definition would fix it, with the same kind of replay note as this PR. Errors: I'd keep ValueError, as on #300. A tool that can't be built is a code defect; a Workflow Task failure lets in-flight runs continue once the fix is deployed, whereas an ApplicationError raised from Workflow code fails them for good. #206 should match whichever you pick.
PR body: 'Draft while the breaking change and these questions are open' is stale, since the PR is ready for review. The repository squashes with the PR title and an empty body, and release-notes reads subjects only, so the Breaking change and Upgrade text has to be pasted into the release draft by hand. The 'Not covered' note on activity_node holds, and not just likely: activity_node(Tracker.route) fails with missing required input key(s) ['self'], and a class with a two-argument constructor is read from the constructor. Cross-language: Go's ActivityAsTool requires func(context.Context, TArgs), so a method expression fails at construction while method values work, and TypeScript's takes a registered name and an explicit schema. This PR therefore leaves no Google ADK language inconsistent; google_genai and strands_agents keep the class bug (#278), as disclosed.
| and params[0].name == "self" | ||
| and ( | ||
| params[0].annotation is inspect.Parameter.empty | ||
| or str(params[0].annotation) == "typing.Self" |
There was a problem hiding this comment.
P2 (non-blocking): a method annotated self: Self in a module with from __future__ import annotations keeps self in the tool, so the model can never call it. Under PEP 563 the annotation is the string 'Self', so this compares 'Self' == 'typing.Self' and the receiver stays. Probe with class Tracker: @activity.defn async def track(self: Self, parcel_id: str) passed as Tracker.track: without the future import the tool offers ['parcel_id']; with it the tool keeps ['self', 'parcel_id'] and ADK declares a self-referencing required object, {"$defs": {"trackParams": {"properties": {"self": {"$ref": "#/$defs/trackParams"}, ...}, "required": ["self", "parcel_id"]}}}. The model then gets mandatory input parameters are not present: self, or fills it and every attempt fails with track() takes 2 positional arguments but 3 were given. Main is just as broken, so this is not a regression, but the body and docstring say a typing.Self receiver is dropped. The SDK's identical text check costs it only typed decoding (it registers arg_types=[typing.Self, str], sees one payload and decodes untyped, and the bound method runs); here the same check decides what the model is offered. Fix: resolve the hints before this check and test hints.get("self", params[0].annotation) is typing.Self. On a patched copy the PEP 563 and eager forms both give ['parcel_id'], and a module-level staticmethod still keeps ['self']. The same point was raised on #300.
There was a problem hiding this comment.
Fixed in 281debf, one step past resolving the hints, to match what #206 and #300 settled on: a method's first parameter named self is now dropped however it is annotated. That covers self: Self under PEP 563, typing_extensions.Self and self: T. The class lookup still decides whether the function is a method, so a staticmethod's or a function's self stays. New row in the metadata test: PostponedHolder.track, in a module with from __future__ import annotations, offers ['parcel_id']; on 4ead9a6 it offers ['self', 'parcel_id'].
| # Look the class up where the function was defined: a decorator's | ||
| # wrapper keeps the function's __qualname__ and __module__, but has its | ||
| # own module's globals. | ||
| module = sys.modules.get(fn.__module__) |
There was a problem hiding this comment.
P2 (edge case, contrived trigger): the sys.modules fallback makes the method-or-staticmethod answer depend on the runner's module table, so a sandboxed and an unsandboxed Worker can disagree on the same code and history. It decides only when inspect.unwrap(fn).__globals__ lacks the class, which happens with a decorator that copies __module__, __qualname__ and __signature__ but not __wrapped__; inside the sandbox, sys.modules lacks the defining module when Workflow code reaches the function only through a passed-through module that re-exports it. With such a decorated staticmethod FbHolder.fb_echo_static(self): main completes the run; the head under UnsandboxedWorkflowRunner completes it; the head under the default sandbox fails every Workflow Task with the ValueError at 246. A history recorded unsandboxed replays unsandboxed and fails in a sandboxed Replayer (decorated method and staticmethod alike). In-process: module present in sys.modules, True; popped, ValueError. Dropping the fallback leaves only the function's own globals, which classify all seven cases in the PR's tests the same way (checked), and makes the decorator case fail identically everywhere; the message can then point at functools.wraps.
There was a problem hiding this comment.
Agreed, dropped in 281debf. The class is looked up only in the function's own globals, after inspect.unwrap, so sandboxed and unsandboxed Workers give the same answer. A decorator that drops __wrapped__ now fails the same way everywhere, and the message points at functools.wraps. test_activity_as_tool_rejects_method_of_unreachable_class has a row for that decorator (unwrapped in tests/helpers/decorators.py); on 4ead9a6 it doesn't raise. The body's Breaking change list now has this case.
| """ | ||
| tool_context_param = _tool_context_parameter(activity_def) | ||
| signature, hints, doc = _tool_signature(activity_def) | ||
| tool_context_param = _tool_context_parameter(activity_def, signature, hints) |
There was a problem hiding this comment.
P2 (disclosure, non-blocking): the Breaking change list of callable classes that worked only because the tool read the constructor misses one shape: a __call__ whose tool_context the function-tool rules reject. TrackCtx with __init__(self, parcel_id: str) and async def __call__(self, parcel_id: str, tool_context=None): on main the run completes with the model's value (trackctx:worker:TrackCtx.parcel_id:None); on the head every Workflow Task fails with Activity 'TrackCtx' has an unannotated 'tool_context' parameter..., and a history recorded on main fails replay on the head with the same error, so draining does not help, as for the classes the body lists. By source, the same rule also rejects a tool_context annotated with anything other than ToolContextSnapshot, an ADK context type under any name, and a ToolContextSnapshot under another name. Rejecting them is right; the body, and the release notes, should list them with the others.
There was a problem hiding this comment.
Thanks, added to the body's Breaking change list: a __call__ whose tool_context the function rules reject (unannotated, another annotation, or an ADK context type or a ToolContextSnapshot under another name). It also says their old runs fail replay with the same error. No code change.
| sig = inspect.signature(activity_def) | ||
| bound = sig.bind(*args, **kw) | ||
| # Bind arguments to the parameters the activity is called with | ||
| bound = binding.bind(*args, **kw) |
There was a problem hiding this comment.
P3: the positional-only fix stops at the Workflow path: outside a Workflow the wrapper still calls activity_def(*args, **kw) (line 400), so the same tool still fails in local ADK runs. Through InMemoryRunner with a scripted model, @activity.defn async def track_fn(parcel_id: str, /) raises TypeError: track_fn() got some positional-only arguments passed as keyword arguments: 'parcel_id' out of run_async on the head (main failed one step earlier, at the bind). README line 246 says activity_as_tool(...) works in local runs. Calling activity_def(*bound.args, **bound.kwargs) there fixes it: verified for the positional-only function, a tool_context snapshot followed by a defaulted parameter, and a **kwargs function, which *activity_args alone would break.
There was a problem hiding this comment.
Fixed in 281debf: the local path now calls activity_def(*bound.args, **bound.kwargs). test_agent_outside_workflow also calls a positional-only function tool outside a Workflow; on 4ead9a6 it fails with TypeError: locate_parcel() got some positional-only arguments passed as keyword arguments: 'parcel_id'.
| This ensures the activity's signature is preserved for ADK's tool schema generation | ||
| while marking it as a tool that executes via 'workflow.execute_activity'. | ||
|
|
||
| ``activity_def`` can be an activity function, a method passed as |
There was a problem hiding this comment.
P3 (docs): this paragraph names three forms but not the two that keep working (bound methods and callable-class instances), and neither it nor README line 246 ('TemporalModel and activity_as_tool(...) work in local ADK runs') says the two new forms run only inside a Workflow. Local probe on the head with a scripted model: Tracker.track raises TypeError: Tracker.track() missing 1 required positional argument: 'self' and TrackParcel raises TypeError: TrackParcel.__init__() got an unexpected keyword argument 'parcel_id', both out of runner.run_async (main also failed, or returned the class instance as the tool result). The body says this under 'Not covered', which adk web users won't read. Suggested: list all five forms here, and add to the README's 'Local ADK Runs' bullets that method and class tools need the Worker's instance and run only under Temporal.
There was a problem hiding this comment.
Done in 281debf. The docstring lists all five forms and says method and class tools run only in a Workflow. The README's "Local ADK Runs" bullet says the same.
| # @activity.defn checks the constructor's signature, not __call__'s, so | ||
| # __call__ can take keyword-only arguments or **kwargs, which the tool | ||
| # can't pass: activities get their arguments by position. | ||
| for p in signature.parameters.values(): |
There was a problem hiding this comment.
P3: a functools.partialmethod __call__ that binds a trailing parameter by keyword is refused with a message about keyword-only parameters the user never declared, although the Worker's positional call works. async def _quote(self, trip: str, passengers: int, currency: str = 'USD') with @activity.defn class QuoteEUR: __call__ = functools.partialmethod(_quote, currency='EUR') binds to (trip, passengers, *, currency='EUR'), and activity_as_tool(QuoteEUR, ...) raises cannot take keyword-only arguments or **kwargs in __call__ ('currency'), while await QuoteEUR()('SFO->LAX', 3) returns 'SFO->LAX:3:EUR'. The docstring advertises partialmethod. Dropping the names in calls[0].keywords from the signature before this loop gives the tool (trip, passengers), schedules ['SFO->LAX', 3], and the Worker call returns 'SFO->LAX:3:EUR' (verified on a patched copy). A partialmethod that binds a leading parameter by keyword is still refused, correctly, because a positional call then fails with got multiple values. At minimum, name the partialmethod in the message.
There was a problem hiding this comment.
I kept the refusal, to match #206 (where you accepted the same decline) and #300, but the message now names the cause: "Its functools.partialmethod binds an argument by keyword, which makes the arguments after it keyword-only." Done in 281debf, with a row in test_activity_as_tool_rejects_unreadable_call. Dropping the bound names from the schema would work here, but then the plugins would accept different __call__ forms.
| ): | ||
| signature = signature.replace(parameters=params[1:]) | ||
| try: | ||
| hints = typing.get_type_hints(activity_def) |
There was a problem hiding this comment.
P3 (pre-existing, but the PR keeps instances on purpose): callable-class instances still take the function branch, so their hints are read from the instance (typing.get_type_hints(instance) is always {}), string annotations never resolve, and every validation message reads activity_def.__name__, which an instance lacks. In a module with from __future__ import annotations, an @activity.defn class LookupWeather whose __call__(self, city: str, tool_context: ToolContextSnapshot) builds as the class (['city']), but activity_as_tool(LookupWeather('us'), ...) raises AttributeError: 'LookupWeather' object has no attribute '__name__', on main too. On the head, an instance whose __call__ takes ctx: Annotated[ToolContext, 'm'] is now caught by the new Annotated stripping but surfaces as the same AttributeError instead of the documented ValueError. An instance's description also ignores __call__'s docstring, which the class form now prefers. Resolving a non-routine's hints from _call_function(inspect.getattr_static(type(activity_def), '__call__', None)) builds the PEP 563 instance (['city'], verified), and getattr(activity_def, '__name__', type(activity_def).__name__) in the messages at 109, 127, 142 and 185 keeps them readable. Optional, same area: setting resolved hints on the wrapper for every form, as 419-423 now does for classes, also fixes ADK's legacy declaration path (JSON_SCHEMA_FOR_FUNC_DECL off). There, function and method tools with tool_context, PEP 563 and a module-local type fail with NameError: name 'Order' is not defined on main and the head, while the class form now builds.
There was a problem hiding this comment.
Done in 281debf, the two small parts: an instance's types are read from its class's __call__, so the PEP 563 instance builds, and the validation messages fall back to the class name, so the Annotated[ToolContext, ...] instance raises the documented ValueError. Rows: PostponedSnapshotActivity() in test_activity_as_tool_accepts_optional_snapshot_annotation and AnnotatedContextActivity() in test_activity_as_tool_rejects_annotated_adk_context; both raise AttributeError on 4ead9a6. I left the instance's description and the legacy declaration path alone: this PR otherwise keeps function, bound-method and instance tools as they are, and the legacy-path NameError is on main too. Both would fit a separate PR.
| except AttributeError: | ||
| attr = None | ||
| if not inspect.isclass(owner) or attr is None: | ||
| raise ValueError( |
There was a problem hiding this comment.
P3: the message's advice is wrong for the case the body calls out, and its premise is wrong in two others. For a staticmethod taking self in a class defined inside a function, 'pass a bound method' cannot help: LocalHolder(obj).echo is the same plain function and raises the same ValueError. Only moving the class or renaming the parameter works, as the body says. The class is already at module level in two other cases: a module-level class whose name was later rebound (Shadowed = Shadowed()), and the sys.modules case above. Main built all three (['self']). Suggested: Cannot tell whether 'X.f' is a method or a staticmethod: no class 'X' is reachable from the function's globals. Define the class at module level (wrap decorators with functools.wraps), pass a bound method for a method, or rename a staticmethod's parameter.
There was a problem hiding this comment.
Updated in 281debf, close to your wording: "Cannot tell whether 'X.f' is a method or a staticmethod: no class 'X' is reachable from the function's globals. Define the class at module level (wrap decorators with functools.wraps), pass a bound method for a method, or rename a staticmethod's parameter." The body now lists the rebound-name and decorator cases next to the function-local one.
| # inherits. | ||
| doc = ( | ||
| _docstring(_call_function(vars(activity_def).get("__call__"))) | ||
| or _docstring(activity_def) |
There was a problem hiding this comment.
P3: a dataclass callable class without docstrings gets its generated constructor signature as the tool description, naming the parameter this PR stops offering, ahead of an inherited __call__ docstring. Probe: @activity.defn @dataclass class QuoteShipping(ShippingBase): carrier: str = 'acme', where ShippingBase.__call__(self, parcel_id: str) is documented 'Quote shipping for a parcel.': the tool offers ['parcel_id'] with the description "QuoteShipping(carrier: str = 'acme')". Main used the same description, but next to a carrier schema it was at least consistent. The body adopts this from #300, where the same point was raised. Suggest skipping the class docstring when dataclasses.is_dataclass(activity_def) and it is the generated one (it starts with f"{activity_def.__name__}("), as #206 does, so the inherited __call__ docstring wins.
There was a problem hiding this comment.
Switched in 281debf to #206's rule, which #300 is also adopting: the class docstring is skipped only when it is exactly the one dataclasses (or namedtuple) wrote, so an inherited __call__ docstring wins. It's an exact match, not a Name( prefix check, which would drop handwritten docstrings like Lookup(city) returns ... (raised on #206). The helpers are #206's _generated_class_doc and _class_doc. Row: DataclassShipping gets "Quote shipping for a parcel."; on 4ead9a6 it gets DataclassShipping(carrier: str = 'acme').
|
|
||
| # The class is found where the function was defined, though a decorator | ||
| # from another module wraps it, and through a private nested class. | ||
| for fn, params in [ |
There was a problem hiding this comment.
P3 (tests): four behaviours the docstring or body promises have no test. Each of these one-line mutations of workflow.py leaves the full suite green (173 passed, 5 skipped). (a) _call_function no longer unwraps staticmethod, classmethod and partialmethod (line 196 becomes while False:): those __call__ forms then raise 'needs a call'. (b) The descriptor-aware binding at 274 becomes 'drop the function's first parameter': a staticmethod __call__ loses its first input. (c) Positional-only parameters are bound by name only for classes (389): async def f(a: str, /) fails again with missing a required positional-only argument: 'a', the body's one exception. (d) include_extras=True is dropped (277): a class tool loses Annotated[int, Field(description=...)] metadata. Also unpinned: the <locals> check (228; a nested function taking self would raise instead of keeping it), the typing.Self clause (312-315), mangling of the final name (242; Holder.__track), and the class docstring winning over an inherited __call__ docstring (297-301). Smallest additions: three classes in the metadata test whose __call__ is a staticmethod, a classmethod and a positional partialmethod, asserting their parameters; a positional-only function in test_activity_as_tool_supports_complex_inputs_via_adk; a description assertion on an Annotated class parameter; and rows in this loop for a self: Self method, a nested function taking self, and a private method.
There was a problem hiding this comment.
Added in 281debf, as you suggested: (a, b) StaticCallTrip, ClassCallTrip and PartialCallTrip in the metadata test, asserting their parameters; (c) a positional-only function, locate_parcel, in test_activity_as_tool_supports_complex_inputs_via_adk; (d) QuoteTrip.passengers is now Annotated[int, Field(description=...)], checked in the tool's annotations and in ADK's declaration; and loop rows for a self: Self method under PEP 563, a nested function taking self, and a private method. The class docstring winning over an inherited __call__ docstring is pinned too. I also reverted your four mutations, and each change in this round, one line at a time on the installed build: each of the 14 now fails a test.
…s docstrings - Drop a method's first `self` parameter however it is annotated, so `self: Self` under `from __future__ import annotations` is dropped too. - Look a method's class up only in the function's globals: sys.modules differs in the Workflow sandbox. - Say how to fix an unreachable class, and name a keyword-bound partialmethod in its error. - Skip a class docstring only when dataclasses or namedtuple wrote it, as openai_agents does. - Read a callable instance's types from its class's __call__, and name its class in errors. - Call the activity by position in local runs too, so positional-only parameters bind there. - Document the five forms, and that method and class tools run only in a Workflow. - Extend the tests for these and for the __call__ forms.
|
Thanks for the review. The round is in
|
What was changed
activity_as_toolingoogle_adknow builds the tool from the parameters the Activity is called with, for a method passed asClass.methodand for a callable-class Activity passed as its class.self, however it is annotated (includingself: Selfin a module withfrom __future__ import annotations). This applies only to a method. The function's class is found by__qualname__in the globals of the function's own module, not insys.modules, which differs in the Workflow sandbox. This also works through afunctools.wrapsdecorator from another module and through private nested classes and methods, whose names Python mangles. A staticmethod keeps itsselfas an input, as do module-level and nested functions.__call__as an instance binds it (without the receiver of a method, classmethod orfunctools.partialmethod, with every parameter of a staticmethod).__call__'s annotations are resolved in its own module, so string annotations work. The description is__call__'s own docstring, else the class's (unless dataclasses or namedtuple wrote it), else that of a__call__it inherits. The tool keeps the class name.tool_context: ToolContextSnapshotparameter of__call__is checked and filled like a function's, including when wrapped inAnnotated[...]or in aliases that nestAnnotatedandOptional; a live ADK context wrapped that way is rejected like an unwrapped one.ValueErrorwhen the tool is built:__call__is missing or of another kind, can't be read, or takes keyword-only arguments or**kwargs.@activity.defnchecks a class's constructor, not its__call__, and the tool can only pass arguments by position. When afunctools.partialmethodbinds an argument by keyword, the message says that this made the arguments after it keyword-only;selfwhose__qualname__puts it in a class that can't be reached from the function's globals: a class defined inside a function, a module-level class whose name was later rebound, or a function wrapped by a decorator that doesn't set__wrapped__. It can't be told from a staticmethod; the message says how to fix it.TypeError(in a Workflow, the Workflow Task failed before anything was scheduled);__call__. One in a module withfrom __future__ import annotationswhose__call__takestool_context: ToolContextSnapshotnow builds, and an instance's validation errors areValueErrors naming its class. Before, both raisedAttributeError.activity_as_tooldocstring names all five forms and says that method and class tools run only in a Workflow. The README's "Local ADK Runs" says so too.This is the design of #206 for
openai_agentsand #300 fordeepagents, applied togoogle_adk. Differences:wrapper. 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 reject it. Here it works today, so rejecting it would break working code.ValueError, like this function's existing errors, as in Breaking: support method and callable-class Activities in Deep Agents activity_as_tool #300. Breaking: build callable-class activity tools from__call__and raise ValueError for tools that can't be built in OpenAI Agents #206 usesApplicationError(type="invalid_tool"), like the existing errors ofopenai_agents.**kwargsis refused only in a class's__call__; function and method tools are unchanged here. 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 refuse it in every form. (@activity.defnalready refuses keyword-only parameters in functions and methods.)selfis dropped only from a method, found through its class. 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 drop it by name alone. Ingoogle_adk, a module-level function's or a staticmethod'sselfworks onmain: the model fills it.No public name or option changes.
Breaking change: the change has no version gate. We are not adding version gates to these fixes: breaking old histories is accepted with the plugins' 1.0 releases.
Two kinds of runs recorded before this change fail replay with
[TMPRL1100]:self. ADK returned a missing-parameter error and the model was called again; built withoutself, the tool now schedules the method's Activity there (Activity type of scheduled event 'invoke_model' does not match activity type of activity command 'shipping.track').Activity type of scheduled event 'shipping.quote' does not match activity type of activity command 'invoke_model').Runs of function, bound-method, staticmethod and callable-instance tools replay. A run whose model passed
selfto a method tool replays too, but its Activity keeps failing after the upgrade: the server retries the recorded input, which hasself. A run that used a positional-only tool and is rolled back to the earlier version fails its Workflow Task again. (Both found in review, at4ead9a6.)Some callable classes that worked only because the tool used the constructor's parameters now fail in new runs. Each has a constructor that takes the same parameters as
__call__, so the model's values happened to reach the right place, and a__call__that also takes:via: Carrier | None = None: ADK fails to build the tool declaration, so the Workflow Task fails, as it would for a function with that parameter;**kwargs:activity_as_toolraisesValueError, so the Workflow Task fails;tool_contextparameter that the function-tool rules reject: unannotated, annotated with anything butToolContextSnapshot(orToolContextSnapshot | None), or an ADK context type or aToolContextSnapshotunder another name:activity_as_toolraisesValueError, so the Workflow Task fails.These classes must change
__call__before they start runs on this version. Their runs recorded on the earlier version also fail replay, with the same error. A matching class whose__call__takes positional-only parameters keeps working.A staticmethod taking a parameter named
selfalso fails now withValueErrorwhen the tool is built, and its runs stop replaying, when its class can't be reached from the function's globals: a class defined inside a function, a module-level class whose name was rebound, or a function wrapped by a decorator that doesn't set__wrapped__. Move the class to module level, usefunctools.wraps, or rename the parameter.Upgrade: let runs that called a method tool or a callable-class tool finish on the earlier version before you upgrade, or keep them there with Worker Versioning. Change the classes listed above in the same deployment as the upgrade: draining runs doesn't help them. Runs whose model passed
selfto a method tool keep failing their Activity: reset them to before that model call, or terminate them.Why?
See #278 and #309.
activity_as_toolbuilt the tool frominspect.signatureof the object it was given:self. If the model filled it, the value was sent as an extra Activity argument and every attempt failed withTypeError; if not, ADK returned a missing-parameter error and nothing ran.__call__. With a one-string constructor and a one-string call, the run completed with a wrong result and no error. Other constructors failed to build the tool or failed every call.Checklist
Closes [Bug] google_adk:
activity_as_tooloffersselffor a method Activity passed asClass.method#309. Fixes thegoogle_adkpart of [Bug] deepagents, google_adk, google_genai, strands_agents:activity_as_toolbuilds a callable-class Activity's tool from its constructor #278.How was this tested:
test_activity_as_tool_supports_complex_inputs_via_adknow also runs, through an ADK agent, a method passed asClass.method, a callable class passed as its class, a callable class whose__call__takes a positional-only parameter, a function whose parameter is positional-only, a module-level function with aselfparameter, a staticmethod with aselfparameter, the same kind of staticmethod wrapped by afunctools.wrapsdecorator from another module, and one in a private nested class. It checks the values each Worker instance got. Onmainatdb14ec3it fails: ADK returns the modelmandatory input parameters are not present: selfand...: currency, and the assertion showsRight contains 2 more items: {'QuoteTrip': ('USD', 'SFO->LAX', 3), 'count_passengers': 3}. With the first revision of this PR (5cbb334) it fails withmissing a required positional-only argument: 'parcel_id'. On64a8481its Workflow Task fails withValueError: Cannot tell whether 'ComplexActivityMethodHolder.echo_decorated' is a method or a staticmethod.test_activity_as_tool_preserves_metadataalso checks the name, parameters, types and docstring of the method and class tools, and that theselfof a function and of a staticmethod stays in its tool. It also checks that a decorated or private-nested-class staticmethod keepsselfand that a decorated or private-nested-class method drops it. Onmainit fails withassert ['self', 'passengers'] == ['passengers']. On5cbb334it fails withassert [] == ['self']for the function, on43a75b9with the same for the staticmethod, and on64a8481withValueErrorfor all four decorated and private-nested-class cases.281debf) extendedtest_activity_as_tool_preserves_metadatawith: classes whose__call__is a staticmethod, a classmethod and a positionalfunctools.partialmethod; theAnnotateddescription of a class parameter, in the tool's annotations and in ADK's declaration; a class docstring over an inherited__call__docstring, and an inherited one over the docstring dataclasses wrote; a private method, a method whoseself: Selfis a string annotation, and a nested function takingself. On4ead9a6it fails withassert "DataclassShipping(carrier: str = 'acme')" == 'Quote shipping for a parcel.'.test_activity_as_tool_rejects_method_of_unreachable_classchecks that a method of a class defined in a function raisesValueError, and so does a staticmethod wrapped by a decorator that drops__wrapped__. On43a75b9the first does not raise; on4ead9a6the second does not.test_activity_as_tool_rejects_unreadable_callchecks the four classValueErrors, and the message for afunctools.partialmethodthat binds an argument by keyword. Onmainnone of them raises.test_agent_outside_workflowalso calls a positional-only function tool outside a Workflow. On4ead9a6it fails withTypeError: locate_parcel() got some positional-only arguments passed as keyword arguments: 'parcel_id'.test_activity_as_tool_accepts_optional_snapshot_annotationalso builds an instance of a callable class from a module withfrom __future__ import annotations, andtest_activity_as_tool_rejects_annotated_adk_contextan instance whose__call__takesAnnotated[ToolContext, ...]. On4ead9a6both raiseAttributeError.workflow.pyat281debf, one for each change in this round and for each of the four untested paths found in review: each makes a test fail (14 of 14).test_activity_as_tool_receives_tool_context_snapshotnow runs a function and a callable class whose__call__takestool_context: Annotated[ToolContextSnapshot, ...]through a Worker.test_tool_schema_excludes_annotated_tool_context_of_classchecks that class's schema.test_activity_as_tool_accepts_nested_snapshot_aliaschecks thatOptional[Annotated[Optional[ToolContextSnapshot], ...]]is accepted and left out of the schema for a function and a class.test_activity_as_tool_rejects_annotated_adk_contextchecks thatAnnotated[ToolContext, ...]is rejected for a function and a class, under any name, inside| Noneand inOptional[Annotated[Optional[ToolContext], ...]]. On5cbb334the class snapshot tool raisesValueErrorand the class withctx: Annotated[ToolContext, ...]is not rejected; on43a75b9the nested-alias class snapshot is rejected and the nested-alias class live context is not.make linttools (ruff, pyright, mypy, basedpyright, pydocstyle) and the conventions check pass with Python 3.13, and the suite gives 175 passed and 5 skipped. The round's tests and basedpyright also pass with Python 3.14. (Run fromuv.lock, not throughmake.)activity_as_tooloffersselffor a method Activity passed asClass.method#309's reproduction exits 1 on 0.0.1 and onmain, and 0 with the change. [Bug] deepagents, google_adk, google_genai, strands_agents:activity_as_toolbuilds a callable-class Activity's tool from its constructor #278's reproduction offers['parcel_id']for the class with the change (['carrier']onmain).5cbb334with the binding fix): callable classes whose__call__is a function, a positional-only function, a staticmethod, a classmethod and afunctools.partialmethod, a module-level function takingselfand an unbound method all complete with the model's values.QuoteShipping("acme-post")and passed as its class now gets the model'sparcel_id; onmainit got the model'scarriervalue asparcel_idand completed with that wrong result. Classes whose constructor takes a client object or two strings now run too; onmainthe first failed its Workflow Task and the second failed every attempt. A class whose__call__takestool_context: ToolContextSnapshotgets the snapshot; onmainits tool offered the constructor's parameter and the Activity failed with a missingtool_context.mainall three completed with the model'sparcel_id; with the change they fail their Workflow Task as described. A matching class and a function tool complete on both.5cbb334, before the positional-only,selfandAnnotatedfixes): Workers with no Workflow cache recorded, onmainand on this branch, a finished run and a run held between two agent turns for four tool forms: a function, a callable-class instance, a method and a callable class. The scripted model fills the offered schema withoutself.mainhistories on this branch: the method and class ones fail with[TMPRL1100]as above; the function and instance ones replay.main(the rollback target): the method and class ones fail with[TMPRL1100]; the function and instance ones replay.[TMPRL1100].main, frommainto this branch, and to a replacement Worker of this branch. Held method and class runs complete on a replacement Worker of this branch, and stop with[TMPRL1100]when carried in either direction, as the replay showed.281debf: the same 16 histories give the same results (method and class histories frommainfail with[TMPRL1100], everything else replays, and onmainthe5cbb334method and class histories fail the same way); the control fails all 16. In review, the replay check was also rerun at4ead9a6with 19 tool scenarios, with the same result.Any docs updates needed?
The
activity_as_tooldocstring and the README's "Local ADK Runs" are updated here. Release notes should say which runs stop replaying and which classes must change (see "Breaking change"). The repository squashes with the PR title only, so that text has to be copied into the release notes by hand.Not covered:
google_genaiandstrands_agents([Bug] deepagents, google_adk, google_genai, strands_agents:activity_as_toolbuilds a callable-class Activity's tool from its constructor #278) is not changed here.activity_nodereads the signature the same way and has the same problem:activity_node(Tracker.route)fails withmissing required input key(s) ['self'], and a class is read from its constructor (found in review).wrapper, so two instance tools on one Agent collide, and ADK calls the last one (found in review; also onmain).*argsis not handled. It did not work before either.functools.partialmethod__call__gets its schema here; the SDK registers an async one as sync before Python 3.13 and decodes its arguments without their types. That was checked for Breaking: build callable-class activity tools from__call__and raise ValueError for tools that can't be built in OpenAI Agents #206, not here.temporalio1.34.x still bundles the old code astemporalio.contrib.google_adk_agents. No backport here.