n8n如何添加AI节点?在自动化流程中融入AI能力

之前有介绍过一个自动化工作流:Get top5 on Product Hunt。也就是说每天定时通过邮件给你发送Product Hunt上的top5产品信息,帮你快速了解最新产品动态。(这一篇文章在这里:Get top5 on Product Hunt | n8n自动化工作流

Product Hunt网站:https://www.producthunt.com/

每天收到的邮件信息:

那么问题来了,针对产品的大篇幅的评论,看起来比较耗时,我能否用AI模型,来整理评论的重要信息?比如是正面还是负面评价,评论里是否有用户的需求,是否有用户提出了产品建议之类的。 这样帮你了解产品趋势和用户想法也是非常有价值的。

比如在之前的表格下面,加一行AI的总结。

这就需要我们在n8n的流程上增加AI的节点,今天我们就来介绍下,如何在n8n使用AI节点,来达到我们分析评论的需求。

我们先说一下这个AI节点要如何配置。

其实n8n里也内置了不少AI的模型。

我们在新建节点里点击Advanced AI,就可以进行选择了。

选择后,通过API key连接上你的AI模型即可。

不过我们今天不通过这种方法来用AI模型(主要是这些模型我都没有充值渠道,没法用 o(╥﹏╥)o )

我们直接用HTTP Request节点的方式来连接AI模型

这里我选择用阿里的通义千问AI模型来试试。因为通义千问的qwen-turbo模型,注册后的一个月内,提供了免费的1000000个token使用。还是很方便的。

官网:https://dashscope.console.aliyun.com/

API文档:https://help.aliyun.com/zh/dashscope/developer-reference/use-qwen-by-api?spm=a2c4g.11186623.0.0.47b046c1x7TXWH

在官网注册完成之后,创建一个API key,复制后妥善保管。

接下来我们通过API来使用通义千问。

可以参考API文档里的参数说明。

好的,那么我们在n8n的HTTP Request节点来配置

这几个配置项如下:

1、method:POST

2、URL:https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation 这个是AI模型的API地址

3、headers:把header的开关打开,需要配置两个参数

①name:Content-Type ;value:application/json

②name:Authorization ;value:Bearer [your api key]

4、body:把body的开关打开,body的类型选择json,然后在json的输入框内输入模型的信息。

这里需要两个字段:

model:数据类型是string,指定用于对话的通义千问模型名,如qwen-turbo

input:数据类型为object,输入模型的信息,这里重要是要输入prompt

大概得一个结构是这样的:

{
  "model": "qwen-turbo",
  "input": {
    "prompt": "请输入你的prompt"
  }
}   

比如我先这样定义了我的prompt

{
  "model": "qwen-turbo",
  "input": {
    "prompt": "以下是5个产品的产品名称Product Nam和对应的评论Comments {{ $json.escapedData }} .请对这5个产品的评论进行分析,分析内容包括:1.大家对该产品的整体评价是好还是坏。2.用户提到了哪些问题。3.用户提到了哪些需求或改进建议。4.请为每个产品给出一个总结性的结论。请用中文输出,并保持结构清晰."
  }
}   

注:{{ $json.escapedData }}是一个变量,数据是从前面节点中output出来的。 这里注意一定要是字符串的格式,不然整个json格式会有问题并且报错。

执行后大概是这样的一个效果:

这就是AI模型节点的一个配置方法。

然后我们看下其他节点的配置。

首先是prompt里的{{ $json.escapedData }},因为是字符串格式,所以从一开始的GraphQL接口输出的数据,就要在过程中进行一些加工。

接下来分别来讲讲(我这几个节点稍微麻烦了一点,主要过程中的各种调试加多了几个code节点,其实可以再简洁一点,不过没关系,我先按这样来说明逻辑,有时间可以做一些简洁和优化)

1、获取产品信息,合并评论文本

这一步主要是想把每个产品中的评论都合并在一起,为了后面统一丢给AI去分析。

因为GraphQL接口输出的数据,评论字段是如下的结构,每个评论都在一个node对象里。

所以这一步主要想把每个产品里的node的数据都分别合并起来

// 确保从名为 'GraphQL' 的节点获取输出数据
const graphqlOutput = $node['GraphQL'].json.data.posts.edges;
// 遍历产品数组,提取每个产品的评论内容,并生成新的结构
return graphqlOutput.map(edge => {
    const product = edge.node;  // 访问产品节点

    // 检查是否有评论,如果有则提取评论内容
    const commentsText = product.comments.edges.map(commentEdge => {
        return commentEdge.node.body;  // 提取每条评论的文本内容
    }).join(" ");  // 将所有评论文本合并成一个字符串,使用空格分隔


  
    // 返回一个新的对象,包含产品信息和合并的评论文本
    return {
        json: {
            product,  // 完整的产品信息
            commentsText  // 合并后的评论文本
        }
    };
});

2、获取产品名称和评论

把产品名称和合并后的评论分别都提取出来。

return items.map(item => {
    return {
        json: {
            productName: item.json.product.name,
            commentsText: item.json.commentsText
        }
    };
});

3、合并产品名称和评论,并去掉特殊字符

这一步把产品名称和评论合并在一起,并且把里面的特殊表情字符都去掉。

const serializedArray = items.map(item => {
    const sanitizedComments = item.json.commentsText.replace(/[^a-zA-Z0-9\s.,]/g, '');    
    return `Product Name: "${item.json.productName}", Comments: "${sanitizedComments}"`;
});

const serializedData = serializedArray.join("; ");


return  [
    {     
            serializedData      
    }
];

4、序列化内容,改为字符串格式

最后是需要把数据的格式改一下,变成字符串,后面给到AI模型节点,在prompt里面就不会出错。

// 获取输入数据
const items = $input.all();
// 创建一个空数组,用于存储处理后的数据
const result = [];
// 遍历每个输入项
items.forEach(item => {
  // 提取 serializedData 字段
  const serializedData = item.json.serializedData;
// 转义特殊字符并去掉外部的双引号
  const escapedData = JSON.stringify(serializedData).slice(1, -1);
  // 将处理后的数据添加到结果数组中
  result.push({
    json: {
      escapedData
    }
  });
});

// 返回处理后的结果
return result;

好了,这些处理完了,就回到我们一开始介绍的http节点来实现AI模型的调用。

调用完成后,我们用code节点把内容变成表格的样式,然后通过gmail发送即可。

修改output格式节点

return items.map(item => {
  const product = $node['GraphQL'].json.data.posts.edges.map(edge => edge.node);

  // 获取上一个 n8n 节点输出的文本内容
  let textContent = $node['AI模型引用'].json.output.text; 

  // 做一些换行的操作,让文本看着更清晰一点
  textContent = textContent
    .replace(/#### /g, '<br>#### ')
    .replace(/- \*\*/g, '<br>- **');
  
  const tableRows = product.map(prod => {
    const comments = prod.comments.edges.map((comment, index) => `${index + 1}. ${comment.node.body}`).join("<br>");
    return `<tr>
      <td>${prod.name}</td>
      <td>${prod.tagline}</td>
      <td>${prod.description}</td>
      <td>${prod.votesCount}</td>
      <td><a href="${prod.website}">${prod.website}</a></td>
      <td>${comments}</td>
    </tr>`;
  }).join("");

  // 在表格末尾追加一个合并的text列
  const tableHTML = `
    <table border="1">
      <thead>
        <tr>
          <th>Name</th>
          <th>Tagline</th>
          <th>Description</th>
          <th>Votes Count</th>
          <th>Website</th>
          <th>Comments</th>
        </tr>
      </thead>
      <tbody>
        ${tableRows}
        <tr>
          <td colspan="6">${textContent}</td> <!-- 合并所有单元格的text列 -->
        </tr>
      </tbody>
    </table>
  `;
  
  return {
    json: {
      tableHTML: tableHTML
    }
  };
});

gmail节点的配置方法我这里就不详细说了,之前这一篇文章有介绍,需要的话可以看这里:Get top5 on Product Hunt | n8n自动化工作流

那么到此,这个流程就配置完成了。

最后还是提醒一句,记得保存并且把运行开关打开。这样流程才会开始自动化运行。

1,248人评论了“n8n如何添加AI节点?在自动化流程中融入AI能力”

  1. Эта публикация погружает вас в мир увлекательных фактов и удивительных открытий. Мы расскажем о ключевых событиях, которые изменили ход истории, и приоткроем завесу над научными достижениями, которые вдохновили миллионы. Узнайте, чему может научить нас прошлое и как применить эти знания в будущем.
    Подробнее можно узнать тут – https://medalkoblog.ru/

  2. ¡Saludos, descubridores de tesoros!
    casino fuera de EspaГ±a con tragamonedas 3D – п»їhttps://casinosonlinefueraespanol.xyz/ casinos fuera de espaГ±a
    ¡Que disfrutes de instantes inolvidables !

  3. ¡Hola, cazadores de recompensas excepcionales!
    Casino online extranjero con pagos por Skrill – п»їhttps://casinosextranjerosdeespana.es/ casinosextranjerosdeespana.es
    ¡Que vivas increíbles victorias memorables !

  4. ¡Saludos, exploradores de oportunidades únicas !
    Casino sin registro sin compartir identidad – п»їemausong.es casino sin licencia espaГ±a
    ¡Que disfrutes de increíbles jugadas impresionantes !

  5. Я бы хотел отметить качество исследования, проведенного автором этой статьи. Он представил обширный объем информации, подкрепленный надежными источниками. Очевидно, что автор проявил большую ответственность в подготовке этой работы.

  6. Я не могу не отметить качество исследования, представленного в этой статье. Она обогатила мои знания и вдохновила меня на дальнейшее изучение темы. Благодарю автора за его ценный вклад!

  7. Hello stewards of pure serenity!
    The best air purifiers for pets are often part of a complete allergy management plan recommended by professionals. Owners of shedding dogs appreciate how an air purifier for dog hair cuts down cleaning time dramatically. When looking for the best air purifier for pet hair, consider models with pet-specific filtration layers.
    Using a pet hair air purifier while brushing your dog or cat minimizes airborne fur during grooming. A good air purifier for pets can trap fur and particles before they settle on bedding or toys.best rated air purifier for petsKeeping an air purifier for pets near crates or kennels maintains a fresher space for your animals.
    Best Pet Air Filter for Allergies and Odors – п»їhttps://www.youtube.com/watch?v=dPE254fvKgQ
    May you enjoy remarkable stunning purity !

  8. ¿Saludos jugadores empedernidos
    Casino europeo implementa modos de aprendizaje donde puedes ver simulaciones y tutoriales antes de jugar con dinero real. Esto ayuda a reducir errores de novato. casinos europeos Aprender antes de arriesgar es una buena idea.
    Casinosonlineeuropeos.guru tiene una secciГіn de alertas para notificarte si un operador recibe sanciones o pierde licencia. AsГ­ puedes actuar con rapidez. La vigilancia activa es parte de su servicio.
    AnГЎlisis de los casinos europeos mГЎs seguros y populares – п»їhttps://casinosonlineeuropeos.guru/
    ¡Que disfrutes de grandes triunfos !

  9. Hello would you mind stating which blog platform you’re using? I’m looking to start my own blog soon but I’m having a tough time making a decision between BlogEngine/Wordpress/B2evolution and Drupal. The reason I ask is because your layout seems different then most blogs and I’m looking for something completely unique. P.S Apologies for getting off-topic but I had to ask!

  10. legit online casinos usa, 888 poker login australia and top online pokies and casinos australian open,
    or free money online casino united kingdom

    Look at my blog; beste spielautomaten richtiges geld 2025 (Nicholas)

  11. Я прочитал эту статью с большим удовольствием! Автор умело смешал факты и личные наблюдения, что придало ей уникальный характер. Я узнал много интересного и наслаждался каждым абзацем. Браво!

  12. As a result, Stake.us is allowed to offer casino-style games in many states where real money online casino gaming is outlawed. Just bear the following things mind: Study traffic patterns and practice in demo mode before betting real money. Well-timed moves can be the difference between big wins and sudden losses. Mission Uncrossable offers seamless cross-platform play, allowing players to enjoy the game on both desktop and mobile devices without the need for downloads. This accessibility ensures that you can play Mission Uncrossable anytime, anywhere, enhancing the overall gaming experience. In the dynamic world of online gaming, Roobet has consistently delivered innovative and engaging experiences. One of its standout offerings is “Mission Uncrossable,” affectionately dubbed the “Chicken Game” by enthusiasts. This game combines elements of strategy, risk, and reward, providing players with an adrenaline-pumping adventure. For Canadian gamers seeking a unique challenge, Mission Uncrossable offers an unparalleled experience.
    https://oomdaanseplaas.co.za/index.php/2025/07/12/big-bass-splash-slot-review-for-uk-players/
    We cant recommend this enough, it replaces any losing images. You should also put other factors into consideration like a secure and trusted crypto casino, where contact information for Pennsylvanian resources can be found. However, security software used to protect players at buffalo king megaways you get a free respin. Don’t be afraid to use a coupon for a new game once you get to the casino, overall the nice design does not make up for its several flaws and we cannot give this much of a recommendation. You can register for an account at Fun Casino in three simple steps, is there a maximum limit for betting on buffalo king megaways Pragmatic Play. Basic Game Info We are sure that you wont be disappointed with the catalog of games the brand has, with 37 pockets to its roulette wheel. When done with the registration and transferred to the dashboard automatically, but a -210 bet would not. How to choose the best casino to play Buffalo King Megaways safely you have a lot of chances in this game to make some seriously fast cash, there are independent organizations that do regular spot-audits. The UK Gambling Commission is one of the strictest authorities in the world, if you have little storage space playing Blackjack in your browser is more viable. A field wager only loses when 5, how can I calculate RTP on Buffalo King Megaways game or you can always check with customer support.

  13. Я прочитал эту статью с огромным интересом! Автор умело объединил факты, статистику и персональные истории, что делает ее настоящей находкой. Я получил много новых знаний и вдохновения. Браво!

  14. Я хотел бы поблагодарить автора этой статьи за его основательное исследование и глубокий анализ. Он представил информацию с обширной перспективой и помог мне увидеть рассматриваемую тему с новой стороны. Очень впечатляюще!

  15. ¡Saludos a todos los jugadores dedicados!
    Casas de apuestas sin dni permiten apostar sin validaciГіn documental. Jugar sin dni es ideal para quienes valoran la rapidez. casas de apuestas sin dni CasasdeapuestasSINdni.guru brinda acceso a plataformas anГіnimas.
    Casas de apuestas sin verificaciГіn aceptan criptomonedas y tarjetas virtuales. Jugar sin registrarse garantiza privacidad completa. CasasdeapuestasSINdni brinda plataformas rГЎpidas y seguras.
    Accede a casas de apuestas sin registro dni desde tu mГіvil – п»їhttps://casasdeapuestassindni.guru/
    ¡Que goces de increíbles premios !

  16. Я просто восхищен этой статьей! Автор предоставил глубокий анализ темы и подкрепил его примерами и исследованиями. Это помогло мне лучше понять предмет и расширить свои знания. Браво!

  17. Thank you, I have just been looking for information approximately this topic for a long time and yours is the greatest I have discovered so far. However, what concerning the conclusion? Are you positive in regards to the supply?

  18. Thanks a bunch for sharing this with all people you actually realize what you are speaking about! Bookmarked. Kindly also visit my web site =). We may have a hyperlink alternate agreement between us

  19. I have been exploring for a little for any high-quality articles or blog posts on this sort of space . Exploring in Yahoo I eventually stumbled upon this site. Studying this information So i am satisfied to exhibit that I have a very good uncanny feeling I came upon just what I needed. I most definitely will make certain to do not disregard this site and give it a look regularly.

  20. Я ценю фактический и информативный характер этой статьи. Она предлагает читателю возможность рассмотреть различные аспекты рассматриваемой проблемы без внушения какого-либо определенного мнения.

  21. You actually make it appear so easy with your presentation but I find this topic to be really something which I feel I would never understand. It sort of feels too complex and extremely large for me. I’m taking a look ahead for your subsequent put up, I’ll try to get the cling of it!

  22. ¡Mis mejores deseos a todos los cazadores de premios!
    Al apostar en casinos online fuera de espaГ±a encaras con jackpots progresivos de alto valor y reglas claras para jugadores exigentes. casinosonlineinternacionales.guru Estas plataformas incluyen herramientas de juego responsable y depГіsitos mГ­nimos muy bajos. AsГ­ se combinan innovaciГіn, velocidad y soporte cercano.
    En un casino internacional se puede jugar en diferentes divisas. Esto incluye euros, dГіlares y criptomonedas. AsГ­, se adapta a cada jugador.
    Casinosonlineinternacionales con juegos innovadores – п»їhttps://casinosonlineinternacionales.guru/
    ¡Que disfrutes de extraordinarias recompensas !

  23. Wonderful goods from you, man. I’ve understand your stuff previous to and you’re just too magnificent. I actually like what you have acquired here, certainly like what you’re saying and the way in which you say it. You make it enjoyable and you still care for to keep it smart. I cant wait to read much more from you. This is actually a tremendous website.

  24. Good day! I know this is kinda off topic however , I’d figured I’d ask. Would you be interested in trading links or maybe guest authoring a blog post or vice-versa? My blog covers a lot of the same topics as yours and I feel we could greatly benefit from each other. If you might be interested feel free to shoot me an e-mail. I look forward to hearing from you! Wonderful blog by the way!

发表评论

您的邮箱地址不会被公开。 必填项已用 * 标注

滚动至顶部