File size: 14,189 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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
#!/usr/bin/env python3
"""
SAAP colossus Server Integration - ColosusSAAPAgent
=================================================

Direct integration with colossus Server für Phase 1 Infrastructure Foundation.
Hybrid Architecture: CachyOS (Orchestrierung) + colossus (LLM Processing)

Server Details:
- URL: https://ai.adrian-schupp.de
- Model: mistral-small3.2:24b-instruct-2506  
- Performance Target: < 2s Response-Zeit

Integration with existing SAAP Agent Communication System.
"""

import asyncio
import json
import time
import logging
import os
from typing import Dict, Any, Optional, List
from dataclasses import dataclass, field
import aiohttp
import redis.asyncio as redis
from dotenv import load_dotenv

# Load environment variables
load_dotenv()

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

@dataclass
class ColossusConfig:
    """colossus Server Configuration"""
    base_url: str = "https://ai.adrian-schupp.de"
    api_key: str = field(default_factory=lambda: os.getenv("COLOSSUS_API_KEY", ""))
    model: str = "mistral-small3.2:24b-instruct-2506"
    max_tokens: int = 1000
    temperature: float = 0.7
    timeout: int = 30  # seconds
    
    def __post_init__(self):
        """Validate configuration after initialization"""
        if not self.api_key:
            raise ValueError(
                "❌ COLOSSUS_API_KEY environment variable not set.\n"
                "Please set it in your .env file:\n"
                "COLOSSUS_API_KEY=your-api-key-here"
            )

