mcpField
F
fastgpt-workflow-generator

fastgpt-workflow-generator

github.com/yyh211Agent 工作流28457 次安装24 周前更新
代码仓库

关于 fastgpt-workflow-generator

将自然语言需求转为 FastGPT 工作流 JSON,也可修改或验证已有工作流。它通过内置模板匹配,并检查结构、连接和逻辑完整性。

主要功能

  1. 01分析工作流需求
  2. 02匹配内置模板
  3. 03生成工作流 JSON
  4. 04验证结构与节点连接
  5. 05修改现有工作流
  6. 06自动排列节点

适用场景

  1. 01根据规格创建工作流
  2. 02按用途调整模板
  3. 03增删工作流节点
  4. 04检查并修复工作流 JSON

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/yyh211/claude-meta-skill --skill fastgpt-workflow-generator

安装后在 Claude Code 中输入/fastgpt-workflow-generator确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

LESSONS_LEARNED.md
references/
json_structure_spec.md
node_types_reference.md
template_matching.md
validation_rules.md
scripts/
validate_workflow.js
templates/
AI金融日报.json
README.md
文档翻译助手.json
简历筛选助手_飞书.json
销售陪练大师.json

详细介绍

FastGPT 工作流生成器

根据自然语言需求自动生成可用于生产环境的 FastGPT 工作流 JSON

何时使用此技能

在需要以下操作时使用此技能:

  • 从头创建新工作流:用户要求“为 X 用途创建一个 FastGPT 工作流”
  • 基于模板生成:用户想要构建与现有模式相似的工作流(文档处理、AI 聊天、数据分析、多 Agent 系统)
  • 修改现有工作流:用户需要在现有工作流 JSON 中添加、删除或更新节点
  • 验证工作流 JSON:用户有一个需要验证或修复的工作流 JSON
  • 设计多 Agent 系统:用户提到并行处理、Agent 协作或工作流编排
  • 自动化工作流创建:用户提供需求文档,并需要可执行的 JSON
  • 将需求转换为 JSON:用户有规格说明,并希望生成兼容 FastGPT 的工作流

触发关键词:FastGPT、工作流、JSON、多 Agent、工作流、模板匹配、工作流自动化、节点配置、工作流验证


核心工作流

此技能采用 5 个阶段的流程来生成可用于生产环境的工作流 JSON:

阶段 1:需求分析

目标:从自然语言输入中提取结构化需求

流程:

  1. 识别请求类型:

    • 从头创建
    • 基于模板创建
    • 修改现有工作流
    • 验证/修复现有 JSON
  2. 使用 AI 语义分析提取关键信息:

    {
      "purpose": "Workflow objective (e.g., 'Travel planning assistance')",
      "domain": "Application domain (travel/event/document/data/general)",
      "complexity": "simple | medium | complex",
      "features": ["aiChat", "knowledgeBase", "httpRequest", "parallel"],
      "inputs": ["userChatInput", "city", "date"],
      "outputs": ["Complete plan", "Recommendations"],
      "externalIntegrations": ["Weather API", "Feishu API"],
      "specialRequirements": ["Multi-agent", "Real-time data"]
    }
    
  3. 完整性检查:如果信息不足,通过对话进行澄清

输出:结构化需求对象


阶段 2:模板匹配

目标:找到最相似的内置模板

内置模板(存储在 templates/ 目录中):

  • templates/文档翻译助手.json - 简单工作流(文档处理)
  • templates/销售陪练大师.json - 中等复杂度(对话式 AI)
  • templates/简历筛选助手_飞书.json - 复杂工作流(数据处理 + 外部集成)
  • templates/AI金融日报.json - 定时触发 + 多 Agent(新闻聚合)

匹配策略:

步骤 1:粗筛(基于元数据)

Calculate similarity scores:
- Domain match: travel vs travel = 1.0, travel vs event = 0.3
- Complexity match: simple vs simple = 1.0, simple vs complex = 0.3
- Feature overlap: Jaccard similarity of feature sets
- Node count similarity: 1 - |count1 - count2| / max(count1, count2)

Combined score = 0.3 * domain + 0.2 * complexity + 0.3 * features + 0.2 * nodeCount

Select Top 3 candidate templates

步骤 2:细筛(语义相似度)

For Top 3 candidates:
1. Analyze user requirements vs template characteristics
2. Evaluate workflow structure similarity
3. Calculate comprehensive score

Final score = 0.3 * domain + 0.2 * complexity + 0.3 * features + 0.2 * semantic

步骤 3:选择策略

