File size: 12,325 Bytes
e4d2119
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Multi-Agent Orchestrator for LoL Coach
Coordinates multiple specialized agents to handle complex queries.
"""

import logging
from typing import List, Dict, Any, Optional
from dataclasses import dataclass
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from specialized_agents import BaseLoLAgent

# Setup logging
logger = logging.getLogger(__name__)


@dataclass
class AgentTask:
    """Represents a task assigned to a specific agent."""
    agent_name: str
    task_description: str
    priority: int = 1  # 1=highest, higher numbers = lower priority
    dependencies: List[str] = None  # Tasks that must complete first
    
    def __post_init__(self):
        if self.dependencies is None:
            self.dependencies = []


@dataclass
class AgentResponse:
    """Response from an agent."""
    agent_name: str
    task_description: str
    response: str
    success: bool = True
    error: Optional[str] = None


class MultiAgentOrchestrator:
    """
    Orchestrates multiple specialized agents to handle complex queries
    that require expertise from multiple domains.
    """
    
    def __init__(
        self,
        llm: ChatOpenAI,
        agents: Dict[str, BaseLoLAgent],
        max_agent_calls: int = 5
    ):
        self.llm = llm
        self.agents = agents
        self.max_agent_calls = max_agent_calls
        
        self.planning_prompt = ChatPromptTemplate.from_messages([
            ("system", """You are an orchestrator for a multi-agent League of Legends coaching system.

Available Agents:
- match_analyzer: Analyzes match history and performance
- build_advisor: Recommends builds, runes, and champions
- video_guide: Finds YouTube tutorials and guides
- knowledge_base: Explains game concepts and terminology

Your job is to break down complex user queries into specific tasks for each agent.

Guidelines:
1. Identify which agents are needed
2. Create specific, focused tasks for each agent
3. Consider task dependencies (some tasks need others to complete first)
4. Keep tasks simple and focused
5. Aim for 2-4 agent calls maximum

For example, "I'm losing as Jinx, help me improve" might need:
1. match_analyzer: "Analyze recent Jinx matches and identify performance issues"
2. build_advisor: "Recommend optimal Jinx builds and runes"
3. video_guide: "Find Jinx improvement guides and tutorials"

