{
  "name": "Dynamic Multi-Agent Router System - Fixed Final",
  "nodes": [
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "agent-task",
        "responseMode": "responseNode",
        "options": {}
      },
      "id": "webhook-start",
      "name": "Webhook - Agent Task",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 1,
      "position": [240, 300],
      "webhookId": "agent-task-webhook"
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict"
          },
          "conditions": [
            {
              "id": "task-validation",
              "leftValue": "={{ $json.task || $json.message }}",
              "rightValue": "",
              "operator": {
                "type": "string",
                "operation": "isNotEmpty"
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "validate-input",
      "name": "Validate Input",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2,
      "position": [460, 300]
    },
    {
      "parameters": {
        "respondWith": "json",
        "responseBody": "={{ {\n  \"success\": false,\n  \"error\": \"Invalid input: Task is required\",\n  \"suggestion\": \"Please provide a task or message in your request.\"\n} }}",
        "options": {}
      },
      "id": "error-response",
      "name": "Error Response",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1,
      "position": [680, 200]
    },
    {
      "parameters": {
        "jsCode": "// Extract and normalize input\nconst input = $input.first().json;\nconst task = input.task || input.message || '';\nconst context = input.context || '';\nconst userId = input.user_id || 'anonymous';\n\n// Return normalized data\nreturn {\n  task: task.trim(),\n  context: context.trim(),\n  userId: userId,\n  timestamp: new Date().toISOString()\n};"
      },
      "id": "normalize-input",
      "name": "Normalize Input",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [680, 400]
    },
    {
      "parameters": {
        "jsCode": "// Simple agent selection based on keywords\nconst task = $input.first().json.task.toLowerCase();\nconst context = $input.first().json.context.toLowerCase();\n\n// Define available agents\nconst agents = [\n  {\n    name: 'mobile-app-builder',\n    department: 'engineering',\n    description: 'Expert in mobile app development for iOS, Android, and cross-platform solutions',\n    keywords: ['mobile', 'app', 'ios', 'android', 'react-native', 'flutter', 'swift', 'kotlin']\n  },\n  {\n    name: 'ui-designer',\n    department: 'design',\n    description: 'Expert in user interface design, creating beautiful and functional interfaces',\n    keywords: ['ui', 'design', 'interface', 'ux', 'figma', 'sketch', 'prototype', 'wireframe']\n  },\n  {\n    name: 'backend-architect',\n    department: 'engineering',\n    description: 'Expert in backend architecture, APIs, databases, and server infrastructure',\n    keywords: ['backend', 'api', 'database', 'server', 'nodejs', 'python', 'aws', 'docker']\n  },\n  {\n    name: 'frontend-developer',\n    department: 'engineering',\n    description: 'Expert in frontend development with modern frameworks and technologies',\n    keywords: ['frontend', 'react', 'vue', 'angular', 'javascript', 'typescript', 'css', 'html']\n  },\n  {\n    name: 'content-creator',\n    department: 'marketing',\n    description: 'Expert in content creation, copywriting, and marketing strategies',\n    keywords: ['content', 'marketing', 'copywriting', 'social-media', 'blog', 'seo', 'branding']\n  },\n  {\n    name: 'growth-hacker',\n    department: 'marketing',\n    description: 'Expert in growth strategies, user acquisition, and marketing analytics',\n    keywords: ['growth', 'analytics', 'acquisition', 'retention', 'conversion', 'metrics', 'funnel']\n  }\n];\n\n// Simple keyword-based selection\nconst selectedAgents = [];\n\nfor (const agent of agents) {\n  const keywordMatches = agent.keywords.filter(keyword => \n    task.includes(keyword) || context.includes(keyword)\n  ).length;\n  \n  if (keywordMatches > 0) {\n    selectedAgents.push({\n      ...agent,\n      matchScore: keywordMatches\n    });\n  }\n}\n\n// Sort by match score and take top 3\nselectedAgents.sort((a, b) => b.matchScore - a.matchScore);\nconst topAgents = selectedAgents.slice(0, 3);\n\n// If no matches, use default agents\nif (topAgents.length === 0) {\n  topAgents.push(agents[0], agents[1]); // mobile-app-builder and ui-designer\n}\n\nreturn {\n  selected_agents: topAgents,\n  reasoning: `Selected based on keyword matching: ${topAgents.map(a => `${a.name}(${a.matchScore || 0})`).join(', ')}`,\n  count: topAgents.length\n};"
      },
      "id": "select-agents",
      "name": "Select Agents",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [900, 400]
    },
    {
      "parameters": {
        "jsCode": "// Generate agent responses - FIXED VERSION\nconst selectedAgents = $input.first().json.selected_agents;\nconst normalizedInput = $('normalize-input').first().json;\nconst task = normalizedInput.task;\nconst context = normalizedInput.context;\n\nconst responses = selectedAgents.map(agent => {\n  let response = `As a ${agent.department} specialist, here's my expert advice for your task: \"${task}\"\\n\\n`;\n  \n  if (agent.name === 'mobile-app-builder') {\n    response += `**Mobile App Development Strategy:**\\n`;\n    response += `1. Choose the right platform: Native iOS/Android vs Cross-platform (React Native/Flutter)\\n`;\n    response += `2. Set up development environment and tools\\n`;\n    response += `3. Design app architecture and navigation flow\\n`;\n    response += `4. Implement core features and user authentication\\n`;\n    response += `5. Test on real devices and optimize performance\\n`;\n    response += `6. Prepare for app store submission\\n\\n`;\n    response += `**Recommended Tech Stack:** React Native for cross-platform, Swift for iOS, Kotlin for Android.`;\n  } else if (agent.name === 'ui-designer') {\n    response += `**UI/UX Design Approach:**\\n`;\n    response += `1. Create user personas and user journey maps\\n`;\n    response += `2. Design wireframes and low-fidelity prototypes\\n`;\n    response += `3. Develop high-fidelity mockups with design system\\n`;\n    response += `4. Ensure responsive design and accessibility\\n`;\n    response += `5. Create interactive prototypes for testing\\n`;\n    response += `6. Hand off designs to development team\\n\\n`;\n    response += `**Design Tools:** Figma for collaboration, Sketch for detailed design, Principle for animations.`;\n  } else if (agent.name === 'backend-architect') {\n    response += `**Backend Architecture Strategy:**\\n`;\n    response += `1. Design scalable API architecture\\n`;\n    response += `2. Choose appropriate database (PostgreSQL/MongoDB)\\n`;\n    response += `3. Implement authentication and authorization\\n`;\n    response += `4. Set up cloud infrastructure (AWS/Azure/GCP)\\n`;\n    response += `5. Implement monitoring and logging\\n`;\n    response += `6. Plan for scalability and security\\n\\n`;\n    response += `**Tech Stack:** Node.js/Python for APIs, PostgreSQL for data, Docker for deployment.`;\n  } else if (agent.name === 'frontend-developer') {\n    response += `**Frontend Development Strategy:**\\n`;\n    response += `1. Choose modern framework (React/Vue/Angular)\\n`;\n    response += `2. Set up build tools and development environment\\n`;\n    response += `3. Implement responsive design and components\\n`;\n    response += `4. Integrate with backend APIs\\n`;\n    response += `5. Implement state management and routing\\n`;\n    response += `6. Optimize performance and SEO\\n\\n`;\n    response += `**Tech Stack:** React with TypeScript, Tailwind CSS, Vite for building.`;\n  } else if (agent.name === 'content-creator') {\n    response += `**Content Strategy:**\\n`;\n    response += `1. Define target audience and content pillars\\n`;\n    response += `2. Create content calendar and editorial plan\\n`;\n    response += `3. Develop brand voice and messaging guidelines\\n`;\n    response += `4. Create engaging content across platforms\\n`;\n    response += `5. Implement SEO best practices\\n`;\n    response += `6. Measure and optimize content performance\\n\\n`;\n    response += `**Content Tools:** Canva for visuals, Grammarly for writing, Hootsuite for scheduling.`;\n  } else if (agent.name === 'growth-hacker') {\n    response += `**Growth Strategy:**\\n`;\n    response += `1. Analyze current metrics and identify growth opportunities\\n`;\n    response += `2. Implement A/B testing for key conversion points\\n`;\n    response += `3. Optimize user acquisition channels\\n`;\n    response += `4. Improve user retention and engagement\\n`;\n    response += `5. Implement referral and viral growth mechanisms\\n`;\n    response += `6. Track and analyze growth metrics\\n\\n`;\n    response += `**Growth Tools:** Google Analytics, Mixpanel for events, Hotjar for user behavior.`;\n  }\n  \n  return {\n    agent: agent.name,\n    department: agent.department,\n    response: response,\n    timestamp: new Date().toISOString()\n  };\n});\n\nreturn responses;"
      },
      "id": "generate-responses",
      "name": "Generate Agent Responses",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [1120, 400]
    },
    {
      "parameters": {
        "jsCode": "// Create final response - FIXED VERSION\nconst startTime = new Date($('normalize-input').first().json.timestamp);\nconst endTime = new Date();\nconst executionTime = endTime.getTime() - startTime.getTime();\n\nconst selectedAgents = $('select-agents').first().json.selected_agents;\nconst individualResponses = $input.all().map(response => response.json);\nconst normalizedInput = $('normalize-input').first().json;\n\n// Create synthesized plan\nconst synthesizedPlan = `# Executive Summary\\n\\nBased on your request: \"${normalizedInput.task}\", I've consulted with ${selectedAgents.length} expert agents to provide comprehensive guidance.\\n\\n## Key Insights\\n\\n${individualResponses.map(r => `- **${r.agent}**: ${r.response.split('\\n')[0]}`).join('\\n')}\\n\\n## Unified Action Plan\\n\\n1. **Immediate Actions** (Week 1):\\n   - Set up development environment and tools\\n   - Create project timeline and milestones\\n   - Begin initial design and architecture work\\n\\n2. **Development Phase** (Weeks 2-4):\\n   - Implement core features and functionality\\n   - Conduct regular testing and iteration\\n   - Maintain communication between team members\\n\\n3. **Launch Preparation** (Weeks 5-6):\\n   - Final testing and optimization\\n   - Prepare for deployment and launch\\n   - Create marketing and content materials\\n\\n## Next Steps\\n\\n1. Review the detailed recommendations from each expert\\n2. Prioritize tasks based on your timeline and resources\\n3. Set up regular check-ins to track progress\\n4. Be prepared to iterate and adapt as you learn more\\n\\n## Expert Recommendations\\n\\n${individualResponses.map(r => `### ${r.agent} (${r.department})\\n${r.response}`).join('\\n\\n')}`;\n\nreturn {\n  success: true,\n  task: normalizedInput.task,\n  context: normalizedInput.context,\n  user_id: normalizedInput.userId,\n  agents_consulted: selectedAgents.map(a => a.name),\n  synthesized_plan: synthesizedPlan,\n  individual_responses: individualResponses,\n  timestamp: endTime.toISOString(),\n  execution_time: executionTime\n};"
      },
      "id": "create-final-response",
      "name": "Create Final Response",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [1340, 400]
    },
    {
      "parameters": {
        "respondWith": "json",
        "responseBody": "={{ $json }}",
        "options": {}
      },
      "id": "success-response",
      "name": "Success Response",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1,
      "position": [1560, 400]
    }
  ],
  "connections": {
    "webhook-start": {
      "main": [
        [
          {
            "node": "validate-input",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "validate-input": {
      "main": [
        [
          {
            "node": "error-response",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "normalize-input",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "normalize-input": {
      "main": [
        [
          {
            "node": "select-agents",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "select-agents": {
      "main": [
        [
          {
            "node": "generate-responses",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "generate-responses": {
      "main": [
        [
          {
            "node": "create-final-response",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "create-final-response": {
      "main": [
        [
          {
            "node": "success-response",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "pinData": {},
  "settings": {
    "executionOrder": "v1"
  },
  "staticData": null,
  "tags": [],
  "triggerCount": 1,
  "updatedAt": "2024-01-15T10:30:00.000Z",
  "versionId": "1"
}
