Tools / Modules /Code_Interpreter.py
Nymbo's picture
Create Modules/Code_Interpreter.py
5f048ad verified
raw
history blame
1.84 kB
from __future__ import annotations
import sys
from io import StringIO
from typing import Annotated
import gradio as gr
from app import _log_call_end, _log_call_start, _truncate_for_log
def Code_Interpreter(code: Annotated[str, "Python source code to run; stdout is captured and returned."]) -> str:
_log_call_start("Code_Interpreter", code=_truncate_for_log(code or "", 300))
if code is None:
result = "No code provided."
_log_call_end("Code_Interpreter", result)
return result
old_stdout = sys.stdout
redirected_output = sys.stdout = StringIO()
try:
exec(code)
result = redirected_output.getvalue()
except Exception as exc: # pylint: disable=broad-except
result = str(exc)
finally:
sys.stdout = old_stdout
_log_call_end("Code_Interpreter", _truncate_for_log(result))
return result
def build_interface() -> gr.Interface:
return gr.Interface(
fn=Code_Interpreter,
inputs=gr.Code(label="Python Code", language="python"),
outputs=gr.Textbox(label="Output", lines=5, max_lines=20),
title="Code Interpreter",
description="<div style=\"text-align:center\">Execute Python code and see the output.</div>",
api_description=(
"Execute arbitrary Python code and return captured stdout or an error message. "
"Supports any valid Python code including imports, variables, functions, loops, and calculations. "
"Examples: 'print(2+2)', 'import math; print(math.sqrt(16))', 'for i in range(3): print(i)'. "
"Parameters: code (str - Python source code to execute). "
"Returns: Combined stdout output or exception text if execution fails."
),
flagging_mode="never",
)
__all__ = ["Code_Interpreter", "build_interface"]