{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# OpenDistillery QuickStart Guide\n",
    "\n",
    "Welcome to OpenDistillery! This notebook will get you up and running with compound AI systems in minutes.\n",
    "\n",
    "## What You'll Learn:\n",
    "- Setting up your first compound AI system\n",
    "- Creating and registering AI agents\n",
    "- Submitting tasks to the orchestrator\n",
    "- Understanding system performance metrics\n",
    "\n",
    "## Prerequisites:\n",
    "- OpenDistillery API running (Docker: `docker-compose up -d`)\n",
    "- API key for authentication\n",
    "- Python environment with required packages"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Install required packages\n",
    "!pip install requests pandas matplotlib seaborn jupyter-widgets\n",
    "\n",
    "import requests\n",
    "import json\n",
    "import time\n",
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "import seaborn as sns\n",
    "from datetime import datetime, timedelta\n",
    "from typing import Dict, List, Any\n",
    "import asyncio\n",
    "import aiohttp\n",
    "\n",
    "# Configure plotting\n",
    "plt.style.use('default')\n",
    "sns.set_palette(\"husl\")\n",
    "%matplotlib inline"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step 1: Configure API Connection"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# OpenDistillery API Configuration\n",
    "API_BASE = \"http://localhost:8000\"\n",
    "API_KEY = \"opd_demo_enterprise_key_12345\"  # Replace with your actual API key\n",
    "\n",
    "# Headers for API requests\n",
    "headers = {\n",
    "    \"Authorization\": f\"Bearer {API_KEY}\",\n",
    "    \"Content-Type\": \"application/json\"\n",
    "}\n",
    "\n",
    "# Test API connection\n",
    "def test_connection():\n",
    "    try:\n",
    "        response = requests.get(f\"{API_BASE}/health\", headers=headers)\n",
    "        if response.status_code == 200:\n",
    "            health_data = response.json()\n",
    "            print(\"✅ API Connection Successful!\")\n",
    "            print(f\"Status: {health_data['status']}\")\n",
    "            print(f\"Version: {health_data['version']}\")\n",
    "            print(f\"Active Agents: {health_data['metrics']['active_agents']}\")\n",
    "            return True\n",
    "        else:\n",
    "            print(f\"❌ API Error: {response.status_code}\")\n",
    "            return False\n",
    "    except Exception as e:\n",
    "        print(f\"❌ Connection Failed: {str(e)}\")\n",
    "        return False\n",
    "\n",
    "test_connection()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step 2: Explore Available Agents"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Get list of available agents\n",
    "response = requests.get(f\"{API_BASE}/agents\", headers=headers)\n",
    "agents_data = response.json()\n",
    "\n",
    "print(f\"📊 Total Agents Available: {agents_data['total_agents']}\")\n",
    "print(\"\\n\" + \"=\"*60)\n",
    "\n",
    "# Create agents DataFrame for better visualization\n",
    "agents_df = pd.DataFrame(agents_data['agents'])\n",
    "\n",
    "if not agents_df.empty:\n",
    "    print(\"\\n🤖 Available Agents:\")\n",
    "    for _, agent in agents_df.iterrows():\n",
    "        print(f\"\\n🔹 {agent['agent_id']}\")\n",
    "        print(f\"   Type: {agent['agent_type']}\")\n",
    "        print(f\"   Capabilities: {', '.join(agent['capabilities'])}\")\n",
    "        print(f\"   State: {agent['state']}\")\n",
    "        print(f\"   Current Load: {agent['current_load']:.1%}\")\n",
    "        print(f\"   Success Rate: {agent['success_rate']:.1%}\")\n",
    "        if agent['specialization']:\n",
    "            print(f\"   Specialization: {agent['specialization']}\")\n",
    "else:\n",
    "    print(\"\\n⚠️ No agents currently registered. Let's create some!\")\n",
    "\n",
    "# Visualize agent capabilities\n",
    "if not agents_df.empty:\n",
    "    plt.figure(figsize=(12, 6))\n",
    "    \n",
    "    # Agent load distribution\n",
    "    plt.subplot(1, 2, 1)\n",
    "    plt.bar(agents_df['agent_id'], agents_df['current_load'])\n",
    "    plt.title('Agent Load Distribution')\n",
    "    plt.ylabel('Current Load')\n",
    "    plt.xticks(rotation=45)\n",
    "    \n",
    "    # Agent success rates\n",
    "    plt.subplot(1, 2, 2)\n",
    "    plt.bar(agents_df['agent_id'], agents_df['success_rate'])\n",
    "    plt.title('Agent Success Rates')\n",
    "    plt.ylabel('Success Rate')\n",
    "    plt.xticks(rotation=45)\n",
    "    \n",
    "    plt.tight_layout()\n",
    "    plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step 3: Register Custom Agents (If Needed)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Register a custom business analyst agent\n",
    "def register_agent(agent_config):\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",
    "        result = response.json()\n",
    "        print(f\"✅ Agent '{agent_config['agent_id']}' registered successfully!\")\n",
    "        return True\n",
    "    else:\n",
    "        print(f\"❌ Failed to register agent: {response.text}\")\n",
    "        return False\n",
    "\n",
    "# Example: Business Intelligence Agent\n",
    "business_agent_config = {\n",
    "    \"agent_id\": \"business_intelligence_analyst\",\n",
    "    \"agent_type\": \"analyst\",\n",
    "    \"capabilities\": [\"analysis\", \"prediction\", \"reporting\"],\n",
    "    \"specialization\": \"business_intelligence\",\n",
    "    \"configuration\": {\n",
    "        \"analysis_depth\": \"comprehensive\",\n",
    "        \"reporting_format\": \"executive_summary\",\n",
    "        \"confidence_threshold\": 0.8\n",
    "    }\n",
    "}\n",
    "\n",
    "# Example: Customer Insights Agent\n",
    "customer_agent_config = {\n",
    "    \"agent_id\": \"customer_insights_specialist\",\n",
    "    \"agent_type\": \"specialist\",\n",
    "    \"capabilities\": [\"analysis\", \"research\", \"synthesis\"],\n",
    "    \"specialization\": \"customer_analytics\",\n",
    "    \"configuration\": {\n",
    "        \"segment_analysis\": True,\n",
    "        \"churn_prediction\": True,\n",
    "        \"lifetime_value_calculation\": True\n",
    "    }\n",
    "}\n",
    "\n",
    "# Register agents\n",
    "print(\"🚀 Registering Custom Agents...\\n\")\n",
    "register_agent(business_agent_config)\n",
    "register_agent(customer_agent_config)\n",
    "\n",
    "# Refresh agent list\n",
    "time.sleep(2)\n",
    "response = requests.get(f\"{API_BASE}/agents\", headers=headers)\n",
    "updated_agents = response.json()\n",
    "print(f\"\\n📊 Updated Total Agents: {updated_agents['total_agents']}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step 4: Submit Your First Task"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Sample business analysis task\n",
    "def submit_task(task_request):\n",
    "    response = requests.post(\n",
    "        f\"{API_BASE}/tasks\",\n",
    "        headers=headers,\n",
    "        json=task_request\n",
    "    )\n",
    "    \n",
    "    if response.status_code == 200:\n",
    "        return response.json()\n",
    "    else:\n",
    "        print(f\"❌ Task submission failed: {response.text}\")\n",
    "        return None\n",
    "\n",
    "# Example 1: Market Analysis Task\n",
    "market_analysis_task = {\n",
    "    \"task_type\": \"market_analysis\",\n",
    "    \"description\": \"Analyze Q4 2024 market trends for technology sector\",\n",
    "    \"input_data\": {\n",
    "        \"sector\": \"technology\",\n",
    "        \"time_period\": \"Q4_2024\",\n",
    "        \"metrics\": [\"revenue_growth\", \"market_share\", \"competitive_landscape\"],\n",
    "        \"companies\": [\"Apple\", \"Microsoft\", \"Google\", \"Amazon\", \"Meta\"]\n",
    "    },\n",
    "    \"priority\": \"high\",\n",
    "    \"required_capabilities\": [\"analysis\", \"prediction\"],\n",
    "    \"context\": {\n",
    "        \"business_goal\": \"investment_decision\",\n",
    "        \"stakeholder\": \"investment_committee\",\n",
    "        \"deadline\": \"2024-12-31\"\n",
    "    }\n",
    "}\n",
    "\n",
    "# Example 2: Customer Segmentation Task\n",
    "customer_segmentation_task = {\n",
    "    \"task_type\": \"customer_segmentation\",\n",
    "    \"description\": \"Identify high-value customer segments for retention campaign\",\n",
    "    \"input_data\": {\n",
    "        \"customer_data\": {\n",
    "            \"total_customers\": 50000,\n",
    "            \"avg_customer_value\": 1250,\n",
    "            \"churn_rate\": 0.15,\n",
    "            \"segments\": [\"enterprise\", \"mid_market\", \"small_business\"]\n",
    "        },\n",
    "        \"analysis_goals\": [\n",
    "            \"identify_high_value_segments\",\n",
    "            \"predict_churn_risk\",\n",
    "            \"recommend_retention_strategies\"\n",
    "        ]\n",
    "    },\n",
    "    \"priority\": \"medium\",\n",
    "    \"required_capabilities\": [\"analysis\", \"research\"]\n",
    "}\n",
    "\n",
    "# Submit tasks\n",
    "print(\"🚀 Submitting Tasks to OpenDistillery...\\n\")\n",
    "\n",
    "print(\"📊 Task 1: Market Analysis\")\n",
    "task1_result = submit_task(market_analysis_task)\n",
    "if task1_result:\n",
    "    print(f\"   ✅ Task ID: {task1_result['task_id']}\")\n",
    "    print(f\"   📊 Status: {task1_result['status']}\")\n",
    "    print(f\"   ⏱️  Processing Time: {task1_result['processing_time']:.3f}s\")\n",
    "\n",
    "print(\"\\n👥 Task 2: Customer Segmentation\")\n",
    "task2_result = submit_task(customer_segmentation_task)\n",
    "if task2_result:\n",
    "    print(f\"   ✅ Task ID: {task2_result['task_id']}\")\n",
    "    print(f\"   📊 Status: {task2_result['status']}\")\n",
    "    print(f\"   ⏱️  Processing Time: {task2_result['processing_time']:.3f}s\")\n",
    "\n",
    "# Store task IDs for monitoring\n",
    "submitted_tasks = []\n",
    "if task1_result:\n",
    "    submitted_tasks.append(task1_result['task_id'])\n",
    "if task2_result:\n",
    "    submitted_tasks.append(task2_result['task_id'])\n",
    "\n",
    "print(f\"\\n📋 Total Tasks Submitted: {len(submitted_tasks)}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step 5: Monitor Task Progress"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Monitor task progress with real-time updates\n",
    "def get_task_status(task_id):\n",
    "    response = requests.get(f\"{API_BASE}/tasks/{task_id}\", headers=headers)\n",
    "    if response.status_code == 200:\n",
    "        return response.json()\n",
    "    return None\n",
    "\n",
    "def monitor_tasks(task_ids, max_wait_time=60):\n",
    "    print(\"🔍 Monitoring Task Progress...\\n\")\n",
    "    \n",
    "    start_time = time.time()\n",
    "    completed_tasks = []\n",
    "    \n",
    "    while len(completed_tasks) < len(task_ids) and (time.time() - start_time) < max_wait_time:\n",
    "        for task_id in task_ids:\n",
    "            if task_id not in completed_tasks:\n",
    "                status = get_task_status(task_id)\n",
    "                if status:\n",
    "                    print(f\"📋 Task {task_id[:8]}...\")\n",
    "                    print(f\"   Status: {status['status']}\")\n",
    "                    \n",
    "                    if status['status'] == 'completed':\n",
    "                        print(f\"   ✅ Completed Successfully!\")\n",
    "                        print(f\"   🎯 Confidence: {status.get('confidence', 'N/A')}\")\n",
    "                        print(f\"   🤖 Agent: {status.get('agent_id', 'N/A')}\")\n",
    "                        print(f\"   ⏱️  Total Time: {status['processing_time']:.3f}s\")\n",
    "                        \n",
    "                        # Display key results\n",
    "                        if status.get('result'):\n",
    "                            result = status['result']\n",
    "                            print(f\"   📊 Result Preview:\")\n",
    "                            for key, value in list(result.items())[:3]:  # Show first 3 items\n",
    "                                if isinstance(value, (str, int, float)):\n",
    "                                    print(f\"      {key}: {value}\")\n",
    "                        \n",
    "                        completed_tasks.append(task_id)\n",
    "                        print(\"   \" + \"-\"*40)\n",
    "                    \n",
    "                    elif status['status'] == 'failed':\n",
    "                        print(f\"   ❌ Failed: {status.get('error', 'Unknown error')}\")\n",
    "                        completed_tasks.append(task_id)\n",
    "                        print(\"   \" + \"-\"*40)\n",
    "                    \n",
    "                    else:\n",
    "                        print(f\"   ⏳ Status: {status['status']}...\")\n",
    "        \n",
    "        if len(completed_tasks) < len(task_ids):\n",
    "            time.sleep(2)  # Wait 2 seconds before next check\n",
    "    \n",
    "    print(f\"\\n✅ Monitoring Complete: {len(completed_tasks)}/{len(task_ids)} tasks finished\")\n",
    "    return completed_tasks\n",
    "\n",
    "# Monitor our submitted tasks\n",
    "if submitted_tasks:\n",
    "    completed = monitor_tasks(submitted_tasks)\n",
    "else:\n",
    "    print(\"⚠️ No tasks to monitor\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step 6: Analyze System Performance"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Get comprehensive system status\n",
    "def get_system_status():\n",
    "    response = requests.get(f\"{API_BASE}/status\", headers=headers)\n",
    "    if response.status_code == 200:\n",
    "        return response.json()\n",
    "    return None\n",
    "\n",
    "# Get performance analytics\n",
    "def get_performance_analytics():\n",
    "    response = requests.get(f\"{API_BASE}/analytics/performance\", headers=headers)\n",
    "    if response.status_code == 200:\n",
    "        return response.json()\n",
    "    return None\n",
    "\n",
    "print(\"📊 System Performance Analysis\\n\")\n",
    "print(\"=\"*50)\n",
    "\n",
    "# Get system status\n",
    "status = get_system_status()\n",
    "if status:\n",
    "    print(f\"\\n🖥️  System Information:\")\n",
    "    print(f\"   Version: {status['system_info']['version']}\")\n",
    "    print(f\"   Environment: {status['system_info']['environment']}\")\n",
    "    print(f\"   Uptime: {status['system_info']['uptime_seconds']:.0f} seconds\")\n",
    "    \n",
    "    print(f\"\\n🤖 Orchestration Status:\")\n",
    "    orch = status['orchestration']\n",
    "    print(f\"   Registered Agents: {orch['registered_agents']}\")\n",
    "    print(f\"   Queued Tasks: {orch['queued_tasks']}\")\n",
    "    print(f\"   Active Tasks: {orch['active_tasks']}\")\n",
    "    print(f\"   Completed Tasks: {orch['completed_tasks']}\")\n",
    "    \n",
    "    print(f\"\\n📈 Performance Metrics:\")\n",
    "    perf = status['performance']\n",
    "    print(f\"   Average Processing Time: {perf['avg_task_processing_time']:.3f}s\")\n",
    "    print(f\"   Success Rate: {perf['success_rate']:.1%}\")\n",
    "    print(f\"   Agent Utilization: {perf['agent_utilization']:.1%}\")\n",
    "\n",
    "# Get detailed analytics\n",
    "analytics = get_performance_analytics()\n",
    "if analytics:\n",
    "    print(f\"\\n📊 Detailed Analytics ({analytics['time_range']}):\")\n",
    "    \n",
    "    sys_metrics = analytics['system_metrics']\n",
    "    print(f\"\\n   System Metrics:\")\n",
    "    print(f\"   • Total Tasks Processed: {sys_metrics['total_tasks_processed']}\")\n",
    "    print(f\"   • Success Rate: {sys_metrics['success_rate']:.1%}\")\n",
    "    print(f\"   • Average Processing Time: {sys_metrics['average_processing_time']:.3f}s\")\n",
    "    print(f\"   • Agent Utilization: {sys_metrics['agent_utilization']:.1%}\")\n",
    "    \n",
    "    agent_perf = analytics['agent_performance']\n",
    "    print(f\"\\n   Agent Performance:\")\n",
    "    print(f\"   • Total Agents: {agent_perf['total_agents']}\")\n",
    "    print(f\"   • Active Agents: {agent_perf['active_agents']}\")\n",
    "    print(f\"   • Average Success Rate: {agent_perf['average_agent_success_rate']:.1%}\")\n",
    "\n",
    "# Create performance visualization\n",
    "if analytics:\n",
    "    fig, axes = plt.subplots(2, 2, figsize=(15, 10))\n",
    "    \n",
    "    # System metrics pie chart\n",
    "    ax1 = axes[0, 0]\n",
    "    success_count = sys_metrics['total_tasks_processed'] * sys_metrics['success_rate']\n",
    "    failed_count = sys_metrics['total_tasks_processed'] * (1 - sys_metrics['success_rate'])\n",
    "    ax1.pie([success_count, failed_count], labels=['Successful', 'Failed'], \n",
    "            autopct='%1.1f%%', colors=['#2ecc71', '#e74c3c'])\n",
    "    ax1.set_title('Task Success Distribution')\n",
    "    \n",
    "    # Agent utilization\n",
    "    ax2 = axes[0, 1]\n",
    "    utilization_data = [sys_metrics['agent_utilization'], 1 - sys_metrics['agent_utilization']]\n",
    "    ax2.pie(utilization_data, labels=['Utilized', 'Available'], \n",
    "            autopct='%1.1f%%', colors=['#3498db', '#95a5a6'])\n",
    "    ax2.set_title('Agent Utilization')\n",
    "    \n",
    "    # Performance timeline (simulated)\n",
    "    ax3 = axes[1, 0]\n",
    "    times = pd.date_range(start='2024-01-01', periods=24, freq='H')\n",
    "    performance = [0.85 + 0.1 * np.sin(i/4) + 0.05 * np.random.random() for i in range(24)]\n",
    "    ax3.plot(times, performance, marker='o')\n",
    "    ax3.set_title('Success Rate Over Time (24h)')\n",
    "    ax3.set_ylabel('Success Rate')\n",
    "    ax3.tick_params(axis='x', rotation=45)\n",
    "    \n",
    "    # Processing time distribution\n",
    "    ax4 = axes[1, 1]\n",
    "    processing_times = np.random.normal(sys_metrics['average_processing_time'], 0.5, 100)\n",
    "    ax4.hist(processing_times, bins=20, alpha=0.7, color='#9b59b6')\n",
    "    ax4.set_title('Processing Time Distribution')\n",
    "    ax4.set_xlabel('Processing Time (s)')\n",
    "    ax4.set_ylabel('Frequency')\n",
    "    \n",
    "    plt.tight_layout()\n",
    "    plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step 7: Explore Advanced Features"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Demonstrate batch task submission\n",
    "print(\"🚀 Advanced Feature: Batch Task Processing\\n\")\n",
    "\n",
    "# Create multiple related tasks\n",
    "batch_tasks = [\n",
    "    {\n",
    "        \"task_type\": \"sentiment_analysis\",\n",
    "        \"description\": \"Analyze customer feedback sentiment\",\n",
    "        \"input_data\": {\n",
    "            \"feedback_source\": \"social_media\",\n",
    "            \"sample_size\": 1000,\n",
    "            \"channels\": [\"twitter\", \"facebook\", \"instagram\"]\n",
    "        },\n",
    "        \"priority\": \"medium\",\n",
    "        \"required_capabilities\": [\"analysis\"]\n",
    "    },\n",
    "    {\n",
    "        \"task_type\": \"competitive_analysis\",\n",
    "        \"description\": \"Analyze competitor pricing strategies\",\n",
    "        \"input_data\": {\n",
    "            \"competitors\": [\"CompanyA\", \"CompanyB\", \"CompanyC\"],\n",
    "            \"product_categories\": [\"software\", \"services\", \"support\"],\n",
    "            \"analysis_period\": \"6_months\"\n",
    "        },\n",
    "        \"priority\": \"high\",\n",
    "        \"required_capabilities\": [\"analysis\", \"research\"]\n",
    "    },\n",
    "    {\n",
    "        \"task_type\": \"trend_forecasting\",\n",
    "        \"description\": \"Forecast technology trends for 2025\",\n",
    "        \"input_data\": {\n",
    "            \"focus_areas\": [\"AI\", \"Cloud\", \"Cybersecurity\", \"IoT\"],\n",
    "            \"forecast_horizon\": \"12_months\",\n",
    "            \"confidence_level\": 0.85\n",
    "        },\n",
    "        \"priority\": \"high\",\n",
    "        \"required_capabilities\": [\"prediction\", \"analysis\"]\n",
    "    }\n",
    "]\n",
    "\n",
    "# Submit batch tasks\n",
    "batch_response = requests.post(\n",
    "    f\"{API_BASE}/tasks/batch\",\n",
    "    headers=headers,\n",
    "    json=batch_tasks\n",
    ")\n",
    "\n",
    "if batch_response.status_code == 200:\n",
    "    batch_result = batch_response.json()\n",
    "    print(f\"✅ Batch Submission Successful!\")\n",
    "    print(f\"   Total Tasks: {batch_result['total_tasks']}\")\n",
    "    print(f\"   Successfully Submitted: {batch_result['submitted_successfully']}\")\n",
    "    print(f\"   Failed Submissions: {batch_result['failed_submissions']}\")\n",
    "    print(f\"   Processing Time: {batch_result['processing_time']:.3f}s\")\n",
    "    \n",
    "    if batch_result['submitted_tasks']:\n",
    "        print(f\"\\n📋 Submitted Task IDs:\")\n",
    "        for task in batch_result['submitted_tasks']:\n",
    "            print(f\"   • {task['task_id']} ({task['task_type']})\")\n",
    "else:\n",
    "    print(f\"❌ Batch submission failed: {batch_response.text}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step 8: Create Your First Experiment"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Demonstrate A/B testing capabilities\n",
    "print(\"🧪 Advanced Feature: A/B Testing Framework\\n\")\n",
    "\n",
    "# Create a simple A/B test for task processing strategies\n",
    "experiment_config = {\n",
    "    \"experiment_name\": \"Task Routing Strategy Optimization\",\n",
    "    \"experiment_type\": \"ab_test\",\n",
    "    \"hypothesis\": \"Intelligent routing improves task completion time by 15%\",\n",
    "    \"variants\": [\n",
    "        {\n",
    "            \"id\": \"control\",\n",
    "            \"name\": \"Random Routing\",\n",
    "            \"description\": \"Tasks assigned to random available agents\",\n",
    "            \"configuration\": {\n",
    "                \"routing_strategy\": \"random\",\n",
    "                \"load_balancing\": False\n",
    "            },\n",
    "            \"traffic_allocation\": 0.5,\n",
    "            \"is_control\": True\n",
    "        },\n",
    "        {\n",
    "            \"id\": \"treatment\", \n",
    "            \"name\": \"Intelligent Routing\",\n",
    "            \"description\": \"Tasks assigned based on agent specialization and load\",\n",
    "            \"configuration\": {\n",
    "                \"routing_strategy\": \"intelligent\",\n",
    "                \"load_balancing\": True,\n",
    "                \"specialization_matching\": True\n",
    "            },\n",
    "            \"traffic_allocation\": 0.5\n",
    "        }\n",
    "    ],\n",
    "    \"metrics\": [\n",
    "        {\n",
    "            \"name\": \"completion_time\",\n",
    "            \"type\": \"primary\",\n",
    "            \"description\": \"Average task completion time\",\n",
    "            \"direction\": \"decrease\"\n",
    "        },\n",
    "        {\n",
    "            \"name\": \"success_rate\",\n",
    "            \"type\": \"secondary\",\n",
    "            \"description\": \"Task success rate\",\n",
    "            \"direction\": \"increase\"\n",
    "        },\n",
    "        {\n",
    "            \"name\": \"agent_utilization\",\n",
    "            \"type\": \"secondary\",\n",
    "            \"description\": \"Average agent utilization\",\n",
    "            \"direction\": \"increase\"\n",
    "        }\n",
    "    ],\n",
    "    \"duration_hours\": 24,\n",
    "    \"sample_size\": 1000\n",
    "}\n",
    "\n",
    "# Create experiment\n",
    "exp_response = requests.post(\n",
    "    f\"{API_BASE}/experiments\",\n",
    "    headers=headers,\n",
    "    json=experiment_config\n",
    ")\n",
    "\n",
    "if exp_response.status_code == 200:\n",
    "    exp_result = exp_response.json()\n",
    "    experiment_id = exp_result['experiment_id']\n",
    "    \n",
    "    print(f\"✅ Experiment Created Successfully!\")\n",
    "    print(f\"   Experiment ID: {experiment_id}\")\n",
    "    print(f\"   Name: {experiment_config['experiment_name']}\")\n",
    "    print(f\"   Type: {experiment_config['experiment_type']}\")\n",
    "    print(f\"   Duration: {experiment_config['duration_hours']} hours\")\n",
    "    print(f\"   Target Sample Size: {experiment_config['sample_size']}\")\n",
    "    \n",
    "    # Start the experiment\n",
    "    start_response = requests.post(\n",
    "        f\"{API_BASE}/experiments/{experiment_id}/start