Nova / src /inference /tool_engine.py
kings1's picture
Upload folder using huggingface_hub
3bc5889 verified
Raw History Blame Contribute Delete
2.77 kB
"""
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, []