Skip to content

[Bug] google_adk: activity_as_tool offers self for a method Activity passed as Class.method #309

Closed

Description

@campoy

Package: python/google_adk (temporalio-google-adk), 0.0.1 and main (db14ec3).

What happens

The Python SDK supports Activities defined as methods. The Worker registers a bound method of an instance, and Workflow code references the method as Class.method, the form workflow.execute_activity_method takes. activity_as_tool accepts Class.method, but it builds the tool from the method's own signature, so the tool asks the model for self too:

  • If the model fills self, the tool sends its value as an extra Activity argument. The Worker's bound method gets one argument too many and fails with TypeError: Tracker.track() takes 2 positional arguments but 3 were given on every attempt; its body never runs. Under the default retry policy the Activity retries without end.
  • If the model leaves self out, ADK returns a missing-parameter error to the model and no Activity runs.

A bound method of an instance built in Workflow code works. Callable-class Activities passed as their class have the same cause and are reported in #278.

Reproduction

One file. It starts a local dev server with WorkflowEnvironment.start_local(), runs a Worker with GoogleAdkPlugin, and runs an ADK agent whose scripted model fills the tool's offered parameters with "P-1", once with every parameter and once without self. A bound method of an instance built in Workflow code is the control. It exits 0 when the Class.method tool offers only parcel_id and runs the Worker's method with the model's value, 1 otherwise.

"""google_adk activity_as_tool with a method Activity passed as Class.method.

One file. Starts a local dev server, runs a Worker with GoogleAdkPlugin and an ADK agent whose
scripted model fills the tool's offered parameters. A bound method of an instance built in Workflow
code is the control. Exits 0 when the Class.method tool offers only `parcel_id` and runs the
Worker's method with the model's value, 1 otherwise.
"""

import asyncio
import sys
import uuid
from datetime import timedelta

from google.adk.agents import Agent
from google.adk.models import BaseLlm, LLMRegistry
from google.adk.models.llm_response import LlmResponse
from google.adk.runners import InMemoryRunner
from google.genai import types
from temporalio import activity, workflow
from temporalio.client import Client
from temporalio.common import RetryPolicy
from temporalio.testing import WorkflowEnvironment
from temporalio.worker import Worker
from temporalio.workflow import ActivityConfig

with workflow.unsafe.imports_passed_through():
    from temporalio.google_adk import GoogleAdkPlugin, TemporalModel
    from temporalio.google_adk.workflow import activity_as_tool


class Tracker:
    def __init__(self, carrier: str) -> None:
        self.carrier = carrier

    @activity.defn
    async def track(self, parcel_id: str) -> str:
        """Track a parcel."""
        return f"parcel {parcel_id} via {self.carrier}"


class ScriptedModel(BaseLlm):
    """Calls the tool with each offered parameter set to "P-1" (all, or all but `self`)."""

    @classmethod
    def supported_models(cls) -> list[str]:
        return ["scripted"]

    async def generate_content_async(self, llm_request, stream=False):
        last = llm_request.contents[-1].parts[0]
        if last.function_response:
            text = str(last.function_response.response)
            yield LlmResponse(content=types.Content(role="model", parts=[types.Part(text=text)]))
            return
        skip_self = llm_request.contents[0].parts[0].text == "skip self"
        decl = llm_request.config.tools[0].function_declarations[0]
        offered = list(decl.parameters_json_schema["properties"])
        args = {p: "P-1" for p in offered if not (skip_self and p == "self")}
        text = f"offered {offered}, calling with {args}"
        call = types.FunctionCall(name=decl.name, args=args)
        yield LlmResponse(
            content=types.Content(role="model", parts=[types.Part(text=text), types.Part(function_call=call)])
        )


