agent-system / tools /agent_generator.py
sp103107's picture
Upload folder using huggingface_hub
e20bd8e verified
Raw History Blame Contribute Delete
7.16 kB
import logging
from pathlib import Path
from datetime import datetime
from tools.smol_manager import get_smol_manager
import json
logger = logging.getLogger(__name__)
class AgentGenerator:
def __init__(self):
self.smol = get_smol_manager()
self.base_path = Path(__file__).parent.parent
self.templates_path = self.base_path / "templates"
def generate_agent_code(self, agent_config):
"""Generate agent code using SMOL"""
try:
# Create agent prompt
prompt = f"""
Create a Python agent with these capabilities: {agent_config['capabilities']}
Requirements:
1. Inherit from BaseAgent
2. Implement process_request method
3. Use these tools: {agent_config.get('tools', [])}
4. Follow this base prompt: {agent_config['base_prompt']}
The agent should be a complete, working Python class.
"""
# Generate code using SMOL
agent_code = self.smol.generate_text(prompt)
# Add imports and setup
full_code = f"""
from flask import Flask, request, jsonify
import os
import logging
from datetime import datetime
from agents.base_agent import BaseAgent
from tools.web_search import get_web_search
from tools.api_client import get_api_client
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
{agent_code}
if __name__ == "__main__":
agent = {agent_config['name'].title()}Agent()
agent.run()
"""
return full_code
except Exception as e:
logger.error(f"Error generating agent code: {str(e)}")
raise
def get_base_agent_template(self):
"""Get the base template that all generated agents should follow"""
return '''
# Base Agent Template
# This serves as a guide for agent generation and defines required capabilities
"""
Inter-Agent Communication Flow:
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ Agent A β”‚ β”‚ Port β”‚ β”‚ Agent B β”‚
β”‚ (Requester) β”‚ β”‚ Registry β”‚ β”‚ (Helper) β”‚
β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”˜
β”‚ β”‚ β”‚
β”‚ 1. Discover β”‚ β”‚
│─────────────────> β”‚ β”‚
β”‚ β”‚ β”‚
β”‚ 2. Get Port β”‚ β”‚
β”‚ <─────────────────-β”‚ β”‚
β”‚ β”‚ β”‚
β”‚ 3. Request Help β”‚
│────────────────────────────────────────> β”‚
β”‚ β”‚ β”‚
β”‚ 4. Process & Execute β”‚
β”‚ β”‚ β”‚
β”‚ 5. Return Results β”‚
β”‚ <────────────────────────────────────────│
β”‚ β”‚ β”‚
Flow Steps:
1. Agent discovers other agents via port_file
2. Gets port number for target agent
3. Sends request to helper agent
4. Helper agent processes request
5. Returns results to requesting agent
Example:
hotel_search β†’ email_manager
weather_agent β†’ travel_planner
music_composer β†’ dialogue_specialist
"""
from flask import Flask, request, jsonify
import os
import logging
from datetime import datetime
import requests
from pathlib import Path
import json
class BaseAgent:
"""Base class that defines core agent capabilities"""
def __init__(self, name):
self.name = name
self.known_agents = {}
self.capabilities = []
self.app = Flask(name)
self.discover_agents()
# Register base routes that all agents should have
self.register_routes()
def register_routes(self):
"""Register standard API endpoints"""
@self.app.route('/execute', methods=['POST'])
def execute():
return self.process_request(request)
@self.app.route('/health', methods=['GET'])
def health():
return jsonify({
"status": "healthy",
"agent": self.name,
"capabilities": self.capabilities,
"timestamp": datetime.now().isoformat()
})
def discover_agents(self):
"""Discover other available agents"""
try:
port_file = Path(__file__).parent.parent / "data" / "agent_ports.json"
if port_file.exists():
with open(port_file) as f:
self.known_agents = json.load(f)
logging.info(f"Discovered agents: {list(self.known_agents.keys())}")
except Exception as e:
logging.error(f"Error discovering agents: {e}")
def request_help(self, agent_name, task_data):
"""Request help from another agent"""
try:
if agent_name in self.known_agents:
port = self.known_agents[agent_name]
response = requests.post(
f"http://localhost:{port}/execute",
json={"task": task_data}
)
return response.json()
else:
logging.error(f"Unknown agent: {agent_name}")
return None
except Exception as e:
logging.error(f"Error requesting help from {agent_name}: {e}")
return None
def register_capability(self, capability):
"""Register a new capability"""
self.capabilities.append(capability)
logging.info(f"Registered new capability: {capability}")
def can_help_with(self, task):
"""Check if agent can help with task"""
required = task.get('required_capabilities', [])
can_help = any(cap in required for cap in self.capabilities)
logging.info(f"Can help with task? {can_help}")
return can_help
def process_request(self, request):
"""Process incoming requests - Must be implemented by child classes"""
raise NotImplementedError("Agents must implement process_request")
def run(self, host="0.0.0.0", port=None):
"""Run the agent server"""
if port:
self.app.run(host=host, port=port)
else:
self.app.run(host=host)
'''
_instance = None
def get_agent_generator():
global _instance
if _instance is None:
_instance = AgentGenerator()
return _instance