Skip to content

Breaking: run OpenAI Agents sync function tools in the workflow - #232

Merged
campoy merged 5 commits into
mainfrom
fix/openai-agents-python-sync-function-tool-thread-offload
Oct 31, 2026
Merged

campoy merged 5 commits into
mainfrom
fix/openai-agents-python-sync-function-tool-thread-offload

Conversation

@campoy

@campoy campoy commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

What was changed

Sync @function_tool tools now run directly in the workflow, as async ones do.

  • Tools are left as they are. Each workflow run (run and run_streamed) enters a scope that sets a context variable and installs, once per workflow event loop, a run_in_executor override.
  • The override runs a call inline, instead of raising NotImplementedError, only inside a run, only when its caller is asyncio.to_thread called from agents.tool (the sync @function_tool path is the only asyncio.to_thread there). That is the SDK's own call, so the tool's invoker still parses arguments, checks output and handles errors, against the tool the run holds. Every other run_in_executor call in workflow code goes to the loop's own method and fails as before.
  • The README says sync tools run directly in the workflow, run again on every replay, and fail the Workflow Task when they take more than two seconds.

No public name or option changes.

Breaking change: the new path has no version gate. We are not adding version gates to these fixes. temporalio-openai-agents already shipped 1.0.0 and 1.1.0, so this break needs its next major release, 2.0.0.

Open runs that called a sync function tool before the upgrade may fail on replay:

  • with [TMPRL1100] if anything the tool did changes the workflow's commands: workflow state or run context it writes, or commands it issues itself, such as workflow.upsert_memo() or workflow.start_activity();
  • with [TMPRL1101] Potential deadlock detected if the tool runs longer than two seconds. On main such a tool failed at once. Now it fails the Workflow Task, in new runs too, instead of returning an error to the model.

Runs that never called a sync tool replay. So do runs whose sync tool changed nothing the commands depend on, and runs that had not yet issued commands based on the tool's work. A run paused for a sync tool's approval runs the tool after the upgrade, and a run stuck because its sync tool raised (failure_error_function=None) completes.

Upgrade: let open runs that called a sync tool finish on 1.x before you upgrade, or pin them with Worker Versioning. Do not roll a Worker back to 1.x while runs that called a sync tool on 2.0 are open: the same runs fail replay there.

The branch has five commits: the first fix, which wrapped each sync tool in _convert_agent; a revision that replaces it and leaves tools as they are; a commit that removes the version gate; and two review commits (README, tests). Review the combined diff against main.

Why?

See #231. The Agents SDK runs a sync function tool with asyncio.to_thread, and the workflow event loop has no threads, so the tool failed before its body ran. The model got An error occurred while running the tool. Please try again. Error: with nothing after it, and the workflow completed. The README's own inline tool example, calculate_circle_area, is sync.

