File size: 2,771 Bytes
23ea6bd
 
 
 
 
3bc5889
23ea6bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3bc5889
23ea6bd
3bc5889
 
23ea6bd
3bc5889
 
 
 
23ea6bd
 
 
 
3bc5889
 
 
23ea6bd
3bc5889
 
 
 
 
 
 
23ea6bd
3bc5889
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
74
75
76
77
78
79
80
81
"""
Nova 1.0 — Autonomous Code Execution & Tool-Use Engine (AGI Capability)
Allows Nova 1.0 to execute Python code blocks, inspect results, and self-correct before responding.
"""

from typing import List, Tuple
import sys
import io
import contextlib
import traceback


class PythonToolEngine:
    def __init__(self, timeout_sec: int = 5):
        self.timeout_sec = timeout_sec

    def execute_python_code(self, code_str: str) -> str:
        """
        Executes python code string in an isolated execution scope and returns stdout or traceback.
        """
        clean_code = code_str.strip()
        if clean_code.startswith("```python"):
            clean_code = clean_code[9:]
        if clean_code.startswith("```"):
            clean_code = clean_code[3:]
        if clean_code.endswith("```"):
            clean_code = clean_code[:-3]

        stdout_buffer = io.StringIO()
        stderr_buffer = io.StringIO()

        exec_globals = {}
        exec_locals = {}

        try:
            with contextlib.redirect_stdout(stdout_buffer), contextlib.redirect_stderr(stderr_buffer):
                exec(clean_code, exec_globals, exec_locals)

            stdout_out = stdout_buffer.getvalue().strip()
            stderr_out = stderr_buffer.getvalue().strip()

            if stdout_out and stderr_out:
                return f"[Stdout]:\n{stdout_out}\n[Stderr]:\n{stderr_out}"
            elif stdout_out:
                return stdout_out
            elif stderr_out:
                return f"[Stderr]: {stderr_out}"
            else:
                return "[Code executed successfully with no stdout output]"

        except Exception as e:
            return f"[Execution Error]: {type(e).__name__}: {str(e)}"


def parse_and_execute_tools(text_response: str) -> Tuple[str, List[str]]:
    """
    Parses <python>...</python> or ```python...``` code blocks from model response,
    executes them, and returns (clean_text, tool_results_list).
    """
    engine = PythonToolEngine()
    results = []

    # Case 1: <python> tags
    if "<python>" in text_response and "</python>" in text_response:
        start_idx = text_response.find("<python>") + 8
        end_idx = text_response.find("</python>")
        code_snippet = text_response[start_idx:end_idx]
        res = engine.execute_python_code(code_snippet)
        results.append(res)
        return text_response, results

    # Case 2: Markdown python blocks
    if "```python" in text_response and "```" in text_response.split("```python", 1)[1]:
        parts = text_response.split("```python", 1)
        code_part = parts[1].split("```", 1)[0]
        res = engine.execute_python_code(code_part)
        results.append(res)
        return text_response, results

    return text_response, []