快来看,n8n更新了!生产级AI实战手册:AI智能体的审计与追踪

qimuai 发布于 阅读:13 一手编译

快来看,n8n更新了!生产级AI实战手册:AI智能体的审计与追踪

内容来源:https://blog.n8n.io/production-ai-playbook-audit-trace-for-ai-agents/

内容总结:

AI智能体审计与追踪:从“无法解释”到“有据可查”

当AI工作流开始自主做出决策,一个棘手的问题随之而来:一个月前那笔本不该批准的退款,究竟是怎么被放行的?提示词改过两次、订单记录已变、没有任何运行记录留存——今天的工作流无法解释它上个月做出的决定。这就是所谓的“审计缺口”。每个让AI工作流自主行动的团队,在真实请求涌入后都会遇到它。无法重建的决策,最终只能靠记忆去辩护。

审计轨迹通过保留每次决策背后的证据来填补这一缺口,包括原始输入、工作流版本以及任何人工审批记录。追踪则将一次运行跨越多个工作流和服务的各个步骤连接起来,记录其耗时与状态。二者结合,才能回答财务团队的那个问题。

在n8n Cloud中,可以从查看单次已保存的执行记录入手:它展示了每个节点接收和返回的内容。在退款工作流中,这意味着你可以看到订单查询返回了什么、智能体又对客户说了什么。将两者对比,即便运行报告成功,也能发现数据并不支持的回复。文章通过“静默失败取证”练习,让读者对比完整记录与两条不可用记录,再启用校验将缺失数据的案例转交人工审核。

仅有执行记录还不够——首先得能找到它。自定义执行数据允许为每次运行附加标签,例如订单ID和最终决策,方便团队按既有搜索习惯检索。练习二展示了如何将结构化决策记录为自定义数据,并利用执行列表中的高亮数据筛选功能快速定位。

追踪则填补了执行记录的另一处空白:它看不到子工作流内部、HTTP请求节点所达服务以及请求发起系统中发生了什么。n8n会为工作流和每个节点生成跨度(span),包含时间、状态和父子关系,并发送至任何OpenTelemetry收集器。携带追踪上下文的请求会加入调用方的追踪,n8n发出的调用也会继续传递该上下文,因此一条追踪可以跟随退款请求从客户门户出发,穿过工作流及其子工作流,直至支付服务。追踪数据存放在n8n之外,按收集器自身的保留和访问规则管理,可按执行ID或追踪ID跨所有工作流搜索,且在执行记录被清理后依然存在。需要查看负载时用执行记录,需要了解时间花在哪里、哪一步失败、运行如何与工作流之外的系统连接时,则用追踪。需注意,追踪功能目前处于预览阶段,官方文档建议不要在生产工作流中依赖它。

文章随后通过三个练习逐步深入:第一个追踪练习使用Docker、cloudflared和Jaeger搭建本地收集器,验证工作流跨度与六个节点跨度,并观察失败节点上的异常信息;第二个练习聚焦AI智能体,对比计算器结果、有效订单查询和空查询在执行日志与追踪中的表现,说明当查询工具找不到数据时,应返回“未找到订单”这类明确信息,而非空字符串;第三个练习演示跨服务追踪与人工审批,通过traceparent请求头让整次运行加入调用方的追踪,并验证审批恢复后新追踪会链接回此前的跨度。

除执行与追踪外,审计事件记录的是人对工作流做了什么,例如创建、更新、发布、登录成功与失败、凭据变更等。Cloud Enterprise的日志流功能可将选定事件发送至syslog服务器、Webhook或Sentry。AI节点事件则覆盖工具调用、模型响应和模型错误。此外,版本历史可证明工作流本身是否发生过变化:Starter保留最近24小时,Pro保留五天,Enterprise保留完整历史;Pro和Enterprise还支持不会被自动清理的命名版本,建议每次工作流上线时命名一个版本,以便说明某一天运行的是哪份定义。

在保留策略上,文章建议根据调查可能需要追溯的时间范围来选择。执行数据保留记录的负载,追踪连接跨服务工作流活动,审计事件记录选定的变更,三者的保留期与访问控制应保持一致。降低追踪采样率虽可减少存储量,但会导致部分执行没有对应追踪;n8n按追踪ID采样,要么完整保留一条追踪,要么整体丢弃。

生产环境最佳实践包括:在智能体使用查询结果前校验必填字段,并记录工作流选定的结构化决策;根据套餐确认执行保留期限(Starter最多2500次执行保留7天,Pro最多25000次保留30天,Enterprise最多50000次且无时间限制),在记录过期前保存所需执行及其工作流版本和外部配置,并在追踪收集器中核实保留情况;保护n8n和收集器中保存的提示词、工具结果和错误详情,审批记录应标明经过身份认证的审核人。

文章最后给出实用提示:每次发送新请求前重新选择“执行工作流”;Cloud需要可访问的收集器URL,基础URL只填一次,追踪路径保留/v1/traces;等待后恢复的运行需按执行ID搜索,因为恢复后的跨度可能属于另一条追踪。该文属于探讨构建可靠AI系统策略的系列文章,下一篇将聚焦发布与扩展,涵盖部署选项、访问控制、环境和扩展行为。

中文翻译:

本文是系列文章的一部分,该系列探讨构建可靠AI系统的经过验证的策略和实用示例。如果您是n8n新手,请从简介开始。

为什么审计和追踪对AI智能体很重要

您的退款智能体已经上线一个月了。它读取每一条客户消息,查询订单,并自行批准小额退款。然后财务团队标记了一笔本不该发出的49.99美元退款,并询问智能体为什么批准了它。您打开工作流想查明原因,但提示词自那以后已被编辑过两次,订单记录已经变更,而且没有人记录是哪次运行做出了那个决定。现实情况是,您今天面前的工作流无法解释它上个月做出的决定。