class ColosusSAAPAgent:
    """
    SAAP Agent mit colossus Server Integration
    
    Hybrid Architecture:
    - CachyOS: Agent Orchestrierung, Message Queue, System Management
    - colossus: High-Performance LLM Processing, AI Inference
    """
    
    def __init__(self, 
                 agent_name: str,
                 agent_role: str = "Coordinator",
                 config: Optional[ColossusConfig] = None,
                 redis_url: str = "redis://localhost:6379"):
        
        self.agent_name = agent_name
        self.agent_role = agent_role
        self.config = config or ColossusConfig()
        self.redis_url = redis_url
        
        # Agent context for specialized roles
        self.agent_contexts = {
            "Coordinator": "Du bist Agent A (Coordinator) für SAAP. Du koordinierst Multi-Agent Workflows und delegierst Tasks effizient.",
            "Developer": "Du bist Agent B (Developer) mit Expertise in Python, Node.js, Vue.js. Du fokussierst auf Clean Code und Performance.",  
            "Analyst": "Du bist Agent C (Analyst) für Requirements-Analyse, Use Cases und Systemdesign. Du lieferst strukturierte Analysen.",
            "General": "Du bist ein SAAP Multi-Agent mit genereller KI-Expertise für vielseitige Tasks."
        }
        
        # Performance tracking
        self.performance_stats = {
            "total_requests": 0,
            "total_response_time": 0.0,
            "average_response_time": 0.0,
            "errors": 0,
            "successful_requests": 0
        }
        
        # Redis connection (will be initialized async)
        self.redis_client = None
        
    async def initialize(self):
        """Initialize async components"""
        try:
            self.redis_client = await redis.from_url(self.redis_url)
            await self.redis_client.ping()
            logger.info(f"✅ {self.agent_name} connected to Redis")
            
            # Register agent in Redis
            await self.register_agent()
            
        except Exception as e:
            logger.error(f"❌ Redis connection failed for {self.agent_name}: {e}")
            # Continue without Redis - degraded mode
    
    async def register_agent(self):
        """Register agent with SAAP system"""
        if not self.redis_client:
            return
            
        agent_info = {
            "name": self.agent_name,
            "role": self.agent_role,
            "status": "active",
            "model": self.config.model,
            "server": "colossus",
            "capabilities": ["llm_processing", "multi_agent_communication", "task_coordination"],
            "performance_target": "< 2s response time",
            "timestamp": time.time()
        }
        
        await self.redis_client.hset(
            f"agent:{self.agent_name}",
            mapping={k: json.dumps(v) if isinstance(v, (dict, list)) else str(v) 
                    for k, v in agent_info.items()}
        )
        
        # Add to active agents set  
        await self.redis_client.sadd("active_agents", self.agent_name)
        
        logger.info(f"📝 {self.agent_name} registered with SAAP system")

    async def call_colossus_api(self, prompt: str) -> Dict[str, Any]:
        """
        Direct API call to colossus Server
        
        Returns response with performance metrics
        """
        start_time = time.time()
        
        try:
            headers = {
                "Authorization": f"Bearer {self.config.api_key}",
                "Content-Type": "application/json"
            }
            
            # Add agent context to prompt
            context = self.agent_contexts.get(self.agent_role, self.agent_contexts["General"])
            enhanced_prompt = f"{context}\\n\\nAufgabe: {prompt}"
            
            payload = {
                "model": self.config.model,
                "messages": [
                    {"role": "user", "content": enhanced_prompt}
                ],
                "max_tokens": self.config.max_tokens,
                "temperature": self.config.temperature
            }
            
            async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=self.config.timeout)) as session:
                async with session.post(
                    f"{self.config.base_url}/v1/chat/completions",
                    headers=headers,
                    json=payload
                ) as response:
                    
                    if response.status == 200:
                        result = await response.json()
                        
                        # Extract response text
                        content = result.get("choices", [{}])[0].get("message", {}).get("content", "No response")
                        
                        # Calculate performance
                        response_time = time.time() - start_time
                        
                        # Update stats
                        self.performance_stats["total_requests"] += 1
                        self.performance_stats["successful_requests"] += 1
                        self.performance_stats["total_response_time"] += response_time
                        self.performance_stats["average_response_time"] = (
                            self.performance_stats["total_response_time"] / 
                            self.performance_stats["total_requests"]
                        )
                        
                        return {
                            "success": True,
                            "content": content,
                            "response_time": response_time,
                            "model": self.config.model,
                            "server": "colossus",
                            "agent": self.agent_name,
                            "role": self.agent_role,
                            "performance_check": response_time < 2.0  # Success if < 2s
                        }
                    
                    else:
                        error_text = await response.text()
                        raise Exception(f"API Error {response.status}: {error_text}")
                        
        except Exception as e:
            # Update error stats
            self.performance_stats["errors"] += 1
            self.performance_stats["total_requests"] += 1
            
            response_time = time.time() - start_time
            
            logger.error(f"❌ colossus API call failed: {e}")
            
            return {
                "success": False,
                "error": str(e),
                "response_time": response_time,
                "agent": self.agent_name,
                "server": "colossus",
                "performance_check": False
            }

    async def process_message(self, message: str, context: Optional[Dict] = None) -> Dict[str, Any]:
        """
        Process incoming message with colossus LLM
        
        Integrates with SAAP Message Queue System
        """
        
        # Log message processing
        logger.info(f"🤖 {self.agent_name} ({self.agent_role}) processing message...")
        
        # Call colossus API
        result = await self.call_colossus_api(message)
        
        # Add SAAP-specific metadata
        result.update({
            "agent_name": self.agent_name,
            "agent_role": self.agent_role,
            "timestamp": time.time(),
            "message_id": context.get("message_id") if context else None,
            "thread_id": context.get("thread_id") if context else None
        })
        
        # Store in Redis if available
        if self.redis_client and result["success"]:
            await self._store_message_result(message, result)
        
        # Performance logging
        performance_emoji = "⚡" if result.get("performance_check", False) else "⏱️"
        logger.info(f"{performance_emoji} {self.agent_name}: {result.get('response_time', 0):.2f}s")
        
        return result

    async def _store_message_result(self, message: str, result: Dict[str, Any]):
        """Store message and result in Redis for monitoring"""
        if not self.redis_client:
            return
            
        message_data = {
            "input": message,
            "output": result.get("content", ""),
            "agent": self.agent_name,
            "role": self.agent_role,
            "response_time": result.get("response_time", 0),
            "timestamp": result.get("timestamp", time.time()),
            "success": result.get("success", False)
        }
        
        # Store in message history
        await self.redis_client.lpush(
            f"messages:{self.agent_name}",
            json.dumps(message_data)
        )
        
        # Keep only recent messages (last 100)
        await self.redis_client.ltrim(f"messages:{self.agent_name}", 0, 99)
        
        # Update agent status
        await self.redis_client.hset(
            f"agent:{self.agent_name}",
            "last_activity",
            str(time.time())
        )

    async def get_performance_stats(self) -> Dict[str, Any]:
        """Get comprehensive performance statistics"""
        stats = self.performance_stats.copy()
        
        # Add colossus-specific metrics
        stats.update({
            "server": "colossus",
            "model": self.config.model,
            "performance_target_met": stats["average_response_time"] < 2.0,
            "success_rate": (
                (stats["successful_requests"] / stats["total_requests"]) * 100 
                if stats["total_requests"] > 0 else 0
            ),
            "agent_name": self.agent_name,
            "agent_role": self.agent_role
        })
        
        return stats

    async def cleanup(self):
        """Cleanup connections"""
        if self.redis_client:
            await self.redis_client.srem("active_agents", self.agent_name)
            await self.redis_client.close()

