Skip to content

Breaking: build Google GenAI callable-class activity tools from __call__, not the constructor - #404

Merged
campoy merged 8 commits into
mainfrom
fix/google-genai-python-activity-tool-callable-class
Nov 4, 2026
Merged

campoy merged 8 commits into
mainfrom
fix/google-genai-python-activity-tool-callable-class

Conversation

@campoy

@campoy campoy commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

What was changed

This PR builds the tool from __call__. It's the same design as #206 (openai_agents), #300 (deepagents) and #312 (google_adk), with the helpers copied from #312.

  • Parameters. For a class, the tool offers __call__'s parameters as an instance binds it, so no self. Types are resolved in __call__'s own module, and the tool's signature carries the resolved types. So quoted types and from __future__ import annotations work, both for the declaration and for Gemini's argument conversion.

  • Calls. The model's values go to __call__ by position, and the Worker's registered instance runs it. The tool keeps the class name.

  • Description. It's __call__'s own docstring. If there's none, it's the class's (unless dataclasses or namedtuple wrote it). If there's none of those either, it's the docstring of a __call__ the class inherits. Before, it was always the class's.

  • Positional-only parameters. Gemini passes every argument by name, so a positional-only parameter of __call__ is bound by name.

  • New ValueErrors when the tool is built, for:

    • an instance of a callable-class Activity (pass the class instead; before, this failed with AttributeError);
    • a __call__ that is missing, or isn't a function, staticmethod, classmethod or functools.partialmethod;
    • a __call__ whose parameters or types can't be read;
    • a __call__ that takes *args, keyword-only arguments or **kwargs. The tool can't pass those: it sends one argument per parameter, by position.

    The messages match Breaking: support method and callable-class Activities in Strands Agents activity_as_tool #402 (strands_agents). As in the sibling PRs, a ValueError fails the Workflow Task, so the run can continue once you fix the code. The two existing errors (no @activity.defn, no name) stay GoogleGenAIError.

  • Unchanged: functions, and methods passed as Class.method.

Why?

Want to use a callable-class Activity as a Gemini tool? Today activity_as_tool in google_genai builds the tool from the class's constructor, not from __call__. So the model sees the constructor's parameters, and their values reach __call__ by position. With a one-string constructor and a one-string call, the run completes with a wrong result and no error. Ouch.

Is this a breaking change?

Yes. There's no version gate, as for the other plugins' 1.0 fixes. Let's see who notices.

Runs whose model called a class tool with different constructor and __call__ parameters. They fail replay with [TMPRL1100] when the recorded call doesn't bind the other version's parameters. That's true after the upgrade and after a rollback:

Activity type of scheduled event 'TrackParcel' does not match activity type of activity command 'gemini_api_client_async_request'

On main, these runs passed the constructor's argument to __call__ and got a wrong result, or nothing ran. A recorded call that binds both versions' parameters still replays. For example: a constructor with a defaulted parameter, and a __call__ with none.

Open runs that offered such a tool, but whose model hasn't called it yet. These don't fail replay, and nothing alerts operators. This is the sneaky one. The model's response to a request from the earlier version fills the constructor's parameters. The new version then schedules no Activity: google-genai sends the model missing a required argument: 'parcel_id', and the run goes on without the tool. After a rollback, the same happens to runs whose request came from this version, with the __call__ parameter's name.

Runs stuck retrying on main. Some class-tool Activities keep failing on main with a TypeError about their arguments. For example: a constructor with no parameters (the model sent {}), or a defaulted one and a __call__ with none. Those runs never finish there, so you can't drain them. Some fail replay with [TMPRL1100] on this version. Others replay and keep retrying the recorded input.

Rollback with postponed or quoted annotations. On main, every class tool in a module with from __future__ import annotations or quoted types fails its Workflow Task while the declaration is built. So runs that use such a tool on this version fail every Workflow Task after a rollback. The other way around, runs stuck on main that way continue on this version.

Classes that already worked. A class whose constructor takes the same parameters as __call__ worked on main, and it keeps working. Unless its __call__ has one of these:

  • *args, keyword-only arguments or **kwargs: ValueError, so the Workflow Task fails.
  • A decorator that returns something other than a function, such as functools.lru_cache: ValueError (needs a __call__ that is a function, ...), so the Workflow Task fails.
  • A parameter with no JSON schema, such as client: Client | None = None: google-genai can't build the declaration (Failed to parse the parameter client), so the Workflow Task fails. Same as for a function with that parameter.
  • A type google-genai's argument check rejects, such as Annotated, Literal, Any, an enum, datetime, UUID, a tuple or a set: google-genai sends a conversion error to the model, and the Activity isn't scheduled. The run still completes.

