Repository navigation
Description
Package: temporalio-openai-agents main (3af00d9).
What happens
When an agent run fails with an error from the Agents SDK, the plugin rewraps it as an AgentsWorkflowError, and makes it non-retryable when the cause is a non-retryable ApplicationError, so a Workflow retry policy does not rerun the whole agent run. _reraise_workflow_failure checks only the direct cause, though. A tool that runs as an Activity fails with an ActivityError whose own cause is the ApplicationError, so a non-retryable failure there fails the run as a retryable AgentsWorkflowError, and the retry policy reruns the whole agent run.
Reproduction
One file, no network or API key. The same ApplicationError(non_retryable=True) is raised by a tool, once in Workflow code (function_tool) and once from an Activity (activity_as_tool), both with failure_error_function=None. The Workflow has a retry policy with three attempts. It exits 1 while the Activity case runs more than once.
"""A non-retryable Activity error from a tool fails the agent run as retryable.
python issue_repro.py (starts a local Temporal dev server; no API key needed)
The same ApplicationError(non_retryable=True) is raised by a tool, once from an
Activity (activity_as_tool) and once in Workflow code (function_tool), both with
failure_error_function=None so the run fails. The Workflow has a retry policy
with three attempts. Raised in the Workflow, the run fails as a non-retryable
AgentsWorkflowError and runs once. Raised from the Activity, it fails as a
retryable AgentsWorkflowError, so the retry policy reruns the whole agent run.
Exits 1 while the Activity case runs more than once.
"""
import asyncio
import sys
import uuid
from datetime import timedelta
from temporalio import activity, workflow
from temporalio.client import Client, WorkflowFailureError
from temporalio.common import RetryPolicy
from temporalio.exceptions import ApplicationError
from temporalio.testing import WorkflowEnvironment
from temporalio.worker import Worker
with workflow.unsafe.imports_passed_through():
from agents import Agent, Model, Runner, function_tool
from temporalio.openai_agents import OpenAIAgentsPlugin
from temporalio.openai_agents.testing import ResponseBuilders, TestModelProvider
from temporalio.openai_agents.workflow import activity_as_tool
RUNS: dict[str, int] = {"activity": 0, "workflow": 0} # agent runs per case
@activity.defn
async def refuse() -> str:
raise ApplicationError("refused", non_retryable=True)
@function_tool(failure_error_function=None)
async def refuse_in_workflow() -> str:
"""Refuse in Workflow code."""
raise ApplicationError("refused", non_retryable=True)
class CallTheTool(Model):
"""Counts agent runs per case and calls the one tool it is offered."""
async def get_response(self, system_instructions, input, model_settings, tools, *args, **kwargs):
RUNS["activity" if tools[0].name == "refuse" else "workflow"] += 1
return ResponseBuilders.tool_call("{}", tools[0].name)
def stream_response(self, *args, **kwargs):
raise NotImplementedError
@workflow.defn
class ToolWorkflow:
@workflow.run
async def run(self, case: str) -> str:
if case == "activity":
tool = activity_as_tool(refuse, start_to_close_timeout=timedelta(seconds=10),
failure_error_function=None)
else:
tool = refuse_in_workflow
result = await Runner.run(Agent(name="helper", tools=[tool]), "Go.")
return result.final_output
async def main() -> int:
plugin = OpenAIAgentsPlugin(model_provider=TestModelProvider(CallTheTool()))
async with await WorkflowEnvironment.start_local() as env:
client = Client(**{**env.client.config(), "plugins": [plugin]})
async with Worker(client, task_queue="tools", workflows=[ToolWorkflow], activities=[refuse]):
for case in ("workflow", "activity"):
try:
await client.execute_workflow(
ToolWorkflow.run, case, id=f"tool-{uuid.uuid4()}", task_queue="tools",
retry_policy=RetryPolicy(maximum_attempts=3, initial_interval=timedelta(seconds=1)))
outcome = "completed"
except WorkflowFailureError as err:
cause = err.cause
outcome = (f"failed: {type(cause).__name__} type={getattr(cause, 'type', None)} "
f"non_retryable={getattr(cause, 'non_retryable', None)}")
print(f"{'tool raises in ' + case:28} {outcome} agent_runs={RUNS[case]}")
return 1 if RUNS["activity"] > 1 else 0
if __name__ == "__main__":
sys.exit(asyncio.run(main()))Output on main at 3af00d9 (temporalio 1.35.0, openai-agents 0.22.3, Python 3.13.16):
tool raises in workflow failed: ApplicationError type=AgentsWorkflowError non_retryable=True agent_runs=1
tool raises in activity failed: ApplicationError type=AgentsWorkflowError non_retryable=False agent_runs=3
exit=1
The first line is the control. On 1.1.0, activity_as_tool() has no failure_error_function, so this script does not run there.
Expected
A non-retryable failure from an Activity-backed tool ends the run as a non-retryable AgentsWorkflowError, as it does when the tool raises in Workflow code.
Impact
A Workflow with a retry policy reruns the whole agent run, model calls and tool calls included, for a failure the tool marked as permanent. The same path applies to other Activity-backed tools with failure_error_function=None, such as MCP tools through temporal_mcp_server() (not run here).
Proposed fix
In _reraise_workflow_failure, look through an ActivityError to its cause: when that is a non-retryable ApplicationError, raise NonRetryableAgentsWorkflowError. The change is in Workflow code; it changes only how the run's final failure is classified.
Activity