import subprocess from langchain.tools import tool @tool(parse_docstring=True) def execute_python_code(code: str) -> str: """ Executes a given Python code snippet in a subprocess and returns its output. Args: code (str): The Python code to execute as a string. Returns: str: The standard output of the executed code if successful, or an error message containing the standard error output if the execution fails. Raises: None: Any exceptions during execution are caught and handled internally. """ try: process = subprocess.run( ["python3", "-c", code], text=True, capture_output=True, check=True ) return process.stdout except subprocess.CalledProcessError as e: return f"Error: {e.stderr}"