That last one is Caller-breaking by decision. google-genai rejects the same types for function tools, and the plugin matches upstream instead of rewriting them. Type support for function and class tools together is a follow-up.

Open runs of these classes fail replay: with the same errors, or with [TMPRL1100] for the last group.

How do I upgrade?

A run is affected as soon as its model request offers a class tool whose constructor and __call__ take different parameters. Even before the model calls it.

  1. Let all open runs that offer such a tool finish on the earlier version, or keep them there with Worker Versioning.
  2. Runs whose class-tool Activity keeps failing on the earlier version with a TypeError about its arguments never finish. Reset them to the Workflow Task before the first model call that used such a tool, or terminate them.
  3. Change the classes from "Classes that already worked" above before you upgrade. Draining runs doesn't help them.

Before a rollback, do the same for runs started on this version.

What's not covered?

  • *args in function Activities: the empty tuple is still passed as one argument, as on main. See [Bug] deepagents, google_adk: activity_as_tool can't pass an Activity's *args #390 for *args in google_adk and deepagents.
  • Type support for function and class tools together (Annotated, Literal, Any, enums, datetime, UUID, tuples, sets, dataclasses, TypedDict, ...), and resolved annotations for function and Class.method tools. That's a follow-up. On main, function tools already fail google-genai's argument check for these types, and for every parameter in a module with from __future__ import annotations or quoted types.
  • A function Activity with a positional-only parameter still can't be called, as on main.
  • temporalio 1.34.x still bundles the old code as temporalio.contrib.google_genai. No backport here.

Decided for both #278 PRs: keep the ValueError refusals, as in #206, #300, #312 and #402.

Checklist

  1. Part of [Bug] deepagents, google_adk, google_genai, strands_agents: activity_as_tool builds a callable-class Activity's tool from its constructor #278: this is the google_genai part, and strands_agents is a separate PR.

  2. How was this tested:

  • The bug. test_multiple_tools_sequential now also calls TrackParcel. Its constructor takes carrier, its __call__ takes parcel_id, and it's registered as TrackParcel("acme-post"). The test checks the instance got the model's parcel_id. On main it fails with assert [] == ['P-1']: the tool offered carrier, the model's parcel_id was dropped, and nothing was scheduled. Both class tools get one attempt, so on main the test fails in seconds instead of timing out.
  • Quoted types. The same test calls TagParcel, whose __call__(self, parcel_id: "str") -> "str" has a quoted annotation. It checks that the instance got "P-2", and that the next model request carries Parcel P-2 is tagged. Without the resolved signature types, the instance is never called (assert [] == ['P-2']).
  • Docstrings. test_activity_as_tool_preserves_doc checks the three docstring sources. That includes a class docstring over an inherited __call__ docstring, and a namedtuple with no docstring. On main it fails with 'Parcel tracking for one carrier.' == 'Track a parcel.'.
  • Signatures. test_activity_as_tool_preserves_signature checks a staticmethod and a classmethod __call__, that the signature carries resolved types, and that a positional-only __call__ parameter binds by name. On main that last one fails with TypeError: got an unexpected keyword argument 'parcel_id'.
  • Errors. test_activity_as_tool_rejects_unreadable_call checks the ValueErrors, including *args and an instance. It also checks the message for a functools.partialmethod that binds an argument by keyword. On main the class cases don't raise, and the instance raises AttributeError.
  • Mutations. Each of 7 one-line mutations of the change made a test fail on the previous revision. Reverting the resolved-types change makes test_multiple_tools_sequential fail.
  • Lint and suite. Locally in Docker, from uv.lock with make: make lint passes, and the suite gives 171 passed on Python 3.13 at this revision. The changed tests also pass on 3.14 (and passed on 3.10 on the previous revision).
  • [Bug] deepagents, google_adk, google_genai, strands_agents: activity_as_tool builds a callable-class Activity's tool from its constructor #278's reproduction now offers ['parcel_id'] for the class (['carrier'] on main).

Does replay still work?

