File size: 2,358 Bytes
e5b79b7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
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