DF_Final_Assignment_Template / tools /execute_python_code_from_file.py
dmfelder's picture
Update tools/execute_python_code_from_file.py
83d8da8 verified
Raw History Blame Contribute Delete
1.3 kB
from langchain_core.tools import tool, ToolException
from loguru import logger
from rizaio import Riza
from tools.load_file import load_file
@tool("execute_python_code_from_file_tool", parse_docstring=True)
def execute_python_code_from_file(path_or_url: str) -> str:
"""
Executes a Python script provided as a file path or URL.
Args:
path_or_url (str): A local file path or URL pointing to a Python script.
Returns:
str: The standard output from executing the Python code.
"""
logger.info(f"execute_python_code_from_file with param: {path_or_url}")
code = load_file(path_or_url).read().decode("utf-8")
logger.debug(f"Python code:\n{code}")
client = Riza()
output = client.command.exec(
language="python",
code=code,
)
if output.exit_code > 0:
raise ToolException(
f"Riza code execution returned a non-zero exit code. "
f"The output captured from stderr was:\n{output.stderr}"
)
return output.stdout
if __name__ == "__main__":
print(execute_python_code_from_file.invoke("../data/f918266a-b3e0-4914-865d-4faa564f1aef.py"))
print(execute_python_code_from_file.invoke("https://agents-course-unit4-scoring.hf.space/files/f918266a-b3e0-4914-865d-4faa564f1aef"))