这就是所谓的审计缺口。每一个让AI工作流自主行动的团队,在真实请求开始涌入后都会遇到这个问题。一个您无法重建的决定,最终只能凭记忆来辩护。审计追踪通过保留每个决定背后的证据来弥合这个缺口,包括原始输入、工作流版本以及任何人工审批。追踪将一次运行的各个步骤跨工作流和服务连接起来,并记录它们的时间和状态。两者结合起来,为您提供了回答财务团队问题的记录。

下面的练习在n8n Cloud中逐步建立这些记录,从一次保存的执行开始,然后添加决策标签和追踪,以跟踪工具调用和人工审批。

阅读一次执行记录

当您质疑某个决定时,从保存的执行记录开始。这是n8n对单次运行的记录,它显示每个节点接收和返回了什么。在退款工作流中,这意味着您可以看到订单查询返回了什么,以及智能体告诉了客户什么。对比两者可以揭示数据不支持的回复,即使运行报告成功。

练习1:静默故障取证

将此检查应用于一个支持智能体,该智能体根据模拟订单查询生成退款回复。对比一条完整记录和两条不可用记录,然后启用验证,将缺失数据的案例路由到人工审核。

  1. 使用下方下载链接导入练习1模板。在第8步之前保持“验证查询”禁用。

  2. 在工作流的三点菜单中,选择“设置”,将“保存手动执行”设为“保存”,然后点击“保存”。对每个练习工作流都使用此设置。

  3. 将您的凭据连接到OpenRouter - Support。模板使用OpenRouter和openai/gpt-4.1-mini;您可以将聊天模型子节点替换为其他支持的提供商。

  4. 打开Webhook - Support Request,将下面的YOUR_WEBHOOK_TEST_URL替换为其测试URL。返回画布,选择“执行工作流”,等待出现“等待触发事件”后再发送:
    Bash
    curl -X POST "YOUR_WEBHOOK_TEST_URL" \ -H "Content-Type: application/json" \ -d '{"orderId":"ORD-1001","message":"Charged twice, refund the duplicate."}'

  5. 在“执行”中,打开最新一次运行。“订单查询”应显示一笔49.99美元的订单,且lookupComplete: true。打开“退款支持智能体”,选择“日志”,然后打开OpenRouter - Support,对比解析后的提示词和回复。

  6. 返回编辑器,再次选择“执行工作流”,并发送下面的请求。在其保存的运行中,预期“订单查询”中orders: []且lookupComplete: false:
    Bash
    curl -X POST "YOUR_WEBHOOK_TEST_URL" \ -H "Content-Type: application/json" \ -d '{"orderId":"ORD-9999","message":"Charged twice, refund the duplicate."}'

  7. 返回编辑器,再次选择“执行工作流”,并发送此请求。在其保存的运行中,“订单查询”应显示一笔金额和币种为null的订单,且lookupComplete: false:
    Bash
    curl -X POST "YOUR_WEBHOOK_TEST_URL" \ -H "Content-Type: application/json" \ -d '{"orderId":"ORD-1004","message":"Charged twice, refund the duplicate."}'
    预期每个请求返回HTTP 200、answeredBy: "agent",并成功保存执行记录。回复措辞会有所不同;智能体可能会为ORD-9999询问详细信息,或为ORD-1004承诺退款,尽管金额缺失。将每条回复与保存的查询和模型日志进行对比,判断其是否有数据支持。此演示生成回复时不处理付款。

  8. 激活“验证查询”节点并重新运行所有三个案例。两个不完整的查询应返回answeredBy: "human-review",而ORD-1001仍会到达智能体。

专业提示:每个测试URL监听器只接受一个请求。如果您收到404提示webhook未注册,请再次选择“执行工作流”并重新发送。

为审计标记执行记录

一次保存的执行记录可以解释一次运行,但首先您得找到它。自定义执行数据让您可以将订单ID和最终决定等标签附加到每次运行:
JavaScript
$execution.customData.set("caseId", "ORD-1001"); $execution.customData.set("decision", "refund_approved");
使用getAll()在执行期间读回这些值。选择您团队已经在搜索的标签,例如订单ID或工单号。写入前请验证值,因为键限制为50个字符,值限制为255个字符,每次执行限制为10个条目。

练习2:可搜索的执行记录

此模板应用一个演示退款政策,要求模型解释其决定,并将该结构化决定记录为自定义数据。

  1. 导入练习2模板。
  2. 将凭据连接到OpenRouter - Support,如练习1所述。
  3. 检查“政策决定”,这是一个编辑字段节点,从订单记录中选择结果;以及“检查标签长度”,这是一个If节点,守护255字符的限制。“标记执行”是一个执行数据节点,将案例详情保存为自定义数据。在回复之后,“记录决定”以同样的方式保存最终结果,而“构建回复”将其返回。
  4. 复制Webhook测试URL,选择“执行工作流”,并发送:
    Bash
    curl -X POST "YOUR_WEBHOOK_TEST_URL" \ -H "Content-Type: application/json" \ -d '{"orderId":"ORD-1001","customerTier":"gold","message":"Please refund this order."}'
  5. 用ORD-1002和ORD-9999重复,每次重新启动监听器。三个决定应分别为refund_approved、refund_declined和needs_human_review。在“记录决定”中确认它们。
  6. 在Cloud Pro或Enterprise上,您可以选择性地打开执行列表中的漏斗筛选器,使用“高亮数据”(保存的自定义数据的当前名称)。输入decision作为键,refund_approved作为值,并勾选“精确匹配”。此筛选器不包含在Starter中。
  7. 发送一个超过255个字符的customerTier。“检查标签长度”应将运行路由到“拒绝超大标签”,这是一个“停止并报错”节点,在任何标签写入之前执行。

