灵阙智能体平台 - Agent 工作流技术规范

文档版本

  • 版本: 1.0.0
  • 创建日期: 2025-11-06
  • 作者: Maurice (猪哥云-数据产品部)
  • 状态: 规划中

1. 产品定位

1.1 核心价值主张

最 SOTA 技术 + 最易用交互 + 最开放定制的企业级 Agent 工作流平台

1.2 目标用户

  • AI 应用开发者
  • 企业技术团队
  • 产品经理和业务分析师
  • 开源社区贡献者

1.3 差异化优势

  1. AI 原生:自然语言直接生成工作流
  2. 开放生态:兼容主流格式 + GitHub 集成
  3. 企业级:完整监控 + 状态持久化
  4. 中文优化:本地化文档和场景

2. 技术架构

2.1 整体架构

┌─────────────────────────────────────────────────────────┐
│                    前端层(Next.js 15)                   │
├─────────────────────────────────────────────────────────┤
│  可视化编辑器  │  AI 转写  │  模板市场  │  执行监控      │
│  (React Flow)  │           │           │  (LangSmith)   │
└─────────────────────────────────────────────────────────┘
                            ↓
┌─────────────────────────────────────────────────────────┐
│                    API 层(Server Actions)               │
├─────────────────────────────────────────────────────────┤
│  工作流管理  │  模板管理  │  执行引擎  │  GitHub 集成    │
└─────────────────────────────────────────────────────────┘
                            ↓
┌─────────────────────────────────────────────────────────┐
│                    编排层(LangGraph)                    │
├─────────────────────────────────────────────────────────┤
│  状态管理  │  节点执行  │  流式输出  │  错误处理        │
└─────────────────────────────────────────────────────────┘
                            ↓
┌─────────────────────────────────────────────────────────┐
│                    数据层(PostgreSQL + Redis)           │
├─────────────────────────────────────────────────────────┤
│  工作流定义  │  执行历史  │  模板库  │  用户数据        │
└─────────────────────────────────────────────────────────┘

3. 核心概念

3.1 工作流(Workflow)

定义:由多个节点和连接组成的有向图,描述 Agent 的执行逻辑

属性

  • id: 唯一标识符(CUID)
  • name: 工作流名称
  • version: 语义版本号(SemVer)
  • nodes: 节点列表
  • edges: 连接列表
  • variables: 全局变量
  • metadata: 元数据(作者、标签、描述)

3.2 节点(Node)

定义:工作流中的单个执行单元,封装特定功能

基础节点类型(15+):

基础层

  1. LLM Node - 调用大语言模型

    {
      type: 'llm',
      config: {
        provider: 'anthropic' | 'openai' | 'google',
        model: 'claude-sonnet-4.5' | 'gpt-4o' | 'gemini-2.0-flash',
        temperature: 0.7,
        maxTokens: 4096,
        systemPrompt: string,
        streaming: boolean
      }
    }
    
  2. Prompt Node - Prompt 模板管理

    {
      type: 'prompt',
      config: {
        template: string,  // 支持 {{variable}} 插值
        variables: Record<string, string>
      }
    }
    
  3. Input Node - 接收外部输入

  4. Output Node - 返回最终结果

数据层

  1. Retrieval Node - RAG 检索

    {
      type: 'retrieval',
      config: {
        dataSource: 'vector_db' | 'file_search',
        topK: 5,
        minScore: 0.7,
        rerank: boolean
      }
    }
    
  2. Embedding Node - 文本向量化

  3. Transform Node - 数据转换

控制流层

  1. Conditional Node - 条件分支

    {
      type: 'conditional',
      config: {
        condition: string,  // JavaScript 表达式
        ifTrue: string,     // 目标节点 ID
        ifFalse: string     // 目标节点 ID
      }
    }
    
  2. Loop Node - 循环执行

  3. Merge Node - 结果合并

工具层

  1. API Call Node - HTTP 请求

    {
      type: 'api',
      config: {
        method: 'GET' | 'POST' | 'PUT' | 'DELETE',
        url: string,
        headers: Record<string, string>,
        body: any,
        auth: {
          type: 'bearer' | 'basic' | 'apikey',
          credentials: string
        }
      }
    }
    
  2. Database Query Node - 数据库操作

  3. Web Search Node - 网络搜索(Tavily)

