Skip to content

openai_agents: document that a tool activity failure fails the agent run as retryable - #406

Merged
campoy merged 6 commits into
mainfrom
docs/openai-agents-tool-activity-retry
Nov 4, 2026
Merged

campoy merged 6 commits into
mainfrom
docs/openai-agents-tool-activity-retry

Conversation

@campoy

@campoy campoy commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

What was changed

python/openai_agents/README.md, in "Temporal Activities as OpenAI Agents Tools":

  • A short note after the Worker example. If a tool's activity fails, the agent run fails with a retryable AgentsWorkflowError, as plain Temporal does with an activity failure the workflow does not catch. So a workflow retry policy reruns the whole agent run, model calls included, even when the activity's error was non-retryable.
  • An example that stops the rerun. It keeps the section's activity_as_tool(...), catches AgentsWorkflowError around Runner.run, and raises a non-retryable ApplicationError when the cause is an ActivityError whose retry_state is RetryState.NON_RETRYABLE_FAILURE. That covers an error raised with non_retryable=True and one whose type is in the activity retry policy's non_retryable_error_types. Invalid tool arguments still go back to the model.
  • Sentences saying that the AgentsWorkflowError's __cause__ is the tool's ActivityError, and that activity_as_tool()'s failure_error_function only formats errors for invalid arguments.
  • The section's example now imports from temporalio import activity, openai_agents, workflow. The old from temporalio.contrib import openai_agents loads the SDK's bundled copy, which fails in a process that has this package.

Docs only. No code changes.

Why?

#302 reported this as a bug. It is the intended behavior: it matches plain Temporal, test_retryable_failures_are_still_retried_by_retry_policy[activity] in tests/test_openai_tool_argument_errors.py pins it, and #92 kept activity errors as they were. The README did not say so, or how to stop the rerun.

Checklist

  1. Closes [Bug] openai_agents: a non-retryable Activity error from a tool fails the agent run as retryable #302

  2. How was this tested:

    • Ran the README examples at 4b19073 on this branch's locked environment (temporalio 1.34.0, openai-agents 0.22.0), with the section's new imports. The workflow has RetryPolicy(maximum_attempts=3). Only the agent = ... line differs from the README. "agent runs" counts the first model turn of each workflow attempt (long lines cut at the end; wft_failed counts failed Workflow Tasks):
      control    agent runs=3 wft_failed=0  failed: ApplicationError type=AgentsWorkflowError non_retryable=False msg=Workflow failure exception in Agents Framework: Error runnin...
      flagged    agent runs=1 wft_failed=0  failed: ApplicationError type=None non_retryable=True msg=No weather
      typed      agent runs=1 wft_failed=0  failed: ApplicationError type=None non_retryable=True msg=NoWeather: No weather (typed)
      retryable  agent runs=3 wft_failed=0  failed: ApplicationError type=AgentsWorkflowError non_retryable=False msg=Workflow failure exception in Agents Framework: Error runnin...
      bad-args   agent runs=1 wft_failed=0  completed: 'tool said: An error occurred while running the tool. Please try again. Error: Invalid JSON input for tool get_'
      ok         agent runs=1 wft_failed=0  completed: "tool said: {'city': 'ok', 'temperature_range': '14-20C', 'conditions': 'Sunny with wind.'}"
      
      • control is the README's first example as written, with an activity that raises ApplicationError(non_retryable=True).
      • The other lines use the new example:
        • flagged: the same non-retryable error.
        • typed: ApplicationError(type="NoWeather"), listed in the activity's non_retryable_error_types.
        • retryable: a retryable error that runs out of the activity's 2 attempts.
        • bad-args: the model sends {"town": "Tokyo"}.
        • ok: the activity succeeds.
      • With the previous @function_tool(failure_error_function=None) example, typed ran 3 times, and bad-args failed the Workflow Task twice and then timed out.
    • scripts/ci/check_conventions.py passes. git diff --check is clean.
  3. Any docs updates needed?
    This PR is the docs update.

