fix: handle nested event loop in tool dispatch (fixes #11)#28
Merged
wxai-space merged 1 commit intowanxingai:mainfrom Mar 31, 2026
Merged
Conversation
Fixes wanxingai#11 When LightAgent is used inside an existing event loop (e.g., FastAPI, Jupyter notebook, or any async framework), calling `asyncio.run()` raises `RuntimeError: asyncio.run() cannot be called from a running event loop`. This commit introduces `run_async_safely()`, a helper function that: 1. Detects if we're already inside an event loop 2. If not, uses `asyncio.run()` as before (no overhead) 3. If yes, runs the coroutine in a separate thread with its own event loop This approach: - Is backward compatible (no API changes) - Works with all async frameworks (FastAPI, Starlette, Quart, etc.) - Works in Jupyter notebooks - Has minimal overhead when no event loop is running Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Collaborator
|
Thank you for your suggestion. The PR you submitted has been merged. |
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
run_async_safely()helper that detects event loop context and adapts execution strategyProblem
When LightAgent is used inside an existing event loop (e.g., FastAPI), the current code calls
asyncio.run()which raises:This happens in two places:
_run_non_stream_logic(line 868)_run_stream_logic(line 1054)Solution
Introduce
run_async_safely()that:asyncio.get_running_loop()asyncio.run()as before (zero overhead)This approach is:
Test Plan
asyncio.run()inside event loopRelated
Fixes #11
🤖 Generated with Claude Code