Spaces:
Build error
Build error
Download main_agent.py from sp103107/agent-system: direct link, hf CLI and curl.
- Browser
- Download file 19.2 kB
-
https://huggingface.co/spaces/sp103107/agent-system/resolve/main/main_agent.py
- Command line
-
hf download hf://spaces/sp103107/agent-system/main_agent.py
-
curl -L -o main_agent.py https://huggingface.co/spaces/sp103107/agent-system/resolve/main/main_agent.py
19.2 kB
| from flask import Flask, request, jsonify | |
| import os | |
| import logging | |
| from datetime import datetime | |
| import requests | |
| from pathlib import Path | |
| from tools.agent_generator import get_agent_generator | |
| from tools.tool_generator import get_tool_generator | |
| from tools.langgraph_node import get_langgraph_node | |
| from tools.tool_wrapper import get_tool_registry | |
| from flask_cors import CORS | |
| import json | |
| import yaml | |
| from dotenv import load_dotenv | |
| import re | |
| from tools.agent_launcher import AgentLauncher | |
| from tools.langchain_connector import LangChainConnector | |
| from agents.crew_coordinator import CrewCoordinator | |
| import uuid | |
| from base_agent import BaseAgent | |
| from models import ExecuteRequest, ExecuteResponse, NetworkInput, NetworkOutput | |
| from typing import Dict, Any | |
| # Configure logging | |
| logging.basicConfig(level=logging.INFO) | |
| logger = logging.getLogger(__name__) | |
| app = Flask(__name__) | |
| CORS(app) # Enable CORS for all routes | |
| PORT = int(os.environ.get("PORT", 8000)) | |
| # Load .env file from project root | |
| env_path = Path(__file__).parent / '.env' | |
| load_dotenv(dotenv_path=env_path) | |
| # Initialize components | |
| langgraph = get_langgraph_node() | |
| tool_registry = get_tool_registry() | |
| agent_launcher = AgentLauncher() | |
| class AgentManager: | |
| def __init__(self): | |
| self.base_path = Path(__file__).parent.parent | |
| self.agent_generator = get_agent_generator() | |
| self.tool_generator = get_tool_generator() | |
| self.agents = self.load_agents() | |
| self.langgraph = get_langgraph_node() | |
| def load_agents(self): | |
| """Load agent configurations from registry""" | |
| try: | |
| registry_path = self.base_path / "agent_registry.json" | |
| if registry_path.exists(): | |
| with open(registry_path) as f: | |
| return json.load(f) | |
| return {} | |
| except Exception as e: | |
| logger.error(f"Error loading agents: {str(e)}") | |
| return {} | |
| def get_agent(self, agent_name: str) -> dict: | |
| """Get agent configuration by name""" | |
| try: | |
| if agent_name in self.agents: | |
| return self.agents[agent_name] | |
| logger.warning(f"Agent {agent_name} not found in configuration") | |
| return None | |
| except Exception as e: | |
| logger.error(f"Error getting agent {agent_name}: {str(e)}") | |
| return None | |
| def get_all_agents(self) -> dict: | |
| """Get all agent configurations""" | |
| return self.agents | |
| def create_agent(self, agent_config): | |
| """Create a new agent using the agent generator""" | |
| try: | |
| # Generate agent code | |
| agent_code = self.agent_generator.generate_agent_code(agent_config) | |
| # Save the generated code | |
| agent_path = self.base_path / "agents" / f"{agent_config['name']}.py" | |
| with open(agent_path, "w") as f: | |
| f.write(agent_code) | |
| logger.info(f"Generated agent: {agent_config['name']}") | |
| return True | |
| except Exception as e: | |
| logger.error(f"Error generating agent {agent_config['name']}: {str(e)}") | |
| return False | |
| # Initialize the agent manager globally | |
| agent_manager = AgentManager() | |
| class MainAgent(BaseAgent): | |
| def __init__(self, name: str = "main_agent", port: int = 8000): | |
| super().__init__(name, port) | |
| self.logger = logging.getLogger(name) | |
| # Register additional routes | |
| def handle_network(): | |
| try: | |
| data = requests.get_json() | |
| network_input = NetworkInput(**data) | |
| result = self.route_network_message(network_input) | |
| return result.dict() | |
| except Exception as e: | |
| self.logger.error(f"Error handling network message: {str(e)}") | |
| return NetworkOutput( | |
| source_agent=data.get("target_agent", "unknown"), | |
| target_agent=data.get("source_agent", "unknown"), | |
| message_type="error", | |
| payload={}, | |
| status="error", | |
| error=str(e) | |
| ).dict(), 500 | |
| def process_request(self, data: Dict[str, Any]) -> Dict[str, Any]: | |
| """Process incoming execute requests""" | |
| try: | |
| request = ExecuteRequest(**data) | |
| # Route request to appropriate handler | |
| if request.action == "network": | |
| return self.handle_network_request(request) | |
| elif request.action == "tool": | |
| return self.handle_tool_request(request) | |
| elif request.action == "agent": | |
| return self.handle_agent_request(request) | |
| else: | |
| return ExecuteResponse( | |
| status="error", | |
| error=f"Unknown action: {request.action}" | |
| ).dict() | |
| except Exception as e: | |
| self.logger.error(f"Error processing request: {str(e)}") | |
| return ExecuteResponse( | |
| status="error", | |
| error=str(e) | |
| ).dict() | |
| def handle_network_request(self, request: ExecuteRequest) -> Dict[str, Any]: | |
| """Handle network-related requests""" | |
| try: | |
| # Get target agent info | |
| target = request.parameters.get("target") | |
| if not target: | |
| raise ValueError("Target agent not specified") | |
| agent_info = self.shared_model.get_agent_info(target) | |
| if not agent_info: | |
| raise ValueError(f"Agent not found: {target}") | |
| # Forward request to target agent | |
| response = requests.post( | |
| f"http://localhost:{agent_info['port']}/execute", | |
| json=request.parameters | |
| ) | |
| response.raise_for_status() | |
| return ExecuteResponse( | |
| status="success", | |
| result=response.json() | |
| ).dict() | |
| except Exception as e: | |
| self.logger.error(f"Error handling network request: {str(e)}") | |
| return ExecuteResponse( | |
| status="error", | |
| error=str(e) | |
| ).dict() | |
| def handle_tool_request(self, request: ExecuteRequest) -> Dict[str, Any]: | |
| """Handle tool-related requests""" | |
| try: | |
| tool_name = request.parameters.get("tool") | |
| if not tool_name: | |
| raise ValueError("Tool name not specified") | |
| tool_info = self.shared_model.get_tool_info(tool_name) | |
| if not tool_info: | |
| raise ValueError(f"Tool not found: {tool_name}") | |
| # Forward request to tool's agent | |
| agent_info = self.shared_model.get_agent_info(tool_info["agent"]) | |
| if not agent_info: | |
| raise ValueError(f"Tool's agent not found: {tool_info['agent']}") | |
| response = requests.post( | |
| f"http://localhost:{agent_info['port']}/execute", | |
| json={ | |
| "action": "execute_tool", | |
| "tool": tool_name, | |
| "parameters": request.parameters | |
| } | |
| ) | |
| response.raise_for_status() | |
| return ExecuteResponse( | |
| status="success", | |
| result=response.json() | |
| ).dict() | |
| except Exception as e: | |
| self.logger.error(f"Error handling tool request: {str(e)}") | |
| return ExecuteResponse( | |
| status="error", | |
| error=str(e) | |
| ).dict() | |
| def handle_agent_request(self, request: ExecuteRequest) -> Dict[str, Any]: | |
| """Handle agent-related requests""" | |
| try: | |
| action = request.parameters.get("action") | |
| if not action: | |
| raise ValueError("Agent action not specified") | |
| if action == "list": | |
| return ExecuteResponse( | |
| status="success", | |
| result={ | |
| "agents": self.shared_model.active_agents, | |
| "tools": self.shared_model.tools | |
| } | |
| ).dict() | |
| elif action == "register": | |
| name = request.parameters.get("name") | |
| port = request.parameters.get("port") | |
| if not name or not port: | |
| raise ValueError("Name and port required for registration") | |
| self.shared_model.register_agent(name, port) | |
| return ExecuteResponse( | |
| status="success", | |
| result={"message": f"Agent {name} registered successfully"} | |
| ).dict() | |
| else: | |
| return ExecuteResponse( | |
| status="error", | |
| error=f"Unknown agent action: {action}" | |
| ).dict() | |
| except Exception as e: | |
| self.logger.error(f"Error handling agent request: {str(e)}") | |
| return ExecuteResponse( | |
| status="error", | |
| error=str(e) | |
| ).dict() | |
| def route_network_message(self, message: NetworkInput) -> NetworkOutput: | |
| """Route network messages between agents""" | |
| try: | |
| # Get target agent info | |
| target_info = self.shared_model.get_agent_info(message.target_agent) | |
| if not target_info: | |
| raise ValueError(f"Target agent not found: {message.target_agent}") | |
| # Forward message to target agent | |
| response = requests.post( | |
| f"http://localhost:{target_info['port']}/network", | |
| json=message.dict() | |
| ) | |
| response.raise_for_status() | |
| return NetworkOutput(**response.json()) | |
| except Exception as e: | |
| self.logger.error(f"Error routing network message: {str(e)}") | |
| return NetworkOutput( | |
| source_agent=message.target_agent, | |
| target_agent=message.source_agent, | |
| message_type="error", | |
| payload={}, | |
| status="error", | |
| error=str(e) | |
| ) | |
| def execute(): | |
| try: | |
| data = request.get_json() | |
| task = data.get("task", {}) | |
| task_type = task.get("type") | |
| # Generate unique task ID | |
| task_id = str(uuid.uuid4()) | |
| # Handle agent/tool creation first | |
| if task_type == "agent_creation": | |
| team_config = task["team"] | |
| created_agents = [] | |
| created_tools = [] | |
| # Create shared tools first | |
| for tool_config in team_config.get("shared_tools", []): | |
| if agent_manager.create_tool(tool_config): | |
| created_tools.append(tool_config["name"]) | |
| # Create agents | |
| for agent_config in team_config.get("agents", []): | |
| if agent_manager.create_agent(agent_config): | |
| created_agents.append(agent_config["name"]) | |
| return { | |
| "status": "success", | |
| "message": "Created agents and tools", | |
| "agents": created_agents, | |
| "tools": created_tools, | |
| "timestamp": datetime.now().isoformat() | |
| } | |
| # Handle text tasks with auto-team option | |
| elif task_type == "text_task": | |
| # Register task with LangGraph | |
| langgraph.register_task( | |
| task_id=task_id, | |
| description=task.get("input", ""), | |
| assigned_agent="main_agent" | |
| ) | |
| # Auto-select team if requested | |
| if task.get("auto_team", False): | |
| task["agents"] = select_agent_team(task["input"]) | |
| team_leader = assign_team_leader(task["agents"], task) | |
| task["team_leader"] = team_leader | |
| result = handle_text_task(task_id, task) | |
| # Update task status in LangGraph | |
| langgraph.update_task_status( | |
| task_id=task_id, | |
| status="completed", | |
| output=result | |
| ) | |
| return { | |
| "status": "success", | |
| "task_id": task_id, | |
| "result": result, | |
| "team": task["agents"], | |
| "leader": task.get("team_leader"), | |
| "timestamp": datetime.now().isoformat() | |
| } | |
| # Handle workflow tasks | |
| elif task_type == "workflow": | |
| # Register workflow task | |
| langgraph.register_task( | |
| task_id=task_id, | |
| description=f"Workflow: {task.get('name', 'Unnamed')}", | |
| assigned_agent="main_agent" | |
| ) | |
| result = handle_workflow(task_id, task) | |
| # Update workflow status | |
| langgraph.update_task_status( | |
| task_id=task_id, | |
| status="completed", | |
| output=result | |
| ) | |
| return { | |
| "status": "success", | |
| "task_id": task_id, | |
| "result": result, | |
| "timestamp": datetime.now().isoformat() | |
| } | |
| else: | |
| return { | |
| "status": "error", | |
| "message": f"Unknown task type: {task_type}", | |
| "timestamp": datetime.now().isoformat() | |
| } | |
| except Exception as e: | |
| logger.error(f"Error in task execution: {str(e)}") | |
| return { | |
| "status": "error", | |
| "message": str(e), | |
| "timestamp": datetime.now().isoformat() | |
| } | |
| def handle_workflow(task_id: str, task_data: dict): | |
| """Handle workflow execution with LangGraph integration""" | |
| try: | |
| workflow_agents = task_data.get("agents", []) | |
| results = [] | |
| for agent_name in workflow_agents: | |
| agent = agent_manager.get_agent(agent_name) | |
| if not agent: | |
| continue | |
| # Create subtask in LangGraph | |
| subtask_id = f"{task_id}_{agent_name}" | |
| langgraph.register_task( | |
| task_id=subtask_id, | |
| description=f"Subtask for {agent_name}", | |
| assigned_agent=agent_name | |
| ) | |
| # Execute agent | |
| response = requests.post( | |
| f"http://localhost:{agent['port']}/execute", | |
| json={"workflow_step": True} | |
| ) | |
| # Update subtask status | |
| langgraph.update_task_status( | |
| task_id=subtask_id, | |
| status="completed", | |
| output=response.json() | |
| ) | |
| results.append({ | |
| "agent": agent_name, | |
| "result": response.json() | |
| }) | |
| return { | |
| "status": "success", | |
| "results": results, | |
| "timestamp": datetime.now().isoformat() | |
| } | |
| except Exception as e: | |
| logger.error(f"Error in workflow execution: {str(e)}") | |
| return { | |
| "status": "error", | |
| "error": str(e), | |
| "timestamp": datetime.now().isoformat() | |
| } | |
| def handle_text_task(task_id: str, task_data: dict): | |
| """Handle text-based tasks with LangGraph integration""" | |
| try: | |
| # Initialize LangChain for task analysis | |
| langchain = LangChainConnector(os.getenv('HUGGINGFACE_TOKEN')) | |
| # Analyze task using LangChain | |
| analysis = langchain.analyze_task(task_data.get("input", "")) | |
| if not analysis: | |
| return { | |
| "status": "error", | |
| "message": "Task analysis failed", | |
| "timestamp": datetime.now().isoformat() | |
| } | |
| # Auto-select team if requested | |
| if task_data.get("auto_team", False): | |
| task_data["agents"] = select_agent_team(task_data["input"]) | |
| team_leader = assign_team_leader(task_data["agents"], task_data) | |
| task_data["team_leader"] = team_leader | |
| # Use CrewAI for agent coordination | |
| coordinator = CrewCoordinator(agent_manager.get_all_agents()) | |
| crew_result = coordinator.execute_crew_workflow({ | |
| "task_id": task_id, | |
| "agents": task_data["agents"], | |
| "tasks": [{ | |
| "description": task_data["input"], | |
| "assigned_agent": task_data.get("team_leader", task_data["agents"][0]) | |
| }] | |
| }) | |
| if crew_result.get("status") == "error": | |
| return crew_result | |
| return { | |
| "status": "success", | |
| "analysis": analysis, | |
| "crew_result": crew_result.get("result"), | |
| "team": task_data["agents"], | |
| "leader": task_data.get("team_leader"), | |
| "timestamp": datetime.now().isoformat() | |
| } | |
| except Exception as e: | |
| logger.error(f"Error in task execution: {str(e)}") | |
| return { | |
| "status": "error", | |
| "message": str(e), | |
| "timestamp": datetime.now().isoformat() | |
| } | |
| def health_check(): | |
| return jsonify({ | |
| "status": "healthy", | |
| "agent": "main_agent", | |
| "timestamp": datetime.now().isoformat() | |
| }), 200 | |
| def list_agents(): | |
| """List all running agents""" | |
| try: | |
| agents_dir = Path(__file__).parent / "agents" | |
| agents = [ | |
| f.stem for f in agents_dir.glob("*.py") | |
| if f.stem not in ["__init__", "base_agent"] | |
| ] | |
| return jsonify({ | |
| "status": "success", | |
| "agents": agents, | |
| "timestamp": datetime.now().isoformat() | |
| }), 200 | |
| except Exception as e: | |
| logger.error(f"Error listing agents: {str(e)}") | |
| return jsonify({ | |
| "status": "error", | |
| "error": str(e), | |
| "timestamp": datetime.now().isoformat() | |
| }), 500 | |
| def get_task_status(task_id: str): | |
| """Get status of a specific task""" | |
| try: | |
| task_state = langgraph.get_task_state(task_id) | |
| return jsonify({ | |
| "status": "success", | |
| "task": task_state, | |
| "timestamp": datetime.now().isoformat() | |
| }), 200 | |
| except Exception as e: | |
| return jsonify({ | |
| "status": "error", | |
| "error": str(e), | |
| "timestamp": datetime.now().isoformat() | |
| }), 404 | |
| if __name__ == "__main__": | |
| agent = MainAgent() | |
| agent.run() |