File size: 1,800 Bytes
976c5ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
102a9b5
976c5ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from smolagents._function_type_hints_utils import FunctionSchema

@tool(schema=FunctionSchema(
    name="execute_code",
    description="Executes Python code and returns the result as a string.",
    parameters=[
        {
            "name": "code_string",
            "type": "string",
            "description": "Python code to execute."
        },
        {
            "name": "data",
            "type": "object",
            "description": "The pandas DataFrame to use.",
            "properties":{},
        }
    ],
    returns={
        "type":"string",
         "description": "The result of executing the code."
    }
))
def execute_code(code_string: str, data: pd.DataFrame) -> str:
  """Executes python code and returns results as a string.

  Args:
      code_string (str): Python code to execute.
      data (pd.DataFrame): The dataframe to use in the code
  Returns:
      str: The result of executing the code or an error message
   """
  try:
        local_vars = {"data": data, "pd": pd, "np": np, "plt": plt, "sns": sns}
        exec(code_string, local_vars)

        if "result" in local_vars:
            if isinstance(local_vars["result"], (pd.DataFrame, pd.Series)):
                return local_vars["result"].to_string()
            elif isinstance(local_vars["result"], plt.Figure):
                buf = io.BytesIO()
                local_vars["result"].savefig(buf, format="png")
                plt.close(local_vars["result"])
                return f"data:image/png;base64,{base64.b64encode(buf.getvalue()).decode()}"
            else:
                return str(local_vars["result"])
        else:
            return "Code executed successfully, but no variable called 'result' was assigned."

  except Exception as e:
        return f"Error executing code: {str(e)}"