# Example Usage & Testing
async def test_colossus_integration():
    """Test colossus Server Integration"""
    
    print("🚀 Testing SAAP colossus Server Integration...")
    
    # Create test agents
    agents = [
        ColosusSAAPAgent("agent_coordinator", "Coordinator"),
        ColosusSAAPAgent("agent_developer", "Developer"), 
        ColosusSAAPAgent("agent_analyst", "Analyst")
    ]
    
    # Initialize all agents
    for agent in agents:
        await agent.initialize()
    
    # Test messages
    test_messages = [
        "Analysiere die SAAP Multi-Agent-Architektur und identifiziere Optimierungsbedarfe.",
        "Entwickle Python Code für Redis Message Queue Integration.",
        "Erstelle Use Cases für Agent-zu-Agent Kommunikation."
    ]
    
    # Process messages in parallel
    tasks = []
    for i, agent in enumerate(agents):
        message = test_messages[i % len(test_messages)]
        tasks.append(agent.process_message(message, {"test_id": i}))
    
    results = await asyncio.gather(*tasks, return_exceptions=True)
    
    # Print results
    print("\\n" + "="*60)
    print("🎯 SAAP colossus Integration Results:")
    print("="*60)
    
    for i, result in enumerate(results):
        if isinstance(result, Exception):
            print(f"❌ Agent {i+1}: Error - {result}")
        else:
            agent_name = result.get("agent_name", f"Agent_{i+1}")
            response_time = result.get("response_time", 0)
            success = result.get("success", False)
            performance = "✅ < 2s" if result.get("performance_check", False) else f"⏱️ {response_time:.2f}s"
            
            print(f"{'✅' if success else '❌'} {agent_name}: {performance}")
            if success:
                content = result.get("content", "")[:100] + "..." if len(result.get("content", "")) > 100 else result.get("content", "")
                print(f"   Response: {content}")
    
    # Performance summary
    print("\\n" + "="*60)
    print("📊 Performance Summary:")
    
    for agent in agents:
        stats = await agent.get_performance_stats()
        print(f"🤖 {agent.agent_name} ({agent.agent_role}):")
        print(f"   Average Response Time: {stats['average_response_time']:.2f}s")
        print(f"   Success Rate: {stats['success_rate']:.1f}%")
        print(f"   Performance Target Met: {'✅' if stats['performance_target_met'] else '❌'}")
    
    # Cleanup
    for agent in agents:
        await agent.cleanup()
    
    print("\\n🎉 colossus Integration Test Complete!")

if __name__ == "__main__":
    asyncio.run(test_colossus_integration())