feat(ai-web): 完成自研流程图的保存
This commit is contained in:
@@ -52,7 +52,7 @@ create table hudi_collect_build_b12.service_ai_flow_task_template
|
||||
created_time datetime(6) comment '记录创建时间',
|
||||
modified_time datetime(6) comment '记录更新时间',
|
||||
description varchar(255) comment '模板功能、内容说明',
|
||||
flow_graph longtext comment '前端流程图数据',
|
||||
flow_graph longtext not null comment '前端流程图数据',
|
||||
input_schema longtext not null comment '模板入参Schema',
|
||||
name varchar(255) not null comment '模板名称',
|
||||
primary key (id)
|
||||
|
||||
@@ -3,10 +3,8 @@ package com.lanyuanxiaoyao.service.ai.web.controller.task;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.lanyuanxiaoyao.service.ai.core.entity.amis.AmisCrudResponse;
|
||||
import com.lanyuanxiaoyao.service.ai.core.entity.amis.AmisResponse;
|
||||
import com.lanyuanxiaoyao.service.ai.web.base.controller.SimpleControllerSupport;
|
||||
import com.lanyuanxiaoyao.service.ai.web.base.controller.query.Query;
|
||||
import com.lanyuanxiaoyao.service.ai.web.base.entity.SimpleItem;
|
||||
import com.lanyuanxiaoyao.service.ai.web.entity.FlowTaskTemplate;
|
||||
import com.lanyuanxiaoyao.service.ai.web.service.task.FlowTaskTemplateService;
|
||||
@@ -17,6 +15,8 @@ import lombok.extern.slf4j.Slf4j;
|
||||
import org.mapstruct.Context;
|
||||
import org.mapstruct.factory.Mappers;
|
||||
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@@ -24,26 +24,19 @@ import org.springframework.web.bind.annotation.RestController;
|
||||
@RestController
|
||||
@RequestMapping("flow_task/template")
|
||||
public class TaskTemplateController extends SimpleControllerSupport<FlowTaskTemplate, TaskTemplateController.SaveItem, TaskTemplateController.ListItem, TaskTemplateController.DetailItem> {
|
||||
private final FlowTaskTemplateService flowTaskTemplateService;
|
||||
private final ObjectMapper mapper;
|
||||
|
||||
public TaskTemplateController(FlowTaskTemplateService flowTaskTemplateService, Jackson2ObjectMapperBuilder builder) {
|
||||
super(flowTaskTemplateService);
|
||||
this.flowTaskTemplateService = flowTaskTemplateService;
|
||||
this.mapper = builder.build();
|
||||
}
|
||||
|
||||
@Override
|
||||
public AmisResponse<Long> save(SaveItem saveItem) throws Exception {
|
||||
log.info("Save: {}", saveItem);
|
||||
SaveItem.Mapper map = Mappers.getMapper(SaveItem.Mapper.class);
|
||||
log.info("Mapper: {}", map.from(saveItem, mapper));
|
||||
return super.save(saveItem);
|
||||
}
|
||||
|
||||
@Override
|
||||
public AmisCrudResponse list(Query query) throws Exception {
|
||||
AmisCrudResponse list = super.list(query);
|
||||
log.info("List: {}", list);
|
||||
return list;
|
||||
@PostMapping("update_flow_graph")
|
||||
public AmisResponse<?> updateFlowGraph(@RequestBody UpdateGraphItem item) throws JsonProcessingException {
|
||||
flowTaskTemplateService.updateFlowGraph(item.getId(), mapper.writeValueAsString(item.getGraph()));
|
||||
return AmisResponse.responseSuccess();
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -97,14 +90,22 @@ public class TaskTemplateController extends SimpleControllerSupport<FlowTaskTemp
|
||||
private String name;
|
||||
private String description;
|
||||
private Map<String, Object> inputSchema;
|
||||
private Map<String, Object> flowGraph;
|
||||
|
||||
@org.mapstruct.Mapper
|
||||
public static abstract class Mapper {
|
||||
public abstract DetailItem from(FlowTaskTemplate template, @Context ObjectMapper mapper) throws Exception;
|
||||
|
||||
public Map<String, Object> mapInputSchema(String inputSchema, @Context ObjectMapper mapper) throws Exception {
|
||||
return mapper.readValue(inputSchema, new TypeReference<>() {});
|
||||
public Map<String, Object> mapJson(String source, @Context ObjectMapper mapper) throws Exception {
|
||||
return mapper.readValue(source, new TypeReference<>() {
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class UpdateGraphItem {
|
||||
private Long id;
|
||||
private Map<String, Object> graph;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,6 +31,6 @@ public class FlowTaskTemplate extends SimpleEntity {
|
||||
@Column(nullable = false, columnDefinition = "longtext")
|
||||
private String inputSchema;
|
||||
@Comment("前端流程图数据")
|
||||
@Column(columnDefinition = "longtext")
|
||||
private String flowGraph;
|
||||
@Column(nullable = false, columnDefinition = "longtext")
|
||||
private String flowGraph = "{}";
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import com.lanyuanxiaoyao.service.ai.web.entity.FlowTaskTemplate;
|
||||
import com.lanyuanxiaoyao.service.ai.web.repository.FlowTaskTemplateRepository;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@@ -12,4 +13,11 @@ public class FlowTaskTemplateService extends SimpleServiceSupport<FlowTaskTempla
|
||||
public FlowTaskTemplateService(FlowTaskTemplateRepository flowTaskTemplateRepository) {
|
||||
super(flowTaskTemplateRepository);
|
||||
}
|
||||
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void updateFlowGraph(Long id, String flowGraph) {
|
||||
FlowTaskTemplate template = detailOrThrow(id);
|
||||
template.setFlowGraph(flowGraph);
|
||||
save(template);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,19 +1,10 @@
|
||||
import {type Connection, type Node} from '@xyflow/react'
|
||||
import {uuid} from 'licia'
|
||||
import {expect, test} from 'vitest'
|
||||
import {
|
||||
atLeastOneEndNodeError,
|
||||
atLeastOneStartNodeError,
|
||||
checkAddConnection,
|
||||
checkAddNode,
|
||||
checkSave,
|
||||
hasCycleError,
|
||||
hasRedundantEdgeError,
|
||||
multiEndNodeError,
|
||||
multiStartNodeError,
|
||||
nodeToSelfError,
|
||||
sourceNodeNotFoundError,
|
||||
startNodeToEndNodeError,
|
||||
targetNodeNotFoundError,
|
||||
} from './FlowChecker.tsx'
|
||||
|
||||
@@ -29,9 +20,6 @@ const createNode = (id: string, type: string): Node => {
|
||||
}
|
||||
}
|
||||
|
||||
const createStartNode = (id: string): Node => createNode(id, 'start-node')
|
||||
const createEndNode = (id: string): Node => createNode(id, 'end-node')
|
||||
|
||||
const createConnection = function (source: string, target: string, sourceHandle: string | null = null, targetHandle: string | null = null): Connection {
|
||||
return {
|
||||
source,
|
||||
@@ -41,31 +29,13 @@ const createConnection = function (source: string, target: string, sourceHandle:
|
||||
}
|
||||
}
|
||||
|
||||
/* check add node */
|
||||
|
||||
test(multiStartNodeError().message, () => {
|
||||
expect(() => checkAddNode('start-node', [createStartNode(uuid())], [])).toThrowError(multiStartNodeError())
|
||||
})
|
||||
|
||||
test(multiEndNodeError().message, () => {
|
||||
expect(() => checkAddNode('end-node', [createEndNode(uuid())], [])).toThrowError(multiEndNodeError())
|
||||
})
|
||||
|
||||
/* check add connection */
|
||||
test(sourceNodeNotFoundError().message, () => {
|
||||
expect(() => checkAddConnection(createConnection('a', 'b'), [], []))
|
||||
})
|
||||
|
||||
test(targetNodeNotFoundError().message, () => {
|
||||
expect(() => checkAddConnection(createConnection('a', 'b'), [createStartNode('a')], []))
|
||||
})
|
||||
|
||||
test(startNodeToEndNodeError().message, () => {
|
||||
expect(() => checkAddConnection(
|
||||
createConnection('a', 'b'),
|
||||
[createStartNode('a'), createEndNode('b')],
|
||||
[]
|
||||
))
|
||||
expect(() => checkAddConnection(createConnection('a', 'b'), [createNode('a', 'normal-node')], []))
|
||||
})
|
||||
|
||||
test(nodeToSelfError().message, () => {
|
||||
@@ -90,24 +60,3 @@ test(hasCycleError().message, () => {
|
||||
checkAddConnection(JSON.parse('{\n "source": "yp-yYfKUzC",\n "sourceHandle": null,\n "target": "N4HQPN-NYZ",\n "targetHandle": null\n}'), nodes, edges)
|
||||
}).toThrowError(hasCycleError())
|
||||
})
|
||||
|
||||
test(hasRedundantEdgeError().message, () => {
|
||||
expect(() => {
|
||||
// language=JSON
|
||||
const {
|
||||
nodes,
|
||||
edges,
|
||||
} = JSON.parse('{\n "nodes": [\n {\n "id": "TCxPixrdkI",\n "type": "start-node",\n "position": {\n "x": -256,\n "y": 109.5\n },\n "data": {},\n "measured": {\n "width": 256,\n "height": 83\n },\n "selected": false,\n "dragging": false\n },\n {\n "id": "tGs78_ietp",\n "type": "llm-node",\n "position": {\n "x": 108,\n "y": -2.5\n },\n "data": {},\n "measured": {\n "width": 256,\n "height": 105\n },\n "selected": false,\n "dragging": false\n },\n {\n "id": "OeZdaU7LpY",\n "type": "llm-node",\n "position": {\n "x": 111,\n "y": 196\n },\n "data": {},\n "measured": {\n "width": 256,\n "height": 105\n },\n "selected": false,\n "dragging": false\n },\n {\n "id": "LjfoCYZo-E",\n "type": "knowledge-node",\n "position": {\n "x": 497.62196259607214,\n "y": -10.792497317791003\n },\n "data": {},\n "measured": {\n "width": 256,\n "height": 75\n },\n "selected": true,\n "dragging": false\n },\n {\n "id": "sQM_22GYB5",\n "type": "end-node",\n "position": {\n "x": 874.3164534765615,\n "y": 151.70316541496913\n },\n "data": {},\n "measured": {\n "width": 256,\n "height": 75\n },\n "selected": false,\n "dragging": false\n },\n {\n "id": "KpMH_xc3ZZ",\n "type": "llm-node",\n "position": {\n "x": 529.6286840434341,\n "y": 150.4721376669937\n },\n "data": {},\n "measured": {\n "width": 256,\n "height": 75\n },\n "selected": false,\n "dragging": false\n }\n ],\n "edges": [\n {\n "source": "TCxPixrdkI",\n "sourceHandle": "source",\n "target": "tGs78_ietp",\n "targetHandle": "target",\n "id": "xy-edge__TCxPixrdkIsource-tGs78_ietptarget"\n },\n {\n "source": "TCxPixrdkI",\n "sourceHandle": "source",\n "target": "OeZdaU7LpY",\n "targetHandle": "target",\n "id": "xy-edge__TCxPixrdkIsource-OeZdaU7LpYtarget"\n },\n {\n "source": "tGs78_ietp",\n "sourceHandle": "source",\n "target": "LjfoCYZo-E",\n "targetHandle": "target",\n "id": "xy-edge__tGs78_ietpsource-LjfoCYZo-Etarget"\n },\n {\n "source": "LjfoCYZo-E",\n "sourceHandle": "source",\n "target": "KpMH_xc3ZZ",\n "targetHandle": "target",\n "id": "xy-edge__LjfoCYZo-Esource-KpMH_xc3ZZtarget"\n },\n {\n "source": "OeZdaU7LpY",\n "sourceHandle": "source",\n "target": "KpMH_xc3ZZ",\n "targetHandle": "target",\n "id": "xy-edge__OeZdaU7LpYsource-KpMH_xc3ZZtarget"\n },\n {\n "source": "KpMH_xc3ZZ",\n "sourceHandle": "source",\n "target": "sQM_22GYB5",\n "targetHandle": "target",\n "id": "xy-edge__KpMH_xc3ZZsource-sQM_22GYB5target"\n }\n ],\n "data": {\n "tGs78_ietp": {\n "model": "qwen3",\n "outputs": {\n "text": {\n "type": "string"\n }\n },\n "systemPrompt": "你是个聪明人"\n },\n "OeZdaU7LpY": {\n "model": "qwen3",\n "outputs": {\n "text": {\n "type": "string"\n }\n },\n "systemPrompt": "你也是个聪明人"\n }\n }\n}')
|
||||
// language=JSON
|
||||
checkAddConnection(JSON.parse('{\n "source": "OeZdaU7LpY",\n "sourceHandle": "source",\n "target": "LjfoCYZo-E",\n "targetHandle": "target"\n}'), nodes, edges)
|
||||
}).toThrowError(hasRedundantEdgeError())
|
||||
})
|
||||
|
||||
/* check save */
|
||||
test(atLeastOneStartNodeError().message, () => {
|
||||
expect(() => checkSave([], [], {})).toThrowError(atLeastOneStartNodeError())
|
||||
})
|
||||
|
||||
test(atLeastOneEndNodeError().message, () => {
|
||||
expect(() => checkSave([createStartNode(uuid())], [], {})).toThrowError(atLeastOneEndNodeError())
|
||||
})
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import {type Connection, type Edge, getConnectedEdges, getIncomers, getOutgoers, type Node} from '@xyflow/react'
|
||||
import {clone, find, findIdx, isEqual, lpad, toStr, uuid} from 'licia'
|
||||
import {type Connection, type Edge, getOutgoers, type Node} from '@xyflow/react'
|
||||
import {find, isEmpty, isEqual, lpad, toStr} from 'licia'
|
||||
|
||||
export class CheckError extends Error {
|
||||
readonly id: string
|
||||
@@ -17,28 +17,16 @@ export class CheckError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
export const multiStartNodeError = () => new CheckError(100, '只能存在1个开始节点')
|
||||
export const multiEndNodeError = () => new CheckError(101, '只能存在1个结束节点')
|
||||
|
||||
const getNodeById = (id: string, nodes: Node[]) => find(nodes, (n: Node) => isEqual(n.id, id))
|
||||
|
||||
// @ts-ignore
|
||||
export const checkAddNode: (type: string, nodes: Node[], edges: Edge[]) => void = (type, nodes, edges) => {
|
||||
if (isEqual(type, 'start-node') && findIdx(nodes, (node: Node) => isEqual(type, node.type)) > -1) {
|
||||
throw multiStartNodeError()
|
||||
}
|
||||
if (isEqual(type, 'end-node') && findIdx(nodes, (node: Node) => isEqual(type, node.type)) > -1) {
|
||||
throw multiEndNodeError()
|
||||
}
|
||||
}
|
||||
|
||||
export const sourceNodeNotFoundError = () => new CheckError(200, '连线起始节点未找到')
|
||||
export const targetNodeNotFoundError = () => new CheckError(201, '连线目标节点未找到')
|
||||
export const startNodeToEndNodeError = () => new CheckError(202, '开始节点不能直连结束节点')
|
||||
export const nodeToSelfError = () => new CheckError(203, '节点不能直连自身')
|
||||
export const hasCycleError = () => new CheckError(204, '禁止流程循环')
|
||||
export const nodeNotOnlyToEndNode = () => new CheckError(206, '直连结束节点的节点不允许连接其他节点')
|
||||
export const hasRedundantEdgeError = () => new CheckError(207, '禁止出现冗余边')
|
||||
|
||||
const hasCycle = (sourceNode: Node, targetNode: Node, nodes: Node[], edges: Edge[], visited = new Set<string>()) => {
|
||||
if (visited.has(targetNode.id)) return false
|
||||
@@ -49,189 +37,6 @@ const hasCycle = (sourceNode: Node, targetNode: Node, nodes: Node[], edges: Edge
|
||||
}
|
||||
}
|
||||
|
||||
/* 摘自Dify的流程合法性判断 */
|
||||
|
||||
type ParallelInfoItem = {
|
||||
parallelNodeId: string
|
||||
depth: number
|
||||
isBranch?: boolean
|
||||
}
|
||||
|
||||
type NodeParallelInfo = {
|
||||
parallelNodeId: string
|
||||
edgeHandleId: string
|
||||
depth: number
|
||||
}
|
||||
|
||||
type NodeHandle = {
|
||||
node: Node
|
||||
handle: string
|
||||
}
|
||||
|
||||
type NodeStreamInfo = {
|
||||
upstreamNodes: Set<string>
|
||||
downstreamEdges: Set<string>
|
||||
}
|
||||
|
||||
const groupBy = (array: Record<string, any>[], iteratee: string) => {
|
||||
const result: Record<string, any[]> = {}
|
||||
for (const item of array) {
|
||||
// 获取属性值并转换为字符串键
|
||||
const key = item[iteratee]
|
||||
if (!result[key]) {
|
||||
result[key] = []
|
||||
}
|
||||
result[key].push(item)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// @ts-ignore
|
||||
export const getParallelInfo = (nodes: Node[], edges: Edge[], parentNodeId?: string) => {
|
||||
// 等到有子图的时候再考虑
|
||||
/*if (parentNodeId) {
|
||||
const parentNode = nodes.find(node => node.id === parentNodeId)
|
||||
if (!parentNode)
|
||||
throw new Error('Parent node not found')
|
||||
|
||||
startNode = nodes.find(node => node.id === (parentNode.data as (IterationNodeType | LoopNodeType)).start_node_id)
|
||||
}
|
||||
else {
|
||||
startNode = nodes.find(node => isEqual(node.type, 'start_node'))
|
||||
}*/
|
||||
let startNode = nodes.find(node => isEqual(node.type, 'start-node'))
|
||||
if (!startNode)
|
||||
throw new Error('Start node not found')
|
||||
|
||||
const parallelList = [] as ParallelInfoItem[]
|
||||
const nextNodeHandles = [{node: startNode, handle: 'source'}]
|
||||
let hasAbnormalEdges = false
|
||||
|
||||
const traverse = (firstNodeHandle: NodeHandle) => {
|
||||
const nodeEdgesSet = {} as Record<string, Set<string>>
|
||||
const totalEdgesSet = new Set<string>()
|
||||
const nextHandles = [firstNodeHandle]
|
||||
const streamInfo = {} as Record<string, NodeStreamInfo>
|
||||
const parallelListItem = {
|
||||
parallelNodeId: '',
|
||||
depth: 0,
|
||||
} as ParallelInfoItem
|
||||
const nodeParallelInfoMap = {} as Record<string, NodeParallelInfo>
|
||||
nodeParallelInfoMap[firstNodeHandle.node.id] = {
|
||||
parallelNodeId: '',
|
||||
edgeHandleId: '',
|
||||
depth: 0,
|
||||
}
|
||||
|
||||
while (nextHandles.length) {
|
||||
const currentNodeHandle = nextHandles.shift()!
|
||||
const {node: currentNode, handle: currentHandle = 'source'} = currentNodeHandle
|
||||
const currentNodeHandleKey = currentNode.id
|
||||
const connectedEdges = edges.filter(edge => edge.source === currentNode.id && edge.sourceHandle === currentHandle)
|
||||
const connectedEdgesLength = connectedEdges.length
|
||||
const outgoers = nodes.filter(node => connectedEdges.some(edge => edge.target === node.id))
|
||||
const incomers = getIncomers(currentNode, nodes, edges)
|
||||
|
||||
if (!streamInfo[currentNodeHandleKey]) {
|
||||
streamInfo[currentNodeHandleKey] = {
|
||||
upstreamNodes: new Set<string>(),
|
||||
downstreamEdges: new Set<string>(),
|
||||
}
|
||||
}
|
||||
|
||||
if (nodeEdgesSet[currentNodeHandleKey]?.size > 0 && incomers.length > 1) {
|
||||
const newSet = new Set<string>()
|
||||
for (const item of totalEdgesSet) {
|
||||
if (!streamInfo[currentNodeHandleKey].downstreamEdges.has(item))
|
||||
newSet.add(item)
|
||||
}
|
||||
if (isEqual(nodeEdgesSet[currentNodeHandleKey], newSet)) {
|
||||
parallelListItem.depth = nodeParallelInfoMap[currentNode.id].depth
|
||||
nextNodeHandles.push({node: currentNode, handle: currentHandle})
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if (nodeParallelInfoMap[currentNode.id].depth > parallelListItem.depth)
|
||||
parallelListItem.depth = nodeParallelInfoMap[currentNode.id].depth
|
||||
|
||||
outgoers.forEach((outgoer) => {
|
||||
const outgoerConnectedEdges = getConnectedEdges([outgoer], edges).filter(edge => edge.source === outgoer.id)
|
||||
const sourceEdgesGroup = groupBy(outgoerConnectedEdges, 'sourceHandle')
|
||||
const incomers = getIncomers(outgoer, nodes, edges)
|
||||
|
||||
if (outgoers.length > 1 && incomers.length > 1)
|
||||
hasAbnormalEdges = true
|
||||
|
||||
Object.keys(sourceEdgesGroup).forEach((sourceHandle) => {
|
||||
nextHandles.push({node: outgoer, handle: sourceHandle})
|
||||
})
|
||||
if (!outgoerConnectedEdges.length)
|
||||
nextHandles.push({node: outgoer, handle: 'source'})
|
||||
|
||||
const outgoerKey = outgoer.id
|
||||
if (!nodeEdgesSet[outgoerKey])
|
||||
nodeEdgesSet[outgoerKey] = new Set<string>()
|
||||
|
||||
if (nodeEdgesSet[currentNodeHandleKey]) {
|
||||
for (const item of nodeEdgesSet[currentNodeHandleKey])
|
||||
nodeEdgesSet[outgoerKey].add(item)
|
||||
}
|
||||
|
||||
if (!streamInfo[outgoerKey]) {
|
||||
streamInfo[outgoerKey] = {
|
||||
upstreamNodes: new Set<string>(),
|
||||
downstreamEdges: new Set<string>(),
|
||||
}
|
||||
}
|
||||
|
||||
if (!nodeParallelInfoMap[outgoer.id]) {
|
||||
nodeParallelInfoMap[outgoer.id] = {
|
||||
...nodeParallelInfoMap[currentNode.id],
|
||||
}
|
||||
}
|
||||
|
||||
if (connectedEdgesLength > 1) {
|
||||
const edge = connectedEdges.find(edge => edge.target === outgoer.id)!
|
||||
nodeEdgesSet[outgoerKey].add(edge.id)
|
||||
totalEdgesSet.add(edge.id)
|
||||
|
||||
streamInfo[currentNodeHandleKey].downstreamEdges.add(edge.id)
|
||||
streamInfo[outgoerKey].upstreamNodes.add(currentNodeHandleKey)
|
||||
|
||||
for (const item of streamInfo[currentNodeHandleKey].upstreamNodes)
|
||||
streamInfo[item].downstreamEdges.add(edge.id)
|
||||
|
||||
if (!parallelListItem.parallelNodeId)
|
||||
parallelListItem.parallelNodeId = currentNode.id
|
||||
|
||||
const prevDepth = nodeParallelInfoMap[currentNode.id].depth + 1
|
||||
const currentDepth = nodeParallelInfoMap[outgoer.id].depth
|
||||
|
||||
nodeParallelInfoMap[outgoer.id].depth = Math.max(prevDepth, currentDepth)
|
||||
} else {
|
||||
for (const item of streamInfo[currentNodeHandleKey].upstreamNodes)
|
||||
streamInfo[outgoerKey].upstreamNodes.add(item)
|
||||
|
||||
nodeParallelInfoMap[outgoer.id].depth = nodeParallelInfoMap[currentNode.id].depth
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
parallelList.push(parallelListItem)
|
||||
}
|
||||
|
||||
while (nextNodeHandles.length) {
|
||||
const nodeHandle = nextNodeHandles.shift()!
|
||||
traverse(nodeHandle)
|
||||
}
|
||||
|
||||
return {
|
||||
parallelList,
|
||||
hasAbnormalEdges,
|
||||
}
|
||||
}
|
||||
|
||||
export const checkAddConnection: (connection: Connection, nodes: Node[], edges: Edge[]) => void = (connection, nodes, edges) => {
|
||||
let sourceNode = getNodeById(connection.source, nodes)
|
||||
if (!sourceNode) {
|
||||
@@ -241,10 +46,6 @@ export const checkAddConnection: (connection: Connection, nodes: Node[], edges:
|
||||
if (!targetNode) {
|
||||
throw targetNodeNotFoundError()
|
||||
}
|
||||
// 禁止短路整个流程
|
||||
if (isEqual('start-node', sourceNode.type) && isEqual('end-node', targetNode.type)) {
|
||||
throw startNodeToEndNodeError()
|
||||
}
|
||||
|
||||
// 禁止流程出现环,必须是有向无环图
|
||||
if (isEqual(sourceNode.id, targetNode.id)) {
|
||||
@@ -253,22 +54,25 @@ export const checkAddConnection: (connection: Connection, nodes: Node[], edges:
|
||||
throw hasCycleError()
|
||||
}
|
||||
|
||||
let newEdges = [...clone(edges), {...connection, id: uuid()}]
|
||||
let {hasAbnormalEdges} = getParallelInfo(nodes, newEdges)
|
||||
if (hasAbnormalEdges) {
|
||||
throw hasRedundantEdgeError()
|
||||
}
|
||||
// let newEdges = [...clone(edges), {...connection, id: uuid()}]
|
||||
// let {hasAbnormalEdges} = getParallelInfo(nodes, newEdges)
|
||||
// if (hasAbnormalEdges) {
|
||||
// throw hasRedundantEdgeError()
|
||||
// }
|
||||
}
|
||||
|
||||
export const atLeastOneStartNodeError = () => new CheckError(300, '至少存在1个开始节点')
|
||||
export const atLeastOneEndNodeError = () => new CheckError(301, '至少存在1个结束节点')
|
||||
export const atLeastOneNode = () => new CheckError(300, '至少包含一个节点')
|
||||
export const hasUnfinishedNode = (nodeId: string) => new CheckError(301, `存在尚未配置完成的节点: ${nodeId}`)
|
||||
|
||||
// @ts-ignore
|
||||
export const checkSave: (nodes: Node[], edges: Edge[], data: any) => void = (nodes, edges, data) => {
|
||||
if (nodes.filter(n => isEqual('start-node', n.type)).length < 1) {
|
||||
throw atLeastOneStartNodeError()
|
||||
if (isEmpty(nodes)) {
|
||||
throw atLeastOneNode()
|
||||
}
|
||||
if (nodes.filter(n => isEqual('end-node', n.type)).length < 1) {
|
||||
throw atLeastOneEndNodeError()
|
||||
|
||||
for (let node of nodes) {
|
||||
if (!data[node.id] || !data[node.id]?.finished) {
|
||||
throw hasUnfinishedNode(node.id)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import {PlusCircleFilled, SaveFilled} from '@ant-design/icons'
|
||||
import {PlusCircleFilled, RollbackOutlined, SaveFilled} from '@ant-design/icons'
|
||||
import {
|
||||
Background,
|
||||
BackgroundVariant,
|
||||
@@ -9,23 +9,22 @@ import {
|
||||
type NodeProps,
|
||||
ReactFlow
|
||||
} from '@xyflow/react'
|
||||
import {useMount} from 'ahooks'
|
||||
import type {Schema} from 'amis'
|
||||
import {Button, Drawer, Dropdown, message, Space} from 'antd'
|
||||
import {Button, Drawer, Dropdown, message, Popconfirm, Space} from 'antd'
|
||||
import {arrToMap, find, isEqual, isNil, randomId} from 'licia'
|
||||
import {type JSX, type MemoExoticComponent, useState} from 'react'
|
||||
import {type JSX, type MemoExoticComponent, useEffect, useState} from 'react'
|
||||
import styled from 'styled-components'
|
||||
import '@xyflow/react/dist/style.css'
|
||||
import {amisRender, commonInfo, horizontalFormOptions} from '../../util/amis.tsx'
|
||||
import {checkAddConnection, checkAddNode, checkSave} from './FlowChecker.tsx'
|
||||
import CodeNode from './node/CodeNode.tsx'
|
||||
import EndNode from './node/EndNode.tsx'
|
||||
import OutputNode from './node/OutputNode.tsx'
|
||||
import KnowledgeNode from './node/KnowledgeNode.tsx'
|
||||
import LlmNode from './node/LlmNode.tsx'
|
||||
import StartNode from './node/StartNode.tsx'
|
||||
import SwitchNode from './node/SwitchNode.tsx'
|
||||
import {useDataStore} from './store/DataStore.ts'
|
||||
import {useFlowStore} from './store/FlowStore.ts'
|
||||
import {useNavigate} from 'react-router'
|
||||
|
||||
const FlowableDiv = styled.div`
|
||||
height: 100%;
|
||||
@@ -72,6 +71,7 @@ export type FlowEditorProps = {
|
||||
}
|
||||
|
||||
function FlowEditor(props: FlowEditorProps) {
|
||||
const navigate = useNavigate()
|
||||
const [messageApi, contextHolder] = message.useMessage()
|
||||
const [nodeDef] = useState<{
|
||||
key: string,
|
||||
@@ -79,14 +79,9 @@ function FlowEditor(props: FlowEditorProps) {
|
||||
component: MemoExoticComponent<(props: NodeProps) => JSX.Element>
|
||||
}[]>([
|
||||
{
|
||||
key: 'start-node',
|
||||
name: '开始',
|
||||
component: StartNode,
|
||||
},
|
||||
{
|
||||
key: 'end-node',
|
||||
name: '结束',
|
||||
component: EndNode,
|
||||
key: 'output-node',
|
||||
name: '输出',
|
||||
component: OutputNode,
|
||||
},
|
||||
{
|
||||
key: 'llm-node',
|
||||
@@ -145,7 +140,13 @@ function FlowEditor(props: FlowEditorProps) {
|
||||
actionType: 'custom',
|
||||
// @ts-ignore
|
||||
script: (context, action, event) => {
|
||||
setDataById(id, context.props.data)
|
||||
setDataById(
|
||||
id,
|
||||
{
|
||||
...context.props.data,
|
||||
finished: true,
|
||||
}
|
||||
)
|
||||
setOpen(false)
|
||||
},
|
||||
},
|
||||
@@ -202,7 +203,7 @@ function FlowEditor(props: FlowEditorProps) {
|
||||
editNode,
|
||||
}
|
||||
|
||||
useMount(() => {
|
||||
useEffect(() => {
|
||||
// language=JSON
|
||||
// let initialData = JSON.parse('{"nodes":[{"id":"TCxPixrdkI","type":"start-node","position":{"x":-256,"y":109.5},"data":{},"measured":{"width":256,"height":83},"selected":false,"dragging":false},{"id":"tGs78_ietp","type":"llm-node","position":{"x":108,"y":-2.5},"data":{},"measured":{"width":256,"height":105},"selected":false,"dragging":false},{"id":"OeZdaU7LpY","type":"llm-node","position":{"x":111,"y":196},"data":{},"measured":{"width":256,"height":105},"selected":false,"dragging":false},{"id":"LjfoCYZo-E","type":"knowledge-node","position":{"x":497.62196259607214,"y":-10.792497317791003},"data":{},"measured":{"width":256,"height":75},"selected":false,"dragging":false},{"id":"sQM_22GYB5","type":"end-node","position":{"x":874.3164534765615,"y":151.70316541496913},"data":{},"measured":{"width":256,"height":75},"selected":false,"dragging":false},{"id":"KpMH_xc3ZZ","type":"llm-node","position":{"x":529.6286840434341,"y":150.4721376669937},"data":{},"measured":{"width":256,"height":75},"selected":false,"dragging":false},{"id":"pOrR6EMVbe","type":"switch-node","position":{"x":110.33793030183864,"y":373.9551529987239},"data":{},"measured":{"width":256,"height":157},"selected":false,"dragging":false}],"edges":[{"source":"TCxPixrdkI","sourceHandle":"source","target":"tGs78_ietp","targetHandle":"target","id":"xy-edge__TCxPixrdkIsource-tGs78_ietptarget"},{"source":"TCxPixrdkI","sourceHandle":"source","target":"OeZdaU7LpY","targetHandle":"target","id":"xy-edge__TCxPixrdkIsource-OeZdaU7LpYtarget"},{"source":"tGs78_ietp","sourceHandle":"source","target":"LjfoCYZo-E","targetHandle":"target","id":"xy-edge__tGs78_ietpsource-LjfoCYZo-Etarget"},{"source":"LjfoCYZo-E","sourceHandle":"source","target":"KpMH_xc3ZZ","targetHandle":"target","id":"xy-edge__LjfoCYZo-Esource-KpMH_xc3ZZtarget"},{"source":"OeZdaU7LpY","sourceHandle":"source","target":"KpMH_xc3ZZ","targetHandle":"target","id":"xy-edge__OeZdaU7LpYsource-KpMH_xc3ZZtarget"},{"source":"KpMH_xc3ZZ","sourceHandle":"source","target":"sQM_22GYB5","targetHandle":"target","id":"xy-edge__KpMH_xc3ZZsource-sQM_22GYB5target"},{"source":"TCxPixrdkI","sourceHandle":"source","target":"pOrR6EMVbe","id":"xy-edge__TCxPixrdkIsource-pOrR6EMVbe"},{"source":"pOrR6EMVbe","sourceHandle":"3","target":"sQM_22GYB5","targetHandle":"target","id":"xy-edge__pOrR6EMVbe3-sQM_22GYB5target"},{"source":"pOrR6EMVbe","sourceHandle":"1","target":"KpMH_xc3ZZ","targetHandle":"target","id":"xy-edge__pOrR6EMVbe1-KpMH_xc3ZZtarget"}],"data":{"tGs78_ietp":{"model":"qwen3","outputs":{"text":{"type":"string"}},"systemPrompt":"你是个聪明人"},"OeZdaU7LpY":{"model":"qwen3","outputs":{"text":{"type":"string"}},"systemPrompt":"你也是个聪明人"}}}')
|
||||
// let initialData: any = {}
|
||||
@@ -217,7 +218,7 @@ function FlowEditor(props: FlowEditorProps) {
|
||||
}
|
||||
setNodes(initialNodes)
|
||||
setEdges(initialEdges)
|
||||
})
|
||||
}, [props.graphData])
|
||||
|
||||
return (
|
||||
<FlowableDiv>
|
||||
@@ -250,6 +251,16 @@ function FlowEditor(props: FlowEditorProps) {
|
||||
新增节点
|
||||
</Button>
|
||||
</Dropdown>
|
||||
<Popconfirm
|
||||
title="返回上一页"
|
||||
description="未保存的流程图将会被丢弃,确认是否返回"
|
||||
onConfirm={() => navigate(-1)}
|
||||
>
|
||||
<Button type="default">
|
||||
<RollbackOutlined/>
|
||||
返回
|
||||
</Button>
|
||||
</Popconfirm>
|
||||
<Button type="primary" onClick={() => {
|
||||
try {
|
||||
if (commonInfo.debug) {
|
||||
|
||||
@@ -2,12 +2,12 @@ import type {NodeProps} from '@xyflow/react'
|
||||
import AmisNode, {outputsFormColumns} from './AmisNode.tsx'
|
||||
import React from 'react'
|
||||
|
||||
const EndNode = (props: NodeProps) => AmisNode({
|
||||
const OutputNode = (props: NodeProps) => AmisNode({
|
||||
nodeProps: props,
|
||||
type: 'end',
|
||||
defaultNodeName: '结束节点',
|
||||
defaultNodeName: '输出节点',
|
||||
defaultNodeDescription: '定义输出变量',
|
||||
columnSchema: outputsFormColumns(true),
|
||||
})
|
||||
|
||||
export default React.memo(EndNode)
|
||||
export default React.memo(OutputNode)
|
||||
@@ -1,68 +0,0 @@
|
||||
import type {NodeProps} from '@xyflow/react'
|
||||
import {Tag} from 'antd'
|
||||
import {each} from 'licia'
|
||||
import React, {type JSX} from 'react'
|
||||
import {horizontalFormOptions} from '../../../util/amis.tsx'
|
||||
import AmisNode from './AmisNode.tsx'
|
||||
|
||||
const typeMap: Record<string, string> = {
|
||||
text: '文本',
|
||||
number: '数字',
|
||||
files: '文件',
|
||||
}
|
||||
|
||||
const StartNode = (props: NodeProps) => AmisNode({
|
||||
nodeProps: props,
|
||||
type: 'start',
|
||||
defaultNodeName: '开始节点',
|
||||
defaultNodeDescription: '定义输入变量',
|
||||
extraNodeDescription: nodeData => {
|
||||
const variables: JSX.Element[] = []
|
||||
const inputs = (nodeData?.inputs ?? {}) as Record<string, { type: string, description: string }>
|
||||
each(inputs, (value, key) => {
|
||||
variables.push(
|
||||
<div className="mt-1 flex justify-between" key={key}>
|
||||
<span>{key}</span>
|
||||
<Tag className="m-0" color="blue">{typeMap[value.type]}</Tag>
|
||||
</div>,
|
||||
)
|
||||
})
|
||||
return (
|
||||
<div className="mt-2">
|
||||
{...variables}
|
||||
</div>
|
||||
)
|
||||
},
|
||||
columnSchema: [
|
||||
{
|
||||
type: 'input-kvs',
|
||||
name: 'inputs',
|
||||
label: '输入变量',
|
||||
addButtonText: '新增入参',
|
||||
draggable: false,
|
||||
keyItem: {
|
||||
label: '参数名称',
|
||||
...horizontalFormOptions(),
|
||||
},
|
||||
valueItems: [
|
||||
{
|
||||
...horizontalFormOptions(),
|
||||
type: 'input-text',
|
||||
name: 'description',
|
||||
label: '参数描述',
|
||||
},
|
||||
{
|
||||
...horizontalFormOptions(),
|
||||
type: 'select',
|
||||
name: 'type',
|
||||
label: '参数类型',
|
||||
required: true,
|
||||
selectFirst: true,
|
||||
options: Object.keys(typeMap).map(key => ({label: typeMap[key], value: key})),
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
})
|
||||
|
||||
export default React.memo(StartNode)
|
||||
@@ -1,6 +1,6 @@
|
||||
import React, {useEffect, useState} from 'react'
|
||||
import React, {useState} from 'react'
|
||||
import styled from 'styled-components'
|
||||
import {useParams, useNavigate} from 'react-router'
|
||||
import {useNavigate, useParams} from 'react-router'
|
||||
import {useMount} from 'ahooks'
|
||||
import axios from 'axios'
|
||||
import {commonInfo} from '../../../../util/amis.tsx'
|
||||
@@ -12,7 +12,7 @@ const FlowTaskTemplateFlowEditDiv = styled.div`
|
||||
const FlowTaskTemplateFlowEdit: React.FC = () => {
|
||||
const navigate = useNavigate()
|
||||
const {template_id} = useParams()
|
||||
const [graphData, setGraphData] = useState<GraphData>()
|
||||
const [graphData, setGraphData] = useState<GraphData>({nodes: [], edges: [], data: {}})
|
||||
|
||||
useMount(async () => {
|
||||
let {data} = await axios.get(
|
||||
@@ -21,13 +21,24 @@ const FlowTaskTemplateFlowEdit: React.FC = () => {
|
||||
headers: commonInfo.authorizationHeaders
|
||||
}
|
||||
)
|
||||
setGraphData(data?.data?.flowGraph)
|
||||
})
|
||||
|
||||
return (
|
||||
<FlowTaskTemplateFlowEditDiv className="h-full w-full">
|
||||
<FlowEditor
|
||||
graphData={graphData}
|
||||
onGraphDataChange={data => {
|
||||
onGraphDataChange={async data => {
|
||||
await axios.post(
|
||||
`${commonInfo.baseAiUrl}/flow_task/template/update_flow_graph`,
|
||||
{
|
||||
id: template_id,
|
||||
graph: data
|
||||
},
|
||||
{
|
||||
headers: commonInfo.authorizationHeaders
|
||||
}
|
||||
)
|
||||
navigate(-1)
|
||||
}}
|
||||
/>
|
||||
|
||||
Reference in New Issue
Block a user