A tool Activity's failure fails the agent run as a retryable
AgentsWorkflowError, as an uncaught Activity failure does in plain
Temporal, so a Workflow retry policy reruns the whole agent run even
when the Activity error was non-retryable. Show how to stop the rerun
by raising a non-retryable ApplicationError from a function_tool that
calls the Activity.
@campoy
campoy marked this pull request as ready for review November 3, 2026 23:26
@campoy
campoy requested a review from a team as a code owner November 3, 2026 23:26

@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 e6f98a0 (one commit on 88e1fb4, README only; it merges cleanly with main at 52bcb2b). On a worktree at the head, make lint passes and make test passes 512 of 512; CI is green on all four cells. Because the change is documentation, I checked each claim with probe Workflows on the pinned dev server (temporalio 1.34.0, openai-agents 0.22.0): real Workers, a scripted model, an activity that raises ApplicationError("No weather", non_retryable=True), a Workflow retry policy of 3 attempts, and the new block pasted verbatim. The claims hold. The section's activity_as_tool(get_weather, ...) fails the run with AgentsWorkflowError (non_retryable=False, cause ActivityError), and the retry policy runs it for all 3 attempts, with a model call in each; Runner.run_streamed gives the same result. A plain Workflow that awaits the same activity without catching it also runs 3 times, so documenting the behaviour instead of changing it (#302) matches plain Temporal. get_weather_or_fail stops the rerun (1 run, non-retryable AgentsWorkflowError) in both run modes, returns the activity's result when it succeeds, and with the default formatter returns An error occurred while running the tool. Please try again. Error: No weather to the model, as line 377 says. The body's two result lines reproduce exactly. Refuted: that activity_as_tool's own failure_error_function changes any of this (it formats only invalid arguments; the run reruns 3 times with the default and with None). Outside the README's scope, nexus_operation_as_tool behaves the same way (a non-retryable ApplicationError in the handler and a failed OperationError each rerun 3 times); the README doesn't document Nexus tools, so the note needn't cover them. Both fixes suggested below went through the same cases plus a Workflow cancelled during the tool's activity (CANCELED, as with activity_as_tool). Docs only, so no replay impact. Not verified: how often a given provider sends tool arguments outside a strict schema (the probe model does it on purpose), and MCP tools, which the note doesn't cover.

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 note's factual claims are accurate; the problems are in the workaround's code. It gives up activity_as_tool's handling of invalid arguments, and its check recognizes only one of the two ways an activity error becomes non-retryable. The block it extends also carries a pre-existing import that fails with this package.

Requesting changes because the workaround, followed as written, leaves a Workflow retrying its Workflow Task until its execution timeout (or forever without one) after a single tool call with invalid arguments, a case activity_as_tool already handles and line 376 says fails the run; the fix is a small, verified change to the example.

Findings on lines outside the diff

  • python/openai_agents/README.md:307: P3 (non-blocking, pre-existing): from temporalio.contrib import openai_agents imports the SDK's bundled copy, which can't be loaded in a process that has this package. In either order, importing temporalio.openai_agents and temporalio.contrib.openai_agents raises TypeError: env value type `temporal.worker_env_value` is already registered by TemporalWorkerEnvValue; in a probe Workflow on a Worker with this plugin, that import failed the Workflow Task until the timeout. The new block uses this example's Weather, get_weather, workflow and timedelta, so a reader who copies the section hits it. from temporalio import openai_agents keeps openai_agents.workflow.activity_as_tool(...) working. Not introduced here, but it's one line in the section this PR extends.

Comment thread python/openai_agents/README.md Outdated
from agents import function_tool
from temporalio.exceptions import ActivityError, ApplicationError

@function_tool(failure_error_function=None)

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: with failure_error_function=None, a tool call whose arguments don't match the schema fails the Workflow Task again and again instead of reaching the model or failing the run, so swapping activity_as_tool for this tool trades a rerun for a stuck Workflow. The stock function_tool raises ModelBehaviorError for invalid arguments before the body runs, and with no formatter it propagates out of Runner.run. Its cause isn't a Temporal failure, so _reraise_workflow_failure returns and run() re-raises it unchanged (_openai_runner.py:410-414), which fails the Workflow Task. Probe with this block verbatim and the model calling get_weather_or_fail with {"town": "Tokyo"}: one model call, no activity, two WorkflowTaskFailed events (ModelBehaviorError: Invalid JSON input for tool get_weather_or_fail), and the Workflow stayed open until its 20 s execution timeout. Every retry replays the same recorded model response, so without a timeout it never ends. With the section's activity_as_tool(get_weather, ...) the same call returns An error occurred while running the tool. Please try again. Error: Invalid JSON input for tool get_weather to the model and the run completes. That is #91, which #92 fixed for activity_as_tool and nexus_operation_as_tool (workflow.py:105-108 raises a non-retryable ApplicationError when their formatter is None) but not for a stock @function_tool. It takes a model that sends arguments outside the schema: OpenAI's strict function schemas prevent that, but not every provider behind LiteLLM or another OpenAI-compatible endpoint enforces them. Line 376 ('makes the error fail the run') is wrong for this case too.

