<UPDATED_CODE>
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Multi-Agent Orchestration: Advanced Collaboration Patterns\n",
    "\n",
    "This notebook demonstrates sophisticated multi-agent collaboration patterns in OpenDistillery for enterprise workflow automation.\n",
    "\n",
    "## Collaboration Patterns Covered:\n",
    "1. **Hierarchical Coordination** - Manager-worker relationships\n",
    "2. **Democratic Consensus** - Voting and agreement mechanisms\n",
    "3. **Expert Routing** - Task-specific agent selection\n",
    "4. **Pipeline Processing** - Sequential workflow chains\n",
    "5. **Swarm Intelligence** - Collective problem solving\n",
    "6. **Auction-Based Assignment** - Competitive task allocation\n",
    "\n",
    "## Enterprise Use Cases:\n",
    "- Financial analysis workflows\n",
    "- Customer service automation\n",
    "- Supply chain optimization\n",
    "- Risk assessment processes"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Setup and imports\n",
    "import requests\n",
    "import json\n",
    "import time\n",
    "import asyncio\n",
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "import seaborn as sns\n",
    "import networkx as nx\n",
    "from datetime import datetime, timedelta\n",
    "from typing import Dict, List, Any, Optional\n",
    "import numpy as np\n",
    "from dataclasses import dataclass\n",
    "from enum import Enum\n",
    "\n",
    "# OpenDistillery connection\n",
    "API_BASE = \"http://localhost:8000\"\n",
    "API_KEY = \"opd_demo_enterprise_key_12345\"\n",
    "headers = {\"Authorization\": f\"Bearer {API_KEY}\", \"Content-Type\": \"application/json\"}\n",
    "\n",
    "# Configure visualization\n",
    "plt.style.use('default')\n",
    "sns.set_palette(\"husl\")\n",
    "%matplotlib inline\n",
    "\n",
    "print(\"🤖 Multi-Agent Orchestration Notebook Ready!\")\n",
    "print(f\"📅 Session: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1. Define Agent Archetypes"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class AgentArchetype(Enum):\n",
    "    MANAGER = \"manager\"\n",
    "    ANALYST = \"analyst\"\n",
    "    SPECIALIST = \"specialist\"\n",
    "    COORDINATOR = \"coordinator\"\n",
    "    VALIDATOR = \"validator\"\n",
    "    EXECUTOR = \"executor\"\n",
    "\n",
    "class CollaborationPattern(Enum):\n",
    "    HIERARCHICAL = \"hierarchical\"\n",
    "    DEMOCRATIC = \"democratic\"\n",
    "    EXPERT_ROUTING = \"expert_routing\"\n",
    "    PIPELINE = \"pipeline\"\n",
    "    SWARM = \"swarm\"\n",
    "    AUCTION = \"auction\"\n",
    "\n",
    "@dataclass\n",
    "class AgentProfile:\n",
    "    agent_id: str\n",
    "    archetype: AgentArchetype\n",
    "    specialization: str\n",
    "    capabilities: List[str]\n",
    "    experience_level: int  # 1-10\n",
    "    collaboration_score: float  # 0-1\n",
    "    cost_per_task: float\n",
    "    max_concurrent_tasks: int\n",
    "    \n",
    "# Define agent profiles for financial analysis workflow\n",
    "financial_agents = [\n",
    "    AgentProfile(\n",
    "        agent_id=\"portfolio_manager\",\n",
    "        archetype=AgentArchetype.MANAGER,\n",
    "        specialization=\"portfolio_management\",\n",
    "        capabilities=[\"strategic_planning\", \"risk_oversight\", \"decision_making\"],\n",
    "        experience_level=9,\n",
    "        collaboration_score=0.9,\n",
    "        cost_per_task=50.0,\n",
    "        max_concurrent_tasks=3\n",
    "    ),\n",
    "    AgentProfile(\n",
    "        agent_id=\"risk_analyst\",\n",
    "        archetype=AgentArchetype.ANALYST,\n",
    "        specialization=\"risk_analysis\",\n",
    "        capabilities=[\"risk_modeling\", \"scenario_analysis\", \"compliance_check\"],\n",
    "        experience_level=8,\n",
    "        collaboration_score=0.8,\n",
    "        cost_per_task=30.0,\n",
    "        max_concurrent_tasks=5\n",
    "    ),\n",
    "    AgentProfile(\n",
    "        agent_id=\"market_analyst\",\n",
    "        archetype=AgentArchetype.ANALYST,\n",
    "        specialization=\"market_analysis\",\n",
    "        capabilities=[\"market_research\", \"trend_analysis\", \"competitive_intelligence\"],\n",
    "        experience_level=7,\n",
    "        collaboration_score=0.7,\n",
    "        cost_per_task=25.0,\n",
    "        max_concurrent_tasks=6\n",
    "    ),\n",
    "    AgentProfile(\n",
    "        agent_id=\"quant_specialist\",\n",
    "        archetype=AgentArchetype.SPECIALIST,\n",
    "        specialization=\"quantitative_modeling\",\n",
    "        capabilities=[\"mathematical_modeling\", \"statistical_analysis\", \"algorithm_development\"],\n",
    "        experience_level=9,\n",
    "        collaboration_score=0.6,\n",
    "        cost_per_task=40.0,\n",
    "        max_concurrent_tasks=4\n",
    "    ),\n",
    "    AgentProfile(\n",
    "        agent_id=\"compliance_validator\",\n",
    "        archetype=AgentArchetype.VALIDATOR,\n",
    "        specialization=\"regulatory_compliance\",\n",
    "        capabilities=[\"compliance_validation\", \"regulatory_check\", \"audit_preparation\"],\n",
    "        experience_level=8,\n",
    "        collaboration_score=0.8,\n",
    "        cost_per_task=35.0,\n",
    "        max_concurrent_tasks=4\n",
    "    ),\n",
    "    AgentProfile(\n",
    "        agent_id=\"trade_executor\",\n",
    "        archetype=AgentArchetype.EXECUTOR,\n",
    "        specialization=\"trade_execution\",\n",
    "        capabilities=[\"order_execution\", \"market_timing\", \"liquidity_analysis\"],\n",
    "        experience_level=7,\n",
    "        collaboration_score=0.7,\n",
    "        cost_per_task=20.0,\n",
    "        max_concurrent_tasks=10\n",
    "    )\n",
    "]\n",
    "\n",
    "# Register agents with OpenDistillery\n",
    "def register_financial_agents():\n",
    "    \"\"\"Register all financial agents\"\"\"\n",
    "    registered_agents = []\n",
    "    \n",
    "    for agent_profile in financial_agents:\n",
    "        agent_config = {\n",
    "            \"agent_id\": agent_profile.agent_id,\n",
    "            \"agent_type\": agent_profile.archetype.value,\n",
    "            \"capabilities\": agent_profile.capabilities,\n",
    "            \"specialization\": agent_profile.specialization,\n",
    "            \"configuration\": {\n",
    "                \"experience_level\": agent_profile.experience_level,\n",
    "                \"collaboration_score\": agent_profile.collaboration_score,\n",
    "                \"cost_per_task\": agent_profile.cost_per_task,\n",
    "                \"max_concurrent_tasks\": agent_profile.max_concurrent_tasks\n",
    "            }\n",
    "        }\n",
    "        \n",
    "        response = requests.post(\n",
    "            f\"{API_BASE}/agents\",\n",
    "            headers=headers,\n",
    "            json=agent_config\n",
    "        )\n",
    "        \n",
    "        if response.status_code == 200:\n",
    "            registered_agents.append(agent_profile.agent_id)\n",
    "            print(f\"✅ Registered: {agent_profile.agent_id} ({agent_profile.archetype.value})\")\n",
    "        else:\n",
    "            print(f\"❌ Failed to register: {agent_profile.agent_id}\")\n",
    "    \n",
    "    return registered_agents\n",
    "\n",
    "# Display agent portfolio\n",
    "print(\"🏢 Financial Analysis Agent Portfolio\")\n",
    "print(\"=\" * 50)\n",
    "\n",
    "for agent in financial_agents:\n",
    "    print(f\"\\n🤖 {agent.agent_id.replace('_', ' ').title()}\")\n",
    "    print(f\"   Type: {agent.archetype.value.title()}\")\n",
    "    print(f\"   Specialization: {agent.specialization}\")\n",
    "    print(f\"   Experience: {agent.experience_level}/10\")\n",
    "    print(f\"   Capabilities: {', '.join(agent.capabilities)}\")\n",
    "    print(f\"   Cost: ${agent.cost_per_task}/task\")\n",
    "    print(f\"   Capacity: {agent.max_concurrent_tasks} concurrent tasks\")\n",
    "\n",
    "# Register agents\n",
    "print(\"\\n🚀 Registering Agents with OpenDistillery...\")\n",
    "registered_agents = register_financial_agents()\n",
    "print(f\"\\n✅ Successfully registered {len(registered_agents)} agents\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2. Hierarchical Coordination Pattern"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class HierarchicalOrchestrator:\n",
    "    \"\"\"Hierarchical collaboration pattern implementation\"\"\"\n",
    "    \n",
    "    def __init__(self, agents: List[AgentProfile]):\n",
    "        self.agents = {agent.agent_id: agent for agent in agents}\n",
    "        self.hierarchy = self._build_hierarchy()\n",
    "        self.active_workflows = {}\n",
    "        \n",
    "    def _build_hierarchy(self) -> Dict[str, List[str]]:\n",
    "        \"\"\"Build agent hierarchy based on archetypes\"\"\"\n",
    "        hierarchy = {\n",
    "            \"managers\": [],\n",
    "            \"coordinators\": [],\n",
    "            \"analysts\": [],\n",
    "            \"specialists\": [],\n",
    "            \"validators\": [],\n",
    "            \"executors\": []\n",
    "        }\n",
    "        \n",
    "        for agent_id, agent in self.agents.items():\n",
    "            if agent.archetype == AgentArchetype.MANAGER:\n",
    "                hierarchy[\"managers\"].append(agent_id)\n",
    "            elif agent.archetype == AgentArchetype.COORDINATOR:\n",
    "                hierarchy[\"coordinators\"].append(agent_id)\n",
    "            elif agent.archetype == AgentArchetype.ANALYST:\n",
    "                hierarchy[\"analysts\"].append(agent_id)\n",
    "            elif agent.archetype == AgentArchetype.SPECIALIST:\n",
    "                hierarchy[\"specialists\"].append(agent_id)\n",
    "            elif agent.archetype == AgentArchetype.VALIDATOR:\n",
    "                hierarchy[\"validators\"].append(agent_id)\n",
    "            elif agent.archetype == AgentArchetype.EXECUTOR:\n",
    "                hierarchy[\"executors\"].append(agent_id)\n",
    "        \n",
    "        return hierarchy\n",
    "    \n",
    "    def execute_investment_analysis(self, investment_request: Dict[str, Any]) -> Dict[str, Any]:\n",
    "        \"\"\"Execute hierarchical investment analysis workflow\"\"\"\n",
    "        workflow_id = f\"investment_analysis_{int(time.time())}\"\n",
    "        \n",
    "        print(f\"🏗️  Starting Hierarchical Investment Analysis: {workflow_id}\")\n",
    "        print(\"=\" * 60)\n",
    "        \n",
    "        workflow_results = {\n",
    "            \"workflow_id\": workflow_id,\n",
    "            \"pattern\": \"hierarchical\",\n",
    "            \"start_time\": datetime.now().isoformat(),\n",
    "            \"steps\": [],\n",
    "            \"agent_contributions\": {}\n",
    "        }\n",
    "        \n",
    "        # Step 1: Manager initiates and plans\n",
    "        manager_id = self.hierarchy[\"managers\"][0]\n",
    "        print(f\"\\n📋 Step 1: Strategic Planning ({manager_id})\")\n",
    "        manager_task = {\n",
    "            \"task_type\": \"investment_planning\",\n",
    "            \"description\": \"Plan investment analysis workflow\",\n",
    "            \"input_data\": investment_request,\n",
    "            \"assigned_agent\": manager_id\n",
    "        }\n",
    "        \n",
    "        manager_result = self._execute_task(manager_task)\n",
    "        workflow_results[\"steps\"].append({\"step\": 1, \"agent\": manager_id, \"result\": manager_result})\n",
    "        workflow_results[\"agent_contributions\"][manager_id] = manager_result\n",
    "        \n",
    "        # Step 2: Parallel analysis by analysts\n",
    "        print(f\"\\n📊 Step 2: Parallel Analysis (Analysts)\")\n",
    "        analysis_tasks = [\n",
    "            {\n",
    "                \"task_type\": \"risk_analysis\",\n",
    "                \"description\": \"Analyze investment risks\",\n",
    "                \"input_data\": {**investment_request, \"focus\": \"risk_assessment\"},\n",
    "                \"assigned_agent\": \"risk_analyst\"\n",
    "            },\n",
    "            {\n",
    "                \"task_type\": \"market_analysis\",\n",
    "                \"description\": \"Analyze market conditions\",\n",
    "                \"input_data\": {**investment_request, \"focus\": \"market_conditions\"},\n",
    "                \"assigned_agent\": \"market_analyst\"\n",
    "            }\n",
    "        ]\n",
    "        \n",
    "        analysis_results = []\n",
    "        for task in analysis_tasks:\n",
    "            result = self._execute_task(task)\n",
    "            analysis_results.append(result)\n",
    "            workflow_results[\"agent_contributions\"][task[\"assigned_agent\"]] = result\n",
    "            print(f\"   ✅ {task['assigned_agent']}: {result.get('summary', 'Analysis complete')}\")\n",
    "        \n",
    "        workflow_results[\"steps\"].append({\"step\": 2, \"type\": \"parallel_analysis\", \"results\": analysis_results})\n",
    "        \n",
    "        # Step 3: Specialist quantitative modeling\n",
    "        print(f\"\\n🔬 Step 3: Quantitative Modeling (Specialist)\")\n",
    "        quant_task = {\n",
    "            \"task_type\": \"quantitative_modeling\",\n",
    "            \"description\": \"Build quantitative investment model\",\n",
    "            \"input_data\": {\n",
    "                **investment_request,\n",
    "                \"analysis_inputs\": analysis_results\n",
    "            },\n",
    "            \"assigned_agent\": \"quant_specialist\"\n",
    "        }\n",
    "        \n",
    "        quant_result = self._execute_task(quant_task)\n",
    "        workflow_results[\"steps\"].append({\"step\": 3, \"agent\": \"quant_specialist\", \"result\": quant_result})\n",
    "        workflow_results[\"agent_contributions\"][\"quant_specialist\"] = quant_result\n",
    "        \n",
    "        # Step 4: Compliance validation\n",
    "        print(f\"\\n🛡️  Step 4: Compliance Validation\")\n",
    "        compliance_task = {\n",
    "            \"task_type\": \"compliance_validation\",\n",
    "            \"description\": \"Validate regulatory compliance\",\n",
    "            \"input_data\": {\n",
    "                \"investment_proposal\": quant_result,\n",
    "                \"regulatory_framework\": \"SEC, FINRA\"\n",
    "            },\n",
    "            \"assigned_agent\": \"compliance_validator\"\n",
    "        }\n",
    "        \n",
    "        compliance_result = self._execute_task(compliance_task)\n",
    "        workflow_results[\"steps\"].append({\"step\": 4, \"agent\": \"compliance_validator\", \"result\": compliance_result})\n",
    "        workflow_results[\"agent_contributions\"][\"compliance_validator\"] = compliance_result\n",
    "        \n",
    "        # Step 5: Manager final decision\n",
    "        print(f\"\\n🎯 Step 5: Final Decision (Manager)\")\n",
    "        decision_task = {\n",
    "            \"task_type\": \"investment_decision\",\n",
    "            \"description\": \"Make final investment decision\",\n",
    "            \"input_data\": {\n",
    "                \"all_analysis\": workflow_results[\"agent_contributions\"],\n",
    "                \"decision_criteria\": investment_request.get(\"criteria\", {})\n",
    "            },\n",
    "            \"assigned_agent\": manager_id\n",
    "        }\n",
    "        \n",
    "        final_decision = self._execute_task(decision_task)\n",
    "        workflow_results[\"steps\"].append({\"step\": 5, \"agent\": manager_id, \"result\": final_decision})\n",
    "        workflow_results[\"final_decision\"] = final_decision\n",
    "        \n",
    "        # Step 6: Execution (if approved)\n",
    "        if final_decision.get(\"approved\", False):\n",
    "            print(f\"\\n⚡ Step 6: Trade Execution\")\n",
    "            execution_task = {\n",
    "                \"task_type\": \"trade_execution\",\n",
    "                \"description\": \"Execute approved investment\",\n",
    "                \"input_data\": final_decision,\n",
    "                \"assigned_agent\": \"trade_executor\"\n",
    "            }\n",
    "            \n",
    "            execution_result = self._execute_task(execution_task)\n",
    "            workflow_results[\"steps\"].append({\"step\": 6, \"agent\": \"trade_executor\", \"result\": execution_result})\n",
    "            workflow_results[\"agent_contributions\"][\"trade_executor\"] = execution_result\n",
    "        \n",
    "        workflow_results[\"end_time\"] = datetime.now().isoformat()\n",
    "        workflow_results[\"total_agents\"] = len(workflow_results[\"agent_contributions\"])\n",
    "        \n",
    "        print(f\"\\n✅ Hierarchical Analysis Complete!\")\n",
    "        print(f\"   Total Steps: {len(workflow_results['steps'])}\")\n",
    "        print(f\"   Agents Involved: {workflow_results['total_agents']}\")\n",
    "        print(f\"   Decision: {'Approved' if final_decision.get('approved', False) else 'Rejected'}\")\n",
    "        \n",
    "        return workflow_results\n",
    "    \n",
    "    def _execute_task(self, task: Dict[str, Any]) -> Dict[str, Any]:\n",
    "        \"\"\"Execute individual task (simulated)\"\"\"\n",
    "        agent_id = task[\"assigned_agent\"]\n",
    "        task_type = task[\"task_type\"]\n",
    "        \n",
    "        # Simulate task execution based on agent type and task\n",
    "        if \"planning\" in task_type:\n",
    "            return {\n",
    "                \"summary\": \"Strategic analysis plan created\",\n",
    "                \"analysis_scope\": [\"risk_assessment\", \"market_analysis\", \"quantitative_modeling\"],\n",
    "                \"timeline\": \"2-3 business days\",\n",
    "                \"resource_allocation\": \"Optimal agent assignment\"\n",
    "            }\n",
    "        elif \"risk_analysis\" in task_type:\n",
    "            return {\n",
    "                \"summary\": \"Risk analysis completed\",\n",
    "                \"risk_score\": 6.5,  # out of 10\n",
    "                \"key_risks\": [\"Market volatility\", \"Liquidity risk\", \"Regulatory changes\"],\n",
    "                \"mitigation_strategies\": [\"Diversification\", \"Stop-loss orders\", \"Regular monitoring\"]\n",
    "            }\n",
    "        elif \"market_analysis\" in task_type:\n",
    "            return {\n",
    "                \"summary\": \"Market analysis completed\",\n",
    "                \"market_sentiment\": \"Bullish\",\n",
    "                \"growth_potential\": \"High\",\n",
    "                \"competitive_position\": \"Strong\",\n",
    "                \"market_timing\": \"Favorable\"\n",
    "            }\n",
    "        elif \"quantitative_modeling\" in task_type:\n",
    "            return {\n",
    "                \"summary\": \"Quantitative model built\",\n",
    "                \"expected_return\": 12.5,  # percentage\n",
    "                \"volatility\": 18.2,\n",
    "                \"sharpe_ratio\": 0.68,\n",
    "                \"var_95\": -8.5,  # Value at Risk\n",
    "                \"model_confidence\": 0.87\n",
    "            }\n",
    "        elif \"compliance_validation\" in task_type:\n",
    "            return {\n",
    "                \"summary\": \"Compliance validation passed\",\n",
    "                \"compliance_score\": 95,  # out of 100\n",
    "                \"regulatory_status\": \"Compliant\",\n",
    "                \"documentation_complete\": True,\n",
    "                \"approval_required\": False\n",
    "            }\n",
    "        elif \"investment_decision\" in task_type:\n",
    "            return {\n",
    "                \"summary\": \"Investment decision made\",\n",
    "                \"approved\": True,\n",
    "                \"confidence_level\": 85,\n",
    "                \"investment_amount\": 2500000,  # $2.5M\n",
    "                \"conditions\": [\"Market timing confirmation\", \"Final risk review\"]\n",
    "            }\n",
    "        elif \"trade_execution\" in task_type:\n",
    "            return {\n",
    "                \"summary\": \"Trade executed successfully\",\n",
    "                \"execution_price\": 145.50,\n",
    "                \"shares_executed\": 17182,\n",
    "                \"total_value\": 2500000,\n",
    "                \"execution_time\": \"2024-01-15 10:30:45\",\n",
    "                \"slippage\": 0.02  # percentage\n",
    "            }\n",
    "        \n",
    "        return {\"summary\": f\"{task_type} completed\", \"status\": \"success\"}\n",
    "\n",
    "# Example investment request\n",
    "investment_request = {\n",
    "    \"investment_type\": \"equity\",\n",
    "    \"target_company\": \"TechGrowth Corp\",\n",
    "    \"sector\": \"Technology\",\n",
    "    \"proposed_amount\": 2500000,\n",
    "    \"investment_horizon\": \"18_months\",\n",
    "    \"criteria\": {\n",
    "        \"min_expected_return\": 10.0,\n",
    "        \"max_risk_score\": 7.0,\n",
    "        \"liquidity_requirement\": \"High\"\n",
    "    },\n",
    "    \"urgency\": \"Normal\"\n",
    "}\n",
    "\n",
    "# Execute hierarchical workflow\n",
    "hierarchical_orchestrator = HierarchicalOrchestrator(financial_agents)\n",
    "hierarchical_result = hierarchical_orchestrator.execute_investment_analysis(investment_request)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3. Democratic Consensus Pattern"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class DemocraticOrchestrator:\n",
    "    \"\"\"Democratic consensus collaboration pattern\"\"\"\n",
    "    \n",
    "    def __init__(self, agents: List[AgentProfile]):\n",
    "        self.agents = {agent.agent_id: agent for agent in agents}\n",
    "        self.voting_weights = self._calculate_voting_weights()\n",
    "        \n",
    "    def _calculate_voting_weights(self) -> Dict[str, float]:\n",
    "        \"\"\"Calculate voting weights based on experience and collaboration scores\"\"\"\n",
    "        weights = {}\n",
    "        \n",
    "        for agent_id, agent in self.agents.items():\n",
    "            # Weight based on experience level and collaboration score\n",
    "            base_weight = agent.experience_level / 10.0\n",
    "            collaboration_bonus = agent.collaboration_score\n",
    "            weights[agent_id] = (base_weight + collaboration_bonus) / 2.0\n",
    "        \n",
    "        # Normalize weights to sum to 1.0\n",
    "        total_weight = sum(weights.values())\n",
    "        return {agent_id: weight / total_weight for agent_id, weight in weights.items()}\n",
    "    \n",
    "    def execute_consensus_analysis(self, problem: Dict[str, Any]) -> Dict[str, Any]:\n",
    "        \"\"\"Execute democratic consensus analysis\"\"\"\n",
    "        workflow_id = f\"consensus_analysis_{int(time.time())}\"\n",
    "        \n",
    "        print(f\"🗳️  Starting Democratic Consensus Analysis: {workflow_id}\")\n",
    "        print(\"=\" * 60)\n",
    "        \n",
    "        workflow_results = {\n",
    "            \"workflow_id\": workflow_id,\n",
    "            \"pattern\": \"democratic_consensus\",\n",
    "            \"start_time\": datetime.now().isoformat(),\n",
    "            \"voting_weights\": self.voting_weights,\n",
    "            \"agent_opinions\": {},\n",
    "            \"voting_rounds\": []\n",
    "        }\n",
    "        \n",
    "        # Round 1: Initial independent analysis\n",
    "        print(f\"\\n📊 Round 1: Independent Analysis\")\n",
    "        print(\"-\" * 30)\n",
    "        \n",
    "        independent_analyses = {}\n",
    "        for agent_id, agent in self.agents.items():\n",
    "            analysis = self._get_agent_analysis(agent_id, problem, context=\"independent\")\n",
    "            independent_analyses[agent_id] = analysis\n",
    "            print(f\"   {agent_id}: {analysis.get('recommendation', 'No recommendation')}\")\n",
    "        \n",
    "        workflow_results[\"agent_opinions\"] = independent_analyses\n",
    "        \n",
    "        # Round 2: Share perspectives and vote\n",
    "        print(f\"\\n🤝 Round 2: Collaborative Discussion\")\n",
    "        print(\"-\" * 30)\n",
    "        \n",
    "        # Simulate agent discussion and perspective sharing\n",
    "        shared_insights = self._facilitate_discussion(independent_analyses)\n",
    "        print(f\"   Key Consensus Points: {len(shared_insights['agreements'])}\")\n",
    "        print(f\"   Areas of Disagreement: {len(shared_insights['disagreements'])}\")\n",
    "        \n",
    "        # Round 3: Updated analysis with shared insights\n",
    "        print(f\"\\n🔄 Round 3: Updated Analysis\")\n",
    "        print(\"-\" * 30)\n",
    "        \n",
    "        updated_analyses = {}\n",
    "        for agent_id, agent in self.agents.items():\n",
    "            updated_analysis = self._get_agent_analysis(\n",
    "                agent_id, problem, \n",
    "                context=\"collaborative\",\n",
    "                shared_insights=shared_insights\n",
    "            )\n",
    "            updated_analyses[agent_id] = updated_analysis\n",
    "            print(f\"   {agent_id}: {updated_analysis.get('recommendation', 'No recommendation')}\")\n",
    "        \n",
    "        # Final voting\n",
    "        print(f\"\\n🗳️  Final Voting\")\n",
    "        print(\"-\" * 30)\n",
    "        \n",
    "        final_votes = self._conduct_weighted_voting(updated_analyses)\n",
    "        consensus_result = self._calculate_consensus(final_votes)\n",
    "        \n",
    "        workflow_results[\"voting_rounds\"].append({\n",
    "            \"round\": \"final\",\n",
    "            \"votes\": final_votes,\n",
    "            \"consensus\": consensus_result\n",
    "        })\n",
    "        \n",
    "        # Display voting results\n",
    "        for vote_option, details in final_votes.items():\n",
    "            print(f\"   {vote_option}: {details['weighted_support']:.1%} support\")\n",
    "            print(f\"      Supporters: {', '.join(details['supporters'])}\")\n",
    "        \n",
    "        workflow_results[\"final_decision\"] = consensus_result\n",
    "        workflow_results[\"end_time\"] = datetime.now().isoformat()\n",
    "        \n",
    "        print(f\"\\n✅ Democratic Consensus Reached!\")\n",
    "        print(f\"   Decision: {consensus_result['decision']}\")\n",
    "        print(f\"   Consensus Level: {consensus_result['consensus_strength']:.1%}\")\n",
    "        print(f\"   Confidence: {consensus_result['confidence']:.1%}\")\n",
    "        \n",
    "        return workflow_results\n",
    "    \n",
    "    def _get_agent_analysis(self, agent_id: str, problem: Dict[str, Any], \n",
    "                          context: str, shared_insights: Dict = None) -> Dict[str, Any]:\n",
    "        \"\"\"Get analysis from specific agent\"\"\"\n",
    "        agent = self.agents[agent_id]\n",
    "        \n",
    "        # Simulate different agent perspectives based on their specialization\n",
    "        if agent.specialization == \"risk_analysis\":\n",
    "            if context == \"independent\":\n",
    "                return {\n",
    "                    \"recommendation\": \"Proceed with Caution\",\n",
    "                    \"confidence\": 0.75,\n",
    "                    \"reasoning\": \"High market volatility requires careful risk management\",\n",
    "                    \"key_concerns\": [\"Market timing\", \"Liquidity risk\", \"Regulatory changes\"]\n",
    "                }\n",
    "            else:\n",
    "                return {\n",
    "                    \"recommendation\": \"Proceed with Enhanced Monitoring\",\n",
    "                    \"confidence\": 0.80,\n",
    "                    \"reasoning\": \"Shared insights suggest manageable risks with proper controls\",\n",
    "                    \"key_concerns\": [\"Enhanced monitoring required\", \"Diversification strategy\"]\n",
    "                }\n",
    "        \n",
    "        elif agent.specialization == \"market_analysis\":\n",
    "            if context == \"independent\":\n",
    "                return {\n",
    "                    \"recommendation\": \"Strong Buy\",\n",
    "                    \"confidence\": 0.85,\n",
    "                    \"reasoning\": \"Market conditions are highly favorable for growth\",\n",
    "                    \"key_factors\": [\"Strong fundamentals\", \"Positive sentiment\", \"Growth trajectory\"]\n",
    "                }\n",
    "            else:\n",
    "                return {\n",
    "                    \"recommendation\": \"Buy with Staged Entry\",\n",
    "                    \"confidence\": 0.83,\n",
    "                    \"reasoning\": \"Risk insights suggest staged approach while maintaining bullish outlook\",\n",
    "                    \"key_factors\": [\"Phased investment\", \"Market timing optimization\"]\n",
    "                }\n",
    "        \n",
    "        elif agent.specialization == \"quantitative_modeling\":\n",
    "            return {\n",
    "                \"recommendation\": \"Mathematical Approval\",\n",
    "                \"confidence\": 0.88,\n",
    "                \"reasoning\": \"Quantitative models show positive risk-adjusted returns\",\n",
    "                \"metrics\": {\"expected_return\": 12.5, \"sharpe_ratio\": 0.68, \"max_drawdown\": -15.2}\n",
    "            }\n",
    "        \n",
    "        elif agent.specialization == \"portfolio_management\":\n",
    "            return {\n",
    "                \"recommendation\": \"Strategic Approval\",\n",
    "                \"confidence\": 0.82,\n",
    "                \"reasoning\": \"Aligns with portfolio objectives and diversification strategy\",\n",
    "                \"strategic_fit\": \"High\"\n",
    "            }\n",
    "        \n",
    "        elif agent.specialization == \"regulatory_compliance\":\n",
    "            return {\n",
    "                \"recommendation\": \"Compliance Approved\",\n",
    "                \"confidence\": 0.95,\n",
    "                \"reasoning\": \"All regulatory requirements satisfied\",\n",
    "                \"compliance_score\": 98\n",
    "            }\n",
    "        \n",
    "        else:\n",
    "            return {\n",
    "                \"recommendation\": \"Conditional Approval\",\n",
    "                \"confidence\": 0.70,\n",
    "                \"reasoning\": \"Standard analysis supports proceeding with normal precautions\"\n",
    "            }\n",
    "    \n",
    "    def _facilitate_discussion(self, analyses: Dict[str, Any]) -> Dict[str, Any]:\n",
    "        \"\"\"Facilitate discussion between agents and identify consensus points\"\"\"\n",
    "        recommendations = [analysis.get(\"recommendation\", \"\") for analysis in analyses.values()]\n",
    "        \n",
    "        # Identify agreements and disagreements\n",
    "        agreements = []\n",
    "        disagreements = []\n",
    "        \n",
    "        # Count recommendation types\n",
    "        rec_counts = {}\n",
    "        for rec in recommendations:\n",
    "            rec_type = rec.split()[0] if rec else \"Unknown\"\n",
    "            rec_counts[rec_type] = rec_counts.get(rec_type, 0) + 1\n",
    "        \n",
    "        # Identify consensus areas\n",
    "        if rec_counts.get(\"Proceed\", 0) + rec_counts.get(\"Strong\", 0) + rec_counts.get(\"Buy\", 0) >= 3:\n",
    "            agreements.append(\"General bullish sentiment\")\n",
    "        \n",
    "        if any(\"risk\" in analysis.get(\"reasoning\", \"\").lower() for analysis in analyses.values()):\n",
    "            agreements.append(\"Risk management importance recognized\")\n",
    "        \n",
    "        # Identify disagreements\n",
    "        if len(set(recommendations)) > 3:\n",
    "            disagreements.append(\"Diverse recommendation approaches\")\n",
    "        \n",
    "        return {\n",
    "            \"agreements\": agreements,\n",
    "            \"disagreements\": disagreements,\n",
    "            \"shared_themes\": [\"Market opportunity exists\", \"Risk management critical\"]\n",
    "        }\n",
    "    \n",
    "    def _conduct_weighted_voting(self, analyses: Dict[str, Any]) -> Dict[str, Any]:\n",
    "        \"\"\"Conduct weighted voting based on agent recommendations\"\"\"\n",
    "        vote_options = {\n",
    "            \"Approve\": {\"supporters\": [], \"weights\": [], \"weighted_support\": 0.0},\n",
    "            \"Approve_with_Conditions\": {\"supporters\": [], \"weights\": [], \"weighted_support\": 0.0},\n",
    "            \"Reject\": {\"supporters\": [], \"weights\": [], \"weighted_support\": 0.0}\n",
    "        }\n",
    "        \n",
    "        for agent_id, analysis in analyses.items():\n",
    "            recommendation = analysis.get(\"recommendation\", \"\")\n",
    "            weight = self.voting_weights[agent_id]\n",
    "            \n",
    "            # Categorize recommendations into vote options\n",
    "            if any(word in recommendation.lower() for word in [\"strong\", \"buy\", \"approval\"]):\n",
    "                if \"condition\" in recommendation.lower() or \"caution\" in recommendation.lower():\n",
    "                    vote_options[\"Approve_with_Conditions\"][\"supporters\"].append(agent_id)\n",
    "                    vote_options[\"Approve_with_Conditions\"][\"weights\"].append(weight)\n",
    "                    vote_options[\"Approve_with_Conditions\"][\"weighted_support\"] += weight\n",
    "                else:\n",
    "                    vote_options[\"Approve\"][\"supporters\"].append(agent_id)\n",
    "                    vote_options[\"Approve\"][\"weights\"].append(weight)\n",
    "                    vote_options[\"Approve\"][\"weighted_support\"] += weight\n",
    "            else:\n",
    "                vote_options[\"Reject\"][\"supporters\"].append(agent_id)\n",
    "                vote_options[\"Reject\"][\"weights\"].append(weight)\n",
    "                vote_options[\"Reject\"][\"weighted_support\"] += weight\n",
    "        \n",
    "        return vote_options\n",
    "    \n",
    "    def _calculate_consensus(self, votes: Dict[str, Any]) -> Dict[str, Any]:\n",
    "        \"\"\"Calculate final consensus from weighted votes\"\"\"\n",
    "        winning_option = max(votes.items(), key=lambda x: x[1][\"weighted_support\"])\n",
    "        \n",
    "        return {\n",
    "            \"decision\": winning_option[0],\n",
    "            \"consensus_strength\": winning_option[1][\"weighted_support\"],\n",
    "            \"confidence\": min(0.95, winning_option[1][\"weighted_support\"] + 0.1),\n",
    "            \"supporting_agents\": winning_option[1][\"supporters\"],\n",
    "            \"vote_distribution\": {option: details[\"weighted_support\"] for option, details in votes.items()}\n",
    "        }\n",
    "\n",
    "# Example problem for consensus analysis\n",
    "consensus_problem = {\n",
    "    \"problem_type\": \"investment_decision\",\n",
    "    \"description\": \"Should we invest $5M in emerging market opportunities?\",\n",
    "    \"context\": {\n",
    "        \"investment_amount\": 5000000,\n",
    "        \"market\": \"Emerging Markets\",\n",
    "        \"sector\": \"Technology\",\n",
    "        \"timeline\": \"2-3 years\",\n",
    "        \"risk_tolerance\": \"Medium-High\"\n",
    "    },\n",
    "    \"decision_criteria\": {\n",
    "        \"min_expected_return\": 15.0,\n",
    "        \"max_acceptable_risk\": 8.0,\n",
    "        \"liquidity_needs\": \"Medium\"\n",
    "    }\n",
    "}\n",
    "\n",
    "# Execute democratic consensus\n",
    "democratic_orchestrator = DemocraticOrchestrator(financial_agents)\n",
    "consensus_result = democratic_orchestrator.execute_consensus_analysis(consensus_problem)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4. Expert Routing Pattern"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class ExpertRouter:\n",
    "    \"\"\"Expert routing collaboration pattern\"\"\"\n",
    "    \n",
    "    def __init__(self, agents: List[AgentProfile]):\n",
    "        self.agents = {agent.agent_id: agent for agent in agents}\n",
    "        self.expertise_map = self._build_expertise_map()\n",
    "        self.routing_history = []\n",
    "        \n",
    "    def _build_expertise_map(self) -> Dict[str, List[str]]:\n",
    "        \"\"\"Build map of expertise areas to agents\"\"\"\n",
    "        expertise_map = {}\n",
    "        \n",
    "        for agent_id, agent in self.agents.items():\n",
    "            # Add specialization\n",
    "            specialization = agent.specialization\n",
    "            if specialization not in expertise_map:\n",
    "                expertise_map[specialization] = []\n",
    "            expertise_map[specialization].append(agent_id)\n",
    "            \n",
    "            # Add capabilities\n",
    "            for capability in agent.capabilities:\n",
    "                if capability not in expertise_map:\n",
    "                    expertise_map[capability] = []\n",
    "                expertise_map[capability].append(agent_id)\n",
    "        \n",
    "        return expertise_map\n",
    "    \n",
    "    def route_complex_query(self, query: Dict[str, Any]) -> Dict[str, Any]:\n",
    "        \"\"\"Route complex query to appropriate experts\"\"\"\n",
    "        workflow_id = f\"expert_routing_{int(time.time())}\"\n",
    "        \n",
    "        print(f\"🎯 Starting Expert Routing: {workflow_id}\")\n",
    "        print(\"=\" * 50)\n",
    "        \n",
    "        workflow_results = {\n",
    "            \"workflow_id\": workflow_id,\n",
    "            \"pattern\": \"expert_routing\",\n",
    "            \"start_time\": datetime.now().isoformat(),\n",
    "            \"query\": query,\n",
    "            \"routing_decisions\": [],\n",
    "            \"expert_responses\": {}\n",
    "        }\n",
    "        \n",
    "        # Analyze query to identify required expertise\n",
    "        required_expertise = self._analyze_query_requirements(query)\n",
    "        print(f\"\\n🔍 Required Expertise: {', '.join(required_expertise)}\")\n",
    "        \n",
    "        # Route to appropriate experts\n",
    "        routing_plan = self._create_routing_plan(required_expertise, query)\n",
    "        \n",
    "        print(f\"\\n📋 Routing Plan:\")\n",
    "        for i, (expertise, agent_id, priority) in enumerate(routing_plan, 1):\n",
    "            print(f\"   {i}. {expertise} → {agent_id} (Priority: {priority})\")\n",
    "        \n",
    "        # Execute expert consultations\n",
    "        expert_responses = {}\n",
    "        for expertise, agent_id, priority in routing_plan:\n",
    "            print(f\"\\n🤖 Consulting {agent_id} for {expertise}...\")\n",
    "            \n",
    "            expert_task = {\n",
    "                \"expertise_area\": expertise,\n",
    "                \"query\": query,\n",
    "                \"priority\": priority,\n",
    "                \"context\": \"expert_consultation\"\n",
    "            }\n",
    "            \n",
    "            response = self._consult_expert(agent_id, expert_task)\n",
    "            expert_responses[f\"{expertise}_{agent_id}\"] = response\n",
    "            \n",
    "            workflow_results[\"routing_decisions\"].append({\n",
    "                \"expertise\": expertise,\n",
    "                \"agent\": agent_id,\n",
    "                \"priority\": priority,\n",
    "                \"response_summary\": response.get(\"summary\", \"\")\n",
    "            })\n",
    "            \n",
    "            print(f\"   ✅ Response: {response.get('summary', 'Expert consultation complete')}\")\n",
    "        \n",
    "        workflow_results[\"expert_responses\"] = expert_responses\n",
    "        \n",
    "        # Synthesize expert insights\n",
    "        print(f\"\\n🔬 Synthesizing Expert Insights...\")\n",
    "        synthesis = self._synthesize_expert_insights(expert_responses, query)\n",
    "        workflow_results[\"synthesis\"] = synthesis\n",
    "        \n",
    "        # Generate recommendations\n",
    "        recommendations = self._generate_expert_recommendations(synthesis, expert_responses)\n",
    "        workflow_results[\"recommendations\"] = recommendations\n",
    "        \n",
    "        workflow_results[\"end_time\"] = datetime.now().isoformat()\n",
    "        \n",
    "        print(f\"\\n✅ Expert Routing Complete!\")\n",
    "        print(f\"   Experts Consulted: {len(routing_plan)}\")\n",
    "        print(f\"   Primary Recommendation: {recommendations.get('primary', 'No recommendation')}\")\n",
    "        print(f\"   Confidence Level: {recommendations.get('confidence', 0):.1%}\")\n",
    "        \n",
    "        return workflow_results\n",
    "    \n",
    "    def _analyze_query_requirements(self, query: Dict[str, Any]) -> List[str]:\n",
    "        \"\"\"Analyze query to determine required expertise\"\"\"\n",
    "        required_expertise = []\n",
    "        \n",
    "        query_text = query.get(\"description\", \"\").lower()\n",
    "        query_type = query.get(\"type\", \"\").lower()\n",
    "        \n",
    "        # Map keywords to expertise areas\n",
    "        expertise_keywords = {\n",
    "            \"risk_analysis\": [\"risk\", \"volatility\", \"downside\", \"uncertainty\"],\n",
    "            \"market_analysis\": [\"market\", \"trend\", \"sentiment\", \"competition\"],\n",
    "            \"quantitative_modeling\": [\"model\", \"calculation\", \"algorithm\", \"statistical\"],\n",
    "            \"portfolio_management\": [\"portfolio\", \"allocation\", \"diversification\", \"strategy\"],\n",
    "            \"regulatory_compliance\": [\"compliance\", \"regulation\", \"legal\", \"audit\"],\n",
    "            \"trade_execution\": [\"execution\", \"trading\", \"order\", \"timing\"]\n",
    "        }\n",
    "        \n",
    "        for expertise, keywords in expertise_keywords.items():\n",
    "            if any(keyword in query_text for keyword in keywords):\n",
    "                required_expertise.append(expertise)\n",
    "        \n",
    "        # Default expertise if none detected\n",
    "        if not required_expertise:\n",
    "            required_expertise = [\"portfolio_management\", \"risk_analysis\"]\n",
    "        \n",
    "        return required_expertise\n",
    "    \n",
    "    def _create_routing_plan(self, required_expertise: List[str], query: Dict[str, Any]) -> List[tuple]:\n",
    "        \"\"\"Create optimal routing plan for expertise requirements\"\"\"\n",
    "        routing_plan = []\n",
    "        \n",
    "        for expertise in required_expertise:\n",
    "            if expertise in self.expertise_map:\n",
    "                # Select best agent for this expertise\n",
    "                candidate_agents = self.expertise_map[expertise]\n",
    "                best_agent = self._select_best_agent(candidate_agents, expertise, query)\n",
    "                \n",
    "                # Determine priority\n",
    "                priority = \"High\" if expertise in [\"risk_analysis\", \"compliance\"] else \"Medium\"\n",
    "                \n",
    "                routing_plan.append((expertise, best_agent, priority))\n",
    "        \n",
    "        # Sort by priority\n",
    "        priority_order = {\"High\": 1, \"Medium\": 2, \"Low\": 3}\n",
    "        routing_plan.sort(key=lambda x: priority_order.get(x[2], 3))\n",
    "        \n",
    "        return routing_plan\n",
    "    \n",
    "    def _select_best_agent(self, candidates: List[str], expertise: str, query: Dict[str, Any]) -> str:\n",
    "        \"\"\"Select best agent from candidates for specific expertise\"\"\"\n",
    "        if not candidates:\n",
    "            return None\n",
    "        \n",
    "        # Score candidates based on experience and specialization match\n",
    "        candidate_scores = {}\n",
    "        \n",
    "        for agent_id in candidates:\n",
    "            if agent_id in self.agents:\n",
    "                agent = self.agents[agent_id]\n",
    "                \n",
    "                # Base score from experience\n",
    "                score = agent.experience_level / 10.0\n",
    "                \n",
    "                # Bonus for exact specialization match\n",
    "                if agent.specialization == expertise:\n",
    "                    score += 0.3\n",
    "                \n",
    "                # Bonus for collaboration score\n",
    "                score += agent.collaboration_score * 0.2\n",
    "                \n",
    "                candidate_scores[agent_id] = score\n",
    "        \n",
    "        # Return highest scoring candidate\n",
    "        return max(candidate_scores.items(), key=lambda x: x[1])[0]\n",
    "    \n",
    "    def _consult_expert(self, agent_id: str, task: Dict[str, Any]) -> Dict[str, Any]:\n",
    "        \"\"\"Consult specific expert agent\"\"\"\n",
    "        agent = self.agents[agent_id]\n",
    "        expertise = task[\"expertise_area\"]\n",
    "        query = task[\"query\"]\n",
    "        \n",
    "        # Simulate expert consultation based on specialization\n",
    "        if expertise == \"risk_analysis\":\n",
    "            return {\n",
    "                \"summary\": \"Comprehensive risk assessment completed\",\n",
    "                \"risk_level\": \"Medium-High\",\n",
    "                \"key_risks\": [\"Market volatility\", \"Liquidity constraints\", \"Regulatory changes\"],\n",
    "                \"mitigation_strategies\": [\"Diversification\", \"Hedging\", \"