高级层

  1. Agent Node - 子工作流嵌套
  2. Memory Node - 对话历史管理
  3. Code Execution Node - 自定义代码(E2B)

3.3 连接(Edge)

定义:节点之间的数据流和执行顺序

类型

  • Sequence Edge: 顺序执行
  • Conditional Edge: 条件分支
  • Data Edge: 数据传递

属性

{
  id: string,
  source: string,      // 源节点 ID
  target: string,      // 目标节点 ID
  sourceHandle?: string,  // 源节点输出端口
  targetHandle?: string,  // 目标节点输入端口
  condition?: {
    type: 'expression' | 'value',
    value: string | boolean
  }
}

4. 数据模型(Prisma Schema)

4.1 工作流表

model Workflow {
  id          String   @id @default(cuid())
  name        String
  description String?
  version     String   @default("1.0.0")

  // 工作流定义
  definition  Json     // { nodes: [], edges: [], variables: {} }

  // 元数据
  category    String?  // 分类:客服/数据分析/代码生成
  tags        String[] // 标签数组
  isPublic    Boolean  @default(false)
  isTemplate  Boolean  @default(false)

  // 统计
  executionCount Int   @default(0)
  lastExecutedAt DateTime?

  // 关联
  userId      String
  user        User     @relation(fields: [userId], references: [id])
  executions  WorkflowExecution[]

  // 时间戳
  createdAt   DateTime @default(now())
  updatedAt   DateTime @updatedAt

  @@index([userId, isPublic])
  @@index([category, tags])
  @@index([isTemplate])
}

4.2 执行记录表

model WorkflowExecution {
  id          String   @id @default(cuid())

  // 关联
  workflowId  String
  workflow    Workflow @relation(fields: [workflowId], references: [id])
  userId      String
  user        User     @relation(fields: [userId], references: [id])

  // 执行状态
  status      String   // pending | running | completed | failed
  startedAt   DateTime @default(now())
  completedAt DateTime?
  duration    Int?     // 毫秒

  // 输入输出
  input       Json
  output      Json?

  // 执行详情
  logs        Json     // 节点执行日志
  metrics     Json?    // 性能指标(tokens, latency)
  error       String?  // 错误信息

  // LangSmith 集成
  langsmithRunId String?

  @@index([workflowId, status])
  @@index([userId, startedAt])
}

4.3 模板市场表

model WorkflowTemplate {
  id          String   @id @default(cuid())
  name        String
  description String
  category    String
  tags        String[]

  // GitHub 信息
  githubUrl   String?
  githubStars Int      @default(0)
  author      String
  authorUrl   String?

  // 工作流定义
  definition  Json

  // 预览
  thumbnail   String?  // 缩略图 URL
  readme      String?  // Markdown 说明

  // 统计
  downloads   Int      @default(0)
  likes       Int      @default(0)

  // 版本
  version     String   @default("1.0.0")

  // 时间戳
  createdAt   DateTime @default(now())
  updatedAt   DateTime @updatedAt

  @@index([category, tags])
  @@index([githubStars])
  @@index([downloads])
}

4.4 节点类型注册表

model NodeType {
  id          String   @id @default(cuid())
  type        String   @unique  // 'llm', 'retrieval', etc.
  name        String
  description String
  category    String   // 'basic', 'data', 'control', 'tool', 'advanced'

  // Schema 定义
  configSchema Json    // Zod schema
  inputSchema  Json
  outputSchema Json

  // UI 配置
  icon        String
  color       String

  // 插件信息
  isBuiltin   Boolean  @default(true)
  pluginId    String?

  // 时间戳
  createdAt   DateTime @default(now())
  updatedAt   DateTime @updatedAt

  @@index([category])
}

5. JSON Schema 规范

5.1 工作流定义格式

interface WorkflowDefinition {
  version: string;  // Schema 版本,如 "1.0.0"
  nodes: Node[];
  edges: Edge[];
  variables?: Record<string, any>;
  config?: WorkflowConfig;
}

interface Node {
  id: string;
  type: NodeType;
  position: { x: number; y: number };
  data: {
    label: string;
    config: Record<string, any>;  // 节点特定配置
  };
}

interface Edge {
  id: string;
  source: string;
  target: string;
  sourceHandle?: string;
  targetHandle?: string;
  condition?: EdgeCondition;
}

