{
  "id": "bNkJA3m2Nin2-w3_GGpw6",
  "name": "AI-powered budget monitoring and cost optimization with multi-agent",
  "tags": [],
  "nodes": [
    {
      "id": "1b074af4-75fb-4298-92c2-2e3ba59a6171",
      "name": "Schedule Trigger",
      "type": "n8n-nodes-base.scheduleTrigger",
      "position": [
        -2512,
        64
      ],
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "hours"
            }
          ]
        }
      },
      "typeVersion": 1.3
    },
    {
      "id": "6d2a41ae-1ffc-41cf-9795-9b6ce9d2b13a",
      "name": "Workflow Configuration",
      "type": "n8n-nodes-base.set",
      "position": [
        -2288,
        64
      ],
      "parameters": {
        "options": {},
        "assignments": {
          "assignments": [
            {
              "id": "id-1",
              "name": "monthlyBudgetLimit",
              "type": "number",
              "value": 10000
            },
            {
              "id": "id-2",
              "name": "criticalThreshold",
              "type": "number",
              "value": 0.9
            },
            {
              "id": "id-3",
              "name": "warningThreshold",
              "type": "number",
              "value": 0.75
            },
            {
              "id": "id-4",
              "name": "slackChannel",
              "type": "string",
              "value": "<__PLACEHOLDER_VALUE__Slack channel ID for alerts__>"
            },
            {
              "id": "id-5",
              "name": "executiveEmail",
              "type": "string",
              "value": "<__PLACEHOLDER_VALUE__Executive email address for reports__>"
            }
          ]
        },
        "includeOtherFields": true
      },
      "typeVersion": 3.4
    },
    {
      "id": "1c6b78bb-5d71-4f87-81f3-7c13d68d650e",
      "name": "Generate Mock Metrics Data",
      "type": "n8n-nodes-base.code",
      "position": [
        -2064,
        64
      ],
      "parameters": {
        "jsCode": "// Generate realistic AI cost metrics data for cost intelligence analysis\n\nconst models = [\n  { name: 'gpt-4', inputCostPer1k: 0.03, outputCostPer1k: 0.06 },\n  { name: 'gpt-3.5-turbo', inputCostPer1k: 0.0015, outputCostPer1k: 0.002 },\n  { name: 'claude-3-opus', inputCostPer1k: 0.015, outputCostPer1k: 0.075 },\n  { name: 'claude-3-sonnet', inputCostPer1k: 0.003, outputCostPer1k: 0.015 },\n  { name: 'claude-3-haiku', inputCostPer1k: 0.00025, outputCostPer1k: 0.00125 }\n];\n\nconst workloadTypes = ['customer-support', 'content-generation', 'data-analysis', 'code-generation', 'summarization'];\n\n// Generate metrics for the current period (last 30 days)\nconst metricsData = [];\nconst currentDate = new Date();\n\nfor (let day = 0; day < 30; day++) {\n  const date = new Date(currentDate);\n  date.setDate(date.getDate() - day);\n  \n  models.forEach(model => {\n    workloadTypes.forEach(workload => {\n      // Generate realistic usage patterns\n      const baseRequests = Math.floor(Math.random() * 5000) + 1000;\n      const inputTokens = Math.floor(baseRequests * (Math.random() * 800 + 200));\n      const outputTokens = Math.floor(baseRequests * (Math.random() * 400 + 100));\n      \n      // Calculate costs\n      const inputCost = (inputTokens / 1000) * model.inputCostPer1k;\n      const outputCost = (outputTokens / 1000) * model.outputCostPer1k;\n      const totalCost = inputCost + outputCost;\n      \n      // Generate latency metrics (in milliseconds)\n      const avgLatency = Math.floor(Math.random() * 2000) + 500;\n      const p95Latency = avgLatency * 1.5;\n      const p99Latency = avgLatency * 2;\n      \n      metricsData.push({\n        date: date.toISOString().split('T')[0],\n        model: model.name,\n        workload: workload,\n        requests: baseRequests,\n        inputTokens: inputTokens,\n        outputTokens: outputTokens,\n        totalTokens: inputTokens + outputTokens,\n        inputCost: parseFloat(inputCost.toFixed(4)),\n        outputCost: parseFloat(outputCost.toFixed(4)),\n        totalCost: parseFloat(totalCost.toFixed(4)),\n        avgLatencyMs: avgLatency,\n        p95LatencyMs: Math.floor(p95Latency),\n        p99LatencyMs: Math.floor(p99Latency),\n        errorRate: parseFloat((Math.random() * 0.05).toFixed(4)),\n        cacheHitRate: parseFloat((Math.random() * 0.3 + 0.1).toFixed(4))\n      });\n    });\n  });\n}\n\n// Calculate summary statistics\nconst totalCost = metricsData.reduce((sum, m) => sum + m.totalCost, 0);\nconst totalRequests = metricsData.reduce((sum, m) => sum + m.requests, 0);\nconst totalTokens = metricsData.reduce((sum, m) => sum + m.totalTokens, 0);\nconst avgCostPerRequest = totalCost / totalRequests;\n\n// Group by model for cost breakdown\nconst costByModel = {};\nmodels.forEach(model => {\n  const modelMetrics = metricsData.filter(m => m.model === model.name);\n  costByModel[model.name] = {\n    totalCost: parseFloat(modelMetrics.reduce((sum, m) => sum + m.totalCost, 0).toFixed(2)),\n    totalRequests: modelMetrics.reduce((sum, m) => sum + m.requests, 0),\n    totalTokens: modelMetrics.reduce((sum, m) => sum + m.totalTokens, 0),\n    avgLatency: Math.floor(modelMetrics.reduce((sum, m) => sum + m.avgLatencyMs, 0) / modelMetrics.length)\n  };\n});\n\n// Group by workload for distribution analysis\nconst costByWorkload = {};\nworkloadTypes.forEach(workload => {\n  const workloadMetrics = metricsData.filter(m => m.workload === workload);\n  costByWorkload[workload] = {\n    totalCost: parseFloat(workloadMetrics.reduce((sum, m) => sum + m.totalCost, 0).toFixed(2)),\n    totalRequests: workloadMetrics.reduce((sum, m) => sum + m.requests, 0),\n    percentage: parseFloat(((workloadMetrics.reduce((sum, m) => sum + m.totalCost, 0) / totalCost) * 100).toFixed(2))\n  };\n});\n\nreturn [\n  {\n    json: {\n      period: {\n        start: new Date(currentDate.setDate(currentDate.getDate() - 30)).toISOString().split('T')[0],\n        end: new Date().toISOString().split('T')[0],\n        days: 30\n      },\n      summary: {\n        totalCost: parseFloat(totalCost.toFixed(2)),\n        totalRequests: totalRequests,\n        totalTokens: totalTokens,\n        avgCostPerRequest: parseFloat(avgCostPerRequest.toFixed(6)),\n        avgCostPerDay: parseFloat((totalCost / 30).toFixed(2))\n      },\n      costByModel: costByModel,\n      costByWorkload: costByWorkload,\n      detailedMetrics: metricsData,\n      budget: {\n        monthly: 50000,\n        current: parseFloat(totalCost.toFixed(2)),\n        remaining: parseFloat((50000 - totalCost).toFixed(2)),\n        utilizationPercent: parseFloat(((totalCost / 50000) * 100).toFixed(2))\n      },\n      timestamp: new Date().toISOString()\n    }\n  }\n];"
      },
      "typeVersion": 2
    },
    {
      "id": "ccaddedb-574b-4c0d-8e47-1bf98ee09c21",
      "name": "Cost Intelligence Agent",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "position": [
        -1824,
        192
      ],
      "parameters": {
        "text": "=Analyze the following AI infrastructure metrics: {{ JSON.stringify($json) }}",
        "options": {
          "systemMessage": "You are a Cost Intelligence Agent specialized in analyzing AI infrastructure metrics.\n\nYour task is to:\n1. Analyze token usage patterns across different models\n2. Evaluate latency metrics and identify performance bottlenecks\n3. Assess workload distribution efficiency\n4. Calculate cost per request and identify cost anomalies\n5. Determine budget utilization percentage\n6. Identify cost optimization opportunities\n7. Provide risk assessment for budget overruns\n\nReturn your analysis in the structured JSON format defined by the output parser."
        },
        "promptType": "define",
        "hasOutputParser": true
      },
      "typeVersion": 3.1
    },
    {
      "id": "658e14b3-a034-49fc-a885-550e6640a2c2",
      "name": "Anthropic Model - Cost Intelligence",
      "type": "@n8n/n8n-nodes-langchain.lmChatAnthropic",
      "position": [
        -1808,
        416
      ],
      "parameters": {
        "model": {
          "__rl": true,
          "mode": "id",
          "value": "claude-3-7-sonnet-20250219"
        },
        "options": {
          "temperature": 0.2
        }
      },
      "credentials": {
        "anthropicApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1.3
    },
    {
      "id": "20e5df1a-b70c-4fa1-a9fa-6179b9dea00c",
      "name": "Cost Analysis Output Parser",
      "type": "@n8n/n8n-nodes-langchain.outputParserStructured",
      "position": [
        -1648,
        416
      ],
      "parameters": {
        "jsonSchemaExample": "{\n  \"totalCost\": 8500.50,\n  \"budgetUtilization\": 0.85,\n  \"budgetStatus\": \"warning\",\n  \"costByModel\": {\n    \"gpt4\": 5200.30,\n    \"claude\": 2100.20,\n    \"gemini\": 1200.00\n  },\n  \"tokenUsage\": {\n    \"total\": 15000000,\n    \"inputTokens\": 9000000,\n    \"outputTokens\": 6000000\n  },\n  \"avgLatency\": 1250,\n  \"workloadDistribution\": {\n    \"production\": 0.70,\n    \"staging\": 0.20,\n    \"development\": 0.10\n  },\n  \"costAnomalies\": [\"Spike in GPT-4 usage detected\"],\n  \"optimizationOpportunities\": [\"Consider routing simple queries to cheaper models\"],\n  \"riskLevel\": \"medium\",\n  \"projectedMonthEndCost\": 9800.00\n}"
      },
      "typeVersion": 1.3
    },
    {
      "id": "83662fe0-7734-4e84-b388-e0465ebcd244",
      "name": "Route by Budget Status",
      "type": "n8n-nodes-base.switch",
      "position": [
        -1472,
        48
      ],
      "parameters": {
        "rules": {
          "values": [
            {
              "outputKey": "Critical",
              "conditions": {
                "options": {
                  "leftValue": "",
                  "caseSensitive": false,
                  "typeValidation": "loose"
                },
                "combinator": "and",
                "conditions": [
                  {
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    },
                    "leftValue": "={{ $json.budgetStatus }}",
                    "rightValue": "critical"
                  }
                ]
              },
              "renameOutput": true
            },
            {
              "outputKey": "Warning",
              "conditions": {
                "options": {
                  "leftValue": "",
                  "caseSensitive": false,
                  "typeValidation": "loose"
                },
                "combinator": "and",
                "conditions": [
                  {
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    },
                    "leftValue": "={{ $json.budgetStatus }}",
                    "rightValue": "warning"
                  }
                ]
              },
              "renameOutput": true
            },
            {
              "outputKey": "Normal",
              "conditions": {
                "options": {
                  "leftValue": "",
                  "caseSensitive": false,
                  "typeValidation": "loose"
                },
                "combinator": "and",
                "conditions": [
                  {
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    },
                    "leftValue": "={{ $json.budgetStatus }}",
                    "rightValue": "normal"
                  }
                ]
              },
              "renameOutput": true
            }
          ]
        },
        "options": {
          "fallbackOutput": "extra"
        }
      },
      "typeVersion": 3.4
    },
    {
      "id": "3a75cfa9-57f7-4270-9750-695d083acf2b",
      "name": "Budget Alert Agent Tool",
      "type": "@n8n/n8n-nodes-langchain.agentTool",
      "position": [
        -1120,
        304
      ],
      "parameters": {
        "text": "={{ $fromAI(\"costAnalysis\", \"Cost analysis data from Cost Intelligence Agent\", \"json\") }}",
        "options": {
          "systemMessage": "You are a Budget Alert Specialist Agent that generates actionable budget alerts.\n\nYour task is to:\n1. Evaluate budget utilization severity\n2. Identify immediate cost reduction actions\n3. Determine stakeholders to notify\n4. Calculate projected budget impact\n5. Recommend emergency cost controls if needed\n6. Provide clear alert messaging\n\nReturn structured alert recommendations in JSON format."
        },
        "hasOutputParser": true,
        "toolDescription": "Generates budget alerts and immediate action recommendations based on cost analysis"
      },
      "typeVersion": 3
    },
    {
      "id": "3af581a8-ada3-4e97-bde0-c293bb483389",
      "name": "Anthropic Model - Budget Alert",
      "type": "@n8n/n8n-nodes-langchain.lmChatAnthropic",
      "position": [
        -1232,
        512
      ],
      "parameters": {
        "model": {
          "__rl": true,
          "mode": "id",
          "value": "claude-3-7-sonnet-20250219"
        },
        "options": {
          "temperature": 0.2
        }
      },
      "credentials": {
        "anthropicApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1.3
    },
    {
      "id": "99753d08-6cbf-4f7a-96f6-ba3bb4a0d1d1",
      "name": "Budget Alert Output Parser",
      "type": "@n8n/n8n-nodes-langchain.outputParserStructured",
      "position": [
        -1024,
        512
      ],
      "parameters": {
        "jsonSchemaExample": "{\n  \"alertSeverity\": \"high\",\n  \"alertMessage\": \"Budget utilization at 85% - immediate action required\",\n  \"immediateActions\": [\"Throttle non-critical workloads\", \"Review expensive model usage\"],\n  \"stakeholdersToNotify\": [\"Engineering Lead\", \"Finance Team\"],\n  \"projectedImpact\": \"Without intervention, budget will exceed by 15% this month\",\n  \"emergencyControls\": [\"Enable rate limiting on GPT-4 endpoints\"]\n}"
      },
      "typeVersion": 1.3
    },
    {
      "id": "74ca3f62-2d70-4bba-b078-31cc8ae3fcdd",
      "name": "Routing Recommendation Agent Tool",
      "type": "@n8n/n8n-nodes-langchain.agentTool",
      "position": [
        -832,
        304
      ],
      "parameters": {
        "text": "={{ $fromAI(\"costAnalysis\", \"Cost analysis data from Cost Intelligence Agent\", \"json\") }}",
        "options": {
          "systemMessage": "You are a Routing Recommendation Specialist Agent that optimizes AI model routing strategies.\n\nYour task is to:\n1. Analyze current workload distribution\n2. Identify opportunities to route requests to more cost-effective models\n3. Recommend model substitution strategies\n4. Calculate potential cost savings\n5. Assess quality/cost tradeoffs\n6. Provide implementation guidance\n\nReturn structured routing recommendations in JSON format."
        },
        "hasOutputParser": true,
        "toolDescription": "Provides intelligent routing recommendations to optimize cost without compromising quality"
      },
      "typeVersion": 3
    },
    {
      "id": "8322e3e4-3bbe-4895-a4ff-02c0cb7e20b0",
      "name": "Anthropic Model - Routing",
      "type": "@n8n/n8n-nodes-langchain.lmChatAnthropic",
      "position": [
        -832,
        512
      ],
      "parameters": {
        "model": {
          "__rl": true,
          "mode": "id",
          "value": "claude-3-7-sonnet-20250219"
        },
        "options": {
          "temperature": 0.2
        }
      },
      "credentials": {
        "anthropicApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1.3
    },
    {
      "id": "a006a1fe-b713-4d55-add4-42600d4e5890",
      "name": "Routing Output Parser",
      "type": "@n8n/n8n-nodes-langchain.outputParserStructured",
      "position": [
        -656,
        512
      ],
      "parameters": {
        "jsonSchemaExample": "{\n  \"routingStrategy\": \"tiered\",\n  \"recommendations\": [\n    {\n      \"currentModel\": \"gpt-4\",\n      \"suggestedModel\": \"gpt-3.5-turbo\",\n      \"useCase\": \"Simple classification tasks\",\n      \"estimatedSavings\": 2500.00,\n      \"qualityImpact\": \"minimal\"\n    }\n  ],\n  \"totalPotentialSavings\": 3200.00,\n  \"implementationPriority\": \"high\",\n  \"implementationSteps\": [\"Update routing logic\", \"Test quality metrics\", \"Gradual rollout\"]\n}"
      },
      "typeVersion": 1.3
    },
    {
      "id": "76dd80ee-03d6-448f-80ef-c2668aceacf6",
      "name": "Cost Projection Calculator Tool",
      "type": "@n8n/n8n-nodes-langchain.toolCode",
      "position": [
        -544,
        304
      ],
      "parameters": {
        "jsCode": "// Calculate cost projections based on current usage trends\nconst metrics = JSON.parse(query);\n\n// Extract current metrics\nconst currentCost = metrics.current_cost || 0;\nconst dailyAverage = metrics.daily_average || 0;\nconst daysInMonth = 30;\nconst daysElapsed = metrics.days_elapsed || 15;\nconst budget = metrics.budget || 0;\n\n// Calculate daily burn rate\nconst dailyBurnRate = currentCost / daysElapsed;\n\n// Calculate month-end projection\nconst monthEndProjection = dailyBurnRate * daysInMonth;\n\n// Calculate budget runway (days until budget exhausted)\nconst remainingBudget = budget - currentCost;\nconst budgetRunway = remainingBudget > 0 ? Math.floor(remainingBudget / dailyBurnRate) : 0;\n\n// Calculate variance from budget\nconst budgetVariance = ((monthEndProjection - budget) / budget * 100).toFixed(2);\n\n// Build projection report\nconst projection = {\n  daily_burn_rate: dailyBurnRate.toFixed(2),\n  month_end_projection: monthEndProjection.toFixed(2),\n  budget_runway_days: budgetRunway,\n  budget_variance_percent: budgetVariance,\n  current_cost: currentCost.toFixed(2),\n  budget: budget.toFixed(2),\n  status: monthEndProjection > budget ? 'over_budget' : 'within_budget'\n};\n\nreturn JSON.stringify(projection, null, 2);",
        "description": "Calculates cost projections and forecasts based on current usage trends and historical data"
      },
      "typeVersion": 1.3
    },
    {
      "id": "eefb56af-3534-4ef4-b7c6-cf5923b3f138",
      "name": "Optimization Coordinator Agent",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "position": [
        -816,
        80
      ],
      "parameters": {
        "text": "=Cost analysis data: {{ JSON.stringify($json) }}",
        "options": {
          "systemMessage": "You are an Optimization Coordinator Agent that orchestrates cost optimization actions.\n\nYour task is to:\n1. Call the Budget Alert Agent Tool to generate alert recommendations\n2. Call the Routing Recommendation Agent Tool to get routing optimizations\n3. Call the Cost Projection Calculator Tool to forecast budget impact\n4. Synthesize all recommendations into a coordinated action plan\n5. Determine notification strategy (Slack alert vs executive report)\n6. Prioritize actions by impact and urgency\n\nBased on budget status:\n- CRITICAL: Generate immediate Slack alerts\n- WARNING/NORMAL: Generate executive summary reports\n\nReturn your coordination plan in the structured JSON format."
        },
        "promptType": "define",
        "hasOutputParser": true
      },
      "typeVersion": 3.1
    },
    {
      "id": "cdef0d6c-56c7-4b67-a57b-dbc78a99662a",
      "name": "Anthropic Model - Coordinator",
      "type": "@n8n/n8n-nodes-langchain.lmChatAnthropic",
      "position": [
        -1248,
        304
      ],
      "parameters": {
        "model": {
          "__rl": true,
          "mode": "id",
          "value": "claude-3-7-sonnet-20250219"
        },
        "options": {
          "temperature": 0.3
        }
      },
      "credentials": {
        "anthropicApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1.3
    },
    {
      "id": "df00ed04-f92d-4e73-ab47-02872116d1d4",
      "name": "Coordinator Output Parser",
      "type": "@n8n/n8n-nodes-langchain.outputParserStructured",
      "position": [
        -416,
        304
      ],
      "parameters": {
        "jsonSchemaExample": "{\n  \"actionType\": \"alert\",\n  \"priority\": \"high\",\n  \"coordinatedActions\": [\n    \"Send immediate Slack alert to engineering team\",\n    \"Implement routing recommendations\",\n    \"Enable cost controls\"\n  ],\n  \"budgetAlertSummary\": \"Budget at 85% utilization - immediate action required\",\n  \"routingRecommendationSummary\": \"Potential savings of $3200 through model optimization\",\n  \"costProjection\": \"Projected to exceed budget by 15% without intervention\",\n  \"notificationChannel\": \"slack\",\n  \"executiveSummary\": \"AI infrastructure costs trending above budget. Immediate optimization actions recommended.\"\n}"
      },
      "typeVersion": 1.3
    },
    {
      "id": "33d8972b-f4f1-4281-9ebc-7b14819f917b",
      "name": "Route by Action Type",
      "type": "n8n-nodes-base.switch",
      "position": [
        -208,
        64
      ],
      "parameters": {
        "rules": {
          "values": [
            {
              "outputKey": "Slack Alert",
              "conditions": {
                "options": {
                  "leftValue": "",
                  "caseSensitive": true,
                  "typeValidation": "strict"
                },
                "combinator": "and",
                "conditions": [
                  {
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    },
                    "leftValue": "={{ $json.actionType }}",
                    "rightValue": "alert"
                  }
                ]
              },
              "renameOutput": true
            },
            {
              "outputKey": "Executive Report",
              "conditions": {
                "options": {
                  "leftValue": "",
                  "caseSensitive": true,
                  "typeValidation": "strict"
                },
                "combinator": "and",
                "conditions": [
                  {
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    },
                    "leftValue": "={{ $json.actionType }}",
                    "rightValue": "report"
                  }
                ]
              },
              "renameOutput": true
            }
          ]
        },
        "options": {
          "fallbackOutput": "extra"
        }
      },
      "typeVersion": 3.4
    },
    {
      "id": "6ec2a5c4-aa78-4f27-b542-fc1ea1f4d481",
      "name": "Send Slack Alert",
      "type": "n8n-nodes-base.slack",
      "position": [
        80,
        96
      ],
      "parameters": {
        "text": "=\ud83d\udea8 *AI Cost Alert - {{ $json.priority.toUpperCase() }} Priority*\n\n*Budget Status:* {{ $json.budgetAlertSummary }}\n\n*Coordinated Actions Required:*\n{{ $json.coordinatedActions.map((action, i) => `${i + 1}. ${action}`).join(\"\\n\") }}\n\n*Cost Projection:* {{ $json.costProjection }}\n\n*Routing Optimization:* {{ $json.routingRecommendationSummary }}\n\n_Automated alert from AI Cost Intelligence System_",
        "select": "channel",
        "channelId": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $('Workflow Configuration').first().json.slackChannel }}"
        },
        "otherOptions": {},
        "authentication": "oAuth2"
      },
      "credentials": {
        "slackOAuth2Api": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 2.4
    },
    {
      "id": "2894d8b0-18f5-49d4-a445-fcf8ea6ce3b1",
      "name": "Send Executive Report Email",
      "type": "n8n-nodes-base.emailSend",
      "position": [
        80,
        288
      ],
      "parameters": {
        "html": "=<!DOCTYPE html>\n<html>\n<head>\n  <style>\n    body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }\n    .container { max-width: 800px; margin: 0 auto; padding: 20px; }\n    .header { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 30px; border-radius: 8px; margin-bottom: 30px; }\n    .header h1 { margin: 0; font-size: 28px; }\n    .header p { margin: 10px 0 0 0; opacity: 0.9; }\n    .section { background: #f8f9fa; padding: 20px; border-radius: 8px; margin-bottom: 20px; border-left: 4px solid #667eea; }\n    .section h2 { color: #667eea; margin-top: 0; font-size: 20px; }\n    .metric { display: inline-block; margin: 10px 20px 10px 0; }\n    .metric-label { font-size: 12px; color: #666; text-transform: uppercase; }\n    .metric-value { font-size: 24px; font-weight: bold; color: #333; }\n    .alert { background: #fff3cd; border-left: 4px solid #ffc107; padding: 15px; margin: 15px 0; border-radius: 4px; }\n    .recommendation { background: white; padding: 15px; margin: 10px 0; border-radius: 4px; border: 1px solid #e0e0e0; }\n    .recommendation h3 { margin: 0 0 10px 0; color: #667eea; font-size: 16px; }\n    .action-item { padding: 10px; margin: 8px 0; background: #e8f4f8; border-radius: 4px; }\n    .footer { text-align: center; padding: 20px; color: #666; font-size: 12px; border-top: 1px solid #e0e0e0; margin-top: 30px; }\n    .status-badge { display: inline-block; padding: 4px 12px; border-radius: 12px; font-size: 12px; font-weight: bold; }\n    .status-warning { background: #fff3cd; color: #856404; }\n    .status-success { background: #d4edda; color: #155724; }\n    .status-danger { background: #f8d7da; color: #721c24; }\n  </style>\n</head>\n<body>\n  <div class=\"container\">\n    <div class=\"header\">\n      <h1>\ud83e\udd16 AI Cost Intelligence Report</h1>\n      <p>{{ $now.format('MMMM DD, YYYY') }} | Automated Analysis & Optimization Recommendations</p>\n    </div>\n\n    <div class=\"section\">\n      <h2>\ud83d\udcca Cost Analysis Summary</h2>\n      <div class=\"metric\">\n        <div class=\"metric-label\">Total Monthly Cost</div>\n        <div class=\"metric-value\">${{ $('Cost Intelligence Agent').first().json.totalCost || '0' }}</div>\n      </div>\n      <div class=\"metric\">\n        <div class=\"metric-label\">Budget Status</div>\n        <div class=\"metric-value\">\n          <span class=\"status-badge {{ $('Cost Intelligence Agent').first().json.budgetStatus === 'over_budget' ? 'status-danger' : ($('Cost Intelligence Agent').first().json.budgetStatus === 'warning' ? 'status-warning' : 'status-success') }}\">\n            {{ $('Cost Intelligence Agent').first().json.budgetStatus || 'N/A' }}\n          </span>\n        </div>\n      </div>\n      <div class=\"metric\">\n        <div class=\"metric-label\">Potential Savings</div>\n        <div class=\"metric-value\">${{ $('Cost Intelligence Agent').first().json.potentialSavings || '0' }}</div>\n      </div>\n    </div>\n\n    {{ $('Cost Intelligence Agent').first().json.budgetStatus === 'over_budget' || $('Cost Intelligence Agent').first().json.budgetStatus === 'warning' ? '<div class=\"alert\">\u26a0\ufe0f <strong>Budget Alert:</strong> Current spending requires attention. Review optimization recommendations below.</div>' : '' }}\n\n    <div class=\"section\">\n      <h2>\ud83d\udca1 Optimization Recommendations</h2>\n      {{ $('Optimization Coordinator Agent').first().json.recommendations ? $('Optimization Coordinator Agent').first().json.recommendations.map(rec => `\n        <div class=\"recommendation\">\n          <h3>${rec.title || 'Optimization Opportunity'}</h3>\n          <p>${rec.description || 'No description available'}</p>\n          <p><strong>Estimated Savings:</strong> $${rec.savings || '0'} | <strong>Priority:</strong> ${rec.priority || 'Medium'}</p>\n        </div>\n      `).join('') : '<p>No specific recommendations at this time.</p>' }}\n    </div>\n\n    <div class=\"section\">\n      <h2>\u2705 Action Items</h2>\n      {{ $('Optimization Coordinator Agent').first().json.actions ? $('Optimization Coordinator Agent').first().json.actions.map(action => `\n        <div class=\"action-item\">\n          <strong>${action.type || 'Action'}:</strong> ${action.description || 'No description'}\n        </div>\n      `).join('') : '<p>No actions required at this time.</p>' }}\n    </div>\n\n    <div class=\"section\">\n      <h2>\ud83d\udcc8 Key Insights</h2>\n      <p>{{ $('Cost Intelligence Agent').first().json.insights || 'AI analysis completed successfully. All metrics are being monitored.' }}</p>\n    </div>\n\n    <div class=\"footer\">\n      <p>This report was automatically generated by the AI Cost Intelligence System</p>\n      <p>For questions or concerns, please contact your infrastructure team</p>\n    </div>\n  </div>\n</body>\n</html>",
        "options": {},
        "subject": "=AI Cost Intelligence Report - {{ $now.format('MMMM yyyy') }}",
        "toEmail": "={{ $('Workflow Configuration').first().json.executiveEmail }}",
        "fromEmail": "<__PLACEHOLDER_VALUE__Sender email address__>"
      },
      "typeVersion": 2.1
    },
    {
      "id": "8460f76f-3034-4738-bc4c-251d53084168",
      "name": "Store Cost Analysis",
      "type": "n8n-nodes-base.dataTable",
      "position": [
        -1472,
        304
      ],
      "parameters": {
        "columns": {
          "value": {
            "riskLevel": "={{ $json.riskLevel }}",
            "timestamp": "={{ $json.timestamp }}",
            "totalCost": "={{ $json.totalCost }}",
            "budgetStatus": "={{ $json.budgetStatus }}",
            "budgetUtilization": "={{ $json.budgetUtilization }}",
            "projectedMonthEndCost": "={{ $json.projectedMonthEndCost }}"
          },
          "mappingMode": "defineBelow"
        },
        "options": {},
        "dataTableId": {
          "__rl": true,
          "mode": "name",
          "value": "CostAnalysisHistory"
        }
      },
      "typeVersion": 1.1
    },
    {
      "id": "10a554da-afc9-47f8-ac96-7d6127fee933",
      "name": "Merge Notification Results",
      "type": "n8n-nodes-base.merge",
      "position": [
        304,
        192
      ],
      "parameters": {
        "mode": "combine",
        "options": {},
        "combineBy": "combineByPosition"
      },
      "typeVersion": 3.2
    },
    {
      "id": "f0af69ea-a545-44dc-af17-93ead23451da",
      "name": "Store Optimization Actions",
      "type": "n8n-nodes-base.dataTable",
      "position": [
        528,
        192
      ],
      "parameters": {
        "columns": {
          "value": {
            "priority": "={{ $json.priority }}",
            "timestamp": "={{ $json.timestamp }}",
            "actionType": "={{ $json.actionType }}",
            "budgetAlertSummary": "={{ $json.budgetAlertSummary }}",
            "coordinatedActions": "={{ $json.coordinatedActions }}",
            "notificationChannel": "={{ $json.notificationChannel }}",
            "routingRecommendationSummary": "={{ $json.routingRecommendationSummary }}"
          },
          "mappingMode": "defineBelow"
        },
        "options": {},
        "dataTableId": {
          "__rl": true,
          "mode": "name",
          "value": "OptimizationActions"
        }
      },
      "typeVersion": 1.1
    },
    {
      "id": "75153ea4-eb72-4cc4-bad9-d9bd105fca48",
      "name": "Sticky Note",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -1200,
        -512
      ],
      "parameters": {
        "color": 4,
        "width": 464,
        "height": 352,
        "content": "## Prerequisites\nn8n (cloud or self-hosted), Anthropic API key (Claude), Slack workspace with bot token \n## Use Cases\nFinance teams automating multi-department budget variance detection and escalation\n## Customization\nReplace Anthropic Claude with OpenAI GPT-4 or NVIDIA NIM in any agent node\n## Benefits\nEliminates manual budget reviews through automated AI-driven cost classification\n"
      },
      "typeVersion": 1
    },
    {
      "id": "dc60d655-db07-42fb-ae64-1fbfc9858f83",
      "name": "Sticky Note1",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -1840,
        -384
      ],
      "parameters": {
        "width": 576,
        "height": 240,
        "content": "## Setup Steps\n1. Import workflow JSON into your n8n instance.\n2. Add Anthropic API credentials.\n3. Set Schedule Trigger frequency.\n4. Update Workflow Configuration node with budget thresholds per department or cost centre.\n5. Add Slack credentials and configure the target channel in the Send Slack Alert node.\n6. Set Gmail/SMTP credentials for the Send Executive Report Email node.\n"
      },
      "typeVersion": 1
    },
    {
      "id": "066e2f6f-017f-4784-b51a-170d5f2cdf3f",
      "name": "Sticky Note2",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -2544,
        -384
      ],
      "parameters": {
        "width": 640,
        "height": 288,
        "content": "## How It Works\nThis workflow automates enterprise budget monitoring and cost optimization using Anthropic Claude as the core AI engine across multiple specialist agents. It targets finance teams, operations managers, and CFOs managing complex multi-department budgets where manual tracking leads to delayed decisions and cost overruns. The workflow triggers on schedule, generates metrics data, and routes it through a Cost Intelligence Agent that classifies budget status (Critical, Warning, Review, Feedback). Each path activates specialist agents\u2014Budget Alert, Routing Recommendation, and Cost Projection\u2014coordinated by an Optimization Coordinator. Results are routed by action type: urgent alerts fire via Slack, executive summaries deliver via email, and all optimization actions are stored. This gives finance teams real-time cost intelligence with automated escalation and audit-ready records."
      },
      "typeVersion": 1
    },
    {
      "id": "1be1536c-203c-4d2a-8011-e973ba813049",
      "name": "Sticky Note3",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -2544,
        -64
      ],
      "parameters": {
        "color": 7,
        "width": 656,
        "height": 544,
        "content": "### Generate Mock Metrics Data\n**What:** Loads or simulates departmental cost and budget metrics.\n**Why:** Provides structured financial data for downstream AI analysis.\n"
      },
      "typeVersion": 1
    },
    {
      "id": "56c2f6a4-4fec-4839-a6d2-295e4043e422",
      "name": "Sticky Note4",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -1280,
        -112
      ],
      "parameters": {
        "color": 7,
        "width": 976,
        "height": 784,
        "content": "## Optimization Coordinator\n**What:** Aggregates all agent outputs and determines the optimal action plan.\n**Why:** Ensures coherent, conflict-free recommendations across all budget streams."
      },
      "typeVersion": 1
    },
    {
      "id": "ffb9ce7c-7b75-4517-8423-831afd143adf",
      "name": "Sticky Note5",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -1872,
        -96
      ],
      "parameters": {
        "color": 7,
        "width": 576,
        "height": 720,
        "content": "\n## Cost Intelligence Agent\n**What:** Anthropic Claude classifies budget status across Critical, Warning, Review, and Feedback tiers.\n**Why:** Prioritizes response urgency, directing resources where risk is highest.\n"
      },
      "typeVersion": 1
    },
    {
      "id": "cf7e1ee2-d7eb-48bf-9015-f0d4c57ce2b6",
      "name": "Sticky Note6",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -256,
        -112
      ],
      "parameters": {
        "color": 7,
        "width": 992,
        "height": 800,
        "content": "\n## Alert & Reporting\n**What:** Slack alerts for urgent issues; executive email report for leadership; results stored.\n**Why:** Delivers timely intelligence to the right stakeholders through the right channel."
      },
      "typeVersion": 1
    }
  ],
  "active": false,
  "settings": {
    "availableInMCP": false,
    "executionOrder": "v1"
  },
  "versionId": "a78550fe-458d-4cce-a3cb-01440e79262d",
  "connections": {
    "Schedule Trigger": {
      "main": [
        [
          {
            "node": "Workflow Configuration",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Send Slack Alert": {
      "main": [
        [
          {
            "node": "Merge Notification Results",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Route by Action Type": {
      "main": [
        [
          {
            "node": "Send Slack Alert",
            "type": "main",
            "index": 0
          },
          {
            "node": "Send Executive Report Email",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Routing Output Parser": {
      "ai_outputParser": [
        [
          {
            "node": "Routing Recommendation Agent Tool",
            "type": "ai_outputParser",
            "index": 0
          }
        ]
      ]
    },
    "Route by Budget Status": {
      "main": [
        [
          {
            "node": "Optimization Coordinator Agent",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Workflow Configuration": {
      "main": [
        [
          {
            "node": "Generate Mock Metrics Data",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Budget Alert Agent Tool": {
      "ai_tool": [
        [
          {
            "node": "Optimization Coordinator Agent",
            "type": "ai_tool",
            "index": 0
          }
        ]
      ]
    },
    "Cost Intelligence Agent": {
      "main": [
        [
          {
            "node": "Route by Budget Status",
            "type": "main",
            "index": 0
          },
          {
            "node": "Store Cost Analysis",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Anthropic Model - Routing": {
      "ai_languageModel": [
        [
          {
            "node": "Routing Recommendation Agent Tool",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Coordinator Output Parser": {
      "ai_outputParser": [
        [
          {
            "node": "Optimization Coordinator Agent",
            "type": "ai_outputParser",
            "index": 0
          }
        ]
      ]
    },
    "Budget Alert Output Parser": {
      "ai_outputParser": [
        [
          {
            "node": "Budget Alert Agent Tool",
            "type": "ai_outputParser",
            "index": 0
          }
        ]
      ]
    },
    "Generate Mock Metrics Data": {
      "main": [
        [
          {
            "node": "Cost Intelligence Agent",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Merge Notification Results": {
      "main": [
        [
          {
            "node": "Store Optimization Actions",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Cost Analysis Output Parser": {
      "ai_outputParser": [
        [
          {
            "node": "Cost Intelligence Agent",
            "type": "ai_outputParser",
            "index": 0
          }
        ]
      ]
    },
    "Send Executive Report Email": {
      "main": [
        [
          {
            "node": "Merge Notification Results",
            "type": "main",
            "index": 0
          },
          {
            "node": "Merge Notification Results",
            "type": "main",
            "index": 1
          }
        ]
      ]
    },
    "Anthropic Model - Coordinator": {
      "ai_languageModel": [
        [
          {
            "node": "Optimization Coordinator Agent",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Anthropic Model - Budget Alert": {
      "ai_languageModel": [
        [
          {
            "node": "Budget Alert Agent Tool",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Optimization Coordinator Agent": {
      "main": [
        [
          {
            "node": "Route by Action Type",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Cost Projection Calculator Tool": {
      "ai_tool": [
        [
          {
            "node": "Optimization Coordinator Agent",
            "type": "ai_tool",
            "index": 0
          }
        ]
      ]
    },
    "Routing Recommendation Agent Tool": {
      "ai_tool": [
        [
          {
            "node": "Optimization Coordinator Agent",
            "type": "ai_tool",
            "index": 0
          }
        ]
      ]
    },
    "Anthropic Model - Cost Intelligence": {
      "ai_languageModel": [
        [
          {
            "node": "Cost Intelligence Agent",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    }
  }
}