Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 14 additions & 13 deletions crewai_tools/tools/code_interpreter_tool/code_interpreter_tool.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@

import importlib.util
import os
import io
import contextlib
from types import ModuleType
from typing import Any, Dict, List, Optional, Type

Expand Down Expand Up @@ -116,14 +118,13 @@ def safe_builtins() -> Dict[str, Any]:
return safe_builtins

@staticmethod
def exec(code: str, locals: Dict[str, Any]) -> None:
def exec(code: str) -> None:
"""Executes Python code in a restricted environment.

Args:
code: The Python code to execute as a string.
locals: A dictionary that will be used for local variable storage.
"""
exec(code, {"__builtins__": SandboxPython.safe_builtins()}, locals)
exec(code, {"__builtins__": SandboxPython.safe_builtins()})


class CodeInterpreterTool(BaseTool):
Expand Down Expand Up @@ -333,14 +334,14 @@ def run_code_in_restricted_sandbox(self, code: str) -> str:
code: The Python code to execute as a string.

Returns:
The value of the 'result' variable from the executed code,
or an error message if execution failed.
The output of the executed code as a string, or an error message if execution failed.
"""
Printer.print("Running code in restricted sandbox", color="yellow")
exec_locals = {}
try:
SandboxPython.exec(code=code, locals=exec_locals)
return exec_locals.get("result", "No result variable found.")
f = StringIO()
with redirect_stdout(f)
SandboxPython.exec(code=code)
return f.getvalue()
except Exception as e:
return f"An error occurred: {str(e)}"

Expand All @@ -355,8 +356,7 @@ def run_code_unsafe(self, code: str, libraries_used: List[str]) -> str:
libraries_used: A list of Python library names to install before execution.

Returns:
The value of the 'result' variable from the executed code,
or an error message if execution failed.
The output of the executed code as a string, or an error message if execution failed.
"""

Printer.print("WARNING: Running code in unsafe mode", color="bold_magenta")
Expand All @@ -366,8 +366,9 @@ def run_code_unsafe(self, code: str, libraries_used: List[str]) -> str:

# Execute the code
try:
exec_locals = {}
exec(code, {}, exec_locals)
return exec_locals.get("result", "No result variable found.")
f = StringIO()
with redirect_stdout(f)
exec(code)
return f.getvalue()
except Exception as e:
return f"An error occurred: {str(e)}"