Fix, verified: keep activity_as_tool and classify the failure around the run. That keeps invalid arguments going to the model, needs no second tool, and shows where the code goes, which the current block leaves to the reader (nothing says to put get_weather_or_fail in tools in place of activity_as_tool(...)):

from temporalio.exceptions import ActivityError, ApplicationError, RetryState
from temporalio.openai_agents import AgentsWorkflowError

        try:
            result = await Runner.run(starting_agent=agent, input=question)
        except AgentsWorkflowError as e:
            failure = e.__cause__  # the tool's ActivityError
            if isinstance(failure, ActivityError) and failure.retry_state == RetryState.NON_RETRYABLE_FAILURE:
                raise ApplicationError(str(failure.cause), non_retryable=True) from e
            raise

In the probe, a non-retryable activity error then fails the Workflow once (also in a streamed run, with the try around the stream_events() loop), and so does an error made non-retryable by the activity's retry policy (next comment); a retryable error that runs out of attempts still runs all 3 Workflow attempts; {"town": "Tokyo"} reaches the model and the run completes; and a Workflow cancelled during the activity ends CANCELED. The plugin raises AgentsWorkflowError from the tool's ActivityError (_openai_runner.py:541), which is what e.__cause__ reads. To keep the @function_tool instead, give it failure_error_function=fail_unless_bad_arguments, where fail_unless_bad_arguments(ctx, error) returns default_tool_error_function(ctx, error) for a ModelBehaviorError and re-raises anything else; with the retry_state check in the body, that gave the same five results. Either way, a sentence that activity_as_tool's own failure_error_function covers only invalid arguments would help, since line 376 describes the same-named @function_tool option.

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, reproduced: with the old block, {"town": "Tokyo"} failed the Workflow Task twice and the run timed out.

Fixed in 7b34a94 with your first suggestion. The example keeps the section's activity_as_tool(...) and catches AgentsWorkflowError around Runner.run, so invalid arguments go back to the model again. It shows the full run method, so it's clear where the code goes. The @function_tool and the line about failure_error_function=None are gone. I added the sentence that activity_as_tool()'s failure_error_function only formats invalid-argument errors. In 4b19073, a sentence also says that the AgentsWorkflowError's __cause__ is the tool's ActivityError, since the example relies on it.

Rerun of the new block at 4b19073, with a 3-attempt Workflow retry policy: {"town": "Tokyo"} reaches the model and the run completes; a non-retryable activity error runs once; a retryable error that runs out of activity attempts still runs 3 times; a successful activity completes.

Comment thread python/openai_agents/README.md Outdated
get_weather, city, start_to_close_timeout=timedelta(seconds=10)
)
except ActivityError as e:
if isinstance(e.cause, ApplicationError) and e.cause.non_retryable:

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): this check misses an error that the activity's retry policy makes non-retryable, so the Workflow still reruns for it. An ApplicationError whose type is in RetryPolicy(non_retryable_error_types=[...]) stops the activity's retries, but its non_retryable flag stays False. Probe: this body with retry_policy=RetryPolicy(non_retryable_error_types=["NoWeather"]) and an activity raising ApplicationError("No weather (typed)", type="NoWeather") ran the agent 3 times under the 3-attempt Workflow retry policy. That ActivityError reports cause.non_retryable=False and retry_state=RetryState.NON_RETRYABLE_FAILURE, and a flagged error also reports NON_RETRYABLE_FAILURE, so if e.retry_state == RetryState.NON_RETRYABLE_FAILURE: (with RetryState from temporalio.exceptions) covers both; it ran once in the same probe. The re-raise also drops the cause's type; str(e.cause) keeps it in the message (NoWeather: No weather (typed)).

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.

