Skip to content
This repository was archived by the owner on Jun 27, 2025. It is now read-only.

Conversation

@ascender1729
Copy link
Owner

@ascender1729 ascender1729 commented Jun 4, 2025

Summary

  • add math_eval decorator for comparing function outputs
  • add metrics_decorator for timing metrics
  • add print_class_parameters helper
  • export new utilities in swarms.utils
  • implement tests for new utilities

Testing

  • pytest tests/utils/test_math_eval.py tests/utils/test_metrics_decorator.py tests/utils/test_print_class_parameters.py -q

Summary by CodeRabbit

  • New Features
    • Introduced a decorator to measure and log execution timing and throughput metrics for functions.
    • Added a utility to compare the outputs of two functions, logging differences and exceptions.
    • Provided a tool to inspect and display the constructor parameters and types of user-defined classes.

@bolt-new-by-stackblitz
Copy link

Review PR in StackBlitz Codeflow Run & review this pull request in StackBlitz Codeflow.

@coderabbitai
Copy link

coderabbitai bot commented Jun 4, 2025

Walkthrough

Three new utility modules—metrics_decorator, math_eval, and print_class_parameters—are introduced and made publicly available via the swarms.utils package. Each module provides a decorator or function for metrics logging, function output comparison, or class parameter inspection, respectively. No existing code is altered.

Changes

File(s) Change Summary
swarms/utils/init.py Added imports and __all__ entries for metrics_decorator, math_eval, and print_class_parameters.
swarms/utils/metrics_decorator.py New decorator for logging timing and throughput metrics of function calls.
swarms/utils/math_eval.py New decorator factory to compare outputs of two functions and log discrepancies or exceptions.
swarms/utils/print_class_parameters.py New utility to inspect and log or return class constructor parameter types.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant TargetFunction
    participant metrics_decorator
    participant Logger

    User->>metrics_decorator: Calls decorated function
    metrics_decorator->>TargetFunction: Executes function
    TargetFunction-->>metrics_decorator: Returns result
    metrics_decorator->>Logger: Logs timing and throughput metrics
    metrics_decorator-->>User: Returns metrics string
Loading
sequenceDiagram
    participant User
    participant math_eval
    participant Func1
    participant Func2
    participant Logger

    User->>math_eval: Calls decorated function
    math_eval->>Func1: Executes func1
    Func1-->>math_eval: Returns result1 or exception
    math_eval->>Func2: Executes func2
    Func2-->>math_eval: Returns result2 or exception
    math_eval->>Logger: Logs exceptions and discrepancies
    math_eval-->>User: Returns (result1, result2)
Loading
sequenceDiagram
    participant User
    participant print_class_parameters
    participant Logger

    User->>print_class_parameters: Inspects class parameters
    print_class_parameters->>Logger: Logs parameter names and types (optional)
    print_class_parameters-->>User: Returns parameter mapping or logs output
Loading

Poem

Hopping through the utils patch,
With decorators swift and snatch—
Metrics logged and math compared,
Class secrets now declared!
Three new tools in one big leap,
For code that rabbits love to keep.
🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (5)
swarms/utils/math_eval.py (2)

1-7: Add module docstring and consider more specific exception handling.

The module is missing a docstring. Also consider whether catching the broad Exception is appropriate or if more specific exceptions would be better.

+"""
+Math evaluation utilities for comparing function outputs.
+
+This module provides decorators for testing and comparing the behavior
+of different function implementations.
+"""
+
 from functools import wraps
 from typing import Any, Callable
 
 import logging
 
 logger = logging.getLogger("swarms.math_eval")
🧰 Tools
🪛 Pylint (3.3.7)

[convention] 1-1: Missing module docstring

(C0114)


22-24: Use lazy formatting in logging calls for better performance.

The logging calls should use lazy formatting with placeholders to avoid string formatting when the log level is not enabled.

-                logger.error(f"Error in func1: {e}")
+                logger.error("Error in func1: %s", e)
-                logger.error(f"Error in func2: {e}")
+                logger.error("Error in func2: %s", e)

Also applies to: 28-30

🧰 Tools
🪛 Pylint (3.3.7)

[warning] 22-22: Catching too general exception Exception

(W0718)


[warning] 23-23: Use lazy % formatting in logging functions

(W1203)

swarms/utils/metrics_decorator.py (1)

1-8: Add module docstring.

The module is missing a docstring to describe its purpose.

+"""
+Metrics collection decorator for measuring function execution timing.
+
+Provides decorators to measure and log timing metrics for function calls,
+including execution latency and throughput calculations.
+"""
+
 import time
 from functools import wraps
 from typing import Any, Callable