- Highest score < 0.5: Start from blank template
- Highest score 0.5-0.7: Use template as reference, major modifications
- Highest score > 0.7: Use template as base, minor adjustments

输出:

  • 最匹配的模板 JSON 对象
  • 匹配分析报告
  • 修改建议列表

阶段 3:JSON 生成

场景 1:基于模板生成

1. Copy template structure

2. Modify nodes
   - Keep: structurally similar nodes (workflowStart, userGuide)
   - Modify: nodes requiring prompt/parameter adjustments
   - Delete: unnecessary nodes
   - Add: new requirement nodes

3. Regenerate NodeId
   function generateNodeId(nodeType, nodeName, existingIds) {
     // Fixed ID mapping
     if (nodeType === 'workflowStart') return 'workflowStart';
     if (nodeType === 'userGuide' || nodeType === 'systemConfig') return 'userGuide';

     // Generate semantic ID (camelCase)
     const baseName = nodeName.replace(/[\s\u4e00-\u9fa5]+/g, '');
     let nodeId = baseName ? `${baseName}Node` : `${nodeType}Node`;

     // Ensure uniqueness
     let counter = 1;
     while (existingIds.has(nodeId)) {
       nodeId = `${baseName}Node_${counter}`;
       counter++;
     }

     return nodeId;
   }

4. Update references
   - Traverse all inputs, replace old nodeId with new nodeId
   - Update edges' source/target
   - Handle two reference formats:
     - Array: ["nodeId", "key"]
     - Template: {{$nodeId.key$}}  (Note: double braces with single $)

5. Auto-layout positions (hierarchical layout algorithm)
   function autoLayout(nodes, edges) {
     // Topological sort to determine layers
     const layers = topologicalLayering(nodes, edges);

     // Calculate positions for each layer
     const LAYER_GAP_X = 350;
     const NODE_GAP_Y = 150;

     layers.forEach((layer, layerIndex) => {
       const x = -200 + layerIndex * LAYER_GAP_X;
       const totalHeight = (layer.length - 1) * NODE_GAP_Y;
       const startY = -totalHeight / 2;

       layer.forEach((nodeId, nodeIndex) => {
         positions[nodeId] = {
           x: x,
           y: startY + nodeIndex * NODE_GAP_Y
         };
       });
     });

     // Fixed position for special nodes
     positions['userGuide'] = { x: -600, y: -250 };
   }

6. Update configuration
   - Modify chatConfig.welcomeText
   - Update chatConfig.variables

场景 2:从头创建

1. Determine node list
   - Required: workflowStart, userGuide
   - Add based on features: chatNode, datasetSearchNode, httpRequest468, etc.
   - Required: answerNode (output node)

2. Generate nodes and connections
   - Use standard node templates
   - Fill required fields
   - Customize inputs/outputs based on requirements

3. Calculate positions and generate configuration

输出:完整的 FastGPT 工作流 JSON


阶段 4:验证

级别 1:JSON 格式验证

✅ JSON is parseable
✅ Top level contains nodes, edges, chatConfig
✅ Each node contains: nodeId, name, flowNodeType, position, inputs, outputs
✅ flowNodeType is in valid type list (40+ types)
✅ position contains x, y numeric coordinates

级别 2:节点连接验证

✅ edges' source/target nodes exist
✅ sourceHandle/targetHandle format correct (nodeId-source-right, nodeId-target-left)
✅ Node input references' nodes and output keys exist
✅ Reference types match (string → string)
✅ Template references {{$nodeId.key$}} nodes and keys exist
✅ No self-loops, no duplicate connections

级别 3:逻辑完整性验证

✅ Required nodes exist (workflowStart, userGuide, at least one output node)
✅ All nodes reachable from workflowStart (connectivity)
✅ No illegal cycles (unless using loop node)
✅ loop nodes correctly configured with parentNodeId and childrenNodeIdList
✅ No dead ends (non-output nodes without outgoing edges)
✅ All required inputs have values

输出:验证报告(包含错误、警告和修复建议)


阶段 5:增量修改(可选)

使用场景:添加/删除/修改节点

处理步骤:

1. 理解修改意图

Use AI to analyze user request, extract:
{
  "action": "add" | "delete" | "modify" | "reconnect",
  "targetNodes": ["aiChatNode"],
  "insertBefore": "aiChatNode",
  "newNodes": [{ "type": "datasetSearchNode", "name": "Knowledge Base Search" }],
  "modifications": {
    "aiChatNode": {
      "inputs": { "quoteQA": ["knowledgeBaseSearch", "searchResult"] }
    }
  }
}

2. 执行修改