使用OpenTelemetry进行追踪

保存的执行记录显示每个节点在一次工作流运行中接收和产生了什么。它不显示运行所调用的子工作流中发生了什么、其HTTP Request节点所到达的服务内部发生了什么,或者最初发送请求的系统发生了什么。追踪填补了这个空白。n8n为工作流和每个节点发出一个跨度,包含时间、状态和父子关系,并将它们发送到任何OpenTelemetry收集器。携带来自另一服务的追踪上下文到达的请求会加入该服务的追踪,而n8n发出的调用会将上下文继续传递下去,因此一个追踪可以跟随一笔退款从客户门户出发,经过工作流及其子工作流,到达支付服务。

追踪也存在于n8n之外。收集器按照自己的保留和访问规则保存它们;您可以按执行ID或追踪ID跨所有工作流搜索它们,而且它们在执行记录被清理后仍然保留。当您需要载荷时使用执行记录。当您需要查看时间花在哪里、哪个步骤失败以及运行如何连接到工作流之外的系统时,使用追踪。

追踪功能处于预览阶段。n8n的文档建议不要在生产工作流中依赖它。

一个workflow.execute跨度记录工作流版本、执行ID、模式和状态。启用节点跨度后,node.execute跨度会添加每个已执行节点的名称、类型和条目计数。失败可能包含异常消息和堆栈跟踪。

专业提示:阅读条目计数时要谨慎。一个条目可以包含一个空数组,而AI子节点在成功调用后可能报告零个条目。当您需要查看实际载荷时,请打开保存的执行记录。

实例所有者和管理员在“设置 > OpenTelemetry”中配置追踪。下面的页面显示了输入隧道URL作为OTLP端点并启用追踪的情况。

在开始练习3之前,请在您的计算机上设置一个本地追踪收集器。练习4和练习5会复用它,因此请保持运行直到完成所有三个练习。您需要三个工具。Docker Desktop运行Jaeger收集器,cloudflared命令行工具为n8n Cloud提供到该收集器的临时HTTPS地址,curl从您的终端发送测试请求。

从Docker文档安装Docker Desktop,从Cloudflare Tunnel下载页面安装cloudflared,或在macOS上使用Homebrew通过brew install cloudflared安装。大多数系统包含curl;否则,请参阅curl下载页面。Jaeger入门指南涵盖了收集器,n8n OpenTelemetry文档解释了每项追踪设置。Jaeger将追踪保存在内存中,因此停止它后追踪会消失。

练习3:您的第一个追踪

此模板将收费金额转换为分,并模拟成功或失败,不涉及模型或支付提供商。

  1. 在Docker运行且cloudflared已安装的情况下,将以下内容保存为docker-compose.yml并运行docker compose up -d:
    YAML
    services: jaeger: image: jaegertracing/jaeger:2.20.0 ports: - "127.0.0.1:16686:16686" - "127.0.0.1:4318:4318"
  2. 在另一个终端中运行cloudflared tunnel --url http://localhost:4318并保持运行。它打印的HTTPS URL让n8n Cloud能够到达您的本地收集器。
  3. 在Cloud的“设置 > OpenTelemetry”中,输入该URL作为OTLP端点,保持追踪路径为/v1/traces。将追踪采样率设为1,保持“包含节点跨度”和“注入出站traceparent”开启,并关闭“仅跟踪已发布的工作流”。启用追踪,保存任何待处理的更改,然后选择“发送测试追踪”。
  4. 在http://localhost:16686打开Jaeger,选择配置的服务名称(默认为n8n),找到测试追踪。
  5. 导入练习3并复制其Webhook测试URL。在画布上选择“执行工作流”,使用工作流下方的按钮而不是节点自身的“执行”步骤,以便每个节点都运行。然后发送:
    Bash
    curl -X POST "YOUR_WEBHOOK_TEST_URL" \ -H "Content-Type: application/json" \ -d '{"requestId":"REQ-3001","amount":49.99}'
  6. 在n8n中,打开“执行”并记下新运行旁边显示的ID。在Jaeger的“标签”字段中,输入n8n.execution.id=YOUR_EXECUTION_ID及该ID,然后选择“查找追踪”。预期看到一个工作流跨度,包含六个节点跨度,分别对应Webhook - Charge Request、Validate Amount、Normalize Request、Charge Card、Capture Charge和Respond。如果只出现webhook跨度,说明运行是从节点而非画布启动的;在画布上选择“执行工作流”并重新发送。在保存的执行记录中,“规范化请求”应返回amountCents: 4999。
  7. 重启监听器并发送{"requestId":"REQ-3002","amount":49.99,"trigger_failure":true}。“Charge Card”是一个If节点,应将请求路由到“拒绝收费”,这是一个“停止并报错”节点,会以card_declined失败,使“捕获收费”和“响应”不被执行。检查“拒绝收费”跨度和工作流跨度上的异常。

在练习5期间保持Jaeger和隧道运行。此演示使用临时追踪存储;在停止隧道并运行docker compose down之前,请恢复您的Cloud追踪设置。

专业提示:在n8n中检查执行状态,而不是信任curl响应。在工作流最终响应节点之前的失败可能会以空HTTP 200或HTTP 500“工作流错误”消息返回,具体取决于n8n版本以及您使用的是测试URL还是生产URL。

追踪AI智能体

