Awesome Reviewers

Reviewer · Performance Optimization

Defer costly imports and work

Avoid paying for expensive operations—module imports, scans, or computations—unless and until they are actually needed. Heavy third-party dependencies (e.g. `litellm`, `mcp`) must not be imported at module/package load time if they are only used inside specific functions: move the `import` statement into the function body (or into a `if TYPE_CHECKING:`...

Instruction

Avoid paying for expensive operations—module imports, scans, or computations—unless and until they are actually needed. Heavy third-party dependencies (e.g. litellm, mcp) must not be imported at module/package load time if they are only used inside specific functions: move the import statement into the function body (or into a if TYPE_CHECKING: block when only used for type hints), so import swarms stays fast and doesn’t eagerly trigger side effects like litellm’s model-cost map fetch.

# Bad: module-level import pays the cost for every consumer of the package
from litellm import embedding

def get_embedding(self, text):
    return embedding(...)

# Good: deferred import, cost paid only when this code path runs
def get_embedding(self, text):
    # Deferred: litellm must not load at `import swarms` time (#1754)
    from litellm import embedding
    return embedding(...)

# Good: type-only usage never needs a runtime import
from typing import TYPE_CHECKING
if TYPE_CHECKING:
    from mcp import ClientSession

The same principle applies to per-iteration computations: don’t unconditionally compute something (e.g. scanning a layer to check for failures) if the result is only used inside a guarded branch. Fold the computation inside the if that consumes it so clean/no-op paths skip the work entirely:

# Bad: layer_clean is computed every iteration even when checkpoint_dir is falsy
layer_clean = not any(
    entry[0] in self.failed_nodes or entry[0] in self.skipped_nodes
    for entry in layer
)
if self.checkpoint_dir:
    ...

# Good: only compute it when it will actually be used
if self.checkpoint_dir:
    layer_clean = not any(
        entry[0] in self.failed_nodes or entry[0] in self.skipped_nodes
        for entry in layer
    )
    ...

When deferring an import, leave a short comment referencing the motivating issue so future readers understand why the import isn’t at the top of the file. Validate the win with a measurement (e.g. import-time before/after) rather than assuming it—cheap imports or rarely-hit code paths may not be worth the added indirection.