Skip to content

Breaking: support method and callable-class Activities in Google ADK activity_as_tool - #312

Merged
campoy merged 5 commits into
mainfrom
fix/google-adk-python-activity-tool-class-signature
Oct 31, 2026
Merged

campoy merged 5 commits into
mainfrom
fix/google-adk-python-activity-tool-class-signature

Conversation

@campoy

@campoy campoy commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

What was changed

activity_as_tool in google_adk now builds the tool from the parameters the Activity is called with, for a method passed as Class.method and for a callable-class Activity passed as its class.

  • For a method, the receiver is dropped: a first parameter named self, however it is annotated (including self: Self in a module with from __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 in sys.modules, which differs in the Workflow sandbox. This also works through a functools.wraps decorator from another module and through private nested classes and methods, whose names Python mangles. A staticmethod keeps its self as an input, as do module-level and nested functions.
  • For a class, the tool's parameters come from __call__ as an instance binds it (without the receiver of a method, classmethod or functools.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.
  • Calls bind the model's arguments to those parameters and pass them to the Activity by position, as before. ADK passes every argument by name, so positional-only parameters are bound by name too, in a Workflow and in local ADK runs. A tool_context: ToolContextSnapshot parameter of __call__ is checked and filled like a function's, including when wrapped in Annotated[...] or in aliases that nest Annotated and Optional; a live ADK context wrapped that way is rejected like an unwrapped one.
  • These now raise ValueError when the tool is built:
    • a class whose __call__ is missing or of another kind, can't be read, or takes keyword-only arguments or **kwargs. @activity.defn checks a class's constructor, not its __call__, and the tool can only pass arguments by position. When a functools.partialmethod binds an argument by keyword, the message says that this made the arguments after it keyword-only;
    • a function taking self whose __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.
  • Function, bound-method and callable-instance tools keep the same schema, name, description and commands, with two exceptions:
    • a positional-only parameter now binds, where before the wrapper raised TypeError (in a Workflow, the Workflow Task failed before anything was scheduled);
    • a callable-class instance's types are read from its class's __call__. One in a module with from __future__ import annotations whose __call__ takes tool_context: ToolContextSnapshot now builds, and an instance's validation errors are ValueErrors naming its class. Before, both raised AttributeError.
  • The activity_as_tool docstring 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_agents and #300 for deepagents, applied to google_adk. Differences:

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]:

  • A run whose model called a method tool without self. ADK returned a missing-parameter error and the model was called again; built without self, 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').
  • A run whose model called a callable-class tool with the constructor's arguments. They no longer fit the tool's schema, so ADK returns a missing-parameter error and calls the model again, where the History has the class's Activity (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 self to a method tool replays too, but its Activity keeps failing after the upgrade: the server retries the recorded input, which has self. 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, at 4ead9a6.)

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:

  • a parameter with no JSON schema, such as 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;
  • a keyword-only parameter or **kwargs: activity_as_tool raises ValueError, so the Workflow Task fails;
  • a tool_context parameter that the function-tool rules reject: unannotated, annotated with anything but ToolContextSnapshot (or ToolContextSnapshot | None), or an ADK context type or a ToolContextSnapshot under another name: activity_as_tool raises ValueError, 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 self also fails now with ValueError when 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, use functools.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 self to a method tool keep failing their Activity: reset them to before that model call, or terminate them.

Why?

See #278 and #309. activity_as_tool built the tool from inspect.signature of the object it was given:

  • A method's tool asked for self. If the model filled it, the value was sent as an extra Activity argument and every attempt failed with TypeError; if not, ADK returned a missing-parameter error and nothing ran.
  • A callable class passed as its class offered 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. Other constructors failed to build the tool or failed every call.

