Agent, reached from a FastAPI route, runs on a worker thread with the callerβs contextvars β the timeout is enforced inside that workerβs loop.
Quick Start
From a sync tool
run_coroutine_from_any_context to call async code from a sync tool:From an async tool
run_sync_in_executor to call blocking code from an async tool without blocking the event loop:Detecting the context
is_async_context to create dual-mode helpers:How It Works
The bridge probes for a running event loop. If no loop exists, it drives the coroutine directly on the callerβs thread viaasyncio.run (wrapped in asyncio.wait_for when a timeout is set). If a loop is already running (FastAPI, Jupyter, a bot handler calling agent.chat() from inside async def), it offloads onto a dedicated worker thread with its own loop β never a deadlock, never a RuntimeError. The callerβs contextvars are copied into the worker thread with contextvars.copy_context(), so trace, session, and approval context set by the caller stays visible inside the coroutine.
Which helper do I call?
Pick betweenawait, run_coroutine_from_any_context, and the wrapper-layer run_sync:
Async guardrails, callbacks, and approvals inside a running loop (PR #5377)
Prior to PR #5377,run_coroutine_from_any_context raised RuntimeError when reached from inside a running event loop (FastAPI async route, Jupyter cell, Discord/Slack bot handler, any async def calling agent.start(), task.execute_callback_sync(), or an approval callback). That surfaced as a spurious βAgent guardrail validation errorβ and burned LLM retries on a valid async guardrail. It also masked real summariser errors as an βevent loop already runningβ fallback to naive truncation. From that PR onwards:
- Async guardrails on
Agent(...)andTask(...)return their real result inside a running loop. - Async task callbacks reached via
Task.execute_callback_syncrun to completion instead of raising. - Async
ApprovalCallback(approve_fn=<async fn>)works from FastAPI / Textual / Jupyter without the caller having to opt in. ContextVars set by the caller (trace ids, session ids, approval context) are visible inside the coroutine.- The timeout is enforced. A coroutine that ignores cancellation (e.g. a blocking C call) can no longer pin the caller past
timeoutβ the worker is abandoned (shutdown(wait=False)). LLM_SUMMARIZEcontext compaction runs the real async summariser under a running loop instead of silently falling back to naive truncation, and provider errors from the summariser now surface instead of being masked.
Agent._process_guardrail, Task._process_guardrail, Task.execute_callback_sync, planning/approval.py, bus/bus.py) all keep their existing code and now work correctly. The sync tool-calling helper run_async_in_sync_context is a thin delegate to run_coroutine_from_any_context(coro, timeout=None).
Configuration Options
run_coroutine_from_any_context (the praisonaiagents.utils.async_bridge helper) takes two arguments:
300 default baked into run_coroutine_from_any_context β it does not read PRAISONAI_RUN_SYNC_TIMEOUT. That env var applies to the wrapper-layer praisonai._async_bridge helpers documented below.Timeout resolution: omitted vs None vs number
The timeout argument on the wrapper-layer helpers β run_sync, run_sync_or_offload, arun_sync_or_offload, and AsyncBridge.run_sync β uses a private _UNSET sentinel as its default, so the bridge can tell βargument omittedβ apart from an explicit timeout=None.
praisonai/integration/bridges/schedules_runner.py, praisonai/cli/commands/schedule.py) pass timeout=None so a long-running claimed job is never cancelled after 300 s.
_default_timeout() reads and parses PRAISONAI_RUN_SYNC_TIMEOUT per call, not at import. A malformed value (e.g. notanumber) falls back to 300.0 instead of crashing import praisonai, and a late-set value (dotenv loaded after import, per-request reconfig) takes effect on the next call.Common Patterns
Reusing async SDKs from sync tools
Offloading blocking calls from async tools
Context-aware dual-mode helper
Best Practices
Prefer await when you're already async
Prefer await when you're already async
run_coroutine_from_any_context inside async def now works β it offloads to a worker thread rather than raising. But await is still the right choice from an existing coroutine: it keeps the work on the callerβs loop and avoids the worker-thread and context-copy overhead the bridge takes on to stay safe.Don't wrap everything
Don't wrap everything
Set a sensible timeout
Set a sensible timeout
Check is_async_context() for dual-mode helpers
Check is_async_context() for dual-mode helpers
Used by
The following synchronous APIs route throughrun_sync() and therefore honour PRAISONAI_RUN_SYNC_TIMEOUT consistently:
praisonai.bots.WebhookApproval.request_approval_sync()praisonai.bots.HTTPApproval.request_approval_sync()praisonai.integrations.get_available_integrations()praisonai._run_praisonai(added PR #1681) β boots the InteractiveRuntime on the persistent background loop. If you callPraisonAI.run()from inside a running event loop, you now get a clearRuntimeErrorinstead of a silent deadlock.- All ~77 wrapper-side
run_synccall sites (gateway, a2u, mcp_server, scheduler) β see PR #1583 for the full list. praisonai.auto.BaseAutoGenerator._structured_completion/_run_coro_syncrunner threads (added in the fix for #3340) β inherit the callerβsscoped_bridge()viacontextvars.copy_context().praisonai_code.cli.features.agent_tools._run_sync(added via PR #3361) β a separate, module-local bridge in the Tier-2praisonai-codepackage that ACP/LSP agent-centric tools route through. Does not importpraisonai._async_bridge(C7 gate), but reads the samePRAISONAI_RUN_SYNC_TIMEOUTenv var and enforces the same 300 s default. Safe under a running loop (offloads to aThreadPoolExecutor), and returns promptly on timeout without waiting for the abandoned worker.- Ten CLI subcommand leaves route through the public
run_cli_coro()helper (PR #5322) βbackground {list, status, cancel, clear},managed {list-check, stop},standardise,sandbox {execute, shell},chatREPL/tasks {list, cancel, status}, and thedirect_promptexternal-agent pass-through β so per-loop connection pools survive across invocations instead of a freshasyncio.run(...)per call.
praisonai._async_bridge) creates its
background loop lazily on the first run_sync() call. Pure imports
do not allocate a loop or thread. Calling the module-level shutdown() before any
run_sync() is a safe no-op β it only affects the shared default bridge, not any AsyncBridge() instances you create yourself.The shared defaultβs atexit teardown hook is also registered lazily, on the first real use of the shared default bridge (inside AsyncBridge._spawn_locked(), guarded by self is globals().get("_BG")). A bare import praisonai no longer installs a process-wide atexit hook, so Django/Airflow/Streamlit embedders are unaffected until they actually call run_sync.Troubleshooting
RuntimeError: run_coroutine_from_any_context() cannot be called from async context
This specificRuntimeError no longer exists. PR #5377 removed it β previously-broken async guardrails, callbacks, and approvals now succeed inside a running loop by offloading to a worker thread. If you still see this message, you are on an older release; upgrade to the version that ships PR #5377.
My async guardrail / callback / approval now works but Iβd rather await it directly
You can. Insideasync def code, await the coroutine yourself instead of routing through the bridge. The bridge is there for the sync-only surfaces (Agent.start, Task.execute_callback_sync, sync tool functions) that cannot await.
asyncio.run() cannot be called from a running event loop
This error used to leak from SDK internals before the async bridge was implemented. If you see this on current versions, upgrade to the latest release.praisonai/tests/unit/test_async_bridge.py::TestBridgeIntegration::test_timeout_cancels_coroutine_and_runs_finally β quote this in the page so users can verify the behaviour locally.
TimeoutError: run_sync_or_offload() worker did not complete within s
This timeout branch is only reachable when the caller is inside a running loop and has opted intoPRAISONAI_ALLOW_LOOP_BLOCKING=true (the offload path). A plain-sync caller still hits the same TimeoutError via run_sync. The offloaded coroutine did not finish inside timeout + 1s β check for blocking I/O or a missing await, or raise PRAISONAI_RUN_SYNC_TIMEOUT if the work is legitimately long-running. Prefer migrating to await arun_sync_or_offload(...) / await praisonai.arun(...) so the loop is never blocked.
PermissionError in approval system
The approval system now fails fast in async contexts. Configure a non-console backend:Wrapper Bridge (praisonai._async_bridge)
The wrapper layer provides a module-level run_sync() for CLI scripts and single-tenant servers, plus a public AsyncBridge class when you need an isolated loop per tenant or service.
- Module-level (default)
- Per-instance AsyncBridge
When to use a per-instance bridge
PRAISONAI_RUN_SYNC_TIMEOUT: Default timeout in seconds (300). Resolved per call (not at import) via_default_timeout(); a malformed value falls back to300.0, and late-set env vars (dotenv loaded after import, per-request reconfig) are honoured. An explicittimeout=Noneopts into an unbounded wait (used by the sync-scheduler bridges for long-lived jobs). Read by bothpraisonai._async_bridge(this page) andpraisonai_code.cli.features.agent_tools._run_sync(see Agent-Centric Tools β Timeouts & Cancellation).
- CLI approval protocol (ACP/LSP tools)
- Interactive runtime start/stop operations
- Deployment scheduler
- Gateway operations
run_cli_coro() β the CLI-leaf entry point
run_cli_coro() is the public helper a synchronous CLI leaf should call instead of a bare asyncio.run(coro). It routes the coroutine onto the shared background loop so per-loop connection pools survive across invocations, any embedder-installed scoped_bridge() binding is honoured, and no fresh loop is spawned on every call (PR #5322).
None) β deliberately different from run_syncβs configurable 300 s default. A CLI leaf owns its runtime: an interactive sandbox shell, a multi-artifact standardise run, or a long background job must not be aborted mid-flight. A caller that wants a deadline passes an explicit timeout=.Migration from asyncio.run()
Replace the bare asyncio.run(...) at a CLI leaf with run_cli_coro(...) β the coroutine now shares the background loop instead of tearing down a fresh one on every invocation.
Migrated CLI sites
Ten CLI subcommand leaves now dispatch throughrun_cli_coro() so repeated invocations reuse the background loop:
praisonai sandbox shell keeps its blocking input() on the main thread so Ctrl-C / SIGINT is still delivered correctly β only the async sandbox operations dispatch through run_cli_coro().dispatch_maybe_awaitable β one helper for sync-hook dispatch
dispatch_maybe_awaitable() is the single owner of the βa sync call may return a coroutine; run it correctlyβ policy. It picks one of four branches from the running-loop state and an explicit DispatchKind.
DispatchKind makes read-vs-write intent explicit at the call site instead of depending on a name-string allow-list. The four branches:
PraisonAIDB._call_store, _merge_and_set, and on_agent_end paths route through β the split policy is no longer hand-rolled per call site (PR #5038). See Async DB Hooks β Shared dispatch for the db-adapter view.
dispatch_maybe_awaitable is a wrapper internal used by the db adapter β end users do not call it directly. The READ strict-inside-a-loop behaviour (PR #4821) and the completion-hook persistence guarantee (PR #4948) are pre-existing behaviours the helper now enforces in one place; PR #5038 is DRY consolidation with no user-visible behaviour change.praisonai/tests/unit/test_async_bridge.py::TestDispatchMaybeAwaitable pin the four branches:
test_non_awaitable_passthroughβ a plain value is returned unchanged.test_no_loop_read_blocks_and_returns_valueβ no running loop +READblocks and returns the value.test_no_loop_write_blocks_and_returns_valueβ no running loop +WRITEruns to completion (fire-and-forget is a running-loop concern).test_running_loop_write_is_tracked_fire_and_forgetβ running loop +WRITEsubmits, tracks, and returnsNonewhile the write still completes.test_running_loop_failed_write_logs_and_does_not_raiseβ a failed deferredWRITEis swallowed (logged) via the done-callback, never surfacing to the sync caller.
run_sync_or_offload β strict inside a running loop
Use run_sync_or_offload() on a code path that can be reached from a plain script or from inside a running event loop (FastAPI, Jupyter, async tests). On a plain-sync caller it dispatches to run_sync. Inside a running loop it now raises RuntimeError by default (PR #4261) and steers you to the awaitable siblings β it never silently pins the loop.
Plain sync caller β works
Inside a FastAPI handler β await instead
RuntimeError. Make the handler async and await the coroutine directly:async def, await the awaitable sibling:Configuration Options
AsyncBridge via run_sync, sharing its background loop and connection pools. Called from inside a running loop with PRAISONAI_ALLOW_LOOP_BLOCKING=true, it copies the callerβs ContextVars onto a worker thread that hands the coroutine to the same bridge β never a fresh asyncio.new_event_loop() β so a caller-installed scoped_bridge() binding still wins and LiteLLM/HTTPX per-loop connection pools are preserved. Exceptions re-raise on the caller thread.
The strict RuntimeError
In the default (strict) mode, a call from inside a running loop raises with this message β grep for it in a traceback:
How it differs from run_sync
PRAISONAI_ALLOW_LOOP_BLOCKING opt-in, run_sync_or_offload() bounds thread.join() at timeout + 1.0s. If the worker is still alive it cancels the in-flight future and raises TimeoutError("run_sync_or_offload() worker did not complete within {timeout}s"). The extra second covers thread hand-off/teardown so the join does not spuriously time out before the worker records its own error.Migration
Any caller that today relies on offload-inside-a-loop must either (a) migrate to the awaitable sibling (await praisonai.arun(...), await adapter.arun(...), or await arun_sync_or_offload(...)), or (b) set PRAISONAI_ALLOW_LOOP_BLOCKING=true as an interim measure. See PR #4261.
Best Practices
Prefer arun / arun_sync_or_offload inside a loop
Prefer arun / arun_sync_or_offload inside a loop
await the awaitable sibling so the loop stays responsive. The sync helper now raises RuntimeError by design rather than parking the loop.Keep run_sync_or_offload for plain-sync surfaces
Keep run_sync_or_offload for plain-sync surfaces
run_sync_or_offload dispatches to run_sync and reuses the shared bridge and its connection pools.Set PRAISONAI_ALLOW_LOOP_BLOCKING=true only for controlled migration windows
Set PRAISONAI_ALLOW_LOOP_BLOCKING=true only for controlled migration windows
timeout + 1s. Use it only as a bounded interim measure while migrating a known-safe path to the awaitable sibling β never as a long-term default.praisonai.auto, persistence.orchestrator, api.agent_invoke) are migrated onto it.
Related
run_sync
scoped_bridge
PRAISONAI_ALLOW_LOOP_BLOCKING=true.Agent-Centric Tools
_run_sync (PR #3361) mirrors the same design.arun_sync_or_offload β await from an async context
Use arun_sync_or_offload() from async callers (FastAPI/Starlette handlers, Jupyter cells, async tests) β await it instead of parking the loop thread with the sync helper.
Import and await
Inside a FastAPI handler
await, donβt park β the loop stays responsive while the agent runs:Configuration Options
run_sync_or_offload, this variant does not park the running loop thread. It submits coro to the active AsyncBridge and awaits the result, so the loop keeps serving other work. The coroutine runs on the shared background bridge loop β never a fresh asyncio.new_event_loop() β so a caller-installed scoped_bridge() binding still wins and per-loop LiteLLM/HTTPX connection pools are preserved. On timeout or cancellation, the in-flight future is cancelled before the exception re-raises.
Best Practices
Await it from async handlers, not run_sync_or_offload
Await it from async handlers, not run_sync_or_offload
run_sync_or_offload raises RuntimeError by default (and only offloads-and-blocks under PRAISONAI_ALLOW_LOOP_BLOCKING=true). arun_sync_or_offload awaits instead, so the loop keeps serving other requests.Keep the sync helper for sync-only paths
Keep the sync helper for sync-only paths
await. Use run_sync_or_offload (or run_sync) there and reserve arun_sync_or_offload for code already inside a coroutine.Related
run_sync_or_offload
scoped_bridge
Per-Session Scoped Bridge
Servers and gateways that handle multiple concurrent sessions need each session to run on its own loop+thread binding.current_bridge() and scoped_bridge() provide ContextVar-backed per-session isolation so sessions never share a bridge accidentally.
PraisonAIDB (or any adapter that inherits from it, e.g. NeonDB) is safe to share across multiple scoped_bridge() loops. Its async init/close no longer caches an event-loop-bound asyncio.Lock on the instance β sync serialisation happens off-loop via asyncio.to_thread under a threading.Lock, so per-session loops can each call on_run_end / aclose against the shared adapter without RuntimeError: <lock> is bound to a different event loop.When to use scoped bridges
Usescoped_bridge() inside any request handler that may run concurrently with other handlers β for example a FastAPI endpoint, a Starlette WebSocket handler, or a custom bot session dispatcher.
The isolation now extends into sync-completion runner threads used by AutoGenerator.generate() β a scoped_bridge() set on the caller is honoured inside the worker thread via contextvars.copy_context().
- Multi-tenant sync embedders no longer need a manual
scoped_bridge()aroundpraisonai workflow run(or aprocess: workflowYAML dispatched throughgenerate_crew_and_kickoff()) β_run_yaml_workflowwrapsworkflow.start(...)in its ownscoped_bridge().
scoped_bridge() context manager
ContextVar so nested scopes work correctly in async tasks and threads β each concurrent task sees only its own bridge.
Scope-owned bridge (preferred)
scoped_bridge() creates a fresh bridge and tears it down with permanent=True when the with block ends. Internal code that calls module-level run_sync() inside the block uses the scoped bridge via contextvars β no import changes required.
current_bridge() for introspection
current_bridge() returns the bridge bound to the current async task, or None when no scope is active. Use it to inspect which bridge is in use without passing it explicitly through call stacks.
Multi-session server example
API Reference
async_scoped_bridge() β async-safe context manager
async_scoped_bridge() is the async-safe sibling of scoped_bridge() for async def callers β same binding semantics, but the scope-owned bridge is torn down off-loop so scope exit never parks the callerβs event loop.
Wrap your async handler in one line β a stuck coroutine in one tenantβs request can no longer freeze the loop for every other tenant:
When to use it
Pick the context manager that matches your caller.scoped_bridge()β sync callers (CLI,generate_crew_and_kickoff, sync request handlers).async_scoped_bridge()β insideasync def(FastAPI handlers,agenerate_crew_and_kickoff, custom async gateways). Preferred over the sync sibling for anyasync def, because scope exit on the sync context manager parks the loop thread for up to ~10s whileshutdown()waits for cancellation and joins the background thread.
FastAPI multi-tenant handler
Teardown internals
A scope-owned bridge (no argument) is torn down viaasyncio.to_thread(bridge.shutdown, permanent=True) under asyncio.shield, so the blocking cancel-and-join runs on a worker thread instead of the event loop. asyncio.shield keeps that teardown running to completion even when the surrounding scope is being cancelled, so the loop+thread is neither leaked nor blocked. A caller-provided bridge is left untouched β the caller owns its lifecycle.
Behavioural contract
API Reference
Per-run auto-scoping (sequential, hierarchical, workflow)
Bothgenerate_crew_and_kickoff() (sync) and agenerate_crew_and_kickoff() (async) now auto-wrap each run in a per-run scoped bridge β the sync path uses scoped_bridge(), the async path uses async_scoped_bridge(). Every run isolates its run_sync-driven work onto its own loop+thread, so a stuck coroutine in one agent/tenant can no longer park the shared default loop for the rest.
Each entry point has two arms β a sequential/hierarchical arm and a YAML-workflow arm β so there are four corners in total. All four are now symmetric.
The same per-run scoping now covers process: workflow on the sync path. _run_yaml_workflow (invoked by praisonai workflow run ... and AgentsGenerator.generate_crew_and_kickoff() when the YAMLβs process: is workflow) wraps workflow.start(...) in scoped_bridge(). The async workflow path (_arun_yaml_workflow) already runs on the callerβs loop and remains unchanged.
PR #5360 closes the last asymmetry: the sync YAML workflow arm now wraps its _run_yaml_workflow(config) call in scoped_bridge(), matching the other three corners so a stuck coroutine in one tenantβs YAML workflow can no longer park the shared default loop for the rest.
Callers doing multi-tenant runs no longer need to add their own scoped_bridge() around either entry point β with this PR that is now true for all four corners β a stuck coroutine in one run cannot affect another. On the async path this closes a live multi-tenancy regression: praisonai serve, the gateway, and FastAPI-embed deployments no longer let a stuck coroutine in one tenant park the shared default loop+thread for the others. The earlier reasoning that async callers await arun directly did not hold in practice β adapter internals, user tools, the sync DeliveryRouter._finalize_delivery, and BlueprintAgent.start() (via run_sync(...)) all reach back into the sync bridge, which previously resolved to the process-default bridge under the async path.
See Wrapper β Lifecycle / cleanup for the embedder view.

