Compare commits
49 Commits
jpa
...
8ebaf5de8e
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8ebaf5de8e | ||
|
|
5f7eeb3596 | ||
|
|
064443f740 | ||
|
|
6809750cfa | ||
|
|
49cb62b287 | ||
|
|
5cbda28594 | ||
|
|
11c5481287 | ||
|
|
67e0cada00 | ||
|
|
cdf51cc85f | ||
|
|
9277d1690c | ||
|
|
24ac681cb3 | ||
|
|
c46da52942 | ||
|
|
7209b52e3d | ||
|
|
959d6fb5c7 | ||
|
|
c5c62ab713 | ||
| e59e89a5ad | |||
| b7626180c1 | |||
|
|
68e54d5110 | ||
|
|
5f133fbfc3 | ||
|
|
d28fbbbba8 | ||
|
|
67f41c08a0 | ||
| 111ca49815 | |||
| 779fd0eb18 | |||
| 8884495a89 | |||
| d08a6babbe | |||
| 9a3375bd03 | |||
|
|
2c808a5bc9 | ||
|
|
6e667c45e1 | ||
|
|
635c6537ed | ||
|
|
d6b70b1750 | ||
|
|
c92a374591 | ||
|
|
a2aba82b6e | ||
| 873c1a1d20 | |||
|
|
f6bd7e52e1 | ||
|
|
6f7f7cea67 | ||
|
|
33df256863 | ||
|
|
3a51d1e33f | ||
|
|
d3c7457889 | ||
| 2d2eaafcd4 | |||
|
|
566dfef208 | ||
| 1cba0f4422 | |||
| ab56385c8a | |||
| b58c34443f | |||
| 53638a8a6d | |||
| dc55605c99 | |||
| 7345774258 | |||
| fcf5f8ad18 | |||
|
|
b53ee57dc3 | ||
|
|
b916acb1c3 |
1
.gitignore
vendored
1
.gitignore
vendored
@@ -110,3 +110,4 @@ Network Trash Folder
|
||||
Temporary Items
|
||||
.apdisk
|
||||
**/temp/
|
||||
.build
|
||||
@@ -1,5 +1,5 @@
|
||||
import {$, fetch, fs, glob, os, path, spinner, syncProcessCwd, usePowerShell} from 'zx'
|
||||
import {isEqual, trim, fileSize} from "licia";
|
||||
import {fileSize, isEqual, trim} from "licia";
|
||||
import md5file from 'md5-file'
|
||||
|
||||
syncProcessCwd(true)
|
||||
@@ -41,20 +41,70 @@ const millisecondToString = (timestamp) => {
|
||||
return parts.join('')
|
||||
}
|
||||
|
||||
const dotBuildPath = () => `.build`
|
||||
const modifiedDataPath = () => `${dotBuildPath()}/modified_time.json`
|
||||
|
||||
const readModifiedTimeData = async () => {
|
||||
if (!fs.existsSync(dotBuildPath())) {
|
||||
fs.mkdirSync(dotBuildPath(), {recursive: true})
|
||||
}
|
||||
if (!(await fs.exists(modifiedDataPath()))) {
|
||||
fs.writeFileSync(modifiedDataPath(), '{}')
|
||||
}
|
||||
return JSON.parse(await fs.readFile(modifiedDataPath(), 'utf-8'))
|
||||
}
|
||||
|
||||
const updateModifiedTimeData = (data) => {
|
||||
fs.writeFileSync(modifiedDataPath(), JSON.stringify(data, null, 2))
|
||||
}
|
||||
|
||||
const isModified = async (target) => {
|
||||
if (!target || !(await fs.exists(target))) {
|
||||
throw new Error("Target 不存在")
|
||||
}
|
||||
let stat = fs.statSync(target)
|
||||
let currentModifiedTime = stat.mtimeMs
|
||||
|
||||
let lastModifiedTime = (await readModifiedTimeData())[target]
|
||||
return !(lastModifiedTime && isEqual(currentModifiedTime, lastModifiedTime));
|
||||
|
||||
}
|
||||
|
||||
const updateModifiedTime = async (target) => {
|
||||
if (!target || !(await fs.exists(target))) {
|
||||
throw new Error("Target 不存在")
|
||||
}
|
||||
let stat = fs.statSync(target)
|
||||
let currentModifiedTime = stat.mtimeMs
|
||||
let modifiedTimeData = await readModifiedTimeData()
|
||||
modifiedTimeData[target] = currentModifiedTime
|
||||
updateModifiedTimeData(modifiedTimeData)
|
||||
}
|
||||
|
||||
export const run_deploy = async (project) => {
|
||||
if (!(await isModified(project))) {
|
||||
console.log(`✅ Skip deploy ${project}`)
|
||||
return
|
||||
}
|
||||
let output = await spinner(
|
||||
`Deploying project ${project}`,
|
||||
() => $`mvn -pl ${project} clean deploy -D skipTests -s ${maven_setting}`
|
||||
)
|
||||
console.log(`✅ Finished deploy ${project} (${millisecondToString(output['duration'])})`)
|
||||
await updateModifiedTime(project)
|
||||
}
|
||||
|
||||
export const run_deploy_root = async () => {
|
||||
if (!(await isModified('pom.xml'))) {
|
||||
console.log(`✅ Skip deploy root`)
|
||||
return
|
||||
}
|
||||
let output = await spinner(
|
||||
`Deploying root`,
|
||||
() => $`mvn clean deploy -N -D skipTests -s ${maven_setting}`
|
||||
)
|
||||
console.log(`✅ Finished deploy root (${millisecondToString(output['duration'])})`)
|
||||
await updateModifiedTime('pom.xml')
|
||||
}
|
||||
|
||||
export const run_deploy_batch = async (projects) => {
|
||||
|
||||
3
bin/test.js
Normal file
3
bin/test.js
Normal file
@@ -0,0 +1,3 @@
|
||||
import {isModified} from './library.js'
|
||||
|
||||
console.log(await isModified('/Users/lanyuanxiaoyao/Project/IdeaProjects/hudi-service/pom.xml'))
|
||||
82
service-ai/database/20250702.sql
Normal file
82
service-ai/database/20250702.sql
Normal file
@@ -0,0 +1,82 @@
|
||||
create table hudi_collect_build_b12.service_ai_feedback
|
||||
(
|
||||
id bigint not null comment '记录唯一标记',
|
||||
created_time datetime(6) comment '记录创建时间',
|
||||
modified_time datetime(6) comment '记录更新时间',
|
||||
analysis longtext comment 'AI的分析结果',
|
||||
conclusion longtext comment 'AI的解决方案',
|
||||
source longtext not null comment '原始报障说明',
|
||||
status enum ('ANALYSIS_PROCESSING','ANALYSIS_SUCCESS','FINISHED') not null comment '报障处理状态',
|
||||
primary key (id)
|
||||
) comment ='报障信息记录' charset = utf8mb4;
|
||||
|
||||
create table hudi_collect_build_b12.service_ai_feedback_pictures
|
||||
(
|
||||
feedback_id bigint not null,
|
||||
pictures_id bigint not null,
|
||||
primary key (feedback_id, pictures_id)
|
||||
) comment ='报障相关截图' charset = utf8mb4;
|
||||
|
||||
alter table hudi_collect_build_b12.service_ai_feedback_pictures
|
||||
add constraint UK3npjcyjyqfbdlf2v5tj64j2g3 unique (pictures_id);
|
||||
|
||||
create table hudi_collect_build_b12.service_ai_file
|
||||
(
|
||||
id bigint not null comment '记录唯一标记',
|
||||
created_time datetime(6) comment '记录创建时间',
|
||||
modified_time datetime(6) comment '记录更新时间',
|
||||
filename varchar(255) comment '文件名称',
|
||||
md5 varchar(255) comment '文件的md5编码,用于校验文件的完整性',
|
||||
path varchar(255) comment '文件在主机上存储的实际路径',
|
||||
size bigint comment '文件大小,单位是byte',
|
||||
type varchar(255) comment '文件类型,通常记录的是文件的后缀名',
|
||||
primary key (id)
|
||||
) comment ='记录上传的文件存储信息' charset = utf8mb4;
|
||||
|
||||
create table hudi_collect_build_b12.service_ai_flow_task
|
||||
(
|
||||
id bigint not null comment '记录唯一标记',
|
||||
created_time datetime(6) comment '记录创建时间',
|
||||
modified_time datetime(6) comment '记录更新时间',
|
||||
error longtext comment '任务运行产生的报错',
|
||||
input longtext comment '任务输入',
|
||||
result longtext comment '任务运行结果',
|
||||
status enum ('ERROR','FINISHED','RUNNING') not null comment '任务运行状态',
|
||||
template_id bigint not null comment '流程任务对应的模板',
|
||||
primary key (id)
|
||||
) comment ='流程任务记录' charset = utf8mb4;
|
||||
|
||||
create table hudi_collect_build_b12.service_ai_flow_task_template
|
||||
(
|
||||
id bigint not null comment '记录唯一标记',
|
||||
created_time datetime(6) comment '记录创建时间',
|
||||
modified_time datetime(6) comment '记录更新时间',
|
||||
description varchar(255) comment '模板功能、内容说明',
|
||||
flow_graph longtext comment '前端流程图数据',
|
||||
input_schema longtext not null comment '模板入参Schema',
|
||||
name varchar(255) not null comment '模板名称',
|
||||
primary key (id)
|
||||
) comment ='流程任务模板' charset = utf8mb4;
|
||||
|
||||
create table hudi_collect_build_b12.service_ai_group
|
||||
(
|
||||
id bigint not null comment '记录唯一标记',
|
||||
created_time datetime(6) comment '记录创建时间',
|
||||
modified_time datetime(6) comment '记录更新时间',
|
||||
name varchar(255) not null comment '分组名称',
|
||||
status enum ('FINISHED','RUNNING') not null comment '分组处理状态',
|
||||
knowledge_id bigint not null,
|
||||
primary key (id)
|
||||
) comment ='知识库下包含的分组' charset = utf8mb4;
|
||||
|
||||
create table hudi_collect_build_b12.service_ai_knowledge
|
||||
(
|
||||
id bigint not null comment '记录唯一标记',
|
||||
created_time datetime(6) comment '记录创建时间',
|
||||
modified_time datetime(6) comment '记录更新时间',
|
||||
description longtext not null comment '知识库说明',
|
||||
name varchar(255) not null comment '知识库名称',
|
||||
strategy enum ('Cosine','Euclid') not null comment '知识库策略',
|
||||
vector_source_id bigint not null comment '知识库对应的向量库名',
|
||||
primary key (id)
|
||||
) comment ='知识库' charset = utf8mb4;
|
||||
@@ -1,18 +0,0 @@
|
||||
CREATE TABLE `service_ai_feedback`
|
||||
(
|
||||
`id` bigint NOT NULL,
|
||||
`created_time` datetime(6) DEFAULT NULL,
|
||||
`modified_time` datetime(6) DEFAULT NULL,
|
||||
`analysis` longtext,
|
||||
`conclusion` longtext,
|
||||
`source` longtext NOT NULL,
|
||||
`status` tinyint NOT NULL,
|
||||
PRIMARY KEY (`id`)
|
||||
) DEFAULT CHARSET = utf8mb4;
|
||||
|
||||
CREATE TABLE `service_ai_feedback_pictures`
|
||||
(
|
||||
`feedback_id` bigint NOT NULL,
|
||||
`pictures_id` bigint NOT NULL,
|
||||
PRIMARY KEY (`feedback_id`, `pictures_id`)
|
||||
) DEFAULT CHARSET = utf8mb4;
|
||||
@@ -1,12 +0,0 @@
|
||||
CREATE TABLE `service_ai_file`
|
||||
(
|
||||
`id` bigint NOT NULL,
|
||||
`created_time` datetime(6) DEFAULT NULL,
|
||||
`modified_time` datetime(6) DEFAULT NULL,
|
||||
`filename` varchar(255) DEFAULT NULL,
|
||||
`md5` varchar(255) DEFAULT NULL,
|
||||
`path` varchar(255) DEFAULT NULL,
|
||||
`size` bigint DEFAULT NULL,
|
||||
`type` varchar(255) DEFAULT NULL,
|
||||
PRIMARY KEY (`id`)
|
||||
) DEFAULT CHARSET = utf8mb4;
|
||||
@@ -1,10 +0,0 @@
|
||||
CREATE TABLE `service_ai_group`
|
||||
(
|
||||
`id` bigint NOT NULL,
|
||||
`created_time` datetime(6) DEFAULT NULL,
|
||||
`modified_time` datetime(6) DEFAULT NULL,
|
||||
`name` varchar(255) NOT NULL,
|
||||
`status` tinyint NOT NULL,
|
||||
`knowledge_id` bigint NOT NULL,
|
||||
PRIMARY KEY (`id`)
|
||||
) DEFAULT CHARSET=utf8mb4;
|
||||
@@ -1,11 +0,0 @@
|
||||
CREATE TABLE `service_ai_knowledge`
|
||||
(
|
||||
`id` bigint NOT NULL,
|
||||
`created_time` datetime(6) DEFAULT NULL,
|
||||
`modified_time` datetime(6) DEFAULT NULL,
|
||||
`description` longtext NOT NULL,
|
||||
`name` varchar(255) NOT NULL,
|
||||
`strategy` tinyint NOT NULL,
|
||||
`vector_source_id` bigint NOT NULL,
|
||||
PRIMARY KEY (`id`)
|
||||
) DEFAULT CHARSET = utf8mb4;
|
||||
@@ -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>
|
||||
|
||||
@@ -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,30 @@ 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);
|
||||
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();
|
||||
|
||||
@@ -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>
|
||||
@@ -78,6 +82,13 @@
|
||||
<groupId>org.noear</groupId>
|
||||
<artifactId>solon-ai-dialect-openai</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.hibernate.orm</groupId>
|
||||
<artifactId>hibernate-ant</artifactId>
|
||||
<version>6.6.8.Final</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
||||
@@ -2,15 +2,12 @@ package com.lanyuanxiaoyao.service.ai.web;
|
||||
|
||||
import com.blinkfox.fenix.EnableFenix;
|
||||
import com.ulisesbocchio.jasyptspringboot.annotation.EnableEncryptableProperties;
|
||||
import org.springframework.beans.BeansException;
|
||||
import org.springframework.boot.ApplicationArguments;
|
||||
import org.springframework.boot.ApplicationRunner;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.ApplicationContextAware;
|
||||
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
|
||||
import org.springframework.retry.annotation.EnableRetry;
|
||||
import org.springframework.scheduling.annotation.EnableScheduling;
|
||||
@@ -27,27 +24,13 @@ import org.springframework.scheduling.annotation.EnableScheduling;
|
||||
@EnableScheduling
|
||||
@EnableFenix
|
||||
@EnableJpaAuditing
|
||||
public class WebApplication implements ApplicationRunner, ApplicationContextAware {
|
||||
private static ApplicationContext context;
|
||||
public class WebApplication implements ApplicationRunner {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(WebApplication.class, args);
|
||||
}
|
||||
|
||||
public static <T> T getBean(Class<T> clazz) {
|
||||
return context.getBean(clazz);
|
||||
}
|
||||
|
||||
public static <T> T getBean(String name, Class<T> clazz) {
|
||||
return context.getBean(name, clazz);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run(ApplicationArguments args) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setApplicationContext(ApplicationContext context) throws BeansException {
|
||||
WebApplication.context = context;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import jakarta.persistence.MappedSuperclass;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import lombok.ToString;
|
||||
import org.hibernate.annotations.Comment;
|
||||
import org.hibernate.annotations.GenericGenerator;
|
||||
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
|
||||
|
||||
@@ -22,6 +23,7 @@ import org.springframework.data.jpa.domain.support.AuditingEntityListener;
|
||||
@MappedSuperclass
|
||||
@EntityListeners(AuditingEntityListener.class)
|
||||
public class IdOnlyEntity {
|
||||
@Comment("记录唯一标记")
|
||||
@Id
|
||||
@GeneratedValue(generator = "snowflake")
|
||||
@GenericGenerator(name = "snowflake", strategy = "com.lanyuanxiaoyao.service.ai.web.configuration.SnowflakeIdGenerator")
|
||||
|
||||
@@ -6,6 +6,7 @@ import java.time.LocalDateTime;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import lombok.ToString;
|
||||
import org.hibernate.annotations.Comment;
|
||||
import org.springframework.data.annotation.CreatedDate;
|
||||
import org.springframework.data.annotation.LastModifiedDate;
|
||||
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
|
||||
@@ -22,8 +23,10 @@ import org.springframework.data.jpa.domain.support.AuditingEntityListener;
|
||||
@MappedSuperclass
|
||||
@EntityListeners(AuditingEntityListener.class)
|
||||
public class SimpleEntity extends IdOnlyEntity {
|
||||
@Comment("记录创建时间")
|
||||
@CreatedDate
|
||||
private LocalDateTime createdTime;
|
||||
@Comment("记录更新时间")
|
||||
@LastModifiedDate
|
||||
private LocalDateTime modifiedTime;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.lanyuanxiaoyao.service.ai.web.configuration;
|
||||
|
||||
import org.springframework.beans.BeansException;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.ApplicationContextAware;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class SpringBeanGetter implements ApplicationContextAware {
|
||||
private static ApplicationContext context;
|
||||
|
||||
public static <T> T getBean(Class<T> clazz) {
|
||||
return context.getBean(clazz);
|
||||
}
|
||||
|
||||
public static <T> T getBean(String name, Class<T> clazz) {
|
||||
return context.getBean(name, clazz);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setApplicationContext(ApplicationContext context) throws BeansException {
|
||||
SpringBeanGetter.context = context;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
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;
|
||||
import java.util.Map;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
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.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> {
|
||||
private final ObjectMapper mapper;
|
||||
|
||||
public TaskTemplateController(FlowTaskTemplateService flowTaskTemplateService, Jackson2ObjectMapperBuilder builder) {
|
||||
super(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;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected SaveItemMapper<FlowTaskTemplate, SaveItem> saveItemMapper() {
|
||||
SaveItem.Mapper map = Mappers.getMapper(SaveItem.Mapper.class);
|
||||
return item -> map.from(item, mapper);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ListItemMapper<FlowTaskTemplate, ListItem> listItemMapper() {
|
||||
return Mappers.getMapper(ListItem.Mapper.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected DetailItemMapper<FlowTaskTemplate, DetailItem> detailItemMapper() {
|
||||
DetailItem.Mapper map = Mappers.getMapper(DetailItem.Mapper.class);
|
||||
return template -> map.from(template, mapper);
|
||||
}
|
||||
|
||||
@Data
|
||||
public static final class SaveItem {
|
||||
private Long id;
|
||||
private String name;
|
||||
private String description;
|
||||
private Map<String, Object> inputSchema;
|
||||
|
||||
@org.mapstruct.Mapper
|
||||
public static abstract class Mapper {
|
||||
public abstract FlowTaskTemplate from(SaveItem saveItem, @Context ObjectMapper mapper) throws Exception;
|
||||
|
||||
protected String mapInputSchema(Map<String, Object> inputSchema, @Context ObjectMapper mapper) throws JsonProcessingException {
|
||||
return mapper.writeValueAsString(inputSchema);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@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 Map<String, Object> inputSchema;
|
||||
|
||||
@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<>() {});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.lanyuanxiaoyao.service.ai.web.engine;
|
||||
|
||||
import com.lanyuanxiaoyao.service.ai.web.engine.entity.FlowGraph;
|
||||
import com.lanyuanxiaoyao.service.ai.web.engine.store.FlowStore;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import org.eclipse.collections.api.map.ImmutableMap;
|
||||
|
||||
/**
|
||||
* 流程执行器
|
||||
*
|
||||
* @author lanyuanxiaoyao
|
||||
* @version 20250630
|
||||
*/
|
||||
public class FlowExecutor {
|
||||
private final FlowStore flowStore;
|
||||
private final ImmutableMap<String, Class<? extends FlowNodeRunner>> runnerMap;
|
||||
|
||||
public FlowExecutor(FlowStore flowStore, ImmutableMap<String, Class<? extends FlowNodeRunner>> runnerMap) {
|
||||
this.flowStore = flowStore;
|
||||
this.runnerMap = runnerMap;
|
||||
}
|
||||
|
||||
public void execute(FlowGraph graph) throws InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException {
|
||||
var runner = new FlowGraphRunner(graph, flowStore, runnerMap);
|
||||
runner.run();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
package com.lanyuanxiaoyao.service.ai.web.engine;
|
||||
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import com.lanyuanxiaoyao.service.ai.web.engine.entity.FlowContext;
|
||||
import com.lanyuanxiaoyao.service.ai.web.engine.entity.FlowEdge;
|
||||
import com.lanyuanxiaoyao.service.ai.web.engine.entity.FlowGraph;
|
||||
import com.lanyuanxiaoyao.service.ai.web.engine.entity.FlowNode;
|
||||
import com.lanyuanxiaoyao.service.ai.web.engine.store.FlowStore;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.util.LinkedList;
|
||||
import java.util.Queue;
|
||||
import org.eclipse.collections.api.map.ImmutableMap;
|
||||
import org.eclipse.collections.api.multimap.set.ImmutableSetMultimap;
|
||||
|
||||
/**
|
||||
* Graph执行器
|
||||
*
|
||||
* @author lanyuanxiaoyao
|
||||
* @version 20250701
|
||||
*/
|
||||
public final class FlowGraphRunner {
|
||||
private final FlowGraph flowGraph;
|
||||
private final FlowStore flowStore;
|
||||
private final ImmutableMap<String, Class<? extends FlowNodeRunner>> nodeRunnerClass;
|
||||
private final Queue<FlowNode> executionQueue = new LinkedList<>();
|
||||
private final ImmutableSetMultimap<String, FlowEdge> nodeInputMap;
|
||||
private final ImmutableSetMultimap<String, FlowEdge> nodeOutputMap;
|
||||
private final ImmutableMap<String, FlowNode> nodeMap;
|
||||
|
||||
public FlowGraphRunner(FlowGraph flowGraph, FlowStore flowStore, ImmutableMap<String, Class<? extends FlowNodeRunner>> nodeRunnerClass) {
|
||||
this.flowGraph = flowGraph;
|
||||
this.flowStore = flowStore;
|
||||
this.nodeRunnerClass = nodeRunnerClass;
|
||||
|
||||
nodeInputMap = flowGraph.edges().groupBy(FlowEdge::target);
|
||||
nodeOutputMap = flowGraph.edges().groupBy(FlowEdge::source);
|
||||
nodeMap = flowGraph.nodes().toImmutableMap(FlowNode::id, node -> node);
|
||||
}
|
||||
|
||||
public void run() throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
|
||||
flowStore.init(flowGraph);
|
||||
|
||||
var context = new FlowContext();
|
||||
for (FlowNode node : flowGraph.nodes()) {
|
||||
executionQueue.offer(node);
|
||||
}
|
||||
while (!executionQueue.isEmpty()) {
|
||||
var node = executionQueue.poll();
|
||||
process(node, context);
|
||||
}
|
||||
}
|
||||
|
||||
private void process(FlowNode node, FlowContext context) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
|
||||
if (
|
||||
(
|
||||
// 没有入节点,即开始节点
|
||||
!nodeInputMap.containsKey(node.id())
|
||||
// 或者所有入的边状态都已经完成
|
||||
|| nodeInputMap.get(node.id()).allSatisfy(edge -> flowStore.checkEdgeStatus(flowGraph.id(), edge.id(), FlowEdge.Status.EXECUTE, FlowEdge.Status.SKIP))
|
||||
)
|
||||
// 当前节点还未执行
|
||||
&& flowStore.checkNodeStatus(flowGraph.id(), node.id(), FlowNode.Status.INITIAL)
|
||||
) {
|
||||
// 是开始节点或入的边有至少一条是「执行」
|
||||
if (
|
||||
!nodeInputMap.containsKey(node.id())
|
||||
|| nodeInputMap.get(node.id()).anySatisfy(edge -> flowStore.checkEdgeStatus(flowGraph.id(), edge.id(), FlowEdge.Status.EXECUTE))
|
||||
) {
|
||||
flowStore.updateNodeToRunning(flowGraph.id(), node.id());
|
||||
|
||||
var runnerClazz = nodeRunnerClass.get(node.type());
|
||||
var runner = runnerClazz.getDeclaredConstructor().newInstance();
|
||||
runner.setNodeId(node.id());
|
||||
runner.setContext(context);
|
||||
runner.run();
|
||||
|
||||
if (runner instanceof FlowNodeOptionalRunner) {
|
||||
var targetPoint = ((FlowNodeOptionalRunner) runner).getTargetPoint();
|
||||
for (FlowEdge edge : nodeOutputMap.get(node.id())) {
|
||||
if (StrUtil.equals(targetPoint, edge.sourcePoint())) {
|
||||
flowStore.updateEdgeToExecute(flowGraph.id(), edge.id());
|
||||
} else {
|
||||
flowStore.updateEdgeToSkip(flowGraph.id(), edge.id());
|
||||
}
|
||||
executionQueue.offer(nodeMap.get(edge.target()));
|
||||
}
|
||||
} else {
|
||||
for (FlowEdge edge : nodeOutputMap.get(node.id())) {
|
||||
flowStore.updateEdgeToExecute(flowGraph.id(), edge.id());
|
||||
executionQueue.offer(nodeMap.get(edge.target()));
|
||||
}
|
||||
}
|
||||
|
||||
flowStore.updateNodeToFinished(flowGraph.id(), node.id());
|
||||
}
|
||||
// 所有入的边都是跳过,当前节点就跳过
|
||||
else {
|
||||
flowStore.updateNodeToSkipped(flowGraph.id(), node.id());
|
||||
|
||||
for (FlowEdge edge : nodeOutputMap.get(node.id())) {
|
||||
flowStore.updateEdgeToSkip(flowGraph.id(), edge.id());
|
||||
executionQueue.offer(nodeMap.get(edge.target()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.lanyuanxiaoyao.service.ai.web.engine;
|
||||
|
||||
import lombok.Getter;
|
||||
|
||||
public abstract class FlowNodeOptionalRunner extends FlowNodeRunner {
|
||||
@Getter
|
||||
private String targetPoint;
|
||||
|
||||
public abstract String runOptional();
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
this.targetPoint = runOptional();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.lanyuanxiaoyao.service.ai.web.engine;
|
||||
|
||||
import com.lanyuanxiaoyao.service.ai.web.engine.entity.FlowContext;
|
||||
import lombok.Getter;
|
||||
|
||||
public abstract class FlowNodeRunner {
|
||||
@Getter
|
||||
private String nodeId;
|
||||
@Getter
|
||||
private FlowContext context;
|
||||
|
||||
public abstract void run();
|
||||
|
||||
void setNodeId(String nodeId) {
|
||||
this.nodeId = nodeId;
|
||||
}
|
||||
|
||||
void setContext(FlowContext context) {
|
||||
this.context = context;
|
||||
}
|
||||
|
||||
protected <T> T getData(String key) {
|
||||
var data = context.get(nodeId);
|
||||
return (T) data.get(key);
|
||||
}
|
||||
|
||||
protected <T> void setData(String key, T value) {
|
||||
var data = context.get(nodeId);
|
||||
data.put(key, value);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.lanyuanxiaoyao.service.ai.web.engine.entity;
|
||||
|
||||
import lombok.Data;
|
||||
import org.eclipse.collections.api.factory.Maps;
|
||||
import org.eclipse.collections.api.map.MutableMap;
|
||||
|
||||
@Data
|
||||
public class FlowContext {
|
||||
private MutableMap<String, MutableMap<String, Object>> data = Maps.mutable.<String, MutableMap<String, Object>>empty().asSynchronized();
|
||||
|
||||
public MutableMap<String, Object> get(String key) {
|
||||
if (!data.containsKey(key)) {
|
||||
data.put(key, Maps.mutable.<String, Object>empty().asSynchronized());
|
||||
}
|
||||
return data.get(key);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.lanyuanxiaoyao.service.ai.web.engine.entity;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 流程图中的边
|
||||
*
|
||||
* @author lanyuanxiaoyao
|
||||
* @version 20250630
|
||||
*/
|
||||
public record FlowEdge(
|
||||
String id,
|
||||
String source,
|
||||
String target,
|
||||
String sourcePoint,
|
||||
String targetPoint
|
||||
) {
|
||||
public enum Status {
|
||||
INITIAL, EXECUTE, SKIP
|
||||
}
|
||||
|
||||
public record State(
|
||||
String id,
|
||||
Status status,
|
||||
LocalDateTime startingTime,
|
||||
LocalDateTime finishedTime
|
||||
) {
|
||||
public State(String edgeId) {
|
||||
this(edgeId, Status.INITIAL, LocalDateTime.now(), null);
|
||||
}
|
||||
|
||||
public State(String edgeId, Status status) {
|
||||
this(edgeId, status, LocalDateTime.now(), null);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.lanyuanxiaoyao.service.ai.web.engine.entity;
|
||||
|
||||
import org.eclipse.collections.api.set.ImmutableSet;
|
||||
|
||||
/**
|
||||
* 流程图
|
||||
*
|
||||
* @author lanyuanxiaoyao
|
||||
* @version 20250630
|
||||
*/
|
||||
public record FlowGraph(
|
||||
String id,
|
||||
ImmutableSet<FlowNode> nodes,
|
||||
ImmutableSet<FlowEdge> edges
|
||||
) {
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package com.lanyuanxiaoyao.service.ai.web.engine.entity;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 流程图中的节点
|
||||
*
|
||||
* @author lanyuanxiaoyao
|
||||
* @version 20250630
|
||||
*/
|
||||
public record FlowNode(
|
||||
String id,
|
||||
String type
|
||||
) {
|
||||
public enum Status {
|
||||
INITIAL, RUNNING, FINISHED, SKIPPED
|
||||
}
|
||||
|
||||
public record State(
|
||||
String id,
|
||||
Status status,
|
||||
LocalDateTime startingTime,
|
||||
LocalDateTime finishedTime
|
||||
) {
|
||||
public State(String nodeId) {
|
||||
this(nodeId, Status.INITIAL, LocalDateTime.now(), null);
|
||||
}
|
||||
|
||||
public State(String nodeId, Status status) {
|
||||
this(nodeId, status, LocalDateTime.now(), null);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.lanyuanxiaoyao.service.ai.web.engine.store;
|
||||
|
||||
import com.lanyuanxiaoyao.service.ai.web.engine.entity.FlowEdge;
|
||||
import com.lanyuanxiaoyao.service.ai.web.engine.entity.FlowGraph;
|
||||
import com.lanyuanxiaoyao.service.ai.web.engine.entity.FlowNode;
|
||||
|
||||
/**
|
||||
* 存储状态
|
||||
*
|
||||
* @author lanyuanxiaoyao
|
||||
* @version 20250701
|
||||
*/
|
||||
public interface FlowStore {
|
||||
void init(FlowGraph flowGraph);
|
||||
|
||||
void updateNodeToRunning(String graphId, String nodeId);
|
||||
|
||||
void updateNodeToSkipped(String graphId, String nodeId);
|
||||
|
||||
void updateNodeToFinished(String graphId, String nodeId);
|
||||
|
||||
void updateEdgeToExecute(String graphId, String edgeId);
|
||||
|
||||
void updateEdgeToSkip(String graphId, String edgeId);
|
||||
|
||||
boolean checkNodeStatus(String graphId, String nodeId, FlowNode.Status... statuses);
|
||||
|
||||
boolean checkEdgeStatus(String graphId, String edgeId, FlowEdge.Status... statuses);
|
||||
|
||||
void print();
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
package com.lanyuanxiaoyao.service.ai.web.engine.store;
|
||||
|
||||
import cn.hutool.core.util.ArrayUtil;
|
||||
import com.lanyuanxiaoyao.service.ai.web.engine.entity.FlowEdge;
|
||||
import com.lanyuanxiaoyao.service.ai.web.engine.entity.FlowGraph;
|
||||
import com.lanyuanxiaoyao.service.ai.web.engine.entity.FlowNode;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.eclipse.collections.api.factory.Maps;
|
||||
import org.eclipse.collections.api.map.MutableMap;
|
||||
|
||||
/**
|
||||
* 基于内存的流程状态存储
|
||||
*
|
||||
* @author lanyuanxiaoyao
|
||||
* @version 20250701
|
||||
*/
|
||||
@Slf4j
|
||||
public class InMemoryFlowStore implements FlowStore {
|
||||
private static final MutableMap<String, FlowNode.State> flowNodeStateMap = Maps.mutable.<String, FlowNode.State>empty().asSynchronized();
|
||||
private static final MutableMap<String, FlowEdge.State> flowEdgeStateMap = Maps.mutable.<String, FlowEdge.State>empty().asSynchronized();
|
||||
|
||||
private String multiKey(String... key) {
|
||||
return String.join("-", key);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void init(FlowGraph flowGraph) {
|
||||
for (FlowNode node : flowGraph.nodes()) {
|
||||
flowNodeStateMap.put(multiKey(flowGraph.id(), node.id()), new FlowNode.State(node.id()));
|
||||
}
|
||||
for (FlowEdge edge : flowGraph.edges()) {
|
||||
flowEdgeStateMap.put(multiKey(flowGraph.id(), edge.id()), new FlowEdge.State(edge.id()));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void updateNodeToRunning(String graphId, String nodeId) {
|
||||
flowNodeStateMap.updateValue(
|
||||
multiKey(graphId, nodeId),
|
||||
() -> new FlowNode.State(nodeId, FlowNode.Status.RUNNING),
|
||||
old -> new FlowNode.State(nodeId, FlowNode.Status.RUNNING, old.startingTime(), old.finishedTime())
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void updateNodeToSkipped(String graphId, String nodeId) {
|
||||
flowNodeStateMap.updateValue(
|
||||
multiKey(graphId, nodeId),
|
||||
() -> new FlowNode.State(nodeId, FlowNode.Status.SKIPPED),
|
||||
old -> new FlowNode.State(nodeId, FlowNode.Status.SKIPPED, old.startingTime(), old.finishedTime())
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void updateNodeToFinished(String graphId, String nodeId) {
|
||||
flowNodeStateMap.updateValue(
|
||||
multiKey(graphId, nodeId),
|
||||
() -> new FlowNode.State(nodeId, FlowNode.Status.FINISHED),
|
||||
old -> new FlowNode.State(nodeId, FlowNode.Status.FINISHED, old.startingTime(), old.finishedTime())
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void updateEdgeToExecute(String graphId, String edgeId) {
|
||||
flowEdgeStateMap.updateValue(
|
||||
multiKey(graphId, edgeId),
|
||||
() -> new FlowEdge.State(edgeId, FlowEdge.Status.EXECUTE),
|
||||
old -> new FlowEdge.State(edgeId, FlowEdge.Status.EXECUTE, old.startingTime(), old.finishedTime())
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void updateEdgeToSkip(String graphId, String edgeId) {
|
||||
flowEdgeStateMap.updateValue(
|
||||
multiKey(graphId, edgeId),
|
||||
() -> new FlowEdge.State(edgeId, FlowEdge.Status.SKIP),
|
||||
old -> new FlowEdge.State(edgeId, FlowEdge.Status.SKIP, old.startingTime(), old.finishedTime())
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean checkNodeStatus(String graphId, String nodeId, FlowNode.Status... statuses) {
|
||||
String key = multiKey(graphId, nodeId);
|
||||
if (flowNodeStateMap.containsKey(key)) {
|
||||
return ArrayUtil.contains(statuses, flowNodeStateMap.get(key).status());
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean checkEdgeStatus(String graphId, String edgeId, FlowEdge.Status... statuses) {
|
||||
String key = multiKey(graphId, edgeId);
|
||||
if (flowEdgeStateMap.containsKey(key)) {
|
||||
return ArrayUtil.contains(statuses, flowEdgeStateMap.get(key).status());
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void print() {
|
||||
log.info("====== Flow Store ======");
|
||||
log.info("====== Flow Node ======");
|
||||
flowNodeStateMap.forEachKeyValue((key, value) -> log.info("{}: {}", key, value.status()));
|
||||
log.info("====== Flow Edge ======");
|
||||
flowEdgeStateMap.forEachKeyValue((key, value) -> log.info("{}: {}", key, value.status()));
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
import lombok.ToString;
|
||||
import org.hibernate.annotations.Comment;
|
||||
import org.hibernate.annotations.DynamicUpdate;
|
||||
|
||||
/**
|
||||
@@ -23,11 +24,17 @@ import org.hibernate.annotations.DynamicUpdate;
|
||||
@DynamicUpdate
|
||||
@Table(catalog = Constants.DATABASE_NAME, name = "service_ai_file")
|
||||
@NoArgsConstructor
|
||||
@Comment("记录上传的文件存储信息")
|
||||
public class DataFile extends SimpleEntity {
|
||||
@Comment("文件名称")
|
||||
private String filename;
|
||||
@Comment("文件大小,单位是byte")
|
||||
private Long size;
|
||||
@Comment("文件的md5编码,用于校验文件的完整性")
|
||||
private String md5;
|
||||
@Comment("文件在主机上存储的实际路径")
|
||||
private String path;
|
||||
@Comment("文件类型,通常记录的是文件的后缀名")
|
||||
private String type;
|
||||
|
||||
public DataFile(String filename) {
|
||||
|
||||
@@ -6,6 +6,8 @@ import jakarta.persistence.Column;
|
||||
import jakarta.persistence.ConstraintMode;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.EntityListeners;
|
||||
import jakarta.persistence.EnumType;
|
||||
import jakarta.persistence.Enumerated;
|
||||
import jakarta.persistence.FetchType;
|
||||
import jakarta.persistence.ForeignKey;
|
||||
import jakarta.persistence.JoinTable;
|
||||
@@ -17,6 +19,7 @@ import java.util.Set;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import lombok.ToString;
|
||||
import org.hibernate.annotations.Comment;
|
||||
import org.hibernate.annotations.DynamicUpdate;
|
||||
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
|
||||
|
||||
@@ -30,18 +33,25 @@ import org.springframework.data.jpa.domain.support.AuditingEntityListener;
|
||||
@NamedEntityGraph(name = "feedback.detail", attributeNodes = {
|
||||
@NamedAttributeNode("pictures")
|
||||
})
|
||||
@Comment("报障信息记录")
|
||||
public class Feedback extends SimpleEntity {
|
||||
@Comment("原始报障说明")
|
||||
@Column(nullable = false, columnDefinition = "longtext")
|
||||
private String source;
|
||||
@Comment("报障相关截图")
|
||||
@OneToMany(fetch = FetchType.EAGER)
|
||||
@JoinTable(catalog = Constants.DATABASE_NAME, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT), inverseForeignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
|
||||
@ToString.Exclude
|
||||
private Set<DataFile> pictures;
|
||||
@Comment("AI的分析结果")
|
||||
@Column(columnDefinition = "longtext")
|
||||
private String analysis;
|
||||
@Comment("AI的解决方案")
|
||||
@Column(columnDefinition = "longtext")
|
||||
private String conclusion;
|
||||
@Comment("报障处理状态")
|
||||
@Column(nullable = false)
|
||||
@Enumerated(EnumType.STRING)
|
||||
private Status status = Status.ANALYSIS_PROCESSING;
|
||||
|
||||
public enum Status {
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
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.EnumType;
|
||||
import jakarta.persistence.Enumerated;
|
||||
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.Comment;
|
||||
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")
|
||||
@Comment("流程任务记录")
|
||||
public class FlowTask extends SimpleEntity {
|
||||
@Comment("流程任务对应的模板")
|
||||
@ManyToOne
|
||||
@JoinColumn(nullable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
|
||||
private FlowTaskTemplate template;
|
||||
@Comment("任务输入")
|
||||
@Column(columnDefinition = "longtext")
|
||||
private String input;
|
||||
@Comment("任务运行状态")
|
||||
@Column(nullable = false)
|
||||
@Enumerated(EnumType.STRING)
|
||||
private Status status = Status.RUNNING;
|
||||
@Comment("任务运行产生的报错")
|
||||
@Column(columnDefinition = "longtext")
|
||||
private String error;
|
||||
@Comment("任务运行结果")
|
||||
@Column(columnDefinition = "longtext")
|
||||
private String result;
|
||||
|
||||
public enum Status {
|
||||
RUNNING,
|
||||
ERROR,
|
||||
FINISHED,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
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.Comment;
|
||||
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")
|
||||
@Comment("流程任务模板")
|
||||
public class FlowTaskTemplate extends SimpleEntity {
|
||||
@Comment("模板名称")
|
||||
@Column(nullable = false)
|
||||
private String name;
|
||||
@Comment("模板功能、内容说明")
|
||||
private String description;
|
||||
@Comment("模板入参Schema")
|
||||
@Column(nullable = false, columnDefinition = "longtext")
|
||||
private String inputSchema;
|
||||
@Comment("前端流程图数据")
|
||||
@Column(columnDefinition = "longtext")
|
||||
private String flowGraph;
|
||||
}
|
||||
@@ -6,6 +6,8 @@ import jakarta.persistence.Column;
|
||||
import jakarta.persistence.ConstraintMode;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.EntityListeners;
|
||||
import jakarta.persistence.EnumType;
|
||||
import jakarta.persistence.Enumerated;
|
||||
import jakarta.persistence.FetchType;
|
||||
import jakarta.persistence.ForeignKey;
|
||||
import jakarta.persistence.JoinColumn;
|
||||
@@ -14,6 +16,7 @@ import jakarta.persistence.Table;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import lombok.ToString;
|
||||
import org.hibernate.annotations.Comment;
|
||||
import org.hibernate.annotations.DynamicUpdate;
|
||||
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
|
||||
|
||||
@@ -28,10 +31,14 @@ import org.springframework.data.jpa.domain.support.AuditingEntityListener;
|
||||
@DynamicUpdate
|
||||
@EntityListeners(AuditingEntityListener.class)
|
||||
@Table(catalog = Constants.DATABASE_NAME, name = "service_ai_group")
|
||||
@Comment("知识库内的逻辑分组,比如一个文件是一个分组或一次上传的所有文本是一个分组,可以自由使用而不是限于文件范畴")
|
||||
public class Group extends SimpleEntity {
|
||||
@Comment("分组名称")
|
||||
@Column(nullable = false)
|
||||
private String name;
|
||||
@Comment("分组处理状态")
|
||||
@Column(nullable = false)
|
||||
@Enumerated(EnumType.STRING)
|
||||
private Status status = Status.RUNNING;
|
||||
|
||||
@ManyToOne(fetch = FetchType.LAZY)
|
||||
|
||||
@@ -6,6 +6,8 @@ import jakarta.persistence.CascadeType;
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.EntityListeners;
|
||||
import jakarta.persistence.EnumType;
|
||||
import jakarta.persistence.Enumerated;
|
||||
import jakarta.persistence.FetchType;
|
||||
import jakarta.persistence.OneToMany;
|
||||
import jakarta.persistence.Table;
|
||||
@@ -13,6 +15,7 @@ import java.util.Set;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import lombok.ToString;
|
||||
import org.hibernate.annotations.Comment;
|
||||
import org.hibernate.annotations.DynamicUpdate;
|
||||
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
|
||||
|
||||
@@ -27,16 +30,23 @@ import org.springframework.data.jpa.domain.support.AuditingEntityListener;
|
||||
@DynamicUpdate
|
||||
@EntityListeners(AuditingEntityListener.class)
|
||||
@Table(catalog = Constants.DATABASE_NAME, name = "service_ai_knowledge")
|
||||
@Comment("知识库")
|
||||
public class Knowledge extends SimpleEntity {
|
||||
@Comment("知识库对应的向量库名")
|
||||
@Column(nullable = false)
|
||||
private Long vectorSourceId;
|
||||
@Comment("知识库名称")
|
||||
@Column(nullable = false)
|
||||
private String name;
|
||||
@Comment("知识库说明")
|
||||
@Column(nullable = false, columnDefinition = "longtext")
|
||||
private String description;
|
||||
@Comment("知识库策略")
|
||||
@Column(nullable = false)
|
||||
@Enumerated(EnumType.STRING)
|
||||
private Strategy strategy = Strategy.Cosine;
|
||||
|
||||
@Comment("知识库下包含的分组")
|
||||
@OneToMany(fetch = FetchType.LAZY, mappedBy = "knowledge", cascade = CascadeType.ALL)
|
||||
@ToString.Exclude
|
||||
private Set<Group> groups;
|
||||
|
||||
@@ -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> {
|
||||
}
|
||||
@@ -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> {
|
||||
}
|
||||
@@ -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")
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
package com.lanyuanxiaoyao.service.ai.web.tools;
|
||||
|
||||
import com.lanyuanxiaoyao.service.ai.web.WebApplication;
|
||||
import com.lanyuanxiaoyao.service.ai.web.configuration.SpringBeanGetter;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.ai.chat.client.ChatClient;
|
||||
import org.springframework.ai.tool.annotation.Tool;
|
||||
@@ -44,7 +44,7 @@ public class ChartTool {
|
||||
""") String request
|
||||
) {
|
||||
log.info("Enter method: mermaid[request]. request:{}", request);
|
||||
ChatClient.Builder builder = WebApplication.getBean("chat", ChatClient.Builder.class);
|
||||
ChatClient.Builder builder = SpringBeanGetter.getBean("chat", ChatClient.Builder.class);
|
||||
ChatClient client = builder.build();
|
||||
return client.prompt()
|
||||
// language=TEXT
|
||||
|
||||
@@ -2,7 +2,7 @@ package com.lanyuanxiaoyao.service.ai.web.tools;
|
||||
|
||||
import cn.hutool.core.util.ObjectUtil;
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import com.lanyuanxiaoyao.service.ai.web.WebApplication;
|
||||
import com.lanyuanxiaoyao.service.ai.web.configuration.SpringBeanGetter;
|
||||
import com.lanyuanxiaoyao.service.forest.service.KnowledgeService;
|
||||
import org.springframework.ai.tool.annotation.Tool;
|
||||
import org.springframework.ai.tool.annotation.ToolParam;
|
||||
@@ -27,7 +27,7 @@ public class KnowledgeTool {
|
||||
""")
|
||||
String query
|
||||
) {
|
||||
KnowledgeService knowledgeService = WebApplication.getBean(KnowledgeService.class);
|
||||
KnowledgeService knowledgeService = SpringBeanGetter.getBean(KnowledgeService.class);
|
||||
var documents = knowledgeService.query(knowledgeId, query, 10, 0.5);
|
||||
if (ObjectUtil.isNotEmpty(documents)) {
|
||||
return StrUtil.format("""
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
package com.lanyuanxiaoyao.service.ai.web.tools;
|
||||
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import com.lanyuanxiaoyao.service.ai.web.WebApplication;
|
||||
import com.lanyuanxiaoyao.service.ai.web.configuration.SpringBeanGetter;
|
||||
import com.lanyuanxiaoyao.service.forest.service.InfoService;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
@@ -27,7 +27,7 @@ public class TableTool {
|
||||
""") String sql
|
||||
) {
|
||||
log.info("Enter method: executeJdbc[sql]. sql:{}", sql);
|
||||
InfoService infoService = WebApplication.getBean(InfoService.class);
|
||||
InfoService infoService = SpringBeanGetter.getBean(InfoService.class);
|
||||
String result = infoService.jdbc(sql)
|
||||
.collect(map -> map.valuesView().makeString(","))
|
||||
.makeString("\n");
|
||||
@@ -48,7 +48,7 @@ public class TableTool {
|
||||
""") String type
|
||||
) {
|
||||
log.info("Enter method: tableCount[type]. type:{}", type);
|
||||
var infoService = WebApplication.getBean(InfoService.class);
|
||||
var infoService = SpringBeanGetter.getBean(InfoService.class);
|
||||
return switch (type) {
|
||||
case "logic" -> StrUtil.format("""
|
||||
逻辑表共{}张,其中重点表{}张
|
||||
@@ -83,7 +83,7 @@ public class TableTool {
|
||||
String type
|
||||
) {
|
||||
log.info("Enter method: version[date, type]. date:{},type:{}", date, type);
|
||||
InfoService infoService = WebApplication.getBean(InfoService.class);
|
||||
InfoService infoService = SpringBeanGetter.getBean(InfoService.class);
|
||||
String version = date;
|
||||
if (StrUtil.isBlank(version)) {
|
||||
version = LocalDateTime.now().minusDays(1).format(FORMATTER);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
package com.lanyuanxiaoyao.service.ai.web.tools;
|
||||
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import com.lanyuanxiaoyao.service.ai.web.WebApplication;
|
||||
import com.lanyuanxiaoyao.service.ai.web.configuration.SpringBeanGetter;
|
||||
import com.lanyuanxiaoyao.service.configuration.entity.yarn.YarnApplication;
|
||||
import com.lanyuanxiaoyao.service.configuration.entity.yarn.YarnQueue;
|
||||
import com.lanyuanxiaoyao.service.configuration.entity.yarn.YarnRootQueue;
|
||||
@@ -27,7 +27,7 @@ public class YarnTool {
|
||||
""") String cluster
|
||||
) {
|
||||
log.info("Enter method: yarnStatus[cluster]. cluster:{}", cluster);
|
||||
YarnService yarnService = WebApplication.getBean(YarnService.class);
|
||||
YarnService yarnService = SpringBeanGetter.getBean(YarnService.class);
|
||||
YarnRootQueue status = yarnService.cluster(cluster);
|
||||
return (status.getUsedCapacity() * 100.0) / status.getCapacity();
|
||||
}
|
||||
@@ -45,7 +45,7 @@ public class YarnTool {
|
||||
""") String queue
|
||||
) {
|
||||
log.info("Enter method: yarnQueueStatus[cluster, queue]. cluster:{},queue:{}", cluster, queue);
|
||||
YarnService yarnService = WebApplication.getBean(YarnService.class);
|
||||
YarnService yarnService = SpringBeanGetter.getBean(YarnService.class);
|
||||
YarnQueue status = yarnService.queueDetail(cluster, queue);
|
||||
return (status.getAbsoluteCapacity() * 100.0) / status.getAbsoluteMaxCapacity();
|
||||
}
|
||||
@@ -66,7 +66,7 @@ public class YarnTool {
|
||||
""") String type
|
||||
) {
|
||||
log.info("Enter method: yarnTaskStatus[cluster, type]. cluster:{},type:{}", cluster, type);
|
||||
YarnService yarnService = WebApplication.getBean(YarnService.class);
|
||||
YarnService yarnService = SpringBeanGetter.getBean(YarnService.class);
|
||||
ImmutableList<YarnApplication> applications = yarnService.jobList(cluster).select(app -> StrUtil.isNotBlank(type) && StrUtil.contains(app.getName(), type));
|
||||
return StrUtil.format(
|
||||
"""
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
package com.lanyuanxiaoyao.service.ai.web;
|
||||
|
||||
import cn.hutool.core.io.FileUtil;
|
||||
import cn.hutool.core.util.ClassUtil;
|
||||
import jakarta.persistence.Entity;
|
||||
import java.util.EnumSet;
|
||||
import org.hibernate.boot.MetadataSources;
|
||||
import org.hibernate.boot.model.naming.CamelCaseToUnderscoresNamingStrategy;
|
||||
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
|
||||
import org.hibernate.dialect.MySQLDialect;
|
||||
import org.hibernate.tool.hbm2ddl.SchemaExport;
|
||||
import org.hibernate.tool.schema.TargetType;
|
||||
import org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy;
|
||||
|
||||
/**
|
||||
* JPA直接生成建表语句
|
||||
*
|
||||
* @author lanyuanxiaoyao
|
||||
* @version 20250702
|
||||
*/
|
||||
public class GenerateDDL {
|
||||
public static void main(String[] args) {
|
||||
String root = "/Users/lanyuanxiaoyao/Project/IdeaProjects/hudi-service/service-ai/target/sql";
|
||||
FileUtil.mkdir(root);
|
||||
/* ClassUtil.scanPackageBySuper("org.hibernate.dialect", Dialect.class)
|
||||
.stream()
|
||||
.filter(clazz -> StrUtil.startWith(clazz.getSimpleName(), "MySQL"))
|
||||
.filter(clazz -> !StrUtil.startWith(clazz.getSimpleName(), "Abstract"))
|
||||
.filter(clazz -> !StrUtil.startWith(clazz.getSimpleName(), "Dialect"))
|
||||
.forEach(dialectClazz -> generateDDL(root, dialectClazz)); */
|
||||
generateDDL(root, MySQLDialect.class);
|
||||
}
|
||||
|
||||
private static void generateDDL(String path, Class<?> dialect) {
|
||||
var metadataSources = new MetadataSources(
|
||||
new StandardServiceRegistryBuilder()
|
||||
.applySetting("hibernate.dialect", dialect.getName())
|
||||
.applySetting("hibernate.physical_naming_strategy", CamelCaseToUnderscoresNamingStrategy.class.getName())
|
||||
.applySetting("hibernate.implicit_naming_strategy", SpringImplicitNamingStrategy.class.getName())
|
||||
.build()
|
||||
);
|
||||
var classes = ClassUtil.scanPackageByAnnotation("com.lanyuanxiaoyao.service.ai.web.entity", Entity.class);
|
||||
classes.forEach(metadataSources::addAnnotatedClass);
|
||||
var export = new SchemaExport();
|
||||
export.setFormat(true);
|
||||
export.setDelimiter(";");
|
||||
export.setOutputFile(path + "/" + dialect.getSimpleName() + ".sql");
|
||||
export.setOverrideOutputFileContent();
|
||||
export.execute(EnumSet.of(TargetType.SCRIPT), SchemaExport.Action.CREATE, metadataSources.buildMetadata());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package com.lanyuanxiaoyao.service.ai.web;
|
||||
|
||||
import com.lanyuanxiaoyao.service.ai.web.engine.FlowExecutor;
|
||||
import com.lanyuanxiaoyao.service.ai.web.engine.FlowNodeOptionalRunner;
|
||||
import com.lanyuanxiaoyao.service.ai.web.engine.FlowNodeRunner;
|
||||
import com.lanyuanxiaoyao.service.ai.web.engine.entity.FlowEdge;
|
||||
import com.lanyuanxiaoyao.service.ai.web.engine.entity.FlowGraph;
|
||||
import com.lanyuanxiaoyao.service.ai.web.engine.entity.FlowNode;
|
||||
import com.lanyuanxiaoyao.service.ai.web.engine.store.InMemoryFlowStore;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.eclipse.collections.api.factory.Maps;
|
||||
import org.eclipse.collections.api.factory.Sets;
|
||||
|
||||
/**
|
||||
* @author lanyuanxiaoyao
|
||||
* @version 20250701
|
||||
*/
|
||||
@Slf4j
|
||||
public class TestFlow {
|
||||
public static void main(String[] args) throws InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException {
|
||||
var store = new InMemoryFlowStore();
|
||||
var executor = new FlowExecutor(
|
||||
store,
|
||||
Maps.immutable.of(
|
||||
"plain-node", PlainNode.class,
|
||||
"option-node", PlainOptionNode.class
|
||||
)
|
||||
);
|
||||
/*
|
||||
* 4 6 7
|
||||
* 1 2 5 8---3
|
||||
* \9/
|
||||
*/
|
||||
var graph = new FlowGraph(
|
||||
"graph-1",
|
||||
Sets.immutable.of(
|
||||
new FlowNode("node-1", "plain-node"),
|
||||
new FlowNode("node-2", "plain-node"),
|
||||
new FlowNode("node-4", "plain-node"),
|
||||
new FlowNode("node-6", "plain-node"),
|
||||
new FlowNode("node-7", "plain-node"),
|
||||
new FlowNode("node-5", "plain-node"),
|
||||
new FlowNode("node-8", "option-node"),
|
||||
new FlowNode("node-9", "plain-node"),
|
||||
new FlowNode("node-3", "plain-node")
|
||||
),
|
||||
Sets.immutable.of(
|
||||
new FlowEdge("edge-1", "node-1", "node-2", null, null),
|
||||
new FlowEdge("edge-2", "node-2", "node-4", null, null),
|
||||
new FlowEdge("edge-3", "node-2", "node-5", null, null),
|
||||
new FlowEdge("edge-4", "node-5", "node-8", null, null),
|
||||
new FlowEdge("edge-5", "node-8", "node-9", "yes", null),
|
||||
new FlowEdge("edge-6", "node-8", "node-3", "no", null),
|
||||
new FlowEdge("edge-7", "node-9", "node-3", null, null),
|
||||
new FlowEdge("edge-8", "node-4", "node-6", null, null),
|
||||
new FlowEdge("edge-9", "node-6", "node-7", null, null),
|
||||
new FlowEdge("edge-10", "node-7", "node-3", null, null)
|
||||
)
|
||||
);
|
||||
executor.execute(graph);
|
||||
store.print();
|
||||
}
|
||||
|
||||
public static class PlainNode extends FlowNodeRunner {
|
||||
@Override
|
||||
public void run() {
|
||||
log.info("run node id: {}", getNodeId());
|
||||
}
|
||||
}
|
||||
|
||||
public static class PlainOptionNode extends FlowNodeOptionalRunner {
|
||||
@Override
|
||||
public String runOptional() {
|
||||
log.info("run node id: {}", getNodeId());
|
||||
// yes / no
|
||||
return "no";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,11 +2,15 @@ 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.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
|
||||
import org.springframework.web.cors.CorsConfiguration;
|
||||
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
|
||||
import org.springframework.web.filter.CorsFilter;
|
||||
|
||||
/**
|
||||
* Spring Security Config
|
||||
@@ -25,6 +29,19 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
|
||||
this.securityProperties = securityProperties;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public CorsFilter corsFilter() {
|
||||
CorsConfiguration configuration = new CorsConfiguration();
|
||||
configuration.setAllowCredentials(true);
|
||||
configuration.addAllowedOriginPattern("*");
|
||||
configuration.addAllowedHeader("*");
|
||||
configuration.addAllowedMethod("*");
|
||||
configuration.setMaxAge(7200L);
|
||||
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
|
||||
source.registerCorsConfiguration("/**", configuration);
|
||||
return new CorsFilter(source);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
http.authorizeHttpRequests()
|
||||
@@ -36,7 +53,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
|
||||
.csrf()
|
||||
.disable()
|
||||
.cors()
|
||||
.disable()
|
||||
.and()
|
||||
.formLogin()
|
||||
.disable();
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@ import org.springframework.security.core.userdetails.User;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.security.web.server.SecurityWebFilterChain;
|
||||
import org.springframework.web.cors.CorsConfiguration;
|
||||
import org.springframework.web.cors.reactive.CorsConfigurationSource;
|
||||
import org.springframework.web.cors.reactive.CorsWebFilter;
|
||||
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
|
||||
|
||||
/**
|
||||
@@ -33,24 +33,12 @@ public class SecurityConfiguration {
|
||||
.httpBasic()
|
||||
.disable()
|
||||
.cors()
|
||||
.configurationSource(corsConfigurationSource())
|
||||
.and()
|
||||
.disable()
|
||||
.csrf()
|
||||
.disable()
|
||||
.build();
|
||||
}
|
||||
|
||||
private CorsConfigurationSource corsConfigurationSource() {
|
||||
CorsConfiguration configuration = new CorsConfiguration();
|
||||
configuration.setAllowCredentials(true);
|
||||
configuration.addAllowedHeader("*");
|
||||
configuration.addAllowedMethod("*");
|
||||
configuration.addAllowedOriginPattern("*");
|
||||
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
|
||||
source.registerCorsConfiguration("/**", configuration);
|
||||
return source;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public MapReactiveUserDetailsService userDetailsService(SecurityProperties securityProperties) {
|
||||
UserDetails user = User.builder()
|
||||
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
|
||||
827
service-web/client/pnpm-lock.yaml
generated
827
service-web/client/pnpm-lock.yaml
generated
File diff suppressed because it is too large
Load Diff
@@ -1,41 +1,128 @@
|
||||
import {ProLayout} from '@ant-design/pro-components'
|
||||
import React from 'react'
|
||||
import {type AppItemProps, ProLayout} from '@ant-design/pro-components'
|
||||
import {ConfigProvider} from 'antd'
|
||||
import {dateFormat} from 'licia'
|
||||
import React, {useMemo} from 'react'
|
||||
import {Outlet, useLocation, useNavigate} from 'react-router'
|
||||
import styled from 'styled-components'
|
||||
import {menus} from '../route.tsx'
|
||||
|
||||
const ProLayoutDiv = styled.div`
|
||||
position: relative;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
|
||||
.ant-menu-sub > .ant-menu-item {
|
||||
padding-left: 16px !important;
|
||||
}
|
||||
`
|
||||
|
||||
const defaultAppIcon =
|
||||
<img
|
||||
src={'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACgAAAAoCAMAAAC7IEhfAAAABGdBTUEAALGPC/xhBQAAAAFzUkdCAK7OHOkAAAMAUExURUdwTBR20EyHx1iq5EWJ1hNyy0mR1EhzwnbB/8P5/Fx/vVuj5zyO4lCY102P0L3u/3K88dz4/8v1/0fW/jLh/013ujN4wBliuEuEy0FrqT13wFmCvkaH0GSLyBVVqe38/0il4FKu7crr/eL3/7Ls/zd3t1WN1TZcnTloojx6whpYpTdfoDVwtVeS1WeOyiNhsTFyuy50wHCPxDFgqLjK5G2Ow2Gy5ylpvB9uxA5x03W/71Wh4E2U2tr2/i6C3G7J+Gex7KTI8eb9/cbz/yC+/srl++P7/Znf+MPv/cn3/rz6/dL8/2fe/8v+/s/6/knN87f5/jx5uRZtwjRppU6I1liM2Bhcrmyl2kZ5uA9vzjd0wj95yjVstqze9hiD2zOH1kqv7Wqv5K7S7LLn/YfT+sfp/bPf+4jb/YbX+735/SjQ/T7J+VjV9rTs+0ns/6Dk/mPJ7eD9/b/8/Q9YxA5Zxw5Zwg5dwg5byhdn0kSO2xFezg5gwg1XwRBjwkqW4EeT3kuY20mV2BBVtg5avxFoxQ9Yu0+g3xJYslWi5h2q9SKA4AtTwAxjzUGN2UiN0VOm4yKj8NX7/0WQ3RFtyUaR1h95zSOc706J0Bt34VCi5yqw9F6s6SOI5Bx02h2M6Rh13SCX7k2c3E6a4lCd5EeQ2iVtyCJ54BVt3ROV8x+0+jS9+hGq+Ra0/WK37sPy/iOR6R1w2A5p0y9nrjJ/1EaO1yV1yDt+zBaJ4hF83FuJyg5nyhei9hJ96BN35ByV5ymq8S151muu5UCr6hzE/xS+/47h/3/r/xyG5SKV6yJ43BlswBJivA5z2A9duw5s1C590CZXpDVvuhec9BGM7xJQrxKE61yo4DOF4DeZ64jG8bbp/h/Q/j2F0xpr1xliyROA4CRst1mc10d8whNQqDqb3Sig5qrh/qLW9iZ/5UeY5pDU9UWf6J7O9oju/mDV/aXp/orj/6P7/4z3/2Pr/iLa/kaDxnuw57rf9ZfW+2Sd5G3X/7LW9zyR51TI+Dao7Zno//A+0MwAAADpdFJOUwD7Lv/+/v4CAQIK/v7+/P7+b/7+/iKh/f5LjBv8z/4d/v5cNf6A5piF/Pts9PST/tP+Qd0Oc/72Pf5B/Pv0/vv7zqD6/4qU+5JjlCv7ff79/lz628SK/pmm+/5cnh/+/vPht/r+pPKX44z7+/z7/P7+wNL////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////+///////////////////////+1awirQAAA+BJREFUOMtjYCAXcMIAAVW4OKjKgJjDW8nXyytT0NOKCyjAgUudt29RwMdPb48dO/b2aEa6MkQvpjrlQqCqz3ki/j4+2VnCv44+S5XHVAm0xHPixHXuOSIiX4TfHeo87OJin/IjTYmBgwNdndvEibkF/sIiX26/+7f6yJo1K/fPtL/53BXDPKeJQkLvPx87Knz79qzOI2tWr959acFaAYE3rii2cwDVOQutU8k/+uHv4cNrQMpWrFgxTXHtWoc3gkgqORkEJzqvW3fr/f8Paye4rFzZufvSisuXr95QVJw9W+C3MlwlB4O87Tp+fn6VV2sVgOo6wequ7tkz4zWP3QHrm45IBroJJd/if37w0CygaZ0Tpi1YMO/qnr17b7yeMePFAZufSlAjQQbeyle5qbBq1apZIGUn1s87DlS3/DrPsj8vr/McdES48Lv7q4NPVq3avx+sbP2cOV0zZsxfftfuZcdsbm6Bb1YM7BATk64pPHk6C6hqGljVnK6uZSfnzl2+bObMmR3csx0OhkIUMpgkHgKatW/fvO3HjwMVdXWdPHly7oYNd3mA6jo6uLm5Q0ABDcSxCU/37du+/f79HfPnz507dwNQ0Ya7dyuudyzu6Fi8eNGiOjUukEp2BqZDcXE7dpw5c+bcuY0bK+CgbtEioLK6+kmVLKIQhRZP4iwtgWp6gKCqpwoCyivqQACorLeXhQnkSKDC83a7dgEVlfeUw0BJScm9SfVAAFTHwjIdqpBpafyuspISIEICxSWV9ZMmLQGr0wVbzcEgbb518+YDFcWlxUAAUgMGNXfqKisrl1QCFaqZgL3NwGkgzsbb2LC5u7sYAUprWu/UL2HZto1FZrosJGbYGWIMbdjYpjRuvtddU1MDVAMB3U3bljZdubJNZqceJMDZGSQv8vX1TZnS2HCguwaqqrS5ubm1CQiuRE3faQSNGQYu469glVMalnZ315SBAUghUGX7Y/3psrD0yM6gvQmoEGh5Y0Pv+Xs1pdUQlUCF7e2PzXeawgwEGQm0nI2tsaFhYdvC3qVl1WClZ1vb2+XkHskisgLQlRc0IeoWtrUxn2+urT5dXVt99ixQ4UWEC8EqNS5o8jaClLX191bXQsDps+1hWo+QLAYnIfULMrxAdf39s6dWt4BB7enT4lqb9Bg40DK2+iZea2tmZub+qbsmA0HLqZZT4vqbpBgYMIoKbZ2H166Z1U9mhYKgUw+CJdHVgd0pGvHwmllvJCMYsJ56oKPBheI+hEoGpnDdrVungsBWQwNVaQas6oCWAIWlo6WkxMTEVAOZQFo5cJW57Mgm4FYGMRUGyK0tAGzv0vrmaa6xAAAAAElFTkSuQmCC'}
|
||||
/>
|
||||
const apps: AppItemProps[] = [
|
||||
{
|
||||
icon: 'http://132.121.223.12:7001/static/webssh/favicon2.ico',
|
||||
title: '运营数据汇聚平台',
|
||||
desc: '企业全融合数字化平台',
|
||||
url: 'http://132.121.223.12:7001/index.html/#/login',
|
||||
},
|
||||
{
|
||||
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/',
|
||||
},
|
||||
{
|
||||
icon: defaultAppIcon,
|
||||
title: '汇聚平台辅助工具',
|
||||
desc: '辅助工具,用于帮助运营工作,不断改进中',
|
||||
url: 'http://132.121.204.100:38080/tools/#/',
|
||||
},
|
||||
{
|
||||
icon: defaultAppIcon,
|
||||
title: 'B12-Yarn',
|
||||
desc: 'B12集群Yarn页面',
|
||||
url: 'http://132.126.207.125:8088/cluster/scheduler',
|
||||
},
|
||||
]
|
||||
|
||||
const App: React.FC = () => {
|
||||
const navigate = useNavigate()
|
||||
const location = useLocation()
|
||||
const currentYear = useMemo(() => dateFormat(new Date(), 'yyyy'), [])
|
||||
return (
|
||||
<ProLayout
|
||||
token={{
|
||||
header: {
|
||||
colorBgHeader: '#292f33',
|
||||
colorHeaderTitle: '#ffffff',
|
||||
colorTextMenu: '#dfdfdf',
|
||||
colorTextMenuSecondary: '#dfdfdf',
|
||||
colorTextMenuSelected: '#ffffff',
|
||||
colorTextMenuActive: '#ffffff',
|
||||
colorBgMenuItemSelected: '#22272b',
|
||||
colorTextRightActionsItem: '#dfdfdf',
|
||||
},
|
||||
}}
|
||||
logo={<img src="icon.png" alt="logo"/>}
|
||||
title="Hudi 服务总台"
|
||||
route={menus}
|
||||
location={{pathname: location.pathname}}
|
||||
menu={{type: 'sub'}}
|
||||
menuItemRender={(item, dom) => {
|
||||
return <div onClick={() => navigate(item.path || '/')}>{dom}</div>
|
||||
}}
|
||||
fixSiderbar={true}
|
||||
layout="mix"
|
||||
splitMenus={true}
|
||||
style={{minHeight: '100vh'}}
|
||||
contentStyle={{backgroundColor: 'white', padding: '10px 10px 10px 20px'}}
|
||||
>
|
||||
<Outlet/>
|
||||
</ProLayout>
|
||||
<ProLayoutDiv>
|
||||
<ProLayout
|
||||
siderWidth={180}
|
||||
token={{
|
||||
colorTextAppListIcon: '#dfdfdf',
|
||||
colorTextAppListIconHover: '#ffffff',
|
||||
header: {
|
||||
colorBgHeader: '#292f33',
|
||||
colorHeaderTitle: '#ffffff',
|
||||
colorTextMenu: '#dfdfdf',
|
||||
colorTextMenuSecondary: '#dfdfdf',
|
||||
colorTextMenuSelected: '#ffffff',
|
||||
colorTextMenuActive: '#ffffff',
|
||||
colorBgMenuItemSelected: '#22272b',
|
||||
colorTextRightActionsItem: '#dfdfdf',
|
||||
},
|
||||
pageContainer: {
|
||||
paddingBlockPageContainerContent: 0,
|
||||
paddingInlinePageContainerContent: 0,
|
||||
marginBlockPageContainerContent: 0,
|
||||
marginInlinePageContainerContent: 0,
|
||||
},
|
||||
}}
|
||||
appList={apps}
|
||||
defaultCollapsed={false}
|
||||
breakpoint={false}
|
||||
disableMobile={true}
|
||||
logo={<img src="icon.png" alt="logo"/>}
|
||||
title="Hudi 服务总台"
|
||||
route={menus}
|
||||
location={{pathname: location.pathname}}
|
||||
menu={{type: 'sub'}}
|
||||
menuItemRender={(item) => {
|
||||
return (
|
||||
<div onClick={() => navigate(item.path || '/')}>
|
||||
{item.icon}
|
||||
<span className="ml-2">{item.name}</span>
|
||||
</div>
|
||||
)
|
||||
}}
|
||||
fixSiderbar={true}
|
||||
layout="mix"
|
||||
splitMenus={true}
|
||||
style={{minHeight: '100vh'}}
|
||||
contentStyle={{backgroundColor: 'white', padding: '10px 10px 10px 20px'}}
|
||||
menuFooterRender={props => {
|
||||
return (
|
||||
<div className="text-sm text-center" style={{userSelect: 'none', msUserSelect: 'none'}}>
|
||||
{props?.collapsed
|
||||
? undefined
|
||||
: <div>© 2023-{currentYear} 汇聚平台</div>}
|
||||
</div>
|
||||
)
|
||||
}}
|
||||
>
|
||||
<ConfigProvider
|
||||
theme={{
|
||||
components: {
|
||||
Card: {
|
||||
bodyPadding: 0,
|
||||
bodyPaddingSM: 0,
|
||||
},
|
||||
},
|
||||
}}
|
||||
>
|
||||
<Outlet/>
|
||||
</ConfigProvider>
|
||||
</ProLayout>
|
||||
</ProLayoutDiv>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
113
service-web/client/src/pages/ai/flow/FlowChecker.test.tsx
Normal file
113
service-web/client/src/pages/ai/flow/FlowChecker.test.tsx
Normal 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())
|
||||
})
|
||||
274
service-web/client/src/pages/ai/flow/FlowChecker.tsx
Normal file
274
service-web/client/src/pages/ai/flow/FlowChecker.tsx
Normal 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()
|
||||
}
|
||||
}
|
||||
299
service-web/client/src/pages/ai/flow/FlowEditor.tsx
Normal file
299
service-web/client/src/pages/ai/flow/FlowEditor.tsx
Normal file
@@ -0,0 +1,299 @@
|
||||
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 {
|
||||
}
|
||||
}
|
||||
`
|
||||
|
||||
export type FlowEditorProps = {
|
||||
}
|
||||
|
||||
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
|
||||
76
service-web/client/src/pages/ai/flow/FlowElBuilder.tsx
Normal file
76
service-web/client/src/pages/ai/flow/FlowElBuilder.tsx
Normal 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(',')})`
|
||||
}
|
||||
199
service-web/client/src/pages/ai/flow/node/AmisNode.tsx
Normal file
199
service-web/client/src/pages/ai/flow/node/AmisNode.tsx
Normal 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
|
||||
52
service-web/client/src/pages/ai/flow/node/CodeNode.tsx
Normal file
52
service-web/client/src/pages/ai/flow/node/CodeNode.tsx
Normal 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)
|
||||
13
service-web/client/src/pages/ai/flow/node/EndNode.tsx
Normal file
13
service-web/client/src/pages/ai/flow/node/EndNode.tsx
Normal 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)
|
||||
66
service-web/client/src/pages/ai/flow/node/KnowledgeNode.tsx
Normal file
66
service-web/client/src/pages/ai/flow/node/KnowledgeNode.tsx
Normal 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)
|
||||
51
service-web/client/src/pages/ai/flow/node/LlmNode.tsx
Normal file
51
service-web/client/src/pages/ai/flow/node/LlmNode.tsx
Normal 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)
|
||||
68
service-web/client/src/pages/ai/flow/node/StartNode.tsx
Normal file
68
service-web/client/src/pages/ai/flow/node/StartNode.tsx
Normal 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)
|
||||
55
service-web/client/src/pages/ai/flow/node/SwitchNode.tsx
Normal file
55
service-web/client/src/pages/ai/flow/node/SwitchNode.tsx
Normal file
@@ -0,0 +1,55 @@
|
||||
import {Handle, type NodeProps, Position} from '@xyflow/react'
|
||||
import {Tag} from 'antd'
|
||||
import React from 'react'
|
||||
import AmisNode from './AmisNode.tsx'
|
||||
|
||||
const cases = [
|
||||
{
|
||||
index: 1,
|
||||
},
|
||||
{
|
||||
index: 2,
|
||||
},
|
||||
{
|
||||
index: 3,
|
||||
},
|
||||
]
|
||||
|
||||
const SwitchNode = (props: NodeProps) => AmisNode({
|
||||
nodeProps: props,
|
||||
type: 'normal',
|
||||
defaultNodeName: '分支节点',
|
||||
defaultNodeDescription: '根据不同的情况前往不同的分支',
|
||||
columnSchema: [],
|
||||
// @ts-ignore
|
||||
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>
|
||||
)
|
||||
},
|
||||
// @ts-ignore
|
||||
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)
|
||||
23
service-web/client/src/pages/ai/flow/store/DataStore.ts
Normal file
23
service-web/client/src/pages/ai/flow/store/DataStore.ts
Normal 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,
|
||||
})
|
||||
},
|
||||
}))
|
||||
56
service-web/client/src/pages/ai/flow/store/FlowStore.ts
Normal file
56
service-web/client/src/pages/ai/flow/store/FlowStore.ts
Normal 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),
|
||||
})
|
||||
},
|
||||
}))
|
||||
95
service-web/client/src/pages/ai/task/FlowTask.tsx
Normal file
95
service-web/client/src/pages/ai/task/FlowTask.tsx
Normal 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
|
||||
36
service-web/client/src/pages/ai/task/FlowTaskAdd.tsx
Normal file
36
service-web/client/src/pages/ai/task/FlowTaskAdd.tsx
Normal 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
|
||||
48
service-web/client/src/pages/ai/task/InputSchema.tsx
Normal file
48
service-web/client/src/pages/ai/task/InputSchema.tsx
Normal file
@@ -0,0 +1,48 @@
|
||||
import type {Schema} from 'amis'
|
||||
|
||||
export const typeMap: Record<string, string> = {
|
||||
text: '文本',
|
||||
number: '数字',
|
||||
files: '文件',
|
||||
}
|
||||
|
||||
export type InputField = {
|
||||
type: string
|
||||
label: string
|
||||
description?: string
|
||||
}
|
||||
|
||||
export const generateInputForm: (inputSchema: Record<string, InputField>) => Schema = inputSchema => {
|
||||
let items: Schema[] = []
|
||||
for (const name of Object.keys(inputSchema)) {
|
||||
let field = inputSchema[name]
|
||||
// @ts-ignore
|
||||
let formItem: Schema = {
|
||||
name: name,
|
||||
...field,
|
||||
}
|
||||
switch (field.type) {
|
||||
case 'text':
|
||||
formItem = {
|
||||
...formItem,
|
||||
type: 'input-text',
|
||||
clearValueOnEmpty: true,
|
||||
}
|
||||
break
|
||||
case 'number':
|
||||
formItem.type = 'input-number'
|
||||
break
|
||||
case 'files':
|
||||
formItem.type = 'input-file'
|
||||
break
|
||||
}
|
||||
items.push(formItem)
|
||||
}
|
||||
return {
|
||||
type: 'form',
|
||||
title: '入参表单预览',
|
||||
canAccessSuperData: false,
|
||||
actions: [],
|
||||
body: items,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
import React from 'react'
|
||||
import {useNavigate} from 'react-router'
|
||||
import {amisRender, commonInfo, crudCommonOptions, paginationTemplate} from '../../../../util/amis.tsx'
|
||||
|
||||
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',
|
||||
tooltip: '新增',
|
||||
tooltipPlacement: 'top',
|
||||
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: '编辑流程',
|
||||
level: 'link',
|
||||
size: 'sm',
|
||||
onEvent: {
|
||||
click: {
|
||||
actions: [
|
||||
{
|
||||
actionType: 'custom',
|
||||
// @ts-ignore
|
||||
script: (context, doAction, 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
|
||||
@@ -0,0 +1,175 @@
|
||||
import {isEmpty, isEqual} from 'licia'
|
||||
import React from 'react'
|
||||
import styled from 'styled-components'
|
||||
import {amisRender, commonInfo, horizontalFormOptions} from '../../../../util/amis.tsx'
|
||||
import {generateInputForm, typeMap} from '../InputSchema.tsx'
|
||||
import { useParams } from 'react-router'
|
||||
|
||||
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
|
||||
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: {
|
||||
id: '${id|default:undefined}',
|
||||
name: '${name}',
|
||||
description: '${description}',
|
||||
inputSchema: '${inputSchema|default:undefined}',
|
||||
},
|
||||
},
|
||||
initApi: preloadTemplateId
|
||||
? {
|
||||
method: 'GET',
|
||||
url: `${commonInfo.baseAiUrl}/flow_task/template/detail/${preloadTemplateId}`,
|
||||
}
|
||||
: undefined,
|
||||
wrapWithPanel: false,
|
||||
...horizontalFormOptions(),
|
||||
onEvent: {
|
||||
change: {
|
||||
actions: [
|
||||
{
|
||||
actionType: 'validate',
|
||||
},
|
||||
{
|
||||
actionType: 'custom',
|
||||
// @ts-ignore
|
||||
script: (context, doAction, event) => {
|
||||
let data = event?.data ?? {}
|
||||
let inputSchema = data.inputSchema ?? []
|
||||
if (!isEmpty(inputSchema) && isEmpty(data?.validateResult?.error ?? undefined)) {
|
||||
doAction({
|
||||
actionType: 'setValue',
|
||||
args: {
|
||||
value: {
|
||||
inputPreview: generateInputForm(inputSchema),
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
body: [
|
||||
{
|
||||
type: 'hidden',
|
||||
name: 'id',
|
||||
},
|
||||
{
|
||||
type: 'input-text',
|
||||
name: 'name',
|
||||
label: '名称',
|
||||
required: true,
|
||||
clearable: true,
|
||||
},
|
||||
{
|
||||
type: 'textarea',
|
||||
name: 'description',
|
||||
label: '描述',
|
||||
required: true,
|
||||
clearable: true,
|
||||
},
|
||||
{
|
||||
type: 'group',
|
||||
body: [
|
||||
{
|
||||
type: 'wrapper',
|
||||
size: 'none',
|
||||
body: [
|
||||
{
|
||||
type: 'input-kvs',
|
||||
name: 'inputSchema',
|
||||
label: '输入变量',
|
||||
addButtonText: '新增入参',
|
||||
draggable: false,
|
||||
keyItem: {
|
||||
label: '参数名称',
|
||||
...horizontalFormOptions(),
|
||||
validations: {
|
||||
isAlphanumeric: true,
|
||||
},
|
||||
},
|
||||
valueItems: [
|
||||
{
|
||||
...horizontalFormOptions(),
|
||||
type: 'input-text',
|
||||
name: 'label',
|
||||
required: true,
|
||||
label: '中文名称',
|
||||
clearValueOnEmpty: true,
|
||||
clearable: true,
|
||||
},
|
||||
{
|
||||
...horizontalFormOptions(),
|
||||
type: 'input-text',
|
||||
name: 'description',
|
||||
label: '参数描述',
|
||||
clearValueOnEmpty: true,
|
||||
clearable: true,
|
||||
},
|
||||
{
|
||||
...horizontalFormOptions(),
|
||||
type: 'select',
|
||||
name: 'type',
|
||||
label: '参数类型',
|
||||
required: true,
|
||||
selectFirst: true,
|
||||
options: Object.keys(typeMap).map(key => ({label: typeMap[key], value: key})),
|
||||
},
|
||||
{
|
||||
...horizontalFormOptions(),
|
||||
type: 'switch',
|
||||
name: 'required',
|
||||
label: '是否必填',
|
||||
required: true,
|
||||
value: true,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
type: 'amis',
|
||||
name: 'inputPreview',
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
type: 'button-toolbar',
|
||||
buttons: [
|
||||
{
|
||||
type: 'submit',
|
||||
label: '提交',
|
||||
level: 'primary',
|
||||
},
|
||||
{
|
||||
type: 'reset',
|
||||
label: '重置',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
})}
|
||||
</TemplateEditDiv>
|
||||
)
|
||||
}
|
||||
|
||||
export default FlowTaskTemplateEdit
|
||||
@@ -31,7 +31,7 @@ const queueCrud = (name: string) => {
|
||||
{
|
||||
name: 'data.flinkJobId',
|
||||
label: '任务 ID',
|
||||
width: 190,
|
||||
width: 200,
|
||||
...copyField('data.flinkJobId'),
|
||||
},
|
||||
{
|
||||
|
||||
@@ -4,6 +4,8 @@ import {
|
||||
ClusterOutlined,
|
||||
CompressOutlined,
|
||||
DatabaseOutlined,
|
||||
FileTextOutlined,
|
||||
GatewayOutlined,
|
||||
InfoCircleOutlined,
|
||||
OpenAIOutlined,
|
||||
QuestionOutlined,
|
||||
@@ -16,10 +18,15 @@ import {values} from 'licia'
|
||||
import {Navigate, type RouteObject} from 'react-router'
|
||||
import Conversation from './pages/ai/Conversation.tsx'
|
||||
import Feedback from './pages/ai/feedback/Feedback.tsx'
|
||||
import FlowEditor from './pages/ai/flow/FlowEditor.tsx'
|
||||
import DataDetail from './pages/ai/knowledge/DataDetail.tsx'
|
||||
import DataImport from './pages/ai/knowledge/DataImport.tsx'
|
||||
import DataSegment from './pages/ai/knowledge/DataSegment.tsx'
|
||||
import Knowledge from './pages/ai/knowledge/Knowledge.tsx'
|
||||
import FlowTask from './pages/ai/task/FlowTask.tsx'
|
||||
import FlowTaskAdd from './pages/ai/task/FlowTaskAdd.tsx'
|
||||
import FlowTaskTemplate from './pages/ai/task/template/FlowTaskTemplate.tsx'
|
||||
import FlowTaskTemplateEdit from './pages/ai/task/template/FlowTaskTemplateEdit.tsx'
|
||||
import App from './pages/App.tsx'
|
||||
import Cloud from './pages/overview/Cloud.tsx'
|
||||
import Overview from './pages/overview/Overview.tsx'
|
||||
@@ -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: <GatewayOutlined/>,
|
||||
routes: [
|
||||
{
|
||||
path: '/ai/flow_task',
|
||||
name: '任务列表',
|
||||
icon: <FileTextOutlined/>,
|
||||
},
|
||||
{
|
||||
path: '/ai/flow_task_template',
|
||||
name: '流程模板',
|
||||
icon: <FileTextOutlined/>,
|
||||
},
|
||||
]
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
|
||||
@@ -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,
|
||||
|
||||
2
service-web/client/src/vite-env.d.ts
vendored
2
service-web/client/src/vite-env.d.ts
vendored
@@ -1 +1,3 @@
|
||||
/// <reference types="vite/client" />
|
||||
|
||||
declare const __APP_VERSION__: string
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
import react from '@vitejs/plugin-react-swc'
|
||||
import {defineConfig, type UserConfig} from 'vite'
|
||||
import obfuscatorPlugin from 'vite-plugin-javascript-obfuscator'
|
||||
import packageJson from './package.json'
|
||||
|
||||
// https://vite.dev/config/
|
||||
export default defineConfig(({mode}) => {
|
||||
let config: UserConfig = {
|
||||
define: {
|
||||
__APP_VERSION__: JSON.stringify(packageJson.version) ?? '0.0.0',
|
||||
},
|
||||
plugins: [
|
||||
react(),
|
||||
obfuscatorPlugin({
|
||||
|
||||
Reference in New Issue
Block a user