Return a JSON array of tasks with: agent_name, task_description, priority (1-5, 1=highest)"""),
            ("human", "{query}")
        ])
    
    def plan_tasks(self, query: str) -> List[AgentTask]:
        """
        Plan which agents to call and what tasks to assign them.
        
        Args:
            query: Complex user query requiring multiple agents
            
        Returns:
            List of AgentTask objects
        """
        logger.info(f"Orchestrator planning for query: {query[:100]}...")
        print(f"\n๐ŸŽญ Orchestrator Planning:")
        print(f"   Query: {query}")
        
        try:
            # Use LLM to plan tasks
            chain = self.planning_prompt | self.llm
            response = chain.invoke({"query": query})
            
            # For now, simple heuristic-based planning
            # (In production, parse LLM JSON response)
            tasks = self._heuristic_planning(query)
            
            logger.info(f"Planned {len(tasks)} tasks for orchestration")
            print(f"   ๐Ÿ“‹ Planned {len(tasks)} tasks:")
            for i, task in enumerate(tasks, 1):
                print(f"      {i}. [{task.agent_name}] {task.task_description[:60]}...")
            
            return tasks
            
        except Exception as e:
            logger.error(f"Planning failed: {str(e)}", exc_info=True)
            # Fallback: create a single task for match analyzer
            return [AgentTask(
                agent_name="match_analyzer",
                task_description=query,
                priority=1
            )]
    
    def _heuristic_planning(self, query: str) -> List[AgentTask]:
        """
        Simple heuristic-based task planning.
        Replace with LLM-based planning in production.
        """
        query_lower = query.lower()
        tasks = []
        
        # Check for pregame/draft strategy needs (check this first as it's pre-game specific)
        if any(word in query_lower for word in [
            "ban", "pick", "select", "draft", "champion select", "team comp",
            "counter pick", "who should i", "what champion", "composition"
        ]):
            tasks.append(AgentTask(
                agent_name="pregame_agent",
                task_description=f"Provide champion select and draft strategy for: {query}",
                priority=1
            ))
        
        # Check for match analysis needs
        if any(word in query_lower for word in [
            "match", "game", "losing", "winning", "performance", "recent", "history"
        ]):
            tasks.append(AgentTask(
                agent_name="match_analyzer",
                task_description=f"Analyze recent match performance related to: {query}",
                priority=1
            ))
        
        # Check for build advice needs
        if any(word in query_lower for word in [
            "build", "items", "rune", "champion", "counter", "what should i"
        ]) and "ban" not in query_lower and "pick" not in query_lower:
            tasks.append(AgentTask(
                agent_name="build_advisor",
                task_description=f"Provide build and champion recommendations for: {query}",
                priority=2
            ))
        
        # Check for video guide needs
        if any(word in query_lower for word in [
            "video", "guide", "tutorial", "learn", "how to", "show me", "watch"
        ]):
            tasks.append(AgentTask(
                agent_name="video_guide",
                task_description=f"Find relevant video guides for: {query}",
                priority=3
            ))
        
        # Check for knowledge/explanation needs
        if any(word in query_lower for word in [
            "what is", "explain", "mean", "how does", "why", "concept"
        ]):
            tasks.append(AgentTask(
                agent_name="knowledge_base",
                task_description=f"Explain concepts related to: {query}",
                priority=2
            ))
        
        # If no specific tasks identified, use all agents
        if not tasks:
            tasks = [
                AgentTask("match_analyzer", f"Analyze relevant matches for: {query}", 1),
                AgentTask("build_advisor", f"Provide recommendations for: {query}", 2),
                AgentTask("video_guide", f"Find helpful guides for: {query}", 3)
            ]
        
        # Sort by priority
        tasks.sort(key=lambda t: t.priority)
        
        # Limit to max_agent_calls
        return tasks[:self.max_agent_calls]
    
    def execute_tasks(
        self,
        tasks: List[AgentTask],
        thread_id: str = "orchestrator"
    ) -> List[AgentResponse]:
        """
        Execute all planned tasks using the appropriate agents.
        
        Args:
            tasks: List of tasks to execute
            thread_id: Thread ID for agent memory
            
        Returns:
            List of AgentResponse objects
        """
        responses = []
        
        print(f"\n๐Ÿ”„ Executing Tasks:")
        
        for i, task in enumerate(tasks, 1):
            agent = self.agents.get(task.agent_name)
            
            if not agent:
                print(f"   โŒ Agent '{task.agent_name}' not found, skipping")
                responses.append(AgentResponse(
                    agent_name=task.agent_name,
                    task_description=task.task_description,
                    response="",
                    success=False,
                    error=f"Agent not found: {task.agent_name}"
                ))
                continue
            
            try:
                print(f"   {i}/{len(tasks)} Calling {task.agent_name}...")
                logger.info(f"Executing task {i}/{len(tasks)} on {task.agent_name}")
                response_text = agent.invoke(task.task_description, thread_id)
                
                responses.append(AgentResponse(
                    agent_name=task.agent_name,
                    task_description=task.task_description,
                    response=response_text,
                    success=True
                ))
                logger.info(f"{task.agent_name} completed successfully")
                print(f"   โœ… {task.agent_name} completed")
                
            except Exception as e:
                logger.error(f"{task.agent_name} failed: {str(e)}", exc_info=True)
                print(f"   โŒ {task.agent_name} failed: {str(e)}")
                responses.append(AgentResponse(
                    agent_name=task.agent_name,
                    task_description=task.task_description,
                    response="",
                    success=False,
                    error=str(e)
                ))
        
        return responses
    
    def synthesize_responses(
        self,
        query: str,
        responses: List[AgentResponse]
    ) -> str:
        """
        Synthesize multiple agent responses into a coherent answer.
        
        Args:
            query: Original user query
            responses: List of agent responses
            
        Returns:
            Synthesized final response
        """
        print(f"\n๐Ÿ”ฎ Synthesizing {len(responses)} responses...")
        
        # Build context from all successful responses
        context_parts = []
        for resp in responses:
            if resp.success:
                agent_icon = {
                    "match_analyzer": "๐ŸŽฏ",
                    "build_advisor": "๐Ÿ› ๏ธ",
                    "video_guide": "๐ŸŽฌ",
                    "knowledge_base": "๐Ÿ“š"
                }.get(resp.agent_name, "๐Ÿค–")
                
                context_parts.append(
                    f"{agent_icon} **{resp.agent_name.replace('_', ' ').title()}:**\n{resp.response}"
                )
        
        if not context_parts:
            return "โŒ I wasn't able to get information from any agents. Please try rephrasing your question."
        
        # Use LLM to synthesize
        synthesis_prompt = ChatPromptTemplate.from_messages([
            ("system", """You are synthesizing responses from multiple specialized agents into one coherent answer.

Your job:
1. Combine information from all agents
2. Remove redundancy
3. Create a natural, flowing response
4. Maintain all important details
5. Structure the response logically

Keep the emoji icons for each section to show which agent contributed what."""),
            ("human", """Original Query: {query}

Agent Responses:
{responses}

Synthesize these responses into one comprehensive, well-structured answer.""")
        ])
        
        chain = synthesis_prompt | self.llm
        result = chain.invoke({
            "query": query,
            "responses": "\n\n".join(context_parts)
        })
        
        return result.content
    
    def handle_query(self, query: str, thread_id: str = "orchestrator") -> str:
        """
        Handle a complex query by orchestrating multiple agents.
        
        Args:
            query: User query requiring multiple agents
            thread_id: Thread ID for agent memory
            
        Returns:
            Synthesized response from all agents
        """
        # Plan tasks
        tasks = self.plan_tasks(query)
        
        # Execute tasks
        responses = self.execute_tasks(tasks, thread_id)
        
        # Synthesize responses
        final_response = self.synthesize_responses(query, responses)
        
        return final_response


def create_orchestrator(
    llm: ChatOpenAI,
    agents: Dict[str, BaseLoLAgent]
) -> MultiAgentOrchestrator:
    """
    Create a configured multi-agent orchestrator.
    
    Args:
        llm: ChatOpenAI instance
        agents: Dictionary of specialized agents
        
    Returns:
        Configured MultiAgentOrchestrator
    """
    return MultiAgentOrchestrator(llm, agents)