当智能体给出错误答案时,原因可能是某个工具调用返回了错误或空数据。AI Agent节点将其模型和工具活动记录为标准节点跨度,因此追踪显示哪个工具运行了、以什么顺序运行以及耗时多久。工具参数和结果在保存的执行日志中。当查询工具找不到任何内容时,让它返回一条清晰的消息,例如“未找到订单”,因为空字符串无法给智能体提供任何可报告的内容。

练习4:找到失败的工具有

在本练习中,您将跨执行日志和追踪对比一个计算器结果、一个有效订单查询和一个空查询。

  1. 导入练习4,将凭据连接到OpenRouter - Agent,并保持练习3中的追踪配置。如果更换模型,请选择支持工具调用的模型。
  2. 复制Webhook测试URL,选择“执行工作流”,并发送:
    Bash
    curl -X POST "YOUR_WEBHOOK_TEST_URL" \ -H "Content-Type: application/json" \ -d '{"query":"What is 47 times 89?"}'
  3. 打开执行记录,检查智能体日志中的“计算器工具”。其结果应为4183;检查模型提供的表达式。在追踪中找到对应的节点跨度。
  4. 重启监听器并发送{"query":"How much was order ORD-1001? Use the order lookup."}。确认工具返回包含49.99 USD的记录。
  5. 用{"query":"How much was order ORD-8888? Tell the customer the amount."}重复。“订单查询工具”返回空字符串,但其执行和跨度仍可能报告成功。检查智能体的回复是否承认了缺失的订单。
  6. 将两个查询跨度与其日志进行对比。使用记录的工具结果来区分有效订单和空查询。
    下载练习4工作流模板

跨服务连接追踪

AI工作流通常位于其他系统之间。请求从客户门户到达,工作流在回答之前调用政策或支付服务。当传入请求携带有效的traceparent头时,n8n使用其追踪ID和父跨度ID,因此工作流加入调用方的追踪。启用出站注入后,HTTP Request节点会以新的跨度ID转发相同的追踪ID,而被检测的下游服务可以在该追踪中记录自己的工作。

子工作流跨度归属于父工作流跨度之下。在等待之后,恢复的工作流可以启动一个新的追踪,并链接回较早的跨度。按n8n.execution.id搜索可以找到同一次执行的两个部分。

练习5:追踪一次审批

此工作流丰富一个请求,生成一个提案,并等待提交的批准或拒绝。它记录决定而不处理付款。

  1. 首先导入、保存并发布练习5的丰富子工作流。然后导入练习5的父工作流,并在“丰富请求子工作流”中明确选择那个已导入的子工作流。两个下载文件也链接在本练习末尾。
  2. 将凭据连接到OpenRouter - Approval并保持追踪启用。复制父工作流的Webhook测试URL并选择“执行工作流”。
  3. 发送此请求。其traceparent头提供了整个运行所加入的追踪ID,您将在第5步中查找该ID。金额以美元分为单位,因此4999代表49.99美元:
    Bash
    curl -X POST "YOUR_WEBHOOK_TEST_URL" \ -H "Content-Type: application/json" \ -H "traceparent: 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01" \ -d '{"requestId":"REQ-2001","amount":4999,"reason":"duplicate charge"}'
  4. 保存返回的executionId和完整的resumeUrl,包括任何查询字符串。等待执行状态变为“等待中”。
  5. 在Jaeger中,将4bf92f3577b34da6a3ce929d0e0e4736(您头中的追踪ID)粘贴到“按追踪ID查找”框中。父工作流跨度应位于您头中的跨度之下,丰富子工作流跨度嵌套在其下。在n8n中,打开等待中执行里的“政策服务调用”。其输出显示一个traceparent,具有相同的追踪ID和不同的跨度ID,这确认n8n转发了追踪上下文。回显服务对它不做其他任何事情。
  6. 将审批提交到恢复URL而不是webhook测试URL。从第3步响应中复制完整的resumeUrl值,包括签名查询字符串,并将其粘贴到下面YOUR_RESUME_URL的位置。当您在等待中的执行里打开“等待人工审批”时,也会出现相同的URL。请将其视为机密,因为任何持有它的人都可以批准请求:
    Bash
    curl -X POST "YOUR_RESUME_URL" \ -H "Content-Type: application/json" \ -d '{"approved":true,"approver":"Demo reviewer"}'
  7. 在“记录审批”中确认approved: true和submittedApprover: "Demo reviewer"。在Jaeger中,在“标签”中搜索n8n.execution.id=YOUR_EXECUTION_ID及本次运行的ID。会出现两个追踪:原始追踪和恢复部分的新追踪,恢复的工作流跨度携带一个指回较早跨度的链接。
  8. 启动一次单独运行,并向其新的恢复URL提交approved: false。确认记录的决定为“拒绝”。缺失或非布尔的approved值,或缺失approver,应导致验证失败。

专业提示:练习5中的approver字段是请求发送的任何内容。在生产环境中,应从经过身份验证的登录中获取审核者身份,并限制对恢复端点的访问。当您测试超出此固定示例的范围时,请为每次运行使用新的追踪ID。

流式传输审计事件

执行记录和追踪记录工作流做了什么。审计事件记录人们对它做了什么,例如更改工作流、发布工作流或登录。Cloud Enterprise增加了“设置 > 日志流式传输”,您可以在其中将选定的事件发送到syslog服务器、webhook或Sentry。审计事件涵盖工作流更改(如创建、更新、发布和取消发布)、用户登录成功和失败以及凭据更改。AI节点事件涵盖工具调用、模型响应和模型错误。