@workflow.defn
class ToolWorkflow:
    @workflow.run
    async def run(self) -> dict[str, list[str]]:
        cases = [
            ("control: instance.track", Tracker("unused").track, "fill all"),
            ("Tracker.track", Tracker.track, "fill all"),
            ("Tracker.track, model leaves out self", Tracker.track, "skip self"),
        ]
        out = {}
        for label, fn, prompt in cases:
            tool = activity_as_tool(
                fn, start_to_close_timeout=timedelta(seconds=5), retry_policy=RetryPolicy(maximum_attempts=1)
            )
            agent = Agent(
                name="agent",
                model=TemporalModel("scripted", activity_config=ActivityConfig(start_to_close_timeout=timedelta(seconds=5))),
                tools=[tool],
            )
            runner = InMemoryRunner(agent=agent, app_name="app")
            session = await runner.session_service.create_session(app_name="app", user_id="u")
            texts = []
            try:
                async for event in runner.run_async(
                    user_id="u",
                    session_id=session.id,
                    new_message=types.Content(role="user", parts=[types.Part(text=prompt)]),
                ):
                    texts += [p.text for p in (event.content.parts if event.content else []) or [] if p.text]
            except Exception as e:
                while e.__cause__ is not None:
                    e = e.__cause__
                texts.append(f"{type(e).__name__}: {e}")
            out[label] = texts
        return out


async def main() -> int:
    LLMRegistry.register(ScriptedModel)
    async with await WorkflowEnvironment.start_local() as env:
        client = Client(**{**env.client.config(), "plugins": [GoogleAdkPlugin()]})
        async with Worker(
            client, task_queue="q", workflows=[ToolWorkflow], activities=[Tracker("acme-post").track]
        ):
            out = await client.execute_workflow(ToolWorkflow.run, id=f"tools-{uuid.uuid4()}", task_queue="q")
    for label, texts in out.items():
        print(f"{label}:")
        for text in texts:
            print(f"  {text}")
    ok = out["Tracker.track"] == [
        "offered ['parcel_id'], calling with {'parcel_id': 'P-1'}",
        "{'result': 'parcel P-1 via acme-post'}",
    ]
    print("correct" if ok else "bug")
    return 0 if ok else 1


if __name__ == "__main__":
    sys.exit(asyncio.run(main()))

Output with Python 3.13.16 and temporalio 1.34.0, in each build's locked environment (dev server and ADK warnings left out):

$ python method_tool.py   # temporalio-google-adk 0.0.1
control: instance.track:
  offered ['parcel_id'], calling with {'parcel_id': 'P-1'}
  {'result': 'parcel P-1 via acme-post'}
Tracker.track:
  offered ['self', 'parcel_id'], calling with {'self': 'P-1', 'parcel_id': 'P-1'}
  ApplicationError: TypeError: Tracker.track() takes 2 positional arguments but 3 were given
Tracker.track, model leaves out self:
  offered ['self', 'parcel_id'], calling with {'parcel_id': 'P-1'}
  {'error': 'Invoking `track()` failed as the following mandatory input parameters are not present:\nself\nYou could retry calling this tool, but it is IMPORTANT for you to provide all the mandatory parameters.'}
bug
exit 1
$ python method_tool.py   # python/google_adk on main (db14ec3)
control: instance.track:
  offered ['parcel_id'], calling with {'parcel_id': 'P-1'}
  {'result': 'parcel P-1 via acme-post'}
Tracker.track:
  offered ['self', 'parcel_id'], calling with {'self': 'P-1', 'parcel_id': 'P-1'}
  ApplicationError: TypeError: Tracker.track() takes 2 positional arguments but 3 were given
Tracker.track, model leaves out self:
  offered ['self', 'parcel_id'], calling with {'parcel_id': 'P-1'}
  {'error': 'Invoking `track()` failed as the following mandatory input parameters are not present:\nself\nYou could retry calling this tool, but it is IMPORTANT for you to provide all the mandatory parameters.'}
bug
exit 1
Build Google ADK in the lock file
temporalio-google-adk 0.0.1 google-adk 2.9.2, google-genai 2.24.0
main (db14ec3) google-adk 2.12.0, google-genai 2.30.1

Expected

The control already works. The Class.method tool offers only parcel_id, schedules the method's Activity with ["P-1"], and the Worker's method returns parcel P-1 via acme-post.

Proposed fix

Build the tool without the method's receiver, the way the SDK drops it: a first parameter named self that is unannotated or annotated typing.Self. #206 does this for openai_agents, and #300 for deepagents. Function, bound-method and instance tools stay the same. A run whose model called a method tool before the change got the missing-parameter error and called the model again; with the fix the tool schedules the method's Activity there, so such a run would fail replay with [TMPRL1100] after the upgrade.

A PR follows, together with the google_adk part of #278.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions