File size: 36,419 Bytes
66dbebd
7506c11
 
66dbebd
 
 
7506c11
 
 
66dbebd
 
 
 
7506c11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66dbebd
7506c11
66dbebd
7506c11
66dbebd
7506c11
 
 
 
66dbebd
7506c11
 
 
 
 
66dbebd
7506c11
 
 
66dbebd
7506c11
 
 
 
66dbebd
7506c11
 
55f436b
7506c11
 
66dbebd
 
7506c11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66dbebd
 
7506c11
 
66dbebd
7506c11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66dbebd
7506c11
 
 
66dbebd
7506c11
 
 
 
66dbebd
7506c11
 
 
55f436b
66dbebd
7506c11
 
 
 
 
 
 
 
 
 
66dbebd
 
7506c11
 
 
 
66dbebd
7506c11
 
 
5a6a2cc
7506c11
 
 
 
fa57725
7506c11
 
 
 
 
5a6a2cc
7506c11
 
 
 
 
 
 
fa57725
 
7506c11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7dd9795
7506c11
 
fa57725
7dd9795
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f89bd21
 
7506c11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fa57725
7506c11
fa57725
7506c11
 
 
fa57725
 
7506c11
 
 
 
fa57725
7506c11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f89bd21
 
7506c11
 
66dbebd
7506c11
 
 
 
 
 
 
 
 
 
 
 
66dbebd
7506c11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66dbebd
7506c11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66dbebd
7506c11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66dbebd
7506c11
66dbebd
7506c11
 
 
 
 
66dbebd
7506c11
 
66dbebd
7506c11
 
 
7dd9795
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55f436b
7506c11
 
55f436b
7506c11
55f436b
7506c11
55f436b
7506c11
55f436b
7506c11
55f436b
7506c11
 
 
f89bd21
 
 
 
 
 
 
7506c11
 
55f436b
f89bd21
93f44e2
f89bd21
 
 
93f44e2
f89bd21
 
 
93f44e2
 
 
f89bd21
 
 
 
 
93f44e2
 
 
f89bd21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7506c11
 
a814110
f89bd21
 
 
 
 
 
 
 
7506c11
a814110
f89bd21
7506c11
 
a814110
f89bd21
 
7506c11
f89bd21
 
 
 
 
7506c11
f89bd21
 
 
a814110
7506c11
 
f89bd21
7506c11
f89bd21
 
7506c11
f89bd21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66dbebd
7506c11
 
 
 
 
 
 
 
 
 
55f436b
66dbebd
 
 
 
 
 
 
 
 
 
 
 
 
 
7506c11
66dbebd
 
7506c11
66dbebd
 
 
 
7506c11
 
 
 
 
66dbebd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7506c11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66dbebd
 
7506c11
 
 
 
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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
"""
Enhanced Synthesis Agent with Expert Consultant Assignment
Based on skill probability scores from Skills Identification Agent
"""

import logging
import json
from typing import Dict, List, Any, Optional, Tuple
from datetime import datetime
import re

logger = logging.getLogger(__name__)


