Calculate the Centroid of a Set of Vectors

工作流概述

这是一个包含8个节点的中等工作流,主要用于自动化处理各种任务。

工作流源代码

下载
{
  "id": "g3q68zSOQvTcydLs",
  "meta": {
    "instanceId": "92786e96ce436aecd3a1d62d818a74e51ca684bb36c805928bef93a3b46549ad"
  },
  "name": "Calculate the Centroid of a Set of Vectors",
  "tags": [],
  "nodes": [
    {
      "id": "32a8aa56-aa7e-4c9e-a39e-f65234224bcf",
      "name": "Receive Vectors",
      "type": "n8n-nodes-base.webhook",
      "position": [
        -440,
        20
      ],
      "webhookId": "30091e91-fc67-4bab-b1fd-ed65c8f4f860",
      "parameters": {
        "path": "centroid",
        "options": {},
        "responseMode": "responseNode"
      },
      "notesInFlow": true,
      "typeVersion": 2
    },
    {
      "id": "a020a49a-cc9f-49af-aa95-829d9d16da04",
      "name": "Extract & Parse Vectors",
      "type": "n8n-nodes-base.set",
      "position": [
        360,
        20
      ],
      "parameters": {
        "options": {},
        "assignments": {
          "assignments": [
            {
              "id": "3e1d9e72-7668-427d-958c-42bff7270a37",
              "name": "vectors",
              "type": "array",
              "value": "={{ $json.query.vectors }}"
            }
          ]
        }
      },
      "typeVersion": 3.4
    },
    {
      "id": "2f328de6-4ef1-4aac-8838-d616637f4b88",
      "name": "Validate & Compute Centroid",
      "type": "n8n-nodes-base.code",
      "position": [
        960,
        20
      ],
      "parameters": {
        "jsCode": "const input = items[0].json;
const vectors = input.vectors;

if (!Array.isArray(vectors) || vectors.length === 0) {
  return [{ json: { error: \"Invalid input: Expected an array of vectors.\" } }];
}

const dimension = vectors[0].length;
if (!vectors.every(v => v.length === dimension)) {
  return [{ json: { error: \"Vectors have inconsistent dimensions.\" } }];
}

const centroid = new Array(dimension).fill(0);
vectors.forEach(vector => {
  vector.forEach((val, index) => {
    centroid[index] += val;
  });
});

for (let i = 0; i < dimension; i++) {
  centroid[i] /= vectors.length;
}

return [{ json: { centroid } }];"
      },
      "typeVersion": 2
    },
    {
      "id": "821bc173-3578-4cf2-9fd7-8ea9cba8dc3f",
      "name": "Return Centroid Response",
      "type": "n8n-nodes-base.respondToWebhook",
      "position": [
        1640,
        20
      ],
      "parameters": {
        "options": {}
      },
      "typeVersion": 1.1
    },
    {
      "id": "73964e7b-1217-422f-8078-09604fa2a3d7",
      "name": "Sticky Note",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        20,
        -200
      ],
      "parameters": {
        "color": 3,
        "width": 620,
        "height": 420,
        "content": "📌 **Description:**  
This node extracts the `vectors` array from the **GET request** and converts it into a properly formatted array for processing.  
- **Ensures `vectors` is a valid array.**  
- **If the parameter is missing, it may generate an error.**  

🔹 **Expected Output Example:**
```json
{
  \"vectors\": [[2,3,4],[4,5,6],[6,7,8]]
}
```
"
      },
      "typeVersion": 1
    },
    {
      "id": "e4793b20-bfa6-4b08-b46c-f92d1c9c2622",
      "name": "Sticky Note1",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        640,
        -280
      ],
      "parameters": {
        "color": 4,
        "width": 700,
        "height": 500,
        "content": "📌 **Description:**  
This node performs **vector validation** and **centroid computation**.  
- **Validation:** Ensures all vectors have the same number of dimensions.  
- **Computation:** Averages each dimension to determine the centroid.  
- **If validation fails:** Returns an error message indicating inconsistent dimensions.  

🔹 **Successful Output Example:**
```json
{
  \"centroid\": [4,5,6]
}
```
🔹 **Error Output Example:**
```json
{
  \"error\": \"Vectors have inconsistent dimensions.\"
}
```
"
      },
      "typeVersion": 1
    },
    {
      "id": "e0ac1c4d-0435-44d1-ba87-0cfc9dea207b",
      "name": "Sticky Note2",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        1340,
        -200
      ],
      "parameters": {
        "color": 2,
        "width": 680,
        "height": 420,
        "content": "📌 **Description:**  
This node sends the **final response** back to the client that made the request.  
- **If the computation is successful**, it returns the centroid.  
- **If an error occurs**, it returns a descriptive error message.  

🔹 **Example Response:**
```json
{
  \"centroid\": [4, 5, 6]
}
```
"
      },
      "typeVersion": 1
    },
    {
      "id": "2b4fbae7-c2e5-4666-ba9f-72a5313fc16f",
      "name": "Sticky Note4",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -820,
        -200
      ],
      "parameters": {
        "color": 4,
        "width": 840,
        "height": 420,
        "content": "📌 **Description:**  
This node acts as the **entry point** for the workflow, receiving a **GET request** containing an array of vectors in the `vectors` parameter.  
- **Expected Input:** `vectors` parameter in JSON format.  
- **Example Request:**  
  ```plaintext
  https://actions.singular-innovation.com/webhook-test/centroid?vectors=[[2,3,4],[4,5,6],[6,7,8]]
  ```
- **Output:** Passes the received data to the next node for processing.
"
      },
      "typeVersion": 1
    }
  ],
  "active": true,
  "pinData": {
    "Receive Vectors": [
      {
        "json": {
          "body": {},
          "query": {
            "vectors": "[[2,3,4],[4,5,6],[6,7,8]]"
          },
          "params": {},
          "headers": {
            "host": "actions.singular-innovation.com",
            "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
            "cookie": "rl_page_init_referrer=RudderEncrypt%3AU2FsdGVkX1%2FNTT5WOkcYG%2FWSKmLWL%2F6W9TAbYFEQv8s%3D; rl_page_init_referring_domain=RudderEncrypt%3AU2FsdGVkX19thqA5y56KyQdmUG3L%2BhCiYIxQok7WXRI%3D; n8n-auth=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6ImZjOTg1OTJjLTcwOWUtNGI5Mi1hODk0LWZiNjVlODY1ZmRlMiIsImhhc2giOiJhOFg4MW1zcU1zIiwiaWF0IjoxNzM3OTg1MzI5LCJleHAiOjE3Mzg1OTAxMjl9.GSjpKJ_cG5CqttWwhEeHOxWwlNByvLTu8CGH7ncVug8; rl_anonymous_id=RudderEncrypt%3AU2FsdGVkX1%2BickXpx2WwsiLS3K45TJoms2IgVIMIQRvQnuaNzfjLtzG9mEXObNu4ojurRNkdq0msPjPy10UDEQ%3D%3D; rl_user_id=RudderEncrypt%3AU2FsdGVkX1%2BbvZ%2F6U02zoG3zOFSyRAIzp7gVabGBqqkm7MUCy3Wkn5WOQd%2F%2Bk5e8gVlJ%2BUkJOYJnhS%2F%2Btc7D99%2FTIaFVympE%2BjrtY7ydRWcd69oJHwZWGK%2BeCP1cKh9fqq%2B3sFCVYv7pnm4xMkAAwAM%2BDuzhFTZ0ZFWEA9t8z9M%3D; rl_trait=RudderEncrypt%3AU2FsdGVkX19s%2BCzIY1zJrLksYKMyyTZBHFB0YpKHQWouDTpomPoyyHa9MtTtEUArCVmtBaEf%2FqNhQKJrC8I4hX%2FepCmsx8TqQ6Rzxij0%2FBPvvdq6JWijlttfLovsIF%2BjDLnmVfeRsPbdVgrJXo0neA%3D%3D; ph_phc_4URIAm1uYfJO7j8kWSe0J8lc8IqnstRLS7Jx8NcakHo_posthog=%7B%22distinct_id%22%3A%2292786e96ce436aecd3a1d62d818a74e51ca684bb36c805928bef93a3b46549ad%23fc98592c-709e-4b92-a894-fb65e865fde2%22%2C%22%24sesid%22%3A%5B1738160096669%2C%220194b262-b90a-74cf-ab0d-257b174571c7%22%2C1738159601930%5D%2C%22%24epp%22%3Atrue%2C%22%24initial_person_info%22%3A%7B%22r%22%3A%22%24direct%22%2C%22u%22%3A%22https%3A%2F%2Factions.singular-innovation.com%2Fsignin%3Fredirect%3D%25252F%22%7D%7D; rl_session=RudderEncrypt%3AU2FsdGVkX19G2WmuxH5ZaEfkSkfe4e2i5iyzrvY4U6jPHxAnaSaY8YaPPAFRADU%2FgEyIFzVE0cEXdOZLTBcsa%2Byoiz3Wng4SqZeqnZu2pr1a%2FT0A6mSwTn%2Bw1Ki5ozJpDTVNg6%2BWfaNDa1LGpWRzCQ%3D%3D",
            "sec-ch-ua": "\"Google Chrome\";v=\"131\", \"Chromium\";v=\"131\", \"Not_A Brand\";v=\"24\"",
            "x-real-ip": "177.232.86.200",
            "connection": "close",
            "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
            "cache-control": "max-age=0",
            "sec-fetch-dest": "document",
            "sec-fetch-mode": "navigate",
            "sec-fetch-site": "none",
            "sec-fetch-user": "?1",
            "accept-encoding": "gzip, deflate, br, zstd",
            "accept-language": "es-419,es;q=0.9",
            "x-forwarded-for": "177.232.86.200",
            "sec-ch-ua-mobile": "?0",
            "x-forwarded-proto": "https",
            "sec-ch-ua-platform": "\"Windows\"",
            "upgrade-insecure-requests": "1"
          },
          "webhookUrl": "https://actions.singular-innovation.com/webhook-test/centroid",
          "executionMode": "test"
        }
      }
    ]
  },
  "settings": {
    "executionOrder": "v1"
  },
  "versionId": "f9c7fa52-264b-4967-ae7a-62247cce7a50",
  "connections": {
    "Receive Vectors": {
      "main": [
        [
          {
            "node": "Extract & Parse Vectors",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Extract & Parse Vectors": {
      "main": [
        [
          {
            "node": "Validate & Compute Centroid",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Validate & Compute Centroid": {
      "main": [
        [
          {
            "node": "Return Centroid Response",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  }
}

功能特点

  • 自动检测新邮件
  • AI智能内容分析
  • 自定义分类规则
  • 批量处理能力
  • 详细的处理日志

技术分析

节点类型及作用

  • Webhook
  • Set
  • Code
  • Respondtowebhook
  • Stickynote

复杂度评估

配置难度:
★★★☆☆
维护难度:
★★☆☆☆
扩展性:
★★★★☆

实施指南

前置条件

  • 有效的Gmail账户
  • n8n平台访问权限
  • Google API凭证
  • AI分类服务订阅

配置步骤

  1. 在n8n中导入工作流JSON文件
  2. 配置Gmail节点的认证信息
  3. 设置AI分类器的API密钥
  4. 自定义分类规则和标签映射
  5. 测试工作流执行
  6. 配置定时触发器(可选)

关键参数

参数名称 默认值 说明
maxEmails 50 单次处理的最大邮件数量
confidenceThreshold 0.8 分类置信度阈值
autoLabel true 是否自动添加标签

最佳实践

优化建议

  • 定期更新AI分类模型以提高准确性
  • 根据邮件量调整处理批次大小
  • 设置合理的分类置信度阈值
  • 定期清理过期的分类规则

安全注意事项

  • 妥善保管API密钥和认证信息
  • 限制工作流的访问权限
  • 定期审查处理日志
  • 启用双因素认证保护Gmail账户

性能优化

  • 使用增量处理减少重复工作
  • 缓存频繁访问的数据
  • 并行处理多个邮件分类任务
  • 监控系统资源使用情况

故障排除

常见问题

邮件未被正确分类

检查AI分类器的置信度阈值设置,适当降低阈值或更新训练数据。

Gmail认证失败

确认Google API凭证有效且具有正确的权限范围,重新进行OAuth授权。

调试技巧

  • 启用详细日志记录查看每个步骤的执行情况
  • 使用测试邮件验证分类逻辑
  • 检查网络连接和API服务状态
  • 逐步执行工作流定位问题节点

错误处理

工作流包含以下错误处理机制:

  • 网络超时自动重试(最多3次)
  • API错误记录和告警
  • 处理失败邮件的隔离机制
  • 异常情况下的回滚操作