Repository navigation
Breaking: run OpenAI Agents sync function tools in the workflow - #232
Conversation
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.
DABH
left a comment
There was a problem hiding this comment.
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. |
There was a problem hiding this comment.
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.'
There was a problem hiding this comment.
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.
Useactivity_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) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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(): |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
|
Thanks for the review. The three threads are answered in place. For the summary:
New head: |
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.
What was changed
Sync
@function_tooltools now run directly in the workflow, as async ones do.runandrun_streamed) enters a scope that sets a context variable and installs, once per workflow event loop, arun_in_executoroverride.NotImplementedError, only inside a run, only when its caller isasyncio.to_threadcalled fromagents.tool(the sync@function_toolpath is the onlyasyncio.to_threadthere). 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 otherrun_in_executorcall in workflow code goes to the loop's own method and fails as before.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:
[TMPRL1100]if anything the tool did changes the workflow's commands: workflow state or run context it writes, or commands it issues itself, such asworkflow.upsert_memo()orworkflow.start_activity();[TMPRL1101] Potential deadlock detectedif the tool runs longer than two seconds. Onmainsuch 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 againstmain.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 gotAn 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
Closes [Bug] openai_agents: a sync
@function_toolnever runs in a Workflow; the model gets an empty error #231How was this tested:
test_workflow_method_toolsintests/test_openai.pygains a sync method tool,add_note, which adds to workflow state, and aRunHooks.on_agent_starthook 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 ownasyncio.to_threadcall still raisesNotImplementedError. Onmainatc664a34it fails withAssertionError: 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 becauseoffload_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 raisedAttributeError: FunctionTool has no wrapped Python callable.test_streamed_run_runs_sync_function_toolsintests/test_openai_streaming.pyruns a sync tool in aRunner.run_streamedrun, with a streaming model, and checks that the model got its result. It passes with the change. Whenrun_streameddoes not enter the scope, it fails: the model getsAn error occurred while running the tool. Please try again. Error:.mainfrom that workflow, where the sync tool got the error, fails replay on9142155:[TMPRL1100] Nondeterminism error: Timer machine does not handle this event: HistoryEvent(id: 23, WorkflowExecutionCompleted). That is the breaking change above, so it is not intest_replay. It also failed on the first commit, with thatAttributeError.__wrapped__callable and sets its error formatter withset_function_tool_failure_error_function, on a sync tool and an async control that both raise: with the change, both giveCUSTOM ERROR: ValueError('body ran'). On the first commit, the hook got theAttributeErrorand the sync tool's error used the default formatter. This ran as a script.6afb461: CI passes. Locally, in Docker with Python 3.13 and uv 0.12.24,make lintpasses and the two tests above pass. A localmake testwas 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.@function_toolnever runs in a Workflow; the model gets an empty error #231's reproduction exits 1 on 1.1.0 and onmainatc664a34. It exits 0 with the change: the sync tool returns5, like the async one.mainthe two sync ones return the error.kill -9between steps, on cases recorded onmain: 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:[TMPRL1100]; the other six replay, including the two waiting runs that had called a sync tool but not yet acted on it;mainhistories with[TMPRL1100].maingotpaid 5, and a run stuck onmainbecause its sync tool raised (failure_error_function=None) completed.9142155reran these checks without the gate, for upgrade and rollback, and also found the command-issuing and slow-tool cases. "Breaking change" gives the results.Any docs updates needed?
The README lines are added here. Release notes should say which runs stop replaying (see "Breaking change").
Not covered:
temporalio1.34.x still bundles the old code astemporalio.contrib.openai_agents. A backport is a separate decision.openai-agents>=0.22,<0.23, andtest_workflow_method_toolsfails if an upgrade moves the call. A supported SDK hook for running a call inline from workflow code can replace it later.