Spaces:
Paused
Paused
File size: 11,823 Bytes
0a61b60 | 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 | #!/usr/bin/env python3
"""
Multi-Agent Communication API Endpoints for SAAP Platform
Provides REST API interface for multi-agent coordination and task delegation
"""
from fastapi import APIRouter, HTTPException, Depends
from typing import Dict, Any, Optional, List
import logging
from datetime import datetime
from pydantic import BaseModel
from services.multi_agent_coordinator import MultiAgentCoordinator, TaskPriority, get_coordinator
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Create router for multi-agent endpoints
multi_agent_router = APIRouter(prefix="/api/v1/multi-agent", tags=["Multi-Agent Communication"])
class MultiAgentChatRequest(BaseModel):
user_message: str
user_context: Optional[Dict[str, Any]] = None
preferred_agent: Optional[str] = None
task_priority: TaskPriority = TaskPriority.NORMAL
class MultiAgentChatResponse(BaseModel):
success: bool
coordinator_response: str
delegated_agent: Optional[str] = None
specialist_response: Optional[str] = None
coordination_chain: List[str] = []
processing_time: float = 0.0
workflow_type: str = "single_agent"
task_id: Optional[str] = None
cost_info: Optional[Dict[str, Any]] = None
error: Optional[str] = None
@multi_agent_router.post("/chat", response_model=MultiAgentChatResponse)
async def multi_agent_chat(
request: MultiAgentChatRequest,
coordinator: MultiAgentCoordinator = Depends(get_coordinator)
):
"""
π€ Multi-Agent Chat Endpoint - Jane Alesi Master Coordinator
Automatically analyzes user intent and either:
1. Handles request directly (Jane as coordinator)
2. Delegates to appropriate specialist agent
3. Orchestrates multi-agent workflow for complex tasks
Examples:
- "Entwickle eine Python App" β Jane delegates to John Alesi (Development)
- "Medizinische Beratung fΓΌr Diabetes" β Jane delegates to Lara Alesi (Medical)
- "Legal Compliance Check" β Jane delegates to Justus Alesi (Legal)
- "SAAP Platform Status" β Jane handles directly as Coordinator
"""
start_time = datetime.now()
try:
logger.info(f"π€ Multi-Agent Chat Request: {request.user_message[:100]}...")
# Execute multi-agent coordination
coordination_result = await coordinator.coordinate_multi_agent_task(
user_message=request.user_message,
user_context=request.user_context or {}
)
processing_time = (datetime.now() - start_time).total_seconds()
if coordination_result.get("success", False):
# Successful coordination
workflow_type = coordination_result.get("workflow_type", "single_agent")
if workflow_type == "multi_agent":
# Complex multi-agent workflow
specialists = coordination_result.get("specialists", [])
workflow_steps = coordination_result.get("workflow_steps", [])
# Build coordination chain
coordination_chain = ["jane_alesi"] # Jane always starts
coordination_chain.extend(specialists)
# Get final response from synthesis step
coordinator_response = coordination_result.get("final_response", "Multi-agent workflow completed successfully.")
# Get specialist response (first specialist for simplicity)
specialist_response = None
delegated_agent = None
if workflow_steps:
for step in workflow_steps:
if step.get("step") == "specialist_analysis":
delegated_agent = step.get("agent")
specialist_response = step.get("result", {}).get("response", "Specialist analysis completed.")
break
logger.info(f"β
Multi-Agent Workflow: {len(workflow_steps)} steps, {len(specialists)} specialists")
return MultiAgentChatResponse(
success=True,
coordinator_response=coordinator_response,
delegated_agent=delegated_agent,
specialist_response=specialist_response,
coordination_chain=coordination_chain,
processing_time=processing_time,
workflow_type="multi_agent",
task_id=coordination_result.get("task_id"),
cost_info={
"total_cost": 0.0, # Multi-agent coordination is free
"task_count": coordination_result.get("task_count", 1),
"agents_involved": len(coordination_chain)
}
)
else:
# Single agent delegation
primary_agent = coordination_result.get("primary_agent", "jane_alesi")
response_text = coordination_result.get("response", "Task completed successfully.")
# Determine coordination chain
coordination_chain = ["jane_alesi"] # Jane analyzes intent
if primary_agent != "jane_alesi":
coordination_chain.append(primary_agent) # Delegate to specialist
coordination_chain.append("jane_alesi") # Jane provides final coordination
logger.info(f"β
Single Agent Delegation: jane_alesi β {primary_agent}")
return MultiAgentChatResponse(
success=True,
coordinator_response=f"Als Master Coordinatorin habe ich deinen Request analysiert und {'direkt bearbeitet' if primary_agent == 'jane_alesi' else f'an {primary_agent} delegiert'}.",
delegated_agent=primary_agent if primary_agent != "jane_alesi" else None,
specialist_response=response_text if primary_agent != "jane_alesi" else None,
coordination_chain=coordination_chain,
processing_time=processing_time,
workflow_type="single_agent",
task_id=coordination_result.get("task_id"),
cost_info={
"total_cost": 0.0,
"agents_involved": len(coordination_chain)
}
)
else:
# Coordination failed
error_msg = coordination_result.get("error", "Unknown coordination error")
logger.error(f"β Multi-Agent Coordination failed: {error_msg}")
return MultiAgentChatResponse(
success=False,
coordinator_response="Als Master Coordinatorin konnte ich deinen Request leider nicht erfolgreich bearbeiten.",
processing_time=processing_time,
error=error_msg
)
except Exception as e:
processing_time = (datetime.now() - start_time).total_seconds()
logger.error(f"β Multi-Agent Chat API Error: {e}")
return MultiAgentChatResponse(
success=False,
coordinator_response="Entschuldigung, es ist ein technischer Fehler im Multi-Agent System aufgetreten.",
processing_time=processing_time,
error=str(e)
)
@multi_agent_router.get("/status")
async def get_multi_agent_status(
coordinator: MultiAgentCoordinator = Depends(get_coordinator)
):
"""
Get current multi-agent coordination status and statistics
"""
try:
stats = await coordinator.get_coordination_stats()
return {
"status": "active",
"coordinator": "jane_alesi",
"available_specialists": [
{"id": "john_alesi", "name": "John Alesi", "specialization": "Development"},
{"id": "lara_alesi", "name": "Lara Alesi", "specialization": "Medical"},
{"id": "justus_alesi", "name": "Justus Alesi", "specialization": "Legal"},
{"id": "theo_alesi", "name": "Theo Alesi", "specialization": "Finance"},
{"id": "leon_alesi", "name": "Leon Alesi", "specialization": "System"},
{"id": "luna_alesi", "name": "Luna Alesi", "specialization": "Coaching"}
],
"coordination_stats": stats,
"features": {
"intent_analysis": True,
"automatic_delegation": True,
"multi_agent_workflows": True,
"real_time_coordination": True,
"task_orchestration": True
},
"timestamp": datetime.now().isoformat()
}
except Exception as e:
logger.error(f"β Multi-Agent Status Error: {e}")
raise HTTPException(status_code=500, detail=f"Status check failed: {str(e)}")
@multi_agent_router.get("/capabilities")
async def get_agent_capabilities(
coordinator: MultiAgentCoordinator = Depends(get_coordinator)
):
"""
Get detailed agent capabilities for intelligent task delegation
"""
try:
capabilities = {}
for agent_id, agent_caps in coordinator.agent_capabilities.items():
capabilities[agent_id] = {
"agent_name": {
"jane_alesi": "Jane Alesi - Master Coordinator",
"john_alesi": "John Alesi - Software Developer",
"lara_alesi": "Lara Alesi - Medical Expert",
"justus_alesi": "Justus Alesi - Legal Expert",
"theo_alesi": "Theo Alesi - Financial Analyst",
"leon_alesi": "Leon Alesi - System Administrator",
"luna_alesi": "Luna Alesi - Coaching Specialist"
}.get(agent_id, agent_id),
"capabilities": [
{
"name": cap.name,
"description": cap.description,
"keywords": cap.keywords,
"complexity_level": cap.complexity_level
}
for cap in agent_caps
],
"specialization": {
"jane_alesi": "Coordination & Architecture",
"john_alesi": "Software Development",
"lara_alesi": "Medical Analysis",
"justus_alesi": "Legal Compliance",
"theo_alesi": "Financial Analysis",
"leon_alesi": "System Administration",
"luna_alesi": "Coaching & Process"
}.get(agent_id, "General")
}
return {
"total_agents": len(capabilities),
"coordinator": "jane_alesi",
"specialists_count": len(capabilities) - 1,
"capabilities": capabilities,
"timestamp": datetime.now().isoformat()
}
except Exception as e:
logger.error(f"β Agent Capabilities Error: {e}")
raise HTTPException(status_code=500, detail=f"Capabilities retrieval failed: {str(e)}")
@multi_agent_router.get("/workload/{agent_id}")
async def get_agent_workload(
agent_id: str,
coordinator: MultiAgentCoordinator = Depends(get_coordinator)
):
"""
Get current workload and task statistics for a specific agent
"""
try:
workload = await coordinator.get_agent_workload(agent_id)
return workload
except Exception as e:
logger.error(f"β Agent Workload Error for {agent_id}: {e}")
raise HTTPException(status_code=500, detail=f"Workload check failed: {str(e)}") |