Mostly. I reran the replay check on this revision. Workers had no Workflow cache, and a scripted model filled the declared parameters. I covered:

  • a function, a Class.method and a callable-class instance;
  • classes with a different constructor, and with a matching one;
  • matching classes whose __call__ also takes a keyword-only argument, *args or an optional client: Client | None, or annotates its parameter Annotated[str, ...].

For each one, I recorded a finished run and a run held between two model turns, on main and on this branch. Here's what happened:

  • Each version replays its own histories (16 and 10).
  • Function, Class.method and matching-class histories replay across versions, both ways.
  • The different-constructor class fails with [TMPRL1100] both ways. So does the Annotated class: on main it ran the Activity, but here google-genai sends the model Subscripted generics cannot be used with class and instance checks instead.
  • main's keyword-only, *args and optional-client histories fail on this branch with the errors above, not [TMPRL1100].
  • The instance fails its Workflow Task on both (AttributeError on main, ValueError here), so it has no history.
  • A control that schedules an extra Activity first fails all 26 with [TMPRL1100].
  • Held runs moved from this branch to main, and from main to this branch, complete. The exceptions: the different-constructor and Annotated classes stop with [TMPRL1100], and on this branch the keyword-only, *args and optional-client classes fail their Workflow Task. All held runs complete on a replacement Worker of this branch.

What if a Worker is replaced mid-call?

I tested this for TrackParcel, while the first model response is pending. The scripted model answers after the first Workflow Worker is replaced, and fills the parameters the first request declared. Workers have no Workflow cache.

  • main → main and this branch → this branch schedule TrackParcel. The instance gets P-1, and the model gets Parcel P-1 is with acme-post.
  • main → this branch and this branch → main schedule no tool Activity. They send the model missing a required argument: 'parcel_id' ('carrier' after the rollback), and complete.
  1. Any docs updates needed? The activity_as_tool docstring is updated here. Release notes should say which runs stop replaying, which open runs silently lose the tool call, which stuck runs need a reset, and which classes must change (see "Is this a breaking change?").

