Skip to content

使用 GPT 进行 AI 编码#

¥AI coding with GPT

自托管不可用。

¥Not available on self-hosted.

不支持 Python。

¥Python isn't supported.

///

在代码节点中使用 AI#

¥Use AI in the Code node

Feature availability

AI assistance in the Code node is available to Cloud users. It isn't available in self-hosted n8n.

AI generated code overwrites your code

If you've already written some code on the Code tab, the AI generated code will replace it. n8n recommends using AI as a starting point to create your initial code, then editing it as needed.

To use ChatGPT to generate code in the Code node:

  1. In the Code node, set Language to JavaScript.
  2. Select the Ask AI tab.
  3. Write your query.
  4. Select Generate Code. n8n sends your query to ChatGPT, then displays the result in the Code tab.

使用限制#

¥Usage limits

在试用阶段,没有使用限制。如果 n8n 将此功能永久启用,则你的定价层级可能存在使用限制。

¥During the trial phase there are no usage limits. If n8n makes the feature permanent, there may be usage limits as part of your pricing tier.

功能限制#

¥Feature limits

n8n 中的 ChatGPT 实现存在以下限制:

¥The ChatGPT implementation in n8n has the following limitations:

  • 人工智能会编写代码来处理来自 n8n 工作流的数据。你无法要求它从其他来源提取数据。

¥The AI writes code that manipulates data from the n8n workflow. You can't ask it to pull in data from other sources.

  • AI 不了解你的数据,只了解模式,因此你需要告诉它如何查找要提取的数据,或者如何检查空值。

¥The AI doesn't know your data, just the schema, so you need to tell it things like how to find the data you want to extract, or how to check for null.

  • 在运行 AI 查询之前,代码节点之前的节点必须执行并将数据传递给代码节点。

¥Nodes before the Code node must execute and deliver data to the Code node before you run your AI query.

  • 不适用于大型传入数据模式。

¥Doesn't work with large incoming data schemas.

  • 如果代码节点之前有很多节点,则可能会出现问题。

¥May have issues if there are a lot of nodes before the code node.

编写良好的提示#

¥Writing good prompts

编写良好的提示可以提高获得有用代码的几率。

¥Writing good prompts increases the chance of getting useful code back.

一些通用技巧:

¥Some general tips:

  • 请提供示例:如果可能,请提供预期输出的示例。这有助于 AI 更好地理解你想要实现的转换或逻辑。

¥Provide examples: if possible, give a sample expected output. This helps the AI to better understand the transformation or logic you’re aiming for.

  • 描述处理步骤:如果数据需要特定的处理步骤或逻辑,请按顺序列出。例如:" 首先,筛选掉所有 18 岁以下的用户。然后,按姓氏对剩余用户进行排序。

¥Describe the processing steps: if there are specific processing steps or logic that should apply to the data, list them in sequence. For example: "First, filter out all users under 18. Then, sort the remaining users by their last name."

  • 避免歧义:虽然 AI 可以理解各种指令,但清晰直接的指令可以确保生成最准确的代码。与其说 "获取较早的用户",不如说 "筛选 60 岁及以上的用户。"。

¥Avoid ambiguities: while the AI understands various instructions, being clear and direct ensures you get the most accurate code. Instead of saying "Get the older users," you might say "Filter users who are 60 years and above."

  • 明确你期望的输出结果。你希望对数据进行转换、过滤、聚合还是排序?尽可能提供详细信息。

¥Be clear about what you expect as the output. Do you want the data transformed, filtered, aggregated, or sorted? Provide as much detail as possible.

以及一些 n8n 特有的指导:

¥And some n8n-specific guidance:

  • 考虑一下输入数据:确保 ChatGPT 知道你要访问哪些数据,以及传入数据代表什么。你可能需要告知 ChatGPT n8n 内置方法和变量的可用性。

¥Think about the input data: make sure ChatGPT knows which pieces of the data you want to access, and what the incoming data represents. You may need to tell ChatGPT about the availability of n8n's built-in methods and variables.

  • 声明节点间的交互:如果你的逻辑涉及来自多个节点的数据,请指定它们应该如何交互。"根据 '用户 ID' 属性合并 '节点 A' 和 '节点 B' 的输出"。如果你希望数据来自特定节点或忽略其他节点,请明确说明:"仅考虑 '购买记录' 节点的数据,忽略 '退款' 节点。"

¥Declare interactions between nodes: if your logic involves data from multiple nodes, specify how they should interact. "Merge the output of 'Node A' with 'Node B' based on the 'userID' property". if you prefer data to come from certain nodes or to ignore others, be clear: "Only consider data from the 'Purchases' node and ignore the 'Refunds' node."

  • 确保输出与 n8n 兼容。有关 n8n 所需的数据结构的更多信息,请参阅 数据结构

¥Ensure the output is compatible with n8n. Refer to Data structure for more information on the data structure n8n requires.

示例提示#

¥Example prompts

这些示例展示了一系列可能的提示和任务。

¥These examples show a range of possible prompts and tasks.

示例 1:在第二个数据集中查找数据#

¥Example 1: Find a piece of data inside a second dataset

要亲自尝试此示例,请执行 下载示例工作流 并将其导入 n8n。

¥To try the example yourself, download the example workflow and import it into n8n.

在第三个代码节点中,输入以下提示:

¥In the third Code node, enter this prompt:

Slack 数据仅包含一个项目。输入数据代表所有 Notion 用户。有时,保存电子邮件地址的 person 属性可能为空。我想找到 Slack 用户的 notionId 并返回它。

