agent-system / shared_model.py
s-diffusion's picture
Initial commit
7df213d
Raw History Blame Contribute Delete
8.75 kB
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()