32 Commits

Author SHA1 Message Date
v-zhangjc9
68e54d5110 feat(ai-web): 尝试自建流程引擎 2025-06-30 19:15:19 +08:00
v-zhangjc9
5f133fbfc3 refactor(web): 无聊的改动 2025-06-30 17:15:35 +08:00
v-zhangjc9
d28fbbbba8 fix(web): 优化冗余边检测导致分支节点不正常 2025-06-30 11:14:45 +08:00
v-zhangjc9
67f41c08a0 feat(web): 优化冗余边检测 2025-06-30 10:41:40 +08:00
111ca49815 feat(web): 引入dify的流程检查算法 2025-06-30 00:12:51 +08:00
779fd0eb18 feat(web): 增加分支节点,增加流程检查的测试 2025-06-29 19:02:19 +08:00
8884495a89 fix(ai-web): 恢复配置文件 2025-06-29 14:27:42 +08:00
d08a6babbe feat(ai-web): 增加任务和任务模板 2025-06-28 21:08:31 +08:00
9a3375bd03 fix(ai-web): 修复跨域错误 2025-06-28 17:23:19 +08:00
v-zhangjc9
2c808a5bc9 feat(web): 增加节点的参数展示 2025-06-27 11:31:02 +08:00
v-zhangjc9
6e667c45e1 feat(web): 节点增加入参变量 2025-06-27 10:04:48 +08:00
v-zhangjc9
635c6537ed feat(web): 实现EL表达式的解析 2025-06-27 10:04:00 +08:00
v-zhangjc9
d6b70b1750 feat(web): 尝试增加并行节点解决解析问题 2025-06-26 20:48:49 +08:00
v-zhangjc9
c92a374591 feat(web): 优化UI展示 2025-06-26 20:48:20 +08:00
v-zhangjc9
a2aba82b6e feat(web): 调整节点入参形式 2025-06-26 14:38:09 +08:00
873c1a1d20 feat(web): 增加EL表达式转换 2025-06-26 00:31:04 +08:00
v-zhangjc9
f6bd7e52e1 feat(ai-web): 尝试解析流程图 2025-06-25 17:55:05 +08:00
v-zhangjc9
6f7f7cea67 feat(web): 增加代码节点 2025-06-25 17:54:43 +08:00
v-zhangjc9
33df256863 feat(web): 增加知识库节点 2025-06-25 17:25:50 +08:00
v-zhangjc9
3a51d1e33f feat(web): 升级依赖 2025-06-25 12:36:43 +08:00
v-zhangjc9
d3c7457889 fix(web): 调整样式 2025-06-25 10:43:26 +08:00
2d2eaafcd4 feat(web): 优化样式 2025-06-25 00:04:27 +08:00
v-zhangjc9
566dfef208 feat(web): 增加流程图连线限制 2025-06-24 14:07:07 +08:00
1cba0f4422 feat(web): 完成流程图外部加载 2025-06-24 10:44:18 +08:00
ab56385c8a feat(web): 增加节点输出编辑 2025-06-24 10:15:08 +08:00
b58c34443f feat(web): 增加跨站导航列表 2025-06-24 09:29:48 +08:00
53638a8a6d feat(web): 优化流程界面显示 2025-06-23 23:55:31 +08:00
dc55605c99 feat(web): 正式提取流程设计能力到AI目录下,做代码拆分 2025-06-23 22:51:40 +08:00
7345774258 feat(web): 增加编辑侧边栏关闭时保存节点数据 2025-06-23 22:27:23 +08:00
fcf5f8ad18 feat(web): 优化编辑界面 2025-06-23 22:27:23 +08:00
v-zhangjc9
b53ee57dc3 feat(web): 替换amis渲染,amis渲染太慢,导致卡顿 2025-06-23 22:27:23 +08:00
v-zhangjc9
b916acb1c3 feat(web): 增加流程定义基本能力 2025-06-23 22:27:23 +08:00
45 changed files with 3021 additions and 376 deletions

View File

@@ -155,6 +155,11 @@
<artifactId>liteflow-spring-boot-starter</artifactId>
<version>2.13.2</version>
</dependency>
<dependency>
<groupId>com.yomahub</groupId>
<artifactId>liteflow-el-builder</artifactId>
<version>2.13.2</version>
</dependency>
<dependency>
<groupId>org.noear</groupId>
<artifactId>solon-ai</artifactId>

View File

@@ -1,7 +1,5 @@
package com.lanyuanxiaoyao.service.configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
@@ -13,6 +11,9 @@ import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
/**
* @author lanyuanxiaoyao
@@ -21,17 +22,31 @@ import org.springframework.security.web.SecurityFilterChain;
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public CorsFilter corsFilter() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowCredentials(true);
configuration.addAllowedOriginPattern("*");
configuration.addAllowedHeader("*");
configuration.addAllowedMethod("*");
configuration.setMaxAge(7200L);
configuration.setAllowPrivateNetwork(true);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return new CorsFilter(source);
}
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
return http.authorizeHttpRequests(
registry -> registry
.requestMatchers(HttpMethod.OPTIONS, "/**")
.permitAll()
.anyRequest()
.authenticated()
registry -> registry
.requestMatchers(HttpMethod.OPTIONS, "/**")
.permitAll()
.anyRequest()
.authenticated()
)
.httpBasic(Customizer.withDefaults())
.cors(AbstractHttpConfigurer::disable)
.cors(Customizer.withDefaults())
.csrf(AbstractHttpConfigurer::disable)
.formLogin(AbstractHttpConfigurer::disable)
.build();

View File

@@ -62,6 +62,10 @@
<groupId>com.yomahub</groupId>
<artifactId>liteflow-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>com.yomahub</groupId>
<artifactId>liteflow-el-builder</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-tika-document-reader</artifactId>

View File

@@ -0,0 +1,93 @@
package com.lanyuanxiaoyao.service.ai.web.controller.task;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lanyuanxiaoyao.service.ai.web.base.controller.SimpleControllerSupport;
import com.lanyuanxiaoyao.service.ai.web.base.entity.SimpleItem;
import com.lanyuanxiaoyao.service.ai.web.entity.FlowTask;
import com.lanyuanxiaoyao.service.ai.web.entity.FlowTaskTemplate;
import com.lanyuanxiaoyao.service.ai.web.service.task.FlowTaskService;
import com.lanyuanxiaoyao.service.ai.web.service.task.FlowTaskTemplateService;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j;
import org.mapstruct.Context;
import org.mapstruct.Mapping;
import org.mapstruct.factory.Mappers;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@Slf4j
@RestController
@RequestMapping("flow_task")
public class TaskController extends SimpleControllerSupport<FlowTask, TaskController.SaveItem, TaskController.ListItem, TaskController.DetailItem> {
private final FlowTaskTemplateService flowTaskTemplateService;
private final ObjectMapper mapper;
public TaskController(FlowTaskService flowTaskService, FlowTaskTemplateService flowTaskTemplateService, Jackson2ObjectMapperBuilder builder) {
super(flowTaskService);
this.flowTaskTemplateService = flowTaskTemplateService;
this.mapper = builder.build();
}
@Override
protected SaveItemMapper<FlowTask, SaveItem> saveItemMapper() {
return item -> {
FlowTask task = new FlowTask();
FlowTaskTemplate template = flowTaskTemplateService.detailOrThrow(item.getTemplateId());
task.setTemplate(template);
task.setInput(mapper.writeValueAsString(item.getInput()));
return task;
};
}
@Override
protected ListItemMapper<FlowTask, ListItem> listItemMapper() {
ListItem.Mapper map = Mappers.getMapper(ListItem.Mapper.class);
return task -> map.from(task, mapper);
}
@Override
protected DetailItemMapper<FlowTask, DetailItem> detailItemMapper() {
DetailItem.Mapper map = Mappers.getMapper(DetailItem.Mapper.class);
return task -> map.from(task, mapper);
}
@Data
public static final class SaveItem {
private Long templateId;
private Object input;
}
@Data
@EqualsAndHashCode(callSuper = true)
public static class ListItem extends SimpleItem {
private Long templateId;
private Object input;
private FlowTask.Status status;
@org.mapstruct.Mapper
public static abstract class Mapper {
@Mapping(target = "templateId", source = "task.template.id")
public abstract ListItem from(FlowTask task, @Context ObjectMapper mapper) throws JsonProcessingException;
protected Object mapInput(String input, @Context ObjectMapper mapper) throws JsonProcessingException {
return mapper.readValue(input, Object.class);
}
}
}
@Data
@EqualsAndHashCode(callSuper = true)
public static class DetailItem extends ListItem {
private String error;
private String result;
@org.mapstruct.Mapper
public static abstract class Mapper extends ListItem.Mapper {
@Mapping(target = "templateId", source = "task.template.id")
public abstract DetailItem from(FlowTask task, @Context ObjectMapper mapper) throws JsonProcessingException;
}
}
}

View File

@@ -0,0 +1,72 @@
package com.lanyuanxiaoyao.service.ai.web.controller.task;
import com.lanyuanxiaoyao.service.ai.web.base.controller.SimpleControllerSupport;
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;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j;
import org.mapstruct.factory.Mappers;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@Slf4j
@RestController
@RequestMapping("flow_task/template")
public class TaskTemplateController extends SimpleControllerSupport<FlowTaskTemplate, TaskTemplateController.SaveItem, TaskTemplateController.ListItem, TaskTemplateController.DetailItem> {
public TaskTemplateController(FlowTaskTemplateService flowTaskTemplateService) {
super(flowTaskTemplateService);
}
@Override
protected SaveItemMapper<FlowTaskTemplate, SaveItem> saveItemMapper() {
return Mappers.getMapper(SaveItem.Mapper.class);
}
@Override
protected ListItemMapper<FlowTaskTemplate, ListItem> listItemMapper() {
return Mappers.getMapper(ListItem.Mapper.class);
}
@Override
protected DetailItemMapper<FlowTaskTemplate, DetailItem> detailItemMapper() {
return Mappers.getMapper(DetailItem.Mapper.class);
}
@Data
public static final class SaveItem {
private String name;
private String description;
private String inputSchema;
private String flow;
@org.mapstruct.Mapper
public interface Mapper extends SaveItemMapper<FlowTaskTemplate, SaveItem> {
}
}
@Data
@EqualsAndHashCode(callSuper = true)
public static class ListItem extends SimpleItem {
private String name;
private String description;
@org.mapstruct.Mapper
public interface Mapper extends ListItemMapper<FlowTaskTemplate, ListItem> {
}
}
@Data
@EqualsAndHashCode(callSuper = true)
public static class DetailItem extends SimpleItem {
private String name;
private String description;
private String inputSchema;
private String flow;
@org.mapstruct.Mapper
public interface Mapper extends DetailItemMapper<FlowTaskTemplate, DetailItem> {
}
}
}

View File

@@ -0,0 +1,19 @@
package com.lanyuanxiaoyao.service.ai.web.engine;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* 流程图中的边
*
* @author lanyuanxiaoyao
* @version 20250630
*/
@Data
@EqualsAndHashCode(onlyExplicitlyIncluded = true)
public class FlowEdge {
@EqualsAndHashCode.Include
private String id;
private String source;
private String target;
}