Good catch. Fixed in 7b34a94: the check is now retry_state == RetryState.NON_RETRYABLE_FAILURE, and the message uses str(failure.cause), so the type stays in it. A sentence after the block says the check covers both cases.

Rerun with RetryPolicy(non_retryable_error_types=["NoWeather"]): the old block ran the agent 3 times; the new one runs it once and fails with NoWeather: No weather (typed).

…example

The SDK's bundled temporalio.contrib.openai_agents can't be loaded in
a process that has this package.
…DME example

A function_tool with failure_error_function=None fails the Workflow
Task, again and again, when the model sends arguments that don't match
the tool's schema. Keep activity_as_tool, which returns those to the
model, and classify the failure around Runner.run instead. Check the
ActivityError's retry_state, so an error listed in the activity retry
policy's non_retryable_error_types also stops the rerun.
The example reads e.__cause__, so document that it is the tool's
ActivityError.
@campoy

campoy commented Nov 4, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the review. The two inline findings are answered in their threads (7b34a94, 4b19073). On the summary:

  • Line 307 import (P3): fixed in 7b9c836. The example now uses from temporalio import activity, openai_agents, workflow, so openai_agents.workflow.activity_as_tool(...) keeps working, and the rerun above imports it with this package loaded.
  • Nexus and MCP tools: the note leaves them out, as you suggested. The README doesn't document Nexus tools, and the note doesn't cover MCP tools.

