Reviewer · Performance Optimization
Defer expensive imports/work
Module-level imports of heavy or optional dependencies (e.g. `litellm`, `mcp`) run at `import swarms` time for every consumer, even those who never use that feature. These imports can cost over a second and may trigger network calls (e.g. fetching a model-cost map), so they must be deferred to the point of actual use rather than paid unconditionally at...
Module-level imports of heavy or optional dependencies (e.g. litellm, mcp) run at import swarms time for every consumer, even those who never use that feature. These imports can cost over a second and may trigger network calls (e.g. fetching a model-cost map), so they must be deferred to the point of actual use rather than paid unconditionally at package import.
Apply this pattern:
- Move the import into the function/method body (or behind
TYPE_CHECKINGif only needed for type hints) instead of the module top-level. - If the import is used by multiple call sites or needs to stay patchable in tests, bind it once into a module-level global guarded by
is None, so the cost is paid only on first real use and an active test patch is never clobbered:
completion = None
def _bind_litellm() -> None:
global completion
if completion is None:
from litellm import completion as _completion
completion = _completion
- More generally, apply the same discipline to any non-trivial computation: only do the work when the condition that actually needs it is true, rather than computing it unconditionally and discarding the result. For example, scanning a layer to determine if a checkpoint can be skipped should happen inside the
if self.checkpoint_dir:guard, not before it.
Before adding or moving an import/computation, verify with a quick benchmark (e.g. timing import swarms or the hot path) that the change actually avoids the unnecessary cost, and prefer the simplest form that keeps existing call sites and tests working unchanged.