…ll__`, not the constructor

activity_as_tool now offers the model a callable-class Activity's
__call__ parameters, as the Worker's registered instance runs them,
and raises ValueError for a __call__ the tool can't read or call
(keyword-only arguments or **kwargs). Runs whose model called such a
tool on the earlier version can fail replay.

Part of #278.
…_tool

A class whose __call__ takes *args now raises ValueError, as for
keyword-only arguments and **kwargs: the tool sends one argument per
parameter, so *args got the empty tuple as one argument. An instance of
a callable-class Activity raises ValueError instead of AttributeError.
This matches the Strands Agents fix for #278.
Keep the class tool's signature on __call__'s resolved types, but stop
rewriting Annotated, Literal, Any, enums, datetime, UUID, tuples and
sets for google-genai's argument check. google-genai rejects the same
types for function tools, and the plugin follows upstream: a callable
class whose __call__ uses them, and which only worked because its
constructor had plain types, is a Caller-breaking case of this fix by
decision. Type support for function and class tools together is a
follow-up.
@campoy

campoy commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor Author

Decision on this PR: let's keep it to the minimal fix.

@campoy
campoy marked this pull request as ready for review November 4, 2026 00:17
@campoy
campoy requested a review from a team as a code owner November 4, 2026 00:17

@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 f209df4 (seven commits on 9d6f9ff; main has not touched python/google_genai since). On a worktree at the head, make lint is clean and make test passes 171 of 171 on Python 3.14.3 and on 3.10.20 (temporalio 1.34.0, google-genai 2.24.0); CI is green. I compared main's and the head's tools by probe on both Python versions: the signature, and the declaration and argument conversion that google-genai's own code produces. I ran 12 callable-class shapes defined under from __future__ import annotations through real Workers on the pinned dev server with a scripted model, on 3.10 and 3.14. I recorded histories for six tool shapes on main and on the head and replayed each on the other, ran the head's new tests against main's build, and put one-line mutations of workflow.py through tests/test_gemini.py. Every finding below was reproduced.

Checked and refuted:

  • The two Gemini claims, end to end. The instance gets the model's values by position. A keyword-only parameter fails the Workflow Task with the documented ValueError while the run stays open. Defaults are filled, and a positional-only parameter binds by name. Pydantic models, list[Parcel] and dict[str, Address] arrive as models. Staticmethod, classmethod, partialmethod, functools.wraps-decorated, sync and @activity.defn(name=...) classes schedule the right Activity with the right arguments.
  • The resolved types: postponed and quoted annotations convert. On main, every class tool in such a module failed its Workflow Task while its declaration was built.
  • Any change for function, bound-method and Class.method tools: their histories replay both ways, and the only code change is that the signature is computed once.
  • self: Self under postponed annotations: the binding drops it on both Python versions.
  • Python 3.10: same results as 3.14, except that typing.get_type_hints declares a str = None parameter like an explicit Optional[str].
  • Refusing an instance: main already failed with AttributeError: 'FutTrack' object has no attribute '__name__'.
  • Generated dataclass docstrings are skipped.
  • A non-string class __doc__ raises AttributeError here; main failed the same way in google-genai's cleandoc.
  • No local variable shadows a parameter.
  • The four helpers are byte-identical to #312's.

Not verified: a live Gemini model. I did not re-run the body's held-run and Worker-replacement checks; its description of them matches the code path.

Severity: P1 = wrong result or stuck run in realistic use; P2 = correctness or robustness in an edge case; P3 = docs, tests, cleanup.

Replay, at the head: histories recorded on main replay on the head, and the head's replay on main, for a function tool, a Class.method tool and a class whose constructor and __call__ take the same parameter. DiffTrack (constructor carrier, __call__ parcel_id) fails in both directions with the disclosed [TMPRL1100] Nondeterminism error: Activity type of scheduled event 'DiffTrack' does not match activity type of activity command 'gemini_api_client_async_request'. The first inline comment has corrections for the release notes: runs whose tool Activity is retrying on main can't be drained, some class runs replay in each direction, and one more class shape stops working. No version gate, per the stated 1.0 policy.

Parity with #312, #300 and #206 (on main):

  • _call_signature follows #312's class branch, with its helpers.
  • An instance is refused, as in #300 and #206. #312 accepts one, because it worked there before.
  • *args is refused, as in #300. #312 leaves it out of ADK's declaration.
  • The partialmethod message matches all three. So does the ValueError that fails the Workflow Task.
  • New here, and needed for Gemini: the signature carries the resolved types, because google-genai converts the model's arguments with the signature's annotations.
  • Three places follow #312 and #300 rather than #206's later rounds:
    • an Args:-only class docstring is still used as the description (inline);
    • _docstring assumes a string __doc__ (#206 checks isinstance(doc, str));
    • the needs a __call__ message doesn't say the staticmethod, classmethod or partialmethod must wrap a function.
  • Google GenAI has no TypeScript or Go plugin, so there is no cross-language gap. strands_agents (#402) is the remaining Python plugin with #278's constructor bug.

Outside the diff, P3 (docstring): the summary at workflow.py line 172 still says the tool has "the same name, docstring, and type signature as fn". For a class, the signature and the docstring now come from __call__. activity_as_tool(TrackParcel) is (parcel_id: str) -> str with "Track a parcel.", while inspect.signature(TrackParcel) is (carrier: str) -> None. Something like "the activity's name, and the parameters and docstring it is called with (__call__'s for a class)" would match the Args: text below it.

Outside this PR (temporalio 1.34.0): these two limitations reach shapes this PR now builds, and are the same for a direct workflow.execute_activity. #206's docstring mentions the partialmethod ones.

  • An annotated self under postponed annotations is dropped from the tool, but the Worker then decodes the arguments without types. _type_hints_from_func keeps the string-annotated receiver, so arg_types has one entry too many and the activity worker discards them. A Pydantic parameter therefore reaches __call__ as a dict (('dict', {...}) on 3.10 and 3.14).
  • A partialmethod __call__ is decoded without types too, and on 3.10 it runs as a sync Activity.

Where the problems cluster: the class path does what the body says, on both Python versions. What is left surrounds it:

  • the upgrade notes miss the runs already stuck on main;
  • the description fallback can still show the constructor's Args:;
  • the new regression test hangs on main instead of failing, and two promised forms have no test;
  • function tools keep the annotation problem this PR fixes for classes.

Approving: there is no P1 and nothing that should block the merge (all items are P3: release notes, tests, docs and one pre-existing gap), CI is green, and the replay break is the disclosed one.

partial.__doc__ = fn.__doc__
schema_fn = partial
if inspect.isclass(fn):
sig, annotations, doc = _call_signature(fn)

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 (release notes, non-blocking): runs whose class-tool Activity is retrying on main never finish there, so the drain advice can't reach them, and the first Breaking change bullet is broader than what happens.

On main, a class whose constructor takes nothing and whose __call__ takes parcel_id (the shape of this PR's TagParcel) is offered no parameters. The model calls it with {}, and main schedules it with no arguments. Under the default retry policy every attempt fails with ZeroCtorTag.__call__() missing 1 required positional argument: 'parcel_id'; in my probe it was at attempt 4 and counting, with the run still Running. A constructor with a defaulted parameter and a __call__ with none (BindsGetTime(tz="UTC")) does the same, with takes 1 positional argument but 2 were given. This PR's own test_multiple_tools_sequential runs into it on main's build (see the comment on the test).

What the upgrade does to these runs, by replay at this head:

  • The ZeroCtorTag history fails with [TMPRL1100] Nondeterminism error: Activity type of scheduled event 'ZeroCtorTag' does not match activity type of activity command 'gemini_api_client_async_request', as the bullet says. But the run can't be drained first.
  • The BindsGetTime history replays. The recorded {"tz": "UTC"} binds a __call__ that has no required parameters, so the head schedules the same Activity type. The server keeps retrying the recorded input ["UTC"], so the run stays stuck and the upgrade reports nothing.
  • In the rollback direction, this head's ZeroCtorTag history replays on main. Main's constructor tool drops parcel_id and schedules the same type, so not every such run fails after a rollback either.

Two more cases for the notes:

  • Rollback. On main, every class tool in a module with from __future__ import annotations or quoted types fails its Workflow Task while the declaration is built (Failed to parse the parameter carrier: 'str' of function E2ETrack for automatic function calling...), whatever its constructor takes. Runs that use such a tool on this version fail every Workflow Task after a rollback. The same fact helps the upgrade: runs stuck on main that way go on with this head.
  • Classes to change before upgrading. The list should include a matching class whose __call__ is wrapped by a decorator that returns something other than a function, such as functools.lru_cache. Main ran it: CachedLookup scheduled ['P-1']. This head refuses it with needs a __call__ that is a function, staticmethod, classmethod or functools.partialmethod, although the user wrote a function.

Suggested text for the release notes: "Runs whose class-tool Activity keeps failing on the earlier version with a TypeError about its arguments never finish there. Reset them to the Workflow Task before the first model call that used such a tool, where this version offers __call__'s parameters, or terminate them." Also narrow the first bullet to runs whose recorded call doesn't bind the other version's parameters.

@campoy campoy Nov 4, 2026 •

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, you're right on all three. I updated the description (no code change):

  • The first bullet now covers only runs whose recorded call doesn't bind the other version's parameters. It also says a call that binds both still replays.
  • New bullet for runs stuck retrying on main. You can't drain them, so reset them to the Workflow Task before the first model call that used the tool, or terminate them. The Upgrade paragraph says the same.
  • New bullet for rolling back class tools under postponed or quoted annotations.
  • A __call__ behind a decorator like functools.lru_cache is now in the list of classes to change.

),
),
activity_as_tool(
TagParcel,

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, non-blocking): these two class tools have no retry limit, so on main this test hangs until the 60 s pytest timeout instead of failing with the assertion the body quotes.

Run against main's build, test_multiple_tools_sequential ends with Failed: Timeout (>60.0s) from pytest-timeout: main schedules TagParcel with no arguments and retries it (6 attempts logged, each missing 1 required positional argument: 'parcel_id'). A reverted change would show up as a slow timeout rather than a failed assertion. With retry_policy=RetryPolicy(maximum_attempts=1) added to both configs, as ToolFailureWorkflow does, main's build fails in about a second with assert [] == ['P-1'], which is what the body says, and the head still passes this test and test_replay_tool_loop.

@campoy campoy Nov 4, 2026 •

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: both class tools now get RetryPolicy(maximum_attempts=1). On main's build, the test now fails in a few seconds with assert [] == ['P-1']. On the head, it passes.

# unless dataclasses wrote it, else that of a __call__ it inherits.
assert activity_as_tool(TrackParcel).__doc__ == "Track a parcel."
assert activity_as_tool(LocateParcel).__doc__ == "Locate a parcel."
assert activity_as_tool(DataclassParcel).__doc__ == "Track a parcel."

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, non-blocking): two forms the body and docstring promise have no test: a staticmethod or classmethod __call__, and a class's own docstring taking precedence over an inherited __call__ docstring.

With both of these one-line mutations of workflow.py applied, tests/test_gemini.py still passes 97 of 97. I checked that the installed build had both.

  • Drop staticmethod, classmethod from the isinstance in _call_function (line 31). Such classes then raise ValueError.
  • Read the class's own __call__ docstring from calls[0] instead of vars(cls).get("__call__") (line 150). An inherited __call__ docstring then wins over the class's own.

The namedtuple branch of _generated_class_doc (line 75) and the blank-docstring check (line 43) are unpinned the same way. As a control, removing or _class_doc(cls) is caught. The LocateParcel assertion here also passes on main, because main used the class docstring.

Suggested cases:

  • a staticmethod and a classmethod __call__, checking the signature and the scheduled arguments;
  • a documented class that inherits a documented __call__;
  • a NamedTuple callable class with no docstring.

@campoy campoy Nov 4, 2026 •

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:

  • a staticmethod and a classmethod __call__ (signature);
  • a documented class that inherits a documented __call__;
  • a NamedTuple with no docstring.

Your two mutations, and dropping the namedtuple branch, now each fail a test. For the staticmethod and classmethod I check the signature, not the scheduled arguments. Why? After the signature, they take the same call path as the other classes, and your end-to-end runs covered that path.

# inherits.
doc = (
_docstring(_call_function(vars(cls).get("__call__")))
or _class_doc(cls)

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 (non-blocking): when __call__ has no docstring, a class docstring that documents the constructor's Args: becomes the description of a tool that no longer takes those parameters.

Take a class whose constructor is (self, carrier: str = "acme") and whose __call__(self, parcel_id: str) has no docstring.

  • With the class docstring """Args:\n carrier: The carrier's name.\n""", the head declares parcel_id with the description Args:\ncarrier: The carrier's name.
  • With """Track parcels for one carrier.\n\nArgs:\n carrier: ...""", the whole text goes out, Args: section included, next to parcel_id.

Main sent the same descriptions with a carrier parameter, so the description and the parameters matched there. google-genai sends the whole cleaned docstring (inspect.cleandoc(callable.__doc__) in parse_function_declaration_json_schema) and doesn't parse its sections. #206's _class_doc returns None for a docstring with no summary; #312 and #300 behave like this PR.

Fix: skip a class docstring whose first line is a Google section header, as #206 does, so the fallback moves on to an inherited __call__ docstring or to none. Cutting the class docstring at its first section header would also cover the second form.

@campoy campoy Nov 4, 2026 •

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, it reads oddly. For now I'm leaving it as #312 and #300 do: main sent the same text, and we're keeping this PR to the defect. #206's section-header check fits better in one follow-up for all three plugins than in this PR alone.

)
partial.__doc__ = fn.__doc__
schema_fn = partial
sig = inspect.signature(schema_fn)

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, adjacent, non-blocking): function and Class.method tools still give google-genai their unresolved annotations, so in a module with from __future__ import annotations (or with quoted types) every call fails google-genai's argument conversion and the Activity never runs, on main and here.

@activity.defn async def e2e_fn(city: str) -> str in such a module, through a real Worker with a scripted call {"city": "Tokyo"}: on both builds the model gets {"error": "isinstance() arg 2 must be a type, a tuple of types, or a union"}, the Activity never runs, and the run completes on the model's next answer. A Class.method tool in the same module converts the same way (its signature is (city: 'str') -> 'str'). google-genai's convert_argument_from_function checks isinstance(value, param.annotation) against the signature's annotation, here the string 'str'. Line 146 fixes exactly this for __call__, so a class tool and a function tool in the same module now behave differently, and 'Not covered' lists types google-genai rejects but not unresolved annotations. Fix: a follow-up that gives this path the same resolved signature (the function's typing.get_type_hints applied to its parameters and return, after the self partial for Class.method), with its own replay note, since calls that got the conversion error would then schedule Activities. Or at least a line in 'Not covered'.

@campoy campoy Nov 4, 2026 •

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.

Right, and main does the same. I added it to "Not covered" as part of the type-support follow-up. That follow-up would give function and Class.method tools resolved annotations too, with its own replay note.

- Give the two class tools in MultipleToolsWorkflow one attempt, so the
  test fails fast on the unfixed code instead of timing out.
- Test a staticmethod and a classmethod __call__, a class docstring over
  an inherited __call__ docstring, and a namedtuple with no docstring.
- Say in activity_as_tool's docstring that a class's tool takes
  __call__'s parameters and docstring.
@campoy

campoy commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks for the thorough review! Here's where each summary item landed:

This round only changes the docstring and tests, so I didn't rerun the replay check. make lint passes, and the suite gives 171 passed on Python 3.13 (the changed tests also on 3.14).

@campoy
campoy merged commit f6e99f7 into main Nov 4, 2026
27 checks passed
@campoy
campoy deleted the fix/google-genai-python-activity-tool-callable-class branch November 4, 2026 03:15

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

Second round, at head 91d851a (one commit over f209df4, which I approved; main has not touched python/google_genai since the merge base, and #403 only added a shared make target). On a worktree at the head, make lint is clean and make test passes 171 of 171 on Python 3.14.3 and 3.10.20 (temporalio 1.34.0, google-genai 2.24.0); CI is green. I reran each of last round's reproductions: the head's test file against main's build, the one-line mutations of workflow.py, and the eight histories I recorded on main last round, replayed at this head. New this round, by probe on main and the head (3.10 and 3.14): runs of three class shapes in a from __future__ import annotations module, recorded here and replayed on main; the body's 'keeps working, unless' list for Literal, enum and datetime parameters (each scheduled on main, each now a conversion error sent to the model, as described); and the class path against google-genai 2.32.0, the newest release the dependency cooldown lets me install. Checked and refuted: that the class path relies on the locked google-genai (2.32.0 declares and schedules the same arguments, and in 2.34.0's source the argument-check change applies only to string annotations, which class tools no longer pass); that the tests bypass the Workflow sandbox (the helper's default runner is sandboxed, so _call_signature ran in it). The error messages match #402 as merged. Not verified: google-genai 2.33.0 and 2.34.0 by run (newer than the cooldown), a live Gemini model, and the body's held-run and Worker-replacement checks (not rerun; that code path is unchanged since last round).

Severity: P1 = wrong result or stuck run in realistic use; P2 = correctness or robustness in an edge case; P3 = docs, tests, cleanup.

Previous rounds. Every item from my approval at f209df4 is addressed or reasonably declined. (1) Release notes: the first bullet now covers only calls that don't bind the other version's parameters, the stuck-run bullet and the reset-or-terminate advice are in, and functools.lru_cache is on the list. The new Rollback bullet uses my wording from last round, which was too broad (inline). (2) The regression test now fails on main's build with assert [] == ['P-1'] (14 selected tests in about 4 seconds, since TagParcel gets one attempt) and passes here on both Python versions. (3) Tests: dropping staticmethod, classmethod from _call_function now fails test_activity_as_tool_preserves_signature, and reading the class's own docstring from calls[0], or skipping the namedtuple branch, fails test_activity_as_tool_preserves_doc. Accepted: checking only the signature for the staticmethod and classmethod forms, which share the call path after it. (4) Accepted: leaving the constructor's Args: in the class-docstring fallback for a follow-up across plugins. #402, merged since, already cuts the class docstring at its Args section (_description in strands_agents/_temporal_activity_tool.py) and skips a non-string __doc__, so until that follow-up the two halves of #278 describe the same class differently. (5) The pre-existing function-tool gap stays out of scope and is now under 'Not covered'; the bullet below corrects that line. (6) The activity_as_tool summary now covers the parameters and docstring, but the wording I suggested gets the name wrong (inline).

Replay, at the head: unchanged and disclosed; the only runtime change since f209df4 is a docstring. Main's histories for a function tool, a Class.method tool, a matching class and BindsGetTime (its stuck run included) replay here. DiffTrack and ZeroCtorTag (its stuck run included) fail with [TMPRL1100] Nondeterminism error: Activity type of scheduled event 'ZeroCtorTag' does not match activity type of activity command 'gemini_api_client_async_request'. No version gate, per the stated 1.0 policy.

'Not covered', P3 (pre-existing): the new line says function tools in a module with from __future__ import annotations or quoted types fail google-genai's argument check for every parameter. That only holds where an annotation's names resolve in the plugin's own module (builtins such as str). When an annotation names anything else, such as a Pydantic model, Optional[str] or datetime.date, the declaration fails with NameError: name 'Parcel' is not defined on main and here, on 3.10 and 3.14, so the run fails every Workflow Task without sending a model request (with a real Worker on each build, on 3.14: two Workflow Task failures within seconds, run still Running). google-genai calls typing.get_type_hints on the wrapper, which evaluates the copied string annotations in temporalio.google_genai.workflow's globals (line 245, line 263); a Class.method tool fails the same way. That is a stuck run rather than an error the model sees, and a class tool in the same module now works, so the line should say so. According to its source, google-genai 2.34.0 (allowed by <3) resolves string annotations in the argument check, which leaves only the NameError case there.

Where the problems cluster: all three items are text: two corrections to wording I suggested last round (the Rollback bullet and the docstring summary) and one to the new 'Not covered' line.

Approving again: no P1 or P2 remains, every earlier item is fixed or reasonably declined, CI is green, and the replay break is the disclosed one.

p = p.replace(kind=inspect.Parameter.POSITIONAL_OR_KEYWORD)
# Gemini builds the declaration from the resolved types, but converts
# the model's arguments with the signature's, so give it those too.
parameters.append(p.replace(annotation=hints.get(p.name, p.annotation)))

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 (release notes, non-blocking): the new Rollback bullet says every class tool in a module with from __future__ import annotations or quoted types fails its Workflow Task on main, but only a constructor parameter with a string annotation does; the wording came from my comment last round ('whatever its constructor takes'), and I had it wrong.

On main, google-genai resolves a string annotation through typing.get_type_hints on the wrapper, whose __annotations__ are the class's own, so the declaration fails only for an annotated constructor parameter that isn't also a class annotation. A constructor with no parameters gives it nothing to parse. Classes in a from __future__ import annotations module, on main's build, 3.10 and 3.14:

  • E2ETrack, constructor (carrier: str): Failed to parse the parameter carrier: 'str' of function E2ETrack ..., as the bullet says.
  • ZeroCtorTag563, constructor (), the shape of this PR's TagParcel: declared with no parameters and scheduled with [].
  • A dataclass with a carrier: str = "acme" field: declared with carrier and scheduled with ["acme"].

I recorded a run of each on this head (each scheduled its Activity with ["P-1"]) and replayed it on main: E2ETrack fails with the declaration error, while ZeroCtorTag563 and the dataclass replay without error. So 'Runs that use such a tool on this version fail every Workflow Task after a rollback' doesn't hold for those two shapes: they replay, and a later call gets main's behaviour (no arguments and retries, or the constructor's parameter). Suggested text: 'Rollback: on main, a class tool fails its Workflow Task while the declaration is built when its constructor takes a parameter with a postponed or quoted annotation that isn't also a class annotation (a dataclass field is one). Runs that use such a tool on this version fail every Workflow Task after a rollback. Runs stuck on main that way continue on this version.' The Upgrade paragraph's advice to let runs finish before a rollback already covers the other shapes.


Returns an async callable with the same name, docstring, and type signature as
``fn``. When Gemini's automatic function calling (AFC) invokes the returned
Returns an async callable with the activity's name, and the parameters and

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, non-blocking): the summary says the tool has 'the activity's name', but it has fn.__name__, which differs whenever @activity.defn(name=...) renames the activity; that wording was also my suggestion last round.

Line 260 sets wrapper.__name__ = schema_fn.__name__, which is the name google-genai declares, while lines 248 and 255 schedule ret.name. With @activity.defn(name="lookup_parcel") class NamedTrack, activity_as_tool(NamedTrack).__name__ is NamedTrack and google-genai declares NamedTrack, while the Activity it schedules is lookup_parcel. A function renamed with @activity.defn(name="weather_lookup") keeps its function name the same way, on main and here. The body's 'The tool keeps the class name' is right. Suggested: 'Returns an async callable named like fn (the model sees that name even when @activity.defn(name=...) renames the activity), with the parameters and docstring the activity is called with (__call__'s for a class).' Please also rewrap line 173 (129 characters): ruff format leaves docstrings alone and the lint target runs ruff check with only the I rules, so nothing flags it.

campoy added a commit that referenced this pull request Nov 10, 2026
Resolve conflicts in AGENTS.md (add main's openai_codex row) and in
google_genai's activity_as_tool docstring (keep #404's wording, drop the
experimental warning).
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.

2 participants