Checklist

  1. Closes [Bug] openai_agents: a sync @function_tool never runs in a Workflow; the model gets an empty error #231

  2. How was this tested:

    • test_workflow_method_tools in tests/test_openai.py gains a sync method tool, add_note, which adds to workflow state, and a RunHooks.on_agent_start hook that reads each tool's __wrapped__ callable. The workflow now returns its notes and the callables the hook saw, and acts on the notes, and the test checks that the model got the tool's result. An async method tool, offload_sum, checks that its own asyncio.to_thread call still raises NotImplementedError. On main at c664a34 it fails with AssertionError: assert {'notes': [],..., 'add_note']} == {'notes': ['c..., 'add_note']}: the hook sees both callables, but the sync tool never runs. It passes with the change. With the caller check made always true, it fails because offload_sum's thread call runs: assert 'to_thread raised NotImplementedError' in .... On this PR's first commit, which wrapped each sync tool in _convert_agent, the hook raised AttributeError: FunctionTool has no wrapped Python callable.
    • test_streamed_run_runs_sync_function_tools in tests/test_openai_streaming.py runs a sync tool in a Runner.run_streamed run, with a streaming model, and checks that the model got its result. It passes with the change. When run_streamed does not enter the scope, it fails: the model gets An error occurred while running the tool. Please try again. Error: .
    • A History recorded on main from that workflow, where the sync tool got the error, fails replay on 9142155: [TMPRL1100] Nondeterminism error: Timer machine does not handle this event: HistoryEvent(id: 23, WorkflowExecutionCompleted). That is the breaking change above, so it is not in test_replay. It also failed on the first commit, with that AttributeError.
    • A run hook that reads a sync tool's __wrapped__ callable and sets its error formatter with set_function_tool_failure_error_function, on a sync tool and an async control that both raise: with the change, both give CUSTOM ERROR: ValueError('body ran'). On the first commit, the hook got the AttributeError and the sync tool's error used the default formatter. This ran as a script.
    • On 6afb461: CI passes. Locally, in Docker with Python 3.13 and uv 0.12.24, make lint passes and the two tests above pass. A local make test was not usable under the machine's load (an xdist worker crashed and unrelated tests hit the 60 s timeout), so the full suite rests on CI.
    • [Bug] openai_agents: a sync @function_tool never runs in a Workflow; the model gets an empty error #231's reproduction exits 1 on 1.1.0 and on main at c664a34. It exits 0 with the change: the sync tool returns 5, like the async one.
    • Three tool calls in one model turn (two sync, one async) all return their results with the change. On main the two sync ones return the error.
    • Replay checks ran on the earlier, gated version of this change, with Workers with no workflow cache, killed with kill -9 between steps, on cases recorded on main: a sync tool that writes workflow state (two turns around a held Activity), a sync tool that writes the run context, a sync tool that needs approval (the held Activity stands for the wait), and an async tool as a control. Each workflow acts on what its tool did after the held Activity. Each was run to the end and also left waiting on the held Activity:
      • without the gate, the two finished histories whose sync tool's work changes commands (workflow state, run context) fail with [TMPRL1100]; the other six replay, including the two waiting runs that had called a sync tool but not yet acted on it;
      • a control that renames an Activity fails all eight main histories with [TMPRL1100].
    • On the gated change, a run waiting for a sync tool's approval on main got paid 5, and a run stuck on main because its sync tool raised (failure_error_function=None) completed.
    • The review at 9142155 reran these checks without the gate, for upgrade and rollback, and also found the command-issuing and slow-tool cases. "Breaking change" gives the results.
  3. Any docs updates needed?
    The README lines are added here. Release notes should say which runs stop replaying (see "Breaking change").

Not covered:

  • temporalio 1.34.x still bundles the old code as temporalio.contrib.openai_agents. A backport is a separate decision.
  • The override is set on the workflow event loop object, and it recognizes the Agents SDK's sync tool call by its caller. That holds for openai-agents>=0.22,<0.23, and test_workflow_method_tools fails if an upgrade moves the call. A supported SDK hook for running a call inline from workflow code can replace it later.

The Agents SDK runs a sync function tool with asyncio.to_thread. The
workflow event loop has no threads, so the tool failed before its body
ran, and the model got "An error occurred while running the tool. Please
try again. Error: " with nothing after it. The README's own inline tool
example is a sync function.

Sync function tools now run directly in the workflow, as async ones do.
Runs that started before this change keep the old behavior, behind a
workflow.patched check, so their histories replay.
The previous commit wrapped each sync function tool in _convert_agent,
for every run with such a tool and before any gate. That replaced the
tool's invoker, so a hook that read the tool's __wrapped__ callable got
AttributeError, and an error formatter set from a run hook was ignored.

Leave the tools as they are. Each Workflow run (run and run_streamed)
enters a scope that sets a context variable and installs, once per
Workflow event loop, a run_in_executor override. The override runs a
call inline only inside a run, only when the caller is asyncio.to_thread
called from agents.tool (the sync @function_tool path), and only if
workflow.patched("openai_agents.inline-sync-function-tools") agrees.
Every other call goes to the loop's own method and fails as before.

test_workflow_method_tools now also passes run hooks that read each
tool's __wrapped__ callable. Its replay History is re-recorded on main
with that change.
Fixes add no version gates for now, so remove the
`openai_agents.inline-sync-function-tools` patch and the replay test
History that only checked it. Sync function tools now run in the
Workflow in every run.

Breaking change: a run whose sync tool got the error before this version
and whose Workflow then acted on what the tool should have done, such as
Workflow state or the run context the tool writes, now runs the tool on
replay, issues different commands and fails with a non-determinism
error. Let those runs finish before you upgrade, or use Worker
Versioning.
@campoy campoy changed the title openai_agents: run sync function tools in the workflow Breaking: run OpenAI Agents sync function tools in the workflow Oct 29, 2026
@campoy
campoy marked this pull request as ready for review October 30, 2026 06:16
@campoy
campoy requested a review from a team as a code owner October 30, 2026 06:16

@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 9142155 (the combined diff of the three commits over c664a34). On a worktree at the head, make lint is clean and make test passes 382 of 382. A trial merge into current main (4bcde9a) has no conflicts, is lint-clean and passes 425 of 425. The new assertions in test_workflow_method_tools fail on main ({'notes': []} != {'notes': ['call back']}) and pass on the head. I checked replay and upgrade with real Workers on a standalone dev server: each History was recorded by a main Worker and replayed by the head's Replayer, and the reverse for rollback. Every replay claim in the body, which it says ran on the gated build, holds at this ungated head. Histories where the workflow acted on state or run context that a sync tool writes fail with [TMPRL1100]. A sync tool whose result nothing acts on, an async-tool control, a run paused for a sync tool's approval and a run stuck on failure_error_function=None all replay. After the upgrade, the paused run finishes on a head Worker with paid 5 and the stuck run completes with 5. A streamed run with a sync tool also works on the head: the model gets 5, where on main it gets the empty error. That settles the body's first 'Not covered' item. The README's calculate_circle_area example now returns 12.566370614359172 instead of the empty error. Refuted: that the override also inlines an async tool's own asyncio.to_thread (at the head that still raises NotImplementedError, as the body says), and any interaction with tool timeouts (upstream rejects timeout on sync tools in _validate_function_tool_timeout_config). The caller match is exact for the locked openai-agents 0.22.0, where the only asyncio.to_thread calls in agents.tool are the two sync-tool lines in _on_invoke_tool_impl (2645 and 2647). Not run locally: Python versions other than 3.14 (CI covers 3.10 on Ubuntu and 3.14 on Ubuntu, macOS and Windows).

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 mechanism is sound, and the regression test covers the main path. What remains is documentation of what running on the workflow thread means (blocking, replay, and which open runs break on upgrade and on rollback), plus tests for the two parts of the contract the suite cannot see: the streamed path, and the calls that must keep failing.

Approving: the fix is correct and verified end to end, the replay break is disclosed with the right upgrade remedy, CI is green, and every remaining item is a non-blocking documentation or test gap.

P3 (PR body, upgrade note; non-blocking): the 'who is affected' sentence is narrower than the break, and rollback is not covered. Release notes come from commit subjects, so whoever writes the 2.0.0 upgrade note will probably start from this text. I verified these at the head against Histories recorded on main. (a) A sync tool that issues a command itself fails replay even when the workflow never acts on its result. A tool calling workflow.upsert_memo({'label': label}) gives [TMPRL1100] ModifyWorkflowPropertiesMachine does not handle HistoryEvent(id: 11, ActivityTaskScheduled), and any other command issued from a sync tool behaves the same way. (b) A sync tool that runs longer than two seconds fails replay with [TMPRL1101] Potential deadlock detected (on main it failed instantly), so an open run that called one gets stuck after the upgrade, whatever it did next. New runs with such a tool now fail their Workflow Task instead of returning an error to the model. So the sentence 'Runs without sync tools replay, and so do runs that had not yet issued commands based on the tool's work' does not hold for these runs. Rollback breaks the same runs in the other direction: Histories recorded on the head in which state, context or a tool-issued command depends on the tool fail on main with [TMPRL1100]. The no-act and approval Histories replay both ways. Your remedy (let open runs that called a sync tool finish first, or pin them with Worker Versioning) covers all of these. Suggested wording: 'Open runs that called a sync function tool before the upgrade may fail on replay: with [TMPRL1100] if anything the tool did changes the workflow's commands (state or run context it writes, or commands it issues), or with [TMPRL1101] if the tool runs longer than two seconds. Let those runs finish on 1.x or pin them with Worker Versioning, and do not roll a Worker back to 1.x while runs that called a sync tool on 2.0 are open.' Also out of date in the body: 'accepted with the plugins' 1.0 releases' (this plugin already shipped 1.0.0 and 1.1.0, and the break ships in 2.0.0); 'Draft while the breaking change and these questions are open' (the PR is marked ready); and the 'Not covered' items for the streamed path and the ungated replay check, which hold as described above.

Your open questions. Recognizing the call by its caller is fine within openai-agents>=0.22,<0.23, and test_workflow_method_tools fails if an upgrade moves the call. A supported hook can come later and should not block this PR. The 1.34.x backport is a separate decision that this PR does not depend on.

Cross-language: in the TypeScript plugin, inline tool() tools already run in the Workflow (its README, line 328), and JavaScript has no thread offload. This change makes the two OpenAI Agents plugins consistent; the TypeScript side needs no change.

Do not perform network, database, filesystem, or other external I/O directly from these tools.
Use a Temporal activity with `activity_as_tool()` instead.
Code running in the workflow can also invoke a Temporal activity directly when needed.
Sync tools run directly in the workflow, not in a separate thread as they do outside Temporal.

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): the new sentence says where sync tools run but not what that means for them. On the workflow thread, the Workflow Task waits for the tool, the tool runs again on every replay, and a tool that takes longer than two seconds fails the Workflow Task. Probe at the head: a deterministic sync tool computing sum(i * i for i in range(200_000_000)) (about 6 s) fails the task with [TMPRL1101] Potential deadlock detected: workflow didn't yield within 2 second(s). and retries indefinitely. On main the same run completed, because the tool never ran. Users whose sync tools block (upstream runs them in a thread, so blocking is safe outside Temporal) now get a stuck run instead of a degraded answer. Suggested: 'Sync tools run directly in the workflow, not in a separate thread as they do outside Temporal. The Workflow Task waits for them and they run again on every replay, so a tool that takes more than two seconds fails the Workflow Task with a deadlock error. Use activity_as_tool() for slow or blocking work.'

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 a896bcc, close to your wording:

They run again on every replay, and the Workflow Task waits for them: a tool that takes more than two seconds fails the Workflow Task with a deadlock error.
Use activity_as_tool() for slow work.

The body's "Breaking change" section now also says that a slow sync tool fails the Workflow Task in new runs, where on main it returned an error to the model.

if not (
_in_agent_run.get() and _called_by_sync_function_tool(sys._getframe(1))
):
return run_in_executor(executor, func, *args)

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): nothing tests the part of the contract that keeps every other run_in_executor call failing. Mutation: making the caller check always true (_in_agent_run.get() and (_called_by_sync_function_tool(sys._getframe(1)) or True)) leaves the full suite green (382 passed). Under that mutant, an async tool's own await asyncio.to_thread(lambda: a + b) inside a run returns 5. At the head it raises NotImplementedError, as on main. This property stops blocking work that an async tool or a library offloads with to_thread from silently running on the workflow thread. A test that pins it: an async @function_tool that returns 'to_thread raised NotImplementedError' from an except NotImplementedError around await asyncio.to_thread(...), with an assertion that this output reaches the model. It returns the error string at the head and 'to_thread returned 5' under the mutant.

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 6afb461, inside test_workflow_method_tools instead of a new test. An async method tool, offload_sum, wraps its own await asyncio.to_thread(lambda: 2 + 3) in except NotImplementedError, and the test checks that the model gets to_thread raised NotImplementedError. It passes at the new head. With your mutant (... or True on the caller check) it fails, because the thread call runs and the model gets to_thread returned 5.

