sail / sail_scripts /agent /tool_executor.py
muterornament's picture
Industrialize: Backup sovereign training pipeline
e5b79b7 verified
Raw
History Blame Contribute Delete
2.36 kB
import json
import subprocess
import sys
import io
import contextlib
class ToolExecutor:
"""
Executes tool calls generated by the AI model.
Supported tool formats: [TOOL_CALL] name [TOOL_ARG] args
"""
def __init__(self):
self.available_tools = {
"calculator": self.calculator,
"python_exec": self.python_exec,
"system_info": self.system_info
}
def execute(self, tool_name, tool_args):
"""Dispatches to the correct tool function."""
if tool_name not in self.available_tools:
return f"Error: Tool '{tool_name}' not found."
try:
return self.available_tools[tool_name](tool_args)
except Exception as e:
return f"Error executing tool '{tool_name}': {str(e)}"
def calculator(self, expression):
"""Safely evaluates a math expression."""
# Note: In production use a safer math parser
return str(eval(expression, {"__builtins__": None}, {}))
def python_exec(self, code):
"""Executes Python code and captures stdout."""
f = io.StringIO()
with contextlib.redirect_stdout(f):
try:
exec(code)
return f.getvalue().strip()
except Exception as e:
return f"Traceback: {str(e)}"
def system_info(self, _):
"""Returns basic system metadata."""
import platform
return f"OS: {platform.system()} | Machine: {platform.machine()} | Python: {sys.version.split()[0]}"
def parse_and_execute_tools(text):
"""
Helper to find [TOOL_CALL] in generated text and run them.
Returns the update string with [TOOL_RESULT] appended.
"""
executor = ToolExecutor()
if "[TOOL_CALL]" not in text:
return None
# Simple regex-based parsing
import re
pattern = r"\[TOOL_CALL\]\s*(\w+)\s*\[TOOL_ARG\]\s*(.*?)(?=\[|$)"
match = re.search(pattern, text)
if match:
tool_name = match.group(1).strip()
tool_args = match.group(2).strip()
print(f"Executing Agent Tool: {tool_name}({tool_args})")
result = executor.execute(tool_name, tool_args)
return f"[TOOL_RESULT] {result}"
return None