Update app.py
Browse files
app.py
CHANGED
@@ -1,11 +1,51 @@
|
|
1 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
2 |
def execute_code(code_string: str, data: pd.DataFrame) -> str:
|
3 |
-
|
4 |
-
|
5 |
-
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from smolagents._function_type_hints_utils import FunctionSchema
|
2 |
+
|
3 |
+
@tool(schema=FunctionSchema(
|
4 |
+
name="execute_code",
|
5 |
+
description="Executes Python code and returns the result as a string.",
|
6 |
+
parameters=[
|
7 |
+
{
|
8 |
+
"name": "code_string",
|
9 |
+
"type": "string",
|
10 |
+
"description": "Python code to execute."
|
11 |
+
},
|
12 |
+
{
|
13 |
+
"name": "data",
|
14 |
+
"type": "object",
|
15 |
+
"description": "The pandas DataFrame to use.",
|
16 |
+
"properties":{},
|
17 |
+
}
|
18 |
+
],
|
19 |
+
returns={
|
20 |
+
"type":"string",
|
21 |
+
"description": "The result of executing the code."
|
22 |
+
}
|
23 |
+
))
|
24 |
def execute_code(code_string: str, data: pd.DataFrame) -> str:
|
25 |
+
"""Executes python code and returns results as a string.
|
26 |
+
|
27 |
+
Args:
|
28 |
+
code_string (str): Python code to execute.
|
29 |
+
data (pd.DataFrame): The dataframe to use in the code
|
30 |
+
Returns:
|
31 |
+
str: The result of executing the code or an error message
|
32 |
+
"""
|
33 |
+
try:
|
34 |
+
local_vars = {"data": data, "pd": pd, "np": np, "plt": plt, "sns": sns}
|
35 |
+
exec(code_string, local_vars)
|
36 |
+
|
37 |
+
if "result" in local_vars:
|
38 |
+
if isinstance(local_vars["result"], (pd.DataFrame, pd.Series)):
|
39 |
+
return local_vars["result"].to_string()
|
40 |
+
elif isinstance(local_vars["result"], plt.Figure):
|
41 |
+
buf = io.BytesIO()
|
42 |
+
local_vars["result"].savefig(buf, format="png")
|
43 |
+
plt.close(local_vars["result"])
|
44 |
+
return f"data:image/png;base64,{base64.b64encode(buf.getvalue()).decode()}"
|
45 |
+
else:
|
46 |
+
return str(local_vars["result"])
|
47 |
+
else:
|
48 |
+
return "Code executed successfully, but no variable called 'result' was assigned."
|
49 |
+
|
50 |
+
except Exception as e:
|
51 |
+
return f"Error executing code: {str(e)}"
|