@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 4b19073 (three commits over e6f98a0, README only). It merges cleanly with main at 45c0adf, and the note is unchanged in that merge. On a worktree at the head, make lint passes and make test passes 512 of 512; CI is green on all four cells. I generated the probe Workflows from the README at the head: the section's example verbatim, new import included, and the new block verbatim except agent = ..., which builds the section's agent (with a retry_policy on activity_as_tool where a case needs one). They ran on real Workers on the pinned dev server (temporalio 1.34.0, openai-agents 0.22.0), with a scripted model and a Workflow retry policy of 3 attempts. Every claim in the note holds. The section's example as written fails with a retryable AgentsWorkflowError whose __cause__ is the tool's ActivityError (retry_state=NON_RETRYABLE_FAILURE) and runs the agent 3 times, with a model call in each; a plain Workflow that doesn't catch the same activity error also runs 3 times. With the new block, ApplicationError(non_retryable=True) runs once and fails with No weather; a type listed in non_retryable_error_types runs once and fails with NoWeather: No weather (typed), and so does a ValueError listed there; a retryable error that uses up its 2 activity attempts still runs 3 times; {"town": "Tokyo"} goes back to the model and the run completes with no Workflow Task failure; a successful activity completes. Runner.run_streamed, with the try around the stream_events() loop, gives the same five results. The body's six result lines reproduce. Refuted: that the retry_state check misses a non-retryable error when the activity's policy has maximum_attempts=1 or when the error comes on the last allowed attempt (each reports NON_RETRYABLE_FAILURE and runs once); that activity_as_tool()'s failure_error_function changes any of this (with None or a custom function, the section's example still runs 3 times and the new block once; with None, invalid arguments fail once with a non-retryable AgentsWorkflowError whose cause is a non-retryable ApplicationError of type ModelBehaviorError, which the block re-raises); and that the try affects cancellation (a Workflow cancelled during the tool's activity or the model call ends CANCELED in both run modes, as the section's example does). Outside the note's scope: a model call that fails non-retryably (the plugin marks most 4xx responses that way) reaches the Workflow as a bare ActivityError, not an AgentsWorkflowError, so this except doesn't see it and the run reruns 3 times in both run modes, as it does without the try. The note speaks only of a tool's activity, so it is accurate as written. Docs only, so no replay impact. Not verified: MCP tools and agents used as tools (agent.as_tool()), which the note doesn't cover.

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 three items from my review at e6f98a0 are addressed; both threads and the summary item have replies, and I checked each fix by rerunning its reproduction. The blocking P2: the example now keeps activity_as_tool(...) and classifies the failure around Runner.run. The model's {"town": "Tokyo"} now gets An error occurred while running the tool. Please try again. Error: Invalid JSON input for tool get_weather back and the run completes in one run with no Workflow Task failure, in both run modes, where the old block failed the Workflow Task twice and then timed out. The retry_state P3: the typed error now runs once and keeps its type in the message. The line 307 P3: the section's example, verbatim with from temporalio import activity, openai_agents, workflow, runs on a Worker with this package (it is the control above). The sentence on activity_as_tool()'s failure_error_function is in, and the block now shows the whole run method, so where the code goes is clear.

Approving: last round's blocking item and both P3s are fixed and verified, every claim in the note holds on real Workers in both run modes, CI is green, and the one new item is a non-blocking docs suggestion for streamed runs.

Not from this PR (the same with the section's example and no try): with activity_as_tool(..., cancellation_type=ActivityCancellationType.WAIT_CANCELLATION_COMPLETED, heartbeat_timeout=...), a Workflow cancelled during the tool's activity ends CANCELED without waiting for the activity to confirm the cancel (the activity's completion then gets workflow execution already completed). The Worker then can't evict the run (RuntimeError: Eviction processed, but 3 tasks remain: two of the Agents SDK's tool-execution tasks and the activity handle, all still cancelling), warns that the slot may stay in use, and hangs on shutdown. With the default TRY_CANCEL none of this happens. Worth an issue.

If the activity fails, the agent run fails with a retryable `AgentsWorkflowError`.
This is how plain Temporal treats an activity failure that the workflow does not catch.
So a workflow retry policy reruns the whole agent run, model calls included, even when the activity's error was non-retryable.
To stop the rerun, catch the error around the run and raise a non-retryable `ApplicationError` in its place:

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): with Runner.run_streamed the error is raised from the stream_events() loop, so a try around the run_streamed(...) call alone catches nothing and the run still reruns. run_streamed returns at once; the plugin rewraps the failure as AgentsWorkflowError inside stream_events() (_openai_runner.py:500-519). Probe with this block, result = Runner.run_streamed(starting_agent=agent, input=question) as the try body and the async for _ in result.stream_events(): pass loop after the except: the non-retryable activity error ran the agent 3 times under the 3-attempt Workflow retry policy and failed with the retryable AgentsWorkflowError. With the loop inside the try it ran once, and the non_retryable_error_types, retryable, {"town": "Tokyo"}, success and cancellation cases gave the same results as with Runner.run. The README documents Runner.run_streamed under Streaming, and 'around the run' doesn't say which line that is there, so one sentence after the block would cover it, for example: 'With Runner.run_streamed, put the async for loop over result.stream_events() inside the try: the error is raised there.'

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. Added your sentence after the block in affa025: "With Runner.run_streamed, put the async for loop over result.stream_events() inside the try: the error is raised there."

Rerun with Runner.run_streamed and a 3-attempt Workflow retry policy. With the loop inside the try, the non-retryable and non_retryable_error_types errors run once, the retryable error still runs 3 times, {"town": "Tokyo"} reaches the model and completes, and a successful activity completes. With the try around the run_streamed(...) call alone, the non-retryable and typed errors ran 3 times, as you found.

With Runner.run_streamed, the error is raised from the stream_events()
loop, not from the run_streamed(...) call.
@campoy

campoy commented Nov 4, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the second round. The streamed-run P3 is answered in its thread (affa025). On the summary:

  • A model call that fails non-retryably reaches the Workflow as a bare ActivityError, so this except doesn't see it: agreed. The note speaks only of a tool's activity, so I left it as is.
  • The WAIT_CANCELLATION_COMPLETED cancel and eviction hang: not from this PR, so I've passed it on to be filed as a separate issue.

@campoy
campoy merged commit be1e411 into main Nov 4, 2026
15 checks passed
@campoy
campoy deleted the docs/openai-agents-tool-activity-retry branch November 4, 2026 03:56
@campoy

campoy commented Nov 4, 2026

Copy link
Copy Markdown
Contributor Author

Follow-up on the WAIT_CANCELLATION_COMPLETED item from the second-round summary. It has two parts:

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] openai_agents: a non-retryable Activity error from a tool fails the agent run as retryable

2 participants