ChatGPT工作计划AI 评分 · 82/100AI 辅助编辑·未发现明显提示词注入风险n8n.io

用 n8n 搭建首个 AI 数据分析师聊天机器人

从 Google Sheets 导入数据 → AI Agent 检索与计算 → 聊天界面输出分析结果

有一点经验步骤流程提示词贴士
给谁
需要在 n8n 中快速搭建 AI 数据查询与分析机器人的用户
你会得到
得到一个可通过聊天交互、从 Google Sheets 拉取数据并做数学运算的 AI Agent 工作流
你需要
n8n

硬约束

需要 n8n 实例;准备 OpenAI API 密钥与 Google Sheets OAuth2 凭证;将模板 workflow.json 导入 n8n;把示例 Google Sheets 文件复制到自己的 Google Drive 并更新所有 Sheets 工具中的文档 URL;按需替换为 Postgres/MySQL 等数据库。

他们做了什么

作者 Solomon 在 n8n 官方模板库发布了一个 31 节点的 AI Agent 工作流模板。核心结构为:Chat Trigger 接收消息 → AI Agent 协调多个工具 → OpenAI gpt-4o 生成回复。数据层通过三种 Google Sheets Tool(全量读取、按状态过滤、按产品名过滤)和一个 Tool Workflow 子工作流(按日期范围过滤)实现检索。子工作流内部使用 HTTP Request 调用 Google Visualization API,再用 Code 节点解析 JSONP 返回,经 Filter 和 Aggregate 后回传。Calculator 工具供 Agent 做数学运算。Buffer Memory 保留最近 5 轮对话上下文。

效果如何

来源报告该模板设计为「easy and efficient」的 AI 数据分折起点,面向数据分析师、开发者、企业主和自动化专家。模板页提供示例提问(如查询一月退款数量与金额、成功销售额、最常见退款原因)。作者注明 Google Sheets 工具可替换为 Postgres/MySQL 等数据库;也提醒不同模型在数据分析任务上表现差异大,建议充分测试。(author_report)

值得知道

1. 子工作流使用 Google Visualization API 的 /gviz/tq 端点,该接口返回 JSONP 而非纯 JSON,因此必须依赖 Code 节点做正则提取和格式转换;若改用真实数据库,此复杂链可大幅简化。2. 所有数据工具均使用 $fromAI 函数,由 AI 根据用户问题自动推断参数值;参数描述质量直接影响调用准确性。3. 来源未提供示例数据的完整列 schema,用户需自行检查复制后的 Sheets 文件结构是否与工具配置匹配(特别是 Status、Product、Date 列)。4. 来源建议可换用 Google Gemini 等免费模型,但强调数据分析任务需充分测试模型表现。5. 本站未实测此工作流,reproduction=not_tested;关键节点参数以 workflow.json 为准,实际运行可能因 n8n 版本差异需调整。

n8n 工作流模板

结构已检查 · 未实际运行

下载后在 n8n 选择“Import from File”,或复制 JSON 后粘贴到编辑器。先配置自己的账号,再用测试数据运行;模板默认未启用。

配置与测试清单

需要绑定的凭证

  • OpenAI Chat Model 节点:绑定OpenAI API 凭证。
  • Google Sheets request 节点:绑定Google Sheets OAuth2 凭证。
  • Get transactions by product name 节点:绑定Google Sheets OAuth2 凭证。
  • Get all transactions 节点:绑定Google Sheets OAuth2 凭证。
  • Get transactions by status 节点:绑定Google Sheets OAuth2 凭证。

需要替换的配置

  • 源模板来自 n8n 公开库 #3050(约 31 个节点)。导入后先保持未启用,核对触发器、表达式与外部 API 端点。
  • Sticky Note 中的说明仅供参考;按自己的账号、表结构或频道 ID 替换占位配置。

测试输入与预期结果

  • 在测试环境手动执行一次主路径,确认每个需凭证的节点已连接且无鉴权错误。
  • 用一条合成/脱敏样例数据跑通,核对输出字段与下游写入目标,再考虑生产启用。

模板处理说明

  • 已移除原作者凭证绑定、webhookId 与执行数据,工作流设为未启用;节点、连线与原文提示词保持原样。未在 n8n 中实际运行。
  • 未改业务逻辑;运行前请自行核对密钥、配额与隐私合规。