interface WorkflowConfig {
  timeout?: number;        // 超时时间(ms)
  maxRetries?: number;     // 最大重试次数
  errorHandling?: 'stop' | 'continue' | 'rollback';
  streaming?: boolean;     // 是否流式输出
}

5.2 Zod 验证 Schema

import { z } from 'zod';

export const NodeSchema = z.object({
  id: z.string().cuid(),
  type: z.enum([
    'llm', 'prompt', 'input', 'output',
    'retrieval', 'embedding', 'transform',
    'conditional', 'loop', 'merge',
    'api', 'database', 'websearch',
    'agent', 'memory', 'code'
  ]),
  position: z.object({
    x: z.number(),
    y: z.number()
  }),
  data: z.object({
    label: z.string(),
    config: z.record(z.any())
  })
});

export const EdgeSchema = z.object({
  id: z.string().cuid(),
  source: z.string().cuid(),
  target: z.string().cuid(),
  sourceHandle: z.string().optional(),
  targetHandle: z.string().optional(),
  condition: z.object({
    type: z.enum(['expression', 'value']),
    value: z.union([z.string(), z.boolean()])
  }).optional()
});

export const WorkflowDefinitionSchema = z.object({
  version: z.string().regex(/^\d+\.\d+\.\d+$/),
  nodes: z.array(NodeSchema),
  edges: z.array(EdgeSchema),
  variables: z.record(z.any()).optional(),
  config: z.object({
    timeout: z.number().optional(),
    maxRetries: z.number().optional(),
    errorHandling: z.enum(['stop', 'continue', 'rollback']).optional(),
    streaming: z.boolean().optional()
  }).optional()
});

6. API 设计

6.1 REST API 端点

工作流管理

GET    /api/workflows              - 获取工作流列表
GET    /api/workflows/:id          - 获取单个工作流
POST   /api/workflows              - 创建工作流
PUT    /api/workflows/:id          - 更新工作流
DELETE /api/workflows/:id          - 删除工作流
POST   /api/workflows/:id/clone    - 克隆工作流

执行管理

POST   /api/workflows/:id/execute  - 执行工作流
GET    /api/executions/:id         - 获取执行详情
GET    /api/executions/:id/stream  - SSE 流式输出
POST   /api/executions/:id/cancel  - 取消执行

AI 转写

POST   /api/ai/generate-workflow   - 自然语言生成工作流
POST   /api/ai/suggest-nodes       - 推荐节点
POST   /api/ai/complete-config     - 智能配置补全

模板市场

GET    /api/templates              - 获取模板列表
GET    /api/templates/:id          - 获取模板详情
POST   /api/templates/:id/install  - 安装模板
POST   /api/templates/import       - 从 GitHub 导入

GitHub 集成

GET    /api/github/auth            - OAuth 认证
GET    /api/github/repos           - 获取仓库列表
GET    /api/github/files           - 浏览文件
POST   /api/github/import          - 导入工作流

6.2 Server Actions

// app/actions/workflow.ts
'use server';

export async function createWorkflow(data: WorkflowInput) {
  const validated = WorkflowDefinitionSchema.parse(data.definition);

  const workflow = await prisma.workflow.create({
    data: {
      name: data.name,
      description: data.description,
      definition: validated,
      userId: session.user.id
    }
  });

  return workflow;
}

export async function executeWorkflow(workflowId: string, input: any) {
  const workflow = await prisma.workflow.findUnique({
    where: { id: workflowId }
  });

  // 使用 LangGraph 执行
  const result = await executeLangGraph(workflow.definition, input);

  // 记录执行历史
  await prisma.workflowExecution.create({
    data: {
      workflowId,
      userId: session.user.id,
      status: 'completed',
      input,
      output: result,
      duration: result.duration
    }
  });

  return result;
}

7. 前端组件设计

7.1 核心组件树

WorkflowEditor/
├── EditorToolbar/          # 工具栏(保存、运行、导入导出)
├── NodePalette/            # 节点面板(拖拽节点库)
├── ReactFlowCanvas/        # 画布主体
│   ├── CustomNodes/        # 自定义节点组件
│   │   ├── LLMNode.tsx
│   │   ├── PromptNode.tsx
│   │   ├── ConditionalNode.tsx
│   │   └── ...
│   └── CustomEdges/        # 自定义连线组件
├── NodeConfigPanel/        # 节点配置面板(右侧)
├── VariablesPanel/         # 全局变量管理
└── ExecutionPanel/         # 执行和调试面板

