|
|
|
|
|
|
|
|
import io
|
|
|
import contextlib
|
|
|
import json
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class ExecutorAgent:
|
|
|
def __init__(self, openai_api_key: str = None):
|
|
|
print("ExecutorAgent initialized.")
|
|
|
self.openai_api_key = openai_api_key
|
|
|
|
|
|
def execute_code(self, python_code: str) -> dict:
|
|
|
print(f"ExecutorAgent received code for execution:\n{python_code}")
|
|
|
|
|
|
|
|
|
|
|
|
import sys
|
|
|
import os
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
try:
|
|
|
|
|
|
import tools.agent_tools as agent_tools_module
|
|
|
except ImportError as e:
|
|
|
return {
|
|
|
"execution_output": f"ExecutorAgent Error: Could not import agent_tools module. Ensure it's in tools/ and __init__.py might be needed in tools/. Error: {e}",
|
|
|
"execution_status": "ERROR: ImportFailure"
|
|
|
}
|
|
|
except Exception as e:
|
|
|
return {
|
|
|
"execution_output": f"ExecutorAgent Error: Unexpected error during tools import. Error: {e}",
|
|
|
"execution_status": "ERROR: ImportFailure"
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
restricted_globals = {
|
|
|
"__builtins__": __builtins__,
|
|
|
"tools": agent_tools_module,
|
|
|
"json": json,
|
|
|
"api_key": self.openai_api_key
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
import builtins
|
|
|
builtins.__agent_usage_collector__ = []
|
|
|
|
|
|
captured_output = io.StringIO()
|
|
|
try:
|
|
|
with contextlib.redirect_stdout(captured_output):
|
|
|
exec(python_code, restricted_globals)
|
|
|
output_str = captured_output.getvalue()
|
|
|
|
|
|
|
|
|
usage_list = builtins.__agent_usage_collector__
|
|
|
aggregated_usage = {
|
|
|
'prompt_tokens': sum(u.get('prompt_tokens', 0) for u in usage_list),
|
|
|
'completion_tokens': sum(u.get('completion_tokens', 0) for u in usage_list),
|
|
|
'total_tokens': sum(u.get('total_tokens', 0) for u in usage_list)
|
|
|
}
|
|
|
|
|
|
return {
|
|
|
"execution_output": output_str.strip() if output_str else "(No output printed by code)",
|
|
|
"execution_status": "SUCCESS",
|
|
|
"usage": aggregated_usage
|
|
|
}
|
|
|
except Exception as e:
|
|
|
error_details = f"{type(e).__name__}: {str(e)}"
|
|
|
|
|
|
|
|
|
|
|
|
usage_list = builtins.__agent_usage_collector__
|
|
|
aggregated_usage = {
|
|
|
'prompt_tokens': sum(u.get('prompt_tokens', 0) for u in usage_list),
|
|
|
'completion_tokens': sum(u.get('completion_tokens', 0) for u in usage_list),
|
|
|
'total_tokens': sum(u.get('total_tokens', 0) for u in usage_list)
|
|
|
}
|
|
|
|
|
|
return {
|
|
|
"execution_output": f"Execution Error!\n{error_details}",
|
|
|
"execution_status": f"ERROR: {type(e).__name__}",
|
|
|
"usage": aggregated_usage
|
|
|
}
|
|
|
|
|
|
if __name__ == '__main__':
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
print("ExecutorAgent should be orchestrated by the ManagerAgent.") |