fix(browser): register event loop on current thread in _execute_async#485
Open
xlyoung wants to merge 1 commit into
Open
fix(browser): register event loop on current thread in _execute_async#485xlyoung wants to merge 1 commit into
xlyoung wants to merge 1 commit into
Conversation
When stream_async() dispatches _execute_async to a worker thread, the event loop created in __init__ is not registered on that thread, causing 'RuntimeError: There is no current event loop in thread'. Fix by calling asyncio.set_event_loop(self._loop) at the start of _execute_async to ensure the loop is always available regardless of which thread executes the method. Fixes strands-agents#453
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Fixes #453
When
stream_async()dispatches_execute_asyncto a worker thread, the event loop created inBrowser.__init__()is not registered on that thread. This causesself._loop.run_until_complete()to fail with:Root Cause
__init__callsasyncio.set_event_loop(self._loop)on the creating thread_execute_asyncis a synchronous method that Strands dispatches to a different thread via_streamrun_until_completeraisesFix
Add
asyncio.set_event_loop(self._loop)at the start of_execute_asyncto ensure the loop is registered on whichever thread executes the method. This is idempotent and safe - if the loop is already set, it's a no-op.Testing
AgentCoreBrowserworks withagent.stream_async()when called from within an already-running async event loopagent()calls continue to work unchangedCloses #453