File size: 8,754 Bytes
7df213d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
import os
import json
from pathlib import Path
from typing import Optional, Dict, Any, List
from dotenv import load_dotenv
import requests
from functools import lru_cache
import logging
from datetime import datetime
import threading

load_dotenv()

class SharedModel:
    _instance = None
    _lock = threading.Lock()
    
    def __init__(self):
        if SharedModel._instance is not None:
            raise RuntimeError("Use SharedModel.get_instance() instead")
            
        self.logger = logging.getLogger("SharedModel")
        
        # Initialize state
        self.active_agents: Dict[str, Dict[str, Any]] = {}
        self.active_ports: List[int] = []
        self.tools: Dict[str, Dict[str, Any]] = {}
        
        # Load persisted state
        self._load_state()
        
    @classmethod
    def get_instance(cls) -> 'SharedModel':
        """Get singleton instance of SharedModel"""
        if cls._instance is None:
            with cls._lock:
                if cls._instance is None:
                    cls._instance = cls()
        return cls._instance
        
    def _load_state(self):
        """Load persisted state from disk"""
        try:
            state_file = Path(__file__).parent / "data" / "shared_state.json"
            if state_file.exists():
                with open(state_file) as f:
                    state = json.load(f)
                    self.active_agents = state.get("active_agents", {})
                    self.active_ports = state.get("active_ports", [])
                    self.tools = state.get("tools", {})
        except Exception as e:
            self.logger.error(f"Error loading state: {str(e)}")
            
    def _save_state(self):
        """Save current state to disk"""
        try:
            state_file = Path(__file__).parent / "data" / "shared_state.json"
            state_file.parent.mkdir(exist_ok=True)
            
            state = {
                "active_agents": self.active_agents,
                "active_ports": self.active_ports,
                "tools": self.tools,
                "last_updated": datetime.now().isoformat()
            }
            
            with open(state_file, 'w') as f:
                json.dump(state, f, indent=2)
                
        except Exception as e:
            self.logger.error(f"Error saving state: {str(e)}")
            
    def register_agent(self, name: str, port: int):
        """Register a new agent"""
        with self._lock:
            if port in self.active_ports:
                raise ValueError(f"Port {port} is already in use")
                
            self.active_agents[name] = {
                "port": port,
                "registered_at": datetime.now().isoformat()
            }
            self.active_ports.append(port)
            self._save_state()
            
    def unregister_agent(self, name: str):
        """Unregister an agent"""
        with self._lock:
            if name in self.active_agents:
                port = self.active_agents[name]["port"]
                del self.active_agents[name]
                self.active_ports.remove(port)
                self._save_state()
                
    def register_tool(self, name: str, capabilities: List[str], agent_name: str):
        """Register a new tool"""
        with self._lock:
            self.tools[name] = {
                "capabilities": capabilities,
                "agent": agent_name,
                "registered_at": datetime.now().isoformat()
            }
            self._save_state()
            
    def unregister_tool(self, name: str):
        """Unregister a tool"""
        with self._lock:
            if name in self.tools:
                del self.tools[name]
                self._save_state()
                
    def get_agent_info(self, name: str) -> Optional[Dict[str, Any]]:
        """Get information about a registered agent"""
        return self.active_agents.get(name)
        
    def get_tool_info(self, name: str) -> Optional[Dict[str, Any]]:
        """Get information about a registered tool"""
        return self.tools.get(name)
        
    def get_agent_port(self, name: str) -> Optional[int]:
        """Get the port number for a registered agent"""
        agent_info = self.get_agent_info(name)
        return agent_info["port"] if agent_info else None
        
    def _load_agent_registry(self):
        """Load existing agent registry from file"""
        if self.agent_registry_path.exists():
            try:
                with open(self.agent_registry_path) as f:
                    self.agents = json.load(f)
                    for agent in self.agents.values():
                        if agent.get('port'):
                            self.active_ports.add(agent['port'])
            except Exception as e:
                print(f"Error loading agent registry: {e}")
                self.agents = {}
        else:
            self._save_agent_registry()  # Create empty registry
                        
    def _save_agent_registry(self):
        """Save agent registry to file"""
        try:
            self.agent_registry_path.parent.mkdir(exist_ok=True)
            with open(self.agent_registry_path, 'w') as f:
                json.dump(self.agents, f, indent=2)
        except Exception as e:
            print(f"Error saving agent registry: {e}")
    
    def update_agent_status(self, name: str, status: str):
        """Update agent status"""
        if name in self.agents:
            self.agents[name]['status'] = status
            self._save_agent_registry()
            
    @lru_cache(maxsize=10)
    def get_model_endpoint(self, model_id: str) -> str:
        """Get HuggingFace model endpoint"""
        return f"https://api-inference.huggingface.co/models/{model_id}"
        
    async def generate_text(self, prompt: str, model_id: str = "HuggingFaceH4/zephyr-7b-beta") -> str:
        """Generate text using HuggingFace model"""
        headers = {"Authorization": f"Bearer {self.hf_token}"}
        payload = {
            "inputs": prompt,
            "parameters": {
                "max_length": 2000,
                "temperature": 0.7,
                "top_p": 0.95
            }
        }
        
        response = requests.post(
            self.get_model_endpoint(model_id),
            headers=headers,
            json=payload
        )
        
        return response.json()[0]["generated_text"]
        
    def create_tool(self, name: str, capabilities: list) -> Dict:
        """Dynamically create a new tool"""
        tool_template = f"""
        import requests
        from typing import Dict, Any
        
        class {name.title()}Tool:
            def __init__(self):
                self.capabilities = {capabilities}
                
            def execute(self, params: Dict[str, Any]) -> Dict[str, Any]:
                # Generated tool logic
                result = {{"status": "success", "tool": "{name}"}}
                return result
        """
        
        tool_path = self.tools_path / f"{name.lower()}_tool.py"
        tool_path.parent.mkdir(exist_ok=True)
        
        with open(tool_path, "w") as f:
            f.write(tool_template)
            
        return {
            "name": name,
            "path": str(tool_path),
            "capabilities": capabilities
        }
        
    async def create_sub_agent(self, name: str, capabilities: list, base_prompt: str) -> Dict:
        """Dynamically create a new sub-agent"""
        # Generate agent code using the model
        agent_prompt = f"""Create a Python agent with these capabilities: {capabilities}
        Base prompt: {base_prompt}
        The agent should inherit from BaseAgent and implement process_request.
        """
        
        agent_code = await self.generate_text(agent_prompt)
        
        # Save the generated agent
        agent_path = Path(__file__).parent / "agents" / f"{name.lower()}_agent.py"
        with open(agent_path, "w") as f:
            f.write(agent_code)
            
        return {
            "name": name,
            "path": str(agent_path),
            "capabilities": capabilities
        }
        
    def communicate(self, target_agent: str, endpoint: str, method: str = "GET", data: Dict = None) -> Dict:
        """Communicate with another agent"""
        agent = self.get_agent(target_agent)
        if not agent:
            raise Exception(f"Agent {target_agent} not found")
            
        url = f"http://localhost:{agent['port']}/{endpoint}"
        
        if method.upper() == "GET":
            response = requests.get(url)
        else:
            response = requests.post(url, json=data)
            
        return response.json()