execute_code
Run Python code for financial analysis and calculations to support research workflows, with results output via print statements.
Instructions
Execute python code can be used in scenarios such as analysis or calculation, and the final result can be printed using the print function.
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| code | Yes | code to be executed |
Implementation Reference
- The async_execute method is the main handler for the execute_code tool. It retrieves the 'code' from input_dict, executes it via exec_code, and sets the output.async def async_execute(self): """Execute the provided Python code asynchronously. The method reads the ``code`` field from ``input_dict``, delegates execution to :func:`exec_code`, and stores the textual result in the operation output. """ self.set_output(exec_code(self.input_dict["code"]))
- The build_tool_call method defines the input schema for the execute_code tool, requiring a 'code' string.def build_tool_call(self) -> ToolCall: """Build the tool call schema used by FlowLLM. Returns: ToolCall: The tool call definition including description and input schema. """ return ToolCall( **{ "description": self.get_prompt("tool_description"), "input_schema": { "code": { "type": "string", "description": "code to be executed", "required": True, }, }, }, )
- finance_mcp/core/gallery/execute_code_op.py:17-18 (registration)The ExecuteCodeOp class is registered as a tool operation using the @C.register_op() decorator.@C.register_op() class ExecuteCodeOp(BaseAsyncToolOp):
- finance_mcp/core/gallery/__init__.py:9-14 (registration)The gallery __init__.py exports ExecuteCodeOp, making it available for import and use as the execute_code tool.from .execute_code_op import ExecuteCodeOp from .execute_shell_op import ExecuteShellOp __all__ = [ "ExecuteCodeOp", "ExecuteShellOp",
- The exec_code function provides the actual code execution logic, capturing stdout or returning exception messages.def exec_code(code: str) -> str: """Execute arbitrary Python code and capture its printed output. The code is executed in the current global context and any text written to ``stdout`` is captured and returned as a string. If an exception occurs, its string representation is returned instead. Args: code: Python source code to execute. Returns: Captured ``stdout`` output, or the exception message if execution fails. """ try: redirected_output = StringIO() with contextlib.redirect_stdout(redirected_output): exec(code) return redirected_output.getvalue() except Exception as e: # noqa: BLE001 return str(e) except BaseException as e: return str(e)