98 lines
2.4 KiB
Python
98 lines
2.4 KiB
Python
"""Code execution tools - exception handling in decorator"""
|
|
import io
|
|
from contextlib import redirect_stdout
|
|
from typing import Dict, Any
|
|
|
|
from luxx.tools.factory import tool
|
|
|
|
|
|
@tool(
|
|
name="python_execute",
|
|
description="Execute Python code and return the result",
|
|
parameters={
|
|
"type": "object",
|
|
"properties": {
|
|
"code": {
|
|
"type": "string",
|
|
"description": "Python code to execute"
|
|
},
|
|
"timeout": {
|
|
"type": "integer",
|
|
"description": "Execution timeout in seconds",
|
|
"default": 30
|
|
}
|
|
},
|
|
"required": ["code"]
|
|
},
|
|
required_params=["code"],
|
|
category="code"
|
|
)
|
|
def python_execute(arguments: Dict[str, Any]):
|
|
"""
|
|
Execute Python code
|
|
|
|
Note: This is a simplified executor, production environments should use safer isolated environments
|
|
such as: Docker containers, Pyodide, etc.
|
|
|
|
Returns:
|
|
{"output": str, "variables": dict}
|
|
"""
|
|
code = arguments.get("code", "")
|
|
|
|
# Create execution environment
|
|
namespace = {
|
|
"__builtins__": __builtins__
|
|
}
|
|
|
|
# Compile and execute code
|
|
compiled = compile(code, "<string>", "exec")
|
|
|
|
# Capture output
|
|
output = io.StringIO()
|
|
|
|
with redirect_stdout(output):
|
|
exec(compiled, namespace)
|
|
|
|
result = output.getvalue()
|
|
|
|
# Extract variables
|
|
result_vars = {k: v for k, v in namespace.items()
|
|
if not k.startswith("_") and k != "__builtins__"}
|
|
|
|
return {
|
|
"output": result,
|
|
"variables": {k: repr(v) for k, v in result_vars.items()}
|
|
}
|
|
|
|
|
|
@tool(
|
|
name="python_eval",
|
|
description="Evaluate a Python expression and return the result",
|
|
parameters={
|
|
"type": "object",
|
|
"properties": {
|
|
"expression": {
|
|
"type": "string",
|
|
"description": "Python expression to evaluate"
|
|
}
|
|
},
|
|
"required": ["expression"]
|
|
},
|
|
required_params=["expression"],
|
|
category="code"
|
|
)
|
|
def python_eval(arguments: Dict[str, Any]):
|
|
"""
|
|
Evaluate Python expression
|
|
|
|
Returns:
|
|
{"result": str, "type": str}
|
|
"""
|
|
expression = arguments.get("expression", "")
|
|
|
|
result = eval(expression)
|
|
return {
|
|
"result": repr(result),
|
|
"type": type(result).__name__
|
|
}
|