View File

@@ -0,0 +1,10 @@
package com.lanyuanxiaoyao.service.ai.web.engine;
/**
* 流程执行器
*
* @author lanyuanxiaoyao
* @version 20250630
*/
public class FlowExecutor {
}

View File

@@ -0,0 +1,20 @@
package com.lanyuanxiaoyao.service.ai.web.engine;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.eclipse.collections.api.set.ImmutableSet;
/**
* 流程图中的节点
*
* @author lanyuanxiaoyao
* @version 20250630
*/
@Data
@EqualsAndHashCode(onlyExplicitlyIncluded = true)
public class FlowNode {
@EqualsAndHashCode.Include
private String id;
private ImmutableSet<String> sourceHandlers;
private ImmutableSet<String> targetHandlers;
}

View File

@@ -0,0 +1,10 @@
package com.lanyuanxiaoyao.service.ai.web.engine.store;
/**
* 数据存储
*
* @author lanyuanxiaoyao
* @version 20250630
*/
public interface FlowStore {
}

View File

@@ -0,0 +1,44 @@
package com.lanyuanxiaoyao.service.ai.web.entity;
import com.lanyuanxiaoyao.service.ai.web.base.entity.SimpleEntity;
import com.lanyuanxiaoyao.service.common.Constants;
import jakarta.persistence.Column;
import jakarta.persistence.ConstraintMode;
import jakarta.persistence.Entity;
import jakarta.persistence.EntityListeners;
import jakarta.persistence.ForeignKey;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.Table;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.hibernate.annotations.DynamicUpdate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
@Getter
@Setter
@ToString
@Entity
@DynamicUpdate
@EntityListeners(AuditingEntityListener.class)
@Table(catalog = Constants.DATABASE_NAME, name = "service_ai_flow_task")
public class FlowTask extends SimpleEntity {
@ManyToOne
@JoinColumn(nullable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
private FlowTaskTemplate template;
@Column(columnDefinition = "longtext")
private String input;
@Column(nullable = false)
private Status status = Status.RUNNING;
@Column(columnDefinition = "longtext")
private String error;
@Column(columnDefinition = "longtext")
private String result;
public enum Status {
RUNNING,
ERROR,
FINISHED,
}
}

View File

@@ -0,0 +1,32 @@
package com.lanyuanxiaoyao.service.ai.web.entity;
import com.lanyuanxiaoyao.service.ai.web.base.entity.SimpleEntity;
import com.lanyuanxiaoyao.service.common.Constants;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.EntityListeners;
import jakarta.persistence.Table;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.hibernate.annotations.DynamicUpdate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
@Getter
@Setter
@ToString
@Entity
@DynamicUpdate
@EntityListeners(AuditingEntityListener.class)
@Table(catalog = Constants.DATABASE_NAME, name = "service_ai_flow_task_template")
public class FlowTaskTemplate extends SimpleEntity {
@Column(nullable = false)
private String name;
private String description;
@Column(nullable = false, columnDefinition = "longtext")
private String inputSchema;
@Column(nullable = false, columnDefinition = "text")
private String flow;
@Column(columnDefinition = "longtext")
private String flowGraph;
}

View File

@@ -0,0 +1,9 @@
package com.lanyuanxiaoyao.service.ai.web.repository;
import com.lanyuanxiaoyao.service.ai.web.base.repository.SimpleRepository;
import com.lanyuanxiaoyao.service.ai.web.entity.FlowTask;
import org.springframework.stereotype.Repository;
@Repository
public interface FlowTaskRepository extends SimpleRepository<FlowTask, Long> {
}

View File

@@ -0,0 +1,9 @@
package com.lanyuanxiaoyao.service.ai.web.repository;
import com.lanyuanxiaoyao.service.ai.web.base.repository.SimpleRepository;
import com.lanyuanxiaoyao.service.ai.web.entity.FlowTaskTemplate;
import org.springframework.stereotype.Repository;
@Repository
public interface FlowTaskTemplateRepository extends SimpleRepository<FlowTaskTemplate, Long> {
}

View File

@@ -15,7 +15,7 @@ import org.springframework.transaction.annotation.Transactional;
@Slf4j
@Service
public class FeedbackService extends SimpleServiceSupport<Feedback> {
public class FeedbackService extends SimpleServiceSupport<Feedback> {
private final FlowExecutor executor;
@SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")

View File

@@ -0,0 +1,15 @@
package com.lanyuanxiaoyao.service.ai.web.service.task;
import com.lanyuanxiaoyao.service.ai.web.base.service.SimpleServiceSupport;
import com.lanyuanxiaoyao.service.ai.web.entity.FlowTask;
import com.lanyuanxiaoyao.service.ai.web.repository.FlowTaskRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
@Slf4j
@Service
public class FlowTaskService extends SimpleServiceSupport<FlowTask> {
public FlowTaskService(FlowTaskRepository flowTaskRepository) {
super(flowTaskRepository);
}
}

View File

@@ -0,0 +1,15 @@
package com.lanyuanxiaoyao.service.ai.web.service.task;
import com.lanyuanxiaoyao.service.ai.web.base.service.SimpleServiceSupport;
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;
@Slf4j
@Service
public class FlowTaskTemplateService extends SimpleServiceSupport<FlowTaskTemplate> {
public FlowTaskTemplateService(FlowTaskTemplateRepository flowTaskTemplateRepository) {
super(flowTaskTemplateRepository);
}
}

View File

@@ -0,0 +1,16 @@
package com.lanyuanxiaoyao.service.ai.web.flow;
import com.yomahub.liteflow.core.NodeComponent;
import lombok.extern.slf4j.Slf4j;
/**
* @author lanyuanxiaoyao
* @version 20250625
*/
@Slf4j
public abstract class BaseNode extends NodeComponent {
@Override
public void process() throws Exception {
log.info(getClass().getName());
}
}

View File

@@ -0,0 +1,12 @@
package com.lanyuanxiaoyao.service.ai.web.flow;
/**
* @author lanyuanxiaoyao
* @version 20250625
*/
public class EndNode extends BaseNode {
@Override
public void process() throws Exception {
}
}

View File

@@ -0,0 +1,304 @@
package com.lanyuanxiaoyao.service.ai.web.flow;
import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.eclipsecollections.EclipseCollectionsModule;
import com.yomahub.liteflow.builder.LiteFlowNodeBuilder;
import com.yomahub.liteflow.core.NodeComponent;
import com.yomahub.liteflow.enums.NodeTypeEnum;
import java.util.LinkedList;
import java.util.Queue;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.collections.api.factory.Lists;
import org.eclipse.collections.api.factory.Maps;
import org.eclipse.collections.api.list.ImmutableList;
import org.eclipse.collections.api.list.MutableList;
import org.eclipse.collections.api.map.ImmutableMap;
/**
* @author lanyuanxiaoyao
* @version 20250625
*/
@Slf4j
public class LiteFlowService {
public LiteFlowService() {
createNode("start-amis-node", NodeTypeEnum.COMMON, StartNode.class);
createNode("end-amis-node", NodeTypeEnum.COMMON, EndNode.class);
createNode("llm-amis-node", NodeTypeEnum.COMMON, LlmNode.class);
}
private static void createNode(String name, NodeTypeEnum type, Class<? extends NodeComponent> clazz) {
LiteFlowNodeBuilder.createNode()
.setId(name)
.setName(name)
.setType(type)
.setClazz(clazz)
.build();
}
public static void main(String[] args) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new EclipseCollectionsModule());
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// language=JSON
String source = """
{
"nodes": [
{
"id": "A",
"type": "start",
"position": {
"x": 8,
"y": 272
},
"data": {},
"measured": {
"width": 256,
"height": 75
},
"selected": false,
"dragging": false
},
{
"id": "F",
"type": "end",
"position": {
"x": 1439.5556937134281,
"y": 282.2797340760818
},
"data": {},
"measured": {
"width": 256,
"height": 75
},
"selected": false,
"dragging": false
},
{
"id": "C",
"type": "normal",
"position": {
"x": 902.6781018665707,
"y": 115.31234529524048
},
"data": {},
"measured": {
"width": 256,
"height": 75
},
"selected": false,
"dragging": false
},
{
"id": "B",
"type": "normal",
"position": {
"x": 338,
"y": 287
},
"data": {},
"measured": {
"width": 256,
"height": 75
},
"selected": false,
"dragging": false
},
{
"id": "E",
"type": "normal",
"position": {
"x": 1086.6322978498904,
"y": 371.3061114283591
},
"data": {},
"measured": {
"width": 256,
"height": 75
},
"selected": true,
"dragging": false
},
{
"id": "D",
"type": "normal",
"position": {
"x": 700.0944461714178,
"y": 369.84258971430364
},
"data": {},
"measured": {
"width": 256,
"height": 75
},
"selected": false,
"dragging": false
}
],
"edges": [
{
"source": "A",
"target": "B",
"id": "xy-edge__A-B"
},
{
"source": "B",
"target": "C",
"id": "xy-edge__B-C"
},
{
"source": "C",
"target": "F",
"id": "xy-edge__C-F"
},
{
"source": "D",
"target": "E",
"id": "xy-edge__D-E"
},
{
"source": "B",
"target": "D",
"id": "xy-edge__B-D"
},
{
"source": "E",
"target": "F",
"id": "xy-edge__E-F"
}
],
"data": {
"A": {
"inputs": {
"name": {
"type": "text"
},
"description": {
"type": "text",
"description": "文件描述"
}
}
},
"C": {
"model": "qwen3",
"outputs": {
"text": {
"type": "string"
}
},
"systemPrompt": "你是个沙雕"
},
"B": {
"count": 3,
"score": 0.75,
"knowledgeId": 3585368238960640,
"query": "hello world"
},
"E": {
"type": "python",
"content": "code='hello'\\nprint(code)"
},
"D": {
"model": "qwen3",
"outputs": {
"text": {
"type": "string"
}
},
"systemPrompt": "你是个聪明人"
}
}
}
""";
FlowData root = mapper.readValue(StrUtil.trim(source), FlowData.class);
log.info("\n{}", buildEl(root.nodes, root.edges));
}
public static String buildEl(ImmutableList<FlowData.Node> nodes, ImmutableList<FlowData.Edge> edges) {
var nodeMap = nodes.toMap(FlowData.Node::getId, node -> node);
var adjacencyGraph = Maps.mutable.<String, MutableList<String>>empty();
var reverseAdjacencyGraph = Maps.mutable.<String, MutableList<String>>empty();
var inDegree = Maps.mutable.<String, Integer>empty();
nodes.forEach(node -> {
adjacencyGraph.put(node.getId(), Lists.mutable.empty());
reverseAdjacencyGraph.put(node.getId(), Lists.mutable.empty());
inDegree.put(node.getId(), 0);
});
edges.forEach(edge -> {
adjacencyGraph.get(edge.getSource()).add(edge.getTarget());
reverseAdjacencyGraph.get(edge.getTarget()).add(edge.getSource());
inDegree.put(edge.getTarget(), inDegree.get(edge.getTarget()) + 1);
});
Queue<String> queue = new LinkedList<>();
var topologicalSortedList = Lists.mutable.<String>empty();
inDegree.forEachKeyValue((id, count) -> {
if (count == 0) {
queue.offer(id);
}
});
while (!queue.isEmpty()) {
String id = queue.poll();
topologicalSortedList.add(id);
for (var neighborId : adjacencyGraph.get(id)) {
inDegree.put(neighborId, inDegree.get(neighborId) - 1);
if (inDegree.get(neighborId) == 0) {
queue.offer(neighborId);
}
}
}
topologicalSortedList.forEach(id -> log.info("{} {}", id, adjacencyGraph.get(id)));
topologicalSortedList.forEach(id -> log.info("{} {}", id, reverseAdjacencyGraph.get(id)));
var nodeQueue = new LinkedList<>(topologicalSortedList);
var chains = Lists.mutable.<MutableList<String>>empty();
while (!nodeQueue.isEmpty()) {
String currentId = nodeQueue.poll();
var subChain = Lists.mutable.<String>empty();
while (true) {
subChain.add(currentId);
nodeQueue.remove(currentId);
if (adjacencyGraph.get(currentId).size() != 1) {
break;
}
String nextId = adjacencyGraph.get(currentId).get(0);
if (reverseAdjacencyGraph.get(nextId).size() > 1) {
break;
}
currentId = nextId;
}
chains.add(subChain);
}
log.info("{}", chains);
return StrUtil.join(",", topologicalSortedList);
}
@Data
public static class FlowData {
private ImmutableList<Node> nodes;
private ImmutableList<Edge> edges;
private ImmutableMap<String, Object> data;
@Data
public static class Node {
private String id;
private String type;
}
@Data
public static class Edge {
private String id;
private String source;
private String target;
}
}
}

View File

@@ -0,0 +1,12 @@
package com.lanyuanxiaoyao.service.ai.web.flow;
/**
* @author lanyuanxiaoyao
* @version 20250625
*/
public class LlmNode extends BaseNode {
@Override
public void process() throws Exception {
}
}

View File

@@ -0,0 +1,12 @@
package com.lanyuanxiaoyao.service.ai.web.flow;
/**
* @author lanyuanxiaoyao
* @version 20250625
*/
public class StartNode extends BaseNode {
@Override
public void process() throws Exception {
}
}

View File

@@ -6,7 +6,8 @@
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"preview": "vite preview"
"preview": "vite preview",
"test": "vitest run"
},
"dependencies": {
"@ant-design/icons": "^6.0.0",
@@ -15,32 +16,33 @@
"@echofly/fetch-event-source": "^3.0.2",
"@fortawesome/fontawesome-free": "^6.7.2",
"@lightenna/react-mermaid-diagram": "^1.0.20",
"@tinyflow-ai/react": "^0.2.1",
"@xyflow/react": "^12.7.1",
"ahooks": "^3.8.5",
"amis": "^6.12.0",
"antd": "^5.26.1",
"antd": "^5.26.2",
"axios": "^1.10.0",
"chart.js": "^4.5.0",
"echarts-for-react": "^3.0.2",
"licia": "^1.48.0",
"markdown-it": "^14.1.0",
"mermaid": "^11.6.0",
"mermaid": "^11.7.0",
"react": "^18.3.1",
"react-chartjs-2": "^5.3.0",
"react-dom": "^18.3.1",
"react-markdown": "^10.1.0",
"react-router": "^7.6.2",
"styled-components": "^6.1.18"
"styled-components": "^6.1.19",
"yocto-queue": "^1.2.1",
"zustand": "^5.0.5"
},
"devDependencies": {
"@types/markdown-it": "^14.1.2",
"@types/react": "^18.3.23",
"@types/react-dom": "^18.3.7",
"@vitejs/plugin-react-swc": "^3.10.2",
"globals": "^16.2.0",
"sass": "^1.89.2",
"typescript": "~5.8.3",
"vite": "^6.3.5",
"vite-plugin-javascript-obfuscator": "^3.1.0"
"vite": "^7.0.0",
"vite-plugin-javascript-obfuscator": "^3.1.0",
"vitest": "^3.2.4"
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,14 +1,26 @@
import {ProLayout} from '@ant-design/pro-components'
import {ConfigProvider} from 'antd'
import React from 'react'
import {Outlet, useLocation, useNavigate} from 'react-router'
import {menus} from '../route.tsx'
const apps: { title: string, desc: string, url: string, icon?: string }[] = [
{
icon: 'http://132.126.207.124:8686/udal-manager/static/favicon.ico',
title: 'CSV-HUDI处理平台',
desc: 'Hudi 批量割接、稽核任务管理平台',
url: 'http://132.126.207.124:8686/udal-manager/',
},
]
const App: React.FC = () => {
const navigate = useNavigate()
const location = useLocation()
return (
<ProLayout
token={{
colorTextAppListIcon: '#dfdfdf',
colorTextAppListIconHover: '#ffffff',
header: {
colorBgHeader: '#292f33',
colorHeaderTitle: '#ffffff',
@@ -20,6 +32,8 @@ const App: React.FC = () => {
colorTextRightActionsItem: '#dfdfdf',
},
}}
appList={apps}
disableMobile={true}
logo={<img src="icon.png" alt="logo"/>}
title="Hudi 服务总台"
route={menus}
@@ -34,7 +48,18 @@ const App: React.FC = () => {
style={{minHeight: '100vh'}}
contentStyle={{backgroundColor: 'white', padding: '10px 10px 10px 20px'}}
>
<Outlet/>
<ConfigProvider
theme={{
components: {
Card: {
bodyPadding: 0,
bodyPaddingSM: 0,
},
},
}}
>
<Outlet/>
</ConfigProvider>
</ProLayout>
)
}

View File

@@ -1,18 +1,6 @@
import {Tinyflow} from '@tinyflow-ai/react'
import '@tinyflow-ai/react/dist/index.css'
function Test() {
return (
<div className="flowable">
<Tinyflow
className="tinyflow-instance"
style={{height: '95vh'}}
onDataChange={(value) => {
console.log(value)
console.log(JSON.stringify(value))
}}
/>
</div>
<div>Test</div>
)
}

View File

@@ -0,0 +1,113 @@
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'
const createNode = (id: string, type: string): Node => {
return {
data: {},
position: {
x: 0,
y: 0
},
id,
type,
}
}
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,
target,
sourceHandle,
targetHandle,
}
}
/* 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')],
[]
))
})
test(nodeToSelfError().message, () => {
expect(() => {
// language=JSON
const {
nodes,
edges
} = JSON.parse('{\n "nodes": [\n {\n "id": "P14abHl4uY",\n "type": "start-node",\n "position": {\n "x": 100,\n "y": 100\n },\n "data": {},\n "measured": {\n "width": 256,\n "height": 82\n }\n },\n {\n "id": "3YDRebKqCX",\n "type": "end-node",\n "position": {\n "x": 773.3027344262372,\n "y": 101.42648884412338\n },\n "data": {},\n "measured": {\n "width": 256,\n "height": 74\n },\n "selected": false,\n "dragging": false\n },\n {\n "id": "YXJ91nHVaz",\n "type": "llm-node",\n "position": {\n "x": 430.94541183662506,\n "y": 101.42648884412338\n },\n "data": {},\n "measured": {\n "width": 256,\n "height": 74\n },\n "selected": true,\n "dragging": false\n }\n ],\n "edges": [\n {\n "source": "P14abHl4uY",\n "target": "YXJ91nHVaz",\n "id": "xy-edge__P14abHl4uY-YXJ91nHVaz"\n },\n {\n "source": "YXJ91nHVaz",\n "target": "3YDRebKqCX",\n "id": "xy-edge__YXJ91nHVaz-3YDRebKqCX"\n }\n ],\n "data": {}\n}')
checkAddConnection(createConnection('YXJ91nHVaz', 'YXJ91nHVaz'), nodes, edges)
}).toThrowError(nodeToSelfError())
})
test(hasCycleError().message, () => {
expect(() => {
// language=JSON
const {
nodes,
edges,
} = JSON.parse('{\n "nodes": [\n {\n "id": "-DKfXm7r3f",\n "type": "start-node",\n "position": {\n "x": -75.45812782717618,\n "y": 14.410669352596976\n },\n "data": {},\n "measured": {\n "width": 256,\n "height": 82\n },\n "selected": false,\n "dragging": false\n },\n {\n "id": "2uL3Hw2CAW",\n "type": "end-node",\n "position": {\n "x": 734.7875356349059,\n "y": -1.2807079327602473\n },\n "data": {},\n "measured": {\n "width": 256,\n "height": 74\n },\n "selected": false,\n "dragging": false\n },\n {\n "id": "yp-yYfKUzC",\n "type": "llm-node",\n "position": {\n "x": 338.2236369686051,\n "y": -92.5759939566568\n },\n "data": {},\n "measured": {\n "width": 256,\n "height": 74\n },\n "selected": false,\n "dragging": false\n },\n {\n "id": "N4HQPN-NYZ",\n "type": "llm-node",\n "position": {\n "x": 332.51768159211156,\n "y": 114.26488844123382\n },\n "data": {},\n "measured": {\n "width": 256,\n "height": 74\n },\n "selected": true,\n "dragging": false\n }\n ],\n "edges": [\n {\n "source": "-DKfXm7r3f",\n "target": "yp-yYfKUzC",\n "id": "xy-edge__-DKfXm7r3f-yp-yYfKUzC"\n },\n {\n "source": "yp-yYfKUzC",\n "target": "2uL3Hw2CAW",\n "id": "xy-edge__yp-yYfKUzC-2uL3Hw2CAW"\n },\n {\n "source": "-DKfXm7r3f",\n "target": "N4HQPN-NYZ",\n "id": "xy-edge__-DKfXm7r3f-N4HQPN-NYZ"\n },\n {\n "source": "N4HQPN-NYZ",\n "target": "yp-yYfKUzC",\n "id": "xy-edge__N4HQPN-NYZ-yp-yYfKUzC"\n }\n ],\n "data": {}\n}')
// language=JSON
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())
})

View File

@@ -0,0 +1,274 @@
import {type Connection, type Edge, getConnectedEdges, getIncomers, getOutgoers, type Node} from '@xyflow/react'
import {clone, find, findIdx, isEqual, lpad, toStr, uuid} from 'licia'
export class CheckError extends Error {
readonly id: string
constructor(
id: number,
message: string,
) {
super(message)
this.id = `E${lpad(toStr(id), 6, '0')}`
}
public toString(): string {
return `${this.id}: ${this.message}`
}
}
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
visited.add(targetNode.id)
for (const outgoer of getOutgoers(targetNode, nodes, edges)) {
if (isEqual(outgoer.id, sourceNode.id)) return true
if (hasCycle(sourceNode, outgoer, nodes, edges, visited)) return true
}
}
/* 摘自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) {
throw sourceNodeNotFoundError()
}
let targetNode = getNodeById(connection.target, nodes)
if (!targetNode) {
throw targetNodeNotFoundError()
}
// 禁止短路整个流程
if (isEqual('start-node', sourceNode.type) && isEqual('end-node', targetNode.type)) {
throw startNodeToEndNodeError()
}
// 禁止流程出现环,必须是有向无环图
if (isEqual(sourceNode.id, targetNode.id)) {
throw nodeToSelfError()
} else if (hasCycle(sourceNode, targetNode, nodes, edges)) {
throw hasCycleError()
}
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个结束节点')
// @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 (nodes.filter(n => isEqual('end-node', n.type)).length < 1) {
throw atLeastOneEndNodeError()
}
}

View File

@@ -0,0 +1,296 @@
import {PlusCircleFilled, SaveFilled} from '@ant-design/icons'
import {Background, BackgroundVariant, Controls, MiniMap, type NodeProps, ReactFlow} from '@xyflow/react'
import {useMount} from 'ahooks'
import type {Schema} from 'amis'
import {Button, Drawer, Dropdown, message, Space} from 'antd'
import {arrToMap, find, isEqual, isNil, randomId} from 'licia'
import {type JSX, type MemoExoticComponent, 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 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'
const FlowableDiv = styled.div`
height: 100%;
.react-flow__node.selectable {
&:focus {
box-shadow: 0 0 20px 1px #e8e8e8;
border-radius: 8px;
}
}
.react-flow__handle.connectionindicator {
width: 10px;
height: 10px;
background-color: #ffffff;
border: 1px solid #000000;
&:hover {
background-color: #e8e8e8;
border: 1px solid #c6c6c6;
}
}
.toolbar {
position: absolute;
right: 20px;
top: 20px;
z-index: 10;
}
.node-card {
cursor: default;
.card-container {
}
}
`
function FlowEditor() {
const [messageApi, contextHolder] = message.useMessage()
const [nodeDef] = useState<{
key: string,
name: string,
component: MemoExoticComponent<(props: NodeProps) => JSX.Element>
}[]>([
{
key: 'start-node',
name: '开始',
component: StartNode,
},
{
key: 'end-node',
name: '结束',
component: EndNode,
},
{
key: 'llm-node',
name: '大模型',
component: LlmNode,
},
{
key: 'knowledge-node',
name: '知识库',
component: KnowledgeNode,
},
{
key: 'code-node',
name: '代码执行',
component: CodeNode,
},
{
key: 'switch-node',
name: '条件分支',
component: SwitchNode,
},
])
const [open, setOpen] = useState(false)
const {data, setData, getDataById, setDataById} = useDataStore()
const {
nodes,
addNode,
removeNode,
setNodes,
onNodesChange,
edges,
setEdges,
onEdgesChange,
onConnect,
} = useFlowStore()
const [currentNodeForm, setCurrentNodeForm] = useState<JSX.Element>()
const editNode = (id: string, columnSchema?: Schema[]) => {
if (!isNil(columnSchema)) {
setCurrentNodeForm(
amisRender(
{
type: 'wrapper',
size: 'none',
body: [
{
debug: commonInfo.debug,
type: 'form',
...horizontalFormOptions(),
wrapWithPanel: false,
onEvent: {
submitSucc: {
actions: [
{
actionType: 'custom',
// @ts-ignore
script: (context, action, event) => {
setDataById(id, context.props.data)
setOpen(false)
},
},
],
},
},
body: [
...(columnSchema ?? []),
{
type: 'wrapper',
size: 'none',
className: 'space-x-2 text-right',
body: [
{
type: 'action',
label: '取消',
onEvent: {
click: {
actions: [
{
actionType: 'custom',
// @ts-ignore
script: (context, action, event) => {
setOpen(false)
},
},
],
},
},
},
{
type: 'submit',
label: '保存',
level: 'primary',
},
],
},
],
},
],
},
getDataById(id),
),
)
setOpen(true)
}
}
// 用于透传node操作到主流程
const initialNodeHandlers = {
getDataById,
setDataById,
removeNode,
editNode,
}
useMount(() => {
// 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 = {}
let initialNodes = initialData?.nodes ?? []
let initialEdges = initialData?.edges ?? []
let initialNodeData = initialData?.data ?? {}
setData(initialNodeData)
for (let node of initialNodes) {
node.data = initialNodeHandlers
}
setNodes(initialNodes)
setEdges(initialEdges)
})
return (
<FlowableDiv>
{contextHolder}
<Space className="toolbar">
<Dropdown
menu={{
items: nodeDef.map(def => ({key: def.key, label: def.name})),
onClick: ({key}) => {
try {
if (commonInfo.debug) {
console.info('Add', key, JSON.stringify({nodes, edges, data}))
}
checkAddNode(key, nodes, edges)
addNode({
id: randomId(10),
type: key,
position: {x: 100, y: 100},
data: initialNodeHandlers,
})
} catch (e) {
// @ts-ignore
messageApi.error(e.toString())
}
},
}}
>
<Button type="default">
<PlusCircleFilled/>
</Button>
</Dropdown>
<Button type="primary" onClick={() => {
try {
if (commonInfo.debug) {
console.info('Save', JSON.stringify({nodes, edges, data}))
}
checkSave(nodes, edges, data)
// let saveData = {nodes, edges, data}
// console.log(buildEL(nodes, edges))
} catch (e) {
// @ts-ignore
messageApi.error(e.toString())
}
}}>
<SaveFilled/>
</Button>
</Space>
<Drawer
title="节点编辑"
open={open}
closeIcon={false}
maskClosable={false}
destroyOnHidden
size="large"
>
{currentNodeForm}
</Drawer>
<ReactFlow
nodes={nodes}
edges={edges}
onNodesChange={onNodesChange}
onEdgesChange={onEdgesChange}
onConnect={(connection) => {
try {
if (commonInfo.debug) {
console.info('Connection', JSON.stringify(connection), JSON.stringify({nodes, edges, data}))
}
checkAddConnection(connection, nodes, edges)
onConnect(connection)
} catch (e) {
// @ts-ignore
messageApi.error(e.toString())
}
}}
// @ts-ignore
nodeTypes={arrToMap(
nodeDef.map(def => def.key),
key => find(nodeDef, def => isEqual(key, def.key))!.component)
}
fitView
>
<Controls/>
<MiniMap/>
<Background variant={BackgroundVariant.Cross} gap={20} size={3}/>
</ReactFlow>
</FlowableDiv>
)
}
export default FlowEditor

View File

@@ -0,0 +1,76 @@
import {type Edge, type Node} from '@xyflow/react'
export const buildEL = (nodes: Node[], edges: Edge[]): string => {
const nodeMap: Map<string, Node> = new Map<string, Node>()
// 构建邻接列表和内图
const adjList = new Map<string, string[]>()
const inDegree = new Map<string, number>()
for (const node of nodes) {
nodeMap.set(node.id, node)
adjList.set(node.id, [])
inDegree.set(node.id, 0)
}
for (const edge of edges) {
adjList.get(edge.source)!.push(edge.target)
inDegree.set(edge.target, inDegree.get(edge.target)! + 1)
}
// Compute levels (longest path from start)
const levelMap = new Map<string, number>()
function computeLevel(nodeId: string): number {
if (levelMap.has(nodeId)) return levelMap.get(nodeId)!
const preds = edges.filter(e => e.target === nodeId).map(e => e.source)
const level = preds.length === 0 ? 0 : Math.max(...preds.map(p => computeLevel(p))) + 1
levelMap.set(nodeId, level)
return level
}
for (const node of nodes) computeLevel(node.id)
// Group nodes by level
const maxLevel = Math.max(...Array.from(levelMap.values()))
const levels: string[][] = Array.from({length: maxLevel + 1}, () => [])
for (const node of nodes) levels[levelMap.get(node.id)!].push(node.id)
const covertNodeFromId = (id: string) => {
let node = nodeMap.get(id)!
return `node("${node.type}").bind("nodeId", ${node.id})`
}
// Build EL expression
const expressions: string[] = []
for (let i = 0; i <= maxLevel; i++) {
const nodesAtLevel = levels[i]
if (nodesAtLevel.length === 0) continue
// 识别从这个级别开始的串行链
const serialChains: string[] = []
for (const nodeId of nodesAtLevel) {
let chain = [nodeId]
let current = nodeId
while (adjList.get(current)?.length === 1) {
const next = adjList.get(current)![0]
if (inDegree.get(next) === 1 && levelMap.get(next) === i + chain.length) {
chain.push(next)
current = next
} else break
}
if (chain.length > 1) {
serialChains.push(`THEN(${chain.map(id => covertNodeFromId(id)).join(',')})`)
// Remove processed nodes from their levels
for (let j = 1; j < chain.length; j++) {
const level = levelMap.get(chain[j])!
levels[level] = levels[level].filter(n => n !== chain[j])
}
} else {
serialChains.push(covertNodeFromId(nodeId))
}
}
// Combine chains or nodes at this level
expressions.push(serialChains.length > 1 ? `WHEN(${serialChains.join(', ')})` : serialChains[0])
}
return `THEN(${expressions.join(',')})`
}

View File

@@ -0,0 +1,199 @@
import {DeleteFilled, EditFilled} from '@ant-design/icons'
import {Handle, type HandleProps, type NodeProps, Position, useNodeConnections} from '@xyflow/react'
import type {Schema} from 'amis'
import {Card, Dropdown} from 'antd'
import {isEmpty, isEqual, isNil} from 'licia'
import {type JSX} from 'react'
import {horizontalFormOptions} from '../../../../util/amis.tsx'
export type AmisNodeType = 'normal' | 'start' | 'end'
export function inputsFormColumns(required: boolean = false, preload?: any): Schema[] {
return [
{
type: 'input-kvs',
name: 'inputs',
label: '输入变量',
value: preload,
addButtonText: '新增输入',
draggable: false,
keyItem: {
...horizontalFormOptions(),
label: '参数名称',
},
required: required,
valueItems: [
{
...horizontalFormOptions(),
type: 'select',
name: 'type',
label: '变量',
required: true,
options: [],
},
],
},
]
}
export function outputsFormColumns(editable: boolean = false, required: boolean = false, preload?: any): Schema[] {
return [
{
disabled: !editable,
type: 'input-kvs',
name: 'outputs',
label: '输出变量',
value: preload,
addButtonText: '新增输出',
draggable: false,
keyItem: {
...horizontalFormOptions(),
label: '参数名称',
},
required: required,
valueItems: [
{
...horizontalFormOptions(),
type: 'select',
name: 'type',
label: '参数',
required: true,
selectFirst: true,
options: [
{
label: '文本',
value: 'string',
},
{
label: '数字',
value: 'number',
},
{
label: '文本数组',
value: 'array-string',
},
{
label: '对象数组',
value: 'array-object',
},
],
},
],
},
]
}
export const LimitHandler = (props: HandleProps & { limit: number }) => {
const connections = useNodeConnections({
handleType: props.type,
})
return (
<Handle
{...props}
isConnectable={connections.length < props.limit}
/>
)
}
type AmisNodeProps = {
nodeProps: NodeProps
type: AmisNodeType
defaultNodeName: String
defaultNodeDescription?: String
extraNodeDescription?: (nodeData: any) => JSX.Element
handlers?: (nodeData: any) => JSX.Element
columnSchema?: Schema[]
}
const AmisNode: (props: AmisNodeProps) => JSX.Element = ({
nodeProps,
type,
defaultNodeName,
defaultNodeDescription,
extraNodeDescription,
handlers,
columnSchema,
}) => {
const {id, data} = nodeProps
const {getDataById, removeNode, editNode} = data
// @ts-ignore
const nodeData = getDataById(id)
const nodeName = isEmpty(nodeData?.node?.name) ? defaultNodeName : nodeData.node.name
const nodeDescription = isEmpty(nodeData?.node?.description) ? defaultNodeDescription : nodeData.node?.description
return (
<div className="w-64">
<Dropdown
className="card-container"
trigger={['contextMenu']}
menu={{
items: [
{
key: 'edit',
label: '编辑',
icon: <EditFilled className="text-gray-600 hover:text-blue-500"/>,
},
{
key: 'remove',
label: '删除',
icon: <DeleteFilled className="text-red-500 hover:text-red-500"/>,
},
],
onClick: menu => {
switch (menu.key) {
case 'edit':
// @ts-ignore
editNode(
id,
[
{
type: 'input-text',
name: 'node.name',
label: '节点名称',
placeholder: nodeName,
},
{
type: 'textarea',
name: 'node.description',
label: '节点描述',
placeholder: nodeDescription,
},
{
type: 'divider',
},
...(columnSchema ?? []),
],
)
break
case 'remove':
// @ts-ignore
removeNode(id)
break
}
},
}}
>
<Card
className="node-card"
title={nodeName}
extra={<span className="text-gray-300 text-xs">{id}</span>}
size="small"
>
<div className="card-description p-2 text-secondary text-sm">
{nodeDescription}
{extraNodeDescription?.(nodeData)}
</div>
</Card>
</Dropdown>
{isNil(handlers)
? <>
{isEqual(type, 'start') || isEqual(type, 'normal')
? <Handle type="source" position={Position.Right} id="source"/> : undefined}
{isEqual(type, 'end') || isEqual(type, 'normal')
? <Handle type="target" position={Position.Left} id="target"/> : undefined}
</>
: handlers?.(nodeData)}
</div>
)
}
export default AmisNode

View File

@@ -0,0 +1,52 @@
import type {NodeProps} from '@xyflow/react'
import AmisNode, {inputsFormColumns, outputsFormColumns} from './AmisNode.tsx'
import React from 'react'
const CodeNode = (props: NodeProps) => AmisNode({
nodeProps: props,
type: 'normal',
defaultNodeName: '代码执行',
defaultNodeDescription: '执行自定义的处理代码',
columnSchema: [
...inputsFormColumns(),
{
type: 'divider',
},
{
type: 'select',
name: 'type',
label: '代码类型',
required: true,
options: [
{
value: 'javascript',
label: 'JavaScript',
},
{
value: 'python',
label: 'Python',
},
{
value: 'lua',
label: 'Lua',
},
],
},
{
type: 'editor',
required: true,
label: '代码内容',
name: 'content',
language: '${type}',
options: {
wordWrap: 'bounded',
},
},
{
type: 'divider',
},
...outputsFormColumns(true, true, {result: {type: 'string'}}),
],
})
export default React.memo(CodeNode)

View File

@@ -0,0 +1,13 @@
import type {NodeProps} from '@xyflow/react'
import AmisNode, {outputsFormColumns} from './AmisNode.tsx'
import React from 'react'
const EndNode = (props: NodeProps) => AmisNode({
nodeProps: props,
type: 'end',
defaultNodeName: '结束节点',
defaultNodeDescription: '定义输出变量',
columnSchema: outputsFormColumns(true),
})
export default React.memo(EndNode)

View File

@@ -0,0 +1,66 @@
import type {NodeProps} from '@xyflow/react'
import {commonInfo} from '../../../../util/amis.tsx'
import AmisNode, {inputsFormColumns, outputsFormColumns} from './AmisNode.tsx'
import React from 'react'
const KnowledgeNode = (props: NodeProps) => AmisNode({
nodeProps: props,
type: 'normal',
defaultNodeName: '知识库',
defaultNodeDescription: '查询知识库获取外部知识',
columnSchema: [
...inputsFormColumns(),
{
type: 'divider',
},
{
type: 'select',
name: 'knowledgeId',
label: '知识库',
required: true,
options: [],
source: {
method: 'get',
url: `${commonInfo.baseAiUrl}/knowledge/list`,
// @ts-ignore
adaptor: (payload, response, api, context) => {
return {
...payload,
data: {
items: payload.data.items.map((item: any) => ({value: item['id'], label: item['name']})),
},
}
},
},
},
{
type: 'input-text',
name: 'query',
label: '查询文本',
required: true,
},
{
type: 'input-range',
name: 'count',
label: '返回数量',
required: true,
value: 3,
max: 10,
},
{
type: 'input-range',
name: 'score',
label: '匹配阀值',
required: true,
value: 0.6,
max: 1,
step: 0.05,
},
{
type: 'divider',
},
...outputsFormColumns(false, true, {result: {type: 'array-string'}}),
],
})
export default React.memo(KnowledgeNode)

View File

@@ -0,0 +1,51 @@
import type {NodeProps} from '@xyflow/react'
import {Tag} from 'antd'
import AmisNode, {inputsFormColumns, outputsFormColumns} from './AmisNode.tsx'
import React from 'react'
const modelMap: Record<string, string> = {
qwen3: 'Qwen3',
deepseek: 'Deepseek',
}
const LlmNode = (props: NodeProps) => AmisNode({
nodeProps: props,
type: 'normal',
defaultNodeName: '大模型',
defaultNodeDescription: '使用大模型对话',
extraNodeDescription: nodeData => {
const model = nodeData?.model as string | undefined
return model
? <div className="mt-2 flex justify-between">
<span></span>
<Tag className="m-0" color="blue">{modelMap[model]}</Tag>
</div>
: <></>
},
columnSchema: [
...inputsFormColumns(),
{
type: 'divider',
},
{
type: 'select',
name: 'model',
label: '大模型',
required: true,
selectFirst: true,
options: Object.keys(modelMap).map(key => ({label: modelMap[key], value: key})),
},
{
type: 'textarea',
name: 'systemPrompt',
label: '系统提示词',
required: true,
},
{
type: 'divider',
},
...outputsFormColumns(false, true, {text: {type: 'string'}}),
],
})
export default React.memo(LlmNode)

View File

@@ -0,0 +1,68 @@
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)

View File

@@ -0,0 +1,53 @@
import {Handle, type NodeProps, Position} from '@xyflow/react'
import AmisNode from './AmisNode.tsx'
import {Tag} from 'antd'
import React from 'react'
const cases = [
{
index: 1
},
{
index: 2
},
{
index: 3
}
]
const SwitchNode = (props: NodeProps) => AmisNode({
nodeProps: props,
type: 'normal',
defaultNodeName: '分支节点',
defaultNodeDescription: '根据不同的情况前往不同的分支',
columnSchema: [],
extraNodeDescription: nodeData => {
return (
<div className="mt-2">
{cases.map(item => (
<div key={item.index} className="mt-1">
<Tag className="m-0" color="blue"> {item.index}</Tag>
</div>
))}
</div>
)
},
handlers: nodeData => {
return (
<>
<Handle type="target" position={Position.Left}/>
{cases.map((item, index) => (
<Handle
type="source"
position={Position.Right}
key={item.index}
id={`${item.index}`}
style={{top: 85 + (25 * index)}}
/>
))}
</>
)
}
})
export default React.memo(SwitchNode)

View File

@@ -0,0 +1,23 @@
import {create} from 'zustand/react'
export const useDataStore = create<{
data: Record<string, any>,
getData: () => Record<string, any>,
setData: (data: Record<string, any>) => void,
getDataById: (id: string) => any,
setDataById: (id: string, data: any) => void,
}>((set, get) => ({
data: {},
getData: () => get().data,
setData: (data) => set({
data: data
}),
getDataById: id => get().data[id],
setDataById: (id, data) => {
let updateData = get().data
updateData[id] = data
set({
data: updateData,
})
},
}))

View File

@@ -0,0 +1,56 @@
import {
addEdge,
applyEdgeChanges,
applyNodeChanges,
type Edge,
type Node,
type OnConnect,
type OnEdgesChange,
type OnNodesChange,
} from '@xyflow/react'
import {filter, find, isEqual} from 'licia'
import {create} from 'zustand/react'
export const useFlowStore = create<{
nodes: Node[],
onNodesChange: OnNodesChange,
getNodeById: (id: string) => Node | undefined,
addNode: (node: Node) => void,
removeNode: (id: string) => void,
setNodes: (nodes: Node[]) => void,
edges: Edge[],
onEdgesChange: OnEdgesChange,
setEdges: (edges: Edge[]) => void,
onConnect: OnConnect,
}>((set, get) => ({
nodes: [],
onNodesChange: changes => {
set({
nodes: applyNodeChanges(changes, get().nodes),
})
},
getNodeById: (id: string) => find(get().nodes, node => isEqual(node.id, id)),
addNode: node => set({nodes: get().nodes.concat(node)}),
removeNode: id => {
set({
nodes: filter(get().nodes, node => !isEqual(node.id, id)),
})
},
setNodes: nodes => set({nodes}),
edges: [],
onEdgesChange: changes => {
set({
edges: applyEdgeChanges(changes, get().edges),
})
},
setEdges: edges => set({edges}),
onConnect: connection => {
set({
edges: addEdge(connection, get().edges),
})
},
}))

View File

@@ -0,0 +1,95 @@
import React from 'react'
import {amisRender, commonInfo, crudCommonOptions, paginationTemplate,} from '../../../util/amis.tsx'
import {useNavigate} from 'react-router'
const FlowTask: React.FC = () => {
const navigate = useNavigate()
return (
<div className="task-template">
{amisRender(
{
type: 'page',
title: '任务记录',
body: [
{
type: 'crud',
api: {
method: 'post',
url: `${commonInfo.baseAiUrl}/flow_task/list`,
data: {
page: {
index: '${page}',
size: '${perPage}',
}
}
},
...crudCommonOptions(),
...paginationTemplate(
10,
5,
[
{
type: 'action',
label: '',
icon: 'fa fa-plus',
size: 'sm',
onEvent: {
click: {
actions: [
{
actionType: 'custom',
// @ts-ignore
script: (context, action, event) => {
navigate(`/ai/flow_task/add`)
},
},
],
},
},
},
],
),
columns: [
{
name: 'id',
label: '任务ID',
width: 200,
},
{
name: 'status',
label: '状态',
},
{
type: 'operation',
label: '操作',
width: 200,
buttons: [
{
type: 'action',
label: '重新执行',
level: 'link',
size: 'sm',
},
{
type: 'action',
label: '删除',
className: 'text-danger btn-deleted',
level: 'link',
size: 'sm',
actionType: 'ajax',
api: `get:${commonInfo.baseAiUrl}/task/remove/\${id}`,
confirmText: '确认删除任务记录:${name}',
confirmTitle: '删除',
},
],
},
],
},
],
},
)}
</div>
)
}
export default FlowTask

View File

@@ -0,0 +1,36 @@
import React from 'react'
import {amisRender,} from '../../../util/amis.tsx'
const FlowTaskAdd: React.FC = () => {
// const navigate = useNavigate()
return (
<div className="task-template">
{amisRender(
{
type: 'page',
title: '发起任务',
body: {
type: 'wizard',
wrapWithPanel: false,
steps:[
{
title: '选择任务模板',
body: []
},
{
title: '填写任务信息',
body: []
},
{
title: '完成',
body: []
},
]
},
},
)}
</div>
)
}
export default FlowTaskAdd

View File

@@ -0,0 +1,108 @@
import React from 'react'
import {amisRender, commonInfo, crudCommonOptions, paginationTemplate,} from '../../../../util/amis.tsx'
import {useNavigate} from 'react-router'
const FlowTaskTemplate: React.FC = () => {
const navigate = useNavigate()
return (
<div className="task-template">
{amisRender(
{
type: 'page',
title: '任务模板',
body: [
{
type: 'crud',
api: {
method: 'post',
url: `${commonInfo.baseAiUrl}/flow_task/template/list`,
data: {
page: {
index: '${page}',
size: '${perPage}',
}
}
},
...crudCommonOptions(),
...paginationTemplate(
10,
5,
[
{
type: 'action',
label: '',
icon: 'fa fa-plus',
size: 'sm',
onEvent: {
click: {
actions: [
{
actionType: 'custom',
// @ts-ignore
script: (context, action, event) => {
navigate(`/ai/flow_task_template/edit/-1`)
},
},
],
},
},
},
],
),
columns: [
{
name: 'name',
label: '名称',
width: 200,
},
{
name: 'description',
label: '描述',
},
{
type: 'operation',
label: '操作',
width: 200,
buttons: [
{
type: 'action',
label: '编辑',
level: 'link',
size: 'sm',
onEvent: {
click: {
actions: [
{
actionType: 'custom',
// @ts-ignore
script: (context, action, event) => {
navigate(`/ai/flow_task_template/edit/${context.props.data['id']}`)
},
},
],
},
},
},
{
type: 'action',
label: '删除',
className: 'text-danger btn-deleted',
level: 'link',
size: 'sm',
actionType: 'ajax',
api: `get:${commonInfo.baseAiUrl}/flow_task/template/remove/\${id}`,
confirmText: '确认删除任务模板:${name}',
confirmTitle: '删除',
},
],
},
],
},
],
},
)}
</div>
)
}
export default FlowTaskTemplate

View File

@@ -0,0 +1,118 @@
import React from 'react'
import {useParams} from 'react-router'
import styled from 'styled-components'
import {amisRender, commonInfo, horizontalFormOptions} from '../../../../util/amis.tsx'
import {isEqual} from 'licia'
const TemplateEditDiv = styled.div`
.antd-EditorControl {
min-height: 500px !important;
}
`
const FlowTaskTemplateEdit: React.FC = () => {
const {template_id} = useParams()
const preloadTemplateId = isEqual(template_id, '-1') ? undefined : template_id
console.log('preloadTemplateId', preloadTemplateId)
return (
<TemplateEditDiv className="task-template-edit h-full">
{amisRender({
type: 'page',
title: '模板编辑',
body: {
debug: commonInfo.debug,
type: 'form',
api: {
method: 'POST',
url: `${commonInfo.baseAiUrl}/flow_task/template/save`,
data: {
name: '${template.name}',
description: '${template.description}',
inputSchema: '${template.inputSchema}',
flow: '${template.flow}',
}
},
initApi: preloadTemplateId
? {
method: 'GET',
url: `${commonInfo.baseAiUrl}/flow_task/template/detail/${preloadTemplateId}`,
// @ts-ignore
adaptor: (payload, response, api, context) => {
return {
...payload,
data: {
template: payload.data,
},
}
},
}
: undefined,
wrapWithPanel: false,
...horizontalFormOptions(),
body: [
{
type: 'input-text',
name: 'template.name',
label: '名称',
required: true,
},
{
type: 'textarea',
name: 'template.description',
label: '描述',
required: true,
},
{
type: 'group',
body: [
{
type: 'editor',
required: true,
label: '入参表单',
description: '使用amis代码编写入参表单结构流程会解析所有name对应的变量传入流程开始阶段只需要编写form的columns部分',
name: 'template.inputSchema',
value: '[]',
language: 'json',
options: {
wordWrap: 'bounded',
},
},
{
type: 'amis',
name: 'template.inputSchema',
}
]
},
{
type: 'editor',
required: true,
label: '任务流程',
name: 'template.flow',
description: '使用标准的LiteFlow语法',
language: 'xml',
options: {
wordWrap: 'bounded',
},
},
{
type: 'button-toolbar',
buttons: [
{
type: 'submit',
label: '提交',
level: 'primary',
},
{
type: 'reset',
label: '重置',
},
],
},
],
},
})}
</TemplateEditDiv>
)
}
export default FlowTaskTemplateEdit

View File

@@ -31,7 +31,7 @@ const queueCrud = (name: string) => {
{
name: 'data.flinkJobId',
label: '任务 ID',
width: 190,
width: 200,
...copyField('data.flinkJobId'),
},
{

View File

@@ -4,6 +4,8 @@ import {
ClusterOutlined,
CompressOutlined,
DatabaseOutlined,
FileTextOutlined,
GatewayOutlined,
InfoCircleOutlined,
OpenAIOutlined,
QuestionOutlined,
@@ -32,6 +34,11 @@ import Yarn from './pages/overview/Yarn.tsx'
import YarnCluster from './pages/overview/YarnCluster.tsx'
import Test from './pages/Test.tsx'
import {commonInfo} from './util/amis.tsx'
import FlowEditor from './pages/ai/flow/FlowEditor.tsx'
import FlowTaskTemplate from './pages/ai/task/template/FlowTaskTemplate.tsx'
import FlowTaskTemplateEdit from './pages/ai/task/template/FlowTaskTemplateEdit.tsx'
import FlowTask from './pages/ai/task/FlowTask.tsx'
import FlowTaskAdd from './pages/ai/task/FlowTaskAdd.tsx'
export const routes: RouteObject[] = [
{
@@ -109,6 +116,26 @@ export const routes: RouteObject[] = [
path: 'knowledge/detail/:knowledge_id/segment/:group_id',
Component: DataSegment,
},
{
path: 'flow_task',
Component: FlowTask,
},
{
path: 'flow_task/add',
Component: FlowTaskAdd,
},
{
path: 'flow_task_template',
Component: FlowTaskTemplate,
},
{
path: 'flow_task_template/edit/:template_id',
Component: FlowTaskTemplateEdit,
},
{
path: 'flowable',
Component: FlowEditor,
},
],
},
{
@@ -152,7 +179,7 @@ export const menus = {
icon: <SyncOutlined/>,
},
{
path: `/yarn/${commonInfo.clusters.compaction_names()}/${values(commonInfo.clusters.compaction).join(",")}/Compaction`,
path: `/yarn/${commonInfo.clusters.compaction_names()}/${values(commonInfo.clusters.compaction).join(',')}/Compaction`,
name: '压缩集群',
icon: <SyncOutlined/>,
},
@@ -211,6 +238,28 @@ export const menus = {
name: '知识库',
icon: <DatabaseOutlined/>,
},
{
path: '/ai/flowable',
name: '流程编排',
icon: <GatewayOutlined/>,
},
{
path: '1089caa6-9477-44a5-99f1-a9c179f6cfd3',
name: '任务',
icon: <FileTextOutlined/>,
routes: [
{
path: '/ai/flow_task',
name: '任务列表',
icon: <FileTextOutlined/>,
},
{
path: '/ai/flow_task_template',
name: '任务模板',
icon: <FileTextOutlined/>,
},
]
},
],
},
],

View File

@@ -10,8 +10,8 @@ import {isEqual} from 'licia'
export const commonInfo = {
debug: isEqual(import.meta.env.MODE, 'development'),
baseUrl: 'http://132.126.207.130:35690/hudi_services/service_web',
baseAiUrl: 'http://132.126.207.130:35690/hudi_services/service_ai_web',
// baseAiUrl: 'http://localhost:8080',
// baseAiUrl: 'http://132.126.207.130:35690/hudi_services/service_ai_web',
baseAiUrl: 'http://localhost:8080',
authorizationHeaders: {
'Authorization': 'Basic QXhoRWJzY3dzSkRiWU1IMjpjWXhnM2I0UHRXb1ZENVNqRmF5V3h0blNWc2p6UnNnNA==',
'Content-Type': 'application/json',
@@ -274,6 +274,15 @@ export function serviceLogByAppNameAndHost(name: string, host: string) {
)
}
export function horizontalFormOptions() {
return {
mode: 'horizontal',
horizontal: {
leftFixed: 'sm'
},
}
}
export function crudCommonOptions() {
return {
affixHeader: false,