| 1 | from ..tool import Tool |
| 2 | |
| 3 | class CodeInterpreter: |
| 4 | def __init__(self, timeout=300): |
| 5 | self.globals = {} |
| 6 | self.locals = {} |
| 7 | self.timeout = timeout |
| 8 | |
| 9 | def execute_code(self, code): |
| 10 | try: |
| 11 | # Wrap the code in an eval() call to return the result |
| 12 | wrapped_code = f"__result__ = eval({repr(code)}, globals(), locals())" |
| 13 | exec(wrapped_code, self.globals, self.locals) |
| 14 | return self.locals.get('__result__', None) |
| 15 | except Exception as e: |
| 16 | try: |
| 17 | # If eval fails, attempt to exec the code without returning a result |
| 18 | exec(code, self.globals, self.locals) |
| 19 | return "Code executed successfully." |
| 20 | except Exception as e: |
| 21 | return f"Error: {str(e)}" |
| 22 | |
| 23 | def reset_session(self): |
| 24 | self.globals = {} |
| 25 | self.locals = {} |
| 26 | |
| 27 | def build_tool(config) -> Tool: |
| 28 | tool = Tool( |