模板获取日期: 2026-10-25

步骤

  1. 导入模板并配置凭证

    在 n8n 中导入本模板 workflow.json。在 Credentials 中配置 openAiApi(OpenAI API Key)与 googleSheetsOAuth2Api(Google OAuth 单服务凭证,参考 https://docs.n8n.io/integrations/builtin/credentials/google/oauth-single-service/)。将示例 Google Sheets 文件 https://docs.google.com/spreadsheets/d/18A4d7KYrk8-uEMbu7shoQe_UIzmbTLV1FMN43bjA7qc/edit?gid=0#gid=0 复制到自己的 Google Drive,然后更新所有 Google Sheets 工具节点中的 documentId 为该文件的 URL。

  2. 配置 AI Agent 核心参数

    打开 AI Agent 节点,确认 Options 中的 System Message 为:'=You are a helpful assistant.\nCurrent timestamp is {{ $now }}'(保留前导等号,使 n8n 解析为表达式)。将 OpenAI Chat Model 设为 gpt-4o,temperature 0.2。连接 Buffer Memory(短期记忆,默认记住最近 5 轮对话)到 AI Agent 的 Memory 接口。

    运行提示词 · 来源原文。AI Agent 节点 → Options → System Message 字段

    =You are a helpful assistant.
    Current timestamp is {{ $now }}
  3. 连接数据检索工具

    将以下四个工具连接到 AI Agent 的 Tools 接口:1) Get all transactions(Google Sheets Tool)— 手动描述设为 'Only use this as last resort, because it will pull all data at once.';2) Get transactions by status — 使用 $fromAI('transaction_status', 'Transaction status can be Refund, Completed or Error', 'string') 过滤 Status 列;3) Get transactions by product name — 使用 $fromAI('product_name', 'The product name', 'string') 过滤 Product 列,工具描述列出 Widget A/B/C/D;4) Records by date — 这是一个 Tool Workflow 节点,调用同工作流内的子工作流,使用 $fromAI 获取 start_date、end_date、status 三个参数。所有工具均使用 $fromAI 函数让 AI 自动填充参数。

    运行提示词 · 来源原文。Records by date 节点 → Description 字段

    Use this tool to get records filtered by date. You can also filter by status at the same time, if you want.

    运行提示词 · 来源原文。Records by date 节点 → Workflow Inputs → start_date

    ={{ $fromAI("start_date", "Start date in format YYYY-MM-DD", "string") }}

    运行提示词 · 来源原文。Records by date 节点 → Workflow Inputs → end_date

    ={{ $fromAI("end_date", "End date in format YYYY-MM-DD", "string") }}

    运行提示词 · 来源原文。Records by date 节点 → Workflow Inputs → status

    ={{ $fromAI("status", "Status of the transaction. Can be Completed, Refund or Error. Leave empty if you don't need this now.", "string") }}

    运行提示词 · 来源原文。Get transactions by product name 节点 → Tool Description

    Find transactions by product.
    Our products are:
    - Widget A
    - Widget B
    - Widget C
    - Widget D

    运行提示词 · 来源原文。Get transactions by product name 节点 → Filters UI → lookupValue

    ={{ $fromAI("product_name", "The product name", "string") }}

    运行提示词 · 来源原文。Get transactions by status 节点 → Tool Description

    Find transactions by status

    运行提示词 · 来源原文。Get transactions by status 节点 → Filters UI → lookupValue

    ={{ $fromAI("transaction_status", "Transaction status can be Refund, Completed or Error", "string") }}

    运行提示词 · 来源原文。Get all transactions 节点 → Tool Description

    Only use this as last resort, because it will pull all data at once.
  4. 配置日期过滤子工作流

    子工作流由 When Executed by Another Workflow 触发,接收 start_date、end_date、status 三个输入。Google Sheets request 节点向 Google Visualization API 发送 HTTP 请求:URL 为 https://docs.google.com/spreadsheets/d/{your-sheet-id}/gviz/tq,query 参数 sheet=Sheet1,tq='SELECT * WHERE A >= DATE "{{ $json.start_date }}" AND A <= DATE "{{ $json.end_date }}"'。Code 节点解析返回的 JSONP 数据,提取 cols 和 rows 并格式化为 JSON 对象数组(含日期格式转换)。Filter by status 节点用条件 $json.Status 包含触发器的 status 输入做过滤。Aggregate 节点将所有结果聚合为单一 item 返回给 AI Agent。

    运行提示词 · 来源原文。Code 节点 → JavaScript Code 字段

    // Ensure there's at least one input item.
    if (!items || items.length === 0) {
      throw new Error("No input items found.");
    }
    
    // Our input is expected to have a 'data' property containing the JSONP string.
    const input = items[0].json;
    
    if (!input.data) {
      throw new Error("Input JSON does not have a 'data' property.");
    }
    
    const rawData = input.data;
    
    // Use a regex to extract the JSON content from the Google Visualization JSONP response.
    const regex = /google\.visualization\.Query\.setResponse\((.*)\);?$/s;
    const match = rawData.match(regex);
    
    if (!match) {
      throw new Error("Input data does not match the expected Google Visualization JSONP format.");
    }
    
    const jsonString = match[1];
    
    // Parse the extracted JSON string.
    let parsed;
    try {
      parsed = JSON.parse(jsonString);
    } catch (error) {
      throw new Error("Failed to parse JSON: " + error.message);
    }
    
    // Verify that the parsed JSON has the expected 'table' structure with 'cols' and 'rows'.
    if (!parsed.table || !Array.isArray(parsed.table.cols) || !Array.isArray(parsed.table.rows)) {
      throw new Error("Parsed JSON does not have the expected 'table' structure with 'cols' and 'rows'.");
    }
    
    const cols = parsed.table.cols;
    const rows = parsed.table.rows;
    
    // Helper function to convert date string from "Date(YYYY,M,D)" to "YYYY-MM-DD"
    function formatDate(dateStr) {
      const match = dateStr.match(/^Date\((\d+),(\d+),(\d+)\)$/);
      if (!match) return dateStr;
      const year = parseInt(match[1], 10);
      const month = parseInt(match[2], 10) + 1; // JavaScript months are 0-indexed
      const day = parseInt(match[3], 10);
      // Format with leading zeros
      return `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
    }
    
    // Map each row into an object using the column labels as keys.
    const newItems = rows.map(row => {
      const obj = {};
      cols.forEach((col, index) => {
        let value = row.c && row.c[index] ? row.c[index].v : null;
        // If the column type is "date" and the value is a string that looks like "Date(YYYY,M,D)"
        if (col.type === "date" && typeof value === "string") {
          value = formatDate(value);
        }
        obj[col.label] = value;
      });
      return { json: obj };
    });
    
    // Return the new array of items.
    return newItems;
  5. 附加 Calculator 工具并测试

    将 Calculator 工具连接到 AI Agent 的 Tools 接口,使 Agent 能够对检索到的数据执行数学运算。保存并启用工作流。在 Chat Trigger 的测试界面尝试提问:'How many refunds in January and what was the amount refunded?' 或 'How many successful sales did we have in January 2025 and what was the final income of those?' 观察 AI 是否正确调用工具、过滤数据并计算结果。

可复制提示词

搭建指导 · 本站建议版本。交给搭建助手,先确认输入和权限

这一段是提示词,页面不会在这里插入广告。

你是一个 n8n 工作流搭建助手。用户希望复现「AI 数据分析师聊天机器人」模板。请按以下顺序协助:
1. 确认用户已有 n8n 实例、OpenAI API Key、Google Sheets OAuth2 凭证;
2. 指导导入 workflow.json 并更新 Google Sheets 文档 URL;
3. 检查 AI Agent 的 System Message、OpenAI Chat Model 设置(gpt-4o, temperature 0.2)及 Buffer Memory 连接;
4. 确认四个数据检索工具(Get all transactions / by status / by product name / Records by date)和 Calculator 已正确连接;
5. 说明子工作流的输入输出逻辑,提醒用户若改用数据库可简化 HTTP Request + Code 节点为直接 SQL 查询。
不要替用户执行任何 API 调用或凭证申请。

搭建前请准备好 OpenAI API Key 与 Google OAuth 凭证;示例 Sheets 文件需复制到自己的 Drive。

来源

Build your first AI data analyst chatbot · solomon · n8n.io · 2025-03-01

留言与反馈

试过这个方法吗?分享效果、遇到的问题或改进建议。留言审核后公开,请勿填写敏感信息。

正在加载…

    相关用例