在“设置 > 日志流式传输 > 事件”下选择您需要的事件,检查其载荷中的敏感数据,并在目标端验证投递和保留。每个目标都可以从审计事件中剥离敏感的载荷数据。日志流式传输在事件发生时记录它们,而保存的执行记录保存节点数据,因此当您需要完整的节点载荷时请保留执行数据。

证明发生了什么变化

如果智能体上个月的行为不同,工作流本身可能已经改变。从工作流的三点菜单中打开“版本历史”以检查或下载较早的定义。每次保存或恢复工作流时,n8n都会创建一个版本。工作流设置的更改不会创建版本。

Starter包含最近24小时的工作流历史,Pro包含五天,Enterprise包含完整历史。Pro和Enterprise还支持命名版本,n8n不会自动清理这些版本。每次工作流上线时命名一个版本,以便您可以展示在给定日期运行的是哪个定义,并导出您需要保留更长时间的任何版本。

Cloud Enterprise提供两个额外的控制。启用环境后,工作流差异显示实例与其连接的Git仓库之间的更改。工作流审查让审核者在n8n发布之前批准已保存的版本。它们从n8n 2.37.0起可用,实例管理员在“设置 > 安全与策略”中开启它们,且它们处于预览阶段,因此请在生产使用前进行评估。审查涵盖工作流的节点和连接。工作流设置、凭据、变量、数据表和子工作流不在审查范围内,您一编辑它们就会更改已发布的工作流。启用审查后,当没有打开的审查时,您仍然可以直接发布。

设计决策

您可能对保留策略有疑问。我们建议根据调查可能需要追溯到多久来选择保留期限。执行数据保留记录的载荷,追踪跨服务连接工作流活动,审计事件记录选定的更改。对齐它们的保留和访问控制。

降低追踪采样率会减少存储量,但会使某些执行不被表示。n8n按追踪ID采样,因此它要么完整保留一个追踪,要么完全丢弃它。在这些练习中保持完整采样,然后决定调查是否能容忍缺失的追踪。

追踪有助于调查单次运行。使用评估来评估答案质量,如“评估与监控”中所述。

生产最佳实践

行动前验证:在智能体使用查询之前检查必填字段,并记录您的工作流选择的结构化决定。

验证保留的证据:Cloud执行保留取决于您的计划。Starter最多保留2,500次执行7天,Pro最多保留25,000次30天,Enterprise最多保留50,000次且无时间限制;一旦达到任一限制,n8n会删除最旧的运行。在工作流设置中,选择保存哪些成功和失败的生产执行。在记录过期之前保留所需的执行,包括其工作流版本和外部配置,并在您的追踪收集器中验证保留情况。

控制访问:保护n8n和收集器中保存的提示词、工具结果和错误详情。审批记录应标识经过身份验证的审核者。

提示与技巧

重启监听器:在每次新请求之前选择“执行工作流”,并在测试追踪时保持“仅跟踪已发布的工作流”关闭。

检查端点:Cloud需要一个可到达的收集器URL。输入一次基础URL,并在追踪路径中保留/v1/traces。

查找恢复的运行:等待后按执行ID搜索,因为恢复的跨度可能属于另一个追踪。

下一步

本文是系列文章的一部分,该系列探讨构建可靠AI系统的经过验证的策略和实用示例。在此处查看“生产AI实践手册”中已有哪些主题,或通过RSS、LinkedIn或X第一时间了解新主题的添加。

系列中的下一篇是“发布与扩展”,涵盖部署选项、访问控制、环境和扩展行为。

英文来源:

