Skip to content

[Bug] openai_agents: activity_as_tool builds a callable-class Activity's tool from its constructor #205

Closed

Description

@campoy

Package: temporalio-openai-agents 1.1.0 and main (c664a34); also temporalio.contrib.openai_agents in temporalio 1.33.0 and 1.34.0.

What happens

The Python SDK documents three Activity forms: functions, methods, and callable classes. Workflow
code references a callable-class Activity by its class (workflow.execute_activity_class), and the
Worker registers an instance.

activity_as_tool accepts the class, but builds the tool from the class's signature, which is its
constructor's. The model is offered the constructor's parameters, and the values it sends are passed
to __call__'s parameters by position. With a one-string constructor and a one-string call, the
model's carrier value reaches __call__ as parcel_id, and the run completes with a wrong
result and no error.

Other constructors fail in other ways: one that takes a client object fails tool construction in
Workflow code with PydanticSchemaGenerationError, so the Workflow Task fails until the Workflow
times out; a two-string constructor makes every call fail with TypeError: __call__() takes 2 positional arguments but 3 were given. Function and Class.method Activities work.

Cause: activity_as_tool calls the Agents SDK's function_schema(fn) on what it is given and
strips a leading self only from methods. For a class, inspect.signature(cls) is the constructor's
signature.

Reproduction

One file, no network: a scripted model that fills each offered parameter by its meaning, as a real
model would, and a local dev server (temporal CLI on PATH). It exits 1 when the Activity gets
the constructor's value.

"""activity_as_tool builds a callable-class Activity's tool from its constructor.

The model fills the schema it is offered, so the constructor's `carrier` value reaches the
Activity's `parcel_id` parameter and the run completes with a wrong result.
Exits 1 when that happens, 0 when the Activity gets the parcel id.
"""

import asyncio
import json
import shutil
import sys
import uuid
from datetime import timedelta

from agents import Model, ModelResponse, Usage
from openai.types.responses import ResponseFunctionToolCall
from temporalio import activity, workflow
from temporalio.testing import WorkflowEnvironment
from temporalio.worker import Worker

try:
    from temporalio.openai_agents.testing import AgentEnvironment, ResponseBuilders
    from temporalio.openai_agents.workflow import activity_as_tool
except ImportError:  # temporalio <= 1.34 bundles the plugin
    from temporalio.contrib.openai_agents.testing import AgentEnvironment, ResponseBuilders
    from temporalio.contrib.openai_agents.workflow import activity_as_tool

with workflow.unsafe.imports_passed_through():
    from agents import Agent, Runner


@activity.defn(name="track_parcel")
class TrackParcel:
    """A callable-class Activity, one of the Activity forms the Python SDK documents."""

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

    async def __call__(self, parcel_id: str) -> str:
        """Track a parcel by its id."""
        return f"parcel {parcel_id} via {self.carrier}"


@workflow.defn
class TrackWorkflow:
    @workflow.run
    async def run(self) -> str:
        # Workflow code references a callable-class Activity by its class.
        tool = activity_as_tool(TrackParcel, start_to_close_timeout=timedelta(seconds=10))
        agent = Agent(name="Tracker", instructions="Track parcel P-1717.", tools=[tool])
        return (await Runner.run(agent, "Where is parcel P-1717?")).final_output


# A model fills each offered parameter from the prompt, by its meaning.
VALUES = {"parcel_id": "P-1717", "carrier": "fast-freight"}


class SchemaFollowingModel(Model):
    async def get_response(self, system_instructions, input, model_settings, tools, *args, **kwargs):
        outputs = [i["output"] for i in input if isinstance(i, dict) and i.get("type") == "function_call_output"]
        if outputs:
            return ResponseBuilders.output_message(outputs[-1])
        (tool,) = tools
        params = list(tool.params_json_schema["properties"])
        print("offered:", tool.name, params)
        call = ResponseFunctionToolCall(
            arguments=json.dumps({p: VALUES[p] for p in params}),
            call_id="c1", name=tool.name, type="function_call", id="fc", status="completed",
        )
        return ModelResponse(output=[call], usage=Usage(), response_id=None)

    def stream_response(self, *args, **kwargs):
        raise NotImplementedError


async def main() -> int:
    async with await WorkflowEnvironment.start_local(dev_server_existing_path=shutil.which("temporal")) as env:
        async with AgentEnvironment(model=SchemaFollowingModel()) as agent_env:
            client = agent_env.applied_on_client(env.client)
            async with Worker(
                client,
                task_queue="tq",
                workflows=[TrackWorkflow],
                activities=[TrackParcel("acme-post")],  # the Worker registers an instance
            ):
                result = await client.execute_workflow(
                    TrackWorkflow.run, id=f"track-{uuid.uuid4()}", task_queue="tq",
                    execution_timeout=timedelta(seconds=30),
                )
    print("result:", result)
    if result == "parcel P-1717 via acme-post":
        print("OK: the Activity got the parcel id")
        return 0
    print("BUG: expected 'parcel P-1717 via acme-post'")
    return 1


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

On temporalio-openai-agents 1.1.0 (temporalio 1.33.0, openai-agents 0.22.0):

offered: TrackParcel ['carrier']
result: parcel fast-freight via acme-post
BUG: expected 'parcel P-1717 via acme-post'

The same output, and exit code 1, on main at c664a34 (temporalio 1.34.0) and on
temporalio.contrib.openai_agents in temporalio 1.33.0 (openai-agents 0.19.4). temporalio
1.34.0 bundles the same activity_as_tool code.

Expected

The tool offers __call__'s parameters without self (parcel_id), keeps the class name as the
tool name, and takes its description from __call__'s docstring. The Worker's registered
TrackParcel("acme-post") then returns parcel P-1717 via acme-post, as Class.method Activities
already work.

Impact

Any callable-class Activity passed to activity_as_tool gets a tool built from its constructor.
When the constructor's parameters decode like the call's, the Activity silently runs with the wrong
argument. Otherwise the run fails or hangs.

Proposed fix

For a class, build the schema from __call__ without self, with the class name and __call__'s
docstring (falling back to the class docstring). Open runs that already called such a tool recorded
the constructor's arguments; building their tool from __call__ would reject those arguments and
not schedule the Activity on replay, so the new schema needs a workflow.patched check. A PR
follows.

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