Skip to content

Breaking: support method and callable-class Activities in Deep Agents activity_as_tool - #300

Merged
campoy merged 5 commits into
mainfrom
fix/deep-agents-python-activity-as-tool-argument-forms
Nov 2, 2026
Merged

campoy merged 5 commits into
mainfrom
fix/deep-agents-python-activity-as-tool-argument-forms

Conversation

@campoy

@campoy campoy commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

What was changed

activity_as_tool in deepagents now calls methods passed as Class.method and callable-class Activities passed as their class. #313 already made it call function Activities with several parameters; this change passes the arguments the same way for every form.

  • The tool's schema has the parameters the Activity is called with. For a method, a first parameter named self is dropped, however it is annotated: the Worker registers the bound method, so its instance fills it. For a class, the schema comes from __call__ as an instance binds it (without the receiver of a method, classmethod or functools.partialmethod, with every parameter of a staticmethod), and __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.
  • Calls schedule the Activity with args=[...], the model's arguments in parameter order, with defaults filled in, as Support zero- and multi-parameter activities in Deep Agents' activity_as_tool #313 does for functions. The arguments are bound with the tool's signature, so the tool body no longer copies the Activity's signature with @wraps.
  • These now fail with ValueError when the tool is built: an instance of a callable-class Activity in place of its class, a class whose __call__ is missing or of another kind or can't be read, and any Activity with *args, keyword-only parameters or **kwargs, which the tool can't pass. Positional-only parameters are offered by name and passed by position.
  • For function tools, the schema, the recorded command and its input stay the same as on main. The scheduled Activity name doesn't change for any form.
  • The activity_as_tool docstring names the three forms.

This is the design of #206 for openai_agents, applied to deepagents. Two differences: errors are ValueError, like this function's existing errors, and *args is refused; openai_agents passes it through the SDK's function_schema.

No public name or option changes.

Breaking change: some tools that work today are now refused, and some old histories stop replaying. 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.

These tools work on main (run at 1e8ae93; #313 doesn't change how they are built or called) and now raise ValueError when they are built, before anything is scheduled. Each is a callable-class Activity that declares its call parameter on the class (parcel_id: str):

  • The class passed as its class, with one constructor parameter matching __call__'s first, where __call__ also takes *args, a keyword-only parameter (*, via: str = "default") or **kwargs. On main the tool used the constructor's schema, so those were never offered or sent.
  • An instance passed in place of its class, whose __call__ takes one parameter.

New runs of these applications fail until the tool is changed. Draining old runs or Worker Versioning doesn't help. Function and method tools with keyword-only parameters or **kwargs already fail on main: the tool passes those values by position. A function with *args gets the model's list as one argument on main; it is now refused too.

Two kinds of runs recorded before this change fail replay with [TMPRL1100]:

  • A run whose model called a method tool without self. LangChain rejected the call and the model was called again; built without self, the tool now schedules the method's Activity instead.
  • A run whose model called a callable-class tool with the constructor's arguments. The tool now rejects them, and the model is called again where the history has the class's Activity.

A run stuck because its model passed self to a method tool completes after the upgrade. A run stuck because its class tool failed to build should continue too (not run). Function tools are not affected. For the release notes of #313's change: a run from before #313 whose multi-parameter tool Activity is still retrying stays stuck after the upgrade, because each retry reuses the one-dict input in its history. Reset it to a Workflow Task before that model turn, so the new code schedules the right arguments, or terminate it.

Upgrade:

  1. Let runs that called a method tool or a callable-class tool, and open runs that build a refused tool, finish on the earlier version before you upgrade, or keep them there with Worker Versioning.
  2. In the same deployment as the upgrade, change refused tools:
    • Pass the class, not an instance. Before this change that form offered the constructor's parameters.
    • Make a keyword-only parameter positional with its default. The model is then offered it.
    • Remove an unused *args or **kwargs.
    • To keep a parameter hidden from the model, call the Activity from your own tool with workflow.execute_activity_class(...).

Why?

See #298 and #278. Before #313, activity_as_tool sent the model's arguments as one Activity argument, so a multi-parameter Activity got one dict and failed with TypeError on every attempt. #313 fixed that for functions. The tool still copies the Activity's signature onto the tool body with @wraps, which fits only a module-level function:

  • A method's schema asks for self. Without it, LangChain rejects the call; with it, the tool raises TypeError in Workflow code.
  • A callable class passed as its class offers its constructor's parameters, and their values reach __call__. With a one-string constructor and a one-string call, the run completes with a wrong result and no error. Other constructors fail to build the tool or fail every call.

Checklist

  1. Closes [Bug] deepagents: activity_as_tool fails for Activities with more than one parameter and for methods #298. Fixes the deepagents 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 in tests/test_tools.py builds a tool for a one-parameter function, a three-parameter function (its first parameter positional-only; the call leaves out a default and passes the parameter after it), a method passed as Class.method and a callable class passed as its class, invokes each, and checks the results and that each Activity was scheduled once.
    • test_activity_as_tool_schema checks the schema and description for two methods (one with self: Self under from __future__ import annotations), the class, its staticmethod, classmethod and functools.partialmethod __call__ forms, the parameter descriptions from Annotated for a method and a class, and the description fallbacks: __call__'s docstring ahead of the class's, the class's own docstring, an inherited __call__'s, and a dataclass whose generated docstring is skipped.
    • test_activity_as_tool_rejects checks the ValueError for a class without __call__, keyword-only parameters (also when a functools.partialmethod binds an argument by keyword, which the message names), *args, **kwargs, an annotation that can't be resolved, and an instance.
    • With main's build at 88745dc, 17 of these 18 cases fail: all the schema and rejects cases, and test_activity_as_tool, which times out (run on a85ffba). Support zero- and multi-parameter activities in Deep Agents' activity_as_tool #313's test_activity_as_tool_passes_each_parameter passes on both. All 18 pass with the change.
    • Locally, on 8d87709: all 171 tests pass, and ruff check --select I, ruff format --check, mypy, basedpyright, pydocstyle and pyright pass. These ran in Docker with Python 3.13 and uv 0.13.1, outside the plugin's required-version, so not through make. CI covers make lint and make test.
    • For seven function Activities (five with one parameter: a string, a dataclass, a default, an Optional, an Annotated description; one with two parameters; one with none), the tool schema the model gets is the same on main at 88745dc and with the change.
    • Fresh runs, on main at 1e8ae93 and with the change at 5c1b711: the three tools listed under "Breaking change" schedule ["P-1"] and return their results on main, and raise ValueError before scheduling with the change. A one-parameter function and a class whose constructor and __call__ take the same parcel_id work on both. Making via positional (now offered to the model), removing **kwargs, and passing the class instead of the instance work with the change.
    • [Bug] deepagents: activity_as_tool fails for Activities with more than one parameter and for methods #298's reproduction exits 1 on 0.0.3 and on main at 1e8ae93, and 0 with the change at 5c1b711: the two-parameter tool schedules ["c-1", 7] and returns c-1/7, and the method tool offers only parcel_id and returns parcel P-1. [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.
    • Replay, on a85ffba against main at 88745dc: Workers with no Workflow cache recorded, on each, a finished run and a run held between two agent turns for each tool form: a one-parameter function, a two-parameter function, a method and a callable class. Each run is a Deep Agent with a scripted model that fills the offered schema (leaving out self). On main, the method runs answer with LangChain's self: Field required error, and the class runs complete with the model's carrier value as parcel_id.
      • Each version replays its own 8 histories.
      • main histories on this branch: the method and class ones fail with [TMPRL1100], for example Activity type of scheduled event 'deepagents.invoke_model' does not match activity type of activity command 'shipping.track'. The one- and two-parameter ones replay.
      • This branch's histories on main (the rollback target): the method and class ones fail with [TMPRL1100]; the other four replay.
      • A control that renames the model Activity fails all 16 with [TMPRL1100].
      • A held one-parameter run completes when carried from this branch to main and from main to this branch, and on a replacement Worker of this branch; so does a held class run on a replacement Worker. A held class run carried in either direction stops with [TMPRL1100], as the replay showed. A run on main stuck because the model passed self to a method tool completes after the upgrade.
      • The histories recorded earlier on main at 1e8ae93 and on 5c1b711 replay on a85ffba the same way: all 8 from 5c1b711, and the one- and two-parameter ones from 1e8ae93.
      • The Workers and the replayer ran with debug_mode=True: in this container, the first create_deep_agent call in a fresh sandbox tripped the 2-second deadlock detector.
  3. Any docs updates needed?
    The activity_as_tool docstring is updated here. Release notes should name the refused tools and their migrations, and say which runs stop replaying (see "Breaking change").

Not covered:

…es in Deep Agents activity_as_tool

activity_as_tool built the tool's schema from the object it was given and sent
the model's arguments as one Activity argument. That only fit a module-level
function with one parameter: a multi-parameter Activity got one dict, a method's
schema asked for `self`, and a callable class passed as its class offered its
constructor's parameters and sent their values to `__call__`.

The tool now takes the parameters the Activity is called with (without a
method's receiver, and from `__call__` for a class, resolving its annotations in
its own module) and schedules the Activity with those arguments in order.
Keyword-only arguments, `**kwargs` and an instance of a callable-class Activity
are rejected when the tool is built.

Runs that called a method tool or a callable-class tool before this change fail
replay with [TMPRL1100].

@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 5c1b711. On a worktree at the head, make lint is clean and make test passes 143 of 143 (Python 3.14). Findings were verified with probe scripts against the locked temporalio 1.34.0, langchain-core 1.6.6 and deepagents 0.7.21, comparing main's _tools.py (1e8ae93) with this head, and the *args item end to end through create_deep_agent on a dev server with a temporary test, since removed. Checked and refuted: the docstring lookup does not reach object or library class docstrings (it reads __doc__ directly, class docstrings are not inherited, and only MRO classes that define __call__ are consulted); the self strip is the SDK's own rule from _type_hints_from_func (its PEP 563 gap is the self: Self comment below); the exception scope is wide enough (the class branch catches Exception, and the function branch's get_type_hints has already succeeded once, because @activity.defn resolves the same hints when it decorates); keyword-only parameters and **kwargs fail at build with ValueError, and staticmethod, classmethod and partialmethod __call__ forms give the right schema and Activity arguments by probe; no ApplicationError is constructed; the changed schemas only change the model Activity's input, which replay does not compare, and seven function schemas (five one-parameter, one two-parameter, one zero-parameter) are identical to main's after convert_to_openai_tool. Rejecting an instance of a callable class is not a regression either: main already failed to build that tool (NameError: name 'Any' is not defined, or KeyError when the class has class-level annotations). I did not re-run the PR's replay matrix; its Breaking change section matches the code.

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 new signature handling is right for the three forms the PR names. Both P2s are parameter shapes at its edge: a *args parameter that is offered to the model but cannot be passed, and a self: Self receiver that is kept under from __future__ import annotations. The P3s are the description of an undocumented dataclass, test coverage, and one line for the release notes.

On the open question, I'd keep ValueError. 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, while an ApplicationError raised from Workflow code fails them for good. It also matches this function's existing errors.

Leaving a comment rather than approving: there is no P1, but the *args case turns a failing Activity into a Workflow Task failure loop and the fix is two lines, so I'd like it settled first.

  • P3 (release notes): runs on main whose multi-parameter tool Activity is still retrying stay stuck after the upgrade. Retries reuse the single-dict input recorded in ActivityTaskScheduled, and under the default retry policy they never end. The Breaking change section says these runs replay, which is true; it should also say they need a reset to the Workflow Task before that model turn (the new code then schedules the right arguments), or termination.

raise ValueError(
f"activity_as_tool cannot pass keyword-only argument {p.name!r}."
)
if p.kind is inspect.Parameter.VAR_KEYWORD:

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): an Activity with *args is offered to the model with that parameter, and a call that fills it raises TypeError from signature.bind in Workflow code, so the run sits in a Workflow Task failure loop. The loop rejects keyword-only parameters and **kwargs but lets VAR_POSITIONAL through, so join_parts(first: str, *rest: str) builds a tool whose schema is ['first', 'rest']. signature.bind(first='a', rest=['b', 'c']) at line 355 raises TypeError: got an unexpected keyword argument 'rest'. ToolNode's default handler re-raises anything that is not a ToolInvocationError (langgraph/prebuilt/tool_node.py:383-391), and run_deep_agent re-raises it unchanged because it has no Temporal cause (workflow.py:280-286). Reproduced through create_deep_agent with mock_model_provider scripting that call, on a dev server: the Workflow stays Running with the Workflow Task failure got an unexpected keyword argument 'rest'. On main the same call scheduled the Activity with one dict and failed inside the Activity, so the stuck Workflow Task is new. The PR body lists *args as not handled, but not this outcome. Fix: reject it at build time like the other two kinds, if p.kind is inspect.Parameter.VAR_POSITIONAL: raise ValueError(f"activity_as_tool cannot pass *{p.name}.") (on a patched copy this gives activity_as_tool cannot pass *rest.), and add it to Raises: and to test_activity_as_tool_rejects. Leaving the parameter out of the schema would also work if you want such Activities usable without it. Raises: also leaves out the error for a class without a usable __call__ (lines 244-248).

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 59c61ef: *args is now refused when the tool is built, like keyword-only arguments and **kwargs. Your join_parts gets activity_as_tool cannot pass *rest. Raises: now names *args and a class without a __call__ the tool can use, and test_activity_as_tool_rejects has a *more case. For reference, openai_agents (#206) keeps *args: its function_schema offers them as a list and spreads them into positional arguments, which signature.bind here can't do.

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 schema, so the model can never call it. Under PEP 563, inspect.signature returns the annotation as the string 'Self', so this line compares 'Self' == 'typing.Self' and the strip is skipped. Probe with class SelfShipping: @activity.defn async def track(self: Self, parcel_id: str): the tool's parameters are {'self': {}, 'parcel_id': {...}}, both required. In the args schema self is the recursive model track, so ainvoke({'parcel_id': 'P-1'}) fails with self: Field required and no value the model can send validates. Main behaves the same, so this is not a regression, but the PR body says a receiver annotated typing.Self is dropped. The SDK's identical string check costs it only typed decoding: its arg_types are [typing.Self, str], the Worker sees a count mismatch with the one payload and decodes without types, and the bound method still runs. Here the same check decides the model-facing schema. Fix: use the hints already resolved at line 264, or hints.get("self") is typing.Self. On a patched copy this gives ['parcel_id'] for the PEP 563 case and leaves the plain self case unchanged.

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 59c61ef, more broadly than your suggestion: a method passed as Class.method now drops a first parameter named self however it is annotated, the rule #206 and #312 use now too. That covers self: Self under from __future__ import annotations, and also self: T with a TypeVar bound to the class, which raised PydanticUserError when called. The one case it gives up, a module-level function whose first parameter is named self, can't be called here anyway: LangChain's StructuredTool._arun(self, ...) rejects a self argument (got multiple values for argument 'self'). test_activity_as_tool_schema has a self: Self case (the test module uses from __future__ import annotations).

# __call__'s own docstring, else the class's, else that of a __call__ it inherits.
doc = (
_docstring(_call_function(vars(activity).get("__call__")))
or _docstring(activity)

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 advertises its constructor signature as the tool description, naming the parameters the PR stops offering. dataclasses writes __doc__ as QuoteShipping(carrier: str) when the class has none, and this line takes it ahead of an inherited __call__ docstring. Probe: @activity.defn @dataclass class QuoteShipping(ShippingBase): carrier: str, 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')" (quoted under PEP 563). The body calls this a deliberate difference from #206 but gives no reason. For the model, a description naming carrier beside a schema asking for parcel_id is the confusion this PR removes from the schema. Suggest skipping the class docstring when dataclasses.is_dataclass(activity) and it is the generated one (it starts with f"{activity.__name__}("), so the inherited __call__ docstring or Temporal activity QuoteShipping. is used, as #206 does.

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 59c61ef: the class docstring is skipped when it is exactly the one dataclasses (or namedtuple) wrote, so your QuoteShipping now gets Quote shipping for a parcel. I used the exact-match helpers from #206 and #312 instead of the prefix check, so a handwritten docstring that starts with QuoteShipping( is kept; #206 moved off the prefix check for that reason. EchoDataclass in test_activity_as_tool_schema covers it.

Comment thread python/deepagents/tests/test_tools.py Outdated
# No `self` for a method passed as Class.method.
(EchoActivities.echo_method, ["text"], "Temporal activity echo_method."),
# A class offers __call__'s parameters and docstring, not its constructor's.
(EchoClass, ["text"], "Echo text with the worker's prefix."),

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 tests don't cover three behaviours the PR changes or describes. (a) The one change for one-parameter functions, a default the model leaves out is now passed (bound.apply_defaults() in _tools.py), has no case; echo_twice has no default. (b) The staticmethod, classmethod and partialmethod __call__ forms. (c) The docstring fallbacks: the class docstring, an inherited __call__ docstring, and the dataclass choice above. By probe they all behave as described: with_default(city: str, days: int = 3) called with {'city': 'Oslo'} schedules ['Oslo', 3]; the three descriptor forms offer ['text'] and schedule ['t']; an inherited documented __call__ supplies its docstring. So this is regression cover only: a default on echo_twice with one call that leaves it out, three small classes in this parametrization, and one inherited-__call__ row would pin them.

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 59c61ef:

  • (a) echo_twice now has two defaults, and the call leaves out times but sets sep. It only returns hi+hi if the tool passes the default for times. A single trailing default would pass without apply_defaults too, since the Activity's own default applies. Support zero- and multi-parameter activities in Deep Agents' activity_as_tool #313's test_activity_as_tool_passes_each_parameter, merged in from main in a85ffba, covers a trailing default and a zero-parameter Activity.
  • (b) staticmethod, classmethod and partialmethod __call__ cases in test_activity_as_tool_schema.
  • (c) cases for the class docstring, an inherited __call__ docstring, and the dataclass.

…rated dataclass docstrings

- Refuse an Activity with *args when the tool is built: the tool passes
  one argument per parameter, so a call that filled it failed the
  Workflow Task.
- Drop a method's first `self` parameter however it is annotated, so
  `self: Self` under `from __future__ import annotations` and a TypeVar
  self type are dropped too.
- Skip a class docstring only when dataclasses or namedtuple wrote it, as
  openai_agents and google_adk do.
- Name *args and a class without a usable __call__ in Raises.
- Extend the tests: a default the model leaves out before one it passes,
  the staticmethod, classmethod and partialmethod __call__ forms, the
  docstring fallbacks, `self: Self` and *args.
#313 maps the model's arguments onto a function Activity's parameters.
This branch already does that with signature.bind for every form, so its
version is kept, with #313's reason for passing defaults. #313's test
stays.
basedpyright reports it as an unused parameter.
@campoy campoy changed the title Breaking: support multi-parameter, method and callable-class Activities in Deep Agents activity_as_tool Breaking: support method and callable-class Activities in Deep Agents activity_as_tool Nov 1, 2026
@campoy

campoy commented Nov 1, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the review. The changes are in 59c61ef, a85ffba merges main, and 8354be8 fixes a basedpyright warning in the new test. Replies are in the threads. On the summary:

@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 8354be8. 59c61ef answers the last round, a85ffba merges main and keeps this branch's argument binding over #313's (it takes only #313's comment into _tools.py and keeps #313's test), and 8354be8 renames a test helper's parameter; main has not touched python/deepagents since. On a worktree at the head, make lint is clean and make test passes 170 of 170 (Python 3.14.3, temporalio 1.34.0, langchain-core 1.6.6, deepagents 0.7.21), and CI is green on 3.11 and 3.14. I re-ran each round-one reproduction against the installed head, compared main's and the head's _tools.py by probe on 3.14 and 3.11, ran the head's new tests against main's build (16 of 17 fail and #313's test passes, as the body says), put twelve one-line mutations of _tools.py through make test, re-ran the replay matrix (below), and passed the same Activity shapes to Google ADK's activity_as_tool on main. Checked and refuted: LangChain dropping a leading self or cls now that _run's qualname contains a dot (StructuredTool.from_function passes filter_args, which skips that branch); the removal of @wraps changing function-tool schemas (seven schemas, including an Annotated description and a dataclass parameter, are identical to main's after convert_to_openai_tool); anything reading the __wrapped__ or copied __dict__ that @wraps left on _run (nothing in the plugin, deepagents 0.7.21 or LangChain's call path); the unguarded get_type_hints in the function branch raising for realistic code (@activity.defn resolves the same hints when it decorates, and an instance is refused first). The one function-tool difference from main is a fix: a parameter named cls, which #313's mapping skips (classify(text, cls) schedules ['t'] on main), is now passed (['t', 'c']); #313 is not released yet (the latest tag is v0.0.3), so it needs no release note. 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.

Previous rounds. All addressed; I checked each by re-running its reproduction. *args is refused at build for every form (star_args(first, *rest) raises activity_as_tool cannot pass *rest.), and Raises: names it and the class without a usable __call__. A self: Self method under from __future__ import annotations now offers ['parcel_id'] and schedules ['P-1']; the fix is broader than the one I suggested (any first parameter named self is dropped). The shape this gives up, a staticmethod or module-level function whose first parameter is named self, now offers the remaining parameters and schedules its Activity one argument short, so every attempt fails with missing 1 required positional argument: 'x'. Main could never call it either (StructuredTool._arun() got multiple values for argument 'self', or LangChain's validation error when the model left self out), as your reply says, so I accept the simpler rule. The generated dataclass docstring is skipped by exact match, with helpers identical to #312's. The descriptor forms and the docstring fallbacks have tests, and the mutations I ran against them (no descriptor unwrapping, dropping the first parameter instead of binding with __get__, keeping the generated docstring) each fail one; the defaults case does not pin what its comment says (inline). The reset-or-terminate note for runs from before #313 is in the body, and ValueError stays. A correction to my last round: 'main already failed to build an instance tool' holds on Python 3.14 (NameError: name 'Any' is not defined), but on 3.11 the narrow shape the body lists builds and schedules ['P-1'] on main, so listing it under Breaking change is right.

Replay, at the head: real Workers on the pinned dev server recorded a Deep Agent run with a scripted model for a one-parameter function, a two-parameter function, a method called without self, and a callable class called with the schema each build offers (on main that class run completes with the model's carrier value as parcel_id: worker:acme). Main's histories on the head: both function runs replay; the method run fails with [TMPRL1100] Nondeterminism error: Activity type of scheduled event 'deepagents.invoke_model' does not match activity type of activity command 'track', and the class run with the same error for 'QuoteShipping' against 'deepagents.invoke_model'. The head's histories on main split the same way, and each build replays its own four. A run stuck on main because the model passed self (Workflow Task failure StructuredTool._arun() got multiple values for argument 'self') completed on a head Worker (track scheduled, parcel P-1). That is the disclosed break, with no gate per the stated 1.0 policy.

Parity with Google ADK (#312, on main): the docstring helpers are identical, and both plugins now drop self: Self under PEP 563 (['parcel_id'] here by probe, and the PostponedHolder.track row there). They differ on purpose in three places, each defensible: an instance is accepted there (it worked and replayed before #312) and refused here (only the narrow shape above built on main); *args in __call__ is left out of ADK's declaration there and refused here; and a staticmethod or function whose first parameter is self keeps it there, through the class lookup, and loses it here (above). The partialmethod message is the one difference that looks unintended (inline).

Where the problems cluster: the code is right for the three forms and for the refusals. What is left is at the edges: one refused class shape missing from the Breaking change list, the partialmethod message #312 already improved, and tests that pin LangChain's default filling rather than the tool's.

On the open question, I'd keep refusing all three. An instance's constructor arguments in Workflow code are ignored, because the Worker's registered instance runs (EchoClass('workflow') would answer with the Worker's prefix), so accepting it as its class would hide a mistake. Refusing keyword-only parameters and **kwargs matches #312, and also @activity.defn, which refuses keyword-only parameters on functions.

Approving: there is no P1 or P2, CI is green, every round-one item is fixed (including the *args Workflow Task loop I wanted settled first), and the replay break is exactly the disclosed one.

parameters = []
for p in signature.parameters.values():
if p.kind is inspect.Parameter.VAR_POSITIONAL:
raise ValueError(f"activity_as_tool cannot pass *{p.name}.")

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 (PR body, non-blocking): a callable class whose __call__ takes *args after a parameter matching its constructor's works on main and is refused here, but the Breaking change list names only keyword-only parameters and **kwargs for classes, and lists *args only for functions, where main passed the model's list as one argument. Probe with @activity.defn class TrackVarargs (class-level parcel_id: str, __init__(self, parcel_id: str), async def __call__(self, parcel_id: str, *extra: str)) in a module without from __future__ import annotations: on main, on Python 3.11 and 3.14, the tool offers ['parcel_id'] and schedules ['P-1'], which the Worker's instance runs with extra == (); on the head, building it raises activity_as_tool cannot pass *extra. Refusing it is consistent with the other two kinds. Since the release notes are pasted from the body, add it to that list and 'Remove an unused *args' to Upgrade step 2.

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 to the description. The class bullet under "Breaking change" now names *args alongside keyword-only parameters and **kwargs, and Upgrade step 2 says "Remove an unused *args or **kwargs." Your TrackVarargs probe gives the same here: on main at 88745dc it offers ['parcel_id'] and schedules ['P-1'], and on this branch it raises activity_as_tool cannot pass *extra.

raise ValueError(f"activity_as_tool cannot pass *{p.name}.")
if p.kind is inspect.Parameter.KEYWORD_ONLY:
raise ValueError(
f"activity_as_tool cannot pass keyword-only argument {p.name!r}."

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): a functools.partialmethod __call__ that binds a trailing argument by keyword is refused with a message about a keyword-only argument the user never declared, where #312 names the cause. With async def _quote(self, trip: str, passengers: int, currency: str = 'USD') and @activity.defn class QuoteEUR: __call__ = functools.partialmethod(_quote, currency='EUR'), this raises activity_as_tool cannot pass keyword-only argument 'currency'., while Google ADK on main raises ... cannot take keyword-only arguments or **kwargs in __call__ ('currency'): activities get their arguments by position. Its functools.partialmethod binds an argument by keyword, which makes the arguments after it keyword-only. Refusing is right (on main this class built a zero-parameter tool that scheduled []), and on #312 you kept the refusal to match this PR and #206 while changing that message. Passing isinstance(calls[0], functools.partialmethod) and bool(calls[0].keywords) from the class branch into this loop and appending the same sentence would make the two plugins say the same thing.

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 8d87709. When __call__ is a functools.partialmethod that binds an argument by keyword, the error now ends with the same sentence as #312's. Your QuoteEUR gets activity_as_tool cannot pass keyword-only argument 'currency'. Its functools.partialmethod binds an argument by keyword, which makes the arguments after it keyword-only. PartialKeywordEchoClass in test_activity_as_tool_rejects covers it.

Comment thread python/deepagents/tests/test_tools.py Outdated
async def run(self, text: str) -> list[str]:
calls: list[tuple[Callable[..., Any], dict[str, Any]]] = [
(echo_activity, {"text": text}),
# `times` is left out: the tool passes its default, so `sep` still

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): this case passes with bound.apply_defaults() deleted, because LangChain fills schema defaults before it calls the tool, and two other behaviours the PR relies on are not pinned either. BaseTool._parse_input adds every field with a default that the input leaves out (in langchain-core 1.5.0, the floor, through the locked 1.6.6), so _run already receives times=2. With _tools.py:408 removed, make test PYTEST_ARGS="tests/test_tools.py -k 'test_activity_as_tool and not schema and not rejects'" gives 2 passed. By probe, tool.ainvoke({'text': 'hi', 'sep': '+'}) schedules ['hi', 2, '+'] with or without that line, while await tool.coroutine(text='hi', sep='+') schedules ['hi', 2, '+'] with it and ['hi'] without. So this comment and the reply describe LangChain's behaviour, not the tool's: call tool.coroutine directly for this case to pin the tool's own default handling, or reword the comment. Also unpinned, each a one-line mutation that leaves the suite green: dropping include_extras=True (_tools.py:318 for functions, 305 for classes) removes Annotated descriptions from the schema (city: Annotated[str, 'The city name'] loses "description": "The city name" in both forms), which the body's claim that function-tool schemas are unchanged depends on; and swapping _tools.py:312 and 313, because no fixture has both a class docstring and its own __call__ docstring. An Annotated parameter on one function and one class in test_activity_as_tool_schema, asserting tool.args[name]['description'], and one class with both docstrings would pin them; #312's tests check an Annotated description the same way.

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.

You're right, and my reply in the last round was wrong: LangChain's _parse_input fills in schema defaults before it calls the tool, so this case can't tell whether the tool fills them. Changes in 8d87709:

  • The comment now says LangChain fills in the default. I kept apply_defaults for callers that skip LangChain's parsing, such as tool.coroutine, and didn't add a test for that path.
  • echo_method and EchoClass.__call__ now take an Annotated description, and test_activity_as_tool_schema checks each offered parameter's description.
  • EchoClass now has a class docstring as well, so its case checks that __call__'s docstring comes first.

I ran your mutations against the schema and rejects tests: dropping include_extras=True in either branch, checking the class docstring before __call__'s, and dropping the new partialmethod sentence each fail one case; the unchanged code passes.

…ns and docstring order

- When a functools.partialmethod __call__ binds an argument by keyword,
  say so in the keyword-only error, as google_adk does.
- Check Annotated parameter descriptions for a method and a class, and
  give EchoClass a class docstring so its case checks that __call__'s
  docstring comes first.
- Say in the defaults case that LangChain fills in the default.
@campoy

campoy commented Nov 2, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the second round. Replies are in the threads, and the change is in 8d87709. Since you'd keep refusing all three constructions, I removed the open question from the description.

@campoy
campoy merged commit 2bc84f3 into main Nov 2, 2026
27 checks passed
@campoy
campoy deleted the fix/deep-agents-python-activity-as-tool-argument-forms branch November 2, 2026 22:46
campoy added a commit that referenced this pull request Nov 3, 2026
Drop the staticmethod self lookup, the tool spec layer for agent, cls,
underscore-prefixed names and forward references, and the pydantic
dependency, by decision on #402. Drop self by name, as #206 and #300 do,
and keep positional-only binding, which the class change needs.
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] deepagents: activity_as_tool fails for Activities with more than one parameter and for methods

2 participants