Final_Assignment_Template / tools /e2b_executor.py
Arash
feat: agent setup with tools
6715b3e
Raw History Blame Contribute Delete
2.74 kB
from pathlib import Path
from pydantic import BaseModel, Field
from langchain_core.tools import tool
from e2b_code_interpreter import Sandbox
import os
import json
# Might want to add validation to the execution result. It might be too large for the LLM to handle.
class E2BCodeExecutionInput(BaseModel):
code: str | None = Field(
default=None, description="The Python code string to execute."
)
file_path: str | None = Field(
default=None, description="Path to a Python file to execute."
)
@tool("execute_python_code_e2b", args_schema=E2BCodeExecutionInput)
def execute_python_e2b_tool(
code: str | None = None, file_path: str | None = None
) -> str:
"""
Execute Python code in a secure E2B sandbox. Only one argument is allowed. Either a code snippet (string) or a python file path (string).
Args:
code: The Python code string to execute.
file_path: Path to a Python file to execute.
"""
print("execute_python_code_e2b called with code:", code, "and file_path:", file_path)
if not os.getenv("E2B_API_KEY"):
raise ValueError("E2B_API_KEY is not set. Please set this environment variable.")
if file_path and code:
raise ValueError("Provide either code or a file_path, not both.")
if file_path:
try:
expanded_file_path = Path(file_path).expanduser()
if not expanded_file_path.is_file():
raise FileNotFoundError(f"The file {expanded_file_path} was not found.")
with open(expanded_file_path, "r") as f:
code = f.read()
except FileNotFoundError as e:
raise
except Exception as e:
raise RuntimeError(f"Error reading file {file_path}: {str(e)}")
if not code:
raise ValueError("No code provided to execute. Either pass a code string or a valid file_path.")
try:
with Sandbox() as sandbox:
execution = sandbox.run_code(code)
if execution.logs.stdout:
print(f"E2B Sandbox stdout:\n{execution.logs.stdout}")
if execution.logs.stderr:
print(f"E2B Sandbox stderr:\n{execution.logs.stderr}")
if execution.error:
error_info = {
"error_type": "E2BSandboxError",
"message": execution.error.message,
"traceback": execution.error.traceback,
"name": execution.error.name
}
return json.dumps({"e2b_execution_error": error_info})
return execution.to_json()
except Exception as e:
raise RuntimeError(f"An unexpected error occurred during E2B sandbox execution: {str(e)}")