7.2 React Flow 配置

// components/workflow-editor/flow-config.ts
import ReactFlow, {
  Background,
  Controls,
  MiniMap,
  useNodesState,
  useEdgesState
} from '@xyflow/react';

export const nodeTypes = {
  llm: LLMNode,
  prompt: PromptNode,
  retrieval: RetrievalNode,
  conditional: ConditionalNode,
  // ... 其他节点类型
};

export const edgeTypes = {
  default: CustomEdge,
  conditional: ConditionalEdge
};

export const defaultEdgeOptions = {
  animated: true,
  style: { stroke: '#94a3b8', strokeWidth: 2 }
};

7.3 状态管理(Zustand)

// stores/workflow-store.ts
import { create } from 'zustand';

interface WorkflowState {
  // 工作流数据
  workflow: Workflow | null;
  nodes: Node[];
  edges: Edge[];
  variables: Record<string, any>;

  // UI 状态
  selectedNode: Node | null;
  isPanelOpen: boolean;
  isExecuting: boolean;

  // Actions
  setWorkflow: (workflow: Workflow) => void;
  addNode: (node: Node) => void;
  updateNode: (id: string, data: Partial<Node>) => void;
  deleteNode: (id: string) => void;
  addEdge: (edge: Edge) => void;
  deleteEdge: (id: string) => void;
  setVariable: (key: string, value: any) => void;

  // 执行
  executeWorkflow: (input: any) => Promise<void>;
  cancelExecution: () => void;
}

export const useWorkflowStore = create<WorkflowState>((set, get) => ({
  workflow: null,
  nodes: [],
  edges: [],
  variables: {},
  selectedNode: null,
  isPanelOpen: false,
  isExecuting: false,

  setWorkflow: (workflow) => set({ workflow }),

  addNode: (node) => set((state) => ({
    nodes: [...state.nodes, node]
  })),

  // ... 其他 actions
}));

8. LangGraph 集成

8.1 工作流转 LangGraph

// lib/langgraph/converter.ts
import { StateGraph } from '@langchain/langgraph';

export function convertToLangGraph(workflow: WorkflowDefinition) {
  const graph = new StateGraph({
    channels: {
      messages: {
        value: (left: any[], right: any[]) => left.concat(right),
        default: () => []
      },
      // ... 其他状态通道
    }
  });

  // 添加节点
  for (const node of workflow.nodes) {
    graph.addNode(node.id, createNodeFunction(node));
  }

  // 添加边
  for (const edge of workflow.edges) {
    if (edge.condition) {
      graph.addConditionalEdge(
        edge.source,
        evaluateCondition(edge.condition),
        { [edge.target]: edge.target }
      );
    } else {
      graph.addEdge(edge.source, edge.target);
    }
  }

  // 设置入口和出口
  const entryNode = workflow.nodes.find(n => n.type === 'input');
  const exitNode = workflow.nodes.find(n => n.type === 'output');

  graph.setEntryPoint(entryNode?.id || workflow.nodes[0].id);
  graph.setFinishPoint(exitNode?.id);

  return graph.compile();
}

8.2 节点执行器

// lib/langgraph/executors.ts
export function createNodeFunction(node: Node) {
  switch (node.type) {
    case 'llm':
      return async (state: GraphState) => {
        const { provider, model, systemPrompt } = node.data.config;
        const response = await callLLM(provider, model, {
          system: systemPrompt,
          messages: state.messages
        });
        return { messages: [response] };
      };

    case 'retrieval':
      return async (state: GraphState) => {
        const { dataSource, topK } = node.data.config;
        const docs = await retrieveDocuments(
          state.messages[state.messages.length - 1].content,
          { dataSource, topK }
        );
        return { context: docs };
      };

    case 'conditional':
      return async (state: GraphState) => {
        const { condition } = node.data.config;
        const result = evaluateCondition(condition, state);
        return { conditionResult: result };
      };

    // ... 其他节点类型
  }
}

9. AI 转写实现

9.1 Prompt 模板

