Spaces:
Sleeping
Sleeping
File size: 1,668 Bytes
df532e4 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
import subprocess
from langchain_core.tools import tool
from dotenv import load_dotenv
import os
load_dotenv()
def strip_code_fences(code: str) -> str:
code = code.strip()
# Remove ```python ... ``` or ``` ... ```
if code.startswith("```"):
# remove first line (```python or ```)
code = code.split("\n", 1)[1]
if code.endswith("```"):
code = code.rsplit("\n", 1)[0]
return code.strip()
@tool
def run_code(code: str) -> dict:
"""
Executes a Python code
This tool:
1. Takes in python code as input
3. Writes code into a temporary .py file
4. Executes the file
5. Returns its output
Parameters
----------
code : str
Python source code to execute.
Returns
-------
dict
{
"stdout": <program output>,
"stderr": <errors if any>,
"return_code": <exit code>
}
"""
try:
filename = "runner.py"
os.makedirs("LLMFiles", exist_ok=True)
with open(os.path.join("LLMFiles", filename), "w") as f:
f.write(code)
proc = subprocess.Popen(
["uv", "run", filename],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
cwd="LLMFiles"
)
stdout, stderr = proc.communicate()
# --- Step 4: Return everything ---
return {
"stdout": stdout,
"stderr": stderr,
"return_code": proc.returncode
}
except Exception as e:
return {
"stdout": "",
"stderr": str(e),
"return_code": -1
} |