- Add node: generate new node, reconnect, calculate position
- Delete node: remove node, bypass reconnect, clean references
- Modify node: update inputs/outputs, validate references

3. 重新布局并验证


示例

示例 1:简单 AI 问答工作流

用户请求:

"Create a simple AI Q&A workflow where users input questions and AI responds directly"

技能处理:

  1. 需求分析

    {
      "purpose": "AI question answering",
      "domain": "general",
      "complexity": "simple",
      "features": ["aiChat"],
      "inputs": ["userChatInput"],
      "outputs": ["AI response"]
    }
    
  2. 模板匹配

    • 文档翻译助手.json - 得分:0.85(简单工作流,直接处理)
  3. JSON 生成

    • 使用模板,修改 systemPrompt 和 welcomeText
  4. 验证结果

    • ✅ 三个层级的验证均通过

生成的 JSON(关键部分):

{
  "nodes": [
    {
      "nodeId": "userGuide",
      "name": "System Configuration",
      "flowNodeType": "userGuide",
      "position": {"x": -600, "y": -250}
    },
    {
      "nodeId": "workflowStart",
      "name": "Start",
      "flowNodeType": "workflowStart",
      "position": {"x": -150, "y": 100},
      "outputs": [
        {"key": "userChatInput", "type": "static", "valueType": "string"}
      ]
    },
    {
      "nodeId": "aiChatNode",
      "name": "AI Response",
      "flowNodeType": "chatNode",
      "position": {"x": 200, "y": 100},
      "inputs": [
        {
          "key": "model",
          "valueType": "string",
          "value": "gpt-4"
        },
        {
          "key": "systemPrompt",
          "valueType": "string",
          "value": "You are a professional AI assistant that can answer various questions. Please provide accurate and helpful answers based on user questions."
        },
        {
          "key": "userChatInput",
          "valueType": "string",
          "value": ["workflowStart", "userChatInput"]
        }
      ],
      "outputs": [
        {"key": "answerText", "type": "static", "valueType": "string"}
      ]
    },
    {
      "nodeId": "outputNode",
      "name": "Output Answer",
      "flowNodeType": "answerNode",
      "position": {"x": 550, "y": 100},
      "inputs": [
        {
          "key": "text",
          "valueType": "string",
          "value": ["aiChatNode", "answerText"]
        }
      ]
    }
  ],
  "edges": [
    {
      "source": "workflowStart",
      "target": "aiChatNode",
      "sourceHandle": "workflowStart-source-right",
      "targetHandle": "aiChatNode-target-left"
    },
    {
      "source": "aiChatNode",
      "target": "outputNode",
      "sourceHandle": "aiChatNode-source-right",
      "targetHandle": "outputNode-target-left"
    }
  ],
  "chatConfig": {
    "welcomeText": "Welcome to the AI Q&A assistant! Please enter your question.",
    "variables": []
  }
}

示例 2:文档翻译工作流(基于模板)

用户请求:

"Create a document translation workflow that translates user-uploaded documents from Chinese to English"

技能处理:

  1. 需求分析

    {
      "purpose": "Document translation",
      "domain": "document",
      "complexity": "medium",
      "features": ["readFiles", "aiChat", "textOutput"],
      "inputs": ["userFiles"],
      "outputs": ["translated document"]
    }
    
  2. 模板匹配

    • 文档翻译助手.json - 得分:0.95(完美匹配!)
  3. 生成 JSON

    • 直接使用模板,仅调整提示词中的语言方向

生成的工作流结构:

workflowStart → readFiles → translateNode → outputNode

关键节点配置:

  • readFiles 节点:读取用户上传的文件
  • translateNode(chatNode):AI 使用专用提示词进行翻译
  • outputNode(answerNode):输出译文

示例 3:增量修改(添加知识库)

用户请求:

"I have an existing AI Q&A workflow (simple_qa_workflow.json),
I want to search the knowledge base first before AI answers,
find relevant information then generate response"

现有工作流结构:

workflowStart → aiChatNode → outputNode

修改目标:

workflowStart → knowledgeBaseSearch → aiChatNode → outputNode