// lib/ai/prompts.ts
export const WORKFLOW_GENERATION_PROMPT = `
你是灵阙智能体平台的工作流设计专家。

## 任务
将用户的自然语言描述转换为结构化的工作流 JSON。

## 用户需求
{user_description}

## 分析步骤
1. 识别主要任务和子任务
2. 确定所需的节点类型
3. 设计节点间的连接关系
4. 配置每个节点的参数

## 可用节点类型
{available_node_types}

## 输出格式
请严格按照以下 JSON Schema 输出:

\`\`\`json
{json_schema}
\`\`\`

## 要求
- 节点 ID 使用语义化命名(如 "llm_customer_service")
- 确保工作流逻辑正确且无循环依赖
- 为每个节点提供清晰的 label
- 配置合理的默认参数

请输出完整的工作流 JSON。
`;

export const NODE_SUGGESTION_PROMPT = `
根据当前工作流上下文,推荐下一个最合适的节点。

## 当前工作流
{current_workflow}

## 最后一个节点
{last_node}

## 可用节点类型
{available_node_types}

请推荐 3 个最合适的节点类型,并说明理由。

输出格式:
\`\`\`json
[
  {
    "type": "节点类型",
    "reason": "推荐理由",
    "suggestedConfig": { /* 建议的配置 */ }
  }
]
\`\`\`
`;

9.2 AI 转写服务

// lib/ai/workflow-generator.ts
import Anthropic from '@anthropic-ai/sdk';

export async function generateWorkflowFromDescription(
  description: string
): Promise<WorkflowDefinition> {
  const anthropic = new Anthropic();

  const response = await anthropic.messages.create({
    model: 'claude-sonnet-4.5-20250219',
    max_tokens: 8000,
    messages: [{
      role: 'user',
      content: WORKFLOW_GENERATION_PROMPT
        .replace('{user_description}', description)
        .replace('{available_node_types}', JSON.stringify(NODE_TYPES))
        .replace('{json_schema}', JSON.stringify(WORKFLOW_SCHEMA))
    }]
  });

  const jsonContent = extractJSON(response.content[0].text);
  const validated = WorkflowDefinitionSchema.parse(jsonContent);

  return validated;
}

function extractJSON(text: string): any {
  const match = text.match(/```json\n([\s\S]*?)\n```/);
  if (!match) throw new Error('No JSON found in response');
  return JSON.parse(match[1]);
}

10. 实施检查清单

Sprint 1(Week 1-2)

  • 创建数据库 Schema(Prisma migrate)
  • 搭建 React Flow 基础编辑器
  • 实现 5 种基础节点组件
  • 实现拖拽和连线功能
  • 实现 JSON 导入导出
  • 工作流保存到数据库

Sprint 2(Week 3-4)

  • 集成 Claude Sonnet 4.5 API
  • 实现自然语言转工作流
  • 实现节点推荐系统
  • 完善 15+ 节点类型
  • 节点配置面板

Sprint 3(Week 5-6)

  • GitHub OAuth 集成
  • 仓库浏览和文件导入
  • 模板市场 UI
  • 50+ 精选模板数据导入
  • 模板搜索和筛选

Sprint 4(Week 7-8)

  • LangGraph 集成
  • 工作流执行引擎
  • 流式输出(SSE)
  • LangSmith 监控集成
  • 执行历史记录

Sprint 5(Week 9-10)

  • 插件系统 SDK
  • REST API 文档(OpenAPI)
  • Webhook 通知
  • 开发者文档站

11. 性能指标

11.1 前端性能

  • 首屏加载:< 2 秒
  • 节点渲染:支持 1000+ 节点
  • 交互响应:< 100ms

11.2 后端性能

  • API 响应:P95 < 200ms
  • 工作流执行:并发 100+
  • 流式输出:< 50ms TTFB

11.3 可用性

  • 系统可用性:99.9%
  • 数据持久化:100%
  • 错误恢复:自动重试

12. 安全考虑

12.1 认证授权

  • JWT Token 认证
  • RBAC 权限模型
  • API Key 管理

12.2 数据安全

  • 敏感数据加密(Secrets)
  • SQL 注入防护(Prisma)
  • XSS 防护(Next.js)

12.3 执行安全

  • 代码沙箱(E2B)
  • 资源限制(Timeout)
  • Rate Limiting

猪哥云(四川)网络科技有限公司 | 合规网 www.hegui.com 猪哥云-数据产品部-Maurice | maurice_wen@proton.me 2025 猪哥云-灵阙企业级智能体平台