Multi-Agent Conversation

工作流概述

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

工作流源代码

下载
{
  "id": "0QQxgdQABUbbDJ0G",
  "meta": {
    "instanceId": "c98909b50b05c4069bd93ee5a4753d07322c9680e81da8568e96de2c713adb5c"
  },
  "name": "Multi-Agent Conversation",
  "tags": [],
  "nodes": [
    {
      "id": "218308e2-dc68-43ee-ae84-d931ad7a4ac5",
      "name": "When chat message received",
      "type": "@n8n/n8n-nodes-langchain.chatTrigger",
      "position": [
        -1880,
        -3280
      ],
      "webhookId": "a74752f3-419a-4510-856f-3efeaceec019",
      "parameters": {
        "options": {}
      },
      "typeVersion": 1.1
    },
    {
      "id": "a519fe1e-8739-46e0-9770-deb256ab96cf",
      "name": "AI Agent",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "position": [
        -340,
        -3280
      ],
      "parameters": {
        "text": "={{ $json.chatInput }}",
        "options": {
          "systemMessage": "=Current date is {{ $now.format('yyyy-MM-dd') }}. The current time is {{ $now.format('HH:MM:ss') }}.

The user is {{ $('Define Global Settings').item.json.user.name }}, based in {{ $('Define Global Settings').item.json.user.location }}. {{ $('Define Global Settings').item.json.user.notes }}

You are part of a conversation with a user and multiple AI Assistants: {{ $('Define Agent Settings').item.json.keys() }}

You are {{ $('First loop?').item.json.name }}.

{{ $('Loop Over Items').item.json.systemMessage }}

{{ $('Define Global Settings').item.json.global.systemMessage }}"
        },
        "promptType": "define"
      },
      "typeVersion": 1.8
    },
    {
      "id": "2e00f0ff-e7af-45d5-99bc-23031b5d7892",
      "name": "Loop Over Items",
      "type": "n8n-nodes-base.splitInBatches",
      "position": [
        -1000,
        -3280
      ],
      "parameters": {
        "options": {}
      },
      "typeVersion": 3
    },
    {
      "id": "1c979a20-46a5-4591-92da-82c1c96277c6",
      "name": "Extract mentions",
      "type": "n8n-nodes-base.code",
      "position": [
        -1220,
        -3280
      ],
      "parameters": {
        "jsCode": "// Analyzes the user message and extracts @mentions in the order they appear. If there are none, all Assistants will be called in random order.
// --- Configuration: Adjust these lines ---
const chatMessageNodeName = 'When chat message received'; // <-- Replace with your Chat Message node name
const agentSetupNodeName = 'Define Agent Settings';         // <-- Replace with your Agent Setup node name
const chatTextPath = 'json.chatInput';               // <-- Replace with path to text in Chat node output (e.g., 'json.message')
// --- End Configuration ---

// Helper function for safe nested property access (alternative to _.get)
function getSafe(obj, path, defaultValue = undefined) {
    const pathParts = path.split('.');
    let current = obj;
    for (const part of pathParts) {
        if (current === null || current === undefined || typeof current !== 'object' || !Object.prototype.hasOwnProperty.call(current, part)) {
            return defaultValue;
        }
        current = current[part];
    }
    return current ?? defaultValue;
}

// 1. Get Chat Text
const chatMessageNode = $(chatMessageNodeName);
const chatText = getSafe(chatMessageNode.item, chatTextPath, '');

// 2. Get Agent Data and Names
const agentSetupNode = $(agentSetupNodeName);
const agentData = getSafe(agentSetupNode.item, 'json', {}); // e.g., { Chad: {...}, Gemma: {...}, Claude: {...} }
const agentNames = Object.keys(agentData);

// 3. Find all mentions, their names, and their positions in the text
const foundMentions = [];
if (chatText && agentNames.length > 0) {
    const escapeRegex = (s) => s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
    const agentPatternPart = agentNames.map(escapeRegex).join('|');

    if (agentPatternPart) {
        const mentionPattern = new RegExp(`\\B@(${agentPatternPart})\\b`, 'gi');
        const matches = chatText.matchAll(mentionPattern);

        for (const match of matches) {
            const matchedNameCaseInsensitive = match[1];
            const matchIndex = match.index;
            const canonicalName = agentNames.find(name => name.toLowerCase() === matchedNameCaseInsensitive.toLowerCase());
            if (canonicalName) {
                foundMentions.push({ name: canonicalName, index: matchIndex });
            }
        }
    }
}

// 4. Sort the found mentions by their index (order of appearance)
foundMentions.sort((a, b) => a.index - b.index);

// 5. Map the sorted mentions to the desired output format (array of agent detail objects)
let outputArray = foundMentions.map(mention => {
    const agentDetails = agentData[mention.name];
    if (!agentDetails) {
        console.warn(`Could not find details for agent: ${mention.name}`);
        return null;
    }
    return {
        name: agentDetails.name,
        model: agentDetails.model,
        systemMessage: agentDetails.systemMessage
    };
}).filter(item => item !== null);

// 6. Check if any mentions were specifically found. If not, populate outputArray with ALL agents in RANDOM order.
if (outputArray.length === 0 && foundMentions.length === 0) { // Check if NO mentions were found initially
    // --- NO MENTIONS FOUND ---
    // Populate outputArray with ALL agents from agentData
    const allAgentDetailsArray = Object.values(agentData);

    // --- Simple Randomization ---
    // Shuffle the array in place using sort with a random comparator
    allAgentDetailsArray.sort(() => 0.5 - Math.random());
    // --- End Randomization ---

    // Map all agents (now in random order) to the output structure
    outputArray = allAgentDetailsArray.map(agentObject => ({
        name: agentObject.name,
        model: agentObject.model,
        systemMessage: agentObject.systemMessage
    }));
} // Intentionally no 'else' here, if outputArray already had items from mentions, we use that.

// 7. Final Output Formatting (Handles both cases: specific mentions OR all agents)
// Check if, after everything, the outputArray is *still* empty (e.g., if agentData was empty initially)
if (outputArray.length === 0) {
    // If still empty, return a status or error as a fallback
     return [{ json: { status: \"no_agents_available\", message: \"No mentions found and no agents defined.\" } }];
} else {
    // Return the array of agent objects formatted for n8n (multiple items)
    return outputArray.map(agentObject => ({ json: agentObject }));
}"
      },
      "typeVersion": 2
    },
    {
      "id": "45f635ca-f4fa-4f6c-a32a-9722906255fd",
      "name": "Simple Memory",
      "type": "@n8n/n8n-nodes-langchain.memoryBufferWindow",
      "position": [
        -192,
        -3060
      ],
      "parameters": {
        "sessionKey": "={{ $('When chat message received').first().json.sessionId }}",
        "sessionIdType": "customKey",
        "contextWindowLength": 99
      },
      "typeVersion": 1.3
    },
    {
      "id": "5c903044-bce2-4aa8-b168-a460a4999c54",
      "name": "Set last Assistant message as input",
      "type": "n8n-nodes-base.set",
      "position": [
        -560,
        -3180
      ],
      "parameters": {
        "options": {},
        "assignments": {
          "assignments": [
            {
              "id": "38aa959a-e1e5-4c84-a7bd-ff5e0f61b62d",
              "name": "=chatInput",
              "type": "string",
              "value": "={{ $('Set lastAssistantMessage').first().json.lastAssistantMessage }}"
            }
          ]
        }
      },
      "typeVersion": 3.4
    },
    {
      "id": "7b389b9f-1751-4bc1-9c6f-bf6a04a1e09f",
      "name": "Set user message as input",
      "type": "n8n-nodes-base.set",
      "position": [
        -560,
        -3380
      ],
      "parameters": {
        "options": {},
        "assignments": {
          "assignments": [
            {
              "id": "75b61275-7526-4431-b624-f8e098aa812d",
              "name": "chatInput",
              "type": "string",
              "value": "={{ $('When chat message received').item.json.chatInput }}"
            }
          ]
        }
      },
      "typeVersion": 3.4
    },
    {
      "id": "a238817f-0d10-4cd4-9760-53f69bb179f7",
      "name": "First loop?",
      "type": "n8n-nodes-base.if",
      "position": [
        -780,
        -3280
      ],
      "parameters": {
        "options": {},
        "conditions": {
          "options": {
            "version": 2,
            "leftValue": "",
            "caseSensitive": true,
            "typeValidation": "strict"
          },
          "combinator": "and",
          "conditions": [
            {
              "id": "51c41fdf-f4d3-4c7a-ac18-06815a59a958",
              "operator": {
                "type": "number",
                "operation": "equals"
              },
              "leftValue": "={{ $runIndex}}",
              "rightValue": 0
            }
          ]
        }
      },
      "typeVersion": 2.2
    },
    {
      "id": "415927d7-b1a4-42b2-9607-c6ff707a528b",
      "name": "Set lastAssistantMessage",
      "type": "n8n-nodes-base.set",
      "position": [
        36,
        -3155
      ],
      "parameters": {
        "options": {},
        "assignments": {
          "assignments": [
            {
              "id": "b93025b2-f5a7-476b-bd09-b5b4af050e73",
              "name": "lastAssistantMessage",
              "type": "string",
              "value": "=**{{ $('Loop Over Items').item.json.name }}**:

{{ $json.output }}"
            }
          ]
        }
      },
      "typeVersion": 3.4
    },
    {
      "id": "77861e4b-a1d2-4c35-bf50-15914602a8b5",
      "name": "Combine and format responses",
      "type": "n8n-nodes-base.code",
      "position": [
        -780,
        -3480
      ],
      "parameters": {
        "jsCode": "// Get the array of items from the input (output of the loop)
const inputItems = items;

// Extract the 'lastAssistantMessage' from each item's JSON data.
// If the field is missing or not a string, use an empty string to avoid errors.
const messages = inputItems.map(item => {
  const message = item.json.lastAssistantMessage;
  return typeof message === 'string' ? message : '';
});

// Join the extracted messages together with a horizontal rule separator
const combinedText = messages.join('\n\n---\n\n');

// Return a new single item containing the combined text.
// You can rename 'output' if you like.
return [{ json: { output: combinedText } }];"
      },
      "typeVersion": 2
    },
    {
      "id": "4da2f95d-bce4-4844-a23c-63ca777efbfd",
      "name": "Define Global Settings",
      "type": "n8n-nodes-base.code",
      "position": [
        -1660,
        -3280
      ],
      "parameters": {
        "jsCode": "// Configure Global settings. This includes information about you - the user - and a section of the System Message that all Assistants will see. (Assistant-specific System Message sections can be set in the 'Define Agent Settings' node.)
return [
  {
    json: {
      \"user\": {
        \"name\": \"Jon\",
        \"location\": \"Melbourne, Australia\",
        \"notes\": \"Jon likes a casual, informal conversation style.\"
      },
      \"global\": {
        \"systemMessage\": \"Don't overdo the helpful, agreeable approach.\"
      }
    }
  }
];
"
      },
      "typeVersion": 2
    },
    {
      "id": "6639a554-9e5f-40ac-b68e-b8eaa777252d",
      "name": "Define Agent Settings",
      "type": "n8n-nodes-base.code",
      "position": [
        -1440,
        -3280
      ],
      "parameters": {
        "jsCode": "// Configure Assistants. The number of Assistants can be changed by adding or removing JSON objects. Use the OpenRouter model naming convention.
return [
  {
    json: {
      \"Chad\": {
        \"name\": \"Chad\",
        \"model\": \"openai/gpt-4o\",
        \"systemMessage\": \"You are a helpful Assistant. You are eccentric and creative, and try to take discussions into unexpected territory.\"
      },
      \"Claude\": {
        \"name\": \"Claude\",
        \"model\": \"anthropic/claude-3.7-sonnet\",
        \"systemMessage\": \"You are logical and practical.\"
      },
      \"Gemma\": {
        \"name\": \"Gemma\",
        \"model\": \"google/gemini-2.0-flash-lite-001\",
        \"systemMessage\": \"You are super friendly and love to debate.\"
      }
    }
  }
];
"
      },
      "typeVersion": 2
    },
    {
      "id": "d55a7e02-3574-4d78-a141-db8d3657857b",
      "name": "Sticky Note",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -1750,
        -3620
      ],
      "parameters": {
        "color": 4,
        "width": 500,
        "height": 500,
        "content": "## Step 1: Configure Settings Nodes

Edit the JSON in these nodes to:

- Configure details about you (the user)
- Define content that will appear in all system messages
- Define Agents.

For Agents, you can configure:
- How many you create
- Their names
- The LLM model they use (choose any that are available via OpenRouter)
- Agent-specific system prompt content"
      },
      "typeVersion": 1
    },
    {
      "id": "d3eb2797-4008-4bdb-a588-b2412ed5ffa7",
      "name": "Sticky Note1",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -400,
        -3620
      ],
      "parameters": {
        "color": 4,
        "width": 360,
        "height": 720,
        "content": "## Step 2: Connect Agent to OpenRouter

Set your OpenRouter credentials, and all other parameters including system messages and model selection are dynamically populated."
      },
      "typeVersion": 1
    },
    {
      "id": "a6085a55-db36-42d8-8c57-c9123490581f",
      "name": "Sticky Note2",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -1940,
        -3900
      ],
      "parameters": {
        "color": 5,
        "width": 2180,
        "height": 1100,
        "content": "# Scalable Multi-Agent Conversations

"
      },
      "typeVersion": 1
    },
    {
      "id": "d2ee6317-3a9c-4df8-8fce-87daa3530233",
      "name": "Sticky Note3",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -1200,
        -3860
      ],
      "parameters": {
        "width": 380,
        "height": 360,
        "content": "## About this workflow

**What does this workflow do?**
Enables you to initiate a conversation with multiple AI agents at once. Each agent can be configured with a unique name, system instructions, a different model.

**How do I use it?**
1. Configure the settings nodes to create the Agents you need.
2. Call one or more individual agents using @Name mentions in your messages. If your message does not have @mentions, all agents will be called, in random order."
      },
      "typeVersion": 1
    },
    {
      "id": "a190a268-7f90-4c4e-aceb-482545d0b72b",
      "name": "Sticky Note4",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -820,
        -3860
      ],
      "parameters": {
        "width": 380,
        "height": 360,
        "content": "**How does it work?**
Settings are configured in the first two nodes after the chat trigger. Then @mentions in your message are extracted and fed into a loop. With each loop, the agent's system message and model are dynamically populated, avoiding the need to create multiple agent nodes and complex routing logic.

When all agents have had their say, their responses are combined and formatted. The use of a shared memory node enables multi-round conversations.

**What are the limitations?**
Agents cannot call each other or respond in parallel. Agents' responses are not visible to the user until all agents have responded.

"
      },
      "typeVersion": 1
    },
    {
      "id": "30d8c207-9a7a-46c5-be89-0deafc6c183f",
      "name": "OpenRouter Chat Model",
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenRouter",
      "position": [
        -312,
        -3060
      ],
      "parameters": {
        "model": "={{ $('Extract mentions').item.json.model }}",
        "options": {}
      },
      "credentials": {
        "openRouterApi": {
          "id": "jB56IT6KRdHSBbkw",
          "name": "OpenRouter account"
        }
      },
      "typeVersion": 1
    }
  ],
  "active": false,
  "pinData": {},
  "settings": {
    "executionOrder": "v1"
  },
  "versionId": "6c0312e7-7a81-41cd-9403-8ad947100b80",
  "connections": {
    "AI Agent": {
      "main": [
        [
          {
            "node": "Set lastAssistantMessage",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "First loop?": {
      "main": [
        [
          {
            "node": "Set user message as input",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Set last Assistant message as input",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Simple Memory": {
      "ai_memory": [
        [
          {
            "node": "AI Agent",
            "type": "ai_memory",
            "index": 0
          }
        ]
      ]
    },
    "Loop Over Items": {
      "main": [
        [
          {
            "node": "Combine and format responses",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "First loop?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Extract mentions": {
      "main": [
        [
          {
            "node": "Loop Over Items",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Define Agent Settings": {
      "main": [
        [
          {
            "node": "Extract mentions",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "OpenRouter Chat Model": {
      "ai_languageModel": [
        [
          {
            "node": "AI Agent",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Define Global Settings": {
      "main": [
        [
          {
            "node": "Define Agent Settings",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Set lastAssistantMessage": {
      "main": [
        [
          {
            "node": "Loop Over Items",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Set user message as input": {
      "main": [
        [
          {
            "node": "AI Agent",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "When chat message received": {
      "main": [
        [
          {
            "node": "Define Global Settings",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Combine and format responses": {
      "main": [
        []
      ]
    },
    "Set last Assistant message as input": {
      "main": [
        [
          {
            "node": "AI Agent",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  }
}

功能特点

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

技术分析

节点类型及作用

  • @N8N/N8N Nodes Langchain.Chattrigger
  • @N8N/N8N Nodes Langchain.Agent
  • Splitinbatches
  • Code
  • @N8N/N8N Nodes Langchain.Memorybufferwindow

复杂度评估

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

实施指南

前置条件

  • 有效的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错误记录和告警
  • 处理失败邮件的隔离机制
  • 异常情况下的回滚操作