# The streaming loop runs in a task created inside run_streamed, which copies
# this context, so the scope only needs to cover the call itself.
with capture_scope(run_config.model_settings):
with capture_scope(run_config.model_settings), _inline_sync_function_tools():

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): the streamed path has no test, so removing _inline_sync_function_tools() from this line leaves the suite green (382 passed). It works today. I ran a temporary test like test_streaming_publishes_raw_events (streaming_topic='events', a WorkflowStream in the workflow) with a streaming model: its first ResponseCompletedEvent carries a ResponseFunctionToolCall for a sync add_sync, and its second echoes the function_call_output. It passes on the head (the model gets 5) and fails on main (the model gets the empty error). This line depends on upstream creating run_loop_task inside run_streamed, so that the task copies the context. If upstream starts that task lazily, sync tools in streamed runs will silently return the empty error again. Adding that test (about 60 lines) would catch it.

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 6afb461: test_streamed_run_runs_sync_function_tools in tests/test_openai_streaming.py. A streaming model first streams a call to a sync add tool, then its usual reply, and the workflow returns the tool outputs of the streamed run. It passes at the new head ([5]). With _inline_sync_function_tools() removed from this line it fails: the model gets An error occurred while running the tool. Please try again. Error: .

Sync tools run again on every replay, and the Workflow Task waits for
them, so a tool that takes more than two seconds fails the task with a
deadlock error. Point slow work to activity_as_tool().
test_streamed_run_runs_sync_function_tools runs a sync tool in a
Runner.run_streamed run. test_workflow_method_tools gains an async tool
whose own asyncio.to_thread call must still raise NotImplementedError.
@campoy

