File size: 12,739 Bytes
88b8ba0
 
 
 
 
 
 
 
 
 
7d69dd0
88b8ba0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
379
380
381
382
383
384
385
386
387
"""
API routes for agent orchestration.
"""

from typing import Any, Dict, List, Optional
from fastapi import APIRouter, Depends, HTTPException, BackgroundTasks
from pydantic import BaseModel, Field
from uuid import uuid4

from src.core import get_logger
from src.api.auth import User
from src.api.dependencies import get_current_user
from src.services.agent_orchestrator import (
    AgentOrchestrator,
    WorkflowDefinition,
    WorkflowStep,
    OrchestrationPattern,
    get_orchestrator
)
from src.agents.deodoro import AgentContext
from src.core.exceptions import OrchestrationError


router = APIRouter()
logger = get_logger("api.orchestration")


class WorkflowStepRequest(BaseModel):
    """Request model for workflow step."""
    step_id: str
    agent_name: str
    action: str
    input_mapping: Dict[str, str] = Field(default_factory=dict)
    output_mapping: Dict[str, str] = Field(default_factory=dict)
    conditions: Dict[str, Any] = Field(default_factory=dict)
    retry_config: Dict[str, Any] = Field(default_factory=dict)
    timeout: int = 300


class WorkflowRequest(BaseModel):
    """Request model for workflow execution."""
    workflow_id: Optional[str] = None
    name: str
    pattern: str = "sequential"
    steps: List[WorkflowStepRequest]
    initial_data: Dict[str, Any]
    timeout: int = 1800


class ConditionalWorkflowRequest(BaseModel):
    """Request model for conditional workflow."""
    workflow_definition: Dict[str, Any]
    initial_data: Dict[str, Any]


class CapabilitySearchRequest(BaseModel):
    """Request model for capability search."""
    required_capabilities: List[str]
    prefer_single_agent: bool = True


@router.post("/workflows/execute")
async def execute_workflow(
    request: WorkflowRequest,
    background_tasks: BackgroundTasks,
    current_user: User = Depends(get_current_user),
    orchestrator: AgentOrchestrator = Depends(get_orchestrator)
):
    """Execute an orchestrated workflow."""
    try:
        # Create workflow definition
        workflow_def = WorkflowDefinition(
            workflow_id=request.workflow_id or str(uuid4()),
            name=request.name,
            pattern=OrchestrationPattern(request.pattern),
            steps=[
                WorkflowStep(
                    step_id=step.step_id,
                    agent_name=step.agent_name,
                    action=step.action,
                    input_mapping=step.input_mapping,
                    output_mapping=step.output_mapping,
                    conditions=step.conditions,
                    retry_config=step.retry_config,
                    timeout=step.timeout
                )
                for step in request.steps
            ],
            timeout=request.timeout
        )
        
        # Register workflow
        orchestrator._workflows[workflow_def.workflow_id] = workflow_def
        
        # Create context
        context = AgentContext(
            investigation_id=str(uuid4()),
            user_id=current_user.id,
            session_id=str(uuid4()),
            metadata={
                "workflow_id": workflow_def.workflow_id,
                "workflow_name": workflow_def.name,
                "pattern": workflow_def.pattern.value
            }
        )
        
        # Execute workflow
        result = await orchestrator.execute_workflow(
            workflow_def.workflow_id,
            request.initial_data,
            context
        )
        
        return {
            "status": "success",
            "workflow_id": workflow_def.workflow_id,
            "result": result
        }
        
    except OrchestrationError as e:
        logger.error(f"Orchestration error: {e}")
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        logger.error(f"Unexpected error in workflow execution: {e}")
        raise HTTPException(status_code=500, detail="Internal server error")


@router.post("/workflows/conditional")
async def execute_conditional_workflow(
    request: ConditionalWorkflowRequest,
    current_user: User = Depends(get_current_user),
    orchestrator: AgentOrchestrator = Depends(get_orchestrator)
):
    """Execute a conditional workflow with branching."""
    try:
        # Create context
        context = AgentContext(
            investigation_id=str(uuid4()),
            user_id=current_user.id,
            session_id=str(uuid4()),
            metadata={
                "workflow_type": "conditional",
                "workflow_definition": request.workflow_definition
            }
        )
        
        # Execute conditional workflow
        execution_path = await orchestrator.execute_conditional_workflow(
            request.workflow_definition,
            request.initial_data,
            context
        )
        
        return {
            "status": "success",
            "execution_path": execution_path,
            "total_steps": len(execution_path)
        }
        
    except Exception as e:
        logger.error(f"Error in conditional workflow: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/agents/discover")
async def discover_agents(
    current_user: User = Depends(get_current_user),
    orchestrator: AgentOrchestrator = Depends(get_orchestrator)
):
    """Discover all available agents and their capabilities."""
    try:
        agents = await orchestrator.discover_agents()
        
        # Enrich with capabilities
        enriched_agents = []
        for agent in agents:
            agent_info = {
                "name": agent["name"],
                "description": agent.get("description", ""),
                "capabilities": orchestrator._agent_capabilities.get(agent["name"], []),
                "status": agent.get("status", "available")
            }
            enriched_agents.append(agent_info)
        
        return {
            "status": "success",
            "total_agents": len(enriched_agents),
            "agents": enriched_agents
        }
        
    except Exception as e:
        logger.error(f"Error discovering agents: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/agents/find-by-capability")
async def find_agents_by_capability(
    request: CapabilitySearchRequest,
    current_user: User = Depends(get_current_user),
    orchestrator: AgentOrchestrator = Depends(get_orchestrator)
):
    """Find agents with specific capabilities."""
    try:
        # Find agents for each capability
        capability_matches = {}
        for capability in request.required_capabilities:
            matching_agents = await orchestrator.find_agents_with_capability(capability)
            capability_matches[capability] = matching_agents
        
        # Find agents that have all required capabilities
        all_agents = set()
        for agents in capability_matches.values():
            for agent in agents:
                all_agents.add(agent["name"])
        
        # Filter agents that have all capabilities
        qualified_agents = []
        for agent_name in all_agents:
            agent_capabilities = orchestrator._agent_capabilities.get(agent_name, [])
            if all(cap in agent_capabilities for cap in request.required_capabilities):
                qualified_agents.append({
                    "name": agent_name,
                    "capabilities": agent_capabilities,
                    "match_score": len(set(request.required_capabilities) & set(agent_capabilities))
                })
        
        # Sort by match score
        qualified_agents.sort(key=lambda x: x["match_score"], reverse=True)
        
        # If prefer single agent, return the best match
        if request.prefer_single_agent and qualified_agents:
            best_agent = await orchestrator.select_best_agent(request.required_capabilities)
            return {
                "status": "success",
                "best_match": {
                    "name": best_agent.name if best_agent else None,
                    "capabilities": orchestrator._agent_capabilities.get(best_agent.name, []) if best_agent else []
                },
                "all_matches": qualified_agents
            }
        
        return {
            "status": "success",
            "matching_agents": qualified_agents,
            "total_matches": len(qualified_agents)
        }
        
    except Exception as e:
        logger.error(f"Error finding agents: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/orchestrator/stats")
async def get_orchestrator_stats(
    current_user: User = Depends(get_current_user),
    orchestrator: AgentOrchestrator = Depends(get_orchestrator)
):
    """Get orchestrator statistics and performance metrics."""
    try:
        stats = await orchestrator.get_stats()
        return {
            "status": "success",
            "statistics": stats
        }
        
    except Exception as e:
        logger.error(f"Error getting orchestrator stats: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/workflows/patterns/{pattern}")
async def execute_pattern_workflow(
    pattern: str,
    data: Dict[str, Any],
    current_user: User = Depends(get_current_user),
    orchestrator: AgentOrchestrator = Depends(get_orchestrator)
):
    """Execute a specific orchestration pattern."""
    try:
        # Validate pattern
        try:
            pattern_enum = OrchestrationPattern(pattern)
        except ValueError:
            raise HTTPException(status_code=400, detail=f"Invalid pattern: {pattern}")
        
        # Create a simple workflow for the pattern
        if pattern == "map_reduce":
            steps = [
                WorkflowStep(
                    step_id="map",
                    agent_name="zumbi",
                    action="analyze"
                ),
                WorkflowStep(
                    step_id="reduce",
                    agent_name="anita",
                    action="aggregate"
                )
            ]
        elif pattern == "fan_out_fan_in":
            steps = [
                WorkflowStep(
                    step_id="analyze1",
                    agent_name="zumbi",
                    action="analyze"
                ),
                WorkflowStep(
                    step_id="analyze2",
                    agent_name="maria_quiteria",
                    action="security_audit"
                ),
                WorkflowStep(
                    step_id="analyze3",
                    agent_name="bonifacio",
                    action="policy_analysis"
                )
            ]
        else:
            steps = [
                WorkflowStep(
                    step_id="step1",
                    agent_name="zumbi",
                    action="analyze"
                )
            ]
        
        workflow = WorkflowDefinition(
            workflow_id=f"{pattern}_{uuid4()}",
            name=f"{pattern} workflow",
            pattern=pattern_enum,
            steps=steps
        )
        
        orchestrator._workflows[workflow.workflow_id] = workflow
        
        # Create context
        context = AgentContext(
            investigation_id=str(uuid4()),
            user_id=current_user.id,
            session_id=str(uuid4()),
            metadata={"pattern": pattern}
        )
        
        # Execute
        result = await orchestrator.execute_workflow(
            workflow.workflow_id,
            data,
            context
        )
        
        return {
            "status": "success",
            "pattern": pattern,
            "result": result
        }
        
    except Exception as e:
        logger.error(f"Error executing pattern workflow: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/workflows")
async def list_workflows(
    current_user: User = Depends(get_current_user),
    orchestrator: AgentOrchestrator = Depends(get_orchestrator)
):
    """List all registered workflows."""
    try:
        workflows = []
        for workflow_id, workflow in orchestrator._workflows.items():
            workflows.append({
                "workflow_id": workflow_id,
                "name": workflow.name,
                "pattern": workflow.pattern.value,
                "steps": len(workflow.steps),
                "timeout": workflow.timeout
            })
        
        return {
            "status": "success",
            "total_workflows": len(workflows),
            "workflows": workflows
        }
        
    except Exception as e:
        logger.error(f"Error listing workflows: {e}")
        raise HTTPException(status_code=500, detail=str(e))