|
| 1 | +from crewai.tools import BaseTool |
| 2 | +from typing import Type |
| 3 | +from pydantic import BaseModel, Field |
| 4 | +from sandboxai import Sandbox |
| 5 | + |
| 6 | + |
| 7 | +class SandboxIPythonToolArgs(BaseModel): |
| 8 | + code: str = Field(..., description="The code to execute in the ipython cell.") |
| 9 | + |
| 10 | + |
| 11 | +class SandboxIPythonTool(BaseTool): |
| 12 | + name: str = "Run Python code" |
| 13 | + description: str = "Run python code and shell commands in an ipython cell. Shell commands should be on a new line and start with a '!'." |
| 14 | + args_schema: Type[BaseModel] = SandboxIPythonToolArgs |
| 15 | + |
| 16 | + def __init__(self, *args, **kwargs): |
| 17 | + super().__init__(*args, **kwargs) |
| 18 | + # Note that the sandbox only shuts down once the Python program exits. |
| 19 | + self._sandbox = Sandbox(embedded=True) |
| 20 | + |
| 21 | + def _run(self, code: str) -> str: |
| 22 | + result = self._sandbox.run_ipython_cell(code=code) |
| 23 | + return result.output |
| 24 | + |
| 25 | + |
| 26 | +class SandboxShellToolArgs(BaseModel): |
| 27 | + command: str = Field(..., description="The bash commands to execute.") |
| 28 | + |
| 29 | + |
| 30 | +class SandboxShellTool(BaseTool): |
| 31 | + name: str = "Run shell command" |
| 32 | + description: str = "Run bash shell commands in a sandbox." |
| 33 | + args_schema: Type[BaseModel] = SandboxShellToolArgs |
| 34 | + |
| 35 | + def __init__(self, *args, **kwargs): |
| 36 | + super().__init__(*args, **kwargs) |
| 37 | + # Note that the sandbox only shuts down once the Python program exits. |
| 38 | + self._sandbox = Sandbox(embedded=True) |
| 39 | + |
| 40 | + def _run(self, command: str) -> str: |
| 41 | + result = self._sandbox.run_shell_command(command=command) |
| 42 | + return result.output |
0 commit comments