campoy commented Oct 31, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the review. The three threads are answered in place. For the summary:

  • Upgrade note: "Breaking change" and "Upgrade" in the body now use your wording: [TMPRL1100] when anything the tool did changes the commands (state, run context, or commands it issues itself), [TMPRL1101] when it runs longer than two seconds, and no rollback to 1.x while runs that called a sync tool on 2.0 are open. It also says that a slow sync tool now fails the Workflow Task in new runs.
  • Out-of-date lines: the gate sentence now says the break needs the next major release, 2.0.0 (same wording as Breaking: deliver OpenAI Agents Nexus tool cancellation before the workflow closes #226). The "Draft while ..." line is gone. The streamed-path and ungated-replay items left "Not covered": the streamed path now has a test, and the body credits your rerun of the replay checks at 9142155.
  • Open questions: moved to "Not covered", with your answers: the caller match holds for openai-agents>=0.22,<0.23, a supported SDK hook can come later, and the 1.34.x backport is a separate decision.

New head: 6afb461. CI passes, and make lint and the new tests pass locally.

@campoy
campoy merged commit 05a81ce into main Oct 31, 2026
27 checks passed
@campoy
campoy deleted the fix/openai-agents-python-sync-function-tool-thread-offload branch October 31, 2026 07:52
campoy added a commit that referenced this pull request Oct 31, 2026
Resolve the conflict with #232 in TemporalOpenAIRunner.run: keep the
Nexus tool operation tracking and enter _inline_sync_function_tools()
in the same with statement.
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 sync @function_tool never runs in a Workflow; the model gets an empty error

2 participants