class ExpertConsultantAssigner:
    """
    Assigns expert consultant profiles based on skill probabilities
    and generates weighted expertise for response synthesis
    """
    
    # Expert consultant profiles with skill mappings
    EXPERT_PROFILES = {
        "data_analysis": {
            "title": "Senior Data Analytics Consultant",
            "expertise": ["Statistical Analysis", "Data Visualization", "Business Intelligence", "Predictive Modeling"],
            "background": "15+ years in data science across finance, healthcare, and tech sectors",
            "style": "methodical, evidence-based, quantitative reasoning"
        },
        "technical_programming": {
            "title": "Principal Software Engineering Consultant", 
            "expertise": ["Full-Stack Development", "System Architecture", "DevOps", "Code Optimization"],
            "background": "20+ years leading technical teams at Fortune 500 companies",
            "style": "practical, solution-oriented, best practices focused"
        },
        "project_management": {
            "title": "Strategic Project Management Consultant",
            "expertise": ["Agile/Scrum", "Risk Management", "Stakeholder Communication", "Resource Optimization"],
            "background": "12+ years managing complex enterprise projects across industries",
            "style": "structured, process-driven, outcome-focused"
        },
        "financial_analysis": {
            "title": "Executive Financial Strategy Consultant",
            "expertise": ["Financial Modeling", "Investment Analysis", "Risk Assessment", "Corporate Finance"],
            "background": "18+ years in investment banking and corporate finance advisory",
            "style": "analytical, risk-aware, ROI-focused"
        },
        "digital_marketing": {
            "title": "Chief Marketing Strategy Consultant",
            "expertise": ["Digital Campaign Strategy", "Customer Analytics", "Brand Development", "Growth Hacking"],
            "background": "14+ years scaling marketing for startups to enterprise clients",
            "style": "creative, data-driven, customer-centric"
        },
        "business_consulting": {
            "title": "Senior Management Consultant",
            "expertise": ["Strategic Planning", "Organizational Development", "Process Improvement", "Change Management"],
            "background": "16+ years at top-tier consulting firms (McKinsey, BCG equivalent)",
            "style": "strategic, framework-driven, holistic thinking"
        },
        "cybersecurity": {
            "title": "Chief Information Security Consultant",
            "expertise": ["Threat Assessment", "Security Architecture", "Compliance", "Incident Response"],
            "background": "12+ years protecting critical infrastructure across government and private sectors",
            "style": "security-first, compliance-aware, risk mitigation focused"
        },
        "healthcare_technology": {
            "title": "Healthcare Innovation Consultant",
            "expertise": ["Health Informatics", "Telemedicine", "Medical Device Integration", "HIPAA Compliance"],
            "background": "10+ years implementing healthcare technology solutions",
            "style": "patient-centric, regulation-compliant, evidence-based"
        },
        "educational_technology": {
            "title": "Learning Technology Strategy Consultant",
            "expertise": ["Instructional Design", "EdTech Implementation", "Learning Analytics", "Curriculum Development"],
            "background": "13+ years transforming educational experiences through technology",
            "style": "learner-focused, pedagogy-driven, accessibility-minded"
        },
        "environmental_science": {
            "title": "Sustainability Strategy Consultant",
            "expertise": ["Environmental Impact Assessment", "Carbon Footprint Analysis", "Green Technology", "ESG Reporting"],
            "background": "11+ years driving environmental initiatives for corporations",
            "style": "sustainability-focused, data-driven, long-term thinking"
        }
    }
    
    def assign_expert_consultant(self, skill_probabilities: Dict[str, float]) -> Dict[str, Any]:
        """
        Create ultra-expert profile combining all relevant consultants
        
        Args:
            skill_probabilities: Dict mapping skill categories to probability scores (0.0-1.0)
            
        Returns:
            Dict containing ultra-expert profile with combined expertise
        """
        if not skill_probabilities:
            return self._get_default_consultant()
        
        # Calculate weighted scores for available expert profiles
        expert_scores = {}
        total_weight = 0
        
        for skill, probability in skill_probabilities.items():
            if skill in self.EXPERT_PROFILES and probability >= 0.2:  # 20% threshold
                expert_scores[skill] = probability
                total_weight += probability
        
        if not expert_scores:
            return self._get_default_consultant()
        
        # Create ultra-expert combining all relevant consultants
        ultra_expert = self._create_ultra_expert(expert_scores, total_weight)
        
        return {
            "assigned_consultant": ultra_expert,
            "expertise_weights": expert_scores,
            "total_weight": total_weight,
            "assignment_rationale": self._generate_ultra_expert_rationale(expert_scores, total_weight)
        }
    
    def _get_default_consultant(self) -> Dict[str, Any]:
        """Default consultant for general inquiries"""
        return {
            "assigned_consultant": {
                "primary_expertise": "business_consulting",
                "title": "Senior Management Consultant",
                "expertise": ["Strategic Planning", "Problem Solving", "Analysis", "Communication"],
                "background": "Generalist consultant with broad industry experience",
                "style": "balanced, analytical, comprehensive",
                "secondary_expertise": [],
                "confidence_score": 0.7
            },
            "expertise_weights": {"business_consulting": 0.7},
            "total_weight": 0.7,
            "assignment_rationale": "Default consultant assigned for general business inquiry"
        }
    
    def _create_ultra_expert(self, expert_scores: Dict[str, float], total_weight: float) -> Dict[str, Any]:
        """Create ultra-expert profile combining all relevant consultants"""
        
        # Sort skills by probability (highest first)
        sorted_skills = sorted(expert_scores.items(), key=lambda x: x[1], reverse=True)
        
        # Combine all expertise areas with weights
        combined_expertise = []
        combined_background_elements = []
        combined_style_elements = []
        
        for skill, weight in sorted_skills:
            if skill in self.EXPERT_PROFILES:
                profile = self.EXPERT_PROFILES[skill]
                
                # Weight-based contribution
                contribution_ratio = weight / total_weight
                
                # Add expertise areas with weight indicators
                for expertise in profile["expertise"]:
                    weighted_expertise = f"{expertise} (Weight: {contribution_ratio:.1%})"
                    combined_expertise.append(weighted_expertise)
                
                # Extract background years and combine
                background = profile["background"]
                combined_background_elements.append(f"{background} [{skill}]")
                
                # Combine style elements
                style_parts = [s.strip() for s in profile["style"].split(",")]
                combined_style_elements.extend(style_parts)
        
        # Create ultra-expert title combining top skills
        top_skills = [skill.replace("_", " ").title() for skill, _ in sorted_skills[:3]]
        ultra_title = f"Visionary Ultra-Expert: {' + '.join(top_skills)} Integration Specialist"
        
        # Combine backgrounds into comprehensive experience
        total_years = sum([self._extract_years_from_background(bg) for bg in combined_background_elements])
        ultra_background = f"{total_years}+ years combined experience across {len(sorted_skills)} domains: " + \
                          "; ".join(combined_background_elements[:3])  # Limit for readability
        
        # Create unified style combining all approaches
        unique_styles = list(set(combined_style_elements))
        ultra_style = ", ".join(unique_styles[:6])  # Top 6 style elements
        
        return {
            "primary_expertise": "ultra_expert_integration",
            "title": ultra_title,
            "expertise": combined_expertise,
            "background": ultra_background,
            "style": ultra_style,
            "domain_integration": sorted_skills,
            "confidence_score": total_weight / len(sorted_skills),  # Average confidence
            "ultra_expert": True,
            "expertise_count": len(sorted_skills),
            "total_experience_years": total_years
        }
    
    def _extract_years_from_background(self, background: str) -> int:
        """Extract years of experience from background string"""
        years_match = re.search(r'(\d+)\+?\s*years?', background.lower())
        return int(years_match.group(1)) if years_match else 10  # Default to 10 years
    
    def _generate_ultra_expert_rationale(self, expert_scores: Dict[str, float], total_weight: float) -> str:
        """Generate explanation for ultra-expert assignment"""
        sorted_skills = sorted(expert_scores.items(), key=lambda x: x[1], reverse=True)
        
        rationale_parts = [
            f"Ultra-Expert Profile combining {len(sorted_skills)} specialized domains",
            f"Total expertise weight: {total_weight:.2f} across integrated skill areas"
        ]
        
        # Add top 3 contributions
        top_contributions = []
        for skill, weight in sorted_skills[:3]:
            contribution = (weight / total_weight) * 100
            top_contributions.append(f"{skill} ({weight:.1%}, {contribution:.0f}% contribution)")
        
        rationale_parts.append(f"Primary domains: {'; '.join(top_contributions)}")
        
        if len(sorted_skills) > 3:
            additional_count = len(sorted_skills) - 3
            rationale_parts.append(f"Plus {additional_count} additional specialized areas")
        
        return " | ".join(rationale_parts)


class EnhancedSynthesisAgent:
    """
    Enhanced synthesis agent with expert consultant assignment
    Compatible with existing ResponseSynthesisAgent interface
    """
    
    def __init__(self, llm_router, agent_id: str = "RESP_SYNTH_001"):
        self.llm_router = llm_router
        self.agent_id = agent_id
        self.specialization = "Multi-source information integration and coherent response generation"
        self.expert_assigner = ExpertConsultantAssigner()
        self._current_user_input = None
        
    async def execute(self, user_input: str = None, agent_outputs: List[Dict[str, Any]] = None, 
                     context: Dict[str, Any] = None, skills_result: Dict[str, Any] = None,
                     **kwargs) -> Dict[str, Any]:
        """
        Execute synthesis with expert consultant assignment
        Compatible with both old interface (agent_outputs first) and new interface (user_input first)
        
        Args:
            user_input: Original user question
            agent_outputs: Results from other agents (can be first positional arg for compatibility)
            context: Conversation context
            skills_result: Output from skills identification agent
            
        Returns:
            Dict containing synthesized response and metadata
        """
        # Handle backward compatibility and normalize arguments
        # Case 1: First arg is agent_outputs (old interface)
        if isinstance(user_input, list) and agent_outputs is None:
            agent_outputs = user_input
            user_input = kwargs.get('user_input', '')
            context = kwargs.get('context', context)
            skills_result = kwargs.get('skills_result', skills_result)
        # Case 2: All args via kwargs
        elif user_input is None:
            user_input = kwargs.get('user_input', '')
            agent_outputs = kwargs.get('agent_outputs', agent_outputs)
            context = kwargs.get('context', context)
            skills_result = kwargs.get('skills_result', skills_result)
        
        # Ensure user_input is a string
        if not isinstance(user_input, str):
            user_input = str(user_input) if user_input else ''
        
        # Default agent_outputs to empty list and normalize format
        if agent_outputs is None:
            agent_outputs = []
        
        # Normalize agent_outputs: convert dict to list if needed
        if isinstance(agent_outputs, dict):
            # Convert dict {task_name: result} to list of dicts
            normalized_outputs = []
            for task_name, result in agent_outputs.items():
                if isinstance(result, dict):
                    # Add task name to the result dict for context
                    result_with_task = result.copy()
                    result_with_task['task_name'] = task_name
                    normalized_outputs.append(result_with_task)
                else:
                    # Wrap non-dict results
                    normalized_outputs.append({
                        'task_name': task_name,
                        'content': str(result),
                        'result': str(result)
                    })
            agent_outputs = normalized_outputs
        
        # Ensure it's a list
        if not isinstance(agent_outputs, list):
            agent_outputs = [agent_outputs] if agent_outputs else []
        
        logger.info(f"{self.agent_id} synthesizing {len(agent_outputs)} agent outputs")
        if context:
            interaction_count = len(context.get('interaction_contexts', [])) if context else 0
            logger.info(f"{self.agent_id} context has {interaction_count} interaction contexts")
            
        # STEP 1: Extract skill probabilities from skills_result
        skill_probabilities = self._extract_skill_probabilities(skills_result)
        logger.info(f"Extracted skill probabilities: {skill_probabilities}")
        
        # STEP 2: Assign expert consultant based on probabilities
        consultant_assignment = self.expert_assigner.assign_expert_consultant(skill_probabilities)
        assigned_consultant = consultant_assignment["assigned_consultant"]
        logger.info(f"Assigned consultant: {assigned_consultant['title']} ({assigned_consultant.get('primary_expertise', 'N/A')})")
        
        # STEP 3: Generate expert consultant preamble
        expert_preamble = self._generate_expert_preamble(assigned_consultant, consultant_assignment)
        
        # STEP 4: Build synthesis prompt with expert context
        synthesis_prompt = self._build_synthesis_prompt_with_expert(
            user_input=user_input,
            context=context,
            agent_outputs=agent_outputs,
            expert_preamble=expert_preamble,
            assigned_consultant=assigned_consultant
        )
        
        logger.info(f"{self.agent_id} calling LLM for response synthesis")
        
        # Call LLM with enhanced prompt
        try:
            response = await self.llm_router.route_inference(
                task_type="response_synthesis",
                prompt=synthesis_prompt,
                max_tokens=2000,
                temperature=0.7
            )
            
            # Only use fallback if LLM actually fails (returns None, empty, or invalid)
            if not response or not isinstance(response, str) or len(response.strip()) == 0:
                logger.warning(f"{self.agent_id} LLM returned empty/invalid response, using fallback")
                return self._get_fallback_response(user_input, agent_outputs, assigned_consultant)
            
            clean_response = response.strip()
            logger.info(f"{self.agent_id} received LLM response (length: {len(clean_response)})")
            
            # Build comprehensive result compatible with existing interface
            result = {
                "synthesized_response": clean_response,
                "draft_response": clean_response,
                "final_response": clean_response,  # Main response field - used by UI
                "assigned_consultant": assigned_consultant,
                "expertise_weights": consultant_assignment["expertise_weights"],
                "assignment_rationale": consultant_assignment["assignment_rationale"],
                "source_references": self._extract_source_references(agent_outputs),
                "coherence_score": 0.90,
                "improvement_opportunities": self._identify_improvements(clean_response),
                "synthesis_method": "expert_enhanced_llm",
                "agent_id": self.agent_id,
                "synthesis_quality_metrics": self._calculate_quality_metrics({"final_response": clean_response}),
                "synthesis_metadata": {
                    "agent_outputs_count": len(agent_outputs),
                    "context_interactions": len(context.get('interaction_contexts', [])) if context else 0,
                    "user_context_available": bool(context.get('user_context', '')) if context else False,
                    "expert_enhanced": True,
                    "processing_timestamp": datetime.now().isoformat()
                }
            }
            
            # Add intent alignment if available
            intent_info = self._extract_intent_info(agent_outputs)
            if intent_info:
                result["intent_alignment"] = self._check_intent_alignment(result, intent_info)
            
            return result
            
        except Exception as e:
            logger.error(f"{self.agent_id} synthesis failed: {str(e)}", exc_info=True)
            return self._get_fallback_response(user_input, agent_outputs, assigned_consultant)
    
    def _extract_skill_probabilities(self, skills_result: Dict[str, Any]) -> Dict[str, float]:
        """Extract skill probabilities from skills identification result"""
        if not skills_result:
            return {}
        
        # Check for skill_classification structure
        skill_classification = skills_result.get('skill_classification', {})
        if 'skill_probabilities' in skill_classification:
            return skill_classification['skill_probabilities']
        
        # Check for direct skill_probabilities
        if 'skill_probabilities' in skills_result:
            return skills_result['skill_probabilities']
        
        # Extract from identified_skills if structured differently
        identified_skills = skills_result.get('identified_skills', [])
        if isinstance(identified_skills, list):
            probabilities = {}
            for skill in identified_skills:
                if isinstance(skill, dict) and 'skill' in skill and 'probability' in skill:
                    # Map skill name to expert profile name if needed
                    skill_name = skill['skill']
                    probability = skill['probability']
                    probabilities[skill_name] = probability
                elif isinstance(skill, dict) and 'category' in skill:
                    skill_name = skill['category']
                    probability = skill.get('probability', skill.get('confidence', 0.5))
                    probabilities[skill_name] = probability
            return probabilities
        
        return {}
    
    def _generate_expert_preamble(self, assigned_consultant: Dict[str, Any], 
                                 consultant_assignment: Dict[str, Any]) -> str:
        """Generate expert consultant preamble for LLM prompt"""
        
        if assigned_consultant.get('ultra_expert'):
            # Ultra-expert preamble
            preamble = f"""You are responding as a {assigned_consultant['title']} - an unprecedented combination of industry-leading experts.

ULTRA-EXPERT PROFILE:
- Integrated Expertise: {assigned_consultant['expertise_count']} specialized domains
- Combined Experience: {assigned_consultant['total_experience_years']}+ years across multiple industries
- Integration Approach: Cross-domain synthesis with deep specialization
- Response Style: {assigned_consultant['style']}

DOMAIN INTEGRATION: {', '.join([f"{skill} ({weight:.1%})" for skill, weight in assigned_consultant['domain_integration']])}

SPECIALIZED EXPERTISE AREAS:
{chr(10).join([f"• {expertise}" for expertise in assigned_consultant['expertise'][:8]])}

ASSIGNMENT RATIONALE: {consultant_assignment['assignment_rationale']}

KNOWLEDGE DEPTH REQUIREMENT: 
- Provide insights equivalent to a visionary thought leader combining expertise from multiple domains
- Synthesize knowledge across {assigned_consultant['expertise_count']} specialization areas
- Apply interdisciplinary thinking and cross-domain innovation
- Leverage combined {assigned_consultant['total_experience_years']}+ years of integrated experience

ULTRA-EXPERT RESPONSE GUIDELINES:
- Draw from extensive cross-domain experience and pattern recognition
- Provide multi-perspective analysis combining different expert viewpoints
- Include interdisciplinary frameworks and innovative approaches
- Acknowledge complexity while providing actionable, synthesized recommendations
- Balance broad visionary thinking with deep domain-specific insights
- Use integrative problem-solving that spans multiple expertise areas
"""
        else:
            # Standard single expert preamble
            preamble = f"""You are responding as a {assigned_consultant['title']} with the following profile:

EXPERTISE PROFILE:
- Primary Expertise: {assigned_consultant['primary_expertise']}
- Core Skills: {', '.join(assigned_consultant['expertise'])}
- Background: {assigned_consultant['background']}
- Response Style: {assigned_consultant['style']}

ASSIGNMENT RATIONALE: {consultant_assignment['assignment_rationale']}

EXPERTISE WEIGHTS: {', '.join([f"{skill}: {weight:.1%}" for skill, weight in consultant_assignment['expertise_weights'].items()])}

"""
            
            if assigned_consultant.get('secondary_expertise'):
                preamble += f"SECONDARY EXPERTISE: {', '.join(assigned_consultant['secondary_expertise'])}\n"
            
            preamble += f"""
KNOWLEDGE DEPTH REQUIREMENT: Provide insights equivalent to a highly experienced, industry-leading {assigned_consultant['title']} with deep domain expertise and practical experience.

RESPONSE GUIDELINES:
- Draw from extensive practical experience in your field
- Provide industry-specific insights and best practices  
- Include relevant frameworks, methodologies, or tools
- Acknowledge complexity while remaining actionable
- Balance theoretical knowledge with real-world application
"""
        
        return preamble
    
    def _build_synthesis_prompt_with_expert(self, user_input: str, context: Dict[str, Any],
                                          agent_outputs: List[Dict[str, Any]], 
                                          expert_preamble: str,
                                          assigned_consultant: Dict[str, Any]) -> str:
        """Build synthesis prompt with expert consultant context"""
        
        # Build context section with summarization for long conversations
        context_section = self._build_context_section(context)
        
        # Build agent outputs section if any
        agent_outputs_section = ""
        if agent_outputs:
            # Handle both dict and list formats
            if isinstance(agent_outputs, dict):
                # Convert dict to list format
                outputs_list = []
                for task_name, result in agent_outputs.items():
                    if isinstance(result, dict):
                        outputs_list.append(result)
                    else:
                        # Wrap string/non-dict results in dict format
                        outputs_list.append({
                            'task': task_name,
                            'content': str(result),
                            'result': str(result)
                        })
                agent_outputs = outputs_list
            
            # Ensure it's a list now
            if isinstance(agent_outputs, list):
                agent_outputs_section = f"\n\nAgent Analysis Results:\n"
                for i, output in enumerate(agent_outputs, 1):
                    # Handle both dict and string outputs
                    if isinstance(output, dict):
                        output_text = output.get('content') or output.get('result') or output.get('final_response') or str(output)
                    else:
                        # If output is a string or other type
                        output_text = str(output)
                    agent_outputs_section += f"Agent {i}: {output_text}\n"
            else:
                # Fallback for unexpected types
                agent_outputs_section = f"\n\nAgent Analysis Results:\n{str(agent_outputs)}\n"
        
        # Construct full prompt
        prompt = f"""{expert_preamble}

User Question: {user_input}

{context_section}{agent_outputs_section}

Instructions: Provide a comprehensive, helpful response that directly addresses the question from your expert perspective. If there's conversation context, use it to answer the current question appropriately. Be detailed, informative, and leverage your specialized expertise in {assigned_consultant.get('primary_expertise', 'general consulting')}.

Response:"""
        
        return prompt
    
    def _build_context_section(self, context: Dict[str, Any]) -> str:
        """Build context section with summarization for long conversations
        
        Uses Context Manager structure:
        - combined_context: Pre-formatted context string (preferred)
        - interaction_contexts: List of interaction summaries with 'summary' and 'timestamp'
        - user_context: User persona summary string
        """
        if not context:
            return ""
        
        # Prefer combined_context if available (pre-formatted by Context Manager)
        # combined_context includes Session Context, User Context, and Interaction Contexts
        combined_context = context.get('combined_context', '')
        if combined_context:
            # Use the pre-formatted context from Context Manager
            # It already includes Session Context, User Context, and Interaction Contexts formatted
            return f"\n\nConversation Context:\n{combined_context}"
        
        # Fallback: Build from individual components if combined_context not available
        # All components are from cache
        session_context = context.get('session_context', {})
        session_summary = session_context.get('summary', '') if isinstance(session_context, dict) else ""
        interaction_contexts = context.get('interaction_contexts', [])
        user_context = context.get('user_context', '')
        
        context_section = ""
        
        # Add session context if available (from cache)
        if session_summary:
            context_section += f"\n\nSession Context (Session Summary):\n{session_summary[:500]}...\n"
        # Add user context if available
        if user_context:
            context_section += f"\n\nUser Context (Persona Summary):\n{user_context[:500]}...\n"
        
        # Add interaction contexts
        if interaction_contexts:
            if len(interaction_contexts) <= 8:
                # Show all interaction summaries for short conversations
                context_section += "\n\nPrevious Conversation Summary:\n"
                for i, ic in enumerate(interaction_contexts, 1):
                    summary = ic.get('summary', '')
                    if summary:
                        context_section += f"  {i}. {summary}\n"
            else:
                # Summarize older interactions, show recent ones
                recent_contexts = interaction_contexts[-8:]  # Last 8 interactions
                older_contexts = interaction_contexts[:-8]   # Everything before last 8
                
                # Create summary of older interactions
                summary = self._summarize_interaction_contexts(older_contexts)
                
                context_section += f"\n\nConversation Summary (earlier context):\n{summary}\n\nRecent Conversation:\n"
                
                for i, ic in enumerate(recent_contexts, 1):
                    summary_text = ic.get('summary', '')
                    if summary_text:
                        context_section += f"  {i}. {summary_text}\n"
        
        return context_section
    
    def _summarize_interaction_contexts(self, interaction_contexts: List[Dict[str, Any]]) -> str:
        """Summarize older interaction contexts to preserve key context
        
        Uses Context Manager structure where interaction_contexts contains:
        - summary: 50-token interaction summary string
        - timestamp: Interaction timestamp
        """
        if not interaction_contexts:
            return "No prior context."
        
        # Extract key topics and themes from summaries
        topics = []
        key_points = []
        
        for ic in interaction_contexts:
            summary = ic.get('summary', '')
            
            if summary:
                # Extract topics from summary (simple keyword extraction)
                # Summaries are already condensed, so extract meaningful terms
                words = summary.lower().split()
                key_terms = [word for word in words if len(word) > 4][:3]
                topics.extend(key_terms)
                
                # Use summary as key point (already a summary)
                key_points.append(summary[:150])
        
        # Build summary
        unique_topics = list(set(topics))[:5]  # Top 5 unique topics
        recent_points = key_points[-5:]  # Last 5 key points
        
        summary_text = f"Topics discussed: {', '.join(unique_topics) if unique_topics else 'General discussion'}\n"
        summary_text += f"Key points: {' | '.join(recent_points) if recent_points else 'No specific points'}"
        
        return summary_text
    
    def _summarize_interactions(self, interactions: List[Dict[str, Any]]) -> str:
        """Legacy method for backward compatibility - delegates to _summarize_interaction_contexts"""
        # Convert old format to new format if needed
        if interactions and 'summary' in interactions[0]:
            # Already in new format
            return self._summarize_interaction_contexts(interactions)
        else:
            # Old format - convert
            interaction_contexts = []
            for interaction in interactions:
                user_input = interaction.get('user_input', '')
                assistant_response = interaction.get('assistant_response') or interaction.get('response', '')
                # Create a simple summary
                summary = f"User asked: {user_input[:100]}..." if user_input else ""
                if summary:
                    interaction_contexts.append({'summary': summary})
            return self._summarize_interaction_contexts(interaction_contexts)
    
    def _extract_intent_info(self, agent_outputs: List[Dict[str, Any]]) -> Dict[str, Any]:
        """Extract intent information from agent outputs"""
        for output in agent_outputs:
            if 'primary_intent' in output:
                return {
                    'primary_intent': output['primary_intent'],
                    'confidence': output.get('confidence_scores', {}).get(output['primary_intent'], 0.5),
                    'source_agent': output.get('agent_id', 'unknown')
                }
        return None
    
    def _extract_source_references(self, agent_outputs: List[Dict[str, Any]]) -> List[str]:
        """Extract source references from agent outputs"""
        sources = []
        for output in agent_outputs:
            agent_id = output.get('agent_id', 'unknown')
            sources.append(agent_id)
        return list(set(sources))  # Remove duplicates
    
    def _calculate_quality_metrics(self, synthesis_result: Dict[str, Any]) -> Dict[str, Any]:
        """Calculate quality metrics for synthesis"""
        response = synthesis_result.get('final_response', '')
        
        return {
            "length": len(response),
            "word_count": len(response.split()) if response else 0,
            "coherence_score": synthesis_result.get('coherence_score', 0.7),
            "source_count": len(synthesis_result.get('source_references', [])),
            "has_structured_elements": bool(re.search(r'[•\d+\.]', response)) if response else False
        }
    
    def _check_intent_alignment(self, synthesis_result: Dict[str, Any], intent_info: Dict[str, Any]) -> Dict[str, Any]:
        """Check if synthesis aligns with detected intent"""
        # Calculate alignment based on intent confidence and response quality
        intent_confidence = intent_info.get('confidence', 0.5)
        coherence_score = synthesis_result.get('coherence_score', 0.7)
        # Alignment is average of intent confidence and coherence
        alignment_score = (intent_confidence + coherence_score) / 2.0
        
        return {
            "intent_detected": intent_info.get('primary_intent'),
            "alignment_score": alignment_score,
            "alignment_verified": alignment_score > 0.7
        }
    
    def _identify_improvements(self, response: str) -> List[str]:
        """Identify opportunities to improve the response"""
        improvements = []
        
        if len(response) < 50:
            improvements.append("Could be more detailed")
        
        if "?" not in response and len(response.split()) < 100:
            improvements.append("Consider adding examples")
        
        return improvements
    
    def _get_fallback_response(self, user_input: str, agent_outputs: List[Dict[str, Any]], 
                               assigned_consultant: Dict[str, Any]) -> Dict[str, Any]:
        """Provide fallback response when synthesis fails (LLM API failure only)"""
        # Only use fallback when LLM API actually fails - not as default
        if user_input:
            fallback_text = f"Thank you for your question: '{user_input}'. I'm processing your request and will provide a detailed response shortly."
        else:
            fallback_text = "I apologize, but I encountered an issue processing your request. Please try again."
        
        return {
            "synthesized_response": fallback_text,
            "draft_response": fallback_text,
            "final_response": fallback_text,
            "assigned_consultant": assigned_consultant,
            "source_references": self._extract_source_references(agent_outputs),
            "coherence_score": 0.5,
            "improvement_opportunities": ["LLM API error - fallback activated"],
            "synthesis_method": "expert_enhanced_fallback",
            "agent_id": self.agent_id,
            "synthesis_quality_metrics": self._calculate_quality_metrics({"final_response": fallback_text}),
            "error": True,
            "synthesis_metadata": {"expert_enhanced": True, "error": True, "llm_api_failed": True}
        }


# Backward compatibility: ResponseSynthesisAgent is now EnhancedSynthesisAgent
ResponseSynthesisAgent = EnhancedSynthesisAgent


# Factory function for compatibility
def create_synthesis_agent(llm_router) -> EnhancedSynthesisAgent:
    """Factory function to create enhanced synthesis agent"""
    return EnhancedSynthesisAgent(llm_router)