技能处理:

  1. 分析修改意图

    {
      "action": "add",
      "targetNodes": ["aiChatNode"],
      "insertBefore": "aiChatNode",
      "newNodes": [
        {
          "type": "datasetSearchNode",
          "name": "Knowledge Base Search"
        }
      ],
      "modifications": {
        "aiChatNode": {
          "inputs": {
            "quoteQA": ["knowledgeBaseSearch", "searchResult"]
          }
        }
      }
    }
    
  2. 执行修改

    • 添加 knowledgeBaseSearch 节点
    • 修改边:workflowStart → knowledgeBaseSearch
    • 添加边:knowledgeBaseSearch → aiChatNode
    • 修改 aiChatNode 的 inputs(添加 quoteQA)
  3. 重新布局位置

    • workflowStart:(-150,100)
    • knowledgeBaseSearch:(50,100)← 新插入
    • aiChatNode:(400,100)← 向右移动
    • outputNode:(750,100)← 向右移动
  4. 验证结果

    • ✅ 所有验证均通过

修改后的 JSON(新增和修改的部分):

{
  "nodes": [
    {
      "nodeId": "knowledgeBaseSearch",
      "name": "Knowledge Base Search",
      "flowNodeType": "datasetSearchNode",
      "position": {"x": 50, "y": 100},
      "inputs": [
        {
          "key": "datasetIds",
          "valueType": "selectDataset",
          "value": [],
          "required": true
        },
        {
          "key": "searchQuery",
          "valueType": "string",
          "value": ["workflowStart", "userChatInput"],
          "required": true
        },
        {
          "key": "similarity",
          "valueType": "number",
          "value": 0.5
        },
        {
          "key": "limitCount",
          "valueType": "number",
          "value": 5
        }
      ],
      "outputs": [
        {
          "key": "searchResult",
          "type": "static",
          "valueType": "datasetQuote"
        }
      ]
    },
    {
      "nodeId": "aiChatNode",
      "inputs": [
        {
          "key": "quoteQA",
          "valueType": "datasetQuote",
          "value": ["knowledgeBaseSearch", "searchResult"]
        }
      ]
    }
  ],
  "edges": [
    {
      "source": "workflowStart",
      "target": "knowledgeBaseSearch"
    },
    {
      "source": "knowledgeBaseSearch",
      "target": "aiChatNode"
    },
    {
      "source": "aiChatNode",
      "target": "outputNode"
    }
  ]
}

修改摘要报告:

  • ✅ 添加 1 个节点:knowledgeBaseSearch(datasetSearchNode)
  • ✅ 修改 1 个节点:aiChatNode(添加 quoteQA 输入)
  • ✅ 添加 1 条边:knowledgeBaseSearch → aiChatNode
  • ✅ 修改 1 条边:workflowStart → knowledgeBaseSearch(原为 workflowStart → aiChatNode)
  • ✅ 重新布局所有位置

技术实现

NodeId 生成算法

规则:

  1. 固定 ID:workflowStart、userGuide(systemConfig)
  2. 语义命名:根据节点名称生成(移除空格和中文,转换为驼峰命名)
  3. 确保唯一性:若发生冲突,则添加 _1、_2 后缀

示例:

  • generateNodeId('chatNode', 'Travel Planning Assistant') → TravelPlanningAssistantNode
  • generateNodeId('httpRequest468', 'Weather Query') → WeatherQueryNode
  • generateNodeId('chatNode', 'Assistant', {TravelPlanningAssistantNode}) → AssistantNode_1
位置自动布局算法

算法:分层布局

步骤:

  1. 拓扑排序以确定层级(BFS)
  2. 计算每一层的水平位置和垂直间距
  3. 特殊节点使用固定位置(userGuide:{x: -600, y: -250})

参数:

  • LAYER_GAP_X = 350(层间水平间距)
  • NODE_GAP_Y = 150(层内垂直间距)
  • START_X = -200,START_Y = 0
引用格式说明

两种引用格式:

1. 数组格式(直接值引用):

"value": ["workflowStart", "userChatInput"]

2. 模板语法(字符串拼接):

"value": "Please create a plan for me.\n\nDestination: {{$workflowStart.userChatInput$}}\n\nWeather: {{$weatherQueryNode.httpRawResponse$}}"

重要提示:模板语法为 {{$nodeId.key$}}(双大括号,单个 $)

特殊节点处理

loop 节点:

  • 必须包含 childrenNodeIdList 字段
  • 子节点必须包含 parentNodeId 字段
  • 子节点包括:loopStart、[处理节点...]、loopEnd

ifElse 节点:

  • 具有多个输出分支
  • 每个分支对应不同的条件

最佳实践

