Spaces:
Sleeping
Sleeping
| """ | |
| π§ 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] = [] | |
| 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) | |
| def from_json(cls, json_str: str) -> 'SaapAgent': | |
| """Create agent from JSON string""" | |
| return cls.model_validate_json(json_str) | |
| 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""" | |
| 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"] | |
| ) | |
| 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"] | |
| ) | |
| 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! | |