pull/709/head
harshalmore31 4 months ago
parent 5cf3219e8e
commit f23321487f

@ -39,57 +39,10 @@ model = OpenAIChat(
PROMPT_JSON_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "agent_prompts.json") PROMPT_JSON_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "agent_prompts.json")
logger.info(f"Loading prompts from: {PROMPT_JSON_PATH}") logger.info(f"Loading prompts from: {PROMPT_JSON_PATH}")
# Global log storage
execution_logs = []
def log_event(level: str, message: str, metadata: Optional[Dict] = None):
timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
log_entry = {
"timestamp": timestamp,
"level": level,
"message": message,
"metadata": metadata or {}
}
execution_logs.append(log_entry)
log_func = getattr(logger, level.lower(), logger.info)
log_func(message)
def get_logs(router: Optional['SwarmRouter'] = None) -> List[str]:
formatted_logs = []
for log in execution_logs:
metadata_str = ""
if log["metadata"]:
metadata_str = f" | Metadata: {json.dumps(log['metadata'])}"
formatted_logs.append(
f"[{log['timestamp']}] {log['level'].upper()}: {log['message']}{metadata_str}"
)
# Add router logs if available
if router and hasattr(router, 'get_logs'):
try:
router_logs = router.get_logs()
formatted_logs.extend([
f"[{log.timestamp}] ROUTER - {log.level}: {log.message}"
for log in router_logs
])
except Exception as e:
formatted_logs.append(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] ERROR: Failed to get router logs: {str(e)}")
return formatted_logs
def clear_logs():
execution_logs.clear()
def load_prompts_from_json() -> Dict[str, str]: def load_prompts_from_json() -> Dict[str, str]:
try: try:
if not os.path.exists(PROMPT_JSON_PATH): if not os.path.exists(PROMPT_JSON_PATH):
error_msg = f"Prompts file not found at: {PROMPT_JSON_PATH}"
log_event("error", error_msg)
# Load default prompts # Load default prompts
return { return {
"agent.data_extractor": "You are a data extraction agent...", "agent.data_extractor": "You are a data extraction agent...",
@ -100,27 +53,31 @@ def load_prompts_from_json() -> Dict[str, str]:
with open(PROMPT_JSON_PATH, 'r', encoding='utf-8') as f: with open(PROMPT_JSON_PATH, 'r', encoding='utf-8') as f:
try: try:
data = json.load(f) data = json.load(f)
except json.JSONDecodeError as e: except json.JSONDecodeError:
error_msg = f"Invalid JSON in prompts file: {str(e)}" # Load default prompts
log_event("error", error_msg) return {
raise "agent.data_extractor": "You are a data extraction agent...",
"agent.summarizer": "You are a summarization agent...",
"agent.onboarding_agent": "You are an onboarding agent..."
}
if not isinstance(data, dict): if not isinstance(data, dict):
error_msg = "Prompts file must contain a JSON object" # Load default prompts
log_event("error", error_msg) return {
raise ValueError(error_msg) "agent.data_extractor": "You are a data extraction agent...",
"agent.summarizer": "You are a summarization agent...",
"agent.onboarding_agent": "You are an onboarding agent..."
}
prompts = {} prompts = {}
for agent_name, details in data.items(): for agent_name, details in data.items():
if not isinstance(details, dict) or "system_prompt" not in details: if not isinstance(details, dict) or "system_prompt" not in details:
log_event("warning", f"Skipping invalid agent config: {agent_name}")
continue continue
prompts[f"agent.{agent_name}"] = details["system_prompt"] prompts[f"agent.{agent_name}"] = details["system_prompt"]
if not prompts: if not prompts:
error_msg = "No valid prompts found in prompts file"
log_event("error", error_msg)
# Load default prompts # Load default prompts
return { return {
"agent.data_extractor": "You are a data extraction agent...", "agent.data_extractor": "You are a data extraction agent...",
@ -128,12 +85,9 @@ def load_prompts_from_json() -> Dict[str, str]:
"agent.onboarding_agent": "You are an onboarding agent..." "agent.onboarding_agent": "You are an onboarding agent..."
} }
log_event("info", f"Successfully loaded {len(prompts)} prompts from JSON")
return prompts return prompts
except Exception as e: except Exception:
error_msg = f"Error loading prompts: {str(e)}"
log_event("error", error_msg)
# Load default prompts # Load default prompts
return { return {
"agent.data_extractor": "You are a data extraction agent...", "agent.data_extractor": "You are a data extraction agent...",
@ -188,18 +142,12 @@ async def execute_task(task: str, max_loops: int, dynamic_temp: float,
""" """
Enhanced task execution with comprehensive error handling and raw result return. Enhanced task execution with comprehensive error handling and raw result return.
""" """
start_time = time.time()
log_event("info", f"Starting task execution: {task}")
try: try:
# Initialize agents # Initialize agents
try: try:
agents = initialize_agents(dynamic_temp, agent_keys) agents = initialize_agents(dynamic_temp, agent_keys)
log_event("info", f"Successfully initialized {len(agents)} agents")
except Exception as e: except Exception as e:
error_msg = f"Agent initialization error: {str(e)}" return None, None, str(e)
log_event("error", error_msg)
return None, None, error_msg
# Swarm-specific configurations # Swarm-specific configurations
router_kwargs = { router_kwargs = {
@ -239,9 +187,7 @@ async def execute_task(task: str, max_loops: int, dynamic_temp: float,
pass pass
os.remove(output_path) # Clean up the test file os.remove(output_path) # Clean up the test file
except OSError as e: except OSError as e:
error_msg = f"Invalid output path: {str(e)}" return None, None, str(e)
log_event("error", error_msg)
return None, None, error_msg
router_kwargs["output_path"] = output_path router_kwargs["output_path"] = output_path
# Create and execute SwarmRouter # Create and execute SwarmRouter
@ -261,30 +207,23 @@ async def execute_task(task: str, max_loops: int, dynamic_temp: float,
timeout=timeout timeout=timeout
) )
if swarm_type == "SpreadSheetSwarm": if swarm_type == "SpreadSheetSwarm":
# Verify the output file was created # Verify the output file was created
if not os.path.exists(output_path): if not os.path.exists(output_path):
error_msg = "Output file was not created" return None, None, "Output file was not created"
log_event("error", error_msg)
return None, None, error_msg
return output_path, router, "" return output_path, router, ""
return result, router, "" return result, router, ""
except asyncio.TimeoutError: except asyncio.TimeoutError:
error_msg = f"Task execution timed out after {timeout} seconds" return None, None, f"Task execution timed out after {timeout} seconds"
log_event("error", error_msg)
return None, None, error_msg
except Exception as e: except Exception as e:
error_msg = f"Task execution error: {str(e)}" return None, None, str(e)
log_event("error", error_msg)
return None, None, error_msg
except Exception as e: except Exception as e:
error_msg = f"Unexpected error in task execution: {str(e)}" return None, None, str(e)
log_event("error", error_msg)
return None, None, error_msg
class UI: class UI:
@ -538,10 +477,8 @@ def create_app():
def update_flow_agents(agent_keys): def update_flow_agents(agent_keys):
"""Update flow agents based on selected agent prompts.""" """Update flow agents based on selected agent prompts."""
if not agent_keys: if not agent_keys:
log_event("warning", "No agents selected for flow configuration")
return [], "No agents selected" return [], "No agents selected"
agent_names = [key.split('.')[-1] for key in agent_keys] agent_names = [key.split('.')[-1] for key in agent_keys]
log_event("info", f"Updated flow agents with {len(agent_names)} agents")
return agent_names, "Select agents in execution order" return agent_names, "Select agents in execution order"
def update_flow_preview(selected_flow_agents): def update_flow_preview(selected_flow_agents):
@ -549,7 +486,6 @@ def create_app():
if not selected_flow_agents: if not selected_flow_agents:
return "Flow will be shown here..." return "Flow will be shown here..."
flow = " -> ".join(selected_flow_agents) flow = " -> ".join(selected_flow_agents)
log_event("info", f"Updated flow preview: {flow}")
return flow return flow
def update_ui_for_swarm_type(swarm_type): def update_ui_for_swarm_type(swarm_type):
@ -559,7 +495,6 @@ def create_app():
is_spreadsheet = swarm_type == "SpreadSheetSwarm" is_spreadsheet = swarm_type == "SpreadSheetSwarm"
max_loops = 5 if is_mixture or is_spreadsheet else 10 max_loops = 5 if is_mixture or is_spreadsheet else 10
log_event("info", f"Swarm type changed to {swarm_type}, max loops set to {max_loops}")
# Return visibility state for flow configuration and max loops update # Return visibility state for flow configuration and max loops update
return ( return (
@ -579,7 +514,6 @@ def create_app():
yield "Please select at least one agent.", "Error: No agents selected" yield "Please select at least one agent.", "Error: No agents selected"
return return
log_event("info", f"Starting task with agents: {agent_prompt_selector}")
# Update status # Update status
yield "Processing...", "Running task..." yield "Processing...", "Running task..."
@ -631,9 +565,7 @@ def create_app():
yield "\n".join(output_lines), "Completed" yield "\n".join(output_lines), "Completed"
except Exception as e: except Exception as e:
error_msg = f"Error: {str(e)}" yield f"Error: {str(e)}", "Error occurred"
log_event("error", error_msg)
yield error_msg, "Error occurred"
# Connect the update functions # Connect the update functions
agent_selector.change( agent_selector.change(
@ -659,7 +591,6 @@ def create_app():
# Connect cancel button to interrupt processing # Connect cancel button to interrupt processing
def cancel_task(): def cancel_task():
log_event("info", "Task cancelled by user")
return "Task cancelled.", "Cancelled" return "Task cancelled.", "Cancelled"
cancel_button.click( cancel_button.click(
@ -679,9 +610,7 @@ def create_app():
def update_logs_display(): def update_logs_display():
"""Update logs display with current logs.""" """Update logs display with current logs."""
logs = get_logs() return ""
formatted_logs = "\n".join(logs)
return formatted_logs
# Update logs when tab is selected # Update logs when tab is selected
logs_tab = gr.Tab("Logs") logs_tab = gr.Tab("Logs")

Loading…
Cancel
Save