This post is part of a series that explores proven strategies and practical examples for building reliable AI systems. If you are new to n8n, start with the introduction.
Why Audit and Trace Matter for AI Agents
Your refund agent has been live for a month. It reads each customer message, looks up the order, and approves small refunds on its own. Then the finance team flags a $49.99 refund that should never have gone out and asks why the agent approved it. You open the workflow to find out, but the prompt has been edited twice since then, the order record has changed, and nobody recorded which run made that decision. The reality is that the workflow in front of you today cannot explain a decision it made last month.
This is what's called the audit gap. Every team that lets an AI workflow act on its own runs into it once real requests start coming in. A decision you cannot reconstruct is a decision you will end up defending from memory. An audit trail closes the gap by keeping the evidence behind each decision, including the original inputs, the workflow version, and any human approval. Tracing connects the steps of a run across workflows and services and records their timing and status. Together, they give you the records to answer the finance team's question.
The exercises below build up that record in n8n Cloud, starting with one saved execution, then adding decision tags and traces to follow tool calls and a human approval.
Reading One Execution
When you question a decision, start with the saved execution. It is n8n's record of a single run, and it shows what each node received and returned. In a refund workflow, that means you can see what the order lookup returned and what the agent told the customer. Comparing the two can reveal a reply the data does not support, even when the run reports success.
Exercise 1: Silent Failure Forensics
Apply this check to a support agent that generates refund replies from a simulated order lookup. Compare a complete record with two unusable records, then enable validation to route the missing-data cases to human review.

  1. Import the Exercise 1 template using the download below. Leave Validate Lookup disabled until step 8.
  2. In the workflow’s three-dot menu, select Settings, set Save manual executions to Save, then click Save. Use this setting for each exercise workflow.
  3. Connect your credentials to OpenRouter - Support. The template uses OpenRouter with openai/gpt-4.1-mini
    ; you can replace the Chat Model sub-node with another supported provider.
  4. Open Webhook - Support Request and replace YOUR_WEBHOOK_TEST_URL
    below with its Test URL. Return to the canvas, select Execute workflow, and wait for Waiting for trigger event before sending:
    Bash
    curl -X POST "YOUR_WEBHOOK_TEST_URL" \ -H "Content-Type: application/json" \ -d '{"orderId":"ORD-1001","message":"Charged twice, refund the duplicate."}'
  5. In Executions, open the newest run. Order Lookup should show one order for 49.99 USD with lookupComplete: true
    . Open Refund Support Agent, select Logs, then OpenRouter - Support to compare the resolved prompt and reply.
  6. Return to Editor, select Execute workflow again, and send the request below. In its saved run, expect orders: []
    and lookupComplete: false
    in Order Lookup:
    Bash
    curl -X POST "YOUR_WEBHOOK_TEST_URL" \ -H "Content-Type: application/json" \ -d '{"orderId":"ORD-9999","message":"Charged twice, refund the duplicate."}'
  7. Return to Editor, select Execute workflow again, and send this request. In its saved run, Order Lookup should show one order with null amount and currency, and lookupComplete: false
    :
    Bash
    curl -X POST "YOUR_WEBHOOK_TEST_URL" \ -H "Content-Type: application/json" \ -d '{"orderId":"ORD-1004","message":"Charged twice, refund the duplicate."}'
    Expect HTTP 200, answeredBy: "agent"
    , and a successfully saved execution for each request. Reply wording varies; the agent may ask for details for ORD-9999
    or promise a refund for ORD-1004
    despite the missing amount. Compare each reply with the saved lookup and model logs to judge whether it is supported. This demo generates replies without processing payments.
  8. Activate the Validate Lookup node and rerun all three cases. The two incomplete lookups should return answeredBy: "human-review"
    , while ORD-1001
    still reaches the agent.
    Pro tip: Each Test URL listener accepts one request. If you get a 404 saying the webhook is not registered, select Execute workflow again and resend.
    Tagging Executions for Audit
    A saved execution explains one run, but first you have to find it. Custom executions data lets you attach labels such as the order ID and the final decision to each run:
    JavaScript
    $execution.customData.set("caseId", "ORD-1001"); $execution.customData.set("decision", "refund_approved");
    Use getAll()
    to read the values back during the execution. Pick labels your team already searches by, such as order IDs or ticket numbers. Validate values before writing them, since keys are limited to 50 characters, values to 255, and each execution to 10 entries.
    Exercise 2: Searchable Executions
    This template applies a demo refund policy, asks the model to explain its decision, and records that structured decision as custom data.
  9. Import the Exercise 2 template.
  10. Connect credentials to OpenRouter - Support, as in Exercise 1.
  11. Inspect Policy Decision, an Edit Fields node that selects the outcome from the order record, and Check Tag Length, an If node that guards the 255-character limit. Tag Execution is an Execution Data node that saves the case details as custom data. After the reply, Record Decision saves the final outcome the same way, and Build Reply returns it.
  12. Copy the Webhook Test URL, select Execute workflow, and send:
    Bash
    curl -X POST "YOUR_WEBHOOK_TEST_URL" \ -H "Content-Type: application/json" \ -d '{"orderId":"ORD-1001","customerTier":"gold","message":"Please refund this order."}'
  13. Repeat with ORD-1002
    and ORD-9999
    , restarting the listener each time. The three decisions should be refund_approved
    , refund_declined
    , and needs_human_review
    . Confirm them in Record Decision.
  14. On Cloud Pro or Enterprise, optionally open the funnel filter in the executions list and use Highlighted data, the current name for saved custom data. Enter decision
    as the key and refund_approved
    as the value, and tick Exact match. This filter is not included on Starter.
  15. Send a customerTier
    longer than 255 characters. Check Tag Length should route the run to Reject Oversized Tag, a Stop and Error node, before any tag is written.
    Tracing with OpenTelemetry
    The saved execution shows what each node received and produced inside one workflow run. It doesn't show what happened in the sub-workflow the run called, inside the service its HTTP Request node reached, or in the system that sent the request in the first place. Tracing fills that gap. n8n emits a span for the workflow and each node, with timing, status, and parent-child relationships, and sends them to any OpenTelemetry collector. A request that arrives with trace context from another service joins that service's trace, and the calls n8n makes carry the context onward, so one trace can follow a refund from the customer portal, through the workflow and its sub-workflow, to the payment service.
    Traces also live outside n8n. The collector keeps them under its own retention and access rules; you can search them by execution ID or trace ID across every workflow, and they remain after the execution record is pruned. Use the execution record when you need the payloads. Use traces when you need to see where the time went, which step failed, and how the run connects to systems beyond the workflow.
    Tracing is in Preview. n8n's documentation advises against relying on it in production workflows.
    A workflow.execute
    span records the workflow version, execution ID, mode, and status. With node spans enabled, node.execute
    spans add each executed node's name, type, and item counts. Failures can include exception messages and stack traces.
    Pro tip: Read item counts with care. One item can hold an empty array, and AI sub-nodes can report zero items after a successful call. Open the saved execution when you need to see the actual payloads.
    Instance owners and admins configure tracing in Settings > OpenTelemetry. The page below shows it with a tunnel URL entered as the OTLP endpoint and tracing enabled.
    Before starting Exercise 3, set up a local trace collector on your computer. Exercises 4 and 5 reuse it, so keep it running until you finish all three. You need three tools. Docker Desktop runs the Jaeger collector, the cloudflared command-line tool gives n8n Cloud a temporary HTTPS address for that collector, and curl sends the test requests from your terminal.
    Install Docker Desktop from the Docker documentation and cloudflared from the Cloudflare Tunnel downloads page, or with Homebrew on macOS using brew install cloudflared
    . Most systems include curl; otherwise, see the curl downloads. The Jaeger getting started guide covers the collector, and the n8n OpenTelemetry documentation explains each tracing setting. Jaeger keeps traces in memory, so they disappear when you stop it.
    Exercise 3: Your First Trace
    This template converts a charge amount to cents and simulates success or failure, without a model or payment provider.
  16. With Docker running and cloudflared installed, save this as docker-compose.yml
    and run docker compose up -d
    :
    YAML
    services: jaeger: image: jaegertracing/jaeger:2.20.0 ports: - "127.0.0.1:16686:16686" - "127.0.0.1:4318:4318"
  17. Run cloudflared tunnel --url http://localhost:4318
    in another terminal and keep it running. The HTTPS URL it prints lets n8n Cloud reach your local collector.
  18. In Cloud Settings > OpenTelemetry, enter that URL as the OTLP endpoint, leaving Trace path as /v1/traces
    . Set Trace sample rate to 1, keep Include node spans and Inject outbound traceparent on, and turn Track published workflows only off. Enable tracing, save any pending changes, and select Send test trace.
  19. Open Jaeger at http://localhost:16686
    , select the configured service name (default n8n
    ), and find the test trace.
  20. Import Exercise 3 and copy its Webhook Test URL. Select Execute workflow on the canvas, using the button below the workflow rather than a node’s own Execute step, so that every node runs. Then send:
    Bash
    curl -X POST "YOUR_WEBHOOK_TEST_URL" \ -H "Content-Type: application/json" \ -d '{"requestId":"REQ-3001","amount":49.99}'
  21. In n8n, open Executions and note the ID shown next to the new run. In Jaeger’s Tags field, enter n8n.execution.id=YOUR_EXECUTION_ID
    with that ID and select Find Traces. Expect a workflow span with six node spans, one for each of Webhook - Charge Request, Validate Amount, Normalize Request, Charge Card, Capture Charge, and Respond. If only the webhook span appears, the run started from a node instead of the canvas; select Execute workflow on the canvas and resend. In the saved execution, Normalize Request should return amountCents: 4999
    .
  22. Restart the listener and send {"requestId":"REQ-3002","amount":49.99,"trigger_failure":true}
    . Charge Card, an If node, should route the request to Decline Charge, a Stop and Error node that fails with card_declined
    , leaving Capture Charge and Respond unexecuted. Inspect the exception on the Decline Charge span and on the workflow span.
    Keep Jaeger and the tunnel running through Exercise 5. This demo uses temporary trace storage; restore your Cloud tracing settings before stopping the tunnel and running docker compose down
    .
    Pro tip: Check the execution status in n8n instead of trusting the curl response. A failure before the workflow’s final response node can come back as an empty HTTP 200 or as an HTTP 500 “Error in workflow” message, depending on the n8n version and whether you used the Test URL or the production URL.
    Tracing AI Agents
    When an agent gives a wrong answer, the cause can be a tool call that returned bad or empty data. The AI Agent node records its model and tool activity as standard node spans, so the trace shows which tool ran, in what order, and how long it took. The tool arguments and results are in the saved execution logs. When a lookup tool finds nothing, have it return a clear message such as "No order found", since an empty string gives the agent nothing to report.
    Exercise 4: Find the Failing Tool
    In this exercise, you will compare a calculator result, a valid order lookup, and an empty lookup across execution logs and traces.
  23. Import Exercise 4, connect credentials to OpenRouter - Agent, and keep the tracing configuration from Exercise 3. If you change models, choose one with tool-calling support.
  24. Copy the Webhook Test URL, select Execute workflow, and send:
    Bash
    curl -X POST "YOUR_WEBHOOK_TEST_URL" \ -H "Content-Type: application/json" \ -d '{"query":"What is 47 times 89?"}'
  25. Open the execution and inspect the Calculator Tool in the agent logs. Its result should be 4183
    ; inspect the expression the model supplied. Find the corresponding node span in the trace.
  26. Restart the listener and send {"query":"How much was order ORD-1001? Use the order lookup."}
    . Confirm the tool returns a record containing 49.99 USD.
  27. Repeat with {"query":"How much was order ORD-8888? Tell the customer the amount."}
    . Order Lookup Tool returns an empty string, yet its execution and span can still report success. Check whether the agent’s reply acknowledges the missing order.
  28. Compare the two lookup spans with their logs. Use the recorded tool results to distinguish the valid order from the empty lookup.
    Download the Exercise 4 workflow templateConnecting Traces Across Services
    AI workflows usually sit between other systems. A request arrives from a customer portal, and the workflow calls a policy or payment service before it answers. When the incoming request carries a valid traceparent
    header, n8n uses its trace ID and parent span ID, so the workflow joins the caller's trace. With outbound injection enabled, an HTTP Request node forwards the same trace ID with a new span ID, and an instrumented downstream service can record its own work in that trace.
    Sub-workflow spans belong under the parent workflow span. After a wait, the resumed workflow can start a new trace with a link back to the earlier span. Search by n8n.execution.id
    to find both parts of the same execution.
    Exercise 5: Trace an Approval
    This workflow enriches a request, generates a proposal, and waits for a submitted approval or rejection. It records the decision without processing a payment.
  29. Import, save, and publish the Exercise 5 enrichment sub-workflow first. Then import the Exercise 5 parent workflow and explicitly select that imported sub-workflow in Enrich Request Sub-workflow. Both downloads are also linked at the end of this exercise.
  30. Connect credentials to OpenRouter - Approval and keep tracing enabled. Copy the parent’s Webhook Test URL and select Execute workflow.
  31. Send this request. Its traceparent
    header supplies the trace ID that the whole run joins, and you will look that ID up in step 5. The amount is in USD cents, so 4999 represents $49.99:
    Bash
    curl -X POST "YOUR_WEBHOOK_TEST_URL" \ -H "Content-Type: application/json" \ -H "traceparent: 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01" \ -d '{"requestId":"REQ-2001","amount":4999,"reason":"duplicate charge"}'
  32. Save the returned executionId
    and the complete resumeUrl
    , including any query string. Wait until the execution status is Waiting.
  33. In Jaeger, paste 4bf92f3577b34da6a3ce929d0e0e4736
    , the trace ID from your header, into the Lookup by Trace ID box. The parent workflow span should sit under the span from your header, with the enrichment sub-workflow span nested under it. In n8n, open Policy Service Call in the waiting execution. Its output shows a traceparent
    with the same trace ID and a different span ID, which confirms that n8n forwarded the trace context. The echo service does nothing else with it.
  34. Submit the approval to the resume URL rather than the webhook Test URL. Copy the complete resumeUrl
    value from the step 3 response, including the signature query string, and paste it in place of YOUR_RESUME_URL
    below. The same URL appears when you open Wait for Human Approval in the waiting execution. Treat it as a secret, since anyone holding it can approve the request:
    Bash
    curl -X POST "YOUR_RESUME_URL" \ -H "Content-Type: application/json" \ -d '{"approved":true,"approver":"Demo reviewer"}'
  35. Confirm approved: true
    and submittedApprover: "Demo reviewer"
    in Record Approval. In Jaeger, search Tags for n8n.execution.id=YOUR_EXECUTION_ID
    with this run’s ID. Two traces appear: the original one and a new one for the resumed part, and the resumed workflow span carries a link back to the earlier span.
  36. Start a separate run and submit approved: false
    to its new resume URL. Confirm the recorded decision is declined. A missing or non-boolean approved
    value, or a missing approver
    , should fail validation.
    Pro tip: The approver
    field in Exercise 5 is whatever the request sends. In production, take the reviewer’s identity from an authenticated login and restrict access to the resume endpoint. When you test beyond this fixed example, use a fresh trace ID for each run.
    Streaming Audit Events
    Executions and traces record what a workflow did. Audit events record what people did to it, such as changing a workflow, publishing it, or signing in. Cloud Enterprise adds Settings > Log Streaming, where you can send selected events to a syslog server, a webhook, or Sentry. Audit events cover workflow changes such as created, updated, published, and unpublished, user login successes and failures, and credential changes. AI node events cover tool calls, model responses, and model errors.
    Choose the events you need under Settings > Log Streaming > Events, inspect their payloads for sensitive data, and verify delivery and retention at the destination. Each destination can strip sensitive payload data from audit events. Log streaming records events as they happen, while the saved execution holds the node data, so keep execution data when you need complete node payloads.
    Proving What Changed
    If an agent behaved differently last month, the workflow itself may have changed. Open Version history from the workflow's three-dot menu to inspect or download earlier definitions. n8n creates a version each time you save or restore a workflow. Changes to workflow settings do not create a version.
    Starter includes the last 24 hours of workflow history, Pro includes five days, and Enterprise includes full history. Pro and Enterprise also support named versions, which n8n does not prune automatically. Name a version each time a workflow goes live so you can show which definition was running on a given date, and export any versions you need to keep longer.
    Cloud Enterprise offers two additional controls. With environments enabled, workflow diffs show changes between the instance and its connected Git repository. Workflow reviews let a reviewer approve a saved version before n8n publishes it. They are available from n8n 2.37.0, an instance admin turns them on in Settings > Security & policies, and they are in Preview, so evaluate them before production use. A review covers the workflow's nodes and connections. Workflow settings, credentials, variables, data tables, and sub-workflows sit outside the review and change the published workflow as soon as you edit them. Enabling reviews still lets you publish directly when no review is open.
    Design Decisions
    You might have questions about your retention. We suggest choosing retention based on how far back an investigation may need to go. Execution data preserves recorded payloads, traces connect workflow activity across services, and audit events record selected changes. Align their retention and access controls.
    Lower trace sampling reduces stored volume but leaves some executions unrepresented. n8n samples by trace ID, so it keeps a trace in full or drops it entirely. Keep full sampling for these exercises, then decide whether an investigation could tolerate missing traces.
    Traces help investigate individual runs. Use evaluations to assess answer quality, as covered in Evaluation and Monitoring.
    Production Best Practices
    Validate before acting: Check required fields before an agent uses a lookup, and record the structured decision your workflow selected.
    Verify retained evidence: Cloud execution retention depends on your plan. Starter keeps up to 2,500 executions for 7 days, Pro keeps up to 25,000 for 30 days, and Enterprise keeps up to 50,000 with no time limit; n8n removes the oldest runs once it reaches either limit. In workflow Settings, choose which successful and failed production executions to save. Preserve required executions, including their workflow versions and external configuration, before records expire, and verify retention in your trace collector.
    Control access: Protect saved prompts, tool results, and error details in both n8n and the collector. Approval records should identify an authenticated reviewer.
    Tips and Tricks
    Restart the listener: Select Execute workflow before every new request, and keep Track published workflows only off while testing traces.
    Check the endpoint: Cloud needs a reachable collector URL. Enter the base URL once and keep /v1/traces in the Trace path.
    Find resumed runs: Search by execution ID after a wait, since the resumed span may belong to another trace.
    What's Next
    This post is part of a series that explores proven strategies and practical examples for building reliable AI systems. Find out what topics are already available in the Production AI Playbook here, or be the first to know when new topics are added via RSS, LinkedIn or X.
    Next in the series is Publish & Scale, covering deployment options, access controls, environments, and scaling behavior.

n8n

文章目录


    扫描二维码,在手机上阅读