123 lines
3.1 KiB
Python
123 lines
3.1 KiB
Python
"""代码执行工具"""
|
||
import json
|
||
import traceback
|
||
import ast
|
||
from typing import Dict, Any
|
||
|
||
from alcor.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"]
|
||
},
|
||
category="code"
|
||
)
|
||
def python_execute(arguments: Dict[str, Any]) -> Dict[str, Any]:
|
||
"""
|
||
执行Python代码
|
||
|
||
注意:这是一个简化的执行器,生产环境应使用更安全的隔离环境
|
||
如:Docker容器、Pyodide等
|
||
"""
|
||
code = arguments.get("code", "")
|
||
timeout = arguments.get("timeout", 30)
|
||
|
||
if not code:
|
||
return {"success": False, "error": "Code is required"}
|
||
|
||
# 创建执行环境(允许大多数操作)
|
||
namespace = {
|
||
"__builtins__": __builtins__
|
||
}
|
||
|
||
try:
|
||
# 编译并执行代码
|
||
compiled = compile(code, "<string>", "exec")
|
||
|
||
# 捕获输出
|
||
import io
|
||
from contextlib import redirect_stdout
|
||
|
||
output = io.StringIO()
|
||
|
||
with redirect_stdout(output):
|
||
exec(compiled, namespace)
|
||
|
||
result = output.getvalue()
|
||
|
||
# 尝试提取变量
|
||
result_vars = {k: v for k, v in namespace.items()
|
||
if not k.startswith("_") and k != "__builtins__"}
|
||
|
||
return {
|
||
"success": True,
|
||
"data": {
|
||
"output": result,
|
||
"variables": {k: repr(v) for k, v in result_vars.items()},
|
||
"error": None
|
||
}
|
||
}
|
||
except SyntaxError as e:
|
||
return {
|
||
"success": False,
|
||
"error": f"Syntax error: {e}"
|
||
}
|
||
except Exception as e:
|
||
return {
|
||
"success": False,
|
||
"error": f"Runtime error: {type(e).__name__}: {str(e)}"
|
||
}
|
||
|
||
|
||
@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"]
|
||
},
|
||
category="code"
|
||
)
|
||
def python_eval(arguments: Dict[str, Any]) -> Dict[str, Any]:
|
||
"""评估Python表达式"""
|
||
expression = arguments.get("expression", "")
|
||
|
||
if not expression:
|
||
return {"success": False, "error": "Expression is required"}
|
||
|
||
try:
|
||
result = eval(expression)
|
||
return {
|
||
"success": True,
|
||
"data": {
|
||
"result": repr(result),
|
||
"type": type(result).__name__
|
||
}
|
||
}
|
||
except Exception as e:
|
||
return {
|
||
"success": False,
|
||
"error": f"Evaluation error: {str(e)}"
|
||
}
|