Spaces:
Build error
Build error
Download base_agent.py from sp103107/agent-system: direct link, hf CLI and curl.
- Browser
- Download file 4.76 kB
-
https://huggingface.co/spaces/sp103107/agent-system/resolve/main/base_agent.py
- Command line
-
hf download hf://spaces/sp103107/agent-system/base_agent.py
-
curl -L -o base_agent.py https://huggingface.co/spaces/sp103107/agent-system/resolve/main/base_agent.py
4.76 kB
| from flask import Flask, request, jsonify | |
| import os | |
| import logging | |
| import signal | |
| import atexit | |
| from datetime import datetime | |
| import traceback | |
| from pathlib import Path | |
| from typing import Dict, Any, List, Optional | |
| import json | |
| import socket | |
| from shared_model import SharedModel | |
| class BaseAgent: | |
| def __init__(self, name: str, port: Optional[int] = None): | |
| self.name = name | |
| self.app = Flask(name) | |
| self.logger = logging.getLogger(name) | |
| # Initialize state | |
| self.is_healthy = True | |
| self.start_time = datetime.now() | |
| self.pid = os.getpid() | |
| # Initialize tools registry | |
| self.tools = {} | |
| self.shared_model = SharedModel.get_instance() | |
| # Setup port | |
| self.port = port or self._setup_port() | |
| # Register cleanup handlers | |
| self._register_cleanup_handlers() | |
| # Register standard routes | |
| self.register_routes() | |
| self.logger.info(f"Initialized {name} agent on port {self.port} with PID {self.pid}") | |
| def _setup_port(self) -> int: | |
| """Setup and register port for the agent""" | |
| try: | |
| # Try to load from config first | |
| port_file = Path(__file__).parent / "data" / "agent_ports.json" | |
| port_file.parent.mkdir(exist_ok=True) | |
| if port_file.exists(): | |
| with open(port_file) as f: | |
| ports = json.load(f) | |
| if self.name in ports: | |
| # Verify port is still available | |
| if self._is_port_available(ports[self.name]): | |
| return ports[self.name] | |
| # Find new available port | |
| port = self._find_available_port() | |
| # Save to config | |
| ports = {} | |
| if port_file.exists(): | |
| with open(port_file) as f: | |
| ports = json.load(f) | |
| ports[self.name] = port | |
| with open(port_file, 'w') as f: | |
| json.dump(ports, f, indent=2) | |
| return port | |
| except Exception as e: | |
| self.logger.error(f"Error setting up port: {str(e)}") | |
| # Fall back to random available port | |
| return self._find_available_port() | |
| def _is_port_available(self, port: int) -> bool: | |
| """Check if a port is available""" | |
| try: | |
| with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: | |
| s.bind(('localhost', port)) | |
| return True | |
| except: | |
| return False | |
| def _find_available_port(self, start: int = 8001, end: int = 8999) -> int: | |
| """Find an available port in the given range""" | |
| for port in range(start, end + 1): | |
| if port not in self.shared_model.active_ports and self._is_port_available(port): | |
| return port | |
| raise RuntimeError("No available ports found") | |
| def _register_cleanup_handlers(self): | |
| """Register cleanup handlers for graceful shutdown""" | |
| def cleanup(): | |
| self.logger.info(f"Cleaning up {self.name} agent...") | |
| self.is_healthy = False | |
| atexit.register(cleanup) | |
| signal.signal(signal.SIGTERM, lambda *args: cleanup()) | |
| signal.signal(signal.SIGINT, lambda *args: cleanup()) | |
| def register_routes(self): | |
| """Register standard HTTP routes""" | |
| def health_check(): | |
| return jsonify({ | |
| 'status': 'healthy' if self.is_healthy else 'unhealthy', | |
| 'uptime': str(datetime.now() - self.start_time), | |
| 'pid': self.pid | |
| }) | |
| def execute(): | |
| try: | |
| data = request.get_json() | |
| result = self.process_request(data) | |
| return jsonify(result) | |
| except Exception as e: | |
| self.logger.error(f"Error processing request: {traceback.format_exc()}") | |
| return jsonify({ | |
| 'error': str(e), | |
| 'status': 'error' | |
| }), 500 | |
| def process_request(self, data: Dict[str, Any]) -> Dict[str, Any]: | |
| """Process incoming requests - to be implemented by child classes""" | |
| raise NotImplementedError("Child classes must implement process_request") | |
| def run(self): | |
| """Start the agent""" | |
| self.shared_model.register_agent(self.name, self.port) | |
| self.app.run(host='0.0.0.0', port=self.port) |