|
|
import sys |
|
|
from io import StringIO |
|
|
|
|
|
|
|
|
_persistent_namespace = {} |
|
|
|
|
|
def run_python_repl(command: str) -> str: |
|
|
"""Executes the provided Python command in a persistent environment and returns the output. |
|
|
Variables defined in one execution will be available in subsequent executions. |
|
|
""" |
|
|
|
|
|
def execute_in_repl(command: str) -> str: |
|
|
"""Helper function to execute the command in the persistent environment.""" |
|
|
old_stdout = sys.stdout |
|
|
sys.stdout = mystdout = StringIO() |
|
|
|
|
|
|
|
|
global _persistent_namespace |
|
|
|
|
|
try: |
|
|
|
|
|
exec(command, _persistent_namespace) |
|
|
output = mystdout.getvalue() |
|
|
except Exception as e: |
|
|
output = f"Error: {str(e)}" |
|
|
finally: |
|
|
sys.stdout = old_stdout |
|
|
return output |
|
|
|
|
|
command = command.strip("```").strip() |
|
|
return execute_in_repl(command) |
|
|
|
|
|
|
|
|
def read_function_source_code(function_name: str) -> str: |
|
|
"""Read the source code of a function from any module path. |
|
|
|
|
|
Parameters |
|
|
---------- |
|
|
function_name (str): Fully qualified function name (e.g., 'bioagentos.tool.support_tools.write_python_code') |
|
|
|
|
|
Returns |
|
|
------- |
|
|
str: The source code of the function |
|
|
|
|
|
""" |
|
|
import importlib |
|
|
import inspect |
|
|
|
|
|
|
|
|
parts = function_name.split(".") |
|
|
module_path = ".".join(parts[:-1]) |
|
|
func_name = parts[-1] |
|
|
|
|
|
try: |
|
|
|
|
|
module = importlib.import_module(module_path) |
|
|
|
|
|
|
|
|
function = getattr(module, func_name) |
|
|
|
|
|
|
|
|
source_code = inspect.getsource(function) |
|
|
|
|
|
return source_code |
|
|
except (ImportError, AttributeError) as e: |
|
|
return f"Error: Could not find function '{function_name}'. Details: {str(e)}" |