¥The slack data contains only one item. The input data represents all Notion users. Sometimes the person property that holds the email can be null. I want to find the notionId of the Slack user and return it.

查看 AI 生成的代码。

¥Take a look at the code the AI generates.

以下是你需要的 JavaScript 代码:

¥This is the JavaScript you need:

1
2
3
4
5
6
7
8
9
const slackUser = $("Mock Slack").all()[0];
const notionUsers = $input.all();
const slackUserEmail = slackUser.json.email;

const notionUser = notionUsers.find(
  (user) => user.json.person && user.json.person.email === slackUserEmail
);

return notionUser ? [{ json: { notionId: notionUser.json.id } }] : [];

示例 2:数据转换#

¥Example 2: Data transformation

要亲自尝试此示例,请执行 下载示例工作流 并将其导入 n8n。

¥To try the example yourself, download the example workflow and import it into n8n.

在“连接项代码”节点中,输入以下提示:

¥In the Join items Code node, enter this prompt:

返回一行文本,其中包含以逗号分隔的所有用户名。每个用户名都应使用双引号括起来。

¥Return a single line of text that has all usernames listed with a comma. Each username should be enquoted with a double quotation mark.

查看 AI 生成的代码。

¥Take a look at the code the AI generates.

以下是你需要的 JavaScript 代码:

¥This is the JavaScript you need:

1
2
3
4
const items = $input.all();
const usernames = items.map((item) => `"${item.json.username}"`);
const result = usernames.join(", ");
return [{ json: { usernames: result } }];

示例 3:摘要数据并创建 Slack 消息#

¥Example 3: Summarize data and create a Slack message

要亲自尝试此示例,请执行 下载示例工作流 并将其导入 n8n。

¥To try the example yourself, download the example workflow and import it into n8n.

在“汇总代码”节点中,输入以下提示:

¥In the Summarize Code node, enter this prompt:

创建一个用于 Slack 的 Markdown 文本,用于统计已提交的想法、功能和错误的数量。提交类型保存在 property_type 字段中。功能具有属性 "功能",错误具有属性 "Bug",想法具有属性 "Bug"。此外,请在该邮件中列出投票数最高的五个提交。使用 "" 作为链接的 Markdown 格式。

¥Create a markdown text for Slack that counts how many ideas, features and bugs have been submitted. The type of submission is saved in the property_type field. A feature has the property "Feature", a bug has the property "Bug" and an idea has the property "Bug". Also, list the five top submissions by vote in that message. Use "" as markdown for links.

查看 AI 生成的代码。

¥Take a look at the code the AI generates.

以下是你需要的 JavaScript 代码:

¥This is the JavaScript you need:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
const submissions = $input.all();

// Count the number of ideas, features, and bugs
let ideaCount = 0;
let featureCount = 0;
let bugCount = 0;

submissions.forEach((submission) => {
  switch (submission.json.property_type[0]) {
    case "Idea":
      ideaCount++;
      break;
    case "Feature":
      featureCount++;
      break;
    case "Bug":
      bugCount++;
      break;
  }
});

// Sort submissions by votes and take the top 5
const topSubmissions = submissions
  .sort((a, b) => b.json.property_votes - a.json.property_votes)
  .slice(0, 5);

let topSubmissionText = "";
topSubmissions.forEach((submission) => {
  topSubmissionText += `<${submission.json.url}|${submission.json.name}> with ${submission.json.property_votes} votes\n`;
});

// Construct the Slack message
const slackMessage = `*Summary of Submissions*\n
Ideas: ${ideaCount}\n
Features: ${featureCount}\n
Bugs: ${bugCount}\n
Top 5 Submissions:\n
${topSubmissionText}`;

return [{ json: { slackMessage } }];

显式引用传入的节点数据#

¥Reference incoming node data explicitly

如果你的传入数据包含嵌套字段,使用点号表示法引用它们可以帮助 AI 理解你想要的数据。

¥If your incoming data contains nested fields, using dot notation to reference them can help the AI understand what data you want.

"Screenshot of an n8n code node, highlighting how to reference data with dot notation in an AI query"

要亲自尝试此示例,请执行 下载示例工作流 并将其导入 n8n。

¥To try the example yourself, download the example workflow and import it into n8n.

在第二个代码节点中,输入以下提示:

¥In the second Code node, enter this prompt:

"模拟数据" 中的数据表示人员列表。对于每个人,返回一个包含 personal_info.first_name 和 work_info.job_title 的新项。

¥The data in "Mock data" represents a list of people. For each person, return a new item containing personal_info.first_name and work_info.job_title.

以下是你需要的 JavaScript 代码:

¥This is the JavaScript you need:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
const items = $input.all();
const newItems = items.map((item) => {
  const firstName = item.json.personal_info.first_name;
  const jobTitle = item.json.work_info.job_title;
  return {
    json: {
      firstName,
      jobTitle,
    },
  };
});
return newItems;

相关资源#

¥Related resources

Pluralsight 提供了一份关于 如何使用 ChatGPT 编写代码 的简短指南,其中包含示例提示。

¥Pluralsight offer a short guide on How to use ChatGPT to write code, which includes example prompts.

修复代码#

¥Fixing the code

人工智能生成的代码可能无需任何修改即可运行,但你可能需要对其进行编辑。你需要了解 n8n 的 数据结构。你可能还会发现 n8n 的内置方法和变量很有用。

¥The AI-generated code may work without any changes, but you may have to edit it. You need to be aware of n8n's Data structure. You may also find n8n's built-in methods and variables useful.