Checklist

  1. Closes [Bug] google_adk: activity_as_tool offers self for a method Activity passed as Class.method #309. Fixes the google_adk part of [Bug] deepagents, google_adk, google_genai, strands_agents: activity_as_tool builds a callable-class Activity's tool from its constructor #278.

  2. How was this tested:

    • test_activity_as_tool_supports_complex_inputs_via_adk now also runs, through an ADK agent, a method passed as Class.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 a self parameter, a staticmethod with a self parameter, the same kind of staticmethod wrapped by a functools.wraps decorator from another module, and one in a private nested class. It checks the values each Worker instance got. On main at db14ec3 it fails: ADK returns the model mandatory input parameters are not present: self and ...: currency, and the assertion shows Right contains 2 more items: {'QuoteTrip': ('USD', 'SFO->LAX', 3), 'count_passengers': 3}. With the first revision of this PR (5cbb334) it fails with missing a required positional-only argument: 'parcel_id'. On 64a8481 its Workflow Task fails with ValueError: Cannot tell whether 'ComplexActivityMethodHolder.echo_decorated' is a method or a staticmethod.
    • test_activity_as_tool_preserves_metadata also checks the name, parameters, types and docstring of the method and class tools, and that the self of a function and of a staticmethod stays in its tool. It also checks that a decorated or private-nested-class staticmethod keeps self and that a decorated or private-nested-class method drops it. On main it fails with assert ['self', 'passengers'] == ['passengers']. On 5cbb334 it fails with assert [] == ['self'] for the function, on 43a75b9 with the same for the staticmethod, and on 64a8481 with ValueError for all four decorated and private-nested-class cases.
    • Review round 1 (281debf) extended test_activity_as_tool_preserves_metadata with: classes whose __call__ is a staticmethod, a classmethod and a positional functools.partialmethod; the Annotated description 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 whose self: Self is a string annotation, and a nested function taking self. On 4ead9a6 it fails with assert "DataclassShipping(carrier: str = 'acme')" == 'Quote shipping for a parcel.'.
    • test_activity_as_tool_rejects_method_of_unreachable_class checks that a method of a class defined in a function raises ValueError, and so does a staticmethod wrapped by a decorator that drops __wrapped__. On 43a75b9 the first does not raise; on 4ead9a6 the second does not.
    • test_activity_as_tool_rejects_unreadable_call checks the four class ValueErrors, and the message for a functools.partialmethod that binds an argument by keyword. On main none of them raises.
    • 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'.
    • test_activity_as_tool_accepts_optional_snapshot_annotation also builds an instance of a callable class from a module with from __future__ import annotations, and test_activity_as_tool_rejects_annotated_adk_context an instance whose __call__ takes Annotated[ToolContext, ...]. On 4ead9a6 both raise AttributeError.
    • One-line mutations of workflow.py at 281debf, 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_snapshot now runs a function and a callable class whose __call__ takes tool_context: Annotated[ToolContextSnapshot, ...] through a Worker. test_tool_schema_excludes_annotated_tool_context_of_class checks that class's schema. test_activity_as_tool_accepts_nested_snapshot_alias checks that Optional[Annotated[Optional[ToolContextSnapshot], ...]] is accepted and left out of the schema for a function and a class. test_activity_as_tool_rejects_annotated_adk_context checks that Annotated[ToolContext, ...] is rejected for a function and a class, under any name, inside | None and in Optional[Annotated[Optional[ToolContext], ...]]. On 5cbb334 the class snapshot tool raises ValueError and the class with ctx: Annotated[ToolContext, ...] is not rejected; on 43a75b9 the nested-alias class snapshot is rejected and the nested-alias class live context is not.
    • Locally, in Docker: the make lint tools (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 from uv.lock, not through make.)
    • [Bug] google_adk: activity_as_tool offers self for a method Activity passed as Class.method #309's reproduction exits 1 on 0.0.1 and on main, and 0 with the change. [Bug] deepagents, google_adk, google_genai, strands_agents: activity_as_tool builds a callable-class Activity's tool from its constructor #278's reproduction offers ['parcel_id'] for the class with the change (['carrier'] on main).
    • Through a real Worker with a scripted model (on 5cbb334 with the binding fix): callable classes whose __call__ is a function, a positional-only function, a staticmethod, a classmethod and a functools.partialmethod, a module-level function taking self and an unbound method all complete with the model's values.
    • Through an agent with a scripted model that fills the offered schema: a callable class registered as QuoteShipping("acme-post") and passed as its class now gets the model's parcel_id; on main it got the model's carrier value as parcel_id and completed with that wrong result. Classes whose constructor takes a client object or two strings now run too; on main the first failed its Workflow Task and the second failed every attempt. A class whose __call__ takes tool_context: ToolContextSnapshot gets the snapshot; on main its tool offered the constructor's parameter and the Activity failed with a missing tool_context.
    • Fresh runs of the classes in "Breaking change", each with a matching one-string constructor: on main all three completed with the model's parcel_id; with the change they fail their Workflow Task as described. A matching class and a function tool complete on both.
    • Replay (run on 5cbb334, before the positional-only, self and Annotated fixes): Workers with no Workflow cache recorded, on main and 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 without self.
      • Each version replays its own 8 histories.
      • main histories on this branch: the method and class ones fail with [TMPRL1100] as above; the function and instance ones replay.
      • This branch's histories on main (the rollback target): the method and class ones fail with [TMPRL1100]; the function and instance ones replay.
      • A control that schedules an extra Activity first fails all 16 with [TMPRL1100].
      • A held function run completes when carried from this branch to main, from main to 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.
    • Replay on 281debf: the same 16 histories give the same results (method and class histories from main fail with [TMPRL1100], everything else replays, and on main the 5cbb334 method and class histories fail the same way); the control fails all 16. In review, the replay check was also rerun at 4ead9a6 with 19 tool scenarios, with the same result.
  3. Any docs updates needed?
    The activity_as_tool docstring 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:

…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].
@campoy
campoy marked this pull request as ready for review October 31, 2026 01:35
@campoy
campoy requested a review from a team as a code owner October 31, 2026 01:35

@DABH DABH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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__)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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():

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 [

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.
@campoy

campoy commented Oct 31, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the review. The round is in 281debf, with a reply in each thread. On the summary:

  • Body: updated. "Draft while..." and the open questions are gone: callable-class instances stay accepted, and errors stay ValueError, as you suggested and as on Breaking: support method and callable-class Activities in Deep Agents activity_as_tool #300. Your three replay notes are now under Breaking change and Upgrade: runs whose model filled self need a reset or termination, function-local staticmethod runs stop replaying, and a positional-only run rolled back to the earlier version fails again. The activity_node note now says it has the same problem, citing your run.
  • Release notes: the docs item now says the Breaking change and Upgrade text has to be copied into the release notes by hand.
  • Instance tools named wrapper: agreed, that's a real hazard. Fixing it renames instance tools and breaks their replay, so I've listed it under Not covered instead of folding it in here.

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] google_adk: activity_as_tool offers self for a method Activity passed as Class.method

2 participants