应遵循的做法(推荐实践)
  • ✅ 始终进行三个层级的验证 - 格式、连接和逻辑
  • ✅ 使用有意义的 nodeId - 使用语义化名称(例如,weatherQueryNode)
  • ✅ 优先使用模板匹配 - 基于模板生成比从头创建更可靠
  • ✅ 直接传值时使用数组引用 - ["nodeId", "key"]
  • ✅ 拼接字符串时使用模板引用 - {{$nodeId.key$}}
  • ✅ 自动布局位置 - 使用自动布局算法
  • ✅ 包含系统配置节点 - 始终包含 userGuide
  • ✅ 通过验证进行测试 - 导入 FastGPT 前使用内置验证
  • ✅ 提供清晰的错误消息 - 包含位置和修复建议
  • ✅ 记录修改内容 - 生成修改摘要报告
不应遵循的做法(禁止实践)
  • ❌ 不要跳过验证 - 绝不跳过验证
  • ❌ 不要使用无效的节点类型 - 检查 flowNodeType 是否有效
  • ❌ 不要在没有循环节点的情况下创建循环引用 - 不允许非法循环
  • ❌ 不要遗漏必填字段 - nodeId、name、flowNodeType、position、inputs、outputs
  • ❌ 不要使用错误的引用格式 - 禁止:{{nodeId.key}}(缺少 $)
  • ❌ 不要忽略警告 - 应修复所有警告
  • ❌ 不要将位置硬编码 - 除 userGuide 外,使用自动布局
  • ❌ 不要创建无法到达的节点 - 确保可从 workflowStart 到达
  • ❌ 不要生成过于复杂的工作流 - 节点数超过 20 的工作流应拆分

故障排除

常见问题

Q1:导入 FastGPT 时提示“Invalid node type”

A:检查 flowNodeType 字段,确保使用受支持的类型。参阅 references/node_types_reference.md。常见错误:

  • chatNode 才是正确值(不是 aiChat)
  • 应保留数字后缀(例如 httpRequest468)

Q2:节点间引用不起作用

A:检查引用格式:

  • ✅ 正确:["workflowStart", "userChatInput"] 或 {{$workflowStart.userChatInput$}}
  • ❌ 错误:{$workflowStart.userChatInput$}(单层大括号,应为双层)

Q3:某些节点在运行时没有执行

A:使用内置验证检查第 3 层,确保所有节点都可从 workflowStart 到达

Q4:并行节点没有并行执行

A:确保多个节点的目标是同一个聚合节点,并且这些节点之间没有依赖关系

Q5:循环工作流出错

A:必须使用 flowNodeType: "loop" 节点,并配置 parentNodeId 和 childrenNodeIdList

调试清单
## Phase 1: JSON Format Check
- [ ] JSON is parseable
- [ ] Contains nodes, edges, chatConfig
- [ ] All strings use double quotes
- [ ] No trailing commas

## Phase 2: Node Check
- [ ] workflowStart node exists
- [ ] At least one output node exists
- [ ] All flowNodeType valid
- [ ] All nodeId unique
- [ ] All position contains x, y

## Phase 3: Connection Check
- [ ] All edges' source and target exist
- [ ] All handle format correct
- [ ] No duplicate edges, no self-loops

## Phase 4: Reference Check
- [ ] All array references' nodes and keys exist
- [ ] All template references' nodes and keys exist
- [ ] Reference types match

## Phase 5: Logic Check
- [ ] All nodes reachable from workflowStart
- [ ] No illegal cycles
- [ ] No dead-end nodes
- [ ] All required inputs have values

## Phase 6: Runtime Test
- [ ] Import to FastGPT without errors
- [ ] Configure necessary parameters
- [ ] Run test cases
- [ ] Check output meets expectations

快速参考

内置模板文件
  • templates/文档翻译助手.json - 简单工作流,文档处理
  • templates/销售陪练大师.json - 中等复杂度,对话式 AI
  • templates/简历筛选助手_飞书.json - 复杂工作流,数据 + 外部集成
  • templates/AI金融日报.json - 定时触发,多 Agent
详细文档
  • references/node_types_reference.md - 40 多种节点类型的完整参考
  • references/validation_rules.md - 详细的三层验证规则
  • references/template_matching.md - 模板匹配算法
  • references/json_structure_spec.md - 完整的 FastGPT JSON 结构规范
示例文档
  • examples/example1_simple_qa.md - 完整示例:简单问答工作流
  • examples/example2_travel_planning.md - 完整示例:旅行规划工作流
  • examples/example3_incremental_modify.md - 完整示例:增量修改
常用命令
# Validate workflow JSON
node scripts/validate_workflow.js path/to/workflow.json

# Copy template
cp templates/文档翻译助手.json my_workflow.json

# View template list
ls -lh templates/

版本:1.0 最后更新:2025-01-02 兼容性:FastGPT v4.8+

评论

支持 Markdown