AutomationFlowsAI & RAG › Optimize Classroom Schedules and Resolve Conflicts with Gpt-4o and Google…

Optimize Classroom Schedules and Resolve Conflicts with Gpt-4o and Google…

Original n8n title: Optimize Classroom Schedules and Resolve Conflicts with Gpt-4o and Google Calendar

ByCheng Siong Chin @cschin on n8n.io

This workflow automates competitive intelligence gathering and market analysis for businesses needing real-time insights on competitors, industry trends, and market positioning. Designed for marketing teams, strategy analysts, and business development professionals, it solves…

Cron / scheduled trigger★★★★★ complexityAI-powered34 nodesOpenAI ChatOutput Parser StructuredAgentSlackEmail SendAgent ToolTool CodeGoogle Calendar Tool
AI & RAG Trigger: Cron / scheduled Nodes: 34 Complexity: ★★★★★ AI nodes: yes Added:

This workflow corresponds to n8n.io template #13319 — we link there as the canonical source.

This workflow follows the Agent → Agenttool recipe pattern — see all workflows that pair these two integrations.

The workflow JSON

Copy or download the full n8n JSON below. Paste it into a new n8n workflow, add your credentials, activate. Full import guide →

Download .json
{
  "id": "Vr-mOV2RREVkuCkKOC5Bt",
  "name": "AI-Driven Classroom Scheduling and Conflict Resolution System",
  "tags": [],
  "nodes": [
    {
      "id": "479fd6ff-e579-4b92-bae1-2acba92f5cc7",
      "name": "Schedule Trigger",
      "type": "n8n-nodes-base.scheduleTrigger",
      "position": [
        176,
        528
      ],
      "parameters": {
        "rule": {
          "interval": [
            {
              "triggerAtHour": 6
            }
          ]
        }
      },
      "typeVersion": 1.3
    },
    {
      "id": "6bb8c3f4-fc66-4cd5-8be2-2bfbf211694c",
      "name": "Workflow Configuration",
      "type": "n8n-nodes-base.set",
      "position": [
        400,
        528
      ],
      "parameters": {
        "options": {},
        "assignments": {
          "assignments": [
            {
              "id": "id-1",
              "name": "slackChannelId",
              "type": "string",
              "value": "<__PLACEHOLDER_VALUE__Slack Channel ID for critical conflicts__>"
            },
            {
              "id": "id-2",
              "name": "schedulingTeamEmail",
              "type": "string",
              "value": "<__PLACEHOLDER_VALUE__Email address for scheduling team__>"
            },
            {
              "id": "id-3",
              "name": "maxClassroomCapacity",
              "type": "number",
              "value": 50
            },
            {
              "id": "id-4",
              "name": "minBreakBetweenClasses",
              "type": "number",
              "value": 15
            },
            {
              "id": "id-5",
              "name": "conflictThreshold",
              "type": "string",
              "value": "high"
            },
            {
              "id": "id-6",
              "name": "googleCalendarId",
              "type": "string",
              "value": "<__PLACEHOLDER_VALUE__Google Calendar ID for scheduling__>"
            },
            {
              "id": "id-7",
              "name": "autoResolutionThreshold",
              "type": "number",
              "value": 0.85
            },
            {
              "id": "id-8",
              "name": "historicalDataDays",
              "type": "number",
              "value": 90
            }
          ]
        },
        "includeOtherFields": true
      },
      "typeVersion": 3.4
    },
    {
      "id": "8bcc431e-add5-40c4-b812-24dd79389099",
      "name": "Prepare Scheduling Data",
      "type": "n8n-nodes-base.set",
      "position": [
        624,
        528
      ],
      "parameters": {
        "options": {},
        "assignments": {
          "assignments": [
            {
              "id": "id-1",
              "name": "classrooms",
              "type": "array",
              "value": "=[{\"id\": \"CR-101\", \"capacity\": 40, \"equipment\": [\"projector\", \"whiteboard\"], \"building\": \"Main\"}, {\"id\": \"CR-102\", \"capacity\": 30, \"equipment\": [\"computers\", \"projector\"], \"building\": \"Main\"}, {\"id\": \"CR-201\", \"capacity\": 50, \"equipment\": [\"projector\", \"audio_system\"], \"building\": \"Science\"}, {\"id\": \"LAB-301\", \"capacity\": 25, \"equipment\": [\"lab_equipment\", \"safety_gear\"], \"building\": \"Science\"}]"
            },
            {
              "id": "id-2",
              "name": "faculty",
              "type": "array",
              "value": "=[{\"id\": \"FAC-001\", \"name\": \"Dr. Smith\", \"department\": \"Mathematics\", \"maxHoursPerDay\": 6, \"preferredTimeSlots\": [\"morning\"]}, {\"id\": \"FAC-002\", \"name\": \"Prof. Johnson\", \"department\": \"Physics\", \"maxHoursPerDay\": 5, \"preferredTimeSlots\": [\"afternoon\"]}, {\"id\": \"FAC-003\", \"name\": \"Dr. Williams\", \"department\": \"Chemistry\", \"maxHoursPerDay\": 6, \"preferredTimeSlots\": [\"morning\", \"afternoon\"]}]"
            },
            {
              "id": "id-3",
              "name": "timetableRequests",
              "type": "array",
              "value": "=[{\"courseId\": \"MATH-101\", \"facultyId\": \"FAC-001\", \"requiredCapacity\": 35, \"duration\": 90, \"preferredTime\": \"09:00\", \"equipment\": [\"projector\"]}, {\"courseId\": \"PHYS-201\", \"facultyId\": \"FAC-002\", \"requiredCapacity\": 28, \"duration\": 120, \"preferredTime\": \"14:00\", \"equipment\": [\"projector\", \"audio_system\"]}, {\"courseId\": \"CHEM-301\", \"facultyId\": \"FAC-003\", \"requiredCapacity\": 20, \"duration\": 180, \"preferredTime\": \"10:00\", \"equipment\": [\"lab_equipment\"]}]"
            }
          ]
        },
        "includeOtherFields": true
      },
      "typeVersion": 3.4
    },
    {
      "id": "b008d65a-65a7-4e9a-93e4-ed92d64bb021",
      "name": "OpenAI Model - Resource Agent",
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenAi",
      "position": [
        848,
        640
      ],
      "parameters": {
        "model": {
          "__rl": true,
          "mode": "id",
          "value": "gpt-4o"
        },
        "options": {
          "temperature": 0.2
        },
        "builtInTools": {}
      },
      "credentials": {
        "openAiApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1.3
    },
    {
      "id": "84a74081-c5d3-4860-a6f8-b9e0a86bf34c",
      "name": "Resource Analysis Output Parser",
      "type": "@n8n/n8n-nodes-langchain.outputParserStructured",
      "position": [
        1040,
        624
      ],
      "parameters": {
        "schemaType": "manual",
        "inputSchema": "{\n  \"type\": \"object\",\n  \"properties\": {\n    \"resourceAnalysis\": {\n      \"type\": \"object\",\n      \"properties\": {\n        \"classroomAvailability\": {\n          \"type\": \"array\",\n          \"items\": {\n            \"type\": \"object\",\n            \"properties\": {\n              \"classroomId\": {\"type\": \"string\"},\n              \"availableSlots\": {\"type\": \"array\", \"items\": {\"type\": \"string\"}},\n              \"utilizationRate\": {\"type\": \"number\"},\n              \"conflicts\": {\"type\": \"array\", \"items\": {\"type\": \"string\"}}\n            }\n          }\n        },\n        \"facultyConstraints\": {\n          \"type\": \"array\",\n          \"items\": {\n            \"type\": \"object\",\n            \"properties\": {\n              \"facultyId\": {\"type\": \"string\"},\n              \"availableHours\": {\"type\": \"number\"},\n              \"scheduledHours\": {\"type\": \"number\"},\n              \"violations\": {\"type\": \"array\", \"items\": {\"type\": \"string\"}}\n            }\n          }\n        },\n        \"equipmentMatches\": {\n          \"type\": \"array\",\n          \"items\": {\n            \"type\": \"object\",\n            \"properties\": {\n              \"courseId\": {\"type\": \"string\"},\n              \"matchingClassrooms\": {\"type\": \"array\", \"items\": {\"type\": \"string\"}},\n              \"equipmentGaps\": {\"type\": \"array\", \"items\": {\"type\": \"string\"}}\n            }\n          }\n        },\n        \"overallFeasibility\": {\"type\": \"string\"},\n        \"criticalIssues\": {\"type\": \"array\", \"items\": {\"type\": \"string\"}}\n      }\n    }\n  }\n}"
      },
      "typeVersion": 1.3
    },
    {
      "id": "dbd1e05f-4ba4-421d-bbe9-9bba24c68abc",
      "name": "Resource Analysis Agent",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "position": [
        848,
        416
      ],
      "parameters": {
        "text": "=Classroom Data: {{ JSON.stringify($json.classrooms) }}\n\nFaculty Data: {{ JSON.stringify($json.faculty) }}\n\nTimetable Requests: {{ JSON.stringify($json.timetableRequests) }}\n\nConstraints: Max Capacity={{ $('Workflow Configuration').first().json.maxClassroomCapacity }}, Min Break={{ $('Workflow Configuration').first().json.minBreakBetweenClasses }} minutes",
        "options": {
          "systemMessage": "You are a Resource Analysis Agent specialized in evaluating classroom scheduling constraints.\n\nYour task is to:\n1. Analyze classroom availability, capacity, and equipment against timetable requests\n2. Evaluate faculty workload constraints including max hours per day and preferred time slots\n3. Identify equipment mismatches between course requirements and classroom capabilities\n4. Calculate classroom utilization rates and identify over/under-utilized spaces\n5. Detect scheduling conflicts including:\n   - Double-booked classrooms\n   - Faculty teaching multiple classes simultaneously\n   - Insufficient break time between classes\n   - Capacity violations (students exceeding room capacity)\n   - Equipment unavailability\n6. Assess overall scheduling feasibility\n7. Flag critical issues that require immediate attention\n8. Return structured analysis with detailed breakdowns\n\nConsider:\n- Classroom capacity must exceed required capacity by at least 10% for safety\n- Faculty cannot exceed their maximum daily hours\n- Minimum break time between classes must be respected\n- Equipment requirements must be fully met\n- Building proximity for back-to-back faculty classes\n\nProvide comprehensive resource analysis in the defined JSON structure."
        },
        "promptType": "define",
        "hasOutputParser": true
      },
      "typeVersion": 3.1
    },
    {
      "id": "bbd6b242-debc-49c4-ade2-db55d0db4d40",
      "name": "OpenAI Model - Operations Agent",
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenAi",
      "position": [
        1232,
        608
      ],
      "parameters": {
        "model": {
          "__rl": true,
          "mode": "id",
          "value": "gpt-4o"
        },
        "options": {
          "temperature": 0.2
        },
        "builtInTools": {}
      },
      "credentials": {
        "openAiApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1.3
    },
    {
      "id": "2dfdb18b-4bfa-4e18-a86b-539c3e6f2d9e",
      "name": "Operations Output Parser",
      "type": "@n8n/n8n-nodes-langchain.outputParserStructured",
      "position": [
        1408,
        512
      ],
      "parameters": {
        "schemaType": "manual",
        "inputSchema": "{\n  \"type\": \"object\",\n  \"properties\": {\n    \"schedulingRecommendations\": {\n      \"type\": \"object\",\n      \"properties\": {\n        \"optimalSchedule\": {\n          \"type\": \"array\",\n          \"items\": {\n            \"type\": \"object\",\n            \"properties\": {\n              \"courseId\": {\"type\": \"string\"},\n              \"classroomId\": {\"type\": \"string\"},\n              \"facultyId\": {\"type\": \"string\"},\n              \"timeSlot\": {\"type\": \"string\"},\n              \"duration\": {\"type\": \"number\"},\n              \"confidence\": {\"type\": \"number\"}\n            }\n          }\n        },\n        \"conflicts\": {\n          \"type\": \"array\",\n          \"items\": {\n            \"type\": \"object\",\n            \"properties\": {\n              \"conflictId\": {\"type\": \"string\"},\n              \"type\": {\"type\": \"string\"},\n              \"severity\": {\"type\": \"string\"},\n              \"affectedCourses\": {\"type\": \"array\", \"items\": {\"type\": \"string\"}},\n              \"description\": {\"type\": \"string\"},\n              \"resolutionOptions\": {\"type\": \"array\", \"items\": {\"type\": \"string\"}}\n            }\n          }\n        },\n        \"alternativeOptions\": {\n          \"type\": \"array\",\n          \"items\": {\n            \"type\": \"object\",\n            \"properties\": {\n              \"courseId\": {\"type\": \"string\"},\n              \"alternatives\": {\"type\": \"array\", \"items\": {\"type\": \"object\"}}\n            }\n          }\n        },\n        \"escalationRequired\": {\"type\": \"boolean\"},\n        \"escalationReason\": {\"type\": \"string\"},\n        \"overallStatus\": {\"type\": \"string\"},\n        \"actionItems\": {\"type\": \"array\", \"items\": {\"type\": \"string\"}}\n      }\n    }\n  }\n}"
      },
      "typeVersion": 1.3
    },
    {
      "id": "a0445ec3-51b2-46a5-8631-66f847803fcd",
      "name": "Operations Agent",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "position": [
        1248,
        320
      ],
      "parameters": {
        "text": "=Resource Analysis Results: {{ JSON.stringify($json.output) }}\n\nOriginal Requests: {{ JSON.stringify($('Prepare Scheduling Data').first().json.timetableRequests) }}",
        "options": {
          "systemMessage": "You are an Operations Agent specialized in orchestrating classroom scheduling and conflict resolution.\n\nYour task is to:\n1. Review the resource analysis from the Resource Analysis Agent\n2. Generate optimal scheduling recommendations that:\n   - Maximize classroom utilization\n   - Respect all faculty constraints\n   - Meet equipment requirements\n   - Minimize conflicts\n   - Balance workload across time slots\n3. Identify and classify conflicts by severity:\n   - CRITICAL: Safety violations, double bookings, impossible constraints\n   - HIGH: Significant capacity issues, major equipment gaps\n   - MEDIUM: Suboptimal scheduling, minor constraint violations\n   - LOW: Preference mismatches, efficiency improvements\n4. Provide alternative scheduling options for conflicted courses\n5. Determine if escalation to human decision-makers is required\n6. Generate actionable recommendations with specific resolution steps\n7. Assess overall scheduling status (OPTIMAL, ACCEPTABLE, PROBLEMATIC, CRITICAL)\n\nEscalation criteria:\n- Any CRITICAL severity conflicts\n- More than 3 HIGH severity conflicts\n- Impossible to schedule all courses within constraints\n- Faculty workload violations that cannot be resolved\n\nProvide comprehensive scheduling recommendations in the defined JSON structure with clear action items."
        },
        "promptType": "define",
        "hasOutputParser": true
      },
      "typeVersion": 3.1
    },
    {
      "id": "17d5f16f-6c16-4305-ae9a-11af379c6150",
      "name": "Route by Severity",
      "type": "n8n-nodes-base.switch",
      "position": [
        3328,
        416
      ],
      "parameters": {
        "rules": {
          "values": [
            {
              "outputKey": "Critical",
              "conditions": {
                "options": {
                  "leftValue": "",
                  "caseSensitive": true,
                  "typeValidation": "strict"
                },
                "combinator": "and",
                "conditions": [
                  {
                    "operator": {
                      "type": "boolean",
                      "operation": "true"
                    },
                    "leftValue": "={{ $json.output.schedulingRecommendations.escalationRequired }}",
                    "rightValue": true
                  }
                ]
              },
              "renameOutput": true
            },
            {
              "outputKey": "Standard",
              "conditions": {
                "options": {
                  "leftValue": "",
                  "caseSensitive": true,
                  "typeValidation": "strict"
                },
                "combinator": "and",
                "conditions": [
                  {
                    "operator": {
                      "type": "boolean",
                      "operation": "false"
                    },
                    "leftValue": "={{ $json.output.schedulingRecommendations.escalationRequired }}",
                    "rightValue": false
                  }
                ]
              },
              "renameOutput": true
            }
          ]
        },
        "options": {}
      },
      "typeVersion": 3.4
    },
    {
      "id": "0d827b64-51c9-4d22-98a7-da0b2f8af538",
      "name": "Notify Critical Conflicts",
      "type": "n8n-nodes-base.slack",
      "position": [
        3552,
        320
      ],
      "parameters": {
        "text": "=\ud83d\udea8 CRITICAL SCHEDULING CONFLICT ALERT\n\n*Status:* {{ $json.output.schedulingRecommendations.overallStatus }}\n*Escalation Reason:* {{ $json.output.schedulingRecommendations.escalationReason }}\n\n*Conflicts Detected:*\n{{ $json.output.schedulingRecommendations.conflicts.map(c => `\u2022 [${c.severity}] ${c.type}: ${c.description}`).join(\"\\n\") }}\n\n*Action Items:*\n{{ $json.output.schedulingRecommendations.actionItems.map((item, i) => `${i+1}. ${item}`).join(\"\\n\") }}\n\n*Affected Courses:*\n{{ $json.output.schedulingRecommendations.conflicts.flatMap(c => c.affectedCourses).join(\", \") }}\n\n\u26a0\ufe0f Manual review and decision required.",
        "select": "channel",
        "channelId": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $('Workflow Configuration').first().json.slackChannelId }}"
        },
        "otherOptions": {},
        "authentication": "oAuth2"
      },
      "credentials": {
        "slackOAuth2Api": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 2.4
    },
    {
      "id": "a452b332-8e6e-4321-9845-6d7306c525a5",
      "name": "Email Scheduling Recommendations",
      "type": "n8n-nodes-base.emailSend",
      "position": [
        3552,
        512
      ],
      "parameters": {
        "html": "=<html>\n<head>\n<style>\n  body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }\n  h2 { color: #2c3e50; border-bottom: 2px solid #3498db; padding-bottom: 10px; }\n  h3 { color: #34495e; margin-top: 20px; }\n  .status { padding: 10px; border-radius: 5px; font-weight: bold; }\n  .optimal { background-color: #d4edda; color: #155724; }\n  .acceptable { background-color: #fff3cd; color: #856404; }\n  .problematic { background-color: #f8d7da; color: #721c24; }\n  .critical { background-color: #f8d7da; color: #721c24; border: 2px solid #721c24; }\n  table { border-collapse: collapse; width: 100%; margin: 15px 0; }\n  th, td { border: 1px solid #ddd; padding: 12px; text-align: left; }\n  th { background-color: #3498db; color: white; }\n  tr:nth-child(even) { background-color: #f2f2f2; }\n  .conflict { margin: 10px 0; padding: 10px; border-left: 4px solid #e74c3c; background-color: #fadbd8; }\n  .action-item { margin: 5px 0; padding: 8px; background-color: #e8f4f8; border-left: 3px solid #3498db; }\n</style>\n</head>\n<body>\n<h2>Classroom Scheduling Recommendations</h2>\n\n<div class=\"status {{ $json.output.schedulingRecommendations.overallStatus.toLowerCase() }}\">\n  Overall Status: {{ $json.output.schedulingRecommendations.overallStatus }}\n</div>\n\n<h3>Optimal Schedule</h3>\n<table>\n  <tr>\n    <th>Course ID</th>\n    <th>Classroom</th>\n    <th>Faculty</th>\n    <th>Time Slot</th>\n    <th>Duration (min)</th>\n    <th>Confidence</th>\n  </tr>\n  {{ $json.output.schedulingRecommendations.optimalSchedule.map(s => `\n  <tr>\n    <td>${s.courseId}</td>\n    <td>${s.classroomId}</td>\n    <td>${s.facultyId}</td>\n    <td>${s.timeSlot}</td>\n    <td>${s.duration}</td>\n    <td>${(s.confidence * 100).toFixed(0)}%</td>\n  </tr>\n  `).join(\"\") }}\n</table>\n\n{{ $json.output.schedulingRecommendations.conflicts.length > 0 ? `\n<h3>Conflicts Detected (${$json.output.schedulingRecommendations.conflicts.length})</h3>\n${$json.output.schedulingRecommendations.conflicts.map(c => `\n<div class=\"conflict\">\n  <strong>[${c.severity}] ${c.type}</strong><br>\n  ${c.description}<br>\n  <em>Affected Courses: ${c.affectedCourses.join(\", \")}</em><br>\n  <strong>Resolution Options:</strong>\n  <ul>\n    ${c.resolutionOptions.map(opt => `<li>${opt}</li>`).join(\"\")}\n  </ul>\n</div>\n`).join(\"\")}` : \"<p>No conflicts detected.</p>\" }}\n\n<h3>Action Items</h3>\n{{ $json.output.schedulingRecommendations.actionItems.map((item, i) => `\n<div class=\"action-item\">\n  ${i+1}. ${item}\n</div>\n`).join(\"\") }}\n\n<hr>\n<p><em>Generated: {{ $now.toISO() }}</em></p>\n</body>\n</html>",
        "options": {},
        "subject": "=Classroom Scheduling Recommendations - {{ $json.output.schedulingRecommendations.overallStatus }}",
        "toEmail": "={{ $('Workflow Configuration').first().json.schedulingTeamEmail }}",
        "fromEmail": "<__PLACEHOLDER_VALUE__Sender email address__>"
      },
      "typeVersion": 2.1
    },
    {
      "id": "ba3dcaf5-c05b-4ac9-9e0f-92703690a942",
      "name": "Log Results",
      "type": "n8n-nodes-base.code",
      "position": [
        3776,
        416
      ],
      "parameters": {
        "jsCode": "const items = $input.all();\n\nconst logEntry = {\n  timestamp: new Date().toISOString(),\n  workflowRun: 'Classroom Scheduling Analysis',\n  totalItems: items.length,\n  results: items.map(item => ({\n    status: item.json.output?.schedulingRecommendations?.overallStatus || 'Unknown',\n    escalationRequired: item.json.output?.schedulingRecommendations?.escalationRequired || false,\n    conflictsCount: item.json.output?.schedulingRecommendations?.conflicts?.length || 0,\n    scheduledCourses: item.json.output?.schedulingRecommendations?.optimalSchedule?.length || 0\n  }))\n};\n\nconsole.log('=== Scheduling Workflow Completed ===');\nconsole.log(JSON.stringify(logEntry, null, 2));\n\nreturn [{ json: logEntry }];"
      },
      "typeVersion": 2
    },
    {
      "id": "e13f6c61-8397-4567-bf78-288e11c9f06b",
      "name": "OpenAI Model - Optimization Agent",
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenAi",
      "position": [
        1872,
        1024
      ],
      "parameters": {
        "model": {
          "__rl": true,
          "mode": "id",
          "value": "gpt-4o"
        },
        "options": {
          "temperature": 0.3
        },
        "builtInTools": {}
      },
      "credentials": {
        "openAiApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1.3
    },
    {
      "id": "b2b34539-180f-44d7-89ad-26634d922083",
      "name": "Optimization Output Parser",
      "type": "@n8n/n8n-nodes-langchain.outputParserStructured",
      "position": [
        2048,
        1024
      ],
      "parameters": {
        "schemaType": "manual",
        "inputSchema": "{\n  \"type\": \"object\",\n  \"properties\": {\n    \"optimizedSchedule\": {\n      \"type\": \"array\",\n      \"items\": {\n        \"type\": \"object\",\n        \"properties\": {\n          \"courseId\": {\"type\": \"string\"},\n          \"classroomId\": {\"type\": \"string\"},\n          \"timeSlot\": {\"type\": \"string\"},\n          \"optimizationScore\": {\"type\": \"number\"},\n          \"reasoning\": {\"type\": \"string\"}\n        }\n      }\n    },\n    \"efficiencyGains\": {\"type\": \"number\"},\n    \"conflictsResolved\": {\"type\": \"number\"}\n  }\n}"
      },
      "typeVersion": 1.3
    },
    {
      "id": "dd4b9977-321e-485f-aed2-29fb26996bc3",
      "name": "Schedule Optimization Agent Tool",
      "type": "@n8n/n8n-nodes-langchain.agentTool",
      "position": [
        1904,
        816
      ],
      "parameters": {
        "text": "={{ $fromAI('scheduleData', 'Current schedule and constraints to optimize', 'json') }}",
        "options": {
          "systemMessage": "You are a Schedule Optimization specialist.\n\nYour task is to:\n1. Analyze the provided schedule and identify optimization opportunities\n2. Apply advanced scheduling algorithms to maximize efficiency\n3. Consider historical patterns and preferences\n4. Minimize conflicts while respecting all constraints\n5. Calculate optimization scores for each proposed change\n6. Return optimized schedule with efficiency metrics"
        },
        "hasOutputParser": true,
        "toolDescription": "Optimizes classroom schedules using advanced algorithms and historical data to maximize efficiency and minimize conflicts"
      },
      "typeVersion": 3
    },
    {
      "id": "4b9208d9-a86c-4108-8674-4a0b7f435c77",
      "name": "Conflict Score Calculator Tool",
      "type": "@n8n/n8n-nodes-langchain.toolCode",
      "position": [
        2192,
        816
      ],
      "parameters": {
        "jsCode": "try {\n  const conflicts = typeof query === 'string' ? JSON.parse(query) : query;\n  \n  if (!Array.isArray(conflicts) || conflicts.length === 0) {\n    return JSON.stringify({ totalScore: 0, breakdown: [], riskLevel: 'NONE' });\n  }\n  \n  // Severity weights\n  const severityWeights = {\n    'CRITICAL': 10,\n    'HIGH': 5,\n    'MEDIUM': 2,\n    'LOW': 1\n  };\n  \n  // Calculate conflict scores\n  const breakdown = conflicts.map(conflict => {\n    const severityScore = severityWeights[conflict.severity] || 1;\n    const affectedCount = (conflict.affectedCourses || []).length;\n    const complexityFactor = affectedCount > 2 ? 1.5 : 1.0;\n    \n    const score = severityScore * affectedCount * complexityFactor;\n    \n    return {\n      conflictId: conflict.conflictId || 'unknown',\n      type: conflict.type || 'unknown',\n      severity: conflict.severity || 'LOW',\n      score: Math.round(score * 10) / 10,\n      affectedCourses: affectedCount\n    };\n  });\n  \n  const totalScore = breakdown.reduce((sum, item) => sum + item.score, 0);\n  \n  // Determine risk level\n  let riskLevel = 'LOW';\n  if (totalScore > 50) riskLevel = 'CRITICAL';\n  else if (totalScore > 25) riskLevel = 'HIGH';\n  else if (totalScore > 10) riskLevel = 'MEDIUM';\n  \n  const result = {\n    totalScore: Math.round(totalScore * 10) / 10,\n    breakdown,\n    riskLevel,\n    conflictCount: conflicts.length,\n    criticalCount: conflicts.filter(c => c.severity === 'CRITICAL').length,\n    highCount: conflicts.filter(c => c.severity === 'HIGH').length\n  };\n  \n  return JSON.stringify(result, null, 2);\n  \n} catch (error) {\n  return `Error calculating conflict scores: ${error.message}`;\n}",
        "description": "Calculates weighted conflict scores based on severity, affected courses, and complexity to prioritize resolution efforts"
      },
      "typeVersion": 1.3
    },
    {
      "id": "b14d5021-4b94-4372-b034-cbeacb5aaf94",
      "name": "Google Calendar Tool",
      "type": "n8n-nodes-base.googleCalendarTool",
      "position": [
        2352,
        864
      ],
      "parameters": {
        "options": {},
        "calendar": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $('Workflow Configuration').first().json.googleCalendarId }}"
        },
        "operation": "getAll",
        "returnAll": true
      },
      "credentials": {
        "googleCalendarOAuth2Api": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1.3
    },
    {
      "id": "1eedb8fb-0aa6-4e53-8de9-57a8e71d9b11",
      "name": "Calculate Historical Patterns",
      "type": "n8n-nodes-base.code",
      "position": [
        1296,
        944
      ],
      "parameters": {
        "jsCode": "const schedulingData = $input.first().json;\nconst historicalDays = $('Workflow Configuration').first().json.historicalDataDays || 90;\n\n// Simulate historical scheduling patterns analysis\n// In production, this would query a database of past schedules\nconst classrooms = schedulingData.classrooms || [];\nconst faculty = schedulingData.faculty || [];\n\nconst historicalPatterns = {\n  classroomUtilization: classrooms.map(room => ({\n    classroomId: room.id,\n    avgUtilization: Math.random() * 0.4 + 0.5, // 50-90%\n    peakHours: ['09:00-12:00', '14:00-16:00'],\n    preferredDays: ['Monday', 'Wednesday', 'Friday'],\n    conflictFrequency: Math.random() * 0.2 // 0-20%\n  })),\n  facultyPreferences: faculty.map(fac => ({\n    facultyId: fac.id,\n    preferredTimeSlots: fac.preferredTimeSlots || [],\n    avgClassesPerDay: Math.random() * 2 + 2, // 2-4 classes\n    cancellationRate: Math.random() * 0.1, // 0-10%\n    studentSatisfactionScore: Math.random() * 0.3 + 0.7 // 70-100%\n  })),\n  conflictTrends: {\n    totalConflictsLast90Days: Math.floor(Math.random() * 50 + 10),\n    mostCommonConflictType: 'Equipment Unavailability',\n    resolutionSuccessRate: 0.78,\n    avgResolutionTime: '2.5 hours'\n  },\n  seasonalPatterns: {\n    highDemandPeriods: ['September-October', 'January-February'],\n    lowDemandPeriods: ['June-August', 'December'],\n    examPeriodAdjustments: true\n  },\n  analysisDate: new Date().toISOString(),\n  dataRangeDays: historicalDays\n};\n\nreturn [{ json: { historicalPatterns, originalData: schedulingData } }];"
      },
      "typeVersion": 2
    },
    {
      "id": "576818d7-ab5a-43e2-badc-cfc5cad76b9a",
      "name": "Merge Analysis Results",
      "type": "n8n-nodes-base.merge",
      "position": [
        1584,
        688
      ],
      "parameters": {
        "numberInputs": 3
      },
      "typeVersion": 3.2
    },
    {
      "id": "118e1d3d-0f76-44d1-93ec-141e3b3e1104",
      "name": "Check Auto-Resolution Possible",
      "type": "n8n-nodes-base.if",
      "position": [
        2656,
        592
      ],
      "parameters": {
        "options": {},
        "conditions": {
          "options": {
            "leftValue": "",
            "caseSensitive": false,
            "typeValidation": "loose"
          },
          "combinator": "and",
          "conditions": [
            {
              "id": "id-1",
              "operator": {
                "type": "boolean",
                "operation": "equals"
              },
              "leftValue": "={{ $json.output.finalDecision.canAutoResolve }}",
              "rightValue": true
            },
            {
              "id": "id-2",
              "operator": {
                "type": "number",
                "operation": "gte"
              },
              "leftValue": "={{ $json.output.finalDecision.confidence }}",
              "rightValue": "0.85"
            }
          ]
        }
      },
      "typeVersion": 2.3
    },
    {
      "id": "99b998ed-cb30-4a29-bd7d-51750a9dc0e8",
      "name": "Apply Auto-Resolution",
      "type": "n8n-nodes-base.set",
      "position": [
        2880,
        480
      ],
      "parameters": {
        "options": {},
        "assignments": {
          "assignments": [
            {
              "id": "id-1",
              "name": "resolutionType",
              "type": "string",
              "value": "AUTO_RESOLVED"
            },
            {
              "id": "id-2",
              "name": "resolutionTimestamp",
              "type": "string",
              "value": "={{ $now.toISO() }}"
            },
            {
              "id": "id-3",
              "name": "appliedActions",
              "type": "array",
              "value": "={{ $json.output.finalDecision.recommendedActions }}"
            },
            {
              "id": "id-4",
              "name": "autoResolutionConfidence",
              "type": "number",
              "value": "={{ $json.output.finalDecision.confidence }}"
            }
          ]
        },
        "includeOtherFields": true
      },
      "typeVersion": 3.4
    },
    {
      "id": "724d21f2-b70e-43b3-ad78-056b56d2ef3a",
      "name": "Generate Conflict Report",
      "type": "n8n-nodes-base.code",
      "position": [
        2880,
        784
      ],
      "parameters": {
        "jsCode": "const data = $input.first().json;\n\nconst conflictReport = {\n  resolutionType: 'MANUAL_ESCALATION',\n  escalationTimestamp: new Date().toISOString(),\n  decision: data.output?.finalDecision || {},\n  conflictSummary: {\n    totalConflictScore: data.output?.finalDecision?.conflictScoreTotal || 0,\n    riskLevel: data.output?.finalDecision?.riskAssessment || 'UNKNOWN',\n    cannotAutoResolveReason: data.output?.finalDecision?.reasoning || 'Insufficient confidence or high-risk conflicts detected',\n    requiresHumanReview: true\n  },\n  recommendedActions: data.output?.finalDecision?.recommendedActions || [],\n  escalationPriority: data.output?.finalDecision?.conflictScoreTotal > 30 ? 'URGENT' : 'STANDARD',\n  reportGeneratedAt: new Date().toISOString()\n};\n\nreturn [{ json: { ...data, conflictReport } }];"
      },
      "typeVersion": 2
    },
    {
      "id": "50afa3d1-c4c5-43ae-80e6-5c95c6e75c22",
      "name": "Merge Resolution Paths",
      "type": "n8n-nodes-base.merge",
      "position": [
        3104,
        592
      ],
      "parameters": {},
      "typeVersion": 3.2
    },
    {
      "id": "df89450b-422f-4982-8f72-e075650f148d",
      "name": "Master Orchestrator Agent",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "position": [
        2112,
        592
      ],
      "parameters": {
        "text": "=Combined Analysis:\n\nResource Analysis: {{ JSON.stringify($json[0].output) }}\n\nHistorical Patterns: {{ JSON.stringify($json[1].historicalPatterns) }}\n\nOperations Recommendations: {{ JSON.stringify($json[2].output) }}",
        "options": {
          "systemMessage": "You are the Master Orchestrator Agent coordinating complex classroom scheduling decisions.\n\nYour task is to:\n1. Synthesize inputs from Resource Analysis, Historical Patterns, and Operations recommendations\n2. Use the Schedule Optimization Agent Tool to generate optimized schedules\n3. Use the Conflict Score Calculator Tool to quantify conflict severity\n4. Use the Google Calendar Tool to check existing calendar events and availability\n5. Determine if conflicts can be auto-resolved based on:\n   - Conflict score below threshold\n   - High confidence in optimization (>85%)\n   - No CRITICAL severity conflicts\n   - Calendar availability confirmed\n6. Provide comprehensive decision with reasoning\n7. Recommend specific actions for both auto-resolution and manual escalation paths\n\nDecision criteria for auto-resolution:\n- Total conflict score < 15\n- Optimization confidence > 85%\n- No CRITICAL conflicts\n- All affected time slots available in calendar\n- Historical success rate for similar scenarios > 75%\n\nReturn structured decision with confidence scores and detailed reasoning."
        },
        "promptType": "define",
        "hasOutputParser": true
      },
      "typeVersion": 3.1
    },
    {
      "id": "70ead711-0b9e-4706-ab2e-af450586a61d",
      "name": "OpenAI Model - Master Orchestrator",
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenAi",
      "position": [
        1776,
        864
      ],
      "parameters": {
        "model": {
          "__rl": true,
          "mode": "id",
          "value": "gpt-4o"
        },
        "options": {
          "temperature": 0.1
        },
        "builtInTools": {}
      },
      "credentials": {
        "openAiApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1.3
    },
    {
      "id": "c33a2b3c-daa8-4c7c-8620-1ce2b9fdfadd",
      "name": "Master Orchestrator Output Parser",
      "type": "@n8n/n8n-nodes-langchain.outputParserStructured",
      "position": [
        2512,
        832
      ],
      "parameters": {
        "schemaType": "manual",
        "inputSchema": "{\n  \"type\": \"object\",\n  \"properties\": {\n    \"finalDecision\": {\n      \"type\": \"object\",\n      \"properties\": {\n        \"canAutoResolve\": {\"type\": \"boolean\"},\n        \"confidence\": {\"type\": \"number\"},\n        \"recommendedActions\": {\"type\": \"array\", \"items\": {\"type\": \"string\"}},\n        \"riskAssessment\": {\"type\": \"string\"},\n        \"calendarIntegration\": {\"type\": \"boolean\"},\n        \"optimizationApplied\": {\"type\": \"boolean\"},\n        \"conflictScoreTotal\": {\"type\": \"number\"},\n        \"reasoning\": {\"type\": \"string\"}\n      }\n    }\n  }\n}"
      },
      "typeVersion": 1.3
    },
    {
      "id": "ef4414b6-5f60-498e-9a9f-0635311bcb56",
      "name": "Sticky Note",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        928,
        -112
      ],
      "parameters": {
        "width": 528,
        "height": 224,
        "content": "## Setup Steps\n1. Connect **Schedule Trigger** (set monitoring frequency: daily/weekly)\n2. Configure **Fetch Data** node with competitor website URLs/APIs\n3. Add **OpenAI API keys** to all AI agent nodes \n4. Link **Google Sheets** credentials for storing historical analysis data\n5. Configure **Gmail** node with SMTP credentials for report distribution\n6. Set up **Slack/Discord** webhooks for instant critical alert notifications"
      },
      "typeVersion": 1
    },
    {
      "id": "fbe736db-09d4-4186-b686-5dab29400759",
      "name": "Sticky Note1",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        1552,
        -240
      ],
      "parameters": {
        "color": 6,
        "width": 544,
        "height": 352,
        "content": "## Prerequisites\nOpenAI API account (GPT-4 recommended), competitor data sources/APIs\n## Use Cases\nSaaS competitor feature tracking, retail pricing intelligence\n## Customization\nModify AI prompts for industry-specific metrics, adjust sentiment thresholds for alert triggers\n## Benefits\nReduces research time by 85%, provides 24/7 competitor monitoring, eliminates manual data aggregation"
      },
      "typeVersion": 1
    },
    {
      "id": "019e6fb8-e639-49ed-8632-931e8079b60f",
      "name": "Sticky Note2",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        176,
        -176
      ],
      "parameters": {
        "width": 688,
        "height": 288,
        "content": "## How It Works\nThis workflow automates competitive intelligence gathering and market analysis for businesses needing real-time insights on competitors, industry trends, and market positioning. Designed for marketing teams, strategy analysts, and business development professionals, it solves the time-intensive challenge of manually monitoring competitor activities across multiple channels. The system schedules regular data collection, fetches competitor information from various sources, employs multiple AI agents (OpenAI for analysis, sentiment evaluation, and report generation) to process data, validates outputs through structured parsing, and delivers comprehensive reports via email. By automating data aggregation, sentiment analysis, and insight generation, organizations gain actionable intelligence faster, identify market opportunities proactively, and maintain competitive advantage through continuous monitoring\u2014essential for dynamic markets where timing determines success."
      },
      "typeVersion": 1
    },
    {
      "id": "bc78b664-b332-4468-9281-c9e70c88504b",
      "name": "Sticky Note3",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        3280,
        176
      ],
      "parameters": {
        "color": 7,
        "width": 880,
        "height": 1024,
        "content": "## Report Generation & Distribution\n**Why**: Delivers actionable intelligence to decision-makers instantly for rapid strategic pivots"
      },
      "typeVersion": 1
    },
    {
      "id": "d191664f-a3e2-4a9a-a73b-125e76c065de",
      "name": "Sticky Note4",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        1152,
        192
      ],
      "parameters": {
        "color": 7,
        "width": 592,
        "height": 976,
        "content": "## Multi-Agent AI Analysis\n**Why**: Delivers expert-level analysis across multiple dimensions simultaneously, uncovering hidden patterns humans miss"
      },
      "typeVersion": 1
    },
    {
      "id": "1cba53ca-d2a1-47f5-9678-47c4b2b399bb",
      "name": "Sticky Note5",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        128,
        192
      ],
      "parameters": {
        "color": 7,
        "width": 992,
        "height": 976,
        "content": "## Automated Data Collection\n**Why**: Schedule trigger initiates competitor data fetching at defined intervals to ensure continuous market monitoring without manual intervention, capturing time-sensitive competitive moves"
      },
      "typeVersion": 1
    },
    {
      "id": "44f96ae7-0652-499e-8d31-1132c00084d0",
      "name": "Sticky Note6",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        1760,
        192
      ],
      "parameters": {
        "color": 7,
        "width": 1488,
        "height": 1024,
        "content": "## Intelligent Routing & Validation\n**Why**: Ensures data quality and prioritizes critical insights requiring immediate strategic response"
      },
      "typeVersion": 1
    }
  ],
  "active": false,
  "settings": {
    "availableInMCP": false,
    "executionOrder": "v1"
  },
  "versionId": "7770899d-fac9-4946-bfde-4028c3715133",
  "connections": {
    "Operations Agent": {
      "main": [
        [
          {
            "node": "Route by Severity",
            "type": "main",
            "index": 0
          },
          {
            "node": "Merge Analysis Results",
            "type": "main",
            "index": 2
          }
        ]
      ]
    },
    "Schedule Trigger": {
      "main": [
        [
          {
            "node": "Workflow Configuration",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Route by Severity": {
      "main": [
        [
          {
            "node": "Notify Critical Conflicts",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Email Scheduling Recommendations",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Google Calendar Tool": {
      "ai_tool": [
        [
          {
            "node": "Master Orchestrator Agent",
            "type": "ai_tool",
            "index": 0
          }
        ]
      ]
    },
    "Apply Auto-Resolution": {
      "main": [
        [
          {
            "node": "Merge Resolution Paths",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Merge Analysis Results": {
      "main": [
        [
          {
            "node": "Master Orchestrator Agent",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Merge Resolution Paths": {
      "main": [
        [
          {
            "node": "Route by Severity",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Workflow Configuration": {
      "main": [
        [
          {
            "node": "Prepare Scheduling Data",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Prepare Scheduling Data": {
      "main": [
        [
          {
            "node": "Resource Analysis Agent",
            "type": "main",
            "index": 0
          },
          {
            "node": "Calculate Historical Patterns",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Resource Analysis Agent": {
      "main": [
        [
          {
            "node": "Operations Agent",
            "type": "main",
            "index": 0
          },
          {
            "node": "Merge Analysis Results",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Generate Conflict Report": {
      "main": [
        [
          {
            "node": "Merge Resolution Paths",
            "type": "main",
            "index": 1
          }
        ]
      ]
    },
    "Operations Output Parser": {
      "ai_outputParser": [
        [
          {
            "node": "Operations Agent",
            "type": "ai_outputParser",
            "index": 0
          }
        ]
      ]
    },
    "Master Orchestrator Agent": {
      "main": [
        [
          {
            "node": "Check Auto-Resolution Possible",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Notify Critical Conflicts": {
      "main": [
        [
          {
            "node": "Log Results",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Optimization Output Parser": {
      "ai_outputParser": [
        [
          {
            "node": "Schedule Optimization Agent Tool",
            "type": "ai_outputParser",
            "index": 0
          }
        ]
      ]
    },
    "Calculate Historical Patterns": {
      "main": [
        [
          {
            "node": "Merge Analysis Results",
            "type": "main",
            "index": 1
          }
        ]
      ]
    },
    "OpenAI Model - Resource Agent": {
      "ai_languageModel": [
        [
          {
            "node": "Resource Analysis Agent",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Check Auto-Resolution Possible": {
      "main": [
        [
          {
            "node": "Apply Auto-Resolution",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Generate Conflict Report",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Conflict Score Calculator Tool": {
      "ai_tool": [
        [
          {
            "node": "Master Orchestrator Agent",
            "type": "ai_tool",
            "index": 0
          }
        ]
      ]
    },
    "OpenAI Model - Operations Agent": {
      "ai_languageModel": [
        [
          {
            "node": "Operations Agent",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Resource Analysis Output Parser": {
      "ai_outputParser": [
        [
          {
            "node": "Resource Analysis Agent",
            "type": "ai_outputParser",
            "index": 0
          }
        ]
      ]
    },
    "Email Scheduling Recommendations": {
      "main": [
        [
          {
            "node": "Log Results",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Schedule Optimization Agent Tool": {
      "ai_tool": [
        [
          {
            "node": "Master Orchestrator Agent",
            "type": "ai_tool",
            "index": 0
          }
        ]
      ]
    },
    "Master Orchestrator Output Parser": {
      "ai_outputParser": [
        [
          {
            "node": "Master Orchestrator Agent",
            "type": "ai_outputParser",
            "index": 0
          }
        ]
      ]
    },
    "OpenAI Model - Optimization Agent": {
      "ai_languageModel": [
        [
          {
            "node": "Schedule Optimization Agent Tool",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "OpenAI Model - Master Orchestrator": {
      "ai_languageModel": [
        [
          {
            "node": "Master Orchestrator Agent",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    }
  }
}

Credentials you'll need

Each integration node will prompt for credentials when you import. We strip credential IDs before publishing — you'll add your own.

Pro

For the full experience including quality scoring and batch install features for each workflow upgrade to Pro

About this workflow

This workflow automates competitive intelligence gathering and market analysis for businesses needing real-time insights on competitors, industry trends, and market positioning. Designed for marketing teams, strategy analysts, and business development professionals, it solves…

Source: https://n8n.io/workflows/13319/ — original creator credit. Request a take-down →

More AI & RAG workflows → · Browse all categories →

Related workflows

Workflows that share integrations, category, or trigger type with this one. All free to copy and import.

AI & RAG

This workflow automates end-to-end carbon emissions monitoring, strategy optimisation, and ESG reporting using a multi-agent AI supervisor architecture in n8n. Designed for sustainability managers, ES

Agent, OpenAI Chat, Output Parser Structured +10
AI & RAG

This workflow automates end-to-end ESG (Environmental, Social, and Governance) sustainability reporting for enterprise sustainability teams, compliance officers, and green governance leads. It solves

Agent, OpenAI Chat, Output Parser Structured +12
AI & RAG

This workflow automates end-to-end carbon emissions monitoring, strategy optimisation, and ESG reporting using a multi-agent AI supervisor architecture in n8n. Designed for sustainability managers, ES

Agent, OpenAI Chat, Output Parser Structured +10
AI & RAG

This workflow automates end-to-end carbon emissions monitoring, strategy optimisation, and ESG reporting using a multi-agent AI supervisor architecture in n8n. Designed for sustainability managers, ES

Agent, OpenAI Chat, Output Parser Structured +10
AI & RAG

This workflow automates semiconductor board-level reliability monitoring using AI agents. It targets reliability engineers, manufacturing teams, and quality analysts. The system collects capacity, his

Google Sheets, Agent, OpenAI Chat +10