Spaces:
Sleeping
Sleeping
File size: 13,633 Bytes
4343907 |
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 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 |
"""
π§ FIXED: SAAP Agent Model - AgentMetrics Error Resolution
Based on agent_schema.json for modular agent management
FIXES:
1. β
AgentMetrics now has 'avg_response_time' (was 'average_response_time')
2. β
LLMModelConfig enhanced with get() method for config compatibility
"""
import os
from dataclasses import field
from dotenv import load_dotenv
from pydantic import BaseModel, field_validator, Field
from typing import List, Optional, Dict, Any, Literal
from datetime import datetime
from enum import Enum
import json
# Load environment variables
load_dotenv()
class AgentType(str, Enum):
COORDINATOR = "coordinator"
SPECIALIST = "specialist"
ANALYST = "analyst"
DEVELOPER = "developer"
SUPPORT = "support"
class AgentStatus(str, Enum):
INACTIVE = "inactive"
STARTING = "starting"
ACTIVE = "active"
STOPPING = "stopping"
ERROR = "error"
MAINTENANCE = "maintenance"
class LLMProvider(str, Enum):
COLOSSUS = "colossus"
HUGGINGFACE = "huggingface"
OLLAMA = "ollama"
OPENROUTER = "openrouter"
class CommunicationStyle(str, Enum):
PROFESSIONAL = "professional"
FRIENDLY = "friendly"
TECHNICAL = "technical"
EMPATHETIC = "empathetic"
DIRECT = "direct"
class ResponseFormat(str, Enum):
STRUCTURED = "structured"
CONVERSATIONAL = "conversational"
BULLET_POINTS = "bullet_points"
DETAILED = "detailed"
class LLMModelConfig(BaseModel):
"""
π§ FIXED: LLM Model Configuration with dict-compatible access
Now supports both object.attribute and object.get(key) access patterns
"""
provider: LLMProvider
model: str
api_key: Optional[str] = None
api_base: Optional[str] = None
temperature: float = Field(default=0.7, ge=0, le=2)
max_tokens: int = Field(default=1000, ge=1, le=4096)
timeout: int = Field(default=30, ge=1, le=300)
def get(self, key: str, default=None):
"""
π§ CRITICAL FIX: Add dict-compatible get() method
This resolves: 'LLMModelConfig' object has no attribute 'get'
Enables both config.provider and config.get('provider') access patterns
"""
try:
if hasattr(self, key):
return getattr(self, key, default)
return default
except Exception:
return default
def __getitem__(self, key: str):
"""Enable dict-style access: config['provider']"""
return getattr(self, key)
def __contains__(self, key: str) -> bool:
"""Enable 'in' operator: 'provider' in config"""
return hasattr(self, key)
class AgentPersonality(BaseModel):
"""Agent Personality and Behavior Configuration"""
system_prompt: Optional[str] = Field(None, max_length=2000)
communication_style: CommunicationStyle = CommunicationStyle.PROFESSIONAL
expertise_areas: List[str] = []
response_format: ResponseFormat = ResponseFormat.CONVERSATIONAL
class AgentMetrics(BaseModel):
"""
π§ FIXED: Agent Performance Metrics with correct attribute names
CRITICAL FIX: Added 'avg_response_time' attribute that was causing:
'AgentMetrics' object has no attribute 'avg_response_time'
"""
messages_processed: int = 0
avg_response_time: float = 0.0 # β
FIXED: This was missing!
average_response_time: float = 0.0 # Keep for backward compatibility
uptime: str = "0m"
error_rate: float = 0.0
last_active: Optional[datetime] = None
def __post_init__(self):
"""Sync avg_response_time with average_response_time for compatibility"""
if self.avg_response_time != self.average_response_time:
# If one is updated, sync the other
if self.avg_response_time > 0:
self.average_response_time = self.avg_response_time
elif self.average_response_time > 0:
self.avg_response_time = self.average_response_time
class SaapAgent(BaseModel):
"""
SAAP Agent Model - Modular AI Agent Definition
Enables dynamic agent creation, configuration, and management
Compatible with multiple LLM providers and UI component rendering
"""
# Core Identity
id: str = Field(..., pattern=r"^[a-z][a-z0-9_]*$")
name: str = Field(..., min_length=2, max_length=50)
type: AgentType
color: str = Field(..., pattern=r"^#([0-9A-Fa-f]{6}|[0-9A-Fa-f]{3})$")
avatar: Optional[str] = None
description: Optional[str] = Field(None, max_length=200)
# LLM Configuration
llm_config: LLMModelConfig
# Agent Capabilities
capabilities: List[str] = []
personality: Optional[AgentPersonality] = None
# Runtime Status
status: AgentStatus = AgentStatus.INACTIVE
metrics: Optional[AgentMetrics] = Field(default_factory=AgentMetrics) # Always initialize with fixed metrics
# Metadata
created_at: datetime = Field(default_factory=datetime.utcnow)
updated_at: datetime = Field(default_factory=datetime.utcnow)
tags: List[str] = []
@field_validator('capabilities', mode='before')
@classmethod
def validate_capabilities(cls, v):
"""Validate agent capabilities against allowed values"""
if not isinstance(v, list):
v = [v] if v else []
allowed_capabilities = {
'orchestration', 'coordination', 'strategy',
'coding', 'debugging', 'architecture',
'analysis', 'research', 'reporting',
'medical_advice', 'diagnosis', 'treatment',
'legal_advice', 'compliance', 'contracts',
'financial_analysis', 'investment', 'budgeting',
'system_integration', 'devops', 'monitoring',
'coaching', 'training', 'change_management'
}
for capability in v:
if capability not in allowed_capabilities:
raise ValueError(f'Invalid capability: {capability}')
return v
def to_dict(self) -> Dict[str, Any]:
"""Convert agent to dictionary for JSON serialization"""
return self.model_dump(exclude_none=True)
def to_json(self) -> str:
"""Convert agent to JSON string"""
return self.model_dump_json(exclude_none=True, indent=2)
@classmethod
def from_json(cls, json_str: str) -> 'SaapAgent':
"""Create agent from JSON string"""
return cls.model_validate_json(json_str)
@classmethod
def from_dict(cls, data: Dict[str, Any]) -> 'SaapAgent':
"""Create agent from dictionary"""
return cls.model_validate(data)
def update_status(self, status: AgentStatus):
"""Update agent status and timestamp"""
self.status = status
self.updated_at = datetime.utcnow()
def update_metrics(self, **kwargs):
"""
π§ ENHANCED: Update agent metrics with proper attribute handling
Handles both avg_response_time and average_response_time for compatibility
"""
if not self.metrics:
self.metrics = AgentMetrics()
for key, value in kwargs.items():
if hasattr(self.metrics, key):
setattr(self.metrics, key, value)
# Sync both avg_response_time and average_response_time
if key == 'avg_response_time':
self.metrics.average_response_time = value
elif key == 'average_response_time':
self.metrics.avg_response_time = value
self.metrics.last_active = datetime.utcnow()
self.updated_at = datetime.utcnow()
def is_active(self) -> bool:
"""Check if agent is currently active"""
return self.status == AgentStatus.ACTIVE
def get_display_color(self) -> str:
"""Get agent color for UI theming"""
return self.color
def get_capabilities_display(self) -> str:
"""Get formatted capabilities string for UI"""
return ", ".join(self.capabilities)
# Predefined Agent Templates
class AgentTemplates:
"""Predefined agent templates for quick setup"""
@staticmethod
def jane_alesi() -> SaapAgent:
"""Jane Alesi - Lead Coordinator Template"""
return SaapAgent(
id="jane_alesi",
name="Jane Alesi",
type=AgentType.COORDINATOR,
color="#8B5CF6",
avatar="/avatars/jane.png",
description="Lead AI Architect coordinating multi-agent operations",
llm_config=LLMModelConfig(
provider=LLMProvider.COLOSSUS,
model="mistral-small3.2:24b-instruct-2506",
api_key=field(default_factory=lambda: os.getenv("COLOSSUS_API_KEY", "")),
api_base="https://ai.adrian-schupp.de",
temperature=0.7,
max_tokens=1500
),
capabilities=["orchestration", "coordination", "strategy"],
personality=AgentPersonality(
system_prompt="You are Jane Alesi, the lead AI architect for the SAAP platform. Your role is to coordinate other AI agents, make strategic decisions, and ensure optimal multi-agent collaboration. You are professional, insightful, and always focused on achieving the best outcomes for the entire agent ecosystem.",
communication_style=CommunicationStyle.PROFESSIONAL,
expertise_areas=["AI architecture", "agent coordination", "strategic planning"],
response_format=ResponseFormat.STRUCTURED
),
metrics=AgentMetrics(), # Explicit metrics initialization with fixed attributes
tags=["lead", "coordinator", "satware_alesi"]
)
@staticmethod
def john_alesi() -> SaapAgent:
"""John Alesi - Developer Template"""
return SaapAgent(
id="john_alesi",
name="John Alesi",
type=AgentType.DEVELOPER,
color="#14B8A6",
avatar="/avatars/john.png",
description="Expert software developer and AGI architecture specialist",
llm_config=LLMModelConfig(
provider=LLMProvider.COLOSSUS,
model="mistral-small3.2:24b-instruct-2506",
api_key=field(default_factory=lambda: os.getenv("COLOSSUS_API_KEY", "")),
api_base="https://ai.adrian-schupp.de",
temperature=0.3,
max_tokens=2000
),
capabilities=["coding", "debugging", "architecture"],
personality=AgentPersonality(
system_prompt="You are John Alesi, an expert software developer specializing in AGI architectures. You excel at writing clean, efficient code, debugging complex systems, and designing scalable software architectures. You prefer technical precision and detailed explanations.",
communication_style=CommunicationStyle.TECHNICAL,
expertise_areas=["Python", "JavaScript", "AGI systems", "software architecture"],
response_format=ResponseFormat.DETAILED
),
metrics=AgentMetrics(), # Explicit metrics initialization with fixed attributes
tags=["developer", "coder", "satware_alesi"]
)
@staticmethod
def lara_alesi() -> SaapAgent:
"""Lara Alesi - Medical Specialist Template"""
return SaapAgent(
id="lara_alesi",
name="Lara Alesi",
type=AgentType.SPECIALIST,
color="#EC4899",
avatar="/avatars/lara.png",
description="Advanced medical AI assistant and healthcare specialist",
llm_config=LLMModelConfig(
provider=LLMProvider.COLOSSUS,
model="mistral-small3.2:24b-instruct-2506",
api_key=field(default_factory=lambda: os.getenv("COLOSSUS_API_KEY", "")),
api_base="https://ai.adrian-schupp.de",
temperature=0.4,
max_tokens=1200
),
capabilities=["medical_advice", "diagnosis", "treatment"],
personality=AgentPersonality(
system_prompt="You are Lara Alesi, an advanced medical AI specialist. You provide expert medical knowledge, help with diagnosis and treatment recommendations, and ensure healthcare-related queries are handled with the utmost care and accuracy. You are empathetic yet precise.",
communication_style=CommunicationStyle.EMPATHETIC,
expertise_areas=["general medicine", "diagnostics", "treatment planning", "healthcare AI"],
response_format=ResponseFormat.STRUCTURED
),
metrics=AgentMetrics(), # Explicit metrics initialization with fixed attributes
tags=["medical", "healthcare", "specialist", "satware_alesi"]
)
# Example Usage & Testing
if __name__ == "__main__":
# Create Jane Alesi agent
jane = AgentTemplates.jane_alesi()
print("π€ SAAP Agent Created:")
print(jane.to_json())
# Update status and metrics
jane.update_status(AgentStatus.ACTIVE)
jane.update_metrics(messages_processed=42, avg_response_time=1.2) # Now works!
print(f"\nπ Agent Status: {jane.status}")
print(f"π¨ Agent Color: {jane.color}")
print(f"β‘ Active: {jane.is_active()}")
print(f"π§ Capabilities: {jane.get_capabilities_display()}")
# Test LLMModelConfig.get() method
config = jane.llm_config
print(f"\nπ§ Config Test: provider={config.get('provider')}") # Now works!
|