Create execute_python_code_from_file.py
Browse files
tools/execute_python_code_from_file.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from langchain_core.tools import tool, ToolException
|
| 2 |
+
from loguru import logger
|
| 3 |
+
from rizaio import Riza
|
| 4 |
+
|
| 5 |
+
from tools.load_file import load_file
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
@tool("execute_python_code_from_file_tool", parse_docstring=True)
|
| 9 |
+
def execute_python_code_from_file(path_or_url: str) -> str:
|
| 10 |
+
"""
|
| 11 |
+
Executes a given Python code snippet.
|
| 12 |
+
Args:
|
| 13 |
+
path_or_url (str): A string containing the Python code to execute.
|
| 14 |
+
Returns:
|
| 15 |
+
str: The standard output resulting from the execution of the code.
|
| 16 |
+
"""
|
| 17 |
+
logger.info(f"execute_python_code_from_file with param: {path_or_url}")
|
| 18 |
+
code = load_file(path_or_url).read().decode("utf-8")
|
| 19 |
+
logger.debug(f"Python code:\n{code}")
|
| 20 |
+
client = Riza()
|
| 21 |
+
output = client.command.exec(
|
| 22 |
+
language="python",
|
| 23 |
+
code=code,
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
if output.exit_code > 0:
|
| 27 |
+
raise ToolException(
|
| 28 |
+
f"Riza code execution returned a non-zero exit code. "
|
| 29 |
+
f"The output captured from stderr was:\n{output.stderr}"
|
| 30 |
+
)
|
| 31 |
+
return output.stdout
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
if __name__ == "__main__":
|
| 35 |
+
print(execute_python_code_from_file.invoke("../data/f918266a-b3e0-4914-865d-4faa564f1aef.py"))
|
| 36 |
+
print(execute_python_code_from_file.invoke("https://agents-course-unit4-scoring.hf.space/files/f918266a-b3e0-4914-865d-4faa564f1aef"))
|