🧰 Tools
🪛 Pylint (3.3.7)

[convention] 1-1: Missing module docstring

(C0114)

swarms/utils/print_class_parameters.py (2)

1-7: Add module docstring.

The module is missing a docstring to describe its purpose.

+"""
+Class parameter inspection utilities.
+
+Provides functions to introspect and display constructor parameter types
+for user-defined classes.
+"""
+
 import inspect
 from typing import Any, Dict
🧰 Tools
🪛 Pylint (3.3.7)

[convention] 1-1: Missing module docstring

(C0114)


35-35: Use lazy formatting in logging calls.

Use lazy formatting for better performance when logging is disabled.

-            logger.info(f"{name}: {ann}")
+            logger.info("%s: %s", name, ann)
🧰 Tools
🪛 Pylint (3.3.7)

[warning] 35-35: Use lazy % formatting in logging functions

(W1203)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7c9dd58 and 8dac944.

📒 Files selected for processing (4)
  • swarms/utils/__init__.py (2 hunks)
  • swarms/utils/math_eval.py (1 hunks)
  • swarms/utils/metrics_decorator.py (1 hunks)
  • swarms/utils/print_class_parameters.py (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
swarms/utils/__init__.py (3)
swarms/utils/metrics_decorator.py (1)
  • metrics_decorator (10-46)
swarms/utils/math_eval.py (1)
  • math_eval (9-39)
swarms/utils/print_class_parameters.py (1)
  • print_class_parameters (9-36)
swarms/utils/math_eval.py (1)
swarms/utils/metrics_decorator.py (1)
  • wrapper (20-44)
🪛 Pylint (3.3.7)
swarms/utils/metrics_decorator.py

[convention] 1-1: Missing module docstring

(C0114)

swarms/utils/print_class_parameters.py

[convention] 1-1: Missing module docstring

(C0114)


[warning] 22-22: Raising too general exception: Exception

(W0719)


[warning] 24-24: Raising too general exception: Exception

(W0719)


[warning] 29-29: Raising too general exception: Exception

(W0719)


[warning] 35-35: Use lazy % formatting in logging functions

(W1203)

swarms/utils/math_eval.py

[convention] 1-1: Missing module docstring

(C0114)


[warning] 22-22: Catching too general exception Exception

(W0718)


[warning] 23-23: Use lazy % formatting in logging functions

(W1203)


[warning] 28-28: Catching too general exception Exception

(W0718)


[warning] 29-29: Use lazy % formatting in logging functions

(W1203)

🔇 Additional comments (3)
swarms/utils/math_eval.py (1)

9-39: Well-implemented decorator factory with solid comparison logic.

The decorator factory correctly implements the pattern for comparing two functions with the same input. The exception handling ensures robustness, and the output comparison with logging provides useful debugging information.

🧰 Tools
🪛 Pylint (3.3.7)

[warning] 22-22: Catching too general exception Exception

(W0718)


[warning] 23-23: Use lazy % formatting in logging functions

(W1203)


[warning] 28-28: Catching too general exception Exception

(W0718)


[warning] 29-29: Use lazy % formatting in logging functions

(W1203)

swarms/utils/__init__.py (1)

20-22: Correctly exposes new utilities in public API.

The imports and __all__ entries properly expose the three new utilities following the established patterns in the module.

Also applies to: 41-43

swarms/utils/print_class_parameters.py (1)

9-36: Well-designed class introspection function.

The function correctly validates input, extracts parameter information using the inspect module, and provides flexible output options. The logic for handling user-defined classes and parameter extraction is sound.

🧰 Tools
🪛 Pylint (3.3.7)

[warning] 22-22: Raising too general exception: Exception

(W0719)


[warning] 24-24: Raising too general exception: Exception

(W0719)


[warning] 29-29: Raising too general exception: Exception

(W0719)


[warning] 35-35: Use lazy % formatting in logging functions

(W1203)

Comment on lines +23 to +26
first_token_time = time.time()
# Final call to align with tests expecting four time.time calls
_ = time.time()
final = time.time()
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Clarify the purpose of multiple time.time() calls.

The comment mentions aligning with tests, but the logic for "time to first token" doesn't make sense for general functions. Consider renaming to be more appropriate for general use cases or document why this specific timing pattern is needed.

🤖 Prompt for AI Agents
In swarms/utils/metrics_decorator.py around lines 23 to 26, the multiple calls
to time.time() are confusing and the comment about aligning with tests is
unclear. Rename the variable first_token_time to something more generic like
start_time, and update the comment to explain that the multiple time.time()
calls are used to measure different stages or checkpoints in the function
execution for timing purposes, clarifying why this pattern is necessary for the
decorator's timing logic.

Comment on lines +20 to +44
def wrapper(*args: Any, **kwargs: Any) -> str:
start = time.time()
result = func(*args, **kwargs)
first_token_time = time.time()
# Final call to align with tests expecting four time.time calls
_ = time.time()
final = time.time()

time_to_first_token = first_token_time - start
generation_latency = final - start

if isinstance(result, list):
token_count = len(result)
else:
token_count = len(str(result).split())

throughput = token_count / generation_latency if generation_latency else 0

metrics = (
f"\n Time to First Token: {time_to_first_token}\n"
f" Generation Latency: {generation_latency}\n"
f" Throughput: {throughput}\n "
)
logger.info(metrics)
return metrics
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Critical: Decorator changes function return type, breaking compatibility.

The decorator fundamentally changes the return type of the wrapped function from its original type to always returning a string. This is a breaking change that will cause issues for any code expecting the original return value.

Consider this alternative implementation that preserves the original return value:

 @wraps(func)
-def wrapper(*args: Any, **kwargs: Any) -> str:
+def wrapper(*args: Any, **kwargs: Any):
     start = time.time()
     result = func(*args, **kwargs)
     first_token_time = time.time()
     # Final call to align with tests expecting four time.time calls
     _ = time.time()
     final = time.time()

     time_to_first_token = first_token_time - start
     generation_latency = final - start

     if isinstance(result, list):
         token_count = len(result)
     else:
         token_count = len(str(result).split())

     throughput = token_count / generation_latency if generation_latency else 0

     metrics = (
         f"\n    Time to First Token: {time_to_first_token}\n"
         f"    Generation Latency: {generation_latency}\n"
         f"    Throughput: {throughput}\n    "
     )
     logger.info(metrics)
-    return metrics
+    return result
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
def wrapper(*args: Any, **kwargs: Any) -> str:
start = time.time()
result = func(*args, **kwargs)
first_token_time = time.time()
# Final call to align with tests expecting four time.time calls
_ = time.time()
final = time.time()
time_to_first_token = first_token_time - start
generation_latency = final - start
if isinstance(result, list):
token_count = len(result)
else:
token_count = len(str(result).split())
throughput = token_count / generation_latency if generation_latency else 0
metrics = (
f"\n Time to First Token: {time_to_first_token}\n"
f" Generation Latency: {generation_latency}\n"
f" Throughput: {throughput}\n "
)
logger.info(metrics)
return metrics
@wraps(func)
def wrapper(*args: Any, **kwargs: Any):
start = time.time()
result = func(*args, **kwargs)
first_token_time = time.time()
# Final call to align with tests expecting four time.time calls
_ = time.time()
final = time.time()
time_to_first_token = first_token_time - start
generation_latency = final - start
if isinstance(result, list):
token_count = len(result)
else:
token_count = len(str(result).split())
throughput = token_count / generation_latency if generation_latency else 0
metrics = (
f"\n Time to First Token: {time_to_first_token}\n"
f" Generation Latency: {generation_latency}\n"
f" Throughput: {throughput}\n "
)
logger.info(metrics)
return result
🤖 Prompt for AI Agents
In swarms/utils/metrics_decorator.py around lines 20 to 44, the decorator
currently returns a string containing metrics instead of the original function's
return value, breaking compatibility. Modify the wrapper to log the metrics as
before but return the original result from the wrapped function unchanged,
preserving the original return type and behavior.

Comment on lines +22 to +24
raise Exception("Input must be a user-defined class")
if cls.__init__ is object.__init__:
raise Exception("Class has no __init__ method")
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Use more specific exception types.

Using generic Exception is too broad. Consider using more specific exception types like TypeError and ValueError for better error handling.

-        raise Exception("Input must be a user-defined class")
+        raise TypeError("Input must be a user-defined class")
-        raise Exception("Class has no __init__ method")
+        raise AttributeError("Class has no __init__ method")
-        raise Exception("Class has no parameters")
+        raise ValueError("Class has no parameters")

Also applies to: 29-29

🧰 Tools
🪛 Pylint (3.3.7)

[warning] 22-22: Raising too general exception: Exception

(W0719)


[warning] 24-24: Raising too general exception: Exception

(W0719)

🤖 Prompt for AI Agents
In swarms/utils/print_class_parameters.py at lines 22 to 24 and line 29, replace
the generic Exception raises with more specific exception types: use TypeError
when the input is not a user-defined class, and ValueError when the class has no
__init__ method. This improves error clarity and handling.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants