Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow user to pass a template ID for E2B sandbox #170

Merged
merged 1 commit into from
Feb 13, 2025

Conversation

shivsak
Copy link
Contributor

@shivsak shivsak commented Feb 12, 2025

Summary by CodeRabbit

  • New Features
    • Introduced an optional template configuration to enhance customization of the sandbox environment setup.

Copy link
Contributor

coderabbitai bot commented Feb 12, 2025

Walkthrough

The update introduces an optional template attribute in the CodeExecutionV2 class. This attribute is initialized to None by default and can be set during instantiation. The _create_or_initialize_sandbox method is modified to pass this template attribute when creating a new Sandbox instance. The core class functionality remains unchanged apart from this added flexibility during sandbox initialization.

Changes

File(s) Change Summary
athina/.../code_execution_v2.py Added optional attribute template (default None) in CodeExecutionV2 constructor; modified _create_or_initialize_sandbox to pass template.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant CodeExecutionV2
    participant Sandbox

    Client->>CodeExecutionV2: Instantiate (with or without template)
    CodeExecutionV2->>CodeExecutionV2: Initialize with template
    CodeExecutionV2->>Sandbox: Create new instance with template
    Sandbox-->>CodeExecutionV2: Return sandbox instance
    CodeExecutionV2-->>Client: Return fully initialized instance
Loading

Poem

I hop through lines of code with glee,
Adding a template for all to see.
Sandbox awaits with a brand new twist,
A little tweak that can't be missed.
My bunny smile grows wide with cheer,
Celebrating changes that are now here! 🐰✨

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

🪧 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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. (Beta)
  • @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
Contributor

@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: 1

🔭 Outside diff range comments (2)
athina/steps/code_execution_v2.py (2)

109-119: 🛠️ Refactor suggestion

Add template parameter to constructor.

The template attribute should be configurable during initialization.

Apply this diff to add the template parameter:

     def __init__(
         self,
         execution_environment: ExecutionEnvironment = EXECUTION_LOCAL,
         sandbox_timeout: Optional[int] = None,
+        template: Optional[str] = None,
         **data,
     ):
         super().__init__(**data)
         self._sandbox = None
         self.execution_environment = execution_environment
         self.sandbox_timeout = sandbox_timeout
+        self.template = template

231-324: 🛠️ Refactor suggestion

Reduce complexity of _execute_e2b method.

The method has a high cyclomatic complexity (13) and handles multiple responsibilities. Consider breaking it down into smaller, focused methods.

Apply this diff to refactor the method:

     def _execute_e2b(self, input_data: dict, start_time: float) -> StepResult:
         try:
             self._create_or_initialize_sandbox()
             if self._sandbox is None:
                 print("Sandbox is not initialized")
                 return self._create_step_result(
                     status="error",
                     data="Sandbox is not initialized",
                     start_time=start_time,
                 )
 
-            # Initialize input variables if we're running Python code
-            if not self.code.strip().startswith(COMMAND_PREFIX):
-                input_vars_code = self._prepare_input_variables(input_data)
-                if input_vars_code:
-                    setup_code = "\n".join(input_vars_code)
-                    setup_execution = self._sandbox.run_code(setup_code)
-                    if setup_execution.error:
-                        print(
-                            f"Error setting up input variables: {setup_execution.error}"
-                        )
-
-            # Execute code based on type (commands or Python)
-            if self.code.strip().startswith(COMMAND_PREFIX):
-                # Handle command execution
-                commands = [
-                    line.strip()[1:] for line in self.code.split("\n") if line.strip()
-                ]
-                output = []
-                for command in commands:
-                    command_result = self._sandbox.commands.run(command)
-                    if command_result.error or command_result.exit_code != 0:
-                        return self._create_step_result(
-                            status="error",
-                            data=f"Failed to execute command: {command}\nexit_code: {command_result.exit_code}\nDetails:\n{command_result.error}",
-                            start_time=start_time,
-                        )
-                    print(f"Command output: {command_result}")
-                    if command_result.stdout:
-                        output.extend(command_result.stdout)
-                return self._create_step_result(
-                    status="success",
-                    data="".join(output),
-                    start_time=start_time,
-                    exported_vars={},
-                )
-            else:
-                # Handle Python code execution
-                execution = self._sandbox.run_code(self.code)
-                if execution.error:
-                    return self._create_step_result(
-                        status="error",
-                        data=f"Failed to execute the code.\nDetails:\n{execution.error}",
-                        start_time=start_time,
-                    )
-
-                # Capture variables for Python execution
-                var_execution = self._sandbox.run_code(VARIABLE_CAPTURE_CODE)
-                if var_execution.error:
-                    print(f"Error capturing variables: {var_execution.error}")
-                    return self._create_step_result(
-                        status="success",
-                        data="\n".join(execution.logs.stdout),
-                        start_time=start_time,
-                        exported_vars={},
-                    )
-
-                # Extract and return results
-                exported_vars = self._extract_exported_vars(
-                    "\n".join(var_execution.logs.stdout)
-                )
-                return self._create_step_result(
-                    status="success",
-                    data="\n".join(execution.logs.stdout),
-                    start_time=start_time,
-                    exported_vars=exported_vars,
-                )
+            return (
+                self._execute_commands(start_time)
+                if self.code.strip().startswith(COMMAND_PREFIX)
+                else self._execute_python_code(input_data, start_time)
+            )
 
         except Exception as e:
             print(f"\nUnexpected error: {str(e)}")
             return self._create_step_result(
                 status="error",
                 data=f"Failed to execute the code.\nDetails:\n{str(e)}",
                 start_time=start_time,
             )
+
+    def _execute_commands(self, start_time: float) -> StepResult:
+        """Execute shell commands in the sandbox."""
+        commands = [
+            line.strip()[1:] for line in self.code.split("\n") if line.strip()
+        ]
+        output = []
+        for command in commands:
+            command_result = self._sandbox.commands.run(command)
+            if command_result.error or command_result.exit_code != 0:
+                return self._create_step_result(
+                    status="error",
+                    data=f"Failed to execute command: {command}\nexit_code: {command_result.exit_code}\nDetails:\n{command_result.error}",
+                    start_time=start_time,
+                )
+            print(f"Command output: {command_result}")
+            if command_result.stdout:
+                output.extend(command_result.stdout)
+        return self._create_step_result(
+            status="success",
+            data="".join(output),
+            start_time=start_time,
+            exported_vars={},
+        )
+
+    def _execute_python_code(self, input_data: dict, start_time: float) -> StepResult:
+        """Execute Python code in the sandbox."""
+        # Initialize input variables
+        if not self._initialize_input_variables(input_data):
+            return self._create_step_result(
+                status="error",
+                data="Failed to initialize input variables",
+                start_time=start_time,
+            )
+
+        # Execute code
+        execution = self._sandbox.run_code(self.code)
+        if execution.error:
+            return self._create_step_result(
+                status="error",
+                data=f"Failed to execute the code.\nDetails:\n{execution.error}",
+                start_time=start_time,
+            )
+
+        # Capture variables
+        exported_vars = self._capture_variables()
+        return self._create_step_result(
+            status="success",
+            data="\n".join(execution.logs.stdout),
+            start_time=start_time,
+            exported_vars=exported_vars,
+        )
+
+    def _initialize_input_variables(self, input_data: dict) -> bool:
+        """Initialize input variables in the sandbox."""
+        input_vars_code = self._prepare_input_variables(input_data)
+        if input_vars_code:
+            setup_code = "\n".join(input_vars_code)
+            setup_execution = self._sandbox.run_code(setup_code)
+            if setup_execution.error:
+                print(f"Error setting up input variables: {setup_execution.error}")
+                return False
+        return True
+
+    def _capture_variables(self) -> dict:
+        """Capture and extract variables from the sandbox."""
+        var_execution = self._sandbox.run_code(VARIABLE_CAPTURE_CODE)
+        if var_execution.error:
+            print(f"Error capturing variables: {var_execution.error}")
+            return {}
+        return self._extract_exported_vars("\n".join(var_execution.logs.stdout))

This refactoring:

  1. Splits the complex method into smaller, focused methods
  2. Improves error handling and readability
  3. Makes the code more maintainable and testable
🧰 Tools
🪛 GitHub Actions: Python Linter

[error] 231-231: 'CodeExecutionV2._execute_e2b' is too complex (13)

🧹 Nitpick comments (1)
athina/steps/code_execution_v2.py (1)

135-141: Add template validation.

The template value should be validated before being passed to the Sandbox constructor to ensure it's not an empty string.

Apply this diff to add validation:

             if self._sandbox is None:
+                if self.template is not None and not self.template.strip():
+                    raise ValueError("Template ID cannot be empty")
                 self._sandbox = Sandbox(
                     template=self.template,
                     timeout=min(
                         self.sandbox_timeout or self.DEFAULT_TIMEOUT, self.MAX_TIMEOUT
                     ),
                     metadata={"session_id": self.session_id},
                 )
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 03d7df1 and a19918e.

📒 Files selected for processing (1)
  • athina/steps/code_execution_v2.py (2 hunks)
🧰 Additional context used
🪛 GitHub Actions: Python Linter
athina/steps/code_execution_v2.py

[error] 231-231: 'CodeExecutionV2._execute_e2b' is too complex (13)

athina/steps/code_execution_v2.py Show resolved Hide resolved
@vivek-athina vivek-athina merged commit 9f35f84 into main Feb 13, 2025
1 check failed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants